FreeCAD

Форк
0
219 строк · 7.8 Кб
1
# ***************************************************************************
2
# *   (c) 2009 Yorik van Havre <yorik@uncreated.net>                        *
3
# *   (c) 2010 Ken Cline <cline@frii.com>                                   *
4
# *   (c) 2019 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 newer Draft Gui Commands."""
26
## @package gui_base
27
# \ingroup draftguitools
28
# \brief Provides the base classes for newer Draft Gui Commands.
29

30
## \addtogroup draftguitools
31
# @{
32
import FreeCAD as App
33
import FreeCADGui as Gui
34
import draftutils.todo as todo
35

36
from draftutils.messages import _toolmsg, _log
37

38

39
class GuiCommandSimplest:
40
    """Simplest base class for GuiCommands.
41

42
    This class only sets up the command name and the document object
43
    to use for the command.
44
    When it is executed, it logs the command name to the log file,
45
    and prints the command name to the console.
46

47
    It implements the `IsActive` method, which must return `True`
48
    when the command should be available.
49
    It should return `True` when there is an active document,
50
    otherwise the command (button or menu) should be disabled.
51

52
    This class is meant to be inherited by other GuiCommand classes
53
    to quickly log the command name, and set the correct document object.
54

55
    Parameter
56
    ---------
57
    name: str, optional
58
        It defaults to `'None'`.
59
        The name of the action that is being run,
60
        for example, `'Heal'`, `'Flip dimensions'`,
61
        `'Line'`, `'Circle'`, etc.
62

63
    doc: App::Document, optional
64
        It defaults to the value of `App.activeDocument()`.
65
        The document object itself, which indicates where the actions
66
        of the command will be executed.
67

68
    Attributes
69
    ----------
70
    command_name: str
71
        This is the command name, which is assigned by `name`.
72

73
    doc: App::Document
74
        This is the document object itself, which is assigned by `doc`.
75

76
        This attribute should be used by functions to make sure
77
        that the operations are performed in the correct document
78
        and not in other documents.
79
        To set the active document we can use
80

81
        >>> App.setActiveDocument(self.doc.Name)
82
    """
83

84
    def __init__(self, name="None", doc=App.activeDocument()):
85
        self.command_name = name
86
        self.doc = doc
87

88
    def IsActive(self):
89
        """Return True when this command should be available.
90

91
        It is `True` when there is a document.
92
        """
93
        if App.activeDocument():
94
            return True
95
        else:
96
            return False
97

98
    def Activated(self):
99
        """Execute when the command is called.
100

101
        Log the command name to the log file and console.
102
        Also update the `doc` attribute.
103
        """
104
        self.doc = App.activeDocument()
105
        _log("Document: {}".format(self.doc.Label))
106
        _log("GuiCommand: {}".format(self.command_name))
107
        _toolmsg("{}".format(16*"-"))
108
        _toolmsg("GuiCommand: {}".format(self.command_name))
109

110

111
class GuiCommandNeedsSelection(GuiCommandSimplest):
112
    """Base class for GuiCommands that need a selection to be available.
113

114
    It re-implements the `IsActive` method to return `True`
115
    when there is both an active document and an active selection.
116

117
    It inherits `GuiCommandSimplest` to set up the document
118
    and other behavior. See this class for more information.
119
    """
120

121
    def IsActive(self):
122
        """Return True when this command should be available.
123

124
        It is `True` when there is a selection.
125
        """
126
        if App.activeDocument() and Gui.Selection.getSelection():
127
            return True
128
        else:
129
            return False
130

131

132
class GuiCommandBase:
133
    """Generic class that is the basis of all Gui commands.
134

135
    This class should eventually replace `DraftTools.DraftTool`,
136
    once all functionality in that class is merged here.
137

138
    Attributes
139
    ----------
140
    commit_list : list of 2-element tuples
141
        Each tuple is made of a string, and a list of strings.
142
        ::
143
            commit_list = [(string1, list1), (string2, list2), ...]
144

145
        The string is a simple header, for example, a command name,
146
        that indicates what is being executed.
147

148
        Each string in the list of strings represents a Python instruction
149
        which will be executed in a delayed fashion
150
        by `todo.ToDo.delayCommit()`
151
        ::
152
            list1 = ["a = FreeCAD.Vector()",
153
                     "pl = FreeCAD.Placement()",
154
                     "Draft.autogroup(obj)"]
155

156
            commit_list = [("Something", list1)]
157

158
        This is used when the 3D view has event callbacks that crash
159
        Coin3D.
160
        If this is not needed, those commands could be called in the
161
        body of the command without problem.
162
        ::
163
            >>> a = FreeCAD.Vector()
164
            >>> pl = FreeCAD.Placement()
165
            >>> Draft.autogroup(obj)
166
    """
167

168
    def __init__(self):
169
        self.call = None
170
        self.commit_list = []
171
        self.doc = None
172
        App.activeDraftCommand = None
173
        self.view = None
174
        self.planetrack = None
175

176
    def IsActive(self):
177
        """Return True when this command should be available."""
178
        if App.ActiveDocument:
179
            return True
180
        else:
181
            return False
182

183
    def finish(self):
184
        """Terminate the active command by committing the list of commands.
185

186
        It also perform some other tasks like terminating
187
        the plane tracker and the snapper.
188
        """
189
        App.activeDraftCommand = None
190
        if self.planetrack:
191
            self.planetrack.finalize()
192
        if hasattr(Gui, "Snapper"):
193
            Gui.Snapper.off()
194
        if self.call:
195
            try:
196
                self.view.removeEventCallback("SoEvent", self.call)
197
            except RuntimeError:
198
                # the view has been deleted already
199
                pass
200
            self.call = None
201
        if self.commit_list:
202
            todo.ToDo.delayCommit(self.commit_list)
203
        self.commit_list = []
204

205
    def commit(self, name, func):
206
        """Store actions to be committed to the document.
207

208
        Parameters
209
        ----------
210
        name : str
211
            A string that indicates what is being committed.
212

213
        func : list of strings
214
            Each element of the list should be a Python command
215
            that will be executed.
216
        """
217
        self.commit_list.append((name, func))
218

219
## @}
220

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

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

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

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