FreeCAD

Форк
0
/
gui_base_original.py 
292 строки · 10.4 Кб
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 the base classes for most old Draft Gui Commands.
26

27
This class is used by Gui Commands to set up some properties
28
of the DraftToolBar, the Snapper, and the working plane.
29
"""
30
## @package gui_base_original
31
# \ingroup draftguitools
32
# \brief Provides the base classes for most old Draft Gui Commands.
33

34
## \addtogroup draftguitools
35
# @{
36

37
from PySide import QtCore
38

39
import FreeCAD as App
40
import FreeCADGui as Gui
41
import DraftVecUtils
42
import WorkingPlane
43
from draftguitools import gui_tool_utils
44
from draftguitools import gui_trackers as trackers
45
from draftutils import gui_utils
46
from draftutils import params
47
from draftutils import todo
48
from draftutils import utils
49
from draftutils.messages import _log, _toolmsg
50

51

52
class DraftTool:
53
    """The base class of all Draft Tools.
54

55
    This is the original class that was defined in `DraftTools.py`
56
    before any re-organization of the code.
57

58
    This class is subclassed by `Creator` and `Modifier`
59
    to set up a few additional properties of these two types.
60

61
    This class connects with the `draftToolBar` and `Snapper` classes
62
    that are installed in the `FreeCADGui` namespace in order to set up some
63
    properties of the running tools such as the task panel, the snapping
64
    functions, and the grid trackers.
65

66
    It also connects with the `WorkingPlane` class.
67

68
    This class is intended to be replaced by newer classes inside the
69
    `gui_base` module, in particular, `GuiCommandBase`.
70
    """
71

72
    def __init__(self):
73
        self.commitList = []
74

75
    def IsActive(self):
76
        """Return True when this command should be available.
77

78
        It is `True` when there is a document.
79
        """
80
        if Gui.ActiveDocument:
81
            return True
82
        else:
83
            return False
84

85
    def Activated(self, name="None", is_subtool=False):
86
        """Execute when the command is called.
87

88
        If an active Gui Command exists, it will call the `finish` method
89
        of it to terminate it.
90

91
        If no active Gui Command exists, it will proceed with configuration
92
        of the tool. The child class that subclasses this class
93
        then should continue with its own Activated method.
94

95
        Parameters
96
        ----------
97
        name: str, optional
98
            It defaults to `'None'`.
99
            It is the `featureName` of the object, to know what is being run.
100

101
        is_subtool: bool, optional
102
            It defaults to `False`.
103
            This is set to `True` when we want to modify an object
104
            by using the mechanism of a `subtool`, introduced
105
            through the `Draft_SubelementHighlight` command.
106
            That is, first we run `Draft_SubelementHighlight`
107
            then we can use `Draft_Move` while setting `is_subtool` to `True`.
108
        """
109
        if App.activeDraftCommand and not is_subtool:
110
            App.activeDraftCommand.finish()
111
        App.activeDraftCommand = self
112

113
        # The Part module is first initialized when using any Gui Command
114
        # for the first time.
115
        global Part, DraftGeomUtils
116
        import Part
117
        import DraftGeomUtils
118

119
        self.call = None
120
        self.commitList = []
121
        self.constrain = None
122
        self.doc = App.ActiveDocument
123
        self.extendedCopy = False
124
        self.featureName = name
125
        self.node = []
126
        self.obj = None
127
        self.point = None
128
        self.pos = []
129
        self.support = None
130
        self.ui = Gui.draftToolBar
131
        self.ui.mouse = True  # reset mouse movement
132
        self.ui.sourceCmd = self
133
        self.view = gui_utils.get_3d_view()
134
        self.wp = WorkingPlane.get_working_plane()
135

136
        self.planetrack = None
137
        if params.get_param("showPlaneTracker"):
138
            self.planetrack = trackers.PlaneTracker()
139
        if hasattr(Gui, "Snapper"):
140
            Gui.Snapper.setTrackers()
141

142
        _toolmsg("{}".format(16*"-"))
143
        _toolmsg("GuiCommand: {}".format(self.featureName))
144

145
    def end_callbacks(self, call):
146
        try:
147
            self.view.removeEventCallback("SoEvent", call)
148
            gui_utils.end_all_events()
149
        except RuntimeError:
150
            # the view has been deleted already
151
            pass
152
        call = None
153

154
    def finish(self, cont=False):
155
        """Finish the current command.
156

157
        These are general cleaning tasks that are performed
158
        when terminating all commands.
159

160
        These include setting the node list to empty,
161
        setting to `None` the active command,
162
        turning off the graphical interface (task panel),
163
        finishing the plane tracker, restoring the working plane,
164
        turning off the snapper.
165

166
        If a callback is installed in the 3D view, the callback is removed,
167
        and set to `None`.
168

169
        If the commit list is non-empty it will commit the instructions on
170
        the list with `draftutils.todo.ToDo.delayCommit`,
171
        and the list will be set to empty.
172
        """
173
        self.node = []
174
        App.activeDraftCommand = None
175
        if self.ui:
176
            self.ui.offUi()
177
            self.ui.sourceCmd = None
178
        if hasattr(Gui, "Snapper"):
179
            Gui.Snapper.off()
180
        if self.planetrack:
181
            self.planetrack.finalize()
182
        self.wp._restore()
183
        if self.commitList:
184
            last_cmd = self.commitList[-1][1][-1]
185
            if last_cmd.find("recompute") >= 0:
186
                self.commitList[-1] = (self.commitList[-1][0], self.commitList[-1][1][:-1])
187
                todo.ToDo.delayCommit(self.commitList)
188
                todo.ToDo.delayAfter(Gui.doCommand, last_cmd)
189
            else:
190
                todo.ToDo.delayCommit(self.commitList)
191
        self.commitList = []
192

193
    def commit(self, name, func):
194
        """Store actions in the commit list to be run later.
195

196
        Parameters
197
        ----------
198
        name: str
199
            An arbitrary string that indicates the name of the operation
200
            to run.
201

202
        func: list of str
203
            Each element of the list is a string that will be run by
204
            `Gui.doCommand`.
205

206
            See the complete information in the `draftutils.todo.ToDo` class.
207
        """
208
        self.commitList.append((name, func))
209

210
    def getStrings(self, addrot=None):
211
        """Return useful strings that will be used to build commands.
212

213
        Returns
214
        -------
215
        str, str, str, str
216
            A tuple of four strings that represent useful information.
217

218
            * the current working plane rotation quaternion as a string
219
            * the support object if available as a string
220
            * the list of nodes inside the `node` attribute as a string
221
            * the string `'True'` or `'False'` depending on the fill mode
222
              of the current tool
223
        """
224
        # Current plane rotation as a string
225
        qr = self.wp.get_placement().Rotation.Q
226
        qr = "({0}, {1}, {2}, {3})".format(qr[0], qr[1], qr[2], qr[3])
227

228
        # Support object
229
        if self.support and params.get_param("useSupport"):
230
            sup = 'FreeCAD.ActiveDocument.getObject'
231
            sup += '("{}")'.format(self.support.Name)
232
        else:
233
            sup = 'None'
234

235
        # Contents of self.node
236
        points = '['
237
        for n in self.node:
238
            if len(points) > 1:
239
                points += ', '
240
            points += DraftVecUtils.toString(n)
241
        points += ']'
242

243
        # Fill mode
244
        if self.ui:
245
            fil = str(bool(self.ui.fillmode))
246
        else:
247
            fil = "True"
248

249
        return qr, sup, points, fil
250

251

252
class Creator(DraftTool):
253
    """A generic Creator tool, used by creation tools such as line or arc.
254

255
    It inherits `DraftTool`, which sets up the majority of the behavior
256
    of this class.
257
    """
258

259
    def Activated(self, name="None"):
260
        """Execute when the command is called.
261

262
        Parameters
263
        ----------
264
        name: str, optional
265
            It defaults to `'None'`.
266
            It is the `featureName` of the object, to know what is being run.
267
        """
268
        super().Activated(name)
269
        # call _save to sync with _restore called in finish method
270
        self.wp._save()
271
        self.support = gui_tool_utils.get_support()
272

273

274
class Modifier(DraftTool):
275
    """A generic Modifier tool, used by modification tools such as move.
276

277
    After initializing the parent class, it sets the `copymode` attribute
278
    to `False`.
279

280
    It inherits `DraftTool`, which sets up the majority of the behavior
281
    of this class.
282
    """
283

284
    def __init__(self):
285
        super().__init__()
286
        self.copymode = False
287

288
    def Activated(self, name="None", is_subtool=False):
289
        super().Activated(name, is_subtool)
290
        # call _save to sync with _restore called in finish method
291
        self.wp._save()
292
## @}
293

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

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

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

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