FreeCAD

Форк
0
/
gui_rectangles.py 
207 строк · 8.7 Кб
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 Rectangle objects."""
26
## @package gui_rectangles
27
# \ingroup draftguitools
28
# \brief Provides GUI tools to create Rectangle objects.
29

30
## \addtogroup draftguitools
31
# @{
32
from PySide.QtCore import QT_TRANSLATE_NOOP
33

34
import FreeCAD as App
35
import FreeCADGui as Gui
36
import DraftVecUtils
37
from draftguitools import gui_base_original
38
from draftguitools import gui_tool_utils
39
from draftguitools import gui_trackers as trackers
40
from draftutils import params
41
from draftutils import utils
42
from draftutils.messages import _err, _toolmsg
43
from draftutils.translate import translate
44

45

46
class Rectangle(gui_base_original.Creator):
47
    """Gui command for the Rectangle tool."""
48

49
    def GetResources(self):
50
        """Set icon, menu and tooltip."""
51

52
        return {'Pixmap': 'Draft_Rectangle',
53
                'Accel': "R, E",
54
                'MenuText': QT_TRANSLATE_NOOP("Draft_Rectangle", "Rectangle"),
55
                'ToolTip': QT_TRANSLATE_NOOP("Draft_Rectangle", "Creates a 2-point rectangle. CTRL to snap.")}
56

57
    def Activated(self):
58
        """Execute when the command is called."""
59
        super().Activated(name="Rectangle")
60
        if self.ui:
61
            self.refpoint = None
62
            self.ui.pointUi(title=translate("draft", "Rectangle"), icon="Draft_Rectangle")
63
            self.ui.extUi()
64
            self.call = self.view.addEventCallback("SoEvent", self.action)
65
            self.rect = trackers.rectangleTracker()
66
            _toolmsg(translate("draft", "Pick first point"))
67

68
    def finish(self, cont=False):
69
        """Terminate the operation.
70

71
        Parameters
72
        ----------
73
        cont: bool or None, optional
74
            Restart (continue) the command if `True`, or if `None` and
75
            `ui.continueMode` is `True`.
76
        """
77
        self.end_callbacks(self.call)
78
        if self.ui:
79
            self.rect.off()
80
            self.rect.finalize()
81
        super().finish()
82
        if cont or (cont is None and self.ui and self.ui.continueMode):
83
            self.Activated()
84

85
    def createObject(self):
86
        """Create the final object in the current document."""
87
        p1 = self.node[0]
88
        p3 = self.node[-1]
89
        diagonal = p3.sub(p1)
90
        p2 = p1.add(DraftVecUtils.project(diagonal, self.wp.v))
91
        p4 = p1.add(DraftVecUtils.project(diagonal, self.wp.u))
92
        length = p4.sub(p1).Length
93
        if abs(DraftVecUtils.angle(p4.sub(p1), self.wp.u, self.wp.axis)) > 1:
94
            length = -length
95
        height = p2.sub(p1).Length
96
        if abs(DraftVecUtils.angle(p2.sub(p1), self.wp.v, self.wp.axis)) > 1:
97
            height = -height
98
        try:
99
            # The command to run is built as a series of text strings
100
            # to be committed through the `draftutils.todo.ToDo` class.
101
            rot, sup, pts, fil = self.getStrings()
102
            base = p1
103
            if length < 0:
104
                length = -length
105
                base = base.add((p1.sub(p4)).negative())
106
            if height < 0:
107
                height = -height
108
                base = base.add((p1.sub(p2)).negative())
109
            Gui.addModule("Draft")
110
            if params.get_param("UsePartPrimitives"):
111
                # Insert a Part::Primitive object
112
                _cmd = 'FreeCAD.ActiveDocument.'
113
                _cmd += 'addObject("Part::Plane", "Plane")'
114
                _cmd_list = ['plane = ' + _cmd,
115
                             'plane.Length = ' + str(length),
116
                             'plane.Width = ' + str(height),
117
                             'pl = FreeCAD.Placement()',
118
                             'pl.Rotation.Q=' + rot,
119
                             'pl.Base = ' + DraftVecUtils.toString(base),
120
                             'plane.Placement = pl',
121
                             'Draft.autogroup(plane)',
122
                             'Draft.select(plane)',
123
                             'FreeCAD.ActiveDocument.recompute()']
124
                self.commit(translate("draft", "Create Plane"),
125
                            _cmd_list)
126
            else:
127
                _cmd = 'Draft.make_rectangle'
128
                _cmd += '('
129
                _cmd += 'length=' + str(length) + ', '
130
                _cmd += 'height=' + str(height) + ', '
131
                _cmd += 'placement=pl, '
132
                _cmd += 'face=' + fil + ', '
133
                _cmd += 'support=' + sup
134
                _cmd += ')'
135
                _cmd_list = ['pl = FreeCAD.Placement()',
136
                             'pl.Rotation.Q = ' + rot,
137
                             'pl.Base = ' + DraftVecUtils.toString(base),
138
                             'rec = ' + _cmd,
139
                             'Draft.autogroup(rec)',
140
                             'FreeCAD.ActiveDocument.recompute()']
141
                self.commit(translate("draft", "Create Rectangle"),
142
                            _cmd_list)
143
        except Exception:
144
            _err("Draft: error delaying commit")
145
        self.finish(cont=None)
146

147
    def action(self, arg):
148
        """Handle the 3D scene events.
149

150
        This is installed as an EventCallback in the Inventor view.
151

152
        Parameters
153
        ----------
154
        arg: dict
155
            Dictionary with strings that indicates the type of event received
156
            from the 3D view.
157
        """
158
        if arg["Type"] == "SoKeyboardEvent":
159
            if arg["Key"] == "ESCAPE":
160
                self.finish()
161
        elif arg["Type"] == "SoLocation2Event":  # mouse movement detection
162
            self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg, noTracker=True)
163
            self.rect.update(self.point)
164
            gui_tool_utils.redraw3DView()
165
        elif (arg["Type"] == "SoMouseButtonEvent"
166
              and arg["State"] == "DOWN"
167
              and arg["Button"] == "BUTTON1"):
168

169
            if arg["Position"] == self.pos:
170
                self.finish(cont=None)
171
                return
172

173
            if (not self.node) and (not self.support):
174
                gui_tool_utils.getSupport(arg)
175
                self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg, noTracker=True)
176
            if self.point:
177
                self.ui.redraw()
178
                self.pos = arg["Position"]
179
                self.appendPoint(self.point)
180

181
    def numericInput(self, numx, numy, numz):
182
        """Validate the entry fields in the user interface.
183

184
        This function is called by the toolbar or taskpanel interface
185
        when valid x, y, and z have been entered in the input fields.
186
        """
187
        self.point = App.Vector(numx, numy, numz)
188
        self.appendPoint(self.point)
189

190
    def appendPoint(self, point):
191
        """Append a point to the list of nodes."""
192
        self.node.append(point)
193
        if len(self.node) > 1:
194
            self.rect.update(point)
195
            self.createObject()
196
        else:
197
            _toolmsg(translate("draft", "Pick opposite point"))
198
            self.ui.setRelative()
199
            self.rect.setorigin(point)
200
            self.rect.on()
201
            if self.planetrack:
202
                self.planetrack.set(point)
203

204

205
Gui.addCommand('Draft_Rectangle', Rectangle())
206

207
## @}
208

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

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

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

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