FreeCAD
360 строк · 14.8 Кб
1# ***************************************************************************
2# * (c) 2009 Yorik van Havre <yorik@uncreated.net> *
3# * (c) 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 create straight Line and Wire objects.
26
27The Line class is used by other Gui Commands that behave in a similar way
28like Wire, BSpline, and BezCurve.
29"""
30## @package gui_lines
31# \ingroup draftguitools
32# \brief Provides GUI tools to create straight Line and Wire objects.
33
34## \addtogroup draftguitools
35# @{
36from PySide.QtCore import QT_TRANSLATE_NOOP37
38import FreeCAD as App39import FreeCADGui as Gui40import DraftVecUtils41from draftguitools import gui_base_original42from draftguitools import gui_tool_utils43from draftutils import gui_utils44from draftutils import params45from draftutils import utils46from draftutils import todo47from draftutils.messages import _err, _toolmsg48from draftutils.translate import translate49
50
51class Line(gui_base_original.Creator):52"""Gui command for the Line tool."""53
54def __init__(self, wiremode=False):55super().__init__()56self.isWire = wiremode57
58def GetResources(self):59"""Set icon, menu and tooltip."""60
61return {'Pixmap': 'Draft_Line',62'Accel': "L,I",63'MenuText': QT_TRANSLATE_NOOP("Draft_Line", "Line"),64'ToolTip': QT_TRANSLATE_NOOP("Draft_Line", "Creates a 2-point line. CTRL to snap, SHIFT to constrain.")}65
66def Activated(self, name=QT_TRANSLATE_NOOP("draft", "Line"), icon="Draft_Line", task_title=None):67"""Execute when the command is called."""68super().Activated(name)69if task_title is None:70title = translate("draft", name)71else:72title = task_title73if self.isWire:74self.ui.wireUi(title=title, icon=icon)75else:76self.ui.lineUi(title=title, icon=icon)77
78self.obj = self.doc.addObject("Part::Feature", self.featureName)79gui_utils.format_object(self.obj)80
81self.call = self.view.addEventCallback("SoEvent", self.action)82_toolmsg(translate("draft", "Pick first point"))83
84def action(self, arg):85"""Handle the 3D scene events.86
87This is installed as an EventCallback in the Inventor view.
88
89Parameters
90----------
91arg: dict
92Dictionary with strings that indicates the type of event received
93from the 3D view.
94"""
95if arg["Type"] == "SoKeyboardEvent" and arg["Key"] == "ESCAPE":96self.finish()97elif arg["Type"] == "SoLocation2Event":98self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg)99gui_tool_utils.redraw3DView()100elif (arg["Type"] == "SoMouseButtonEvent"101and arg["State"] == "DOWN"102and arg["Button"] == "BUTTON1"):103if arg["Position"] == self.pos:104self.finish(cont=None)105return106if (not self.node) and (not self.support):107gui_tool_utils.getSupport(arg)108(self.point,109ctrlPoint, info) = gui_tool_utils.getPoint(self, arg)110if self.point:111self.ui.redraw()112self.pos = arg["Position"]113self.node.append(self.point)114self.drawSegment(self.point)115if not self.isWire and len(self.node) == 2:116self.finish(cont=None, closed=False)117if len(self.node) > 2:118# The wire is closed119if (self.point - self.node[0]).Length < utils.tolerance():120self.undolast()121if len(self.node) > 2:122self.finish(cont=None, closed=True)123else:124self.finish(cont=None, closed=False)125
126def finish(self, cont=False, closed=False):127"""Terminate the operation and close the polyline if asked.128
129Parameters
130----------
131cont: bool or None, optional
132Restart (continue) the command if `True`, or if `None` and
133`ui.continueMode` is `True`.
134closed: bool, optional
135Close the line if `True`.
136"""
137self.end_callbacks(self.call)138self.removeTemporaryObject()139
140if len(self.node) > 1:141Gui.addModule("Draft")142# The command to run is built as a series of text strings143# to be committed through the `draftutils.todo.ToDo` class.144if (len(self.node) == 2145and params.get_param("UsePartPrimitives")):146# Insert a Part::Primitive object147p1 = self.node[0]148p2 = self.node[-1]149
150_cmd = 'FreeCAD.ActiveDocument.'151_cmd += 'addObject("Part::Line", "Line")'152_cmd_list = ['line = ' + _cmd,153'line.X1 = ' + str(p1.x),154'line.Y1 = ' + str(p1.y),155'line.Z1 = ' + str(p1.z),156'line.X2 = ' + str(p2.x),157'line.Y2 = ' + str(p2.y),158'line.Z2 = ' + str(p2.z),159'Draft.autogroup(line)',160'Draft.select(line)',161'FreeCAD.ActiveDocument.recompute()']162self.commit(translate("draft", "Create Line"),163_cmd_list)164else:165# Insert a Draft line166rot, sup, pts, fil = self.getStrings()167
168_base = DraftVecUtils.toString(self.node[0])169_cmd = 'Draft.make_wire'170_cmd += '('171_cmd += 'points, '172_cmd += 'placement=pl, '173_cmd += 'closed=' + str(closed) + ', '174_cmd += 'face=' + fil + ', '175_cmd += 'support=' + sup176_cmd += ')'177_cmd_list = ['pl = FreeCAD.Placement()',178'pl.Rotation.Q = ' + rot,179'pl.Base = ' + _base,180'points = ' + pts,181'line = ' + _cmd,182'Draft.autogroup(line)',183'FreeCAD.ActiveDocument.recompute()']184self.commit(translate("draft", "Create Wire"),185_cmd_list)186super().finish()187if cont or (cont is None and self.ui and self.ui.continueMode):188self.Activated()189
190def removeTemporaryObject(self):191"""Remove temporary object created."""192if self.obj:193try:194old = self.obj.Name195except ReferenceError:196# object already deleted, for some reason197pass198else:199todo.ToDo.delay(self.doc.removeObject, old)200self.obj = None201
202def undolast(self):203"""Undoes last line segment."""204import Part205if len(self.node) > 1:206self.node.pop()207# last = self.node[-1]208if self.obj.Shape.Edges:209edges = self.obj.Shape.Edges210if len(edges) > 1:211newshape = Part.makePolygon(self.node)212self.obj.Shape = newshape213else:214self.obj.ViewObject.hide()215# DNC: report on removal216# _toolmsg(translate("draft", "Removing last point"))217_toolmsg(translate("draft", "Pick next point"))218
219def drawSegment(self, point):220"""Draws new line segment."""221import Part222if self.planetrack and self.node:223self.planetrack.set(self.node[-1])224if len(self.node) == 1:225_toolmsg(translate("draft", "Pick next point"))226elif len(self.node) == 2:227last = self.node[len(self.node) - 2]228newseg = Part.LineSegment(last, point).toShape()229self.obj.Shape = newseg230self.obj.ViewObject.Visibility = True231if self.isWire:232_toolmsg(translate("draft", "Pick next point"))233else:234currentshape = self.obj.Shape.copy()235last = self.node[len(self.node) - 2]236if not DraftVecUtils.equals(last, point):237newseg = Part.LineSegment(last, point).toShape()238newshape = currentshape.fuse(newseg)239self.obj.Shape = newshape240_toolmsg(translate("draft", "Pick next point"))241
242def wipe(self):243"""Remove all previous segments and starts from last point."""244if len(self.node) > 1:245# self.obj.Shape.nullify() # For some reason this fails246self.obj.ViewObject.Visibility = False247self.node = [self.node[-1]]248if self.planetrack:249self.planetrack.set(self.node[0])250_toolmsg(translate("draft", "Pick next point"))251
252def orientWP(self):253"""Orient the working plane."""254if len(self.node) > 1 and self.obj:255import DraftGeomUtils256n = DraftGeomUtils.getNormal(self.obj.Shape)257if not n:258n = self.wp.axis259p = self.node[-1]260v = self.node[-1].sub(self.node[-2])261self.wp.align_to_point_and_axis(p, n, upvec=v, _hist_add=False)262if self.planetrack:263self.planetrack.set(self.node[-1])264
265def numericInput(self, numx, numy, numz):266"""Validate the entry fields in the user interface.267
268This function is called by the toolbar or taskpanel interface
269when valid x, y, and z have been entered in the input fields.
270"""
271self.point = App.Vector(numx, numy, numz)272self.node.append(self.point)273self.drawSegment(self.point)274if not self.isWire and len(self.node) == 2:275self.finish(cont=None, closed=False)276self.ui.setNextFocus()277
278
279Gui.addCommand('Draft_Line', Line())280
281
282class Wire(Line):283"""Gui command for the Wire or Polyline tool.284
285It inherits the `Line` class, and calls essentially the same code,
286only this time the `wiremode` is set to `True`,
287so we are allowed to place more than two points.
288"""
289
290def __init__(self):291super().__init__(wiremode=True)292
293def GetResources(self):294"""Set icon, menu and tooltip."""295
296return {'Pixmap': 'Draft_Wire',297'Accel': "P, L",298'MenuText': QT_TRANSLATE_NOOP("Draft_Wire", "Polyline"),299'ToolTip': QT_TRANSLATE_NOOP("Draft_Wire", "Creates a multiple-points line (polyline). CTRL to snap, SHIFT to constrain.")}300
301def Activated(self):302"""Execute when the command is called."""303import Part304
305# If there is a selection, and this selection contains various306# two-point lines, their shapes are extracted, and we attempt307# to join them into a single Wire (polyline),308# then the old lines are removed.309if len(Gui.Selection.getSelection()) > 1:310edges = []311for o in Gui.Selection.getSelection():312if utils.get_type(o) != "Wire":313edges = []314break315edges.extend(o.Shape.Edges)316if edges:317try:318w = Part.Wire(Part.__sortEdges__(edges))319except Exception:320_err(translate("draft",321"Unable to create a Wire "322"from selected objects"))323else:324# Points of the new fused Wire in string form325# 'FreeCAD.Vector(x,y,z), FreeCAD.Vector(x1,y1,z1), ...'326pts = ", ".join([str(v.Point) for v in w.Vertexes])327pts = pts.replace("Vector ", "FreeCAD.Vector")328
329# List of commands to remove the old objects330rems = list()331for o in Gui.Selection.getSelection():332rems.append('FreeCAD.ActiveDocument.'333'removeObject("' + o.Name + '")')334
335Gui.addModule("Draft")336# The command to run is built as a series of text strings337# to be committed through the `draftutils.todo.ToDo` class338_cmd = 'wire = Draft.make_wire('339_cmd += '[' + pts + '], closed=' + str(w.isClosed())340_cmd += ')'341_cmd_list = [_cmd]342_cmd_list.extend(rems)343_cmd_list.append('Draft.autogroup(wire)')344_cmd_list.append('FreeCAD.ActiveDocument.recompute()')345
346_op_name = translate("draft", "Convert to Wire")347todo.ToDo.delayCommit([(_op_name, _cmd_list)])348return349
350# If there was no selection or the selection was just one object351# then we proceed with the normal line creation functions,352# only this time we will be able to input more than two points353super().Activated(name="Polyline",354icon="Draft_Wire",355task_title=translate("draft", "Polyline"))356
357
358Gui.addCommand('Draft_Wire', Wire())359
360## @}
361