FreeCAD
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
27For example, add objects to groups, select objects inside groups,
28set the automatic group in which to create objects, and add objects
29to 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# @{
37import PySide.QtCore as QtCore38from PySide.QtCore import QT_TRANSLATE_NOOP39from PySide import QtWidgets40
41import FreeCAD as App42import FreeCADGui as Gui43import Draft_rc44from draftguitools import gui_base45from draftutils import groups46from draftutils import params47from draftutils import utils48from draftutils.translate import translate49
50
51# The module is used to prevent complaints from code checkers (flake8)
52True if Draft_rc.__name__ else False53
54
55class AddToGroup(gui_base.GuiCommandNeedsSelection):56"""GuiCommand for the Draft_AddToGroup tool.57
58It adds selected objects to a group, or removes them from any group.
59
60It inherits `GuiCommandNeedsSelection` to only be available
61when there is a document and a selection.
62See this class for more information.
63"""
64
65def __init__(self):66super(AddToGroup, self).__init__(name=translate("draft", "Add to group"))67self.ungroup = translate("draft", "Ungroup")68#add new group string option69self.addNewGroupStr = "+ " + translate("draft", "Add new group")70
71def GetResources(self):72"""Set icon, menu and tooltip."""73return {'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
77def Activated(self):78"""Execute when the command is called."""79super(AddToGroup, self).Activated()80
81self.groups = [self.ungroup]82self.groups.extend(groups.get_group_names())83
84self.labels = [self.ungroup]85for group in self.groups:86obj = self.doc.getObject(group)87if obj:88self.labels.append(obj.Label)89#add new group option90self.labels.append(self.addNewGroupStr)91
92# It uses the `DraftToolBar` class defined in the `DraftGui` module93# and globally initialized in the `Gui` namespace,94# in order to pop up a menu with group labels95# or the default `Ungroup` text.96# Once the desired option is chosen97# it launches the `proceed` method.98self.ui = Gui.draftToolBar99self.ui.sourceCmd = self100self.ui.popupMenu(self.labels)101
102
103def proceed(self, labelname):104"""Place the selected objects in the chosen group or ungroup them.105Parameters
106----------
107labelname: str
108The passed string with the name of the group.
109It puts the selected objects inside this group.
110"""
111# If the selected group matches the ungroup label,112# remove the selection from all groups.113if labelname == self.ungroup:114for obj in Gui.Selection.getSelection():115try:116groups.ungroup(obj)117except Exception:118pass119else:120# Deactivate the source command of the `DraftToolBar` class121# so that it doesn't do more with this command.122self.ui.sourceCmd = None123
124#if new group is selected then launch AddNamedGroup125if labelname == self.addNewGroupStr:126add=AddNamedGroup()127add.Activated()128else:129#else add selection to the selected group130if labelname in self.labels :131i = self.labels.index(labelname)132g = self.doc.getObject(self.groups[i])133moveToGroup(g)134
135
136Gui.addCommand('Draft_AddToGroup', AddToGroup())137
138
139def moveToGroup(group):140"""141Place the selected objects in the chosen group.
142"""
143
144for obj in Gui.Selection.getSelection():145try:146#retrieve group's visibility147obj.ViewObject.Visibility = group.ViewObject.Visibility148group.addObject(obj)149
150except Exception:151pass152
153App.activeDocument().recompute(None, True, True)154
155
156class SelectGroup(gui_base.GuiCommandNeedsSelection):157"""GuiCommand for the Draft_SelectGroup tool."""158
159def __init__(self):160super(SelectGroup, self).__init__(name=translate("draft","Select group"))161
162def GetResources(self):163"""Set icon, menu and tooltip."""164return {'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
168def Activated(self):169"""Execute when the command is called."""170super(SelectGroup, self).Activated()171
172sel = Gui.Selection.getSelection()173subs = []174for obj in sel:175if groups.is_group(obj):176for sub in obj.Group:177subs.append(sub)178else:179for parent in obj.InList:180if groups.is_group(parent):181for sub in parent.Group:182subs.append(sub)183
184# Always clear the selection:185Gui.Selection.clearSelection()186
187# Create a new selection from the sub objects:188for sub in subs:189Gui.Selection.addSelection(sub)190
191# Inform the user if there is no new selection:192if not Gui.Selection.hasSelection():193msg = translate("draft", "No new selection. You must select non-empty groups or objects inside groups.")194App.Console.PrintMessage(msg + "\n")195
196
197Gui.addCommand('Draft_SelectGroup', SelectGroup())198
199
200class SetAutoGroup(gui_base.GuiCommandSimplest):201"""GuiCommand for the Draft_AutoGroup tool."""202
203def __init__(self):204super(SetAutoGroup, self).__init__(name=translate("draft","Autogroup"))205
206def GetResources(self):207"""Set icon, menu and tooltip."""208return {'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
212def Activated(self):213"""Execute when the command is called.214
215It calls the `setAutogroup` method of the `DraftToolBar` class
216installed inside the global `Gui` namespace.
217"""
218super(SetAutoGroup, self).Activated()219
220if not hasattr(Gui, "draftToolBar"):221return222
223# It uses the `DraftToolBar` class defined in the `DraftGui` module224# and globally initialized in the `Gui` namespace to run225# some actions.226# If there is only a group selected, it runs the `AutoGroup` method.227self.ui = Gui.draftToolBar228s = Gui.Selection.getSelection()229if len(s) == 1:230if (utils.get_type(s[0]) == "Layer"231or (params.get_param("AutogroupAddGroups")232and groups.is_group(s[0]))):233self.ui.setAutoGroup(s[0].Name)234return235
236# Otherwise it builds a list of layers, with names and icons,237# including the options "None" and "Add new layer".238self.groups = [translate("draft", "None")]239gn = [o.Name for o in self.doc.Objects if utils.get_type(o) == "Layer"]240if params.get_param("AutogroupAddGroups"):241gn.extend(groups.get_group_names())242self.groups.extend(gn)243self.labels = [translate("draft", "None")]244self.icons = [self.ui.getIcon(":/icons/button_invalid.svg")]245for g in gn:246o = self.doc.getObject(g)247if o:248self.labels.append(o.Label)249self.icons.append(o.ViewObject.Icon)250self.labels.append(translate("draft", "Add new Layer"))251self.icons.append(self.ui.getIcon(":/icons/document-new.svg"))252
253# With the lists created is uses the interface254# to pop up a menu with layer options.255# Once the desired option is chosen256# it launches the `proceed` method.257self.ui.sourceCmd = self258pos = self.ui.autoGroupButton.mapToGlobal(QtCore.QPoint(0, self.ui.autoGroupButton.geometry().height()))259self.ui.popupMenu(self.labels, self.icons, pos)260
261def proceed(self, labelname):262"""Set the defined autogroup, or create a new layer.263
264Parameters
265----------
266labelname: str
267The passed string with the name of the group or layer.
268"""
269# Deactivate the source command of the `DraftToolBar` class270# so that it doesn't do more with this command271# when it finishes.272self.ui.sourceCmd = None273
274if labelname in self.labels:275if labelname == self.labels[0]:276# First option "None" deactivates autogrouping277self.ui.setAutoGroup(None)278elif labelname == self.labels[-1]:279# Last option "Add new layer" creates new layer280Gui.runCommand("Draft_Layer")281else:282# Set autogroup to the chosen layer283i = self.labels.index(labelname)284self.ui.setAutoGroup(self.groups[i])285
286
287Gui.addCommand('Draft_AutoGroup', SetAutoGroup())288
289
290class AddToConstruction(gui_base.GuiCommandNeedsSelection):291"""Gui Command for the AddToConstruction tool.292
293It adds the selected objects to the construction group
294defined in the `DraftToolBar` class which is initialized
295in the `Gui` namespace when the workbench loads.
296
297It adds a construction group if it doesn't exist.
298
299Added objects are also given the visual properties of the construction
300group.
301"""
302
303def __init__(self):304super(AddToConstruction, self).__init__(name=translate("draft","Add to construction group"))305
306def GetResources(self):307"""Set icon, menu and tooltip."""308return {'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
312def Activated(self):313"""Execute when the command is called."""314super(AddToConstruction, self).Activated()315
316if not hasattr(Gui, "draftToolBar"):317return318
319col = params.get_param("constructioncolor") & 0xFFFFFF00320
321# Get the construction group or create it if it doesn't exist322grp = self.doc.getObject("Draft_Construction")323if not grp:324grp = self.doc.addObject("App::DocumentObjectGroup", "Draft_Construction")325grp.Label = params.get_param("constructiongroupname")326
327for obj in Gui.Selection.getSelection():328grp.addObject(obj)329
330# Change the appearance to the construction colors331vobj = obj.ViewObject332if "TextColor" in vobj.PropertiesList:333vobj.TextColor = col334if "PointColor" in vobj.PropertiesList:335vobj.PointColor = col336if "LineColor" in vobj.PropertiesList:337vobj.LineColor = col338if "ShapeColor" in vobj.PropertiesList:339vobj.ShapeColor = col340if hasattr(vobj, "Transparency"):341vobj.Transparency = 80342
343
344Draft_AddConstruction = AddToConstruction345Gui.addCommand('Draft_AddConstruction', AddToConstruction())346
347
348class AddNamedGroup(gui_base.GuiCommandSimplest):349
350"""Gui Command for the addGroup tool.351It adds a new named group
352"""
353def __init__(self):354super().__init__(name=translate("draft", "Add a new group with a given name"))355
356
357def GetResources(self):358"""Set icon, menu and tooltip."""359return {'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
364def Activated(self):365super().Activated()366panel = Ui_AddNamedGroup()367Gui.Control.showDialog(panel)368panel.name.setFocus()369
370
371Draft_AddNamedGroup = AddNamedGroup372Gui.addCommand('Draft_AddNamedGroup', AddNamedGroup())373
374
375class Ui_AddNamedGroup():376"""377User interface for addgroup tool
378simple label and line edit in dialogbox
379"""
380def __init__(self):381self.form = QtWidgets.QWidget()382self.form.setWindowTitle(translate("draft", "Add group"))383row = QtWidgets.QHBoxLayout(self.form)384lbl = QtWidgets.QLabel(translate("draft", "Group name") + ":")385self.name = QtWidgets.QLineEdit()386row.addWidget(lbl)387row.addWidget(self.name)388
389
390def accept(self):391group = App.activeDocument().addObject("App::DocumentObjectGroup",translate("draft", "Group"))392group.Label=self.name.text()393moveToGroup(group)394Gui.Control.closeDialog()395
396
397## @}
398