From 91493b2fbc5ea4f467467e4cdd4b59c6abb941c9 Mon Sep 17 00:00:00 2001 From: Marius Stanciu Date: Wed, 6 May 2020 02:10:18 +0300 Subject: [PATCH 1/4] - wip in adding Exclusion areas in Geometry object; each Geometry object has now a storage for shapes (exclusion shapes, should I make them more general?) --- CHANGELOG.md | 4 ++ FlatCAMApp.py | 7 ++- FlatCAMTool.py | 70 +++++++++++++++++++------- flatcamGUI/PlotCanvasLegacy.py | 4 +- flatcamObjects/FlatCAMGeometry.py | 82 ++++++++++++++++++++++++++----- flatcamTools/ToolNCC.py | 25 +++++++--- 6 files changed, 152 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6fc2717..5be0edb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ CHANGELOG for FlatCAM beta ================================================= +6.05.2020 + +- wip in adding Exclusion areas in Geometry object; each Geometry object has now a storage for shapes (exclusion shapes, should I make them more general?) + 5.05.2020 - fixed an issue that made the preprocessors comboxes in Preferences not to load and display the saved value fro the file diff --git a/FlatCAMApp.py b/FlatCAMApp.py index 923a599e..3ac389df 100644 --- a/FlatCAMApp.py +++ b/FlatCAMApp.py @@ -5119,12 +5119,17 @@ class App(QtCore.QObject): for obj_active in self.collection.get_selected(): # if the deleted object is GerberObject then make sure to delete the possible mark shapes - if isinstance(obj_active, GerberObject): + if obj_active.kind == 'gerber': for el in obj_active.mark_shapes: obj_active.mark_shapes[el].clear(update=True) obj_active.mark_shapes[el].enabled = False # obj_active.mark_shapes[el] = None del el + # if the deleted object is GerberObject then make sure to delete the possible mark shapes + if obj_active.kind == 'geometry': + obj_active.exclusion_shapes.clear(update=True) + obj_active.exclusion_shapes.enabled = False + del obj_active.exclusion_shapes elif isinstance(obj_active, CNCJobObject): try: obj_active.text_col.enabled = False diff --git a/FlatCAMTool.py b/FlatCAMTool.py index 3b7f8d0f..470a484a 100644 --- a/FlatCAMTool.py +++ b/FlatCAMTool.py @@ -110,6 +110,11 @@ class FlatCAMTool(QtWidgets.QWidget): :return: """ + if 'shapes_storage' in kwargs: + s_storage = kwargs['shapes_storage'] + else: + s_storage = self.app.tool_shapes + if 'color' in kwargs: color = kwargs['color'] else: @@ -139,10 +144,9 @@ class FlatCAMTool(QtWidgets.QWidget): color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:] - self.app.tool_shapes.add(sel_rect, color=color, face_color=color_t, update=True, - layer=0, tolerance=None) + s_storage.add(sel_rect, color=color, face_color=color_t, update=True, layer=0, tolerance=None) if self.app.is_legacy is True: - self.app.tool_shapes.redraw() + s_storage.redraw() def draw_selection_shape_polygon(self, points, **kwargs): """ @@ -151,6 +155,12 @@ class FlatCAMTool(QtWidgets.QWidget): :param kwargs: :return: """ + + if 'shapes_storage' in kwargs: + s_storage = kwargs['shapes_storage'] + else: + s_storage = self.app.tool_shapes + if 'color' in kwargs: color = kwargs['color'] else: @@ -165,6 +175,7 @@ class FlatCAMTool(QtWidgets.QWidget): face_alpha = kwargs['face_alpha'] else: face_alpha = 0.3 + if len(points) < 3: sel_rect = LineString(points) else: @@ -175,14 +186,24 @@ class FlatCAMTool(QtWidgets.QWidget): color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:] - self.app.tool_shapes.add(sel_rect, color=color, face_color=color_t, update=True, - layer=0, tolerance=None) + s_storage.add(sel_rect, color=color, face_color=color_t, update=True, layer=0, tolerance=None) if self.app.is_legacy is True: - self.app.tool_shapes.redraw() + s_storage.redraw() - def delete_tool_selection_shape(self): - self.app.tool_shapes.clear() - self.app.tool_shapes.redraw() + def delete_tool_selection_shape(self, **kwargs): + """ + + :param kwargs: + :return: + """ + + if 'shapes_storage' in kwargs: + s_storage = kwargs['shapes_storage'] + else: + s_storage = self.app.tool_shapes + + s_storage.clear() + s_storage.redraw() def draw_moving_selection_shape_poly(self, points, data, **kwargs): """ @@ -192,6 +213,12 @@ class FlatCAMTool(QtWidgets.QWidget): :param kwargs: :return: """ + + if 'shapes_storage' in kwargs: + s_storage = kwargs['shapes_storage'] + else: + s_storage = self.app.move_tool.sel_shapes + if 'color' in kwargs: color = kwargs['color'] else: @@ -226,18 +253,27 @@ class FlatCAMTool(QtWidgets.QWidget): color_t_error = "#00000000" if geo.is_valid and not geo.is_empty: - self.app.move_tool.sel_shapes.add(geo, color=color, face_color=color_t, update=True, - layer=0, tolerance=None) + s_storage.add(geo, color=color, face_color=color_t, update=True, layer=0, tolerance=None) elif not geo.is_valid: - self.app.move_tool.sel_shapes.add(geo, color="red", face_color=color_t_error, update=True, - layer=0, tolerance=None) + s_storage.add(geo, color="red", face_color=color_t_error, update=True, layer=0, tolerance=None) if self.app.is_legacy is True: - self.app.move_tool.sel_shapes.redraw() + s_storage.redraw() - def delete_moving_selection_shape(self): - self.app.move_tool.sel_shapes.clear() - self.app.move_tool.sel_shapes.redraw() + def delete_moving_selection_shape(self, **kwargs): + """ + + :param kwargs: + :return: + """ + + if 'shapes_storage' in kwargs: + s_storage = kwargs['shapes_storage'] + else: + s_storage = self.app.move_tool.sel_shapes + + s_storage.clear() + s_storage.redraw() def confirmation_message(self, accepted, minval, maxval): if accepted is False: diff --git a/flatcamGUI/PlotCanvasLegacy.py b/flatcamGUI/PlotCanvasLegacy.py index df9c8231..a9a6216f 100644 --- a/flatcamGUI/PlotCanvasLegacy.py +++ b/flatcamGUI/PlotCanvasLegacy.py @@ -948,10 +948,10 @@ class ShapeCollectionLegacy: """ :param obj: This is the object to which the shapes collection is attached and for - which it will have to draw shapes + which it will have to draw shapes :param app: This is the FLatCAM.App usually, needed because we have to access attributes there :param name: This is the name given to the Matplotlib axes; it needs to be unique due of - Matplotlib requurements + Matplotlib requurements :param annotation_job: Make this True if the job needed is just for annotation :param linewidth: THe width of the line (outline where is the case) """ diff --git a/flatcamObjects/FlatCAMGeometry.py b/flatcamObjects/FlatCAMGeometry.py index f4d0554f..62d5924d 100644 --- a/flatcamObjects/FlatCAMGeometry.py +++ b/flatcamObjects/FlatCAMGeometry.py @@ -16,6 +16,7 @@ import shapely.affinity as affinity from camlib import Geometry from flatcamObjects.FlatCAMObj import * +from flatcamGUI.VisPyVisuals import ShapeCollection import FlatCAMTool import ezdxf @@ -163,6 +164,18 @@ class GeometryObject(FlatCAMObj, Geometry): self.points = [] self.poly_drawn = False + # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry + # VisPy visuals + if self.app.is_legacy is False: + try: + self.exclusion_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1) + except AttributeError: + self.exclusion_shapes = None + else: + from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy + self.exclusion_shapes = ShapeCollectionLegacy( + obj=self, app=self.app, name="exclusion" + self.options['name']) + # Attributes to be included in serialization # Always append to it because it carries contents # from predecessors. @@ -363,7 +376,7 @@ class GeometryObject(FlatCAMObj, Geometry): "endxy": self.ui.endxy_entry, "cnctooldia": self.ui.addtool_entry, "area_exclusion": self.ui.exclusion_cb, - "area_shape":self.ui.area_shape_radio, + "area_shape": self.ui.area_shape_radio, "area_strategy": self.ui.strategy_radio, "area_overz": self.ui.over_z_entry, }) @@ -1149,8 +1162,7 @@ class GeometryObject(FlatCAMObj, Geometry): "- 'V-tip Angle' -> angle at the tip of the tool\n" "- 'V-tip Dia' -> diameter at the tip of the tool \n" "- Tool Dia -> 'Dia' column found in the Tool Table\n" - "NB: a value of zero means that Tool Dia = 'V-tip Dia'" - ) + "NB: a value of zero means that Tool Dia = 'V-tip Dia'") ) self.ui.cutz_entry.setToolTip( _("Disabled because the tool is V-shape.\n" @@ -1159,8 +1171,7 @@ class GeometryObject(FlatCAMObj, Geometry): "- 'V-tip Angle' -> angle at the tip of the tool\n" "- 'V-tip Dia' -> diameter at the tip of the tool \n" "- Tool Dia -> 'Dia' column found in the Tool Table\n" - "NB: a value of zero means that Tool Dia = 'V-tip Dia'" - ) + "NB: a value of zero means that Tool Dia = 'V-tip Dia'") ) self.update_cutz() @@ -1172,8 +1183,7 @@ class GeometryObject(FlatCAMObj, Geometry): self.ui.cutz_entry.setDisabled(False) self.ui.cutzlabel.setToolTip( _("Cutting depth (negative)\n" - "below the copper surface." - ) + "below the copper surface.") ) self.ui.cutz_entry.setToolTip('') @@ -2636,7 +2646,11 @@ class GeometryObject(FlatCAMObj, Geometry): self.exclusion_areas_list.append(new_rectangle) # add a temporary shape on canvas - FlatCAMTool.FlatCAMTool.draw_tool_selection_shape(self, old_coords=(x0, y0), coords=(x1, y1)) + FlatCAMTool.FlatCAMTool.draw_tool_selection_shape( + self, old_coords=(x0, y0), coords=(x1, y1), + color="#FF7400", + face_color="#FF7400BF", + shapes_storage=self.exclusion_shapes) self.first_click = False return @@ -2672,7 +2686,11 @@ class GeometryObject(FlatCAMObj, Geometry): # do not add invalid polygons even if they are drawn by utility geometry if pol.is_valid: self.exclusion_areas_list.append(pol) - FlatCAMTool.FlatCAMTool.draw_selection_shape_polygon(self, points=self.points) + FlatCAMTool.FlatCAMTool.draw_selection_shape_polygon( + self, points=self.points, + color="#FF7400", + face_color="#FF7400BF", + shapes_storage=self.exclusion_shapes) self.app.inform.emit( _("Zone added. Click to start adding next zone or right click to finish.")) @@ -2680,7 +2698,7 @@ class GeometryObject(FlatCAMObj, Geometry): self.poly_drawn = False return - FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self) + # FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) if self.app.is_legacy is False: self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release) @@ -2702,6 +2720,29 @@ class GeometryObject(FlatCAMObj, Geometry): if len(self.exclusion_areas_list) == 0: return + else: + self.exclusion_areas_list = MultiPolygon(self.exclusion_areas_list) + + self.app.inform.emit( + "[success] %s" % _("Exclusion areas added. Checking overlap with the object geometry ...")) + if self.exclusion_areas_list.intersects(MultiPolygon(self.solid_geometry)): + self.exclusion_areas_list = [] + self.app.inform.emit( + "[ERROR_NOTCL] %s" % _("Failed. Exclusion areas intersects the object geometry ...")) + return + else: + self.app.inform.emit( + "[success] %s" % _("Exclusion areas added.")) + self.ui.generate_cnc_button.setStyleSheet(""" + QPushButton + { + font-weight: bold; + color: orange; + } + """) + self.ui.generate_cnc_button.setToolTip( + '%s %s' % (_("Generate the CNC Job object."), _("With Exclusion areas.")) + ) def area_disconnect(self): if self.app.is_legacy is False: @@ -2723,7 +2764,7 @@ class GeometryObject(FlatCAMObj, Geometry): self.exclusion_areas_list = [] FlatCAMTool.FlatCAMTool.delete_moving_selection_shape(self) - FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self) + # FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) self.app.call_source = "app" self.app.inform.emit("[WARNING_NOTCL] %s" % _("Cancelled. Area exclusion drawing was interrupted.")) @@ -2775,16 +2816,33 @@ class GeometryObject(FlatCAMObj, Geometry): if self.first_click: self.app.delete_selection_shape() self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]), + color="#FF7400", + face_color="#FF7400BF", coords=(curr_pos[0], curr_pos[1])) else: FlatCAMTool.FlatCAMTool.delete_moving_selection_shape(self) FlatCAMTool.FlatCAMTool.draw_moving_selection_shape_poly( - self, points=self.points, data=(curr_pos[0], curr_pos[1])) + self, points=self.points, + color="#FF7400", + face_color="#FF7400BF", + data=(curr_pos[0], curr_pos[1])) def on_clear_area_click(self): self.exclusion_areas_list = [] FlatCAMTool.FlatCAMTool.delete_moving_selection_shape(self) self.app.delete_selection_shape() + FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) + + # restore the default StyleSheet + self.ui.generate_cnc_button.setStyleSheet("") + # update the StyleSheet + self.ui.generate_cnc_button.setStyleSheet(""" + QPushButton + { + font-weight: bold; + } + """) + self.ui.generate_cnc_button.setToolTip('%s' % _("Generate the CNC Job object.")) @staticmethod def merge(geo_list, geo_final, multigeo=None): diff --git a/flatcamTools/ToolNCC.py b/flatcamTools/ToolNCC.py index 01b879b9..0b80c735 100644 --- a/flatcamTools/ToolNCC.py +++ b/flatcamTools/ToolNCC.py @@ -2066,6 +2066,7 @@ class NonCopperClear(FlatCAMTool, Gerber): # unfortunately for this function to work time efficient, # if the Gerber was loaded without buffering then it require the buffering now. + # TODO 'buffering status' should be a property of the object not the project property if self.app.defaults['gerber_buffering'] == 'no': self.solid_geometry = ncc_obj.solid_geometry.buffer(0) else: @@ -2158,6 +2159,7 @@ class NonCopperClear(FlatCAMTool, Gerber): self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering")) sol_geo = sol_geo.buffer(distance=ncc_offset) self.app.inform.emit('[success] %s ...' % _("Buffering finished")) + empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box) if empty == 'fail': return 'fail' @@ -2203,14 +2205,15 @@ class NonCopperClear(FlatCAMTool, Gerber): """ Clear the excess copper from the entire object. - :param ncc_obj: ncc cleared object + :param ncc_obj: ncc cleared object :param sel_obj: - :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear - :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation - :param outname: name of the resulting object - :param order: - :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one. - Usage of the different one is related to when this function is called from a TcL command. + :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear + :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation + :param outname: name of the resulting object + :param order: Tools order + :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one. + Usage of the different one is related to when this function is called + from a TcL command. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will run non-threaded for TclShell usage @@ -3870,6 +3873,11 @@ class NonCopperClear(FlatCAMTool, Gerber): Returns the complement of target geometry within the given boundary polygon. If not specified, it defaults to the rectangular bounding box of target geometry. + + :param target: The geometry that is to be 'inverted' + :param boundary: A polygon that surrounds the entire solid geometry and from which we subtract in order to + create a "negative" geometry (geometry to be emptied of copper) + :return: """ if isinstance(target, Polygon): geo_len = 1 @@ -3882,6 +3890,7 @@ class NonCopperClear(FlatCAMTool, Gerber): boundary = target.envelope else: boundary = boundary + try: ret_val = boundary.difference(target) except Exception: @@ -3889,10 +3898,10 @@ class NonCopperClear(FlatCAMTool, Gerber): for el in target: # provide the app with a way to process the GUI events when in a blocking loop QtWidgets.QApplication.processEvents() - if self.app.abort_flag: # graceful abort requested by the user raise grace + boundary = boundary.difference(el) pol_nr += 1 disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100])) From 343d4ee534d24549b04f9647543bc21cc3fa9294 Mon Sep 17 00:00:00 2001 From: Marius Stanciu Date: Wed, 6 May 2020 03:44:56 +0300 Subject: [PATCH 2/4] - changed the above: too many shapes collections and the performance will go down. Created a class Exclusion areas that holds all the require properties and the Object UI elements will connect to it's methods. This way I can apply this to Excellon object too (who are a special type of Geometry Object) --- CHANGELOG.md | 1 + FlatCAMApp.py | 7 +- FlatCAMCommon.py | 368 ++++++++++++++++++++++++++++++ flatcamObjects/FlatCAMGeometry.py | 302 ++---------------------- 4 files changed, 390 insertions(+), 288 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5be0edb1..6a962f28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ CHANGELOG for FlatCAM beta 6.05.2020 - wip in adding Exclusion areas in Geometry object; each Geometry object has now a storage for shapes (exclusion shapes, should I make them more general?) +- changed the above: too many shapes collections and the performance will go down. Created a class Exclusion areas that holds all the require properties and the Object UI elements will connect to it's methods. This way I can apply this to Excellon object too (who are a special type of Geometry Object) 5.05.2020 diff --git a/FlatCAMApp.py b/FlatCAMApp.py index 3ac389df..16c54bf9 100644 --- a/FlatCAMApp.py +++ b/FlatCAMApp.py @@ -43,7 +43,7 @@ import socket # #################################################################################################################### # Diverse -from FlatCAMCommon import LoudDict, color_variant +from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas from FlatCAMBookmark import BookmarkManager from FlatCAMDB import ToolsDB2 @@ -1601,6 +1601,11 @@ class App(QtCore.QObject): self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T') self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True) + # ########################################################################################################### + # ########################################### EXCLUSION AREAS ############################################### + # ########################################################################################################### + self.exc_areas = ExclusionAreas(app=self) + # ########################################################################################################### # ##################################### Finished the CONSTRUCTOR ############################################ # ########################################################################################################### diff --git a/FlatCAMCommon.py b/FlatCAMCommon.py index 952ed0cd..f9e8c3f6 100644 --- a/FlatCAMCommon.py +++ b/FlatCAMCommon.py @@ -11,6 +11,13 @@ # Date: 11/4/2019 # # ########################################################## +from shapely.geometry import Polygon, MultiPolygon + +from flatcamGUI.VisPyVisuals import ShapeCollection +from FlatCAMTool import FlatCAMTool + +import numpy as np + import gettext import FlatCAMTranslation as fcTranslate import builtins @@ -119,3 +126,364 @@ def color_variant(hex_color, bright_factor=1): new_rgb.append(mod_color_hex) return "#" + "".join([i for i in new_rgb]) + + +class ExclusionAreas: + + def __init__(self, app): + self.app = app + + # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry + # VisPy visuals + if self.app.is_legacy is False: + try: + self.exclusion_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1) + except AttributeError: + self.exclusion_shapes = None + else: + from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy + self.exclusion_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name="exclusion") + + # Event signals disconnect id holders + self.mr = None + self.mm = None + self.kp = None + + # variables to be used in area exclusion + self.cursor_pos = (0, 0) + self.first_click = False + self.points = [] + self.poly_drawn = False + + ''' + Here we store the exclusion shapes and some other information's + Each list element is a dictionary with the format: + + { + "obj_type": string ("excellon" or "geometry") <- self.obj_type + "shape": Shapely polygon + "strategy": string ("over" or "around") <- self.strategy + "overz": float <- self.over_z + } + ''' + self.exclusion_areas_storage = [] + + self.mouse_is_dragging = False + + self.solid_geometry = [] + self.obj_type = None + + self.shape_type = 'square' # TODO use the self.app.defaults when made general (not in Geo object Pref UI) + self.over_z = 0.1 + self.strategy = None + self.cnc_button = None + + def on_add_area_click(self, shape_button, overz_button, strategy_radio, cnc_button, solid_geo, obj_type): + """ + + :param shape_button: a FCButton that has the value for the shape + :param overz_button: a FCDoubleSpinner that holds the Over Z value + :param strategy_radio: a RadioSet button with the strategy value + :param cnc_button: a FCButton in Object UI that when clicked the CNCJob is created + We have a reference here so we can change the color signifying that exclusion areas are + available. + :param solid_geo: reference to the object solid geometry for which we add exclusion areas + :param obj_type: Type of FlatCAM object that called this method + :type obj_type: String: "excellon" or "geometry" + :return: + """ + self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area.")) + self.app.call_source = 'geometry' + + self.shape_type = shape_button.get_value() + self.over_z = overz_button.get_value() + self.strategy = strategy_radio.get_value() + self.cnc_button = cnc_button + + self.solid_geometry = solid_geo + self.obj_type = obj_type + + if self.app.is_legacy is False: + self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot) + self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot) + self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot) + else: + self.app.plotcanvas.graph_event_disconnect(self.app.mp) + self.app.plotcanvas.graph_event_disconnect(self.app.mm) + self.app.plotcanvas.graph_event_disconnect(self.app.mr) + + self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release) + self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move) + # self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press) + + # To be called after clicking on the plot. + def on_mouse_release(self, event): + if self.app.is_legacy is False: + event_pos = event.pos + # event_is_dragging = event.is_dragging + right_button = 2 + else: + event_pos = (event.xdata, event.ydata) + # event_is_dragging = self.app.plotcanvas.is_dragging + right_button = 3 + + event_pos = self.app.plotcanvas.translate_coords(event_pos) + if self.app.grid_status(): + curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1]) + else: + curr_pos = (event_pos[0], event_pos[1]) + + x1, y1 = curr_pos[0], curr_pos[1] + + # shape_type = self.ui.area_shape_radio.get_value() + + # do clear area only for left mouse clicks + if event.button == 1: + if self.shape_type == "square": + if self.first_click is False: + self.first_click = True + self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area.")) + + self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos) + if self.app.grid_status(): + self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1]) + else: + self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish.")) + self.app.delete_selection_shape() + + x0, y0 = self.cursor_pos[0], self.cursor_pos[1] + + pt1 = (x0, y0) + pt2 = (x1, y0) + pt3 = (x1, y1) + pt4 = (x0, y1) + + new_rectangle = Polygon([pt1, pt2, pt3, pt4]) + + # { + # "obj_type": string("excellon" or "geometry") < - self.obj_type + # "shape": Shapely polygon + # "strategy": string("over" or "around") < - self.strategy + # "overz": float < - self.over_z + # } + new_el = { + "obj_type": self.obj_type, + "shape": new_rectangle, + "strategy": self.strategy, + "overz": self.over_z + } + self.exclusion_areas_storage.append(new_el) + + # add a temporary shape on canvas + FlatCAMTool.draw_tool_selection_shape( + self, old_coords=(x0, y0), coords=(x1, y1), + color="#FF7400", + face_color="#FF7400BF", + shapes_storage=self.exclusion_shapes) + + self.first_click = False + return + else: + self.points.append((x1, y1)) + + if len(self.points) > 1: + self.poly_drawn = True + self.app.inform.emit(_("Click on next Point or click right mouse button to complete ...")) + + return "" + elif event.button == right_button and self.mouse_is_dragging is False: + + shape_type = self.shape_type + + if shape_type == "square": + self.first_click = False + else: + # if we finish to add a polygon + if self.poly_drawn is True: + try: + # try to add the point where we last clicked if it is not already in the self.points + last_pt = (x1, y1) + if last_pt != self.points[-1]: + self.points.append(last_pt) + except IndexError: + pass + + # we need to add a Polygon and a Polygon can be made only from at least 3 points + if len(self.points) > 2: + FlatCAMTool.delete_moving_selection_shape(self) + pol = Polygon(self.points) + # do not add invalid polygons even if they are drawn by utility geometry + if pol.is_valid: + # { + # "obj_type": string("excellon" or "geometry") < - self.obj_type + # "shape": Shapely polygon + # "strategy": string("over" or "around") < - self.strategy + # "overz": float < - self.over_z + # } + new_el = { + "obj_type": self.obj_type, + "shape": pol, + "strategy": self.strategy, + "overz": self.over_z + } + self.exclusion_areas_storage.append(new_el) + FlatCAMTool.draw_selection_shape_polygon( + self, points=self.points, + color="#FF7400", + face_color="#FF7400BF", + shapes_storage=self.exclusion_shapes) + self.app.inform.emit( + _("Zone added. Click to start adding next zone or right click to finish.")) + + self.points = [] + self.poly_drawn = False + return + + # FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) + + if self.app.is_legacy is False: + self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release) + self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move) + # self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press) + else: + self.app.plotcanvas.graph_event_disconnect(self.mr) + self.app.plotcanvas.graph_event_disconnect(self.mm) + # self.app.plotcanvas.graph_event_disconnect(self.kp) + + self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', + self.app.on_mouse_click_over_plot) + self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', + self.app.on_mouse_move_over_plot) + self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release', + self.app.on_mouse_click_release_over_plot) + + self.app.call_source = 'app' + + if len(self.exclusion_areas_storage) == 0: + return + + self.app.inform.emit( + "[success] %s" % _("Exclusion areas added. Checking overlap with the object geometry ...")) + + for el in self.exclusion_areas_storage: + if el["shape"].intersects(MultiPolygon(self.solid_geometry)): + self.on_clear_area_click() + self.app.inform.emit( + "[ERROR_NOTCL] %s" % _("Failed. Exclusion areas intersects the object geometry ...")) + return + + self.app.inform.emit( + "[success] %s" % _("Exclusion areas added.")) + self.cnc_button.setStyleSheet(""" + QPushButton + { + font-weight: bold; + color: orange; + } + """) + self.cnc_button.setToolTip( + '%s %s' % (_("Generate the CNC Job object."), _("With Exclusion areas.")) + ) + + for k in self.exclusion_areas_storage: + print(k) + + def area_disconnect(self): + if self.app.is_legacy is False: + self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release) + self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move) + else: + self.app.plotcanvas.graph_event_disconnect(self.mr) + self.app.plotcanvas.graph_event_disconnect(self.mm) + self.app.plotcanvas.graph_event_disconnect(self.kp) + + self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', + self.app.on_mouse_click_over_plot) + self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', + self.app.on_mouse_move_over_plot) + self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release', + self.app.on_mouse_click_release_over_plot) + self.points = [] + self.poly_drawn = False + self.exclusion_areas_storage = [] + + FlatCAMTool.delete_moving_selection_shape(self) + # FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) + + self.app.call_source = "app" + self.app.inform.emit("[WARNING_NOTCL] %s" % _("Cancelled. Area exclusion drawing was interrupted.")) + + # called on mouse move + def on_mouse_move(self, event): + shape_type = self.shape_type + + if self.app.is_legacy is False: + event_pos = event.pos + event_is_dragging = event.is_dragging + # right_button = 2 + else: + event_pos = (event.xdata, event.ydata) + event_is_dragging = self.app.plotcanvas.is_dragging + # right_button = 3 + + curr_pos = self.app.plotcanvas.translate_coords(event_pos) + + # detect mouse dragging motion + if event_is_dragging is True: + self.mouse_is_dragging = True + else: + self.mouse_is_dragging = False + + # update the cursor position + if self.app.grid_status(): + # Update cursor + curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1]) + + self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]), + symbol='++', edge_color=self.app.cursor_color_3D, + edge_width=self.app.defaults["global_cursor_width"], + size=self.app.defaults["global_cursor_size"]) + + # update the positions on status bar + self.app.ui.position_label.setText("    X: %.4f   " + "Y: %.4f" % (curr_pos[0], curr_pos[1])) + if self.cursor_pos is None: + self.cursor_pos = (0, 0) + + self.app.dx = curr_pos[0] - float(self.cursor_pos[0]) + self.app.dy = curr_pos[1] - float(self.cursor_pos[1]) + self.app.ui.rel_position_label.setText("Dx: %.4f   Dy: " + "%.4f    " % (self.app.dx, self.app.dy)) + + # draw the utility geometry + if shape_type == "square": + if self.first_click: + self.app.delete_selection_shape() + self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]), + color="#FF7400", + face_color="#FF7400BF", + coords=(curr_pos[0], curr_pos[1])) + else: + FlatCAMTool.delete_moving_selection_shape(self) + FlatCAMTool.draw_moving_selection_shape_poly( + self, points=self.points, + color="#FF7400", + face_color="#FF7400BF", + data=(curr_pos[0], curr_pos[1])) + + def on_clear_area_click(self): + self.exclusion_areas_storage.clear() + FlatCAMTool.delete_moving_selection_shape(self) + self.app.delete_selection_shape() + FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) + + # restore the default StyleSheet + self.cnc_button.setStyleSheet("") + # update the StyleSheet + self.cnc_button.setStyleSheet(""" + QPushButton + { + font-weight: bold; + } + """) + self.cnc_button.setToolTip('%s' % _("Generate the CNC Job object.")) diff --git a/flatcamObjects/FlatCAMGeometry.py b/flatcamObjects/FlatCAMGeometry.py index 62d5924d..1d2bad73 100644 --- a/flatcamObjects/FlatCAMGeometry.py +++ b/flatcamObjects/FlatCAMGeometry.py @@ -16,8 +16,6 @@ import shapely.affinity as affinity from camlib import Geometry from flatcamObjects.FlatCAMObj import * -from flatcamGUI.VisPyVisuals import ShapeCollection -import FlatCAMTool import ezdxf import math @@ -152,30 +150,6 @@ class GeometryObject(FlatCAMObj, Geometry): self.param_fields = {} - # Event signals disconnect id holders - self.mr = None - self.mm = None - self.kp = None - - # variables to be used in area exclusion - self.cursor_pos = (0, 0) - self.exclusion_areas_list = [] - self.first_click = False - self.points = [] - self.poly_drawn = False - - # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry - # VisPy visuals - if self.app.is_legacy is False: - try: - self.exclusion_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1) - except AttributeError: - self.exclusion_shapes = None - else: - from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy - self.exclusion_shapes = ShapeCollectionLegacy( - obj=self, app=self.app, name="exclusion" + self.options['name']) - # Attributes to be included in serialization # Always append to it because it carries contents # from predecessors. @@ -2479,6 +2453,21 @@ class GeometryObject(FlatCAMObj, Geometry): return factor + def on_add_area_click(self): + shape_button = self.ui.area_shape_radio + overz_button = self.ui.over_z_entry + strategy_radio = self.ui.strategy_radio + cnc_button = self.ui.generate_cnc_button + solid_geo = self.solid_geometry + obj_type = self.kind + + self.app.exc_areas.on_add_area_click( + shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio, + solid_geo=solid_geo, obj_type=obj_type) + + def on_clear_area_click(self): + self.app.exc_areas.on_clear_area_click() + def plot_element(self, element, color=None, visible=None): if color is None: @@ -2583,267 +2572,6 @@ class GeometryObject(FlatCAMObj, Geometry): self.ui.plot_cb.setChecked(True) self.ui_connect() - def on_add_area_click(self): - self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area.")) - self.app.call_source = 'geometry' - - if self.app.is_legacy is False: - self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot) - self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot) - self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot) - else: - self.app.plotcanvas.graph_event_disconnect(self.app.mp) - self.app.plotcanvas.graph_event_disconnect(self.app.mm) - self.app.plotcanvas.graph_event_disconnect(self.app.mr) - - self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release) - self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move) - # self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press) - - # To be called after clicking on the plot. - def on_mouse_release(self, event): - if self.app.is_legacy is False: - event_pos = event.pos - # event_is_dragging = event.is_dragging - right_button = 2 - else: - event_pos = (event.xdata, event.ydata) - # event_is_dragging = self.app.plotcanvas.is_dragging - right_button = 3 - - event_pos = self.app.plotcanvas.translate_coords(event_pos) - if self.app.grid_status(): - curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1]) - else: - curr_pos = (event_pos[0], event_pos[1]) - - x1, y1 = curr_pos[0], curr_pos[1] - - shape_type = self.ui.area_shape_radio.get_value() - - # do clear area only for left mouse clicks - if event.button == 1: - if shape_type == "square": - if self.first_click is False: - self.first_click = True - self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area.")) - - self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos) - if self.app.grid_status(): - self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1]) - else: - self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish.")) - self.app.delete_selection_shape() - - x0, y0 = self.cursor_pos[0], self.cursor_pos[1] - - pt1 = (x0, y0) - pt2 = (x1, y0) - pt3 = (x1, y1) - pt4 = (x0, y1) - - new_rectangle = Polygon([pt1, pt2, pt3, pt4]) - self.exclusion_areas_list.append(new_rectangle) - - # add a temporary shape on canvas - FlatCAMTool.FlatCAMTool.draw_tool_selection_shape( - self, old_coords=(x0, y0), coords=(x1, y1), - color="#FF7400", - face_color="#FF7400BF", - shapes_storage=self.exclusion_shapes) - - self.first_click = False - return - else: - self.points.append((x1, y1)) - - if len(self.points) > 1: - self.poly_drawn = True - self.app.inform.emit(_("Click on next Point or click right mouse button to complete ...")) - - return "" - elif event.button == right_button and self.mouse_is_dragging is False: - - shape_type = self.ui.area_shape_radio.get_value() - - if shape_type == "square": - self.first_click = False - else: - # if we finish to add a polygon - if self.poly_drawn is True: - try: - # try to add the point where we last clicked if it is not already in the self.points - last_pt = (x1, y1) - if last_pt != self.points[-1]: - self.points.append(last_pt) - except IndexError: - pass - - # we need to add a Polygon and a Polygon can be made only from at least 3 points - if len(self.points) > 2: - FlatCAMTool.FlatCAMTool.delete_moving_selection_shape(self) - pol = Polygon(self.points) - # do not add invalid polygons even if they are drawn by utility geometry - if pol.is_valid: - self.exclusion_areas_list.append(pol) - FlatCAMTool.FlatCAMTool.draw_selection_shape_polygon( - self, points=self.points, - color="#FF7400", - face_color="#FF7400BF", - shapes_storage=self.exclusion_shapes) - self.app.inform.emit( - _("Zone added. Click to start adding next zone or right click to finish.")) - - self.points = [] - self.poly_drawn = False - return - - # FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) - - if self.app.is_legacy is False: - self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release) - self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move) - # self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press) - else: - self.app.plotcanvas.graph_event_disconnect(self.mr) - self.app.plotcanvas.graph_event_disconnect(self.mm) - # self.app.plotcanvas.graph_event_disconnect(self.kp) - - self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', - self.app.on_mouse_click_over_plot) - self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', - self.app.on_mouse_move_over_plot) - self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release', - self.app.on_mouse_click_release_over_plot) - - self.app.call_source = 'app' - - if len(self.exclusion_areas_list) == 0: - return - else: - self.exclusion_areas_list = MultiPolygon(self.exclusion_areas_list) - - self.app.inform.emit( - "[success] %s" % _("Exclusion areas added. Checking overlap with the object geometry ...")) - if self.exclusion_areas_list.intersects(MultiPolygon(self.solid_geometry)): - self.exclusion_areas_list = [] - self.app.inform.emit( - "[ERROR_NOTCL] %s" % _("Failed. Exclusion areas intersects the object geometry ...")) - return - else: - self.app.inform.emit( - "[success] %s" % _("Exclusion areas added.")) - self.ui.generate_cnc_button.setStyleSheet(""" - QPushButton - { - font-weight: bold; - color: orange; - } - """) - self.ui.generate_cnc_button.setToolTip( - '%s %s' % (_("Generate the CNC Job object."), _("With Exclusion areas.")) - ) - - def area_disconnect(self): - if self.app.is_legacy is False: - self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release) - self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move) - else: - self.app.plotcanvas.graph_event_disconnect(self.mr) - self.app.plotcanvas.graph_event_disconnect(self.mm) - self.app.plotcanvas.graph_event_disconnect(self.kp) - - self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', - self.app.on_mouse_click_over_plot) - self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', - self.app.on_mouse_move_over_plot) - self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release', - self.app.on_mouse_click_release_over_plot) - self.points = [] - self.poly_drawn = False - self.exclusion_areas_list = [] - - FlatCAMTool.FlatCAMTool.delete_moving_selection_shape(self) - # FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) - - self.app.call_source = "app" - self.app.inform.emit("[WARNING_NOTCL] %s" % _("Cancelled. Area exclusion drawing was interrupted.")) - - # called on mouse move - def on_mouse_move(self, event): - shape_type = self.ui.area_shape_radio.get_value() - - if self.app.is_legacy is False: - event_pos = event.pos - event_is_dragging = event.is_dragging - # right_button = 2 - else: - event_pos = (event.xdata, event.ydata) - event_is_dragging = self.app.plotcanvas.is_dragging - # right_button = 3 - - curr_pos = self.app.plotcanvas.translate_coords(event_pos) - - # detect mouse dragging motion - if event_is_dragging is True: - self.mouse_is_dragging = True - else: - self.mouse_is_dragging = False - - # update the cursor position - if self.app.grid_status(): - # Update cursor - curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1]) - - self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]), - symbol='++', edge_color=self.app.cursor_color_3D, - edge_width=self.app.defaults["global_cursor_width"], - size=self.app.defaults["global_cursor_size"]) - - # update the positions on status bar - self.app.ui.position_label.setText("    X: %.4f   " - "Y: %.4f" % (curr_pos[0], curr_pos[1])) - if self.cursor_pos is None: - self.cursor_pos = (0, 0) - - self.app.dx = curr_pos[0] - float(self.cursor_pos[0]) - self.app.dy = curr_pos[1] - float(self.cursor_pos[1]) - self.app.ui.rel_position_label.setText("Dx: %.4f   Dy: " - "%.4f    " % (self.app.dx, self.app.dy)) - - # draw the utility geometry - if shape_type == "square": - if self.first_click: - self.app.delete_selection_shape() - self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]), - color="#FF7400", - face_color="#FF7400BF", - coords=(curr_pos[0], curr_pos[1])) - else: - FlatCAMTool.FlatCAMTool.delete_moving_selection_shape(self) - FlatCAMTool.FlatCAMTool.draw_moving_selection_shape_poly( - self, points=self.points, - color="#FF7400", - face_color="#FF7400BF", - data=(curr_pos[0], curr_pos[1])) - - def on_clear_area_click(self): - self.exclusion_areas_list = [] - FlatCAMTool.FlatCAMTool.delete_moving_selection_shape(self) - self.app.delete_selection_shape() - FlatCAMTool.FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) - - # restore the default StyleSheet - self.ui.generate_cnc_button.setStyleSheet("") - # update the StyleSheet - self.ui.generate_cnc_button.setStyleSheet(""" - QPushButton - { - font-weight: bold; - } - """) - self.ui.generate_cnc_button.setToolTip('%s' % _("Generate the CNC Job object.")) - @staticmethod def merge(geo_list, geo_final, multigeo=None): """ From afbe2d974f21293ca6342398440aef95d59a7b7c Mon Sep 17 00:00:00 2001 From: Marius Stanciu Date: Wed, 6 May 2020 04:11:31 +0300 Subject: [PATCH 3/4] - handled the New project event and the object deletion (when all objects are deleted then the exclusion areas will be deleted too) --- CHANGELOG.md | 7 ++++--- FlatCAMApp.py | 12 +++++++----- FlatCAMCommon.py | 11 +++++++---- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a962f28..2269d4d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,16 +10,17 @@ CHANGELOG for FlatCAM beta 6.05.2020 - wip in adding Exclusion areas in Geometry object; each Geometry object has now a storage for shapes (exclusion shapes, should I make them more general?) -- changed the above: too many shapes collections and the performance will go down. Created a class Exclusion areas that holds all the require properties and the Object UI elements will connect to it's methods. This way I can apply this to Excellon object too (who are a special type of Geometry Object) +- changed the above: too many shapes collections and the performance will go down. Created a class ExclusionAreas that holds all the require properties and the Object UI elements will connect to it's methods. This way I can apply this feature to Excellon object too (who is a special type of Geometry Object) +- handled the New project event and the object deletion (when all objects are deleted then the exclusion areas will be deleted too) 5.05.2020 -- fixed an issue that made the preprocessors comboxes in Preferences not to load and display the saved value fro the file +- fixed an issue that made the preprocessors combo boxes in Preferences not to load and display the saved value fro the file - some PEP8 corrections 4.05.2020 -- in detachable tabs, Linux loose the reference of the detached tab and on close of the detachable tabs will gave a 'segmantation fault' error. Solved it by not deleting the reference in case of Unix-like systems +- in detachable tabs, Linux loose the reference of the detached tab and on close of the detachable tabs will gave a 'segmentation fault' error. Solved it by not deleting the reference in case of Unix-like systems - some strings added to translation strings 3.05.2020 diff --git a/FlatCAMApp.py b/FlatCAMApp.py index 16c54bf9..994f422e 100644 --- a/FlatCAMApp.py +++ b/FlatCAMApp.py @@ -5130,11 +5130,6 @@ class App(QtCore.QObject): obj_active.mark_shapes[el].enabled = False # obj_active.mark_shapes[el] = None del el - # if the deleted object is GerberObject then make sure to delete the possible mark shapes - if obj_active.kind == 'geometry': - obj_active.exclusion_shapes.clear(update=True) - obj_active.exclusion_shapes.enabled = False - del obj_active.exclusion_shapes elif isinstance(obj_active, CNCJobObject): try: obj_active.text_col.enabled = False @@ -5152,6 +5147,10 @@ class App(QtCore.QObject): self.inform.emit('%s...' % _("Object(s) deleted")) # make sure that the selection shape is deleted, too self.delete_selection_shape() + + # if there are no longer objects delete also the exclusion areas shapes + if not self.collection.get_list(): + self.exc_areas.clear_shapes() else: self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected...")) else: @@ -7419,6 +7418,9 @@ class App(QtCore.QObject): except AttributeError: pass + # delete the exclusion areas + self.exc_areas.clear_shapes() + # tcl needs to be reinitialized, otherwise old shell variables etc remains self.shell.init_tcl() diff --git a/FlatCAMCommon.py b/FlatCAMCommon.py index f9e8c3f6..8897662e 100644 --- a/FlatCAMCommon.py +++ b/FlatCAMCommon.py @@ -472,10 +472,7 @@ class ExclusionAreas: data=(curr_pos[0], curr_pos[1])) def on_clear_area_click(self): - self.exclusion_areas_storage.clear() - FlatCAMTool.delete_moving_selection_shape(self) - self.app.delete_selection_shape() - FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) + self.clear_shapes() # restore the default StyleSheet self.cnc_button.setStyleSheet("") @@ -487,3 +484,9 @@ class ExclusionAreas: } """) self.cnc_button.setToolTip('%s' % _("Generate the CNC Job object.")) + + def clear_shapes(self): + self.exclusion_areas_storage.clear() + FlatCAMTool.delete_moving_selection_shape(self) + self.app.delete_selection_shape() + FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) From a161354c25e5d624f9332afcaf27cf12a7741d1c Mon Sep 17 00:00:00 2001 From: Marius Stanciu Date: Wed, 6 May 2020 16:37:48 +0300 Subject: [PATCH 4/4] - solved issue with new parameter end_xy when it is None - solved issue with applying theme and not making the change in the Preferences UI. In Preferences UI the theme radio is always Light (white) - now the annotations will invert the selected color in the Preferences, when selecting Dark theme --- CHANGELOG.md | 3 + FlatCAMApp.py | 3 + FlatCAMCommon.py | 25 +++ camlib.py | 155 ++++++------------ .../general/GeneralGUIPrefGroupUI.py | 17 +- 5 files changed, 96 insertions(+), 107 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2269d4d0..fbcc3f4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ CHANGELOG for FlatCAM beta - wip in adding Exclusion areas in Geometry object; each Geometry object has now a storage for shapes (exclusion shapes, should I make them more general?) - changed the above: too many shapes collections and the performance will go down. Created a class ExclusionAreas that holds all the require properties and the Object UI elements will connect to it's methods. This way I can apply this feature to Excellon object too (who is a special type of Geometry Object) - handled the New project event and the object deletion (when all objects are deleted then the exclusion areas will be deleted too) +- solved issue with new parameter end_xy when it is None +- solved issue with applying theme and not making the change in the Preferences UI. In Preferences UI the theme radio is always Light (white) +- now the annotations will invert the selected color in the Preferences, when selecting Dark theme 5.05.2020 diff --git a/FlatCAMApp.py b/FlatCAMApp.py index 994f422e..eb4e9569 100644 --- a/FlatCAMApp.py +++ b/FlatCAMApp.py @@ -522,6 +522,9 @@ class App(QtCore.QObject): else: self.cursor_color_3D = 'gray' + # update the defaults dict with the setting in QSetting + self.defaults['global_theme'] = theme + self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry) self.ui.final_save.connect(self.final_save) diff --git a/FlatCAMCommon.py b/FlatCAMCommon.py index 8897662e..c29ac4f3 100644 --- a/FlatCAMCommon.py +++ b/FlatCAMCommon.py @@ -17,6 +17,7 @@ from flatcamGUI.VisPyVisuals import ShapeCollection from FlatCAMTool import FlatCAMTool import numpy as np +import re import gettext import FlatCAMTranslation as fcTranslate @@ -490,3 +491,27 @@ class ExclusionAreas: FlatCAMTool.delete_moving_selection_shape(self) self.app.delete_selection_shape() FlatCAMTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes) + + +class InvertHexColor: + """ + Will invert a hex color made out of 3 chars or 6 chars + From here: http://code.activestate.com/recipes/527747-invert-css-hex-colors/ + """ + def __init__(self): + self.p6 = re.compile("#[0-9a-f]{6};", re.IGNORECASE) + self.p3 = re.compile("#[0-9a-f]{3};", re.IGNORECASE) + + def modify(self, original_color=3): + code = {} + l1 = "#;0123456789abcdef" + l2 = "#;fedcba9876543210" + + for i in range(len(l1)): + code[l1[i]] = l2[i] + inverted = "" + + content = p6.sub(modify, content) + content = p3.sub(modify, content) + return inverted + diff --git a/camlib.py b/camlib.py index 6e5bdcf2..e7070fa4 100644 --- a/camlib.py +++ b/camlib.py @@ -2671,8 +2671,11 @@ class CNCjob(Geometry): if self.xy_toolchange == '': self.xy_toolchange = None else: - self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) - self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",") if self.xy_toolchange != ''] + self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None + + if self.xy_toolchange and self.xy_toolchange != '': + self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")] + if self.xy_toolchange and len(self.xy_toolchange) < 2: self.app.inform.emit('[ERROR]%s' % _("The Toolchange X,Y field in Edit -> Preferences has to be " @@ -2682,8 +2685,11 @@ class CNCjob(Geometry): log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e)) pass - self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) - self.xy_end = [float(eval(a)) for a in self.xy_end.split(",") if self.xy_end != ''] + self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None + + if self.xy_end and self.xy_end != '': + self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")] + if self.xy_end and len(self.xy_end) < 2: self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be " "in the format (x, y) but now there is only one value, not two.")) @@ -3583,8 +3589,11 @@ class CNCjob(Geometry): self.startz = float(startz) if startz is not None else None self.z_end = float(endz) if endz is not None else None - self.xy_end = re.sub('[()\[\]]', '', str(endxy)) - self.xy_end = [float(eval(a)) for a in self.xy_end.split(",") if endxy != ''] + self.xy_end = re.sub('[()\[\]]', '', str(endxy)) if endxy else None + + if self.xy_end and self.xy_end != '': + self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")] + if self.xy_end and len(self.xy_end) < 2: self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be " "in the format (x, y) but now there is only one value, not two.")) @@ -3602,8 +3611,11 @@ class CNCjob(Geometry): if toolchangexy == '': self.xy_toolchange = None else: - self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) - self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")] + self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if toolchangexy else None + + if self.xy_toolchange and self.xy_toolchange != '': + self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")] + if len(self.xy_toolchange) < 2: self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be " "in the format (x, y) \n" @@ -3970,9 +3982,12 @@ class CNCjob(Geometry): self.startz = float(startz) if startz is not None else self.app.defaults["geometry_startz"] self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"] - self.xy_end = endxy if endxy != '' else self.app.defaults["geometry_endxy"] - self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) - self.xy_end = [float(eval(a)) for a in self.xy_end.split(",") if self.xy_end != ''] + self.xy_end = endxy if endxy != '' and endxy else self.app.defaults["geometry_endxy"] + self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None + + if self.xy_end is not None and self.xy_end != '': + self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")] + if self.xy_end and len(self.xy_end) < 2: self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be " "in the format (x, y) but now there is only one value, not two.")) @@ -3988,8 +4003,11 @@ class CNCjob(Geometry): if toolchangexy == '': self.xy_toolchange = None else: - self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) - self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")] + self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if self.xy_toolchange else None + + if self.xy_toolchange and self.xy_toolchange != '': + self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")] + if len(self.xy_toolchange) < 2: self.app.inform.emit( '[ERROR] %s' % @@ -4875,97 +4893,30 @@ class CNCjob(Geometry): if geo['kind'][0] == 'C': obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0], visible=visible, layer=1) - # current_x = gcode_parsed[0]['geom'].coords[0][0] - # current_y = gcode_parsed[0]['geom'].coords[0][1] - # old_pos = ( - # current_x, - # current_y - # ) - # - # for geo in gcode_parsed: - # if geo['kind'][0] == 'T': - # current_position = ( - # geo['geom'].coords[0][0] + old_pos[0], - # geo['geom'].coords[0][1] + old_pos[1] - # ) - # if current_position not in pos: - # pos.append(current_position) - # path_num += 1 - # text.append(str(path_num)) - # - # delta = ( - # geo['geom'].coords[-1][0] - geo['geom'].coords[0][0], - # geo['geom'].coords[-1][1] - geo['geom'].coords[0][1] - # ) - # current_position = ( - # current_position[0] + geo['geom'].coords[-1][0], - # current_position[1] + geo['geom'].coords[-1][1] - # ) - # if current_position not in pos: - # pos.append(current_position) - # path_num += 1 - # text.append(str(path_num)) - # - # # plot the geometry of Excellon objects - # if self.origin_kind == 'excellon': - # if isinstance(geo['geom'], Point): - # # if geo is Point - # current_position = ( - # current_position[0] + geo['geom'].x, - # current_position[1] + geo['geom'].y - # ) - # poly = Polygon(Point(current_position)) - # elif isinstance(geo['geom'], LineString): - # # if the geos are travel lines (LineStrings) - # new_line_pts = [] - # old_line_pos = deepcopy(current_position) - # for p in list(geo['geom'].coords): - # current_position = ( - # current_position[0] + p[0], - # current_position[1] + p[1] - # ) - # new_line_pts.append(current_position) - # old_line_pos = p - # new_line = LineString(new_line_pts) - # - # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle) - # poly = poly.simplify(tool_tolerance) - # else: - # # plot the geometry of any objects other than Excellon - # new_line_pts = [] - # old_line_pos = deepcopy(current_position) - # for p in list(geo['geom'].coords): - # current_position = ( - # current_position[0] + p[0], - # current_position[1] + p[1] - # ) - # new_line_pts.append(current_position) - # old_line_pos = p - # new_line = LineString(new_line_pts) - # - # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle) - # poly = poly.simplify(tool_tolerance) - # - # old_pos = deepcopy(current_position) - # - # if kind == 'all': - # obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0], - # visible=visible, layer=1 if geo['kind'][0] == 'C' else 2) - # elif kind == 'travel': - # if geo['kind'][0] == 'T': - # obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0], - # visible=visible, layer=2) - # elif kind == 'cut': - # if geo['kind'][0] == 'C': - # obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0], - # visible=visible, layer=1) try: - obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'], - font_size=self.app.defaults["cncjob_annotation_fontsize"], - color=self.app.defaults["cncjob_annotation_fontcolor"]) - except Exception: - pass + if self.app.defaults['global_theme'] == 'white': + obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'], + font_size=self.app.defaults["cncjob_annotation_fontsize"], + color=self.app.defaults["cncjob_annotation_fontcolor"]) + else: + # invert the color + old_color = self.app.defaults["cncjob_annotation_fontcolor"].lower() + new_color = '' + code = {} + l1 = "#;0123456789abcdef" + l2 = "#;fedcba9876543210" + for i in range(len(l1)): + code[l1[i]] = l2[i] + + for x in range(len(old_color)): + new_color += code[old_color[x]] + + obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'], + font_size=self.app.defaults["cncjob_annotation_fontsize"], + color=new_color) + except Exception as e: + log.debug("CNCJob.plot2() --> annotations --> %s" % str(e)) def create_geometry(self): self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"), diff --git a/flatcamGUI/preferences/general/GeneralGUIPrefGroupUI.py b/flatcamGUI/preferences/general/GeneralGUIPrefGroupUI.py index 94044c27..d71fab4c 100644 --- a/flatcamGUI/preferences/general/GeneralGUIPrefGroupUI.py +++ b/flatcamGUI/preferences/general/GeneralGUIPrefGroupUI.py @@ -420,13 +420,20 @@ class GeneralGUIPrefGroupUI(OptionsGroupUI): def on_theme_change(self): val = self.theme_radio.get_value() - qsettings = QSettings("Open Source", "FlatCAM") - qsettings.setValue('theme', val) - # This will write the setting to the platform specific storage. - del qsettings + theme_settings = QtCore.QSettings("Open Source", "FlatCAM") + if theme_settings.contains("theme"): + theme = theme_settings.value('theme', type=str) + else: + theme = 'white' - self.app.on_app_restart() + if val != theme: + theme_settings.setValue('theme', val) + + # This will write the setting to the platform specific storage. + del theme_settings + + self.app.on_app_restart() @staticmethod def handle_style(style):