FreeCAD

Форк
0
397 строк · 15.0 Кб
1
# ***************************************************************************
2
# *   (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net>                  *
3
# *   (c) 2009, 2010 Ken Cline <cline@frii.com>                             *
4
# *   (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de>           *
5
# *                                                                         *
6
# *   This file is part of the FreeCAD CAx development system.              *
7
# *                                                                         *
8
# *   This program is free software; you can redistribute it and/or modify  *
9
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
10
# *   as published by the Free Software Foundation; either version 2 of     *
11
# *   the License, or (at your option) any later version.                   *
12
# *   for detail see the LICENCE text file.                                 *
13
# *                                                                         *
14
# *   FreeCAD is distributed in the hope that it will be useful,            *
15
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
16
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
17
# *   GNU Library General Public License for more details.                  *
18
# *                                                                         *
19
# *   You should have received a copy of the GNU Library General Public     *
20
# *   License along with FreeCAD; if not, write to the Free Software        *
21
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
22
# *   USA                                                                   *
23
# *                                                                         *
24
# ***************************************************************************
25
"""Provides GUI tools to do various operations with groups.
26

27
For example, add objects to groups, select objects inside groups,
28
set the automatic group in which to create objects, and add objects
29
to the construction group.
30
"""
31
## @package gui_groups
32
# \ingroup draftguitools
33
# \brief Provides GUI tools to do various operations with groups.
34

35
## \addtogroup draftguitools
36
# @{
37
import PySide.QtCore as QtCore
38
from PySide.QtCore import QT_TRANSLATE_NOOP
39
from PySide import QtWidgets
40

41
import FreeCAD as App
42
import FreeCADGui as Gui
43
import Draft_rc
44
from draftguitools import gui_base
45
from draftutils import groups
46
from draftutils import params
47
from draftutils import utils
48
from draftutils.translate import translate
49

50

51
# The module is used to prevent complaints from code checkers (flake8)
52
True if Draft_rc.__name__ else False
53

54

55
class AddToGroup(gui_base.GuiCommandNeedsSelection):
56
    """GuiCommand for the Draft_AddToGroup tool.
57

58
    It adds selected objects to a group, or removes them from any group.
59

60
    It inherits `GuiCommandNeedsSelection` to only be available
61
    when there is a document and a selection.
62
    See this class for more information.
63
    """
64

65
    def __init__(self):
66
        super(AddToGroup, self).__init__(name=translate("draft", "Add to group"))
67
        self.ungroup = translate("draft", "Ungroup")
68
        #add new group string option
69
        self.addNewGroupStr = "+ " + translate("draft", "Add new group")
70

71
    def GetResources(self):
72
        """Set icon, menu and tooltip."""
73
        return {'Pixmap': 'Draft_AddToGroup',
74
                'MenuText': QT_TRANSLATE_NOOP("Draft_AddToGroup", "Move to group..."),
75
                'ToolTip': QT_TRANSLATE_NOOP("Draft_AddToGroup", "Moves the selected objects to an existing group, or removes them from any group.\nCreate a group first to use this tool.")}
76

77
    def Activated(self):
78
        """Execute when the command is called."""
79
        super(AddToGroup, self).Activated()
80

81
        self.groups = [self.ungroup]
82
        self.groups.extend(groups.get_group_names())
83

84
        self.labels = [self.ungroup]
85
        for group in self.groups:
86
            obj = self.doc.getObject(group)
87
            if obj:
88
                self.labels.append(obj.Label)
89
        #add new group option
90
        self.labels.append(self.addNewGroupStr)
91

92
        # It uses the `DraftToolBar` class defined in the `DraftGui` module
93
        # and globally initialized in the `Gui` namespace,
94
        # in order to pop up a menu with group labels
95
        # or the default `Ungroup` text.
96
        # Once the desired option is chosen
97
        # it launches the `proceed` method.
98
        self.ui = Gui.draftToolBar
99
        self.ui.sourceCmd = self
100
        self.ui.popupMenu(self.labels)
101

102

103
    def proceed(self, labelname):
104
        """Place the selected objects in the chosen group or ungroup them.
105
        Parameters
106
        ----------
107
        labelname: str
108
            The passed string with the name of the group.
109
            It puts the selected objects inside this group.
110
        """
111
        # If the selected group matches the ungroup label,
112
        # remove the selection from all groups.
113
        if labelname == self.ungroup:
114
            for obj in Gui.Selection.getSelection():
115
                try:
116
                    groups.ungroup(obj)
117
                except Exception:
118
                    pass
119
        else:
120
            # Deactivate the source command of the `DraftToolBar` class
121
            # so that it doesn't do more with this command.
122
            self.ui.sourceCmd = None
123

124
            #if new group is selected then launch AddNamedGroup
125
            if labelname == self.addNewGroupStr:
126
                add=AddNamedGroup()
127
                add.Activated()
128
            else:
129
            #else add selection to the selected group
130
                if labelname in self.labels :
131
                    i = self.labels.index(labelname)
132
                    g = self.doc.getObject(self.groups[i])
133
                    moveToGroup(g)
134

135

136
Gui.addCommand('Draft_AddToGroup', AddToGroup())
137

138

139
def moveToGroup(group):
140
    """
141
    Place the selected objects in the chosen group.
142
    """
143

144
    for obj in Gui.Selection.getSelection():
145
        try:
146
            #retrieve group's visibility
147
            obj.ViewObject.Visibility = group.ViewObject.Visibility
148
            group.addObject(obj)
149

150
        except Exception:
151
            pass
152

153
    App.activeDocument().recompute(None, True, True)
154

155

156
class SelectGroup(gui_base.GuiCommandNeedsSelection):
157
    """GuiCommand for the Draft_SelectGroup tool."""
158

159
    def __init__(self):
160
        super(SelectGroup, self).__init__(name=translate("draft","Select group"))
161

162
    def GetResources(self):
163
        """Set icon, menu and tooltip."""
164
        return {'Pixmap': 'Draft_SelectGroup',
165
                'MenuText': QT_TRANSLATE_NOOP("Draft_SelectGroup", "Select group"),
166
                'ToolTip': QT_TRANSLATE_NOOP("Draft_SelectGroup", "Selects the contents of selected groups. For selected non-group objects, the contents of the group they are in is selected.")}
167

168
    def Activated(self):
169
        """Execute when the command is called."""
170
        super(SelectGroup, self).Activated()
171

172
        sel = Gui.Selection.getSelection()
173
        subs = []
174
        for obj in sel:
175
            if groups.is_group(obj):
176
                for sub in obj.Group:
177
                    subs.append(sub)
178
            else:
179
                for parent in obj.InList:
180
                    if groups.is_group(parent):
181
                        for sub in parent.Group:
182
                            subs.append(sub)
183

184
        # Always clear the selection:
185
        Gui.Selection.clearSelection()
186

187
        # Create a new selection from the sub objects:
188
        for sub in subs:
189
            Gui.Selection.addSelection(sub)
190

191
        # Inform the user if there is no new selection:
192
        if not Gui.Selection.hasSelection():
193
            msg = translate("draft", "No new selection. You must select non-empty groups or objects inside groups.")
194
            App.Console.PrintMessage(msg + "\n")
195

196

197
Gui.addCommand('Draft_SelectGroup', SelectGroup())
198

199

200
class SetAutoGroup(gui_base.GuiCommandSimplest):
201
    """GuiCommand for the Draft_AutoGroup tool."""
202

203
    def __init__(self):
204
        super(SetAutoGroup, self).__init__(name=translate("draft","Autogroup"))
205

206
    def GetResources(self):
207
        """Set icon, menu and tooltip."""
208
        return {'Pixmap': 'Draft_AutoGroup',
209
                'MenuText': QT_TRANSLATE_NOOP("Draft_AutoGroup", "Autogroup"),
210
                'ToolTip': QT_TRANSLATE_NOOP("Draft_AutoGroup", "Select a group to add all Draft and Arch objects to.")}
211

212
    def Activated(self):
213
        """Execute when the command is called.
214

215
        It calls the `setAutogroup` method of the `DraftToolBar` class
216
        installed inside the global `Gui` namespace.
217
        """
218
        super(SetAutoGroup, self).Activated()
219

220
        if not hasattr(Gui, "draftToolBar"):
221
            return
222

223
        # It uses the `DraftToolBar` class defined in the `DraftGui` module
224
        # and globally initialized in the `Gui` namespace to run
225
        # some actions.
226
        # If there is only a group selected, it runs the `AutoGroup` method.
227
        self.ui = Gui.draftToolBar
228
        s = Gui.Selection.getSelection()
229
        if len(s) == 1:
230
            if (utils.get_type(s[0]) == "Layer"
231
                or (params.get_param("AutogroupAddGroups")
232
                    and groups.is_group(s[0]))):
233
                self.ui.setAutoGroup(s[0].Name)
234
                return
235

236
        # Otherwise it builds a list of layers, with names and icons,
237
        # including the options "None" and "Add new layer".
238
        self.groups = [translate("draft", "None")]
239
        gn = [o.Name for o in self.doc.Objects if utils.get_type(o) == "Layer"]
240
        if params.get_param("AutogroupAddGroups"):
241
            gn.extend(groups.get_group_names())
242
        self.groups.extend(gn)
243
        self.labels = [translate("draft", "None")]
244
        self.icons = [self.ui.getIcon(":/icons/button_invalid.svg")]
245
        for g in gn:
246
            o = self.doc.getObject(g)
247
            if o:
248
                self.labels.append(o.Label)
249
                self.icons.append(o.ViewObject.Icon)
250
        self.labels.append(translate("draft", "Add new Layer"))
251
        self.icons.append(self.ui.getIcon(":/icons/document-new.svg"))
252

253
        # With the lists created is uses the interface
254
        # to pop up a menu with layer options.
255
        # Once the desired option is chosen
256
        # it launches the `proceed` method.
257
        self.ui.sourceCmd = self
258
        pos = self.ui.autoGroupButton.mapToGlobal(QtCore.QPoint(0, self.ui.autoGroupButton.geometry().height()))
259
        self.ui.popupMenu(self.labels, self.icons, pos)
260

261
    def proceed(self, labelname):
262
        """Set the defined autogroup, or create a new layer.
263

264
        Parameters
265
        ----------
266
        labelname: str
267
            The passed string with the name of the group or layer.
268
        """
269
        # Deactivate the source command of the `DraftToolBar` class
270
        # so that it doesn't do more with this command
271
        # when it finishes.
272
        self.ui.sourceCmd = None
273

274
        if labelname in self.labels:
275
            if labelname == self.labels[0]:
276
                # First option "None" deactivates autogrouping
277
                self.ui.setAutoGroup(None)
278
            elif labelname == self.labels[-1]:
279
                # Last option "Add new layer" creates new layer
280
                Gui.runCommand("Draft_Layer")
281
            else:
282
                # Set autogroup to the chosen layer
283
                i = self.labels.index(labelname)
284
                self.ui.setAutoGroup(self.groups[i])
285

286

287
Gui.addCommand('Draft_AutoGroup', SetAutoGroup())
288

289

290
class AddToConstruction(gui_base.GuiCommandNeedsSelection):
291
    """Gui Command for the AddToConstruction tool.
292

293
    It adds the selected objects to the construction group
294
    defined in the `DraftToolBar` class which is initialized
295
    in the `Gui` namespace when the workbench loads.
296

297
    It adds a construction group if it doesn't exist.
298

299
    Added objects are also given the visual properties of the construction
300
    group.
301
    """
302

303
    def __init__(self):
304
        super(AddToConstruction, self).__init__(name=translate("draft","Add to construction group"))
305

306
    def GetResources(self):
307
        """Set icon, menu and tooltip."""
308
        return {'Pixmap': 'Draft_AddConstruction',
309
                'MenuText': QT_TRANSLATE_NOOP("Draft_AddConstruction", "Add to construction group"),
310
                'ToolTip': QT_TRANSLATE_NOOP("Draft_AddConstruction", "Adds the selected objects to the construction group,\nand changes their appearance to the construction style.\nIt creates a construction group if it doesn't exist.")}
311

312
    def Activated(self):
313
        """Execute when the command is called."""
314
        super(AddToConstruction, self).Activated()
315

316
        if not hasattr(Gui, "draftToolBar"):
317
            return
318

319
        col = params.get_param("constructioncolor") & 0xFFFFFF00
320

321
        # Get the construction group or create it if it doesn't exist
322
        grp = self.doc.getObject("Draft_Construction")
323
        if not grp:
324
            grp = self.doc.addObject("App::DocumentObjectGroup", "Draft_Construction")
325
            grp.Label = params.get_param("constructiongroupname")
326

327
        for obj in Gui.Selection.getSelection():
328
            grp.addObject(obj)
329

330
            # Change the appearance to the construction colors
331
            vobj = obj.ViewObject
332
            if "TextColor" in vobj.PropertiesList:
333
                vobj.TextColor = col
334
            if "PointColor" in vobj.PropertiesList:
335
                vobj.PointColor = col
336
            if "LineColor" in vobj.PropertiesList:
337
                vobj.LineColor = col
338
            if "ShapeColor" in vobj.PropertiesList:
339
                vobj.ShapeColor = col
340
            if hasattr(vobj, "Transparency"):
341
                vobj.Transparency = 80
342

343

344
Draft_AddConstruction = AddToConstruction
345
Gui.addCommand('Draft_AddConstruction', AddToConstruction())
346

347

348
class AddNamedGroup(gui_base.GuiCommandSimplest):
349

350
    """Gui Command for the addGroup tool.
351
        It adds a new named group
352
    """
353
    def __init__(self):
354
        super().__init__(name=translate("draft", "Add a new group with a given name"))
355

356

357
    def GetResources(self):
358
        """Set icon, menu and tooltip."""
359
        return {'Pixmap': 'Draft_AddNamedGroup',
360
                'MenuText': QT_TRANSLATE_NOOP("Draft_AddNamedGroup", "Add a new named group"),
361
                'ToolTip': QT_TRANSLATE_NOOP("Draft_AddNamedGroup", "Add a new group with a given name.")}
362

363

364
    def Activated(self):
365
        super().Activated()
366
        panel = Ui_AddNamedGroup()
367
        Gui.Control.showDialog(panel)
368
        panel.name.setFocus()
369

370

371
Draft_AddNamedGroup = AddNamedGroup
372
Gui.addCommand('Draft_AddNamedGroup', AddNamedGroup())
373

374

375
class Ui_AddNamedGroup():
376
    """
377
    User interface for addgroup tool
378
    simple label and line edit in dialogbox
379
    """
380
    def __init__(self):
381
        self.form = QtWidgets.QWidget()
382
        self.form.setWindowTitle(translate("draft", "Add group"))
383
        row = QtWidgets.QHBoxLayout(self.form)
384
        lbl = QtWidgets.QLabel(translate("draft", "Group name") + ":")
385
        self.name = QtWidgets.QLineEdit()
386
        row.addWidget(lbl)
387
        row.addWidget(self.name)
388

389

390
    def accept(self):
391
        group = App.activeDocument().addObject("App::DocumentObjectGroup",translate("draft", "Group"))
392
        group.Label=self.name.text()
393
        moveToGroup(group)
394
        Gui.Control.closeDialog()
395

396

397
## @}
398

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.