def __init__(self): self.form = QtGui.QWidget() self.form.setObjectName("ShapeStringTaskPanel") self.form.setWindowTitle(translate("draft", "ShapeString")) layout = QtGui.QVBoxLayout(self.form) uiFile = QtCore.QFile(":/ui/TaskShapeString.ui") loader = Gui.UiLoader() self.task = loader.load(uiFile) layout.addWidget(self.task) qStart = U.Quantity(0.0, U.Length) self.task.sbX.setProperty('rawValue', qStart.Value) self.task.sbX.setProperty('unit', qStart.getUserPreferred()[2]) self.task.sbY.setProperty('rawValue', qStart.Value) self.task.sbY.setProperty('unit', qStart.getUserPreferred()[2]) self.task.sbZ.setProperty('rawValue', qStart.Value) self.task.sbZ.setProperty('unit', qStart.getUserPreferred()[2]) self.task.sbHeight.setProperty('rawValue', 10.0) self.task.sbHeight.setProperty('unit', qStart.getUserPreferred()[2]) self.stringText = translate("draft", "Default") self.task.leString.setText(self.stringText) self.platWinDialog("Overwrite") self.task.fcFontFile.setFileName(Draft.getParam("FontFile", "")) self.fileSpec = Draft.getParam("FontFile", "") self.point = App.Vector(0.0, 0.0, 0.0) self.pointPicked = False # Default for the "DontUseNativeFontDialog" preference: self.font_dialog_pref = False QtCore.QObject.connect( self.task.fcFontFile, QtCore.SIGNAL("fileNameSelected(const QString&)"), self.fileSelect) QtCore.QObject.connect(self.task.pbReset, QtCore.SIGNAL("clicked()"), self.resetPoint) self.point = None self.view = Draft.get3DView() self.call = self.view.addEventCallback("SoEvent", self.action) _msg(translate("draft", "Pick ShapeString location point:"))
def Activated(self, mode="None"): """Execute when the command is called. Parameters ---------- action: str Indicates the type of mode to switch to. It can be `'construction'` or `'continue'`. """ super(BaseMode, self).Activated() if hasattr(Gui, "draftToolBar"): _ui = Gui.draftToolBar else: _msg(_tr("No active Draft Toolbar.")) return if _ui is not None: if mode == "construction" and hasattr(_ui, "constrButton"): _ui.constrButton.toggle() elif mode == "continue": _ui.toggleContinue()
def test_stretch(self): """Stretch a line. NOT IMPLEMENTED.""" operation = "Draft Stretch" _msg(" Test '{}'".format(operation)) _msg(" This test requires an object and a selection") a = Vector(0, 0, 0) b = Vector(1, 1, 0) _msg(" Line") _msg(" a={0}, b={1}".format(a, b)) line = Draft.makeLine(a, b) direction = Vector(4, 1, 0) Draft.stretch = aux._fake_function obj = Draft.stretch(line, direction) self.assertTrue(obj, "'{}' failed".format(operation))
def test_bezcurve(self): """Create a bezier curve of six points, degree five.""" operation = "Draft BezCurve" _msg(" Test '{}'".format(operation)) a = Vector(0, 0, 0) b = Vector(2, 2, 0) c = Vector(5, 3, 0) d = Vector(9, 0, 0) e = Vector(12, 5, 0) f = Vector(12, 8, 0) _msg(" a={0}, b={1}".format(a, b)) _msg(" c={0}, d={1}".format(c, d)) _msg(" e={0}, f={1}".format(e, f)) obj = Draft.makeBezCurve([a, b, c, d, e, f]) self.assertTrue(obj, "'{}' failed".format(operation))
def test_scale_part_feature_lines(self): """Create and scale a part feature (lines).""" operation = "Draft Scale part feature (lines)" _msg(" Test '{}'".format(operation)) base = Vector(3.5, 2.5, 0.0) cen = Vector(2.0, 1.0, 0.0) # center for scaling sca = Vector(2.0, 3.0, 1.0) pts = [ Vector(0.0, 0.0, 0.0), Vector(4.0, 0.0, 0.0), Vector(4.0, 3.0, 0.0), Vector(0.0, 3.0, 0.0) ] shp = Part.Shape([ Part.LineSegment(pts[0], pts[1]), Part.LineSegment(pts[1], pts[2]), Part.LineSegment(pts[2], pts[3]), Part.LineSegment(pts[3], pts[0]) ]) obj = App.ActiveDocument.addObject("Part::Feature") obj.Shape = shp obj.Placement.Base = base App.ActiveDocument.recompute() Draft.scale([obj], sca, cen, False) App.ActiveDocument.recompute() newPts = [ Vector(5.0, 5.5, 0.0), Vector(13.0, 5.5, 0.0), Vector(13.0, 14.5, 0.0), Vector(5.0, 14.5, 0.0) ] vrts = obj.Shape.Vertexes for i in range(4): self.assertTrue(vrts[i].Point.isEqual(newPts[i], 1e-8), "'{}' failed".format(operation))
def find_doc(doc=None): """Return the active document or find a document by name. Parameters ---------- doc: App::Document or str, optional The document that will be searched in the session. It defaults to `None`, in which case it tries to find the active document. If `doc` is a string, it will try to get the document by `Name`. Returns ------- bool, App::Document A tuple containing the information on whether the search was successful. In this case, the boolean is `True`, and the second value is the document instance. False, None If there is no active document, or the string in `doc` doesn't correspond to an open document in the session. """ FOUND = True if not doc: doc = App.activeDocument() if not doc: return not FOUND, None if isinstance(doc, str): try: doc = App.getDocument(doc) except NameError: _msg("document: {}".format(doc)) _err(_tr("Wrong input: unknown document.")) return not FOUND, None return FOUND, doc
def Activated(self): """Execute when the command is called.""" if self.cont: self.finish() elif self.selected_app_measure(): super(Dimension, self).Activated(name="Dimension") self.dimtrack = trackers.dimTracker() self.arctrack = trackers.arcTracker() self.create_with_app_measure() self.finish() else: super(Dimension, self).Activated(name="Dimension") if self.ui: self.ui.pointUi(title=translate("draft", self.featureName), icon="Draft_Dimension") self.ui.continueCmd.show() self.ui.selectButton.show() self.altdown = False self.call = self.view.addEventCallback("SoEvent", self.action) self.dimtrack = trackers.dimTracker() self.arctrack = trackers.arcTracker() self.link = None self.edges = [] self.angles = [] self.angledata = None self.indices = [] self.center = None self.arcmode = False self.point1 = None self.point2 = None self.proj_point1 = None self.proj_point2 = None self.force = None self.info = None self.selectmode = False self.set_selection() _msg(translate("draft", "Pick first point")) Gui.draftToolBar.show()
def handle_mouse_click_event(self, arg): """Handle the mouse when the first button is clicked.""" if not self.ghosts: self.set_ghosts() if not self.point: return self.ui.redraw() if self.node == []: self.node.append(self.point) self.ui.isRelative.show() for ghost in self.ghosts: ghost.on() _msg(translate("draft", "Pick end point")) if self.planetrack: self.planetrack.set(self.point) else: last = self.node[0] self.vector = self.point.sub(last) self.move() if gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT): self.extendedCopy = True else: self.finish(cont=True)
def Activated(self, name=translate("draft", "Line")): """Execute when the command is called.""" super().Activated(name) if not self.doc: return self.obj = None # stores the temp shape self.oldWP = None # stores the WP if we modify it if self.isWire: self.ui.wireUi(name) else: self.ui.lineUi(name) self.ui.setTitle(translate("draft", "Line")) if sys.version_info.major < 3: if isinstance(self.featureName, unicode): self.featureName = self.featureName.encode("utf8") self.obj = self.doc.addObject("Part::Feature", self.featureName) gui_utils.format_object(self.obj) self.call = self.view.addEventCallback("SoEvent", self.action) _msg(translate("draft", "Pick first point"))
def test_label(self): """Create a label.""" operation = "Draft Label" _msg(" Test '{}'".format(operation)) _msg(" Occasionally crashes") target_point = Vector(0, 0, 0) distance = -25 placement = App.Placement(Vector(50, 50, 0), App.Rotation()) _msg(" target_point={0}, " "distance={1}".format(target_point, distance)) _msg(" placement={}".format(placement)) obj = Draft.makeLabel(targetpoint=target_point, distance=distance, placement=placement) App.ActiveDocument.recompute() self.assertTrue(obj, "'{}' failed".format(operation))
def buildRelProductColors(ifcfile, prodrepr): """Build the colors relation table from a product. Returns ------- dict A dictionary with `{id: (r,g,b), ...}` values. """ if DEBUG_prod_repr: _msg(32 * "-") _msg("Product-color table") colors = dict() i = 0 for p in prodrepr.keys(): # Representation item, see `IfcRepresentationItem` documentation. # All kinds of geometric or topological representation items # `IfcExtrudedAreaSolid`, `IfcMappedItem`, `IfcFacetedBrep`, # `IfcBooleanResult`, `IfcBooleanClippingResult`, etc. _body = ifcfile[p].Representation.Representations[0] repr_item = _body.Items[0] if DEBUG_prod_colors: _msg("{}: {}, {}, '{}', rep_item {}".format(i, ifcfile[p].id(), ifcfile[p].is_a(), ifcfile[p].Name, repr_item)) # Get the geometric representations which have a presentation style. # All representation items have the inverse attribute `StyledByItem` # for this. # There will be geometric representations which do not have # a presentation style so `StyledByItem` will be empty. if repr_item.StyledByItem: if DEBUG_prod_colors: _msg(" StyledByItem -> {}".format(repr_item.StyledByItem)) # it has to be a `IfcStyledItem`, no check needed styled_item = repr_item.StyledByItem[0] # Write into colors table if a `IfcStyledItem` exists # for this product, write `None` if something goes wrong # or if the ifc file has errors and thus no valid color # is returned colors[p] = getColorFromStyledItem(styled_item) i += 1 return colors
def numericRadius(self, rad): """Validate the radius entry field in the user interface. This function is called by the toolbar or taskpanel interface when a valid radius has been entered in the input field. """ if self.step == 1: self.ui.labelRadius.setText(translate("draft", "Rotation")) _tip = ("The amount of rotation you wish to perform.\n" "The final angle will be the base angle " "plus this amount.") self.ui.radiusValue.setToolTip(translate("draft", _tip)) self.ui.radiusValue.setText(U.Quantity(0, U.Angle).UserString) self.firstangle = math.radians(rad) self.arctrack.setStartAngle(self.firstangle) self.arctrack.on() for ghost in self.ghosts: ghost.on() self.step = 2 _msg(translate("draft", "Pick rotation angle")) else: self.angle = math.radians(rad) self.rotate(self.ui.isCopy.isChecked()) self.finish(cont=True)
def print_messages(self): """Print messages about the operation.""" 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] _msg(_tr("Object:") + " {}".format(sel_obj.Label)) _msg(_tr("Number of elements:") + " {}".format(self.number)) _msg(_tr("Polar angle:") + " {}".format(self.angle)) _msg( _tr("Center of rotation:") + " ({0}, {1}, {2})".format( self.center.x, self.center.y, self.center.z)) self.print_fuse_state(self.fuse) self.print_link_state(self.use_link)
def Activated(self, action="None"): """Execute when the command is called. Parameters ---------- action: str Indicates the type of action to perform with the line object. It can be `'finish'`, `'close'`, or `'undo'`. """ if hasattr(App, "activeDraftCommand"): _command = App.activeDraftCommand else: _msg(_tr("No active command.")) return if (_command is not None and _command.featureName in ("Line", "Polyline", "BSpline", "BezCurve", "CubicBezCurve")): if action == "finish": _command.finish(False) elif action == "close": _command.finish(True) elif action == "undo": _command.undolast()
def Activated(self): """Execute when the command is called. 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() self.callback_move = \ self.view.addEventCallbackPivy(self.location, self.move) self.callback_click = \ self.view.addEventCallbackPivy(self.mouse_event, self.click) self.ui = task_polararray.TaskPanelPolarArray() # The calling class (this one) is saved in the object # of the interface, to be able to call a function from within it. self.ui.source_command = self # Gui.Control.showDialog(self.ui) todo.ToDo.delay(Gui.Control.showDialog, self.ui)
def print_header(name, description, debug=True): """Print a line to the console when something is called, and log it. Parameters ---------- name: str The name of the function or class that is being called. This `name` will be logged in the log file, so if there are problems the log file can be investigated for clues. description: str Arbitrary text that will be printed to the console when the function or class is called. debug: bool, optional It defaults to `True`. If it is `False` the `description` will not be printed to the console. On the other hand the `name` will always be logged. """ _log(name) if debug: _msg(16 * "-") _msg(description)
def _import_test(module): """Try importing a module.""" _msg(" Try importing '{}'".format(module)) try: imported = __import__("{}".format(module)) except ImportError as exc: imported = False _msg(" {}".format(exc)) _msg(traceback.format_exc()) return imported
def test_bspline(self): """Create a BSpline of three points.""" operation = "Draft BSpline" _msg(" Test '{}'".format(operation)) a = Vector(0, 0, 0) b = Vector(2, 0, 0) c = Vector(2, 2, 0) _msg(" a={0}, b={1}".format(a, b)) _msg(" c={}".format(c)) obj = Draft.makeBSpline([a, b, c]) self.assertTrue(obj, "'{}' failed".format(operation))
def test_polyline(self): """Create a polyline.""" operation = "Draft Wire" _msg(" Test '{}'".format(operation)) a = Vector(0, 0, 0) b = Vector(2, 0, 0) c = Vector(2, 2, 0) _msg(" a={0}, b={1}".format(a, b)) _msg(" c={}".format(c)) obj = Draft.makeWire([a, b, c]) self.assertTrue(obj, "'{}' failed".format(operation))
def test_cubicbezcurve(self): """Create a cubic bezier curve of four points.""" operation = "Draft CubBezCurve" _msg(" Test '{}'".format(operation)) a = Vector(0, 0, 0) b = Vector(2, 2, 0) c = Vector(5, 3, 0) d = Vector(9, 0, 0) _msg(" a={0}, b={1}".format(a, b)) _msg(" c={0}, d={1}".format(c, d)) obj = Draft.makeBezCurve([a, b, c, d], degree=3) self.assertTrue(obj, "'{}' failed".format(operation))
def test_arc_3points(self): """Create a circular arc from three points.""" operation = "Draft Arc 3Points" _msg(" Test '{}'".format(operation)) a = Vector(5, 0, 0) b = Vector(4, 3, 0) c = Vector(0, 5, 0) _msg(" a={0}, b={1}".format(a, b)) _msg(" c={}".format(c)) obj = Draft.make_arc_3points([a, b, c]) self.assertTrue(obj, "'{}' failed".format(operation))
def test_shapestring(self): """Create a ShapeString. NOT IMPLEMENTED CURRENTLY.""" operation = "Draft ShapeString" _msg(" Test '{}'".format(operation)) _msg(" In order to test this, a font file is needed.") text = "Testing Shapestring " # TODO: find a reliable way to always get a font file here font = None _msg(" text='{0}', font='{1}'".format(text, font)) Draft.makeShapeString = aux._fake_function obj = Draft.makeShapeString("Text", font) # Draft.makeShapeString("Text", FontFile="") self.assertTrue(obj, "'{}' failed".format(operation))
def test_arc(self): """Create a circular arc.""" operation = "Draft Arc" _msg(" Test '{}'".format(operation)) radius = 2 start_angle = 0 end_angle = 90 _msg(" radius={}".format(radius)) _msg(" startangle={0}, endangle={1}".format(start_angle, end_angle)) obj = Draft.makeCircle(radius, startangle=start_angle, endangle=end_angle) self.assertTrue(obj, "'{}' failed".format(operation))
def test_export_svg(self): """Create some figures and export them to an SVG file.""" operation = "importSVG.export" _msg(" Test '{}'".format(operation)) file = 'Mod/Draft/drafttest/out_test.svg' out_file = os.path.join(App.getResourceDir(), file) _msg(" file={}".format(out_file)) _msg(" exists={}".format(os.path.exists(out_file))) Draft.export_svg = aux.fake_function obj = Draft.export_svg(out_file) self.assertTrue(obj, "'{}' failed".format(operation))
def test_dimension_linear_obj(self): """Create a linear dimension linked to an object.""" operation = "Draft Dimension" _msg(" Test '{}'".format(operation)) _msg(" Occasionally crashes") a = Vector(0, 0, 0) b = Vector(9, 0, 0) _msg(" a={0}, b={1}".format(a, b)) line = Draft.make_line(a, b) self.doc.recompute() obj = Draft.make_linear_dimension_obj(line, i1=1, i2=2, dim_line=Vector(5, 3, 0)) self.assertTrue(obj, "'{}' failed".format(operation))
def test_dimension_radial(self): """Create a circle and then a radial dimension.""" operation = "Draft Dimension Radial" _msg(" Test '{}'".format(operation)) radius = 3 start_angle = 0 end_angle = 90 _msg(" radius={}".format(radius)) _msg(" startangle={0}, endangle={1}".format(start_angle, end_angle)) circ = Draft.makeCircle(radius, startangle=start_angle, endangle=end_angle) obj1 = Draft.makeDimension(circ, 0, p3="radius", p4=Vector(1, 1, 0)) obj2 = Draft.makeDimension(circ, 0, p3="diameter", p4=Vector(3, 1, 0)) self.assertTrue(obj1 and obj2, "'{}' failed".format(operation))
def test_clone(self): """Create a box, then create a clone of it. Test for a bug introduced by changes in attachment code. """ operation = "Draft Clone" _msg(" Test '{}'".format(operation)) box = App.ActiveDocument.addObject("Part::Box") App.ActiveDocument.recompute() _msg(" object: '{0}' ({1})".format(box.Shape.ShapeType, box.TypeId)) obj = Draft.clone(box) _msg(" clone: '{0}' ({1})".format(obj.Proxy.Type, obj.TypeId)) self.assertTrue(obj, "'{}' failed".format(operation)) self.assertTrue(obj.hasExtension("Part::AttachExtension"), "'{}' failed".format(operation))
def draw_arc(self, rad, chamfer, delete): """Process the selection and draw the actual object.""" wires = Gui.Selection.getSelection() if not wires or len(wires) != 2: _err(_tr("Two elements needed.")) return for o in wires: _msg(utils.get_type(o)) _test = translate("draft", "Test object") _test_off = translate("draft", "Test object removed") _cant = translate("draft", "Fillet cannot be created") _msg(4 * "=" + _test) arc = Draft.make_fillet(wires, rad) if not arc: _err(_cant) return self.doc.removeObject(arc.Name) _msg(4 * "=" + _test_off) _doc = 'FreeCAD.ActiveDocument.' _wires = '[' _wires += _doc + wires[0].Name + ', ' _wires += _doc + wires[1].Name _wires += ']' Gui.addModule("Draft") _cmd = 'Draft.make_fillet' _cmd += '(' _cmd += _wires + ', ' _cmd += 'radius=' + str(rad) if chamfer: _cmd += ', chamfer=' + str(chamfer) if delete: _cmd += ', delete=' + str(delete) _cmd += ')' _cmd_list = [ 'arc = ' + _cmd, 'Draft.autogroup(arc)', 'FreeCAD.ActiveDocument.recompute()' ] self.commit(translate("draft", "Create fillet"), _cmd_list)
def _are_numbers(d_x, d_y, d_z=None, name="Unknown"): """Check that the numbers are numbers.""" _msg("d_x: {}".format(d_x)) _msg("d_y: {}".format(d_y)) if d_z: _msg("d_z: {}".format(d_z)) try: if d_z: utils.type_check([(d_x, (int, float)), (d_y, (int, float)), (d_z, (int, float))], name=name) else: utils.type_check([(d_x, (int, float)), (d_y, (int, float))], name=name) except TypeError: _err(_tr("Wrong input: must be a number.")) return False, d_x, d_y, d_z return True, d_x, d_y, d_z
def test_dimension_radial_obj(self): """Create a circle and then a radial and a diameter dimension.""" operation = "Draft Dimension Radial" _msg(" Test '{}'".format(operation)) radius = 10 start_angle = 0 end_angle = 90 _msg(" radius={}".format(radius)) _msg(" startangle={0}, endangle={1}".format(start_angle, end_angle)) circ = Draft.make_circle(radius, startangle=start_angle, endangle=end_angle) self.doc.recompute() obj1 = Draft.make_radial_dimension_obj(circ, index=1, mode="radius", dim_line=Vector(1, 1, 0)) obj2 = Draft.make_radial_dimension_obj(circ, index=1, mode="diameter", dim_line=Vector(3, 1, 0)) self.assertTrue(obj1 and obj2, "'{}' failed".format(operation))