FreeCAD

Форк
0
233 строки · 9.7 Кб
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 create Label objects.
26

27
Labels are similar to text annotations but include a leader line
28
and an arrow in order to point to an object and indicate some of its
29
properties.
30
"""
31
## @package gui_labels
32
# \ingroup draftguitools
33
# \brief Provides GUI tools to create Label objects.
34

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

40
import FreeCAD as App
41
import FreeCADGui as Gui
42
import Draft_rc
43
import DraftVecUtils
44
from draftguitools import gui_base_original
45
from draftguitools import gui_tool_utils
46
from draftguitools import gui_trackers as trackers
47
from draftutils import params
48
from draftutils.messages import _toolmsg
49
from draftutils.translate import translate
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 Label(gui_base_original.Creator):
56
    """Gui Command for the Label tool."""
57

58
    def GetResources(self):
59
        """Set icon, menu and tooltip."""
60

61
        return {'Pixmap': 'Draft_Label',
62
                'Accel': "D, L",
63
                'MenuText': QT_TRANSLATE_NOOP("Draft_Label", "Label"),
64
                'ToolTip': QT_TRANSLATE_NOOP("Draft_Label", "Creates a label, optionally attached to a selected object or subelement.\n\nFirst select a vertex, an edge, or a face of an object, then call this command,\nand then set the position of the leader line and the textual label.\nThe label will be able to display information about this object, and about the selected subelement,\nif any.\n\nIf many objects or many subelements are selected, only the first one in each case\nwill be used to provide information to the label.")}
65

66
    def Activated(self):
67
        """Execute when the command is called."""
68
        super().Activated(name="Label")
69
        self.ghost = None
70
        self.labeltype = params.get_param("labeltype")
71
        self.sel = Gui.Selection.getSelectionEx()
72
        if self.sel:
73
            self.sel = self.sel[0]
74
        self.ui.labelUi(title=translate("draft",self.featureName), callback=self.setmode)
75
        self.ui.xValue.setFocus()
76
        self.ui.xValue.selectAll()
77
        self.ghost = trackers.lineTracker()
78
        self.call = self.view.addEventCallback("SoEvent", self.action)
79
        _toolmsg(translate("draft", "Pick target point"))
80
        self.ui.isCopy.hide()
81

82
    def setmode(self, i):
83
        """Set the type of label, if it is associated to an object."""
84
        from draftobjects.label import get_label_types
85
        self.labeltype = get_label_types()[i]
86
        params.set_param("labeltype", self.labeltype)
87

88
    def finish(self, cont=False):
89
        """Finish the command."""
90
        self.end_callbacks(self.call)
91
        if self.ghost:
92
            self.ghost.finalize()
93
        super().finish()
94

95
    def create(self):
96
        """Create the actual object."""
97
        if len(self.node) == 3:
98
            targetpoint = self.node[0]
99
            basepoint = self.node[2]
100
            v = self.node[2].sub(self.node[1])
101
            dist = v.Length
102
            h = self.wp.u
103
            n = self.wp.axis
104
            r = self.wp.get_placement().Rotation
105

106
            if abs(DraftVecUtils.angle(v, h, n)) <= math.pi/4:
107
                direction = "Horizontal"
108
                dist = -dist
109
            elif abs(DraftVecUtils.angle(v, h, n)) >= math.pi*3/4:
110
                direction = "Horizontal"
111
            elif DraftVecUtils.angle(v, h, n) > 0:
112
                direction = "Vertical"
113
            else:
114
                direction = "Vertical"
115
                dist = -dist
116

117
            tp = DraftVecUtils.toString(targetpoint)
118
            sel = None
119
            if self.sel:
120
                sel = "FreeCAD.ActiveDocument." + self.sel.Object.Name
121

122
                if self.sel.SubElementNames:
123
                    sub = "'" + self.sel.SubElementNames[0] + "'"
124
                else:
125
                    sub = "None"
126

127
            pl = "FreeCAD.Placement"
128
            pl += "("
129
            pl += DraftVecUtils.toString(basepoint) + ", "
130
            pl += "FreeCAD.Rotation" + str(r.Q)
131
            pl += ")"
132

133
            Gui.addModule("Draft")
134
            _cmd = "Draft.make_label"
135
            _cmd += "("
136
            _cmd += "target_point=" + tp + ", "
137
            _cmd += "placement=" + pl + ", "
138
            if sel:
139
                _cmd += "target_object=" + sel + ", "
140
                _cmd += "subelements=" + sub + ", "
141
            _cmd += "label_type=" + "'" + self.labeltype + "'" + ", "
142
            # _cmd += "custom_text=" + "'Label'" + ", "
143
            _cmd += "direction=" + "'" + direction + "'" + ", "
144
            _cmd += "distance=" + str(dist)
145
            _cmd += ")"
146

147
            # Commit the creation instructions through the parent class,
148
            # the Creator class
149
            _cmd_list = ['_label_ = ' + _cmd,
150
                         'Draft.autogroup(_label_)',
151
                         'FreeCAD.ActiveDocument.recompute()']
152
            self.commit(translate("draft", "Create Label"),
153
                        _cmd_list)
154
        self.finish()
155

156
    def action(self, arg):
157
        """Handle the 3D scene events.
158

159
        This is installed as an EventCallback in the Inventor view.
160

161
        Parameters
162
        ----------
163
        arg: dict
164
            Dictionary with strings that indicates the type of event received
165
            from the 3D view.
166
        """
167
        if arg["Type"] == "SoKeyboardEvent":
168
            if arg["Key"] == "ESCAPE":
169
                self.finish()
170
        elif arg["Type"] == "SoLocation2Event":
171
            if hasattr(Gui, "Snapper"):
172
                Gui.Snapper.affinity = None  # don't keep affinity
173
            if len(self.node) == 2:
174
                gui_tool_utils.setMod(arg, gui_tool_utils.get_mod_constrain_key(), True)
175
            self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg)
176
            gui_tool_utils.redraw3DView()
177
        elif arg["Type"] == "SoMouseButtonEvent":
178
            if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"):
179
                if self.point:
180
                    self.ui.redraw()
181
                    if not self.node:
182
                        # first click
183
                        self.node.append(self.point)
184
                        self.ui.isRelative.show()
185
                        _toolmsg(translate("draft",
186
                                       "Pick endpoint of leader line"))
187
                        if self.planetrack:
188
                            self.planetrack.set(self.point)
189
                    elif len(self.node) == 1:
190
                        # second click
191
                        self.node.append(self.point)
192
                        if self.ghost:
193
                            self.ghost.p1(self.node[0])
194
                            self.ghost.p2(self.node[1])
195
                            self.ghost.on()
196
                        _toolmsg(translate("draft", "Pick text position"))
197
                    else:
198
                        # third click
199
                        self.node.append(self.point)
200
                        self.create()
201

202
    def numericInput(self, numx, numy, numz):
203
        """Validate the entry fields in the user interface.
204

205
        This function is called by the toolbar or taskpanel interface
206
        when valid x, y, and z have been entered in the input fields.
207
        """
208
        self.point = App.Vector(numx, numy, numz)
209
        if not self.node:
210
            # first click
211
            self.node.append(self.point)
212
            self.ui.isRelative.show()
213
            _toolmsg(translate("draft", "Pick endpoint of leader line"))
214
            if self.planetrack:
215
                self.planetrack.set(self.point)
216
        elif len(self.node) == 1:
217
            # second click
218
            self.node.append(self.point)
219
            if self.ghost:
220
                self.ghost.p1(self.node[0])
221
                self.ghost.p2(self.node[1])
222
                self.ghost.on()
223
            _toolmsg(translate("draft", "Pick text position"))
224
        else:
225
            # third click
226
            self.node.append(self.point)
227
            self.create()
228

229

230
Draft_Label = Label
231
Gui.addCommand('Draft_Label', Label())
232

233
## @}
234

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

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

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

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