FreeCAD
323 строки · 12.8 Кб
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 move objects in the 3D space."""
26## @package gui_move
27# \ingroup draftguitools
28# \brief Provides GUI tools to move objects in the 3D space.
29
30## \addtogroup draftguitools
31# @{
32from PySide.QtCore import QT_TRANSLATE_NOOP33
34import FreeCAD as App35import FreeCADGui as Gui36import Draft_rc37import DraftVecUtils38import draftutils.groups as groups39import draftutils.todo as todo40import draftguitools.gui_base_original as gui_base_original41import draftguitools.gui_tool_utils as gui_tool_utils42import draftguitools.gui_trackers as trackers43
44from draftutils.messages import _msg, _err, _toolmsg45from draftutils.translate import translate46from draftguitools.gui_subelements import SubelementHighlight47
48# The module is used to prevent complaints from code checkers (flake8)
49True if Draft_rc.__name__ else False50
51
52class Move(gui_base_original.Modifier):53"""Gui Command for the Move tool."""54
55def GetResources(self):56"""Set icon, menu and tooltip."""57
58return {'Pixmap': 'Draft_Move',59'Accel': "M, V",60'MenuText': QT_TRANSLATE_NOOP("Draft_Move", "Move"),61'ToolTip': QT_TRANSLATE_NOOP("Draft_Move", "Moves the selected objects from one base point to another point.\nIf the \"copy\" option is active, it will create displaced copies.\nCTRL to snap, SHIFT to constrain.")}62
63def Activated(self):64"""Execute when the command is called."""65super().Activated(name="Move",66is_subtool=isinstance(App.activeDraftCommand,67SubelementHighlight))68if not self.ui:69return70self.ghosts = []71self.get_object_selection()72
73def get_object_selection(self):74"""Get the object selection."""75if Gui.Selection.getSelectionEx():76return self.proceed()77self.ui.selectUi(on_close_call=self.finish)78_msg(translate("draft", "Select an object to move"))79self.call = \80self.view.addEventCallback("SoEvent", gui_tool_utils.selectObject)81
82def proceed(self):83"""Continue with the command after a selection has been made."""84if self.call:85self.view.removeEventCallback("SoEvent", self.call)86self.selected_objects = Gui.Selection.getSelection()87self.selected_objects = \88groups.get_group_contents(self.selected_objects,89addgroups=True,90spaces=True,91noarchchild=True)92self.selected_subelements = Gui.Selection.getSelectionEx()93self.ui.lineUi(title=translate("draft", self.featureName), icon="Draft_Move")94self.ui.modUi()95if self.copymode:96self.ui.isCopy.setChecked(True)97self.ui.xValue.setFocus()98self.ui.xValue.selectAll()99self.call = self.view.addEventCallback("SoEvent", self.action)100_toolmsg(translate("draft", "Pick start point"))101
102def finish(self, cont=False):103"""Terminate the operation.104
105Parameters
106----------
107cont: bool or None, optional
108Restart (continue) the command if `True`, or if `None` and
109`ui.continueMode` is `True`.
110"""
111self.end_callbacks(self.call)112for ghost in self.ghosts:113ghost.finalize()114super().finish()115if cont or (cont is None and self.ui and self.ui.continueMode):116todo.ToDo.delayAfter(self.Activated, [])117
118def action(self, arg):119"""Handle the 3D scene events.120
121This is installed as an EventCallback in the Inventor view.
122
123Parameters
124----------
125arg: dict
126Dictionary with strings that indicates the type of event received
127from the 3D view.
128"""
129if arg["Type"] == "SoKeyboardEvent" and arg["Key"] == "ESCAPE":130self.finish()131elif arg["Type"] == "SoLocation2Event":132self.handle_mouse_move_event(arg)133elif (arg["Type"] == "SoMouseButtonEvent"134and arg["State"] == "DOWN"135and arg["Button"] == "BUTTON1"):136self.handle_mouse_click_event(arg)137
138def handle_mouse_move_event(self, arg):139"""Handle the mouse when moving."""140for ghost in self.ghosts:141ghost.off()142self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg)143if len(self.node) > 0:144last = self.node[len(self.node) - 1]145self.vector = self.point.sub(last)146for ghost in self.ghosts:147ghost.move(self.vector)148ghost.on()149if self.extendedCopy:150if not gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key()):151self.finish()152gui_tool_utils.redraw3DView()153
154def handle_mouse_click_event(self, arg):155"""Handle the mouse when the first button is clicked."""156if not self.ghosts:157self.set_ghosts()158if not self.point:159return160self.ui.redraw()161if self.node == []:162self.node.append(self.point)163self.ui.isRelative.show()164for ghost in self.ghosts:165ghost.on()166_toolmsg(translate("draft", "Pick end point"))167if self.planetrack:168self.planetrack.set(self.point)169else:170last = self.node[0]171self.vector = self.point.sub(last)172self.move(self.ui.isCopy.isChecked()173or gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key()))174if gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key()):175self.extendedCopy = True176else:177self.finish(cont=None)178
179def set_ghosts(self):180"""Set the ghost to display."""181for ghost in self.ghosts:182ghost.remove()183if self.ui.isSubelementMode.isChecked():184self.ghosts = self.get_subelement_ghosts()185else:186self.ghosts = [trackers.ghostTracker(self.selected_objects)]187
188def get_subelement_ghosts(self):189"""Get ghost for the subelements (vertices, edges)."""190import Part191
192ghosts = []193for sel in Gui.Selection.getSelectionEx("", 0):194for sub in sel.SubElementNames if sel.SubElementNames else [""]:195if "Vertex" in sub or "Edge" in sub:196shape = Part.getShape(sel.Object, sub, needSubElement=True, retType=0)197ghosts.append(trackers.ghostTracker(shape))198return ghosts199
200def move(self, is_copy=False):201"""Perform the move of the subelements or the entire object."""202if self.ui.isSubelementMode.isChecked():203self.move_subelements(is_copy)204else:205self.move_object(is_copy)206
207def move_subelements(self, is_copy):208"""Move the subelements."""209Gui.addModule("Draft")210try:211if is_copy:212self.commit(translate("draft", "Copy"),213self.build_copy_subelements_command())214else:215self.commit(translate("draft", "Move"),216self.build_move_subelements_command())217except Exception:218_err(translate("draft", "Some subelements could not be moved."))219
220def build_copy_subelements_command(self):221"""Build the string to commit to copy the subelements."""222import Part223
224command = []225arguments = []226E = len("Edge")227for obj in self.selected_subelements:228for index, subelement in enumerate(obj.SubObjects):229if not isinstance(subelement, Part.Edge):230continue231_edge_index = int(obj.SubElementNames[index][E:]) - 1232_cmd = '['233_cmd += 'FreeCAD.ActiveDocument.'234_cmd += obj.ObjectName + ', '235_cmd += str(_edge_index) + ', '236_cmd += DraftVecUtils.toString(self.vector)237_cmd += ']'238arguments.append(_cmd)239
240all_args = ', '.join(arguments)241command.append('Draft.copy_moved_edges([' + all_args + '])')242command.append('FreeCAD.ActiveDocument.recompute()')243return command244
245def build_move_subelements_command(self):246"""Build the string to commit to move the subelements."""247import Part248
249command = []250V = len("Vertex")251E = len("Edge")252for obj in self.selected_subelements:253for index, subelement in enumerate(obj.SubObjects):254if isinstance(subelement, Part.Vertex):255_vertex_index = int(obj.SubElementNames[index][V:]) - 1256_cmd = 'Draft.move_vertex'257_cmd += '('258_cmd += 'FreeCAD.ActiveDocument.'259_cmd += obj.ObjectName + ', '260_cmd += str(_vertex_index) + ', '261_cmd += DraftVecUtils.toString(self.vector)262_cmd += ')'263command.append(_cmd)264elif isinstance(subelement, Part.Edge):265_edge_index = int(obj.SubElementNames[index][E:]) - 1266_cmd = 'Draft.move_edge'267_cmd += '('268_cmd += 'FreeCAD.ActiveDocument.'269_cmd += obj.ObjectName + ', '270_cmd += str(_edge_index) + ', '271_cmd += DraftVecUtils.toString(self.vector)272_cmd += ')'273command.append(_cmd)274command.append('FreeCAD.ActiveDocument.recompute()')275return command276
277def move_object(self, is_copy):278"""Move the object."""279_doc = 'FreeCAD.ActiveDocument.'280_selected = self.selected_objects281
282objects = '['283objects += ', '.join([_doc + obj.Name for obj in _selected])284objects += ']'285Gui.addModule("Draft")286
287_cmd = 'Draft.move'288_cmd += '('289_cmd += objects + ', '290_cmd += DraftVecUtils.toString(self.vector) + ', '291_cmd += 'copy=' + str(is_copy)292_cmd += ')'293_cmd_list = [_cmd,294'FreeCAD.ActiveDocument.recompute()']295
296_mode = "Copy" if is_copy else "Move"297self.commit(translate("draft", _mode),298_cmd_list)299
300def numericInput(self, numx, numy, numz):301"""Validate the entry fields in the user interface.302
303This function is called by the toolbar or taskpanel interface
304when valid x, y, and z have been entered in the input fields.
305"""
306self.point = App.Vector(numx, numy, numz)307if not self.node:308self.node.append(self.point)309self.ui.isRelative.show()310self.ui.isCopy.show()311for ghost in self.ghosts:312ghost.on()313_toolmsg(translate("draft", "Pick end point"))314else:315last = self.node[-1]316self.vector = self.point.sub(last)317self.move(self.ui.isCopy.isChecked())318self.finish(cont=None)319
320
321Gui.addCommand('Draft_Move', Move())322
323## @}
324