- PEP8 cleanup of the Geo Editor

This commit is contained in:
Marius Stanciu
2019-05-22 15:37:07 +03:00
committed by Marius
parent cffcbb2410
commit f400294027
3 changed files with 222 additions and 235 deletions

View File

@@ -95,7 +95,7 @@ class App(QtCore.QObject):
# Version # Version
version = 8.917 version = 8.917
version_date = "2019/05/18" version_date = "2019/05/22"
beta = True beta = True
# current date now # current date now

View File

@@ -12,6 +12,7 @@ CAD program, and create G-Code for Isolation routing.
22.05.2019 22.05.2019
- Geo Editor - added a new editor tool, Eraser - Geo Editor - added a new editor tool, Eraser
- PEP8 cleanup of the Geo Editor
21.05.2019 21.05.2019

View File

@@ -1,15 +1,15 @@
############################################################ # ###########################################################
# FlatCAM: 2D Post-processing for Manufacturing # # FlatCAM: 2D Post-processing for Manufacturing #
# http://flatcam.org # # http://flatcam.org #
# Author: Juan Pablo Caram (c) # # Author: Juan Pablo Caram (c) #
# Date: 2/5/2014 # # Date: 2/5/2014 #
# MIT Licence # # MIT Licence #
############################################################ # ###########################################################
############################################################ # # ########################################################### #
# File Modified: Marius Adrian Stanciu (c) # # File Modified: Marius Adrian Stanciu (c) #
# Date: 3/10/2019 # # Date: 3/10/2019 #
############################################################ # ###########################################################
from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt, QSettings from PyQt5.QtCore import Qt, QSettings
@@ -33,9 +33,9 @@ from flatcamParsers.ParseFont import *
# from vispy.io import read_png # from vispy.io import read_png
import gettext import gettext
import FlatCAMTranslation as fcTranslate import FlatCAMTranslation as fcTranslate
import builtins
fcTranslate.apply_language('strings') fcTranslate.apply_language('strings')
import builtins
if '_' not in builtins.__dict__: if '_' not in builtins.__dict__:
_ = gettext.gettext _ = gettext.gettext
@@ -414,7 +414,7 @@ class PaintOptionsTool(FlatCAMTool):
self.app = app self.app = app
self.fcdraw = fcdraw self.fcdraw = fcdraw
## Title # Title
title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName)) title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
title_label.setStyleSheet(""" title_label.setStyleSheet("""
QLabel QLabel
@@ -431,7 +431,7 @@ class PaintOptionsTool(FlatCAMTool):
# Tool dia # Tool dia
ptdlabel = QtWidgets.QLabel(_('Tool dia:')) ptdlabel = QtWidgets.QLabel(_('Tool dia:'))
ptdlabel.setToolTip( ptdlabel.setToolTip(
_( "Diameter of the tool to\n" _("Diameter of the tool to\n"
"be used in the operation.") "be used in the operation.")
) )
grid.addWidget(ptdlabel, 0, 0) grid.addWidget(ptdlabel, 0, 0)
@@ -460,7 +460,7 @@ class PaintOptionsTool(FlatCAMTool):
# Margin # Margin
marginlabel = QtWidgets.QLabel(_('Margin:')) marginlabel = QtWidgets.QLabel(_('Margin:'))
marginlabel.setToolTip( marginlabel.setToolTip(
_( "Distance by which to avoid\n" _("Distance by which to avoid\n"
"the edges of the polygon to\n" "the edges of the polygon to\n"
"be painted.") "be painted.")
) )
@@ -486,7 +486,7 @@ class PaintOptionsTool(FlatCAMTool):
# Connect lines # Connect lines
pathconnectlabel = QtWidgets.QLabel(_("Connect:")) pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
pathconnectlabel.setToolTip( pathconnectlabel.setToolTip(
_( "Draw lines between resulting\n" _("Draw lines between resulting\n"
"segments to minimize tool lifts.") "segments to minimize tool lifts.")
) )
grid.addWidget(pathconnectlabel, 4, 0) grid.addWidget(pathconnectlabel, 4, 0)
@@ -502,8 +502,7 @@ class PaintOptionsTool(FlatCAMTool):
self.paintcontour_cb = FCCheckBox() self.paintcontour_cb = FCCheckBox()
grid.addWidget(self.paintcontour_cb, 5, 1) grid.addWidget(self.paintcontour_cb, 5, 1)
# Buttons
## Buttons
hlay = QtWidgets.QHBoxLayout() hlay = QtWidgets.QHBoxLayout()
self.layout.addLayout(hlay) self.layout.addLayout(hlay)
hlay.addStretch() hlay.addStretch()
@@ -512,7 +511,7 @@ class PaintOptionsTool(FlatCAMTool):
self.layout.addStretch() self.layout.addStretch()
## Signals # Signals
self.paint_button.clicked.connect(self.on_paint) self.paint_button.clicked.connect(self.on_paint)
self.set_tool_ui() self.set_tool_ui()
@@ -528,7 +527,7 @@ class PaintOptionsTool(FlatCAMTool):
self.app.ui.notebook.setTabText(2, _("Paint Tool")) self.app.ui.notebook.setTabText(2, _("Paint Tool"))
def set_tool_ui(self): def set_tool_ui(self):
## Init GUI # Init GUI
if self.app.defaults["tools_painttooldia"]: if self.app.defaults["tools_painttooldia"]:
self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"]) self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
else: else:
@@ -654,18 +653,18 @@ class TransformEditorTool(FlatCAMTool):
self.empty_label4.setFixedWidth(70) self.empty_label4.setFixedWidth(70)
self.transform_lay.addWidget(self.empty_label) self.transform_lay.addWidget(self.empty_label)
## Rotate Title # Rotate Title
rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName) rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
self.transform_lay.addWidget(rotate_title_label) self.transform_lay.addWidget(rotate_title_label)
## Layout # Layout
form_layout = QtWidgets.QFormLayout() form_layout = QtWidgets.QFormLayout()
self.transform_lay.addLayout(form_layout) self.transform_lay.addLayout(form_layout)
form_child = QtWidgets.QHBoxLayout() form_child = QtWidgets.QHBoxLayout()
self.rotate_label = QtWidgets.QLabel(_("Angle:")) self.rotate_label = QtWidgets.QLabel(_("Angle:"))
self.rotate_label.setToolTip( self.rotate_label.setToolTip(
_( "Angle for Rotation action, in degrees.\n" _("Angle for Rotation action, in degrees.\n"
"Float number between -360 and 359.\n" "Float number between -360 and 359.\n"
"Positive numbers for CW motion.\n" "Positive numbers for CW motion.\n"
"Negative numbers for CCW motion.") "Negative numbers for CCW motion.")
@@ -692,11 +691,11 @@ class TransformEditorTool(FlatCAMTool):
self.transform_lay.addWidget(self.empty_label1) self.transform_lay.addWidget(self.empty_label1)
## Skew Title # Skew Title
skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName) skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
self.transform_lay.addWidget(skew_title_label) self.transform_lay.addWidget(skew_title_label)
## Form Layout # Form Layout
form1_layout = QtWidgets.QFormLayout() form1_layout = QtWidgets.QFormLayout()
self.transform_lay.addLayout(form1_layout) self.transform_lay.addLayout(form1_layout)
form1_child_1 = QtWidgets.QHBoxLayout() form1_child_1 = QtWidgets.QHBoxLayout()
@@ -704,7 +703,7 @@ class TransformEditorTool(FlatCAMTool):
self.skewx_label = QtWidgets.QLabel(_("Angle X:")) self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
self.skewx_label.setToolTip( self.skewx_label.setToolTip(
_( "Angle for Skew action, in degrees.\n" _("Angle for Skew action, in degrees.\n"
"Float number between -360 and 359.") "Float number between -360 and 359.")
) )
self.skewx_label.setFixedWidth(50) self.skewx_label.setFixedWidth(50)
@@ -715,14 +714,14 @@ class TransformEditorTool(FlatCAMTool):
self.skewx_button = FCButton() self.skewx_button = FCButton()
self.skewx_button.set_value(_("Skew X")) self.skewx_button.set_value(_("Skew X"))
self.skewx_button.setToolTip( self.skewx_button.setToolTip(
_( "Skew/shear the selected shape(s).\n" _("Skew/shear the selected shape(s).\n"
"The point of reference is the middle of\n" "The point of reference is the middle of\n"
"the bounding box for all selected shapes.")) "the bounding box for all selected shapes."))
self.skewx_button.setFixedWidth(60) self.skewx_button.setFixedWidth(60)
self.skewy_label = QtWidgets.QLabel(_("Angle Y:")) self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
self.skewy_label.setToolTip( self.skewy_label.setToolTip(
_( "Angle for Skew action, in degrees.\n" _("Angle for Skew action, in degrees.\n"
"Float number between -360 and 359.") "Float number between -360 and 359.")
) )
self.skewy_label.setFixedWidth(50) self.skewy_label.setFixedWidth(50)
@@ -749,11 +748,11 @@ class TransformEditorTool(FlatCAMTool):
self.transform_lay.addWidget(self.empty_label2) self.transform_lay.addWidget(self.empty_label2)
## Scale Title # Scale Title
scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName) scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
self.transform_lay.addWidget(scale_title_label) self.transform_lay.addWidget(scale_title_label)
## Form Layout # Form Layout
form2_layout = QtWidgets.QFormLayout() form2_layout = QtWidgets.QFormLayout()
self.transform_lay.addLayout(form2_layout) self.transform_lay.addLayout(form2_layout)
form2_child_1 = QtWidgets.QHBoxLayout() form2_child_1 = QtWidgets.QHBoxLayout()
@@ -771,7 +770,7 @@ class TransformEditorTool(FlatCAMTool):
self.scalex_button = FCButton() self.scalex_button = FCButton()
self.scalex_button.set_value(_("Scale X")) self.scalex_button.set_value(_("Scale X"))
self.scalex_button.setToolTip( self.scalex_button.setToolTip(
_( "Scale the selected shape(s).\n" _("Scale the selected shape(s).\n"
"The point of reference depends on \n" "The point of reference depends on \n"
"the Scale reference checkbox state.")) "the Scale reference checkbox state."))
self.scalex_button.setFixedWidth(60) self.scalex_button.setFixedWidth(60)
@@ -788,7 +787,7 @@ class TransformEditorTool(FlatCAMTool):
self.scaley_button = FCButton() self.scaley_button = FCButton()
self.scaley_button.set_value(_("Scale Y")) self.scaley_button.set_value(_("Scale Y"))
self.scaley_button.setToolTip( self.scaley_button.setToolTip(
_( "Scale the selected shape(s).\n" _("Scale the selected shape(s).\n"
"The point of reference depends on \n" "The point of reference depends on \n"
"the Scale reference checkbox state.")) "the Scale reference checkbox state."))
self.scaley_button.setFixedWidth(60) self.scaley_button.setFixedWidth(60)
@@ -823,11 +822,11 @@ class TransformEditorTool(FlatCAMTool):
self.transform_lay.addWidget(self.empty_label3) self.transform_lay.addWidget(self.empty_label3)
## Offset Title # Offset Title
offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName) offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
self.transform_lay.addWidget(offset_title_label) self.transform_lay.addWidget(offset_title_label)
## Form Layout # Form Layout
form3_layout = QtWidgets.QFormLayout() form3_layout = QtWidgets.QFormLayout()
self.transform_lay.addLayout(form3_layout) self.transform_lay.addLayout(form3_layout)
form3_child_1 = QtWidgets.QHBoxLayout() form3_child_1 = QtWidgets.QHBoxLayout()
@@ -845,7 +844,7 @@ class TransformEditorTool(FlatCAMTool):
self.offx_button = FCButton() self.offx_button = FCButton()
self.offx_button.set_value(_("Offset X")) self.offx_button.set_value(_("Offset X"))
self.offx_button.setToolTip( self.offx_button.setToolTip(
_( "Offset the selected shape(s).\n" _("Offset the selected shape(s).\n"
"The point of reference is the middle of\n" "The point of reference is the middle of\n"
"the bounding box for all selected shapes.\n") "the bounding box for all selected shapes.\n")
) )
@@ -880,11 +879,11 @@ class TransformEditorTool(FlatCAMTool):
self.transform_lay.addWidget(self.empty_label4) self.transform_lay.addWidget(self.empty_label4)
## Flip Title # Flip Title
flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName) flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
self.transform_lay.addWidget(flip_title_label) self.transform_lay.addWidget(flip_title_label)
## Form Layout # Form Layout
form4_layout = QtWidgets.QFormLayout() form4_layout = QtWidgets.QFormLayout()
form4_child_hlay = QtWidgets.QHBoxLayout() form4_child_hlay = QtWidgets.QHBoxLayout()
self.transform_lay.addLayout(form4_child_hlay) self.transform_lay.addLayout(form4_child_hlay)
@@ -937,7 +936,7 @@ class TransformEditorTool(FlatCAMTool):
self.flip_ref_button = FCButton() self.flip_ref_button = FCButton()
self.flip_ref_button.set_value(_("Add")) self.flip_ref_button.set_value(_("Add"))
self.flip_ref_button.setToolTip( self.flip_ref_button.setToolTip(
_( "The point coordinates can be captured by\n" _("The point coordinates can be captured by\n"
"left click on canvas together with pressing\n" "left click on canvas together with pressing\n"
"SHIFT key. Then click Add button to insert.") "SHIFT key. Then click Add button to insert.")
) )
@@ -957,7 +956,7 @@ class TransformEditorTool(FlatCAMTool):
self.transform_lay.addStretch() self.transform_lay.addStretch()
## Signals # Signals
self.rotate_button.clicked.connect(self.on_rotate) self.rotate_button.clicked.connect(self.on_rotate)
self.skewx_button.clicked.connect(self.on_skewx) self.skewx_button.clicked.connect(self.on_skewx)
self.skewy_button.clicked.connect(self.on_skewy) self.skewy_button.clicked.connect(self.on_skewy)
@@ -994,7 +993,7 @@ class TransformEditorTool(FlatCAMTool):
FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs) FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
def set_tool_ui(self): def set_tool_ui(self):
## Initialize form # Initialize form
if self.app.defaults["tools_transform_rotate"]: if self.app.defaults["tools_transform_rotate"]:
self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"]) self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
else: else:
@@ -1458,15 +1457,6 @@ class TransformEditorTool(FlatCAMTool):
else: else:
with self.app.proc_container.new(_("Applying Offset")): with self.app.proc_container.new(_("Applying Offset")):
try: try:
# first get a bounding box to fit all
for sha in shape_list:
xmin, ymin, xmax, ymax = sha.bounds()
xminlist.append(xmin)
yminlist.append(ymin)
# get the minimum x,y and maximum x,y for all objects selected
xminimal = min(xminlist)
yminimal = min(yminlist)
self.app.progress.emit(20) self.app.progress.emit(20)
for sha in shape_list: for sha in shape_list:
@@ -1476,10 +1466,6 @@ class TransformEditorTool(FlatCAMTool):
sha.offset((0, num)) sha.offset((0, num))
self.draw_app.replot() self.draw_app.replot()
# self.draw_app.add_shape(DrawToolShape(sha.geo))
#
# self.draw_app.transform_complete.emit()
self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis)) self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
self.app.progress.emit(100) self.app.progress.emit(100)
@@ -1559,7 +1545,7 @@ class TransformEditorTool(FlatCAMTool):
return return
else: else:
self.app.inform.emit( self.app.inform.emit(
_( "[WARNING_NOTCL] Geometry shape skew X cancelled...")) _("[WARNING_NOTCL] Geometry shape skew X cancelled..."))
def on_skewy_key(self): def on_skewy_key(self):
val_box = FCInputDialog(title=_("Skew on Y axis ..."), val_box = FCInputDialog(title=_("Skew on Y axis ..."),
@@ -1572,7 +1558,7 @@ class TransformEditorTool(FlatCAMTool):
if ok: if ok:
self.on_skewx(val=val) self.on_skewx(val=val)
self.app.inform.emit( self.app.inform.emit(
_( "[success] Geometry shape skew on Y axis done...")) _("[success] Geometry shape skew on Y axis done..."))
return return
else: else:
self.app.inform.emit( self.app.inform.emit(
@@ -1599,19 +1585,19 @@ class DrawToolShape(object):
""" """
pts = [] pts = []
## Iterable: descend into each item. # Iterable: descend into each item.
try: try:
for subo in o: for subo in o:
pts += DrawToolShape.get_pts(subo) pts += DrawToolShape.get_pts(subo)
## Non-iterable # Non-iterable
except TypeError: except TypeError:
if o is not None: if o is not None:
## DrawToolShape: descend into .geo. # DrawToolShape: descend into .geo.
if isinstance(o, DrawToolShape): if isinstance(o, DrawToolShape):
pts += DrawToolShape.get_pts(o.geo) pts += DrawToolShape.get_pts(o.geo)
## Descend into .exerior and .interiors # Descend into .exerior and .interiors
elif type(o) == Polygon: elif type(o) == Polygon:
pts += DrawToolShape.get_pts(o.exterior) pts += DrawToolShape.get_pts(o.exterior)
for i in o.interiors: for i in o.interiors:
@@ -1619,7 +1605,7 @@ class DrawToolShape(object):
elif type(o) == MultiLineString: elif type(o) == MultiLineString:
for line in o: for line in o:
pts += DrawToolShape.get_pts(line) pts += DrawToolShape.get_pts(line)
## Has .coords: list them. # Has .coords: list them.
else: else:
if DrawToolShape.tolerance is not None: if DrawToolShape.tolerance is not None:
pts += list(o.simplify(DrawToolShape.tolerance).coords) pts += list(o.simplify(DrawToolShape.tolerance).coords)
@@ -1645,14 +1631,14 @@ class DrawToolShape(object):
""" """
# fixed issue of getting bounds only for one level lists of objects # fixed issue of getting bounds only for one level lists of objects
# now it can get bounds for nested lists of objects # now it can get bounds for nested lists of objects
def bounds_rec(shape): def bounds_rec(shape_el):
if type(shape) is list: if type(shape_el) is list:
minx = Inf minx = Inf
miny = Inf miny = Inf
maxx = -Inf maxx = -Inf
maxy = -Inf maxy = -Inf
for k in shape: for k in shape_el:
minx_, miny_, maxx_, maxy_ = bounds_rec(k) minx_, miny_, maxx_, maxy_ = bounds_rec(k)
minx = min(minx, minx_) minx = min(minx, minx_)
miny = min(miny, miny_) miny = min(miny, miny_)
@@ -1661,7 +1647,7 @@ class DrawToolShape(object):
return minx, miny, maxx, maxy return minx, miny, maxx, maxy
else: else:
# it's a Shapely object, return it's bounds # it's a Shapely object, return it's bounds
return shape.bounds return shape_el.bounds
bounds_coords = bounds_rec(self.geo) bounds_coords = bounds_rec(self.geo)
return bounds_coords return bounds_coords
@@ -1681,14 +1667,14 @@ class DrawToolShape(object):
px, py = point px, py = point
xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis] xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
def mirror_geom(shape): def mirror_geom(shape_el):
if type(shape) is list: if type(shape_el) is list:
new_obj = [] new_obj = []
for g in shape: for g in shape_el:
new_obj.append(mirror_geom(g)) new_obj.append(mirror_geom(g))
return new_obj return new_obj
else: else:
return affinity.scale(shape, xscale, yscale, origin=(px,py)) return affinity.scale(shape_el, xscale, yscale, origin=(px, py))
try: try:
self.geo = mirror_geom(self.geo) self.geo = mirror_geom(self.geo)
@@ -1714,14 +1700,14 @@ class DrawToolShape(object):
px, py = point px, py = point
def rotate_geom(shape): def rotate_geom(shape_el):
if type(shape) is list: if type(shape_el) is list:
new_obj = [] new_obj = []
for g in shape: for g in shape_el:
new_obj.append(rotate_geom(g)) new_obj.append(rotate_geom(g))
return new_obj return new_obj
else: else:
return affinity.rotate(shape, angle, origin=(px, py)) return affinity.rotate(shape_el, angle, origin=(px, py))
try: try:
self.geo = rotate_geom(self.geo) self.geo = rotate_geom(self.geo)
@@ -1745,14 +1731,14 @@ class DrawToolShape(object):
""" """
px, py = point px, py = point
def skew_geom(shape): def skew_geom(shape_el):
if type(shape) is list: if type(shape_el) is list:
new_obj = [] new_obj = []
for g in shape: for g in shape_el:
new_obj.append(skew_geom(g)) new_obj.append(skew_geom(g))
return new_obj return new_obj
else: else:
return affinity.skew(shape, angle_x, angle_y, origin=(px, py)) return affinity.skew(shape_el, angle_x, angle_y, origin=(px, py))
try: try:
self.geo = skew_geom(self.geo) self.geo = skew_geom(self.geo)
@@ -1778,7 +1764,7 @@ class DrawToolShape(object):
def translate_recursion(geom): def translate_recursion(geom):
if type(geom) == list: if type(geom) == list:
geoms=list() geoms = list()
for local_geom in geom: for local_geom in geom:
geoms.append(translate_recursion(local_geom)) geoms.append(translate_recursion(local_geom))
return geoms return geoms
@@ -1825,7 +1811,7 @@ class DrawToolShape(object):
def scale_recursion(geom): def scale_recursion(geom):
if type(geom) == list: if type(geom) == list:
geoms=list() geoms = list()
for local_geom in geom: for local_geom in geom:
geoms.append(scale_recursion(local_geom)) geoms.append(scale_recursion(local_geom))
return geoms return geoms
@@ -2928,9 +2914,9 @@ class FCTransform(FCShapeTool):
self.draw_app.transform_tool.run() self.draw_app.transform_tool.run()
######################## # #######################
### Main Application ### # ## Main Application ###
######################## # #######################
class FlatCAMGeoEditor(QtCore.QObject): class FlatCAMGeoEditor(QtCore.QObject):
transform_complete = QtCore.pyqtSignal() transform_complete = QtCore.pyqtSignal()
@@ -2976,7 +2962,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
"constructor": FCCopy} "constructor": FCCopy}
} }
### Data # ## Data
self.active_tool = None self.active_tool = None
self.storage = FlatCAMGeoEditor.make_storage() self.storage = FlatCAMGeoEditor.make_storage()
@@ -2992,7 +2978,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
self.shapes.enabled = False self.shapes.enabled = False
self.tool_shape.enabled = False self.tool_shape.enabled = False
## List of selected shapes. # List of selected shapes.
self.selected = [] self.selected = []
self.flat_geo = [] self.flat_geo = []
@@ -3258,7 +3244,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
self.fcgeometry.visible = True self.fcgeometry.visible = True
def connect_canvas_event_handlers(self): def connect_canvas_event_handlers(self):
## Canvas events # Canvas events
# first connect to new, then disconnect the old handlers # first connect to new, then disconnect the old handlers
# don't ask why but if there is nothing connected I've seen issues # don't ask why but if there is nothing connected I've seen issues
@@ -3288,7 +3274,6 @@ class FlatCAMGeoEditor(QtCore.QObject):
self.app.ui.draw_cut.triggered.connect(self.cutpath) self.app.ui.draw_cut.triggered.connect(self.cutpath)
self.app.ui.draw_move.triggered.connect(self.on_move) self.app.ui.draw_move.triggered.connect(self.on_move)
def disconnect_canvas_event_handlers(self): def disconnect_canvas_event_handlers(self):
# we restore the key and mouse control to FlatCAMApp method # we restore the key and mouse control to FlatCAMApp method
# first connect to new, then disconnect the old handlers # first connect to new, then disconnect the old handlers
@@ -3366,8 +3351,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
"Shape object has empty geometry (None)" "Shape object has empty geometry (None)"
assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \ assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
not isinstance(shape.geo, list), \ not isinstance(shape.geo, list), "Shape objects has empty geometry ([])"
"Shape objects has empty geometry ([])"
if isinstance(shape, DrawToolUtilityShape): if isinstance(shape, DrawToolUtilityShape):
self.utility.append(shape) self.utility.append(shape)
@@ -3407,6 +3391,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
into the editor. into the editor.
:param fcgeometry: FlatCAMGeometry :param fcgeometry: FlatCAMGeometry
:param multigeo_tool: a tool for the case of multigeo
:return: None :return: None
""" """
assert isinstance(fcgeometry, Geometry), \ assert isinstance(fcgeometry, Geometry), \
@@ -3444,9 +3429,8 @@ class FlatCAMGeoEditor(QtCore.QObject):
self.replot() self.replot()
# start with GRID toolbar activated # start with GRID toolbar activated
if self.app.ui.grid_snap_btn.isChecked() == False: if self.app.ui.grid_snap_btn.isChecked() is False:
self.app.ui.grid_snap_btn.trigger() self.app.ui.grid_snap_btn.trigger()
def on_buffer_tool(self): def on_buffer_tool(self):
@@ -3535,7 +3519,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
if self.active_tool is not None and event.button is 1: if self.active_tool is not None and event.button is 1:
# Dispatch event to active_tool # Dispatch event to active_tool
msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1])) self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
# If it is a shape generating tool # If it is a shape generating tool
if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete: if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
@@ -3585,7 +3569,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
if self.active_tool is None: if self.active_tool is None:
return return
### Snap coordinates # ## Snap coordinates
if self.app.grid_status(): if self.app.grid_status():
x, y = self.snap(x, y) x, y = self.snap(x, y)
self.app.app_cursor.enabled = True self.app.app_cursor.enabled = True
@@ -3610,7 +3594,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: " self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
"%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy)) "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
### Utility geometry (animated) # ## Utility geometry (animated)
geo = self.active_tool.utility_geometry(data=(x, y)) geo = self.active_tool.utility_geometry(data=(x, y))
if isinstance(geo, DrawToolShape) and geo.geo is not None: if isinstance(geo, DrawToolShape) and geo.geo is not None:
@@ -3618,17 +3602,17 @@ class FlatCAMGeoEditor(QtCore.QObject):
self.tool_shape.clear(update=True) self.tool_shape.clear(update=True)
self.draw_utility_geometry(geo=geo) self.draw_utility_geometry(geo=geo)
### Selection area on canvas section ### # ## Selection area on canvas section ###
dx = pos[0] - self.pos[0] dx = pos[0] - self.pos[0]
if event.is_dragging == 1 and event.button == 1: if event.is_dragging == 1 and event.button == 1:
self.app.delete_selection_shape() self.app.delete_selection_shape()
if dx < 0: if dx < 0:
self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y), self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
color=self.app.defaults["global_alt_sel_line"], color=self.app.defaults["global_alt_sel_line"],
face_color=self.app.defaults['global_alt_sel_fill']) face_color=self.app.defaults['global_alt_sel_fill'])
self.app.selection_type = False self.app.selection_type = False
else: else:
self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y)) self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
self.app.selection_type = True self.app.selection_type = True
else: else:
self.app.selection_type = None self.app.selection_type = None
@@ -3700,7 +3684,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
elif isinstance(self.active_tool, FCSelect): elif isinstance(self.active_tool, FCSelect):
# Dispatch event to active_tool # Dispatch event to active_tool
# msg = self.active_tool.click(self.snap(event.xdata, event.ydata)) # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
msg = self.active_tool.click_release((self.pos[0], self.pos[1])) self.active_tool.click_release((self.pos[0], self.pos[1]))
# self.app.inform.emit(msg) # self.app.inform.emit(msg)
self.replot() self.replot()
except Exception as e: except Exception as e:
@@ -3713,15 +3697,14 @@ class FlatCAMGeoEditor(QtCore.QObject):
:param start_pos: mouse position when the selection LMB click was done :param start_pos: mouse position when the selection LMB click was done
:param end_pos: mouse position when the left mouse button is released :param end_pos: mouse position when the left mouse button is released
:param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
:type Bool
:return: :return:
""" """
poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])]) poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
self.app.delete_selection_shape() self.app.delete_selection_shape()
for obj in self.storage.get_objects(): for obj in self.storage.get_objects():
if (sel_type is True and poly_selection.contains(obj.geo)) or \ if (sel_type is True and poly_selection.contains(obj.geo)) or (sel_type is False and
(sel_type is False and poly_selection.intersects(obj.geo)): poly_selection.intersects(obj.geo)):
if self.key == self.app.defaults["global_mselect_key"]: if self.key == self.app.defaults["global_mselect_key"]:
if obj in self.selected: if obj in self.selected:
self.selected.remove(obj) self.selected.remove(obj)
@@ -3844,14 +3827,14 @@ class FlatCAMGeoEditor(QtCore.QObject):
for geo in geometry: for geo in geometry:
plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth) plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
## Non-iterable # Non-iterable
except TypeError: except TypeError:
## DrawToolShape # DrawToolShape
if isinstance(geometry, DrawToolShape): if isinstance(geometry, DrawToolShape):
plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth) plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
## Polygon: Descend into exterior and each interior. # Polygon: Descend into exterior and each interior.
if type(geometry) == Polygon: if type(geometry) == Polygon:
plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth) plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth) plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
@@ -3912,7 +3895,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
@staticmethod @staticmethod
def make_storage(): def make_storage():
## Shape storage. # Shape storage.
storage = FlatCAMRTreeStorage() storage = FlatCAMRTreeStorage()
storage.get_points = DrawToolShape.get_pts storage.get_points = DrawToolShape.get_pts
@@ -3952,9 +3935,9 @@ class FlatCAMGeoEditor(QtCore.QObject):
snap_x, snap_y = (x, y) snap_x, snap_y = (x, y)
snap_distance = Inf snap_distance = Inf
### Object (corner?) snap # ## Object (corner?) snap
### No need for the objects, just the coordinates # ## No need for the objects, just the coordinates
### in the index. # ## in the index.
if self.options["corner_snap"]: if self.options["corner_snap"]:
try: try:
nearest_pt, shape = self.storage.nearest((x, y)) nearest_pt, shape = self.storage.nearest((x, y))
@@ -3966,7 +3949,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
except (StopIteration, AssertionError): except (StopIteration, AssertionError):
pass pass
### Grid snap # ## Grid snap
if self.options["grid_snap"]: if self.options["grid_snap"]:
if self.options["global_gridx"] != 0: if self.options["global_gridx"] != 0:
snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx'] snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
@@ -4048,23 +4031,24 @@ class FlatCAMGeoEditor(QtCore.QObject):
:return: None :return: None
""" """
shapes = self.get_selected() geo_shapes = self.get_selected()
try: try:
results = shapes[0].geo results = geo_shapes[0].geo
except Exception as e: except Exception as e:
log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e)) log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
self.app.inform.emit(_("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection.")) self.app.inform.emit(
_("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
self.select_tool('select') self.select_tool('select')
return return
for shape in shapes[1:]: for shape_el in geo_shapes[1:]:
results = results.intersection(shape.geo) results = results.intersection(shape_el.geo)
# Delete originals. # Delete originals.
for_deletion = [s for s in self.get_selected()] for_deletion = [s for s in self.get_selected()]
for shape in for_deletion: for shape_el in for_deletion:
self.delete_shape(shape) self.delete_shape(shape_el)
# Selected geometry is now gone! # Selected geometry is now gone!
self.selected = [] self.selected = []
@@ -4080,30 +4064,31 @@ class FlatCAMGeoEditor(QtCore.QObject):
:return: None :return: None
""" """
shapes = self.get_selected() geo_shapes = self.get_selected()
results = [] results = []
intact = [] intact = []
try: try:
intersector = shapes[0].geo intersector = geo_shapes[0].geo
except Exception as e: except Exception as e:
log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e)) log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
self.app.inform.emit(_("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection.")) self.app.inform.emit(
_("[WARNING_NOTCL] A selection of at least 2 geo items is required to do Intersection."))
self.select_tool('select') self.select_tool('select')
return return
for shape in shapes[1:]: for shape_el in geo_shapes[1:]:
if intersector.intersects(shape.geo): if intersector.intersects(shape_el.geo):
results.append(intersector.intersection(shape.geo)) results.append(intersector.intersection(shape_el.geo))
else: else:
intact.append(shape) intact.append(shape_el)
if len(results) != 0: if len(results) != 0:
# Delete originals. # Delete originals.
for_deletion = [s for s in self.get_selected()] for_deletion = [s for s in self.get_selected()]
for shape in for_deletion: for shape_el in for_deletion:
if shape not in intact: if shape_el not in intact:
self.delete_shape(shape) self.delete_shape(shape_el)
for geo in results: for geo in results:
self.add_shape(DrawToolShape(geo)) self.add_shape(DrawToolShape(geo))
@@ -4158,8 +4143,8 @@ class FlatCAMGeoEditor(QtCore.QObject):
try: try:
for linestring in target.geo: for linestring in target.geo:
self.add_shape(DrawToolShape(linestring.difference(toolgeo))) self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
except: except Exception as e:
self.app.log.warning("Current LinearString does not intersect the target") self.app.log.warning("Current LinearString does not intersect the target. %s" % str(e))
else: else:
self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo))) self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
return return
@@ -4172,7 +4157,8 @@ class FlatCAMGeoEditor(QtCore.QObject):
if buf_distance < 0: if buf_distance < 0:
self.app.inform.emit( self.app.inform.emit(
_( "[ERROR_NOTCL] Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape")) _("[ERROR_NOTCL] Negative buffer value is not accepted. "
"Use Buffer interior to generate an 'inside' shape"))
# deselect everything # deselect everything
self.selected = [] self.selected = []
@@ -4412,13 +4398,13 @@ class FlatCAMGeoEditor(QtCore.QObject):
if reset: if reset:
self.flat_geo = [] self.flat_geo = []
## If iterable, expand recursively. # If iterable, expand recursively.
try: try:
for geo in geometry: for geo_el in geometry:
if geo is not None: if geo_el is not None:
recurse(geometry=geo, reset=False) recurse(geometry=geo_el, reset=False)
## Not iterable, do the actual indexing and add. # Not iterable, do the actual indexing and add.
except TypeError: except TypeError:
self.flat_geo.append(geometry) self.flat_geo.append(geometry)