Draft: gui_ and task_orthoarray cleanup

This commit is contained in:
vocx-fc
2020-03-07 23:55:47 -06:00
committed by Yorik van Havre
parent 8cbb599208
commit 48619ad6e9
2 changed files with 274 additions and 207 deletions

View File

@@ -31,13 +31,15 @@ from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
import FreeCADGui as Gui
import Draft
import Draft_rc
import Draft_rc # include resources, icons, ui files
from draftutils.messages import _msg, _log
from draftutils.translate import _tr
from draftguitools import gui_base
from drafttaskpanels import task_orthoarray
import draftutils.todo as todo
# The module is used to prevent complaints from code checkers (flake8)
True if Draft_rc.__name__ else False
bool(Draft_rc.__name__)
class GuiCommandOrthoArray(gui_base.GuiCommandBase):
@@ -45,7 +47,7 @@ class GuiCommandOrthoArray(gui_base.GuiCommandBase):
def __init__(self):
super().__init__()
self.command_name = "OrthoArray"
self.command_name = "Orthogonal array"
# self.location = None
self.mouse_event = None
self.view = None
@@ -56,14 +58,15 @@ class GuiCommandOrthoArray(gui_base.GuiCommandBase):
def GetResources(self):
"""Set icon, menu and tooltip."""
_msg = ("Creates copies of a selected object, "
_tip = ("Creates copies of a selected object, "
"and places the copies in an orthogonal pattern.\n"
"The properties of the array can be further modified after "
"the new object is created, including turning it into "
"a different type of array.")
d = {'Pixmap': 'Draft_Array',
'MenuText': QT_TRANSLATE_NOOP("Draft", "Array"),
'ToolTip': QT_TRANSLATE_NOOP("Draft", _msg)}
'ToolTip': QT_TRANSLATE_NOOP("Draft", _tip)}
return d
def Activated(self):
@@ -72,6 +75,10 @@ class GuiCommandOrthoArray(gui_base.GuiCommandBase):
We add callbacks that connect the 3D view with
the widgets of the task panel.
"""
_log("GuiCommand: {}".format(_tr(self.command_name)))
_msg("{}".format(16*"-"))
_msg("GuiCommand: {}".format(_tr(self.command_name)))
# self.location = coin.SoLocation2Event.getClassTypeId()
self.mouse_event = coin.SoMouseButtonEvent.getClassTypeId()
self.view = Draft.get3DView()

View File

@@ -1,8 +1,3 @@
"""Provide the task panel for the Draft OrthoArray tool."""
## @package task_orthoarray
# \ingroup DRAFT
# \brief Provide the task panel for the Draft OrthoArray tool.
# ***************************************************************************
# * (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * *
@@ -25,175 +20,226 @@
# * USA *
# * *
# ***************************************************************************
import FreeCAD as App
import FreeCADGui as Gui
# import Draft
import Draft_rc
import DraftVecUtils
"""Provides the task panel for the Draft OrthoArray tool."""
## @package task_orthoarray
# \ingroup DRAFT
# \brief Provide the task panel for the Draft OrthoArray tool.
import PySide.QtGui as QtGui
from PySide.QtCore import QT_TRANSLATE_NOOP
# import DraftTools
from draftutils.translate import translate
# from DraftGui import displayExternal
_Quantity = App.Units.Quantity
import FreeCAD as App
import FreeCADGui as Gui
import Draft_rc # include resources, icons, ui files
import DraftVecUtils
from draftutils.messages import _msg, _err, _log
from draftutils.translate import _tr
from FreeCAD import Units as U
def _Msg(text, end="\n"):
"""Print message with newline."""
App.Console.PrintMessage(text + end)
def _Wrn(text, end="\n"):
"""Print warning with newline."""
App.Console.PrintWarning(text + end)
def _tr(text):
"""Translate with the context set."""
return translate("Draft", text)
# So the resource file doesn't trigger errors from code checkers (flake8)
True if Draft_rc else False
# The module is used to prevent complaints from code checkers (flake8)
bool(Draft_rc.__name__)
class TaskPanelOrthoArray:
"""TaskPanel for the OrthoArray command.
"""TaskPanel code for the OrthoArray command.
The names of the widgets are defined in the `.ui` file.
In this class all those widgets are automatically created
under the name `self.form.<name>`
This `.ui` file `must` be loaded into an attribute
called `self.form` so that it is loaded into the task panel correctly.
In this class all widgets are automatically created
as `self.form.<widget_name>`.
The `.ui` file may use special FreeCAD widgets such as
`Gui::InputField` (based on `QLineEdit`) and
`Gui::QuantitySpinBox` (based on `QAbstractSpinBox`).
See the Doxygen documentation of the corresponding files in `src/Gui/`,
for example, `InputField.h` and `QuantitySpinBox.h`.
Attributes
----------
source_command: gui_base.GuiCommandBase
This attribute holds a reference to the calling class
of this task panel.
This parent class, which is derived from `gui_base.GuiCommandBase`,
is responsible for calling this task panel, for installing
certain callbacks, and for removing them.
It also delays the execution of the internal creation commands
by using the `draftutils.todo.ToDo` class.
See Also
--------
* https://forum.freecadweb.org/viewtopic.php?f=10&t=40007
* https://forum.freecadweb.org/viewtopic.php?t=5374#p43038
"""
def __init__(self):
self.name = "Orthogonal array"
_log(_tr("Task panel:") + "{}".format(_tr(self.name)))
# The .ui file must be loaded into an attribute
# called `self.form` so that it is displayed in the task panel.
ui_file = ":/ui/TaskPanel_OrthoArray.ui"
self.form = Gui.PySideUic.loadUi(ui_file)
self.name = self.form.windowTitle()
icon_name = "Draft_Array"
svg = ":/icons/" + icon_name
pix = QtGui.QPixmap(svg)
icon = QtGui.QIcon.fromTheme(icon_name, QtGui.QIcon(svg))
self.form.setWindowIcon(icon)
self.form.setWindowTitle(_tr(self.name))
self.form.label_icon.setPixmap(pix.scaled(32, 32))
start_x = _Quantity(100.0, App.Units.Length)
# -------------------------------------------------------------------
# Default values for the internal function,
# and for the task panel interface
start_x = U.Quantity(100.0, App.Units.Length)
start_y = start_x
start_z = start_x
start_zero = _Quantity(0.0, App.Units.Length)
length_unit = start_x.getUserPreferred()[2]
self.form.input_X_x.setProperty('rawValue', start_x.Value)
self.v_x = App.Vector(start_x.Value, 0, 0)
self.v_y = App.Vector(0, start_y.Value, 0)
self.v_z = App.Vector(0, 0, start_z.Value)
self.form.input_X_x.setProperty('rawValue', self.v_x.x)
self.form.input_X_x.setProperty('unit', length_unit)
self.form.input_X_y.setProperty('rawValue', start_zero.Value)
self.form.input_X_y.setProperty('rawValue', self.v_x.y)
self.form.input_X_y.setProperty('unit', length_unit)
self.form.input_X_z.setProperty('rawValue', start_zero.Value)
self.form.input_X_z.setProperty('rawValue', self.v_x.z)
self.form.input_X_z.setProperty('unit', length_unit)
self.form.input_Y_x.setProperty('rawValue', start_zero.Value)
self.form.input_Y_x.setProperty('rawValue', self.v_y.x)
self.form.input_Y_x.setProperty('unit', length_unit)
self.form.input_Y_y.setProperty('rawValue', start_y.Value)
self.form.input_Y_y.setProperty('rawValue', self.v_y.y)
self.form.input_Y_y.setProperty('unit', length_unit)
self.form.input_Y_z.setProperty('rawValue', start_zero.Value)
self.form.input_Y_z.setProperty('rawValue', self.v_y.z)
self.form.input_Y_z.setProperty('unit', length_unit)
self.form.input_Z_x.setProperty('rawValue', start_zero.Value)
self.form.input_Z_x.setProperty('rawValue', self.v_z.x)
self.form.input_Z_x.setProperty('unit', length_unit)
self.form.input_Z_y.setProperty('rawValue', start_zero.Value)
self.form.input_Z_y.setProperty('rawValue', self.v_z.y)
self.form.input_Z_y.setProperty('unit', length_unit)
self.form.input_Z_z.setProperty('rawValue', start_z.Value)
self.form.input_Z_z.setProperty('rawValue', self.v_z.z)
self.form.input_Z_z.setProperty('unit', length_unit)
self.v_X = App.Vector(100, 0, 0)
self.v_Y = App.Vector(0, 100, 0)
self.v_Z = App.Vector(0, 0, 100)
self.n_x = 2
self.n_y = 2
self.n_z = 1
# Old style for Qt4, avoid!
# QtCore.QObject.connect(self.form.button_reset,
# QtCore.SIGNAL("clicked()"),
# self.reset_point)
self.form.spinbox_n_X.setValue(self.n_x)
self.form.spinbox_n_Y.setValue(self.n_y)
self.form.spinbox_n_Z.setValue(self.n_z)
self.fuse = False
self.use_link = True
self.form.checkbox_fuse.setChecked(self.fuse)
self.form.checkbox_link.setChecked(self.use_link)
# -------------------------------------------------------------------
# Some objects need to be selected before we can execute the function.
self.selection = None
# This is used to test the input of the internal function.
# It should be changed to True before we can execute the function.
self.valid_input = False
self.set_widget_callbacks()
self.tr_true = QT_TRANSLATE_NOOP("Draft", "True")
self.tr_false = QT_TRANSLATE_NOOP("Draft", "False")
def set_widget_callbacks(self):
"""Set up the callbacks (slots) for the widget signals."""
# New style for Qt5
self.form.button_reset_X.clicked.connect(lambda: self.reset_v("X"))
self.form.button_reset_Y.clicked.connect(lambda: self.reset_v("Y"))
self.form.button_reset_Z.clicked.connect(lambda: self.reset_v("Z"))
self.n_X = 2
self.n_Y = 2
self.n_Z = 1
self.form.spinbox_n_X.setValue(self.n_X)
self.form.spinbox_n_Y.setValue(self.n_Y)
self.form.spinbox_n_Z.setValue(self.n_Z)
self.valid_input = False
# When the checkbox changes, change the fuse value
self.fuse = False
# When the checkbox changes, change the internal value
self.form.checkbox_fuse.stateChanged.connect(self.set_fuse)
self.use_link = False
self.form.checkbox_link.stateChanged.connect(self.set_link)
# Old style for Qt4, avoid!
# QtCore.QObject.connect(self.form.button_reset,
# QtCore.SIGNAL("clicked()"),
# self.reset_point)
def accept(self):
"""Execute when clicking the OK button."""
selection = Gui.Selection.getSelection()
n_X = self.form.spinbox_n_X.value()
n_Y = self.form.spinbox_n_Y.value()
n_Z = self.form.spinbox_n_Z.value()
self.valid_input = self.validate_input(selection,
n_X,
n_Y,
n_Z)
"""Execute when clicking the OK button or Enter key."""
self.selection = Gui.Selection.getSelection()
(self.v_x,
self.v_y,
self.v_z) = self.get_intervals()
(self.n_x,
self.n_y,
self.n_z) = self.get_numbers()
self.valid_input = self.validate_input(self.selection,
self.v_x, self.v_y, self.v_z,
self.n_x, self.n_y, self.n_z)
if self.valid_input:
self.create_object(selection)
self.print_messages(selection)
self.create_object()
self.print_messages()
self.finish()
def validate_input(self, selection, n_X, n_Y, n_Z):
"""Check that the input is valid."""
def validate_input(self, selection,
v_x, v_y, v_z,
n_x, n_y, n_z):
"""Check that the input is valid.
Some values may not need to be checked because
the interface may not allow to input wrong data.
"""
if not selection:
_Wrn(_tr("At least one element must be selected"))
_err(_tr("At least one element must be selected."))
return False
if n_X < 1 or n_Y < 1 or n_Z < 1:
_Wrn(_tr("Number of elements must be at least 1"))
if n_x < 1 or n_y < 1 or n_z < 1:
_err(_tr("Number of elements must be at least 1."))
return False
# Todo: each of the elements of the selection could be tested,
# not only the first one.
# TODO: this should handle multiple objects.
# Each of the elements of the selection should be tested.
obj = selection[0]
if obj.isDerivedFrom("App::FeaturePython"):
_Wrn(_tr("Selection is not suitable for array"))
_Wrn(_tr("Object:") + " {0} ({1})".format(obj.Label, obj.TypeId))
_err(_tr("Selection is not suitable for array."))
_err(_tr("Object:") + " {0} ({1})".format(obj.Label, obj.TypeId))
return False
return True
def create_object(self, selection):
"""Create the actual object."""
self.v_X, self.v_Y, self.v_Z = self.set_intervals()
self.n_X, self.n_Y, self.n_Z = self.set_numbers()
if len(selection) == 1:
sel_obj = selection[0]
else:
# This can be changed so a compound of multiple
# selected objects is produced
sel_obj = selection[0]
# The other arguments are not tested but they should be present.
if v_x and v_y and v_z:
pass
self.fuse = self.form.checkbox_fuse.isChecked()
self.use_link = self.form.checkbox_link.isChecked()
return True
def create_object(self):
"""Create the new object.
At this stage we already tested that the input is correct
so the necessary attributes are already set.
Then we proceed with the internal function to create the new object.
"""
if len(self.selection) == 1:
sel_obj = self.selection[0]
else:
# TODO: this should handle multiple objects.
# For example, it could take the shapes of all objects,
# make a compound and then use it as input for the array function.
sel_obj = self.selection[0]
# This creates the object immediately
# obj = Draft.makeArray(sel_obj,
# self.v_X, self.v_Y, self.v_Z,
# self.n_X, self.n_Y, self.n_Z)
# self.v_x, self.v_y, self.v_z,
# self.n_x, self.n_y, self.n_z,
# self.use_link)
# if obj:
# obj.Fuse = self.fuse
@@ -201,146 +247,160 @@ class TaskPanelOrthoArray:
# of this class, the GuiCommand.
# This is needed to schedule geometry manipulation
# that would crash Coin3D if done in the event callback.
_cmd = "obj = Draft.makeArray("
_cmd += "FreeCAD.ActiveDocument." + sel_obj.Name + ", "
_cmd += "arg1=" + DraftVecUtils.toString(self.v_X) + ", "
_cmd += "arg2=" + DraftVecUtils.toString(self.v_Y) + ", "
_cmd += "arg3=" + DraftVecUtils.toString(self.v_Z) + ", "
_cmd += "arg4=" + str(self.n_X) + ", "
_cmd += "arg5=" + str(self.n_Y) + ", "
_cmd += "arg6=" + str(self.n_Z) + ", "
_cmd = "draftobjects.orthoarray.make_ortho_array"
_cmd += "("
_cmd += "App.ActiveDocument." + sel_obj.Name + ", "
_cmd += "v_x=" + DraftVecUtils.toString(self.v_x) + ", "
_cmd += "v_y=" + DraftVecUtils.toString(self.v_y) + ", "
_cmd += "v_z=" + DraftVecUtils.toString(self.v_z) + ", "
_cmd += "n_x=" + str(self.n_x) + ", "
_cmd += "n_y=" + str(self.n_y) + ", "
_cmd += "n_z=" + str(self.n_z) + ", "
_cmd += "use_link=" + str(self.use_link)
_cmd += ")"
_cmd_list = ["FreeCADGui.addModule('Draft')",
_cmd,
_cmd_list = ["Gui.addModule('Draft')",
"Gui.addModule('draftobjects.orthoarray')",
"obj = " + _cmd,
"obj.Fuse = " + str(self.fuse),
"Draft.autogroup(obj)",
"FreeCAD.ActiveDocument.recompute()"]
self.source_command.commit("Ortho array", _cmd_list)
"App.ActiveDocument.recompute()"]
def set_numbers(self):
"""Assign the number of elements."""
self.n_X = self.form.spinbox_n_X.value()
self.n_Y = self.form.spinbox_n_Y.value()
self.n_Z = self.form.spinbox_n_Z.value()
return self.n_X, self.n_Y, self.n_Z
# We commit the command list through the parent command
self.source_command.commit(_tr(self.name), _cmd_list)
def set_intervals(self):
"""Assign the interval vectors."""
v_X_x_str = self.form.input_X_x.text()
v_X_y_str = self.form.input_X_y.text()
v_X_z_str = self.form.input_X_z.text()
self.v_X = App.Vector(_Quantity(v_X_x_str).Value,
_Quantity(v_X_y_str).Value,
_Quantity(v_X_z_str).Value)
def get_numbers(self):
"""Get the number of elements from the widgets."""
return (self.form.spinbox_n_X.value(),
self.form.spinbox_n_Y.value(),
self.form.spinbox_n_Z.value())
v_Y_x_str = self.form.input_Y_x.text()
v_Y_y_str = self.form.input_Y_y.text()
v_Y_z_str = self.form.input_Y_z.text()
self.v_Y = App.Vector(_Quantity(v_Y_x_str).Value,
_Quantity(v_Y_y_str).Value,
_Quantity(v_Y_z_str).Value)
def get_intervals(self):
"""Get the interval vectors from the widgets."""
v_x_x_str = self.form.input_X_x.text()
v_x_y_str = self.form.input_X_y.text()
v_x_z_str = self.form.input_X_z.text()
v_x = App.Vector(U.Quantity(v_x_x_str).Value,
U.Quantity(v_x_y_str).Value,
U.Quantity(v_x_z_str).Value)
v_Z_x_str = self.form.input_Z_x.text()
v_Z_y_str = self.form.input_Z_y.text()
v_Z_z_str = self.form.input_Z_z.text()
self.v_Z = App.Vector(_Quantity(v_Z_x_str).Value,
_Quantity(v_Z_y_str).Value,
_Quantity(v_Z_z_str).Value)
return self.v_X, self.v_Y, self.v_Z
v_y_x_str = self.form.input_Y_x.text()
v_y_y_str = self.form.input_Y_y.text()
v_y_z_str = self.form.input_Y_z.text()
v_y = App.Vector(U.Quantity(v_y_x_str).Value,
U.Quantity(v_y_y_str).Value,
U.Quantity(v_y_z_str).Value)
v_z_x_str = self.form.input_Z_x.text()
v_z_y_str = self.form.input_Z_y.text()
v_z_z_str = self.form.input_Z_z.text()
v_z = App.Vector(U.Quantity(v_z_x_str).Value,
U.Quantity(v_z_y_str).Value,
U.Quantity(v_z_z_str).Value)
return v_x, v_y, v_z
def reset_v(self, interval):
"""Reset the interval to zero distance."""
"""Reset the interval to zero distance.
Parameters
----------
interval: str
Either "X", "Y", "Z", to reset the interval vector
for that direction.
"""
if interval == "X":
self.form.input_X_x.setProperty('rawValue', 100)
self.form.input_X_y.setProperty('rawValue', 0)
self.form.input_X_z.setProperty('rawValue', 0)
_Msg(_tr("Interval X reset:")
+ " ({0}, {1}, {2})".format(self.v_X.x,
self.v_X.y,
self.v_X.z))
self.v_x, self.v_y, self.v_z = self.get_intervals()
_msg(_tr("Interval X reset:")
+ " ({0}, {1}, {2})".format(self.v_x.x,
self.v_x.y,
self.v_x.z))
elif interval == "Y":
self.form.input_Y_x.setProperty('rawValue', 0)
self.form.input_Y_y.setProperty('rawValue', 100)
self.form.input_Y_z.setProperty('rawValue', 0)
_Msg(_tr("Interval Y reset:")
+ " ({0}, {1}, {2})".format(self.v_Y.x,
self.v_Y.y,
self.v_Y.z))
self.v_x, self.v_y, self.v_z = self.get_intervals()
_msg(_tr("Interval Y reset:")
+ " ({0}, {1}, {2})".format(self.v_y.x,
self.v_y.y,
self.v_y.z))
elif interval == "Z":
self.form.input_Z_x.setProperty('rawValue', 0)
self.form.input_Z_y.setProperty('rawValue', 0)
self.form.input_Z_z.setProperty('rawValue', 100)
_Msg(_tr("Interval Z reset:")
+ " ({0}, {1}, {2})".format(self.v_Z.x,
self.v_Z.y,
self.v_Z.z))
self.v_x, self.v_y, self.v_z = self.get_intervals()
_msg(_tr("Interval Z reset:")
+ " ({0}, {1}, {2})".format(self.v_z.x,
self.v_z.y,
self.v_z.z))
self.n_X, self.n_Y, self.n_Z = self.set_intervals()
def print_fuse_state(self):
"""Print the state translated."""
if self.fuse:
translated_state = QT_TRANSLATE_NOOP("Draft", "True")
def print_fuse_state(self, fuse):
"""Print the fuse state translated."""
if fuse:
state = self.tr_true
else:
translated_state = QT_TRANSLATE_NOOP("Draft", "False")
_Msg(_tr("Fuse:") + " {}".format(translated_state))
state = self.tr_false
_msg(_tr("Fuse:") + " {}".format(state))
def set_fuse(self):
"""Run callback when the fuse checkbox changes."""
"""Execute as a callback when the fuse checkbox changes."""
self.fuse = self.form.checkbox_fuse.isChecked()
self.print_fuse_state()
self.print_fuse_state(self.fuse)
def print_link_state(self):
"""Print the state translated."""
if self.use_link:
translated_state = QT_TRANSLATE_NOOP("Draft", "True")
def print_link_state(self, use_link):
"""Print the link state translated."""
if use_link:
state = self.tr_true
else:
translated_state = QT_TRANSLATE_NOOP("Draft", "False")
_Msg(_tr("Use Link object:") + " {}".format(translated_state))
state = self.tr_false
_msg(_tr("Create Link array:") + " {}".format(state))
def set_link(self):
"""Run callback when the link checkbox changes."""
"""Execute as a callback when the link checkbox changes."""
self.use_link = self.form.checkbox_link.isChecked()
self.print_link_state()
self.print_link_state(self.use_link)
def print_messages(self, selection):
def print_messages(self):
"""Print messages about the operation."""
if len(selection) == 1:
sel_obj = selection[0]
if len(self.selection) == 1:
sel_obj = self.selection[0]
else:
# This can be changed so a compound of multiple
# selected objects is produced
sel_obj = selection[0]
_Msg("{}".format(16*"-"))
_Msg("{}".format(self.name))
_Msg(_tr("Object:") + " {}".format(sel_obj.Label))
_Msg(_tr("Number of X elements:") + " {}".format(self.n_X))
_Msg(_tr("Interval X:")
+ " ({0}, {1}, {2})".format(self.v_X.x,
self.v_X.y,
self.v_X.z))
_Msg(_tr("Number of Y elements:") + " {}".format(self.n_Y))
_Msg(_tr("Interval Y:")
+ " ({0}, {1}, {2})".format(self.v_Y.x,
self.v_Y.y,
self.v_Y.z))
_Msg(_tr("Number of Z elements:") + " {}".format(self.n_Z))
_Msg(_tr("Interval Z:")
+ " ({0}, {1}, {2})".format(self.v_Z.x,
self.v_Z.y,
self.v_Z.z))
self.print_fuse_state()
self.print_link_state()
# TODO: this should handle multiple objects.
# For example, it could take the shapes of all objects,
# make a compound and then use it as input for the array function.
sel_obj = self.selection[0]
_msg(_tr("Object:") + " {}".format(sel_obj.Label))
_msg(_tr("Number of X elements:") + " {}".format(self.n_x))
_msg(_tr("Interval X:")
+ " ({0}, {1}, {2})".format(self.v_x.x,
self.v_x.y,
self.v_x.z))
_msg(_tr("Number of Y elements:") + " {}".format(self.n_y))
_msg(_tr("Interval Y:")
+ " ({0}, {1}, {2})".format(self.v_y.x,
self.v_y.y,
self.v_y.z))
_msg(_tr("Number of Z elements:") + " {}".format(self.n_z))
_msg(_tr("Interval Z:")
+ " ({0}, {1}, {2})".format(self.v_z.x,
self.v_z.y,
self.v_z.z))
self.print_fuse_state(self.fuse)
self.print_link_state(self.use_link)
def reject(self):
"""Run when clicking the Cancel button."""
_Msg(_tr("Aborted:") + " {}".format(self.name))
"""Execute when clicking the Cancel button or pressing Escape."""
_msg(_tr("Aborted:") + " {}".format(_tr(self.name)))
self.finish()
def finish(self):
"""Run at the end after OK or Cancel."""
"""Finish the command, after accept or reject.
It finally calls the parent class to execute
the delayed functions, and perform cleanup.
"""
# App.ActiveDocument.commitTransaction()
Gui.ActiveDocument.resetEdit()
# Runs the parent command to complete the call