FreeCAD

Форк
0
/
gui_selectplane.py 
291 строка · 11.2 Кб
1
# ***************************************************************************
2
# *   Copyright (c) 2019 Yorik van Havre <yorik@uncreated.net>              *
3
# *   Copyright (c) 2023 FreeCAD Project Association                        *
4
# *                                                                         *
5
# *   This program is free software; you can redistribute it and/or modify  *
6
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
7
# *   as published by the Free Software Foundation; either version 2 of     *
8
# *   the License, or (at your option) any later version.                   *
9
# *   for detail see the LICENCE text file.                                 *
10
# *                                                                         *
11
# *   This program is distributed in the hope that it will be useful,       *
12
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
# *   GNU Library General Public License for more details.                  *
15
# *                                                                         *
16
# *   You should have received a copy of the GNU Library General Public     *
17
# *   License along with this program; if not, write to the Free Software   *
18
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
19
# *   USA                                                                   *
20
# *                                                                         *
21
# ***************************************************************************
22
"""Provides GUI tools to set up the working plane and its grid."""
23
## @package gui_selectplane
24
# \ingroup draftguitools
25
# \brief Provides GUI tools to set up the working plane and its grid.
26

27
## \addtogroup draftguitools
28
# @{
29
from PySide import QtGui
30
from PySide.QtCore import QT_TRANSLATE_NOOP
31

32
import FreeCAD as App
33
import FreeCADGui as Gui
34
import Part
35
import WorkingPlane
36

37
from FreeCAD import Units
38
from drafttaskpanels import task_selectplane
39
from draftutils import params
40
from draftutils import utils
41
from draftutils.messages import _msg
42
from draftutils.todo import todo
43
from draftutils.translate import translate
44

45
__title__ = "FreeCAD Draft Workbench GUI Tools - Working plane-related tools"
46
__author__ = ("Yorik van Havre, Werner Mayer, Martin Burbaum, Ken Cline, "
47
              "Dmitry Chigrin")
48
__url__ = "https://www.freecad.org"
49

50

51
class Draft_SelectPlane:
52
    """The Draft_SelectPlane FreeCAD command definition."""
53

54
    def GetResources(self):
55
        """Set icon, menu and tooltip."""
56
        return {"Pixmap": "Draft_SelectPlane",
57
                "Accel": "W, P",
58
                "MenuText": QT_TRANSLATE_NOOP("Draft_SelectPlane", "Select plane"),
59
                "ToolTip": QT_TRANSLATE_NOOP("Draft_SelectPlane", "Select 3 vertices, one or more shapes or an object to define a working plane.")}
60

61
    def IsActive(self):
62
        """Return True when this command should be available."""
63
        if Gui.ActiveDocument:
64
            return True
65
        else:
66
            return False
67

68
    def Activated(self):
69
        """Execute when the command is called."""
70
        # Finish active Draft command if any
71
        if App.activeDraftCommand is not None:
72
            App.activeDraftCommand.finish()
73

74
        App.activeDraftCommand = self
75
        self.call = None
76

77
        # Set variables
78
        self.wp = WorkingPlane.get_working_plane()
79
        self.view = self.wp._view
80
        self.grid = None
81
        if hasattr(Gui, "Snapper"):
82
            Gui.Snapper.setTrackers()
83
            self.grid = Gui.Snapper.grid
84
        self.offset = 0
85
        self.center = params.get_param("CenterPlaneOnView")
86

87
        # Create task panel
88
        self.taskd = task_selectplane.SelectPlaneTaskPanel()
89
        self.taskd.reject = self.reject
90
        form = self.taskd.form
91

92
        # Fill values
93
        form.fieldOffset.setText(Units.Quantity(self.offset, Units.Length).UserString)
94
        form.checkCenter.setChecked(self.center)
95
        try:
96
            q = Units.Quantity(params.get_param("gridSpacing"))
97
        except ValueError:
98
            q = Units.Quantity("1 mm")
99
        form.fieldGridSpacing.setText(q.UserString)
100
        form.fieldGridMainLine.setValue(params.get_param("gridEvery"))
101
        form.fieldGridExtension.setValue(params.get_param("gridSize"))
102
        form.fieldSnapRadius.setValue(params.get_param("snapRange"))
103

104
        # Set icons
105
        form.setWindowIcon(QtGui.QIcon(":/icons/Draft_SelectPlane.svg"))
106
        form.buttonTop.setIcon(QtGui.QIcon(":/icons/view-top.svg"))
107
        form.buttonFront.setIcon(QtGui.QIcon(":/icons/view-front.svg"))
108
        form.buttonSide.setIcon(QtGui.QIcon(":/icons/view-right.svg"))
109
        form.buttonAlign.setIcon(QtGui.QIcon(":/icons/view-isometric.svg"))
110
        form.buttonAuto.setIcon(QtGui.QIcon(":/icons/view-axonometric.svg"))
111
        form.buttonMove.setIcon(QtGui.QIcon(":/icons/Draft_Move.svg"))
112
        form.buttonCenter.setIcon(QtGui.QIcon(":/icons/view-fullscreen.svg"))
113
        form.buttonPrevious.setIcon(QtGui.QIcon(":/icons/sel-back.svg"))
114
        form.buttonNext.setIcon(QtGui.QIcon(":/icons/sel-forward.svg"))
115

116
        # Grid color
117
        color = params.get_param("gridColor")
118
        form.buttonColor.setProperty("color", QtGui.QColor(utils.rgba_to_argb(color)))
119

120
        # Connect slots
121
        form.buttonTop.clicked.connect(self.on_click_top)
122
        form.buttonFront.clicked.connect(self.on_click_front)
123
        form.buttonSide.clicked.connect(self.on_click_side)
124
        form.buttonAlign.clicked.connect(self.on_click_align)
125
        form.buttonAuto.clicked.connect(self.on_click_auto)
126
        form.buttonMove.clicked.connect(self.on_click_move)
127
        form.buttonCenter.clicked.connect(self.on_click_center)
128
        form.buttonPrevious.clicked.connect(self.on_click_previous)
129
        form.buttonNext.clicked.connect(self.on_click_next)
130
        form.fieldOffset.textEdited.connect(self.on_set_offset)
131
        form.checkCenter.stateChanged.connect(self.on_set_center)
132
        form.fieldGridSpacing.textEdited.connect(self.on_set_grid_size)
133
        form.fieldGridMainLine.valueChanged.connect(self.on_set_main_line)
134
        form.fieldGridExtension.valueChanged.connect(self.on_set_extension)
135
        form.fieldSnapRadius.valueChanged.connect(self.on_set_snap_radius)
136
        form.buttonColor.changed.connect(self.on_color_changed)
137

138
        # Enable/disable buttons.
139
        form.buttonPrevious.setEnabled(self.wp._has_previous())
140
        form.buttonNext.setEnabled(self.wp._has_next())
141

142
        # Try to find a WP from the current selection
143
        if Gui.Selection.hasSelection():
144
            if self.wp.align_to_selection(self.offset):
145
                Gui.Selection.clearSelection()
146
            self.finish()
147
            return
148

149
        # Execute the actual task panel delayed to catch possible active Draft command
150
        todo.delay(Gui.Control.showDialog, self.taskd)
151
        todo.delay(form.setFocus, None)
152
        _msg(translate(
153
                "draft",
154
                "Select 3 vertices, one or more shapes or an object to define a working plane"))
155
        self.call = self.view.addEventCallback("SoEvent", self.action)
156

157
    def finish(self):
158
        """Execute when the command is terminated."""
159
        App.activeDraftCommand = None
160
        Gui.Control.closeDialog()
161
        if hasattr(Gui, "Snapper"):
162
            Gui.Snapper.off()
163
        # Terminate coin callbacks
164
        if self.call:
165
            try:
166
                self.view.removeEventCallback("SoEvent", self.call)
167
            except RuntimeError:
168
                # The view has been deleted already
169
                pass
170
            self.call = None
171

172
    def reject(self):
173
        """Execute when clicking the Cancel button."""
174
        self.finish()
175

176
    def action(self, arg):
177
        """Set the callbacks for the view."""
178
        if arg["Type"] == "SoKeyboardEvent" and arg["Key"] == "ESCAPE":
179
            self.reject()
180
        if arg["Type"] == "SoMouseButtonEvent" \
181
                and (arg["State"] == "DOWN") \
182
                and (arg["Button"] == "BUTTON1"):
183
            self.check_selection()
184

185
    def check_selection(self):
186
        """Check the selection, if it is usable, finish the command."""
187
        if self.wp.align_to_selection(self.offset):
188
            Gui.Selection.clearSelection()
189
            self.finish()
190

191
    def on_click_top(self):
192
        self.wp.set_to_top(self.offset, self.center)
193
        self.finish()
194

195
    def on_click_front(self):
196
        self.wp.set_to_front(self.offset, self.center)
197
        self.finish()
198

199
    def on_click_side(self):
200
        self.wp.set_to_side(self.offset, self.center)
201
        self.finish()
202

203
    def on_click_align(self):
204
        self.wp.set_to_view(self.offset, self.center)
205
        self.finish()
206

207
    def on_click_auto(self):
208
        self.wp.set_to_auto()
209
        self.finish()
210

211
    def on_click_move(self):
212
        sels = Gui.Selection.getSelectionEx("", 0)
213
        if len(sels) == 1 \
214
                and len(sels[0].SubObjects) == 1 \
215
                and sels[0].SubObjects[0].ShapeType == "Vertex":
216
            vert = Part.getShape(sels[0].Object,
217
                                 sels[0].SubElementNames[0],
218
                                 needSubElement=True,
219
                                 retType=0)
220
            self.wp.set_to_position(vert.Point)
221
            Gui.Selection.clearSelection()
222
            self.finish()
223
        else:
224
            # Move the WP to the center of the current view
225
            self.wp.center_on_view()
226
            self.finish()
227

228
    def on_click_center(self):
229
        self.wp.align_view()
230
        self.finish()
231

232
    def on_click_previous(self):
233
        self.wp._previous()
234
        self.finish()
235

236
    def on_click_next(self):
237
        self.wp._next()
238
        self.finish()
239

240
    def on_set_offset(self, text):
241
        try:
242
            q = Units.Quantity(text)
243
        except Exception:
244
            pass
245
        else:
246
            self.offset = q.Value
247

248
    def on_set_center(self, val):
249
        self.center = bool(val)
250
        params.set_param("CenterPlaneOnView", self.center)
251

252
    def on_set_grid_size(self, text):
253
        try:
254
            q = Units.Quantity(text)
255
        except Exception:
256
            pass
257
        else:
258
            params.set_param("gridSpacing", q.UserString)
259
            # ParamObserver handles grid changes. See params.py.
260
            if self.grid is not None:
261
                self.grid.show_during_command = True
262
                self.grid.on()
263

264
    def on_set_main_line(self, i):
265
        if i > 1:
266
            params.set_param("gridEvery", i)
267
            # ParamObserver handles grid changes. See params.py.
268
            if self.grid is not None:
269
                self.grid.show_during_command = True
270
                self.grid.on()
271

272
    def on_set_extension(self, i):
273
        if i > 1:
274
            params.set_param("gridSize", i)
275
            # ParamObserver handles grid changes. See params.py.
276
            if self.grid is not None:
277
                self.grid.show_during_command = True
278
                self.grid.on()
279

280
    def on_set_snap_radius(self, i):
281
        params.set_param("snapRange", i)
282
        if hasattr(Gui, "Snapper"):
283
            Gui.Snapper.showradius()
284

285
    def on_color_changed(self):
286
        color = utils.argb_to_rgba(self.taskd.form.buttonColor.property("color").rgba())
287
        params.set_param("gridColor", color)
288

289
Gui.addCommand('Draft_SelectPlane', Draft_SelectPlane())
290

291
## @}
292

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

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

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

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