Draft: make move, rotate and scale commands link-aware (#18795)

* Draft: make move, rotate and scale commands link-aware

Fixes #12836.
Fixes #15681.

These changes are presented as a single ('big') PR because the mentioned commands have several similarities. Working on them seperately would have made less sense.

The commands have been made 'link-aware' meaning they can now handle Links and objects in linked containers.

This required several changes in the following main files. For each command all options are handled by a single function now (the `move`, `rotate` and `scale` functions). This was the only reasonable solution to correctly handle nested placements. As a result there is no longer a need to build very complex 'cmd' strings in the gui_*.py files (which is a good thing IMO).

Main files:

* move.py
* rotate.py
* scale.py
* gui_move.py
* gui_rotate.py
* gui_scale.py
* gui_trackers.py

The following files have also been updated:

* Draft.py: Imports updated.
* DraftGui.py: If `CopyMode` is changed the ghosts have to be updated. The move and rotate commands now also show previews of movable children. But since those are not copied they should be removed from the ghosts if `CopyMode` is changed to `True`.
* utils.py: Some helper functions have been added. An existing helper function (only used internally) has been renamed.
* gui_utils.py: The `select` function has been updated to accept a list of tuples to allow the reselection of nested objects.
* clone.py: A new property `ForceCompound`, necessary for non-uniform scaling, has been added.
* join.py: The `join_wires` function now returns the resultant wire objects.
* task_scale.py: Updated to allow negative scale factors. Support for `SubelementMode` preference added.
* dimension.py: `transform` methods added.
* layer.py: `get_layer` function added.
* svg.py: Updated to use `get_layer`.
* view_text.py: Instead of two added `coin.SoTransform()` nodes the main transform node is used instead. This was done so that ghosts of Draft Texts can be handled properly without requiring dedicated code in gui_trackers.py.

Notes:

* Support for "App::Annotation" is limited. Only their `Position` is handled (by the move and rotate commands).
* Support for "Image::ImagePlane" has been removed from the scale command. The object has its own calibrate feature (see https://wiki.freecad.org/Std_Import).
* Copies and clones are always created in the global space.

* Fix several unit test issues.

* Reset value that was changed while testing

* Rebase and update test_modification.py

* Reintroduce scaling of image planes
This commit is contained in:
Roy-043
2025-01-20 18:23:36 +01:00
committed by GitHub
parent 8d46ba6414
commit d587e6a91a
19 changed files with 1042 additions and 973 deletions

View File

@@ -78,7 +78,6 @@ from draftutils.utils import (get_real_name,
compare_objects,
compareObjects,
shapify,
filter_objects_for_modifiers,
is_closed_edge)
from draftutils.utils import (string_encode_coin,
@@ -154,20 +153,17 @@ from draftfunctions.heal import heal
from draftfunctions.move import (move,
move_vertex,
move_edge,
copy_moved_edge,
copy_moved_edges)
copy_moved_edge)
from draftfunctions.rotate import (rotate,
rotate_vertex,
rotate_edge,
copy_rotated_edge,
copy_rotated_edges)
copy_rotated_edge)
from draftfunctions.scale import (scale,
scale_vertex,
scale_edge,
copy_scaled_edge,
copy_scaled_edges)
copy_scaled_edge)
from draftfunctions.join import (join_wires,
joinWires,
@@ -371,7 +367,8 @@ if App.GuiUp:
from draftviewproviders.view_fillet import ViewProviderFillet
from draftobjects.layer import (Layer,
_VisGroup)
_VisGroup,
get_layer)
from draftmake.make_layer import make_layer

View File

@@ -982,6 +982,9 @@ class DraftToolBar:
params.set_param("OffsetCopyMode", bool(val))
else:
params.set_param("CopyMode", bool(val))
# if CopyMode is changed ghosts must be updated.
# Moveable children should not be included if CopyMode is True.
self.sourceCmd.set_ghosts()
def setSubelementMode(self, val):
params.set_param("SubelementMode", bool(val))

View File

@@ -34,6 +34,7 @@ import DraftVecUtils
def join_wires(wires, joinAttempts = 0):
"""join_wires(objects): merges a set of wires where possible, if any of those
wires have a coincident start and end point"""
wires = list(wires)
if joinAttempts > len(wires):
return
joinAttempts += 1
@@ -45,6 +46,7 @@ def join_wires(wires, joinAttempts = 0):
wires.pop(wire2Index)
break
join_wires(wires, joinAttempts)
return wires
joinWires = join_wires

View File

@@ -2,6 +2,7 @@
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * Copyright (c) 2024 The FreeCAD Project Association *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
@@ -31,62 +32,82 @@ import FreeCAD as App
from draftfunctions import join
from draftmake import make_copy
from draftmake import make_line
from draftutils import groups
from draftobjects import layer
from draftutils import gui_utils
from draftutils import params
from draftutils import utils
def move(objectslist, vector, copy=False):
"""move(objects,vector,[copy])
def move(selection, vector, copy=False, subelements=False):
"""move(selection, vector, [copy], [subelements])
Move the objects contained in objects (that can be an object or a
list of objects) in the direction and distance indicated by the given
vector.
Moves or copies selected objects.
Parameters
----------
objectslist : list
selection: single object / list of objects / selection set
When dealing with nested objects, use `Gui.Selection.getSelectionEx("", 0)`
to create the selection set.
vector : Base.Vector
Delta Vector to move the clone from the original position.
vector: App.Vector
Delta vector.
copy : bool
If copy is True, the actual objects are not moved, but copies
are created instead.
copy: bool, optional
Defaults to `False`.
If `True` the selected objects are not moved, but moved copies are
created instead.
Return
----------
The objects (or their copies) are returned.
subelements: bool, optional
Defaults to `False`.
If `True` subelements instead of whole objects are processed.
Only used if selection is a selection set.
Returns
-------
single object / list with 2 or more objects / empty list
The objects (or their copies)
"""
utils.type_check([(vector, App.Vector), (copy,bool)], "move")
if not isinstance(objectslist, list):
objectslist = [objectslist]
utils.type_check([(vector, App.Vector), (copy, bool), (subelements, bool)], "move")
if not isinstance(selection, list):
selection = [selection]
if not selection:
return None
objectslist.extend(groups.get_movable_children(objectslist))
newobjlist = []
if selection[0].isDerivedFrom("Gui::SelectionObject"):
if subelements:
return _move_subelements(selection, vector, copy)
else:
objs, parent_places, sel_info = utils._modifiers_process_selection(selection, copy)
else:
objs = utils._modifiers_filter_objects(utils._modifiers_get_group_contents(selection), copy)
parent_places = None
sel_info = None
if not objs:
return None
newobjs = []
newgroups = {}
objectslist = utils.filter_objects_for_modifiers(objectslist, copy)
if copy:
doc = App.ActiveDocument
for obj in objectslist:
if obj.isDerivedFrom("App::DocumentObjectGroup") \
and obj.Name not in newgroups:
newgroups[obj.Name] = doc.addObject(obj.TypeId,
utils.get_real_name(obj.Name))
for obj in objs:
if obj.isDerivedFrom("App::DocumentObjectGroup") and obj.Name not in newgroups:
newgroups[obj.Name] = obj.Document.addObject(obj.TypeId, utils.get_real_name(obj.Name))
for obj in objectslist:
for idx, obj in enumerate(objs):
newobj = None
# real_vector have been introduced to take into account
# the possibility that object is inside an App::Part
# TODO: Make Move work also with App::Link
if hasattr(obj, "getGlobalPlacement"):
v_minus_global = obj.getGlobalPlacement().inverse().Rotation.multVec(vector)
real_vector = obj.Placement.Rotation.multVec(v_minus_global)
if parent_places is not None:
parent_place = parent_places[idx]
elif hasattr(obj, "getGlobalPlacement"):
parent_place = obj.getGlobalPlacement() * obj.Placement.inverse()
else:
parent_place = App.Placement()
if copy or parent_place.isIdentity():
real_vector = vector
else:
real_vector = parent_place.inverse().Rotation.multVec(vector)
if obj.isDerivedFrom("App::DocumentObjectGroup"):
if copy:
@@ -94,121 +115,127 @@ def move(objectslist, vector, copy=False):
else:
newobj = obj
elif hasattr(obj, "Shape"):
elif hasattr(obj, "Placement"):
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Placement = parent_place * newobj.Placement
else:
newobj = obj
pla = newobj.Placement
pla.move(real_vector)
newobj.Placement.move(real_vector)
elif obj.isDerivedFrom("App::Annotation"):
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Position = parent_place.multVec(newobj.Position)
else:
newobj = obj
newobj.Position = obj.Position.add(real_vector)
newobj.Position = newobj.Position.add(real_vector)
elif utils.get_type(obj) in ["Text", "DraftText"]:
elif utils.get_type(obj) in ("Dimension", "LinearDimension", "AngularDimension"):
# "Dimension" was the type for linear dimensions <= v0.18.
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Proxy.transform(newobj, parent_place)
else:
newobj = obj
newobj.Placement.Base = obj.Placement.Base.add(real_vector)
elif utils.get_type(obj) in ["Dimension", "LinearDimension"]:
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
newobj.Start = obj.Start.add(real_vector)
newobj.End = obj.End.add(real_vector)
newobj.Dimline = obj.Dimline.add(real_vector)
elif utils.get_type(obj) == "AngularDimension":
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
newobj.Center = obj.Center.add(real_vector)
newobj.Dimline = obj.Dimline.add(real_vector)
elif hasattr(obj, "Placement"):
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
pla = newobj.Placement
pla = App.Placement()
pla.move(real_vector)
newobj.Proxy.transform(newobj, pla)
if newobj is not None:
newobjlist.append(newobj)
newobjs.append(newobj)
if copy:
lyr = layer.get_layer(obj)
if lyr is not None:
lyr.Proxy.addObject(lyr, newobj)
for parent in obj.InList:
if parent.isDerivedFrom("App::DocumentObjectGroup") \
and (parent in objectslist):
if parent.isDerivedFrom("App::DocumentObjectGroup") and (parent in objs):
newgroups[parent.Name].addObject(newobj)
if utils.get_type(parent) == "Layer":
parent.Proxy.addObject(parent ,newobj)
if copy and params.get_param("selectBaseObjects"):
gui_utils.select(objectslist)
if not copy or params.get_param("selectBaseObjects"):
if sel_info is not None:
gui_utils.select(sel_info)
else:
gui_utils.select(objs)
else:
gui_utils.select(newobjlist)
gui_utils.select(newobjs)
if len(newobjlist) == 1:
return newobjlist[0]
return newobjlist
if len(newobjs) == 1:
return newobjs[0]
return newobjs
# Following functions are needed for SubObjects modifiers
# implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire)
def move_vertex(object, vertex_index, vector):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
vector = object.getGlobalPlacement().inverse().Rotation.multVec(vector)
points = object.Points
points[vertex_index] = points[vertex_index].add(vector)
object.Points = points
def move_edge(object, edge_index, vector):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
move_vertex(object, edge_index, vector)
if utils.is_closed_edge(edge_index, object):
move_vertex(object, 0, vector)
def _move_subelements(selection, vector, copy):
data_list, sel_info = utils._modifiers_process_subselection(selection, copy)
newobjs = []
if copy:
for obj, vert_idx, edge_idx, global_place in data_list:
if edge_idx >= 0:
newobjs.append(copy_moved_edge(obj, edge_idx, vector, global_place))
newobjs = join.join_wires(newobjs)
else:
move_vertex(object, edge_index+1, vector)
for obj, vert_idx, edge_idx, global_place in data_list:
if vert_idx >= 0:
move_vertex(obj, vert_idx, vector, global_place)
elif edge_idx >= 0:
move_edge(obj, edge_idx, vector, global_place)
def copy_moved_edges(arguments):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
copied_edges = []
for argument in arguments:
copied_edges.append(copy_moved_edge(argument[0], argument[1], argument[2]))
join.join_wires(copied_edges)
def copy_moved_edge(object, edge_index, vector):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
vertex1 = object.getGlobalPlacement().multVec(object.Points[edge_index]).add(vector)
if utils.is_closed_edge(edge_index, object):
vertex2 = object.getGlobalPlacement().multVec(object.Points[0]).add(vector)
if not copy or params.get_param("selectBaseObjects"):
gui_utils.select(sel_info)
else:
vertex2 = object.getGlobalPlacement().multVec(object.Points[edge_index+1]).add(vector)
return make_line.make_line(vertex1, vertex2)
gui_utils.select(newobjs)
if len(newobjs) == 1:
return newobjs[0]
return newobjs
def move_vertex(obj, vert_idx, vector, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vector = glp.inverse().Rotation.multVec(vector)
points = obj.Points
points[vert_idx] = points[vert_idx].add(vector)
obj.Points = points
def move_edge(obj, edge_idx, vector, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
move_vertex(obj, edge_idx, vector, global_place)
if utils.is_closed_edge(edge_idx, obj):
move_vertex(obj, 0, vector, global_place)
else:
move_vertex(obj, edge_idx+1, vector, global_place)
def copy_moved_edge(obj, edge_idx, vector, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vertex1 = glp.multVec(obj.Points[edge_idx]).add(vector)
if utils.is_closed_edge(edge_idx, obj):
vertex2 = glp.multVec(obj.Points[0]).add(vector)
else:
vertex2 = glp.multVec(obj.Points[edge_idx+1]).add(vector)
newobj = make_line.make_line(vertex1, vertex2)
gui_utils.format_object(newobj, obj)
return newobj
## @}

View File

@@ -2,6 +2,7 @@
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * Copyright (c) 2024 The FreeCAD Project Association *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
@@ -34,152 +35,178 @@ import DraftVecUtils
from draftfunctions import join
from draftmake import make_copy
from draftmake import make_line
from draftobjects import layer
from draftutils import groups
from draftutils import gui_utils
from draftutils import params
from draftutils import utils
def rotate(objectslist, angle, center=App.Vector(0, 0, 0),
axis=App.Vector(0, 0, 1), copy=False):
"""rotate(objects,angle,[center,axis,copy])
def rotate(selection, angle, center=App.Vector(0, 0, 0),
axis=App.Vector(0, 0, 1), copy=False, subelements=False):
"""rotate(selection, angle, [center], [axis], [copy], [subelements])
Rotates the objects contained in objects (that can be a list of objects
or an object) of the given angle (in degrees) around the center, using
axis as a rotation axis.
Rotates or copies selected objects.
Parameters
----------
objectslist : list
selection: single object / list of objects / selection set
When dealing with nested objects, use `Gui.Selection.getSelectionEx("", 0)`
to create the selection set.
angle : rotation angle (in degrees)
angle: float / integer
Rotation angle (in degrees).
center : Base.Vector
center: App.Vector, optional
Defaults to `App.Vector(0, 0, 0)`.
Rotation center.
axis : Base.Vector
If axis is omitted, the rotation will be around the vertical Z axis.
axis: App.Vector, optional
Defaults to `App.Vector(0, 0, 1)`.
Rotation axis.
copy : bool
If copy is True, the actual objects are not moved, but copies
are created instead.
copy: bool, optional
Defaults to `False`.
If `True` the selected objects are not rotated, but rotated copies are
created instead.
Return
----------
The objects (or their copies) are returned.
subelements: bool, optional
Defaults to `False`.
If `True` subelements instead of whole objects are processed.
Only used if selection is a selection set.
Returns
-------
single object / list with 2 or more objects / empty list
The objects (or their copies).
"""
import Part
utils.type_check([(copy,bool)], "rotate")
if not isinstance(objectslist,list):
objectslist = [objectslist]
utils.type_check([(angle, (float, int)), (center, App.Vector),
(axis, App.Vector), (copy, bool), (subelements, bool)], "rotate")
if not isinstance(selection, list):
selection = [selection]
if not selection:
return None
objectslist.extend(groups.get_movable_children(objectslist))
newobjlist = []
if selection[0].isDerivedFrom("Gui::SelectionObject"):
if subelements:
return _rotate_subelements(selection, angle, center, axis, copy)
else:
objs, parent_places, sel_info = utils._modifiers_process_selection(selection, copy)
else:
objs = utils._modifiers_filter_objects(utils._modifiers_get_group_contents(selection), copy)
parent_places = None
sel_info = None
if not objs:
return None
newobjs = []
newgroups = {}
objectslist = utils.filter_objects_for_modifiers(objectslist, copy)
if copy:
doc = App.ActiveDocument
for obj in objectslist:
if obj.isDerivedFrom("App::DocumentObjectGroup") \
and obj.Name not in newgroups:
newgroups[obj.Name] = doc.addObject(obj.TypeId,
utils.get_real_name(obj.Name))
for obj in objs:
if obj.isDerivedFrom("App::DocumentObjectGroup") and obj.Name not in newgroups:
newgroups[obj.Name] = obj.Document.addObject(obj.TypeId, utils.get_real_name(obj.Name))
for obj in objectslist:
for idx, obj in enumerate(objs):
newobj = None
# real_center and real_axis are introduced to take into account
# the possibility that object is inside an App::Part
if hasattr(obj, "getGlobalPlacement"):
ci = obj.getGlobalPlacement().inverse().multVec(center)
real_center = obj.Placement.multVec(ci)
ai = obj.getGlobalPlacement().inverse().Rotation.multVec(axis)
real_axis = obj.Placement.Rotation.multVec(ai)
if parent_places is not None:
parent_place = parent_places[idx]
elif hasattr(obj, "getGlobalPlacement"):
parent_place = obj.getGlobalPlacement() * obj.Placement.inverse()
else:
parent_place = App.Placement()
if copy or parent_place.isIdentity():
real_center = center
real_axis = axis
else:
real_center = parent_place.inverse().multVec(center)
real_axis = parent_place.inverse().Rotation.multVec(axis)
if obj.isDerivedFrom("App::Annotation"):
# TODO: this is very different from how move handle annotations
# maybe we can uniform the two methods
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
if axis.normalize() == App.Vector(1, 0, 0):
newobj.ViewObject.RotationAxis = "X"
newobj.ViewObject.Rotation = angle
elif axis.normalize() == App.Vector(0, 1, 0):
newobj.ViewObject.RotationAxis = "Y"
newobj.ViewObject.Rotation = angle
elif axis.normalize() == App.Vector(0, -1, 0):
newobj.ViewObject.RotationAxis = "Y"
newobj.ViewObject.Rotation = -angle
elif axis.normalize() == App.Vector(0, 0, 1):
newobj.ViewObject.RotationAxis = "Z"
newobj.ViewObject.Rotation = angle
elif axis.normalize() == App.Vector(0, 0, -1):
newobj.ViewObject.RotationAxis = "Z"
newobj.ViewObject.Rotation = -angle
elif obj.isDerivedFrom("App::DocumentObjectGroup"):
if obj.isDerivedFrom("App::DocumentObjectGroup"):
if copy:
newobj = newgroups[obj.Name]
else:
newobj = obj
elif hasattr(obj, "Placement"):
# App.Console.PrintMessage("placement rotation\n")
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Placement = parent_place * newobj.Placement
else:
newobj = obj
newobj.Placement.rotate(real_center, real_axis, angle, comp=True)
elif hasattr(obj, "Shape"):
elif obj.isDerivedFrom("App::Annotation"):
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Position = parent_place.multVec(newobj.Position)
else:
newobj = obj
shape = newobj.Shape.copy()
shape.rotate(real_center, real_axis, angle)
newobj.Shape = shape
newobj.Position = rotate_vector_from_center(newobj.Position, angle, axis, center)
elif utils.get_type(obj) in ("Dimension", "LinearDimension", "AngularDimension"):
# "Dimension" was the type for linear dimensions <= v0.18.
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Proxy.transform(newobj, parent_place)
else:
newobj = obj
pla = App.Placement()
pla.rotate(real_center, real_axis, angle, comp=True)
newobj.Proxy.transform(newobj, pla)
if newobj is not None:
newobjlist.append(newobj)
newobjs.append(newobj)
if copy:
lyr = layer.get_layer(obj)
if lyr is not None:
lyr.Proxy.addObject(lyr, newobj)
for parent in obj.InList:
if parent.isDerivedFrom("App::DocumentObjectGroup") \
and (parent in objectslist):
if parent.isDerivedFrom("App::DocumentObjectGroup") and (parent in objs):
newgroups[parent.Name].addObject(newobj)
if utils.get_type(parent) == "Layer":
parent.Proxy.addObject(parent ,newobj)
if copy and params.get_param("selectBaseObjects"):
gui_utils.select(objectslist)
if not copy or params.get_param("selectBaseObjects"):
if sel_info is not None:
gui_utils.select(sel_info)
else:
gui_utils.select(objs)
else:
gui_utils.select(newobjlist)
gui_utils.select(newobjs)
if len(newobjlist) == 1:
return newobjlist[0]
return newobjlist
if len(newobjs) == 1:
return newobjs[0]
return newobjs
# Following functions are needed for SubObjects modifiers
# implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire)
def _rotate_subelements(selection, angle, center, axis, copy):
data_list, sel_info = utils._modifiers_process_subselection(selection, copy)
newobjs = []
if copy:
for obj, vert_idx, edge_idx, global_place in data_list:
if edge_idx >= 0:
newobjs.append(copy_rotated_edge(obj, edge_idx, angle, center, axis, global_place))
newobjs = join.join_wires(newobjs)
else:
for obj, vert_idx, edge_idx, global_place in data_list:
if vert_idx >= 0:
rotate_vertex(obj, vert_idx, angle, center, axis, global_place)
elif edge_idx >= 0:
rotate_edge(obj, edge_idx, angle, center, axis, global_place)
if not copy or params.get_param("selectBaseObjects"):
gui_utils.select(sel_info)
else:
gui_utils.select(newobjs)
def rotate_vertex(object, vertex_index, angle, center, axis):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
points = object.Points
points[vertex_index] = object.getGlobalPlacement().inverse().multVec(
rotate_vector_from_center(
object.getGlobalPlacement().multVec(points[vertex_index]),
angle, axis, center))
object.Points = points
if len(newobjs) == 1:
return newobjs[0]
return newobjs
def rotate_vector_from_center(vector, angle, axis, center):
@@ -192,46 +219,57 @@ def rotate_vector_from_center(vector, angle, axis, center):
return center.add(rv)
def rotate_edge(object, edge_index, angle, center, axis):
def rotate_vertex(obj, vert_idx, angle, center, axis, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
rotate_vertex(object, edge_index, angle, center, axis)
if utils.is_closed_edge(edge_index, object):
rotate_vertex(object, 0, angle, center, axis)
if global_place is None:
glp = obj.getGlobalPlacement()
else:
rotate_vertex(object, edge_index+1, angle, center, axis)
glp = global_place
points = obj.Points
points[vert_idx] = glp.inverse().multVec(
rotate_vector_from_center(
glp.multVec(points[vert_idx]),
angle, axis, center))
obj.Points = points
def copy_rotated_edges(arguments):
def rotate_edge(obj, edge_idx, angle, center, axis, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
copied_edges = []
for argument in arguments:
copied_edges.append(copy_rotated_edge(argument[0], argument[1],
argument[2], argument[3], argument[4]))
join.join_wires(copied_edges)
rotate_vertex(obj, edge_idx, angle, center, axis, global_place)
if utils.is_closed_edge(edge_idx, obj):
rotate_vertex(obj, 0, angle, center, axis, global_place)
else:
rotate_vertex(obj, edge_idx+1, angle, center, axis, global_place)
def copy_rotated_edge(object, edge_index, angle, center, axis):
def copy_rotated_edge(obj, edge_idx, angle, center, axis, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vertex1 = rotate_vector_from_center(
object.getGlobalPlacement().multVec(object.Points[edge_index]),
glp.multVec(obj.Points[edge_idx]),
angle, axis, center)
if utils.is_closed_edge(edge_index, object):
if utils.is_closed_edge(edge_idx, obj):
vertex2 = rotate_vector_from_center(
object.getGlobalPlacement().multVec(object.Points[0]),
glp.multVec(obj.Points[0]),
angle, axis, center)
else:
vertex2 = rotate_vector_from_center(
object.getGlobalPlacement().multVec(object.Points[edge_index+1]),
glp.multVec(obj.Points[edge_idx+1]),
angle, axis, center)
return make_line.make_line(vertex1, vertex2)
newobj = make_line.make_line(vertex1, vertex2)
gui_utils.format_object(newobj, obj)
return newobj
## @}

View File

@@ -2,6 +2,7 @@
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * Copyright (c) 2024 FreeCAD Project Association *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
@@ -27,132 +28,327 @@
## \addtogroup draftfunctions
# @{
import math
import FreeCAD as App
import DraftVecUtils
from draftfunctions import join
from draftmake import make_clone
from draftmake import make_copy
from draftmake import make_line
from draftmake import make_wire
from draftobjects import layer
from draftutils import gui_utils
from draftutils import params
from draftutils import utils
def scale(objectslist, scale=App.Vector(1,1,1),
center=App.Vector(0,0,0), copy=False):
"""scale(objects, scale, [center], copy)
def scale(selection, scale, center=App.Vector(0, 0, 0),
copy=False, clone=False, subelements=False):
"""scale(selection, scale, [center], [copy], [clone], [subelements])
Scales the objects contained in objects (that can be a list of objects or
an object) of the given around given center.
Scales or copies selected objects.
Parameters
----------
objectlist : list
selection: single object / list of objects / selection set
When dealing with nested objects, use `Gui.Selection.getSelectionEx("", 0)`
to create the selection set.
scale : Base.Vector
Scale factors defined by a given vector (in X, Y, Z directions).
scale: App.Vector
The X, Y and Z component of the vector define the scale factors.
objectlist : Base.Vector
center: App.Vector, optional
Defaults to `App.Vector(0, 0, 0)`.
Center of the scale operation.
copy : bool
If copy is True, the actual objects are not scaled, but copies
are created instead.
copy: bool, optional
Defaults to `False`.
If `True` the selected objects are not scaled, but scaled copies are
created instead. If clone is `True`, copy is internally set to `False`.
Return
----------
The objects (or their copies) are returned.
clone: bool, optional
Defaults to `False`.
If `True` the selected objects are not scaled, but scaled clones are
created instead.
subelements: bool, optional
Defaults to `False`.
If `True` subelements instead of whole objects are processed.
Only used if selection is a selection set.
Returns
-------
single object / list with 2 or more objects / empty list
The objects (or their copies).
"""
if not isinstance(objectslist, list):
objectslist = [objectslist]
newobjlist = []
for obj in objectslist:
if copy:
newobj = make_copy.make_copy(obj)
utils.type_check([(scale, App.Vector), (center, App.Vector),
(copy, bool), (clone, bool), (subelements, bool)], "scale")
sx, sy, sz = scale
if sx * sy * sz == 0:
raise ValueError("Zero component in scale vector")
if not isinstance(selection, list):
selection = [selection]
if not selection:
return None
if clone:
copy = False
if selection[0].isDerivedFrom("Gui::SelectionObject"):
if subelements:
return _scale_subelements(selection, scale, center, copy)
else:
newobj = obj
if hasattr(obj,'Shape'):
scaled_shape = obj.Shape.copy()
m = App.Matrix()
m.move(center.negative())
m.scale(scale.x,scale.y,scale.z)
m.move(center)
scaled_shape = scaled_shape.transformGeometry(m)
if utils.get_type(obj) == "Rectangle":
p = []
for v in scaled_shape.Vertexes:
p.append(v.Point)
pl = obj.Placement.copy()
pl.Base = p[0]
diag = p[2].sub(p[0])
bb = p[1].sub(p[0])
bh = p[3].sub(p[0])
nb = DraftVecUtils.project(diag,bb)
nh = DraftVecUtils.project(diag,bh)
if obj.Length < 0: l = -nb.Length
else: l = nb.Length
if obj.Height < 0: h = -nh.Length
else: h = nh.Length
newobj.Length = l
newobj.Height = h
tr = p[0].sub(obj.Shape.Vertexes[0].Point) # unused?
newobj.Placement = pl
elif utils.get_type(obj) == "Wire" or utils.get_type(obj) == "BSpline":
for index, point in enumerate(newobj.Points):
scale_vertex(newobj, index, scale, center)
elif hasattr(obj,'Shape'):
newobj.Shape = scaled_shape
elif hasattr(obj,"Position"):
d = obj.Position.sub(center)
newobj.Position = center.add(App.Vector(d.x * scale.x,
d.y * scale.y,
d.z * scale.z))
elif hasattr(obj,"Placement"):
d = obj.Placement.Base.sub(center)
newobj.Placement.Base = center.add(App.Vector(d.x * scale.x,
d.y * scale.y,
d.z * scale.z))
if hasattr(obj,"Height"):
obj.setExpression('Height', None)
obj.Height = obj.Height * scale.y
if hasattr(obj,"Width"):
obj.setExpression('Width', None)
obj.Width = obj.Width * scale.x
if hasattr(obj,"XSize"):
obj.setExpression('XSize', None)
obj.XSize = obj.XSize * scale.x
if hasattr(obj,"YSize"):
obj.setExpression('YSize', None)
obj.YSize = obj.YSize * scale.y
if obj.ViewObject and hasattr(obj.ViewObject,"FontSize"):
obj.ViewObject.FontSize = obj.ViewObject.FontSize * scale.y
if copy:
gui_utils.format_object(newobj,obj)
newobjlist.append(newobj)
if copy and params.get_param("selectBaseObjects"):
gui_utils.select(objectslist)
objs, parent_places, sel_info = utils._modifiers_process_selection(selection, (copy or clone), scale=True)
else:
gui_utils.select(newobjlist)
if len(newobjlist) == 1: return newobjlist[0]
return newobjlist
objs = utils._modifiers_filter_objects(utils._modifiers_get_group_contents(selection), (copy or clone), scale=True)
parent_places = None
sel_info = None
if not objs:
return None
newobjs = []
newgroups = {}
if copy or clone:
for obj in objs:
if obj.isDerivedFrom("App::DocumentObjectGroup") and obj.Name not in newgroups:
newgroups[obj.Name] = obj.Document.addObject(obj.TypeId, utils.get_real_name(obj.Name))
for idx, obj in enumerate(objs):
newobj = None
create_non_parametric = False
if parent_places is not None:
parent_place = parent_places[idx]
elif hasattr(obj, "getGlobalPlacement"):
parent_place = obj.getGlobalPlacement() * obj.Placement.inverse()
else:
parent_place = App.Placement()
if obj.isDerivedFrom("App::DocumentObjectGroup"):
if copy or clone:
newobj = newgroups[obj.Name]
else:
newobj = obj
elif obj.isDerivedFrom("App::Annotation"):
if parent_place.isIdentity():
pos = obj.Position
else:
pos = parent_place.multVec(obj.Position)
pos = scale_vector_from_center(pos, scale, center)
if copy or clone:
newobj = make_copy.make_copy(obj)
newobj.Position = pos
else:
newobj = obj
if parent_place.isIdentity():
newobj.Position = pos
else:
newobj.Position = parent_place.inverse().multVec(pos)
elif obj.isDerivedFrom("Image::ImagePlane"):
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
scale = pla.Rotation.inverted().multVec(scale)
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
newobj.XSize = newobj.XSize * abs(scale.x)
newobj.YSize = newobj.YSize * abs(scale.y)
elif clone:
if not hasattr(obj, "Placement"):
continue
if not hasattr(obj, "Shape"):
continue
if sx == sy == sz:
newobj = make_clone.make_clone(obj, forcedraft=True)
newobj.Placement.Base = scale_vector_from_center(newobj.Placement.Base, scale, center)
newobj.Scale = scale
else:
if parent_place.isIdentity():
source = obj
else:
source = make_clone.make_clone(obj, forcedraft=True)
source.Placement = parent_place * obj.Placement
source.Visibility = False
delta = scale_vector_from_center(App.Vector(), scale, center)
newobj = make_clone.make_clone(source, delta=delta, forcedraft=True)
newobj.ForceCompound = True
newobj.Scale = scale
elif utils.get_type(obj) in ("Circle", "Ellipse"):
if abs(sx) == abs(sy) == abs(sz):
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
if utils.get_type(newobj) == "Circle":
newobj.Radius = abs(sx) * newobj.Radius
else:
newobj.MinorRadius = abs(sx) * newobj.MinorRadius
newobj.MajorRadius = abs(sx) * newobj.MajorRadius
if newobj.FirstAngle != newobj.LastAngle and sx * sy * sz < 0:
newobj.FirstAngle = (newobj.FirstAngle.Value + 180) % 360
newobj.LastAngle = (newobj.LastAngle.Value + 180) % 360
else:
create_non_parametric = True
elif utils.get_type(obj) == "Rectangle":
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pts = [
App.Vector (0.0, 0.0, 0.0),
App.Vector (obj.Length.Value, 0.0, 0.0),
App.Vector (obj.Length.Value, obj.Height.Value, 0.0),
App.Vector (0.0, obj.Height.Value, 0.0)
]
pts = [pla.multVec(p) for p in pts]
pts = [scale_vector_from_center(p, scale, center) for p in pts]
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
x_vec = pts[1] - pts[0]
y_vec = pts[3] - pts[0]
ang = x_vec.getAngle(y_vec)
if math.isclose(ang % math.pi/2, math.pi/4, abs_tol=1e-6):
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
newobj.Length = x_vec.Length
newobj.Height = y_vec.Length
else:
newobj = make_wire.make_wire(pts, closed=True, placement=pla, face=obj.MakeFace)
gui_utils.format_object(newobj, obj)
if not copy:
obj.Document.removeObject(obj.Name)
elif utils.get_type(obj) in ("Wire", "BSpline"):
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pts = [pla.multVec(p) for p in obj.Points]
pts = [scale_vector_from_center(p, scale, center) for p in pts]
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
pla_inv = pla.inverse()
newobj.Points = [pla_inv.multVec(p) for p in pts]
elif hasattr(obj, "Placement") and hasattr(obj, "Shape"):
create_non_parametric = True
if create_non_parametric:
import Part
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
mtx = _get_scaled_matrix(parent_place, scale, center)
shp = obj.Shape.copy().transformShape(pla.Matrix.inverse() * mtx, False, True)
newobj = obj.Document.addObject("Part::FeaturePython", utils.get_real_name(obj.Name))
newobj.Shape = Part.Compound([shp])
newobj.Placement = pla
if App.GuiUp:
if utils.get_type(obj) in ("Circle", "Ellipse"):
from draftviewproviders.view_base import ViewProviderDraft
ViewProviderDraft(newobj.ViewObject)
else:
newobj.ViewObject.Proxy = 0
gui_utils.format_object(newobj, obj)
if not copy:
obj.Document.removeObject(obj.Name)
if newobj is not None:
newobjs.append(newobj)
if copy:
lyr = layer.get_layer(obj)
if lyr is not None:
lyr.Proxy.addObject(lyr, newobj)
for parent in obj.InList:
if parent.isDerivedFrom("App::DocumentObjectGroup") and (parent in objs):
newgroups[parent.Name].addObject(newobj)
if not (copy or clone) or params.get_param("selectBaseObjects"):
if sel_info is not None:
gui_utils.select(sel_info)
else:
gui_utils.select(objs)
else:
gui_utils.select(newobjs)
if len(newobjs) == 1:
return newobjs[0]
return newobjs
# Following functions are needed for SubObjects modifiers
# implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire)
def _scale_subelements(selection, scale, center, copy):
data_list, sel_info = utils._modifiers_process_subselection(selection, copy)
newobjs = []
if copy:
for obj, vert_idx, edge_idx, global_place in data_list:
if edge_idx >= 0:
newobjs.append(copy_scaled_edge(obj, edge_idx, scale, center, global_place))
newobjs = join.join_wires(newobjs)
else:
for obj, vert_idx, edge_idx, global_place in data_list:
if vert_idx >= 0:
scale_vertex(obj, vert_idx, scale, center, global_place)
elif edge_idx >= 0:
scale_edge(obj, edge_idx, scale, center, global_place)
if not copy or params.get_param("selectBaseObjects"):
gui_utils.select(sel_info)
else:
gui_utils.select(newobjs)
if len(newobjs) == 1:
return newobjs[0]
return newobjs
def scale_vertex(obj, vertex_index, scale, center):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
points = obj.Points
points[vertex_index] = obj.getGlobalPlacement().inverse().multVec(
scale_vector_from_center(
obj.getGlobalPlacement().multVec(points[vertex_index]),
scale, center))
obj.Points = points
def _get_scaled_matrix(pla, scale, center):
mtx = App.Matrix(pla.Matrix)
mtx.move(-center)
mtx.scale(scale)
mtx.move(center)
return mtx
def scale_vector_from_center(vector, scale, center):
@@ -160,49 +356,53 @@ def scale_vector_from_center(vector, scale, center):
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
return vector.sub(center).scale(scale.x, scale.y, scale.z).add(center)
return vector.sub(center).scale(*scale).add(center)
def scale_edge(obj, edge_index, scale, center):
def scale_vertex(obj, vert_idx, scale, center, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
scale_vertex(obj, edge_index, scale, center)
if utils.is_closed_edge(edge_index, obj):
scale_vertex(obj, 0, scale, center)
if global_place is None:
glp = obj.getGlobalPlacement()
else:
scale_vertex(obj, edge_index+1, scale, center)
glp = global_place
points = obj.Points
points[vert_idx] = glp.inverse().multVec(
scale_vector_from_center(glp.multVec(points[vert_idx]), scale, center)
)
obj.Points = points
def copy_scaled_edge(obj, edge_index, scale, center):
def scale_edge(obj, edge_idx, scale, center, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
vertex1 = scale_vector_from_center(
obj.getGlobalPlacement().multVec(obj.Points[edge_index]),
scale, center)
if utils.is_closed_edge(edge_index, obj):
vertex2 = scale_vector_from_center(
obj.getGlobalPlacement().multVec(obj.Points[0]),
scale, center)
scale_vertex(obj, edge_idx, scale, center, global_place)
if utils.is_closed_edge(edge_idx, obj):
scale_vertex(obj, 0, scale, center, global_place)
else:
vertex2 = scale_vector_from_center(
obj.getGlobalPlacement().multVec(obj.Points[edge_index+1]),
scale, center)
return make_line.make_line(vertex1, vertex2)
scale_vertex(obj, edge_idx+1, scale, center, global_place)
def copy_scaled_edges(arguments):
def copy_scaled_edge(obj, edge_idx, scale, center, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
copied_edges = []
for argument in arguments:
copied_edges.append(copy_scaled_edge(argument[0], argument[1],
argument[2], argument[3]))
join.join_wires(copied_edges)
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vertex1 = scale_vector_from_center(glp.multVec(obj.Points[edge_idx]), scale, center)
if utils.is_closed_edge(edge_idx, obj):
vertex2 = scale_vector_from_center(glp.multVec(obj.Points[0]), scale, center)
else:
vertex2 = scale_vector_from_center(glp.multVec(obj.Points[edge_idx+1]), scale, center)
newobj = make_line.make_line(vertex1, vertex2)
gui_utils.format_object(newobj, obj)
return newobj
## @}

View File

@@ -35,6 +35,7 @@ import DraftVecUtils
import WorkingPlane
from draftfunctions import svgtext
from draftfunctions.svgshapes import get_proj, get_circle, get_path
from draftobjects import layer
from draftutils import params
from draftutils import utils
from draftutils.messages import _wrn, _err
@@ -955,31 +956,14 @@ def _get_view_object(obj):
return None
# Similar function as in view_layer.py
def _get_layer(obj):
"""Get the layer the object belongs to."""
finds = obj.Document.findObjects(Name="LayerContainer")
if not finds:
return None
# First look in the LayerContainer:
for layer in finds[0].Group:
if utils.get_type(layer) == "Layer" and obj in layer.Group:
return layer
# If not found, look through all App::FeaturePython objects (not just layers):
for find in obj.Document.findObjects(Type="App::FeaturePython"):
if utils.get_type(find) == "Layer" and obj in find.Group:
return find
return None
def get_print_color(obj):
"""Return the print color of the parent layer, if available."""
# Layers are not in the Inlist of obj because a layer's Group is App::PropertyLinkListHidden:
layer = _get_layer(obj)
if layer is None:
lyr = layer.get_layer(obj)
if lyr is None:
return None
if layer.ViewObject.UsePrintColor:
return layer.ViewObject.LinePrintColor
if lyr.ViewObject.UsePrintColor:
return lyr.ViewObject.LinePrintColor
return None

View File

@@ -1,7 +1,8 @@
# ***************************************************************************
# * (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2024 FreeCAD Project Association *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
@@ -33,20 +34,15 @@ from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
import FreeCADGui as Gui
import Draft_rc
import DraftVecUtils
import draftutils.groups as groups
import draftutils.todo as todo
import draftguitools.gui_base_original as gui_base_original
import draftguitools.gui_tool_utils as gui_tool_utils
import draftguitools.gui_trackers as trackers
from draftguitools import gui_base_original
from draftguitools import gui_tool_utils
from draftguitools import gui_trackers as trackers
from draftguitools.gui_subelements import SubelementHighlight
from draftutils import utils
from draftutils import todo
from draftutils.messages import _msg, _err, _toolmsg
from draftutils.translate import translate
from draftguitools.gui_subelements import SubelementHighlight
# The module is used to prevent complaints from code checkers (flake8)
True if Draft_rc.__name__ else False
class Move(gui_base_original.Modifier):
@@ -54,11 +50,10 @@ class Move(gui_base_original.Modifier):
def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Draft_Move',
'Accel': "M, V",
'MenuText': QT_TRANSLATE_NOOP("Draft_Move", "Move"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Move", "Moves the selected objects from one base point to another point.\nIf the \"copy\" option is active, it will create displaced copies.\nCTRL to snap, SHIFT to constrain.")}
return {"Pixmap": "Draft_Move",
"Accel": "M, V",
"MenuText": QT_TRANSLATE_NOOP("Draft_Move", "Move"),
"ToolTip": QT_TRANSLATE_NOOP("Draft_Move", "Moves the selected objects from one base point to another point.\nIf the \"copy\" option is active, it will create displaced copies.\nCTRL to snap, SHIFT to constrain.")}
def Activated(self):
"""Execute when the command is called."""
@@ -72,24 +67,18 @@ class Move(gui_base_original.Modifier):
def get_object_selection(self):
"""Get the object selection."""
if Gui.Selection.getSelectionEx():
if Gui.Selection.hasSelection():
return self.proceed()
self.ui.selectUi(on_close_call=self.finish)
_msg(translate("draft", "Select an object to move"))
self.call = \
self.view.addEventCallback("SoEvent", gui_tool_utils.selectObject)
self.call = self.view.addEventCallback("SoEvent", gui_tool_utils.selectObject)
def proceed(self):
"""Continue with the command after a selection has been made."""
if self.call:
self.view.removeEventCallback("SoEvent", self.call)
self.selected_objects = Gui.Selection.getSelection()
self.selected_objects = \
groups.get_group_contents(self.selected_objects,
addgroups=True,
spaces=True,
noarchchild=True)
self.selected_subelements = Gui.Selection.getSelectionEx()
self.selection = Gui.Selection.getSelectionEx("", 0)
Gui.doCommand("selection = FreeCADGui.Selection.getSelectionEx(\"\", 0)")
self.ui.lineUi(title=translate("draft", self.featureName), icon="Draft_Move")
self.ui.modUi()
if self.copymode:
@@ -184,122 +173,39 @@ class Move(gui_base_original.Modifier):
"""Set the ghost to display."""
for ghost in self.ghosts:
ghost.remove()
copy = self.ui.isCopy.isChecked()
if self.ui.isSubelementMode.isChecked():
self.ghosts = self.get_subelement_ghosts()
self.ghosts = self.get_subelement_ghosts(self.selection, copy)
if not self.ghosts:
_err(translate("draft", "No valid subelements selected"))
else:
self.ghosts = [trackers.ghostTracker(self.selected_objects)]
objs, places, _ = utils._modifiers_process_selection(self.selection, copy, add_movable_children=(not copy))
self.ghosts = [trackers.ghostTracker(objs, parent_places=places)]
def get_subelement_ghosts(self):
def get_subelement_ghosts(self, selection, copy):
"""Get ghost for the subelements (vertices, edges)."""
import Part
ghosts = []
for sel in Gui.Selection.getSelectionEx("", 0):
for sel in selection:
for sub in sel.SubElementNames if sel.SubElementNames else [""]:
if "Vertex" in sub or "Edge" in sub:
if (not copy and "Vertex" in sub) or "Edge" in sub:
shape = Part.getShape(sel.Object, sub, needSubElement=True, retType=0)
ghosts.append(trackers.ghostTracker(shape))
return ghosts
def move(self, is_copy=False):
"""Perform the move of the subelements or the entire object."""
if self.ui.isSubelementMode.isChecked():
self.move_subelements(is_copy)
def move(self, copy):
"""Perform the move of the subelement(s) or the entire object(s)."""
if copy:
cmd_name = translate("draft", "Copy")
else:
self.move_object(is_copy)
def move_subelements(self, is_copy):
"""Move the subelements."""
cmd_name = translate("draft", "Move")
Gui.addModule("Draft")
try:
if is_copy:
self.commit(translate("draft", "Copy"),
self.build_copy_subelements_command())
else:
self.commit(translate("draft", "Move"),
self.build_move_subelements_command())
except Exception:
_err(translate("draft", "Some subelements could not be moved."))
def build_copy_subelements_command(self):
"""Build the string to commit to copy the subelements."""
import Part
command = []
arguments = []
E = len("Edge")
for obj in self.selected_subelements:
for index, subelement in enumerate(obj.SubObjects):
if not isinstance(subelement, Part.Edge):
continue
_edge_index = int(obj.SubElementNames[index][E:]) - 1
_cmd = '['
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_edge_index) + ', '
_cmd += DraftVecUtils.toString(self.vector)
_cmd += ']'
arguments.append(_cmd)
all_args = ', '.join(arguments)
command.append('Draft.copy_moved_edges([' + all_args + '])')
command.append('FreeCAD.ActiveDocument.recompute()')
return command
def build_move_subelements_command(self):
"""Build the string to commit to move the subelements."""
import Part
command = []
V = len("Vertex")
E = len("Edge")
for obj in self.selected_subelements:
for index, subelement in enumerate(obj.SubObjects):
if isinstance(subelement, Part.Vertex):
_vertex_index = int(obj.SubElementNames[index][V:]) - 1
_cmd = 'Draft.move_vertex'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_vertex_index) + ', '
_cmd += DraftVecUtils.toString(self.vector)
_cmd += ')'
command.append(_cmd)
elif isinstance(subelement, Part.Edge):
_edge_index = int(obj.SubElementNames[index][E:]) - 1
_cmd = 'Draft.move_edge'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_edge_index) + ', '
_cmd += DraftVecUtils.toString(self.vector)
_cmd += ')'
command.append(_cmd)
command.append('FreeCAD.ActiveDocument.recompute()')
return command
def move_object(self, is_copy):
"""Move the object."""
_doc = 'FreeCAD.ActiveDocument.'
_selected = self.selected_objects
objects = '['
objects += ', '.join([_doc + obj.Name for obj in _selected])
objects += ']'
Gui.addModule("Draft")
_cmd = 'Draft.move'
_cmd += '('
_cmd += objects + ', '
_cmd += DraftVecUtils.toString(self.vector) + ', '
_cmd += 'copy=' + str(is_copy)
_cmd += ')'
_cmd_list = [_cmd,
'FreeCAD.ActiveDocument.recompute()']
_mode = "Copy" if is_copy else "Move"
self.commit(translate("draft", _mode),
_cmd_list)
cmd = "Draft.move(selection, "
cmd += DraftVecUtils.toString(self.vector) + ", "
cmd += "copy=" + str(copy) + ", "
cmd += "subelements=" + str(self.ui.isSubelementMode.isChecked()) + ")"
cmd_list = [cmd, "FreeCAD.ActiveDocument.recompute()"]
self.commit(cmd_name, cmd_list)
def numericInput(self, numx, numy, numz):
"""Validate the entry fields in the user interface.

View File

@@ -1,7 +1,8 @@
# ***************************************************************************
# * (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2024 FreeCAD Project Association *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
@@ -34,20 +35,15 @@ from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
import FreeCADGui as Gui
import Draft_rc
import DraftVecUtils
import draftutils.groups as groups
import draftutils.todo as todo
import draftguitools.gui_base_original as gui_base_original
import draftguitools.gui_tool_utils as gui_tool_utils
import draftguitools.gui_trackers as trackers
from FreeCAD import Units as U
from draftguitools import gui_base_original
from draftguitools import gui_tool_utils
from draftguitools import gui_trackers as trackers
from draftutils import utils
from draftutils import todo
from draftutils.messages import _msg, _err, _toolmsg
from draftutils.translate import translate
# The module is used to prevent complaints from code checkers (flake8)
True if Draft_rc.__name__ else False
from FreeCAD import Units as U
class Rotate(gui_base_original.Modifier):
@@ -55,12 +51,10 @@ class Rotate(gui_base_original.Modifier):
def GetResources(self):
"""Set icon, menu and tooltip."""
_tip = ()
return {'Pixmap': 'Draft_Rotate',
'Accel': "R, O",
'MenuText': QT_TRANSLATE_NOOP("Draft_Rotate", "Rotate"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Rotate", "Rotates the selected objects. Choose the center of rotation, then the initial angle, and then the final angle.\nIf the \"copy\" option is active, it will create rotated copies.\nCTRL to snap, SHIFT to constrain. Hold ALT and click to create a copy with each click.")}
return {"Pixmap": "Draft_Rotate",
"Accel": "R, O",
"MenuText": QT_TRANSLATE_NOOP("Draft_Rotate", "Rotate"),
"ToolTip": QT_TRANSLATE_NOOP("Draft_Rotate", "Rotates the selected objects. Choose the center of rotation, then the initial angle, and then the final angle.\nIf the \"copy\" option is active, it will create rotated copies.\nCTRL to snap, SHIFT to constrain. Hold ALT and click to create a copy with each click.")}
def Activated(self):
"""Execute when the command is called."""
@@ -73,24 +67,18 @@ class Rotate(gui_base_original.Modifier):
def get_object_selection(self):
"""Get the object selection."""
if Gui.Selection.getSelection():
if Gui.Selection.hasSelection():
return self.proceed()
self.ui.selectUi(on_close_call=self.finish)
_msg(translate("draft", "Select an object to rotate"))
self.call = \
self.view.addEventCallback("SoEvent", gui_tool_utils.selectObject)
self.call = self.view.addEventCallback("SoEvent", gui_tool_utils.selectObject)
def proceed(self):
"""Continue with the command after a selection has been made."""
if self.call:
self.view.removeEventCallback("SoEvent", self.call)
self.selected_objects = Gui.Selection.getSelection()
self.selected_objects = \
groups.get_group_contents(self.selected_objects,
addgroups=True,
spaces=True,
noarchchild=True)
self.selected_subelements = Gui.Selection.getSelectionEx()
self.selection = Gui.Selection.getSelectionEx("", 0)
Gui.doCommand("selection = FreeCADGui.Selection.getSelectionEx(\"\", 0)")
self.step = 0
self.center = None
self.ui.rotateSetCenterUi()
@@ -234,22 +222,25 @@ class Rotate(gui_base_original.Modifier):
"""Set the ghost to display."""
for ghost in self.ghosts:
ghost.remove()
copy = self.ui.isCopy.isChecked()
if self.ui.isSubelementMode.isChecked():
self.ghosts = self.get_subelement_ghosts()
self.ghosts = self.get_subelement_ghosts(self.selection, copy)
if not self.ghosts:
_err(translate("draft", "No valid subelements selected"))
else:
self.ghosts = [trackers.ghostTracker(self.selected_objects)]
objs, places, _ = utils._modifiers_process_selection(self.selection, copy, add_movable_children=(not copy))
self.ghosts = [trackers.ghostTracker(objs, parent_places=places)]
if self.center:
for ghost in self.ghosts:
ghost.center(self.center)
def get_subelement_ghosts(self):
def get_subelement_ghosts(self, selection, copy):
"""Get ghost for the subelements (vertices, edges)."""
import Part
ghosts = []
for sel in Gui.Selection.getSelectionEx("", 0):
for sel in selection:
for sub in sel.SubElementNames if sel.SubElementNames else [""]:
if "Vertex" in sub or "Edge" in sub:
if (not copy and "Vertex" in sub) or "Edge" in sub:
shape = Part.getShape(sel.Object, sub, needSubElement=True, retType=0)
ghosts.append(trackers.ghostTracker(shape))
return ghosts
@@ -272,113 +263,21 @@ class Rotate(gui_base_original.Modifier):
if cont or (cont is None and self.ui and self.ui.continueMode):
todo.ToDo.delayAfter(self.Activated, [])
def rotate(self, is_copy=False):
"""Perform the rotation of the subelements or the entire object."""
if self.ui.isSubelementMode.isChecked():
self.rotate_subelements(is_copy)
def rotate(self, copy):
"""Perform the rotation of the subelement(s) or the entire object(s)."""
if copy:
cmd_name = translate("draft", "Copy")
else:
self.rotate_object(is_copy)
def rotate_subelements(self, is_copy):
"""Rotate the subelements."""
cmd_name = translate("draft", "Rotate")
Gui.addModule("Draft")
try:
if is_copy:
self.commit(translate("draft", "Copy"),
self.build_copy_subelements_command())
else:
self.commit(translate("draft", "Rotate"),
self.build_rotate_subelements_command())
except Exception:
_err(translate("draft", "Some subelements could not be moved."))
def build_copy_subelements_command(self):
"""Build the string to commit to copy the subelements."""
import Part
command = []
arguments = []
E = len("Edge")
for obj in self.selected_subelements:
for index, subelement in enumerate(obj.SubObjects):
if not isinstance(subelement, Part.Edge):
continue
_edge_index = int(obj.SubElementNames[index][E:]) - 1
_cmd = '['
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_edge_index) + ', '
_cmd += str(math.degrees(self.angle)) + ', '
_cmd += DraftVecUtils.toString(self.center) + ', '
_cmd += DraftVecUtils.toString(self.wp.axis)
_cmd += ']'
arguments.append(_cmd)
all_args = ', '.join(arguments)
command.append('Draft.copy_rotated_edges([' + all_args + '])')
command.append('FreeCAD.ActiveDocument.recompute()')
return command
def build_rotate_subelements_command(self):
"""Build the string to commit to rotate the subelements."""
import Part
command = []
V = len("Vertex")
E = len("Edge")
for obj in self.selected_subelements:
for index, subelement in enumerate(obj.SubObjects):
if isinstance(subelement, Part.Vertex):
_vertex_index = int(obj.SubElementNames[index][V:]) - 1
_cmd = 'Draft.rotate_vertex'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_vertex_index) + ', '
_cmd += str(math.degrees(self.angle)) + ', '
_cmd += DraftVecUtils.toString(self.center) + ', '
_cmd += DraftVecUtils.toString(self.wp.axis)
_cmd += ')'
command.append(_cmd)
elif isinstance(subelement, Part.Edge):
_edge_index = int(obj.SubElementNames[index][E:]) - 1
_cmd = 'Draft.rotate_edge'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_edge_index) + ', '
_cmd += str(math.degrees(self.angle)) + ', '
_cmd += DraftVecUtils.toString(self.center) + ', '
_cmd += DraftVecUtils.toString(self.wp.axis)
_cmd += ')'
command.append(_cmd)
command.append('FreeCAD.ActiveDocument.recompute()')
return command
def rotate_object(self, is_copy):
"""Move the object."""
_doc = 'FreeCAD.ActiveDocument.'
_selected = self.selected_objects
objects = '['
objects += ','.join([_doc + obj.Name for obj in _selected])
objects += ']'
_cmd = 'Draft.rotate'
_cmd += '('
_cmd += objects + ', '
_cmd += str(math.degrees(self.angle)) + ', '
_cmd += DraftVecUtils.toString(self.center) + ', '
_cmd += 'axis=' + DraftVecUtils.toString(self.wp.axis) + ', '
_cmd += 'copy=' + str(is_copy)
_cmd += ')'
_cmd_list = [_cmd,
'FreeCAD.ActiveDocument.recompute()']
_mode = "Copy" if is_copy else "Rotate"
Gui.addModule("Draft")
self.commit(translate("draft", _mode),
_cmd_list)
cmd = "Draft.rotate(selection, "
cmd += str(math.degrees(self.angle)) + ", "
cmd += "center=" + DraftVecUtils.toString(self.center) + ", "
cmd += "axis=" + DraftVecUtils.toString(self.wp.axis) + ", "
cmd += "copy=" + str(copy) + ", "
cmd += "subelements=" + str(self.ui.isSubelementMode.isChecked()) + ")"
cmd_list = [cmd, "FreeCAD.ActiveDocument.recompute()"]
self.commit(cmd_name, cmd_list)
def numericInput(self, numx, numy, numz):
"""Validate the entry fields in the user interface.

View File

@@ -1,7 +1,8 @@
# ***************************************************************************
# * (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2024 FreeCAD Project Association *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
@@ -40,21 +41,17 @@ from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
import FreeCADGui as Gui
import Draft_rc
import DraftVecUtils
import draftutils.utils as utils
import draftutils.groups as groups
import draftutils.todo as todo
import draftguitools.gui_base_original as gui_base_original
import draftguitools.gui_tool_utils as gui_tool_utils
import draftguitools.gui_trackers as trackers
import drafttaskpanels.task_scale as task_scale
from draftguitools import gui_base_original
from draftguitools import gui_tool_utils
from draftguitools import gui_trackers as trackers
from draftutils import groups
from draftutils import params
from draftutils import utils
from draftutils import todo
from draftutils.messages import _msg, _err, _toolmsg
from draftutils.translate import translate
# The module is used to prevent complaints from code checkers (flake8)
True if Draft_rc.__name__ else False
from drafttaskpanels import task_scale
class Scale(gui_base_original.Modifier):
@@ -65,11 +62,10 @@ class Scale(gui_base_original.Modifier):
def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Draft_Scale',
'Accel': "S, C",
'MenuText': QT_TRANSLATE_NOOP("Draft_Scale", "Scale"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Scale", "Scales the selected objects from a base point.\nCTRL to snap, SHIFT to constrain, ALT to copy.")}
return {"Pixmap": "Draft_Scale",
"Accel": "S, C",
"MenuText": QT_TRANSLATE_NOOP("Draft_Scale", "Scale"),
"ToolTip": QT_TRANSLATE_NOOP("Draft_Scale", "Scales the selected objects from a base point.\nCTRL to snap, SHIFT to constrain, ALT to copy.")}
def Activated(self):
"""Execute when the command is called."""
@@ -85,18 +81,14 @@ class Scale(gui_base_original.Modifier):
return self.proceed()
self.ui.selectUi(on_close_call=self.finish)
_msg(translate("draft", "Select an object to scale"))
self.call = self.view.addEventCallback("SoEvent",
gui_tool_utils.selectObject)
self.call = self.view.addEventCallback("SoEvent", gui_tool_utils.selectObject)
def proceed(self):
"""Proceed with execution of the command after selection."""
if self.call:
self.view.removeEventCallback("SoEvent", self.call)
self.selected_objects = Gui.Selection.getSelection()
self.selected_objects = \
groups.get_group_contents(self.selected_objects)
self.selected_subelements = Gui.Selection.getSelectionEx()
self.selection = Gui.Selection.getSelectionEx("", 0)
Gui.doCommand("selection = FreeCADGui.Selection.getSelectionEx(\"\", 0)")
self.refs = []
self.ui.pointUi(title=translate("draft",self.featureName), icon="Draft_Scale")
self.ui.isRelative.hide()
@@ -111,24 +103,50 @@ class Scale(gui_base_original.Modifier):
"""Set the ghost to display."""
for ghost in self.ghosts:
ghost.remove()
if self.task and self.task.isSubelementMode.isChecked():
self.ghosts = self.get_subelement_ghosts()
if self.task is None:
copy = params.get_param("ScaleCopy")
clone = params.get_param("ScaleClone")
subelements = params.get_param("SubelementMode")
else:
self.ghosts = [trackers.ghostTracker(self.selected_objects)]
copy = self.task.isCopy.isChecked()
clone = self.task.isClone.isChecked()
subelements = self.task.isSubelementMode.isChecked()
if subelements:
self.ghosts = self.get_subelement_ghosts(self.selection, copy)
if not self.ghosts:
_err(translate("draft", "No valid subelements selected"))
else:
objs, places, _ = utils._modifiers_process_selection(self.selection, (copy or clone), scale=True)
self.ghosts = [trackers.ghostTracker(objs, parent_places=places)]
def get_subelement_ghosts(self):
def get_subelement_ghosts(self, selection, copy):
"""Get ghost for the subelements (vertices, edges)."""
import Part
ghosts = []
for sel in Gui.Selection.getSelectionEx("", 0):
for sel in selection:
for sub in sel.SubElementNames if sel.SubElementNames else [""]:
if "Vertex" in sub or "Edge" in sub:
if (not copy and "Vertex" in sub) or "Edge" in sub:
shape = Part.getShape(sel.Object, sub, needSubElement=True, retType=0)
ghosts.append(trackers.ghostTracker(shape))
return ghosts
def pickRef(self):
def scale_ghosts(self, x, y, z, rel):
"""Scale the preview of the object."""
delta = App.Vector(x, y, z)
if rel:
delta = self.wp.get_global_coords(delta)
for ghost in self.ghosts:
ghost.scale(delta)
# calculate a correction factor depending on the scaling center
corr = App.Vector(self.node[0])
corr.scale(*delta)
corr = (corr.sub(self.node[0])).negative()
for ghost in self.ghosts:
ghost.flip_normals(x * y * z < 0)
ghost.move(corr)
ghost.on()
def pick_ref(self):
"""Pick a point of reference."""
self.pickmode = True
if self.node:
@@ -174,213 +192,32 @@ class Scale(gui_base_original.Modifier):
Scales the subelements, or with a clone, or just general scaling.
"""
self.delta = App.Vector(self.task.xValue.value(),
self.task.yValue.value(),
self.task.zValue.value())
self.center = self.node[0]
if self.task.isSubelementMode.isChecked():
self.scale_subelements()
elif self.task.isClone.isChecked():
self.scale_with_clone()
else:
self.scale_object()
self.finish()
sx = self.task.xValue.value()
sy = self.task.yValue.value()
sz = self.task.zValue.value()
if sx * sy * sz == 0:
_err(translate("draft", "Zero scale factor not allowed"))
self.finish()
return
def scale_subelements(self):
"""Scale only the subelements if the appropriate option is set.
The subelements operations only really work with polylines (Wires)
because internally the functions `scale_vertex` and `scale_edge`
only work with polylines that have a `Points` property.
BUG: the code should not cause an error. It should check that
the selected object is not a rectangle or another object
that can't be used with `scale_vertex` and `scale_edge`.
"""
Gui.addModule("Draft")
try:
if self.task.isCopy.isChecked():
self.commit(translate("draft", "Copy"),
self.build_copy_subelements_command())
else:
self.commit(translate("draft", "Scale"),
self.build_scale_subelements_command())
except Exception:
_err(translate("draft", "Some subelements could not be scaled."))
def scale_with_clone(self):
"""Scale with clone."""
self.delta = App.Vector(sx, sy, sz)
if self.task.relative.isChecked():
self.delta = self.wp.get_global_coords(self.delta)
Gui.addModule("Draft")
_doc = 'FreeCAD.ActiveDocument.'
_selected = self.selected_objects
objects = '['
objects += ', '.join([_doc + obj.Name for obj in _selected])
objects += ']'
self.center = self.node[0]
if self.task.isCopy.isChecked():
_cmd_name = translate("draft", "Copy")
cmd_name = translate("draft", "Copy")
else:
_cmd_name = translate("draft", "Scale")
# the correction translation of the clone placement is
# (node[0] - clone.Placement.Base) - (node[0] - clone.Placement.Base)\
# .scale(delta.x,delta.y,delta.z)
# equivalent to:
# (node[0] - clone.Placement.Base)\
# .scale(1-delta.x,1-delta.y,1-delta.z)
str_node0 = DraftVecUtils.toString(self.node[0])
str_delta = DraftVecUtils.toString(self.delta)
str_delta_corr = DraftVecUtils.toString(App.Vector(1,1,1) - self.delta)
_cmd = 'Draft.make_clone'
_cmd += '('
_cmd += objects + ', '
_cmd += 'forcedraft=True'
_cmd += ')'
_cmd_list = ['clone = ' + _cmd,
'clone.Scale = ' + str_delta,
'clone_corr = (' + str_node0 + ' - clone.Placement.Base)'\
+ '.scale(*'+ str_delta_corr + ')',
'clone.Placement.move(clone_corr)',
'FreeCAD.ActiveDocument.recompute()']
self.commit(_cmd_name, _cmd_list)
def build_copy_subelements_command(self):
"""Build the string to commit to copy the subelements."""
import Part
command = []
arguments = []
E = len("Edge")
for obj in self.selected_subelements:
for index, subelement in enumerate(obj.SubObjects):
if not isinstance(subelement, Part.Edge):
continue
_edge_index = int(obj.SubElementNames[index][E:]) - 1
_cmd = '['
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_edge_index) + ', '
_cmd += DraftVecUtils.toString(self.delta) + ', '
_cmd += DraftVecUtils.toString(self.center)
_cmd += ']'
arguments.append(_cmd)
all_args = ', '.join(arguments)
command.append('Draft.copy_scaled_edges([' + all_args + '])')
command.append('FreeCAD.ActiveDocument.recompute()')
return command
def build_scale_subelements_command(self):
"""Build the strings to commit to scale the subelements."""
import Part
command = []
V = len("Vertex")
E = len("Edge")
for obj in self.selected_subelements:
for index, subelement in enumerate(obj.SubObjects):
if isinstance(subelement, Part.Vertex):
_vertex_index = int(obj.SubElementNames[index][V:]) - 1
_cmd = 'Draft.scale_vertex'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_vertex_index) + ', '
_cmd += DraftVecUtils.toString(self.delta) + ', '
_cmd += DraftVecUtils.toString(self.center)
_cmd += ')'
command.append(_cmd)
elif isinstance(subelement, Part.Edge):
_edge_index = int(obj.SubElementNames[index][E:]) - 1
_cmd = 'Draft.scale_edge'
_cmd += '('
_cmd += 'FreeCAD.ActiveDocument.'
_cmd += obj.ObjectName + ', '
_cmd += str(_edge_index) + ', '
_cmd += DraftVecUtils.toString(self.delta) + ', '
_cmd += DraftVecUtils.toString(self.center)
_cmd += ')'
command.append(_cmd)
command.append('FreeCAD.ActiveDocument.recompute()')
return command
def is_scalable(self, obj):
"""Return True only for the supported objects.
Currently it only supports `Rectangle`, `Wire`, `Annotation`
and `BSpline`.
"""
t = utils.getType(obj)
if t in ["Rectangle", "Wire", "Annotation", "BSpline","Image::ImagePlane"]:
# TODO: support more types in Draft.scale
return True
else:
return False
def scale_object(self):
"""Scale the object."""
if self.task.relative.isChecked():
self.delta =self.wp.get_global_coords(self.delta)
goods = []
bads = []
for obj in self.selected_objects:
if self.is_scalable(obj):
goods.append(obj)
else:
bads.append(obj)
if bads:
if len(bads) == 1:
m = translate("draft", "Unable to scale object:")
m += " "
m += bads[0].Label
else:
m = translate("draft", "Unable to scale objects:")
m += " "
m += ", ".join([o.Label for o in bads])
m += " - " + translate("draft","This object type cannot be scaled directly. Please use the clone method.")
_err(m)
if goods:
_doc = 'FreeCAD.ActiveDocument.'
objects = '['
objects += ', '.join([_doc + obj.Name for obj in goods])
objects += ']'
Gui.addModule("Draft")
if self.task.isCopy.isChecked():
_cmd_name = translate("draft", "Copy")
else:
_cmd_name = translate("draft", "Scale")
_cmd = 'Draft.scale'
_cmd += '('
_cmd += objects + ', '
_cmd += 'scale=' + DraftVecUtils.toString(self.delta) + ', '
_cmd += 'center=' + DraftVecUtils.toString(self.center) + ', '
_cmd += 'copy=' + str(self.task.isCopy.isChecked())
_cmd += ')'
_cmd_list = ['ss = ' + _cmd,
'FreeCAD.ActiveDocument.recompute()']
self.commit(_cmd_name, _cmd_list)
def scaleGhost(self, x, y, z, rel):
"""Scale the preview of the object."""
delta = App.Vector(x, y, z)
if rel:
delta = self.wp.get_global_coords(delta)
for ghost in self.ghosts:
ghost.scale(delta)
# calculate a correction factor depending on the scaling center
corr = App.Vector(self.node[0].x, self.node[0].y, self.node[0].z)
corr.scale(delta.x, delta.y, delta.z)
corr = (corr.sub(self.node[0])).negative()
for ghost in self.ghosts:
ghost.move(corr)
ghost.on()
cmd_name = translate("draft", "Scale")
Gui.addModule("Draft")
cmd = "Draft.scale(selection, "
cmd += "scale=" + DraftVecUtils.toString(self.delta) + ", "
cmd += "center=" + DraftVecUtils.toString(self.center) + ", "
cmd += "copy=" + str(self.task.isCopy.isChecked()) + ", "
cmd += "clone=" + str(self.task.isClone.isChecked()) + ", "
cmd += "subelements=" + str(self.task.isSubelementMode.isChecked()) + ")"
cmd_list = [cmd, "FreeCAD.ActiveDocument.recompute()"]
self.commit(cmd_name, cmd_list)
self.finish()
def numericInput(self, numx, numy, numz):
"""Validate the entry fields in the user interface.

View File

@@ -700,17 +700,21 @@ class ghostTracker(Tracker):
You can pass it an object or a list of objects, or a shape.
"""
def __init__(self, sel, dotted=False, scolor=None, swidth=None, mirror=False):
def __init__(self, sel, dotted=False, scolor=None, swidth=None, mirror=False, parent_places=None):
self.trans = coin.SoTransform()
self.trans.translation.setValue([0, 0, 0])
self.children = [self.trans]
rootsep = coin.SoSeparator()
self.rootsep = coin.SoSeparator()
if not isinstance(sel, list):
sel = [sel]
for obj in sel:
for idx, obj in enumerate(sel):
if parent_places is not None:
parent_place = parent_places[idx]
else:
parent_place = None
import Part
if not isinstance(obj, Part.Vertex):
rootsep.addChild(self.getNode(obj))
self.rootsep.addChild(self.getNode(obj, parent_place))
else:
self.coords = coin.SoCoordinate3()
self.coords.point.setValue((obj.X, obj.Y, obj.Z))
@@ -721,10 +725,13 @@ class ghostTracker(Tracker):
selnode.addChild(self.coords)
selnode.addChild(self.marker)
node.addChild(selnode)
rootsep.addChild(node)
self.rootsep.addChild(node)
if mirror is True:
self._flip(rootsep)
self.children.append(rootsep)
self._do_flip(self.rootsep)
self.flipped = True
else:
self.flipped = False
self.children.append(self.rootsep)
super().__init__(dotted, scolor, swidth,
children=self.children, name="ghostTracker")
self.setColor(scolor)
@@ -760,26 +767,32 @@ class ghostTracker(Tracker):
"""Scale the ghost by the given factor."""
self.trans.scaleFactor.setValue([delta.x, delta.y, delta.z])
def getNode(self, obj):
def getNode(self, obj, parent_place=None):
"""Return a coin node representing the given object."""
import Part
if isinstance(obj, Part.Shape):
return self.getNodeLight(obj)
elif obj.isDerivedFrom("Part::Feature"):
return self.getNodeFull(obj)
else:
return self.getNodeFull(obj)
return self.getNodeFull(obj, parent_place)
def getNodeFull(self, obj):
def getNodeFull(self, obj, parent_place=None):
"""Get a coin node which is a copy of the current representation."""
sep = coin.SoSeparator()
try:
sep.addChild(obj.ViewObject.RootNode.copy())
# add Part container offset
if hasattr(obj, "getGlobalPlacement") and obj.Placement != obj.getGlobalPlacement():
if parent_place is not None:
if hasattr(obj, "Placement"):
gpl = parent_place * obj.Placement
else:
gpl = parent_place
elif hasattr(obj, "getGlobalPlacement"):
gpl = obj.getGlobalPlacement()
else:
gpl = None
if gpl is not None:
transform = gui_utils.find_coin_node(sep.getChild(0), coin.SoTransform)
if transform is not None:
gpl = obj.getGlobalPlacement()
transform.translation.setValue(tuple(gpl.Base))
transform.rotation.setValue(gpl.Rotation.Q)
except Exception:
@@ -826,7 +839,17 @@ class ghostTracker(Tracker):
matrix.A41, matrix.A42, matrix.A43, matrix.A44)
self.trans.setMatrix(m)
def _flip(self, root):
def flip_normals(self, flip):
if flip:
if not self.flipped:
self._do_flip(self.rootsep)
self.flipped = True
else:
if self.flipped:
self._do_flip(self.rootsep)
self.flipped = False
def _do_flip(self, root):
"""Flip the normals of the coin faces."""
# Code by wmayer:
# https://forum.freecad.org/viewtopic.php?p=702640#p702640

View File

@@ -33,31 +33,35 @@ import FreeCAD as App
import DraftVecUtils
from draftobjects.base import DraftObject
from draftutils import gui_utils
from draftutils.messages import _wrn
from draftutils.translate import translate
class Clone(DraftObject):
"""The Clone object"""
def __init__(self,obj):
def __init__(self, obj):
self.set_properties(obj)
super().__init__(obj, "Clone")
_tip = QT_TRANSLATE_NOOP("App::Property",
"The objects included in this clone")
obj.addProperty("App::PropertyLinkListGlobal", "Objects",
"Draft", _tip)
_tip = QT_TRANSLATE_NOOP("App::Property",
"The scale factor of this clone")
obj.addProperty("App::PropertyVector", "Scale",
"Draft", _tip)
_tip = QT_TRANSLATE_NOOP("App::Property",
"If Clones includes several objects,\n"
"set True for fusion or False for compound")
obj.addProperty("App::PropertyBool", "Fuse",
"Draft", _tip)
obj.Scale = App.Vector(1,1,1)
def set_properties(self, obj):
pl = obj.PropertiesList
if not "Objects" in pl:
_tip = QT_TRANSLATE_NOOP("App::Property", "The objects included in this clone")
obj.addProperty("App::PropertyLinkListGlobal", "Objects", "Draft", _tip)
if not "Scale" in pl:
_tip = QT_TRANSLATE_NOOP("App::Property", "The scale factor of this clone")
obj.addProperty("App::PropertyVector", "Scale", "Draft", _tip)
obj.Scale = App.Vector(1, 1, 1)
if not "Fuse" in pl:
_tip = QT_TRANSLATE_NOOP("App::Property",
"If Clones includes several objects,\n"
"set True for fusion or False for compound")
obj.addProperty("App::PropertyBool", "Fuse", "Draft", _tip)
if not "ForceCompound" in pl:
_tip = QT_TRANSLATE_NOOP("App::Property", "Always create a compound")
obj.addProperty("App::PropertyBool", "ForceCompound", "Draft", _tip)
def onDocumentRestored(self, obj):
super().onDocumentRestored(obj)
@@ -65,9 +69,14 @@ class Clone(DraftObject):
gui_utils.restore_view_object(
obj, vp_module="view_clone", vp_class="ViewProviderClone", format_ref=ref
)
if hasattr(obj, "ForceCompound"):
return
self.set_properties(obj)
_wrn("v1.1, " + obj.Label + ", " + translate("draft", "added 'ForceCompound' property"))
def join(self,obj,shapes):
fuse = getattr(obj, 'Fuse', False)
def join(self, obj, shapes):
fuse = getattr(obj, "Fuse", False)
force_compound = getattr(obj, "ForceCompound", False)
if fuse:
tmps = []
for s in shapes:
@@ -79,9 +88,12 @@ class Clone(DraftObject):
for s in shapes:
tmps += s.Edges
shapes = tmps
if len(shapes) == 1:
return shapes[0]
import Part
if len(shapes) == 1:
if force_compound:
return Part.makeCompound([shapes[0]])
else:
return shapes[0]
if fuse:
try:
sh = shapes[0].multiFuse(shapes[1:])
@@ -89,7 +101,10 @@ class Clone(DraftObject):
except Exception:
pass
else:
return sh
if force_compound:
return Part.makeCompound([sh])
else:
return sh
return Part.makeCompound(shapes)
def execute(self,obj):

View File

@@ -320,6 +320,14 @@ class LinearDimension(DimensionBase):
if hasattr(obj, "Support"):
obj.setPropertyStatus('Support', 'Hidden')
def transform(self, obj, pla):
"""Transform the object by applying a placement."""
obj.Start = pla.multVec(obj.Start)
obj.End = pla.multVec(obj.End)
obj.Dimline = pla.multVec(obj.Dimline)
obj.Normal = pla.Rotation.multVec(obj.Normal)
obj.Direction = pla.Rotation.multVec(obj.Direction)
def execute(self, obj):
"""Execute when the object is created or recomputed.
@@ -571,6 +579,24 @@ class AngularDimension(DimensionBase):
return
super().update_properties_0v21(obj, vobj)
def transform(self, obj, pla):
"""Transform the object by applying a placement."""
import Part
new_normal = pla.Rotation.multVec(obj.Normal)
c_old = Part.makeCircle(1, App.Vector(), obj.Normal)
c_tra = c_old.transformShape((pla * c_old.Placement).Rotation.Matrix)
c_new = Part.makeCircle(1, App.Vector(), new_normal)
delta_angle = math.degrees(c_new.Curve.parameter(c_tra.firstVertex().Point))
first_angle = (obj.FirstAngle.Value + delta_angle) % 360
last_angle = (obj.LastAngle.Value + delta_angle) % 360
obj.Center = pla.multVec(obj.Center)
obj.Dimline = pla.multVec(obj.Dimline)
obj.Normal = new_normal
obj.FirstAngle = first_angle
obj.LastAngle = last_angle
def execute(self, obj):
"""Execute when the object is created or recomputed.

View File

@@ -32,6 +32,7 @@ from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
from draftutils import gui_utils
from draftutils import utils
from draftutils.messages import _wrn
from draftutils.translate import translate
@@ -160,4 +161,21 @@ class LayerContainer:
if state:
self.Type = state
# Similar function as in view_layer.py
def get_layer(obj):
"""Get the layer the object belongs to."""
finds = obj.Document.findObjects(Name="LayerContainer")
if not finds:
return None
# First look in the LayerContainer:
for layer in finds[0].Group:
if utils.get_type(layer) == "Layer" and obj in layer.Group:
return layer
# If not found, look through all App::FeaturePython objects (not just layers):
for find in obj.Document.findObjects(Type="App::FeaturePython"):
if utils.get_type(find) == "Layer" and obj in find.Group:
return find
return None
## @}

View File

@@ -55,21 +55,21 @@ class ScaleTaskPanel:
self.xLabel = QtWidgets.QLabel()
layout.addWidget(self.xLabel, 0, 0, 1, 1)
self.xValue = QtWidgets.QDoubleSpinBox()
self.xValue.setRange(0.0000001, 1000000.0)
self.xValue.setRange(-1000000.0, 1000000.0)
self.xValue.setDecimals(decimals)
self.xValue.setValue(1)
layout.addWidget(self.xValue,0,1,1,1)
self.yLabel = QtWidgets.QLabel()
layout.addWidget(self.yLabel,1,0,1,1)
self.yValue = QtWidgets.QDoubleSpinBox()
self.yValue.setRange(0.0000001, 1000000.0)
self.yValue.setRange(-1000000.0, 1000000.0)
self.yValue.setDecimals(decimals)
self.yValue.setValue(1)
layout.addWidget(self.yValue,1,1,1,1)
self.zLabel = QtWidgets.QLabel()
layout.addWidget(self.zLabel,2,0,1,1)
self.zValue = QtWidgets.QDoubleSpinBox()
self.zValue.setRange(0.0000001, 1000000.0)
self.zValue.setRange(-1000000.0, 1000000.0)
self.zValue.setDecimals(decimals)
self.zValue.setValue(1)
layout.addWidget(self.zValue,2,1,1,1)
@@ -83,6 +83,7 @@ class ScaleTaskPanel:
self.isCopy.setChecked(params.get_param("ScaleCopy"))
layout.addWidget(self.isCopy,5,0,1,2)
self.isSubelementMode = QtWidgets.QCheckBox()
self.isSubelementMode.setChecked(params.get_param("SubelementMode"))
layout.addWidget(self.isSubelementMode,6,0,1,2)
self.isClone = QtWidgets.QCheckBox()
layout.addWidget(self.isClone,7,0,1,2)
@@ -112,7 +113,7 @@ class ScaleTaskPanel:
"""Set the relative scaling."""
params.set_param("ScaleRelative", state)
if self.sourceCmd:
self.sourceCmd.scaleGhost(self.xValue.value(),self.yValue.value(),self.zValue.value(),self.relative.isChecked())
self.sourceCmd.scale_ghosts(self.xValue.value(),self.yValue.value(),self.zValue.value(),self.relative.isChecked())
def setCopy(self, state):
"""Set the scale and copy option."""
@@ -121,11 +122,12 @@ class ScaleTaskPanel:
self.isClone.setChecked(False)
def setSubelementMode(self, state):
params.set_param("SubelementMode", state)
if state and self.isClone.isChecked():
self.isClone.setChecked(False)
if self.sourceCmd:
self.sourceCmd.set_ghosts()
self.sourceCmd.scaleGhost(self.xValue.value(),self.yValue.value(),self.zValue.value(),self.relative.isChecked())
self.sourceCmd.scale_ghosts(self.xValue.value(),self.yValue.value(),self.zValue.value(),self.relative.isChecked())
def setClone(self, state):
"""Set the clone and scale option."""
@@ -145,7 +147,7 @@ class ScaleTaskPanel:
if not self.zValue.hasFocus():
self.zValue.setValue(val)
if self.sourceCmd:
self.sourceCmd.scaleGhost(self.xValue.value(),self.yValue.value(),self.zValue.value(),self.relative.isChecked())
self.sourceCmd.scale_ghosts(self.xValue.value(),self.yValue.value(),self.zValue.value(),self.relative.isChecked())
def retranslateUi(self, widget=None):
"""Translate the various widgets"""
@@ -163,7 +165,7 @@ class ScaleTaskPanel:
def pickRef(self):
"""Pick a reference point from the calling class."""
if self.sourceCmd:
self.sourceCmd.pickRef()
self.sourceCmd.pick_ref()
def accept(self):
"""Execute when clicking the OK button."""

View File

@@ -680,7 +680,7 @@ class DraftModification(test_base.DraftTestCaseDoc):
obj.Shape = shp
obj.Placement.Base = base
self.doc.recompute()
Draft.scale([obj], sca, cen, False)
obj = Draft.scale(obj, sca, cen, False)
self.doc.recompute()
# check endpoints of arcs:
@@ -724,7 +724,7 @@ class DraftModification(test_base.DraftTestCaseDoc):
obj.Shape = shp
obj.Placement.Base = base
self.doc.recompute()
Draft.scale([obj], sca, cen, False)
obj = Draft.scale(obj, sca, cen, False)
self.doc.recompute()
newPts = [Vector( 5.0, 5.5, 0.0),
@@ -750,7 +750,7 @@ class DraftModification(test_base.DraftTestCaseDoc):
obj = Draft.make_rectangle(len, hgt)
obj.Placement.Base = base
self.doc.recompute()
Draft.scale([obj], sca, cen, False)
obj = Draft.scale(obj, sca, cen, False)
self.doc.recompute()
newBase = Vector(5.0, 5.5, 0.0)
@@ -782,14 +782,15 @@ class DraftModification(test_base.DraftTestCaseDoc):
obj = Draft.make_bspline(pts, False)
obj.Placement.Base = base
self.doc.recompute()
Draft.scale([obj], sca, cen, False)
obj = Draft.scale(obj, sca, cen, False)
self.doc.recompute()
pla = obj.Placement
newPts = [Vector( 5.0, 5.5, 0.0),
Vector( 9.0, 14.5, 0.0),
Vector(13.0, 5.5, 0.0)]
for i in range(3):
self.assertTrue(obj.Points[i].add(base).isEqual(newPts[i], 1e-6),
self.assertTrue(pla.multVec(obj.Points[i]).isEqual(newPts[i], 1e-6),
"'{}' failed".format(operation))
def test_scale_wire(self):
@@ -808,7 +809,7 @@ class DraftModification(test_base.DraftTestCaseDoc):
obj = Draft.make_wire(pts, True)
obj.Placement.Base = base
self.doc.recompute()
Draft.scale([obj], sca, cen, False)
obj = Draft.scale(obj, sca, cen, False)
self.doc.recompute()
newPts = [Vector( 5.0, 5.5, 0.0),

View File

@@ -675,10 +675,12 @@ def select(objs=None, gui=App.GuiUp):
Parameters
----------
objs: list of App::DocumentObject, optional
objs: list of App::DocumentObjects or tuples, or a single object or tuple, optional
It defaults to `None`.
Any type of scripted object.
It may be a list of objects or a single object.
Format for tuples:
`(doc.Name or "", sel.Object.Name, sel.SubElementName or "")`
For example (Box nested in Part):
`("", "Part", "Box.Edge1")`
gui: bool, optional
It defaults to the value of `App.GuiUp`, which is `True`
@@ -689,12 +691,21 @@ def select(objs=None, gui=App.GuiUp):
"""
if gui:
Gui.Selection.clearSelection()
if objs:
if objs is not None:
if not isinstance(objs, list):
objs = [objs]
for obj in objs:
if obj:
Gui.Selection.addSelection(obj)
if not obj:
continue
if isinstance(obj, tuple):
Gui.Selection.addSelection(*obj)
continue
try:
if not obj.isAttachedToDocument():
continue
except:
continue
Gui.Selection.addSelection(obj)
def load_texture(filename, size=None, gui=App.GuiUp):

View File

@@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-
# ***************************************************************************
# * (c) 2009, 2010 *
# * Yorik van Havre <yorik@uncreated.net>, Ken Cline <cline@frii.com> *
# * (c) 2019 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2019 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * Copyright (c) 2024 The FreeCAD Project Association *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
@@ -40,7 +41,7 @@ import PySide.QtCore as QtCore
import FreeCAD as App
from draftutils import params
from draftutils.messages import _wrn, _err, _log
from draftutils.messages import _wrn, _err, _log
from draftutils.translate import translate
# TODO: move the functions that require the graphical interface
@@ -174,7 +175,7 @@ def type_check(args_and_types, name="?"):
for v, t in args_and_types:
if not isinstance(v, t):
w = "typecheck[{}]: '{}' is not {}".format(name, v, t)
_wrn(w)
_err(w)
raise TypeError("Draft." + str(name))
@@ -884,26 +885,105 @@ def get_rgba_tuple(color, typ=1.0):
return color
def filter_objects_for_modifiers(objects, isCopied=False):
filteredObjects = []
for obj in objects:
if hasattr(obj, "MoveBase") and obj.MoveBase and obj.Base:
def _modifiers_process_subselection(sels, copy):
data_list = []
sel_info = []
for sel in sels:
for sub in sel.SubElementNames if sel.SubElementNames else [""]:
if not ("Vertex" in sub or "Edge" in sub):
continue
if copy and "Vertex" in sub:
continue
obj = sel.Object.getSubObject(sub, 1)
pla = sel.Object.getSubObject(sub, 3)
if "Vertex" in sub:
vert_idx = int(sub.rpartition("Vertex")[2]) - 1
edge_idx = -1
else:
vert_idx = -1
edge_idx = int(sub.rpartition("Edge")[2]) - 1
data_list.append((obj, vert_idx, edge_idx, pla))
sel_info.append(("", sel.Object.Name, sub))
return data_list, sel_info
def _modifiers_process_selection(sels, copy, scale=False, add_movable_children=False):
# Only when creating ghosts and if copy is False, should add_movable_children be True.
objects = []
places = []
sel_info = []
for sel in sels:
for sub in sel.SubElementNames if sel.SubElementNames else [""]:
obj = sel.Object.getSubObject(sub, 1)
# Get the global placement of the parent:
if obj == sel.Object:
pla = App.Placement()
else:
pla = sel.Object.getSubObject(sub.rpartition(obj.Name)[0], 3)
objs = _modifiers_get_group_contents(obj)
if add_movable_children:
children = []
for obj in objs:
children.extend(_modifiers_get_movable_children(obj))
objs.extend(children)
objs = _modifiers_filter_objects(objs, copy, scale)
objects.extend(objs)
places.extend(len(objs) * [pla])
if "." in sub:
sub = sub.rpartition(".")[0] + "."
elif "Face" in sub or "Edge" in sub or "Vertex" in sub:
sub = ""
sel_info.append(("", sel.Object.Name, sub))
return objects, places, sel_info
def _modifiers_get_group_contents(obj):
from draftutils import groups
return groups.get_group_contents(obj, addgroups=True, spaces=True, noarchchild=True)
def _modifiers_get_movable_children(obj):
result = []
if hasattr(obj, "Proxy") and hasattr(obj.Proxy, "getMovableChildren"):
children = obj.Proxy.getMovableChildren(obj)
result.extend(children)
for child in children:
result.extend(_modifiers_get_movable_children(child))
return result
def _modifiers_filter_objects(objs, copy, scale=False):
def is_scalable(obj):
if hasattr(obj, "Placement") and hasattr(obj, "Shape"):
return True
if obj.isDerivedFrom("App::DocumentObjectGroup"):
return True
if obj.isDerivedFrom("App::Annotation"):
return True
if obj.isDerivedFrom("Image::ImagePlane"):
return True
return False
result = []
for obj in objs:
if not copy and hasattr(obj, "MoveBase") and obj.MoveBase and obj.Base:
parents = []
for parent in obj.Base.InList:
if parent.isDerivedFrom("Part::Feature"):
parents.append(parent.Name)
if len(parents) > 1:
warningMessage = translate("draft", "%s shares a base with %d other objects. Please check if you want to modify this.") % (obj.Name,len(parents) - 1)
App.Console.PrintError(warningMessage)
if App.GuiUp:
Gui.getMainWindow().showMessage(warningMessage, 0)
filteredObjects.append(obj.Base)
elif hasattr(obj,"Placement") and obj.getEditorMode("Placement") == ["ReadOnly"] and not isCopied:
App.Console.PrintError(translate("draft", "%s cannot be modified because its placement is readonly.") % obj.Name)
continue
else:
filteredObjects.append(obj)
return filteredObjects
message = translate("draft", "%s shares a base with %d other objects. Please check if you want to modify this.") % (obj.Name,len(parents) - 1)
_err(message)
if not scale or utils.get_type(obj.Base) == "Wire":
result.append(obj.Base)
elif not copy \
and hasattr(obj, "Placement") \
and "ReadOnly" in obj.getEditorMode("Placement"):
_err(translate("draft", "%s cannot be modified because its placement is readonly") % obj.Name)
elif not scale or is_scalable(obj):
result.append(obj)
return result
def is_closed_edge(edge_index, object):

View File

@@ -35,6 +35,7 @@ from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD as App
import FreeCADGui as Gui
from draftutils import gui_utils
from draftutils import params
from draftutils.translate import translate
from draftviewproviders.view_draft_annotation import ViewProviderDraftAnnotation
@@ -74,7 +75,6 @@ class ViewProviderText(ViewProviderDraftAnnotation):
self.Object = vobj.Object
# Main attributes of the Coin scenegraph
self.trans = coin.SoTransform()
self.mattext = coin.SoMaterial()
self.font = coin.SoFont()
self.text_wld = coin.SoAsciiText() # World orientation. Can be oriented in 3D space.
@@ -90,14 +90,12 @@ class ViewProviderText(ViewProviderDraftAnnotation):
self.text_scr.justification = coin.SoText2.LEFT
self.node_wld = coin.SoGroup()
self.node_wld.addChild(self.trans)
self.node_wld.addChild(self.mattext)
self.node_wld.addChild(textdrawstyle)
self.node_wld.addChild(self.font)
self.node_wld.addChild(self.text_wld)
self.node_scr = coin.SoGroup()
self.node_scr.addChild(self.trans)
self.node_scr.addChild(self.mattext)
self.node_scr.addChild(textdrawstyle)
self.node_scr.addChild(self.font)
@@ -122,8 +120,10 @@ class ViewProviderText(ViewProviderDraftAnnotation):
self.text_scr.string.setValues(_list)
elif prop == "Placement":
self.trans.translation.setValue(obj.Placement.Base)
self.trans.rotation.setValue(obj.Placement.Rotation.Q)
transform = gui_utils.find_coin_node(obj.ViewObject.RootNode, coin.SoTransform)
if transform:
transform.translation.setValue(obj.Placement.Base)
transform.rotation.setValue(obj.Placement.Rotation.Q)
def onChanged(self, vobj, prop):
"""Execute when a view property is changed."""