- replaced the testing if instance of FlatCAMObj with testing the obj.kind attribute

- removed the import of the whole FlatCAMApp file only for the usage of GracefulException
- remove the import of FlatCAMApp and used alternate ways
- optimized the imports in some files
- moved the Bookmarksmanager and ToolDB classes into their own files
- solved some bugs that were not so visible in the Editors and HPGL parser
This commit is contained in:
Marius Stanciu 2020-04-27 10:03:22 +03:00 committed by Marius
parent 61020e3624
commit 3ec666edbb
28 changed files with 3452 additions and 3389 deletions

View File

@ -13,6 +13,12 @@ CHANGELOG for FlatCAM beta
- updated the requirements.txt file to request that the Shapely package needs to be at least version 1.7.0 as it is needed in the latest versions of FlatCAM beta
- some TOOD cleanups
- minor changes
- replaced the testing if instance of FlatCAMObj with testing the obj.kind attribute
- removed the import of the whole FlatCAMApp file only for the usage of GracefulException
- remove the import of FlatCAMApp and used alternate ways
- optimized the imports in some files
- moved the Bookmarksmanager and ToolDB classes into their own files
- solved some bugs that were not so visible in the Editors and HPGL parser
25.04.2020

View File

@ -46,6 +46,10 @@ import socket
# #######################################
# # Imports part of FlatCAM ##
# #######################################
from FlatCAMCommon import LoudDict, color_variant
from FlatCAMBookmark import BookmarkManager
from FlatCAMDB import ToolsDB2
from ObjectCollection import *
from FlatCAMObj import *
from camlib import to_dict, dict2obj, ET, ParseError
@ -55,7 +59,6 @@ from flatcamGUI.PlotCanvasLegacy import *
from flatcamGUI.FlatCAMGUI import *
from flatcamGUI.GUIElements import FCFileSaveDialog
from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB, ToolsDB2, color_variant
from FlatCAMPostProc import load_preprocessors
from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
@ -4313,7 +4316,7 @@ class App(QtCore.QObject):
# update the KeyWords list with the name of the file
self.myKeywords.append(obj.options['name'])
FlatCAMApp.App.log.debug("Moving new object back to main thread.")
log.debug("Moving new object back to main thread.")
# Move the object to the main thread and let the app know that it is available.
obj.moveToThread(self.main_thread)
@ -12862,13 +12865,4 @@ class ArgsThread(QtCore.QObject):
def run(self):
self.my_loop(self.address)
class GracefulException(Exception):
# Graceful Exception raised when the user is requesting to cancel the current threaded task
def __init__(self):
super().__init__()
def __str__(self):
return '\n\n%s' % _("The user requested a graceful exit of the current task.")
# end of file

381
FlatCAMBookmark.py Normal file
View File

@ -0,0 +1,381 @@
from PyQt5 import QtGui, QtCore, QtWidgets
from flatcamGUI.GUIElements import FCTable, FCEntry, FCButton, FCFileSaveDialog
import sys
import webbrowser
from copy import deepcopy
from datetime import datetime
import gettext
import FlatCAMTranslation as fcTranslate
import builtins
fcTranslate.apply_language('strings')
if '_' not in builtins.__dict__:
_ = gettext.gettext
class BookmarkManager(QtWidgets.QWidget):
mark_rows = QtCore.pyqtSignal()
def __init__(self, app, storage, parent=None):
super(BookmarkManager, self).__init__(parent)
self.app = app
assert isinstance(storage, dict), "Storage argument is not a dictionary"
self.bm_dict = deepcopy(storage)
# Icon and title
# self.setWindowIcon(parent.app_icon)
# self.setWindowTitle(_("Bookmark Manager"))
# self.resize(600, 400)
# title = QtWidgets.QLabel(
# "<font size=8><B>FlatCAM</B></font><BR>"
# )
# title.setOpenExternalLinks(True)
# layouts
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
table_hlay = QtWidgets.QHBoxLayout()
layout.addLayout(table_hlay)
self.table_widget = FCTable(drag_drop=True, protected_rows=[0, 1])
self.table_widget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
table_hlay.addWidget(self.table_widget)
self.table_widget.setColumnCount(3)
self.table_widget.setColumnWidth(0, 20)
self.table_widget.setHorizontalHeaderLabels(
[
'#',
_('Title'),
_('Web Link')
]
)
self.table_widget.horizontalHeaderItem(0).setToolTip(
_("Index.\n"
"The rows in gray color will populate the Bookmarks menu.\n"
"The number of gray colored rows is set in Preferences."))
self.table_widget.horizontalHeaderItem(1).setToolTip(
_("Description of the link that is set as an menu action.\n"
"Try to keep it short because it is installed as a menu item."))
self.table_widget.horizontalHeaderItem(2).setToolTip(
_("Web Link. E.g: https://your_website.org "))
# pal = QtGui.QPalette()
# pal.setColor(QtGui.QPalette.Background, Qt.white)
# New Bookmark
new_vlay = QtWidgets.QVBoxLayout()
layout.addLayout(new_vlay)
new_title_lbl = QtWidgets.QLabel('<b>%s</b>' % _("New Bookmark"))
new_vlay.addWidget(new_title_lbl)
form0 = QtWidgets.QFormLayout()
new_vlay.addLayout(form0)
title_lbl = QtWidgets.QLabel('%s:' % _("Title"))
self.title_entry = FCEntry()
form0.addRow(title_lbl, self.title_entry)
link_lbl = QtWidgets.QLabel('%s:' % _("Web Link"))
self.link_entry = FCEntry()
self.link_entry.set_value('http://')
form0.addRow(link_lbl, self.link_entry)
# Buttons Layout
button_hlay = QtWidgets.QHBoxLayout()
layout.addLayout(button_hlay)
add_entry_btn = FCButton(_("Add Entry"))
remove_entry_btn = FCButton(_("Remove Entry"))
export_list_btn = FCButton(_("Export List"))
import_list_btn = FCButton(_("Import List"))
# closebtn = QtWidgets.QPushButton(_("Close"))
# button_hlay.addStretch()
button_hlay.addWidget(add_entry_btn)
button_hlay.addWidget(remove_entry_btn)
button_hlay.addWidget(export_list_btn)
button_hlay.addWidget(import_list_btn)
# button_hlay.addWidget(closebtn)
# ##############################################################################
# ######################## SIGNALS #############################################
# ##############################################################################
add_entry_btn.clicked.connect(self.on_add_entry)
remove_entry_btn.clicked.connect(self.on_remove_entry)
export_list_btn.clicked.connect(self.on_export_bookmarks)
import_list_btn.clicked.connect(self.on_import_bookmarks)
self.title_entry.returnPressed.connect(self.on_add_entry)
self.link_entry.returnPressed.connect(self.on_add_entry)
# closebtn.clicked.connect(self.accept)
self.table_widget.drag_drop_sig.connect(self.mark_table_rows_for_actions)
self.build_bm_ui()
def build_bm_ui(self):
self.table_widget.setRowCount(len(self.bm_dict))
nr_crt = 0
sorted_bookmarks = sorted(list(self.bm_dict.items()), key=lambda x: int(x[0]))
for entry, bookmark in sorted_bookmarks:
row = nr_crt
nr_crt += 1
title = bookmark[0]
weblink = bookmark[1]
id_item = QtWidgets.QTableWidgetItem('%d' % int(nr_crt))
# id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
self.table_widget.setItem(row, 0, id_item) # Tool name/id
title_item = QtWidgets.QTableWidgetItem(title)
self.table_widget.setItem(row, 1, title_item)
weblink_txt = QtWidgets.QTextBrowser()
weblink_txt.setOpenExternalLinks(True)
weblink_txt.setFrameStyle(QtWidgets.QFrame.NoFrame)
weblink_txt.document().setDefaultStyleSheet("a{ text-decoration: none; }")
weblink_txt.setHtml('<a href=%s>%s</a>' % (weblink, weblink))
self.table_widget.setCellWidget(row, 2, weblink_txt)
vertical_header = self.table_widget.verticalHeader()
vertical_header.hide()
horizontal_header = self.table_widget.horizontalHeader()
horizontal_header.setMinimumSectionSize(10)
horizontal_header.setDefaultSectionSize(70)
horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
horizontal_header.resizeSection(0, 20)
horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
self.mark_table_rows_for_actions()
self.app.defaults["global_bookmarks"].clear()
for key, val in self.bm_dict.items():
self.app.defaults["global_bookmarks"][key] = deepcopy(val)
def on_add_entry(self, **kwargs):
"""
Add a entry in the Bookmark Table and in the menu actions
:return: None
"""
if 'title' in kwargs:
title = kwargs['title']
else:
title = self.title_entry.get_value()
if title == '':
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Title entry is empty."))
return 'fail'
if 'link' in kwargs:
link = kwargs['link']
else:
link = self.link_entry.get_value()
if link == 'http://':
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Web link entry is empty."))
return 'fail'
# if 'http' not in link or 'https' not in link:
# link = 'http://' + link
for bookmark in self.bm_dict.values():
if title == bookmark[0] or link == bookmark[1]:
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Either the Title or the Weblink already in the table."))
return 'fail'
# for some reason if the last char in the weblink is a slash it does not make the link clickable
# so I remove it
if link[-1] == '/':
link = link[:-1]
# add the new entry to storage
new_entry = len(self.bm_dict) + 1
self.bm_dict[str(new_entry)] = [title, link]
# add the link to the menu but only if it is within the set limit
bm_limit = int(self.app.defaults["global_bookmarks_limit"])
if len(self.bm_dict) < bm_limit:
act = QtWidgets.QAction(parent=self.app.ui.menuhelp_bookmarks)
act.setText(title)
act.setIcon(QtGui.QIcon(self.app.resource_location + '/link16.png'))
act.triggered.connect(lambda: webbrowser.open(link))
self.app.ui.menuhelp_bookmarks.insertAction(self.app.ui.menuhelp_bookmarks_manager, act)
self.app.inform.emit('[success] %s' % _("Bookmark added."))
# add the new entry to the bookmark manager table
self.build_bm_ui()
def on_remove_entry(self):
"""
Remove an Entry in the Bookmark table and from the menu actions
:return:
"""
index_list = []
for model_index in self.table_widget.selectionModel().selectedRows():
index = QtCore.QPersistentModelIndex(model_index)
index_list.append(index)
title_to_remove = self.table_widget.item(model_index.row(), 1).text()
if title_to_remove == 'FlatCAM' or title_to_remove == 'Backup Site':
self.app.inform.emit('[WARNING_NOTCL] %s.' % _("This bookmark can not be removed"))
self.build_bm_ui()
return
else:
for k, bookmark in list(self.bm_dict.items()):
if title_to_remove == bookmark[0]:
# remove from the storage
self.bm_dict.pop(k, None)
for act in self.app.ui.menuhelp_bookmarks.actions():
if act.text() == title_to_remove:
# disconnect the signal
try:
act.triggered.disconnect()
except TypeError:
pass
# remove the action from the menu
self.app.ui.menuhelp_bookmarks.removeAction(act)
# house keeping: it pays to have keys increased by one
new_key = 0
new_dict = {}
for k, v in self.bm_dict.items():
# we start with key 1 so we can use the len(self.bm_dict)
# when adding bookmarks (keys in bm_dict)
new_key += 1
new_dict[str(new_key)] = v
self.bm_dict = deepcopy(new_dict)
new_dict.clear()
self.app.inform.emit('[success] %s' % _("Bookmark removed."))
# for index in index_list:
# self.table_widget.model().removeRow(index.row())
self.build_bm_ui()
def on_export_bookmarks(self):
self.app.report_usage("on_export_bookmarks")
self.app.log.debug("on_export_bookmarks()")
date = str(datetime.today()).rpartition('.')[0]
date = ''.join(c for c in date if c not in ':-')
date = date.replace(' ', '_')
filter__ = "Text File (*.TXT);;All Files (*.*)"
filename, _f = FCFileSaveDialog.get_saved_filename( caption=_("Export FlatCAM Bookmarks"),
directory='{l_save}/FlatCAM_{n}_{date}'.format(
l_save=str(self.app.get_last_save_folder()),
n=_("Bookmarks"),
date=date),
filter=filter__)
filename = str(filename)
if filename == "":
self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
return
else:
try:
f = open(filename, 'w')
f.close()
except PermissionError:
self.app.inform.emit('[WARNING] %s' %
_("Permission denied, saving not possible.\n"
"Most likely another app is holding the file open and not accessible."))
return
except IOError:
self.app.log.debug('Creating a new bookmarks file ...')
f = open(filename, 'w')
f.close()
except Exception:
e = sys.exc_info()[0]
self.app.log.error("Could not load defaults file.")
self.app.log.error(str(e))
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load bookmarks file."))
return
# Save Bookmarks to a file
try:
with open(filename, "w") as f:
for title, link in self.bm_dict.items():
line2write = str(title) + ':' + str(link) + '\n'
f.write(line2write)
except Exception:
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write bookmarks to file."))
return
self.app.inform.emit('[success] %s: %s' % (_("Exported bookmarks to"), filename))
def on_import_bookmarks(self):
self.app.log.debug("on_import_bookmarks()")
filter_ = "Text File (*.txt);;All Files (*.*)"
filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Bookmarks"), filter=filter_)
filename = str(filename)
if filename == "":
self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
else:
try:
with open(filename) as f:
bookmarks = f.readlines()
except IOError:
self.app.log.error("Could not load bookmarks file.")
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Could not load bookmarks file."))
return
for line in bookmarks:
proc_line = line.replace(' ', '').partition(':')
self.on_add_entry(title=proc_line[0], link=proc_line[2])
self.app.inform.emit('[success] %s: %s' % (_("Imported Bookmarks from"), filename))
def mark_table_rows_for_actions(self):
for row in range(self.table_widget.rowCount()):
item_to_paint = self.table_widget.item(row, 0)
if row < self.app.defaults["global_bookmarks_limit"]:
item_to_paint.setBackground(QtGui.QColor('gray'))
# item_to_paint.setForeground(QtGui.QColor('black'))
else:
item_to_paint.setBackground(QtGui.QColor('white'))
# item_to_paint.setForeground(QtGui.QColor('black'))
def rebuild_actions(self):
# rebuild the storage to reflect the order of the lines
self.bm_dict.clear()
for row in range(self.table_widget.rowCount()):
title = self.table_widget.item(row, 1).text()
wlink = self.table_widget.cellWidget(row, 2).toPlainText()
entry = int(row) + 1
self.bm_dict.update(
{
str(entry): [title, wlink]
}
)
self.app.install_bookmarks(book_dict=self.bm_dict)
# def accept(self):
# self.rebuild_actions()
# super().accept()
def closeEvent(self, QCloseEvent):
self.rebuild_actions()
super().closeEvent(QCloseEvent)

File diff suppressed because it is too large Load Diff

2399
FlatCAMDB.py Normal file

File diff suppressed because it is too large Load Diff

View File

@ -31,7 +31,6 @@ from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
from flatcamParsers.ParseExcellon import Excellon
from flatcamParsers.ParseGerber import Gerber
from camlib import Geometry, CNCjob
import FlatCAMApp
# from flatcamGUI.VisPyVisuals import ShapeCollection
@ -224,7 +223,7 @@ class FlatCAMObj(QtCore.QObject):
"""
self.muted_ui = True
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
try:
# HACK: disconnect the scale entry signal since on focus out event will trigger an undesired scale()
@ -334,7 +333,7 @@ class FlatCAMObj(QtCore.QObject):
:return: None
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
for option in self.options:
try:
self.set_form_item(option)
@ -348,7 +347,7 @@ class FlatCAMObj(QtCore.QObject):
:return: None
:rtype: None
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
for option in self.options:
try:
self.read_form_item(option)
@ -392,7 +391,7 @@ class FlatCAMObj(QtCore.QObject):
:param kind: Used by only some of the FlatCAM objects
:return: Whether to continue plotting or not depending on the "plot" option. Boolean
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
if self.deleted:
return False
@ -691,7 +690,7 @@ class FlatCAMGerber(FlatCAMObj, Gerber):
:return: None
"""
FlatCAMObj.set_ui(self, ui)
FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
log.debug("FlatCAMGerber.set_ui()")
self.units = self.app.defaults['units'].upper()
@ -1768,7 +1767,7 @@ class FlatCAMGerber(FlatCAMObj, Gerber):
:param kwargs: Color and face_color, visible
:return:
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
# Does all the required setup and returns False
# if the 'ptint' option is set to False.
@ -1871,7 +1870,7 @@ class FlatCAMGerber(FlatCAMObj, Gerber):
:return:
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
# Does all the required setup and returns False
# if the 'ptint' option is set to False.
@ -1961,8 +1960,10 @@ class FlatCAMGerber(FlatCAMObj, Gerber):
"""
self.ui_disconnect()
cw = self.sender()
try:
cw = self.sender()
assert isinstance(cw, FCCheckBox),\
"Expected a cellWidget but got %s" % type(cw)
cw_index = self.ui.apertures_table.indexAt(cw.pos())
cw_row = cw_index.row()
except AttributeError:
@ -2870,7 +2871,7 @@ class FlatCAMExcellon(FlatCAMObj, Excellon):
"""
FlatCAMObj.set_ui(self, ui)
FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
log.debug("FlatCAMExcellon.set_ui()")
self.units = self.app.defaults['units'].upper()
@ -6570,7 +6571,7 @@ class FlatCAMCNCjob(FlatCAMObj, CNCjob):
feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
spindlespeed=None):
FlatCAMApp.App.log.debug("Creating CNCJob object...")
log.debug("Creating CNCJob object...")
self.decimals = self.app.decimals
@ -6882,7 +6883,7 @@ class FlatCAMCNCjob(FlatCAMObj, CNCjob):
def set_ui(self, ui):
FlatCAMObj.set_ui(self, ui)
FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
log.debug("FlatCAMCNCJob.set_ui()")
assert isinstance(self.ui, CNCObjectUI), \
"Expected a CNCObjectUI, got %s" % type(self.ui)
@ -7756,7 +7757,7 @@ class FlatCAMScript(FlatCAMObj):
def __init__(self, name):
self.decimals = self.app.decimals
FlatCAMApp.App.log.debug("Creating a FlatCAMScript object...")
log.debug("Creating a FlatCAMScript object...")
FlatCAMObj.__init__(self, name)
self.kind = "script"
@ -7785,7 +7786,7 @@ class FlatCAMScript(FlatCAMObj):
:return:
"""
FlatCAMObj.set_ui(self, ui)
FlatCAMApp.App.log.debug("FlatCAMScript.set_ui()")
log.debug("FlatCAMScript.set_ui()")
assert isinstance(self.ui, ScriptObjectUI), \
"Expected a ScriptObjectUI, got %s" % type(self.ui)
@ -7960,7 +7961,7 @@ class FlatCAMDocument(FlatCAMObj):
def __init__(self, name):
self.decimals = self.app.decimals
FlatCAMApp.App.log.debug("Creating a Document object...")
log.debug("Creating a Document object...")
FlatCAMObj.__init__(self, name)
self.kind = "document"
@ -7982,7 +7983,7 @@ class FlatCAMDocument(FlatCAMObj):
def set_ui(self, ui):
FlatCAMObj.set_ui(self, ui)
FlatCAMApp.App.log.debug("FlatCAMDocument.set_ui()")
log.debug("FlatCAMDocument.set_ui()")
assert isinstance(self.ui, DocumentObjectUI), \
"Expected a DocumentObjectUI, got %s" % type(self.ui)

View File

@ -12,8 +12,10 @@ from abc import ABCMeta, abstractmethod
import math
# module-root dictionary of preprocessors
import FlatCAMApp
import logging
log = logging.getLogger('base')
preprocessors = {}
@ -23,7 +25,7 @@ class ABCPostProcRegister(ABCMeta):
newclass = super(ABCPostProcRegister, cls).__new__(cls, clsname, bases, attrs)
if object not in bases:
if newclass.__name__ in preprocessors:
FlatCAMApp.App.log.warning('Preprocessor %s has been overriden' % newclass.__name__)
log.warning('Preprocessor %s has been overriden' % newclass.__name__)
preprocessors[newclass.__name__] = newclass() # here is your register function
return newclass

View File

@ -19,7 +19,6 @@ from PyQt5.QtGui import QColor
from FlatCAMObj import FlatCAMGerber, FlatCAMGeometry, FlatCAMExcellon, FlatCAMCNCjob, FlatCAMDocument, FlatCAMScript, \
FlatCAMObj
import inspect # TODO: Remove
import FlatCAMApp
import re
import logging
@ -332,7 +331,7 @@ class ObjectCollection(QtCore.QAbstractItemModel):
self.update_list_signal.connect(self.on_update_list_signal)
def promise(self, obj_name):
FlatCAMApp.App.log.debug("Object %s has been promised." % obj_name)
log.debug("Object %s has been promised." % obj_name)
self.promises.add(obj_name)
def has_promises(self):
@ -349,7 +348,7 @@ class ObjectCollection(QtCore.QAbstractItemModel):
return len(self.plot_promises) > 0
def on_mouse_down(self, event):
FlatCAMApp.App.log.debug("Mouse button pressed on list")
log.debug("Mouse button pressed on list")
def on_menu_request(self, pos):
@ -532,21 +531,21 @@ class ObjectCollection(QtCore.QAbstractItemModel):
# return QtWidgets.QAbstractItemModel.flags(self, index)
def append(self, obj, active=False, to_index=None):
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> OC.append()")
log.debug(str(inspect.stack()[1][3]) + " --> OC.append()")
name = obj.options["name"]
# Check promises and clear if exists
if name in self.promises:
self.promises.remove(name)
# FlatCAMApp.App.log.debug("Promised object %s became available." % name)
# FlatCAMApp.App.log.debug("%d promised objects remaining." % len(self.promises))
# log.debug("Promised object %s became available." % name)
# log.debug("%d promised objects remaining." % len(self.promises))
# Prevent same name
while name in self.get_names():
# ## Create a new name
# Ends with number?
FlatCAMApp.App.log.debug("new_object(): Object name (%s) exists, changing." % name)
log.debug("new_object(): Object name (%s) exists, changing." % name)
match = re.search(r'(.*[^\d])?(\d+)$', name)
if match: # Yes: Increment the number!
base = match.group(1) or ''
@ -596,7 +595,7 @@ class ObjectCollection(QtCore.QAbstractItemModel):
:rtype: list
"""
# FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> OC.get_names()")
# log.debug(str(inspect.stack()[1][3]) + " --> OC.get_names()")
return [x.options['name'] for x in self.get_list()]
def get_bounds(self):
@ -606,7 +605,7 @@ class ObjectCollection(QtCore.QAbstractItemModel):
:return: [xmin, ymin, xmax, ymax]
:rtype: list
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.get_bounds()")
log.debug(str(inspect.stack()[1][3]) + "--> OC.get_bounds()")
# TODO: Move the operation out of here.
@ -624,7 +623,7 @@ class ObjectCollection(QtCore.QAbstractItemModel):
xmax = max([xmax, gxmax])
ymax = max([ymax, gymax])
except Exception as e:
FlatCAMApp.App.log.warning("DEV WARNING: Tried to get bounds of empty geometry. %s" % str(e))
log.warning("DEV WARNING: Tried to get bounds of empty geometry. %s" % str(e))
return [xmin, ymin, xmax, ymax]
@ -638,7 +637,7 @@ class ObjectCollection(QtCore.QAbstractItemModel):
:return: The requested object or None if no such object.
:rtype: FlatCAMObj or None
"""
# FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.get_by_name()")
# log.debug(str(inspect.stack()[1][3]) + "--> OC.get_by_name()")
if isCaseSensitive is None or isCaseSensitive is True:
for obj in self.get_list():
@ -760,7 +759,7 @@ class ObjectCollection(QtCore.QAbstractItemModel):
self.app.all_objects_list = self.get_list()
def delete_all(self):
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.delete_all()")
log.debug(str(inspect.stack()[1][3]) + "--> OC.delete_all()")
self.app.object_status_changed.emit(None, 'delete_all', '')
@ -897,8 +896,15 @@ class ObjectCollection(QtCore.QAbstractItemModel):
self.set_inactive(name)
def on_list_selection_change(self, current, previous):
# FlatCAMApp.App.log.debug("on_list_selection_change()")
# FlatCAMApp.App.log.debug("Current: %s, Previous %s" % (str(current), str(previous)))
"""
:param current: Current selected item
:param previous: Previously selected item
:return:
"""
# log.debug("on_list_selection_change()")
# log.debug("Current: %s, Previous %s" % (str(current), str(previous)))
try:
obj = current.indexes()[0].internalPointer().obj
@ -942,12 +948,12 @@ class ObjectCollection(QtCore.QAbstractItemModel):
)
except IndexError:
self.item_selected.emit('none')
# FlatCAMApp.App.log.debug("on_list_selection_change(): Index Error (Nothing selected?)")
# log.debug("on_list_selection_change(): Index Error (Nothing selected?)")
self.app.inform.emit('')
try:
self.app.ui.selected_scroll_area.takeWidget()
except Exception as e:
FlatCAMApp.App.log.debug("Nothing to remove. %s" % str(e))
log.debug("Nothing to remove. %s" % str(e))
self.app.setup_component_editor()
return

527
camlib.py

File diff suppressed because it is too large Load Diff

View File

@ -12,7 +12,6 @@ from camlib import distance, arc, FlatCAMRTreeStorage
from flatcamGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, RadioSet, FCSpinner
from flatcamEditors.FlatCAMGeoEditor import FCShapeTool, DrawTool, DrawToolShape, DrawToolUtilityShape, FlatCAMGeoEditor
from flatcamParsers.ParseExcellon import Excellon
import FlatCAMApp
from shapely.geometry import LineString, LinearRing, MultiLineString, Polygon, MultiPolygon, Point
import shapely.affinity as affinity
@ -179,7 +178,7 @@ class FCDrillArray(FCShapeTool):
try:
QtGui.QGuiApplication.restoreOverrideCursor()
except Exception as e:
except Exception:
pass
self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_drill_array.png'))
@ -1516,7 +1515,7 @@ class FlatCAMExcEditor(QtCore.QObject):
draw_shape_idx = -1
def __init__(self, app):
assert isinstance(app, FlatCAMApp.App), "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
# assert isinstance(app, FlatCAMApp.App), "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
super(FlatCAMExcEditor, self).__init__()
@ -2230,8 +2229,8 @@ class FlatCAMExcEditor(QtCore.QObject):
# store the status of the editor so the Delete at object level will not work until the edit is finished
self.editor_active = False
def entry2option(option, entry):
self.options[option] = float(entry.text())
# def entry2option(option, entry):
# self.options[option] = float(entry.text())
# Event signals disconnect id holders
self.mp = None
@ -2388,7 +2387,7 @@ class FlatCAMExcEditor(QtCore.QObject):
try:
# Find no of slots for the current tool
for slot in self.slots:
for slot in self.slot_points_edit:
if slot['tool'] == tool_no:
slot_cnt += 1
@ -2661,15 +2660,13 @@ class FlatCAMExcEditor(QtCore.QObject):
# self.tools_table_exc.selectionModel().currentChanged.disconnect()
self.is_modified = True
new_dia = None
# new_dia = None
if self.tools_table_exc.currentItem() is not None:
try:
new_dia = float(self.tools_table_exc.currentItem().text())
except ValueError as e:
log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
self.tools_table_exc.setCurrentItem(None)
return
try:
new_dia = float(self.tools_table_exc.currentItem().text())
except ValueError as e:
log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
return
row_of_item_changed = self.tools_table_exc.currentRow()
# rows start with 0, tools start with 1 so we adjust the value by 1
@ -3297,7 +3294,8 @@ class FlatCAMExcEditor(QtCore.QObject):
return self.edited_obj_name
def update_options(self, obj):
@staticmethod
def update_options(obj):
try:
if not obj.options:
obj.options = {}
@ -3316,10 +3314,14 @@ class FlatCAMExcEditor(QtCore.QObject):
"""
Creates a new Excellon object for the edited Excellon. Thread-safe.
:param outname: Name of the resulting object. None causes the
name to be that of the file.
:type outname: str
:return: None
:param outname: Name of the resulting object. None causes the
name to be that of the file.
:type outname: str
:param n_drills: The new Drills storage
:param n_slots: The new Slots storage
:param n_tools: The new Tools storage
:return: None
"""
self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
@ -3429,12 +3431,12 @@ class FlatCAMExcEditor(QtCore.QObject):
self.replot()
def toolbar_tool_toggle(self, key):
self.options[key] = self.sender().isChecked()
if self.options[key] is True:
return 1
else:
return 0
# def toolbar_tool_toggle(self, key):
# self.options[key] = self.sender().isChecked()
# if self.options[key] is True:
# return 1
# else:
# return 0
def on_canvas_click(self, event):
"""
@ -3446,12 +3448,12 @@ class FlatCAMExcEditor(QtCore.QObject):
"""
if self.app.is_legacy is False:
event_pos = event.pos
event_is_dragging = event.is_dragging
right_button = 2
# 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_is_dragging = self.app.plotcanvas.is_dragging
# right_button = 3
self.pos = self.canvas.translate_coords(event_pos)
@ -3575,8 +3577,8 @@ class FlatCAMExcEditor(QtCore.QObject):
if isinstance(shape, DrawToolUtilityShape):
self.utility.append(shape)
else:
self.storage.insert(shape) # TODO: Check performance
# else:
# self.storage.insert(shape)
def on_exc_click_release(self, event):
"""
@ -3591,11 +3593,11 @@ class FlatCAMExcEditor(QtCore.QObject):
if self.app.is_legacy is False:
event_pos = event.pos
event_is_dragging = event.is_dragging
# event_is_dragging = event.is_dragging
right_button = 2
else:
event_pos = (event.xdata, event.ydata)
event_is_dragging = self.app.plotcanvas.is_dragging
# event_is_dragging = self.app.plotcanvas.is_dragging
right_button = 3
pos_canvas = self.canvas.translate_coords(event_pos)
@ -4027,7 +4029,7 @@ class FlatCAMExcEditor(QtCore.QObject):
del self.slot_points_edit[storage][0]
if del_shape in self.selected:
self.selected.remove(del_shape) # TODO: Check performance
self.selected.remove(del_shape)
def delete_utility_geometry(self):
for_deletion = [util_shape for util_shape in self.utility]

View File

@ -20,7 +20,6 @@ from flatcamGUI.ObjectUI import RadioSet
from flatcamGUI.GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCComboBox, FCTextAreaRich, \
FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog, FCTree
from flatcamParsers.ParseFont import *
import FlatCAMApp
from shapely.geometry import LineString, LinearRing, MultiLineString, Polygon, MultiPolygon
from shapely.ops import cascaded_union, unary_union, linemerge
@ -3299,8 +3298,8 @@ class FlatCAMGeoEditor(QtCore.QObject):
draw_shape_idx = -1
def __init__(self, app, disabled=False):
assert isinstance(app, FlatCAMApp.App), \
"Expected the app to be a FlatCAMApp.App, got %s" % type(app)
# assert isinstance(app, FlatCAMApp.App), \
# "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
super(FlatCAMGeoEditor, self).__init__()
@ -4011,6 +4010,7 @@ class FlatCAMGeoEditor(QtCore.QObject):
:return: Boolean. Status of the checkbox that toggled the Editor Tool
"""
cb_widget = self.sender()
assert isinstance(cb_widget, QtWidgets.QAction), "Expected a QAction got %s" % type(cb_widget)
self.options[key] = cb_widget.isChecked()
return 1 if self.options[key] is True else 0

View File

@ -21,7 +21,6 @@ from camlib import distance, arc, three_point_circle
from flatcamGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, FCSpinner, RadioSet, \
EvalEntry2, FCInputDialog, FCButton, OptionalInputSection, FCCheckBox
from FlatCAMTool import FlatCAMTool
import FlatCAMApp
import numpy as np
from numpy.linalg import norm as numpy_norm
@ -182,6 +181,7 @@ class FCShapeTool(DrawTool):
def __init__(self, draw_app):
DrawTool.__init__(self, draw_app)
self.name = None
def make(self):
pass
@ -199,7 +199,7 @@ class FCPad(FCShapeTool):
try:
QtGui.QGuiApplication.restoreOverrideCursor()
except Exception as e:
except Exception:
pass
self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_circle.png'))
QtGui.QGuiApplication.setOverrideCursor(self.cursor)
@ -1415,7 +1415,7 @@ class FCDisc(FCShapeTool):
try:
QtGui.QGuiApplication.restoreOverrideCursor()
except Exception as e:
except Exception:
pass
self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_disc.png'))
QtGui.QGuiApplication.setOverrideCursor(self.cursor)
@ -2422,8 +2422,8 @@ class FlatCAMGrbEditor(QtCore.QObject):
mp_finished = QtCore.pyqtSignal(list)
def __init__(self, app):
assert isinstance(app, FlatCAMApp.App), \
"Expected the app to be a FlatCAMApp.App, got %s" % type(app)
# assert isinstance(app, FlatCAMApp.App), \
# "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
super(FlatCAMGrbEditor, self).__init__()
@ -3479,7 +3479,7 @@ class FlatCAMGrbEditor(QtCore.QObject):
current_table_dia_edited = float(self.apertures_table.currentItem().text())
except ValueError as e:
log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
self.apertures_table.setCurrentItem(None)
# self.apertures_table.setCurrentItem(None)
return
row_of_item_changed = self.apertures_table.currentRow()
@ -3956,10 +3956,10 @@ class FlatCAMGrbEditor(QtCore.QObject):
global_clear_geo = []
# create one big geometry made out of all 'negative' (clear) polygons
for apid in app_obj.gerber_obj.apertures:
for aper_id in app_obj.gerber_obj.apertures:
# first check if we have any clear_geometry (LPC) and if yes added it to the global_clear_geo
if 'geometry' in app_obj.gerber_obj.apertures[apid]:
for elem in app_obj.gerber_obj.apertures[apid]['geometry']:
if 'geometry' in app_obj.gerber_obj.apertures[aper_id]:
for elem in app_obj.gerber_obj.apertures[aper_id]['geometry']:
if 'clear' in elem:
global_clear_geo.append(elem['clear'])
log.warning("Found %d clear polygons." % len(global_clear_geo))
@ -3967,7 +3967,7 @@ class FlatCAMGrbEditor(QtCore.QObject):
if global_clear_geo:
global_clear_geo = MultiPolygon(global_clear_geo)
if isinstance(global_clear_geo, Polygon):
global_clear_geo = list(global_clear_geo)
global_clear_geo = [global_clear_geo]
# we subtract the big "negative" (clear) geometry from each solid polygon but only the part of
# clear geometry that fits inside the solid. otherwise we may loose the solid
@ -3979,8 +3979,8 @@ class FlatCAMGrbEditor(QtCore.QObject):
# solid_geo = elem['solid']
# for clear_geo in global_clear_geo:
# # Make sure that the clear_geo is within the solid_geo otherwise we loose
# # the solid_geometry. We want for clear_geometry just to cut into solid_geometry not to
# # delete it
# # the solid_geometry. We want for clear_geometry just to cut
# # into solid_geometry not to delete it
# if clear_geo.within(solid_geo):
# solid_geo = solid_geo.difference(clear_geo)
# try:
@ -4307,14 +4307,14 @@ class FlatCAMGrbEditor(QtCore.QObject):
self.plot_all()
def toolbar_tool_toggle(self, key):
"""
:param key: key to update in self.options dictionary
:return:
"""
self.options[key] = self.sender().isChecked()
return self.options[key]
# def toolbar_tool_toggle(self, key):
# """
#
# :param key: key to update in self.options dictionary
# :return:
# """
# self.options[key] = self.sender().isChecked()
# return self.options[key]
def on_grb_shape_complete(self, storage=None, specific_shape=None, no_plot=False):
"""
@ -4389,12 +4389,12 @@ class FlatCAMGrbEditor(QtCore.QObject):
"""
if self.app.is_legacy is False:
event_pos = event.pos
event_is_dragging = event.is_dragging
right_button = 2
# 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_is_dragging = self.app.plotcanvas.is_dragging
# right_button = 3
self.pos = self.canvas.translate_coords(event_pos)
@ -4457,11 +4457,11 @@ class FlatCAMGrbEditor(QtCore.QObject):
self.modifiers = QtWidgets.QApplication.keyboardModifiers()
if self.app.is_legacy is False:
event_pos = event.pos
event_is_dragging = event.is_dragging
# event_is_dragging = event.is_dragging
right_button = 2
else:
event_pos = (event.xdata, event.ydata)
event_is_dragging = self.app.plotcanvas.is_dragging
# event_is_dragging = self.app.plotcanvas.is_dragging
right_button = 3
pos_canvas = self.canvas.translate_coords(event_pos)
@ -4747,10 +4747,10 @@ class FlatCAMGrbEditor(QtCore.QObject):
Plots a geometric object or list of objects without rendering. Plotted objects
are returned as a list. This allows for efficient/animated rendering.
:param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
:param color: Shape color
:param linewidth: Width of lines in # of pixels.
:return: List of plotted elements.
:param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
:param color: Shape color
:param linewidth: Width of lines in # of pixels.
:return: List of plotted elements.
"""
if geometry is None:
@ -5597,7 +5597,7 @@ class TransformEditorTool(FlatCAMTool):
self.flip_ref_entry.set_value((0, 0))
def template(self):
if not self.fcdraw.selected:
if not self.draw_app.selected:
self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. No shape selected."))
return

View File

@ -2876,7 +2876,7 @@ class FlatCAMGUI(QtWidgets.QMainWindow):
# Open Excellon file
if key == QtCore.Qt.Key_E:
self.app.on_fileopenexcellon()
self.app.on_fileopenexcellon(signal=None)
# Open Gerber file
if key == QtCore.Qt.Key_G:
@ -2884,7 +2884,7 @@ class FlatCAMGUI(QtWidgets.QMainWindow):
if 'editor' in widget_name.lower():
self.app.goto_text_line()
else:
self.app.on_fileopengerber()
self.app.on_fileopengerber(signal=None)
# Distance Tool
if key == QtCore.Qt.Key_M:

View File

@ -16,8 +16,6 @@ from descartes.patch import PolygonPatch
from shapely.geometry import Polygon, LineString, LinearRing
import FlatCAMApp
from copy import deepcopy
import logging
@ -496,7 +494,7 @@ class PlotCanvasLegacy(QtCore.QObject):
:param event:
:return:
"""
FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
log.debug('on_key_down(): ' + str(event.key))
self.key = event.key
def on_key_up(self, event):
@ -531,7 +529,7 @@ class PlotCanvasLegacy(QtCore.QObject):
try:
self.figure.clf()
except KeyError:
FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
log.warning("KeyError in MPL figure.clf()")
# Re-build
self.figure.add_axes(self.axes)
@ -582,7 +580,7 @@ class PlotCanvasLegacy(QtCore.QObject):
try:
r = width / height
except ZeroDivisionError:
FlatCAMApp.App.log.error("Height is %f" % height)
log.error("Height is %f" % height)
return
canvas_w, canvas_h = self.canvas.get_width_height()
canvas_r = float(canvas_w) / canvas_h
@ -1190,10 +1188,10 @@ class ShapeCollectionLegacy:
linewidth=local_shapes[element]['linewidth'])
self.axes.add_patch(patch)
except AssertionError:
FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
FlatCAMApp.App.log.warning(str(element))
log.warning("A geometry component was not a polygon:")
log.warning(str(element))
except Exception as e:
FlatCAMApp.App.log.debug(
log.debug(
"PlotCanvasLegacy.ShepeCollectionLegacy.redraw() gerber 'solid' --> %s" % str(e))
else:
try:

View File

@ -7,7 +7,6 @@
# ########################################################## ##
from camlib import Geometry
import FlatCAMApp
import shapely.affinity as affinity
from shapely.geometry import Point, LineString
@ -19,6 +18,7 @@ import traceback
from copy import deepcopy
import FlatCAMTranslation as fcTranslate
from FlatCAMCommon import GracefulException as grace
import gettext
import builtins
@ -86,6 +86,7 @@ class Excellon(Geometry):
:return: Excellon object.
:rtype: Excellon
"""
self.decimals = self.app.decimals
if geo_steps_per_circle is None:
@ -241,12 +242,12 @@ class Excellon(Geometry):
def parse_file(self, filename=None, file_obj=None):
"""
Reads the specified file as array of lines as
passes it to ``parse_lines()``.
Reads the specified file as array of lines as passes it to ``parse_lines()``.
:param filename: The file to be read and parsed.
:type filename: str
:return: None
:param filename: The file to be read and parsed.
:param file_obj:
:type filename: str
:return: None
"""
if file_obj:
estr = file_obj
@ -298,7 +299,7 @@ class Excellon(Geometry):
for eline in elines:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
line_num += 1
# log.debug("%3d %s" % (line_num, str(eline)))
@ -526,7 +527,7 @@ class Excellon(Geometry):
slot_dia = 0.05
try:
slot_dia = float(self.tools[current_tool]['C'])
except Exception as e:
except Exception:
pass
log.debug(
'Milling/Drilling slot with tool %s, diam=%f' % (
@ -596,7 +597,7 @@ class Excellon(Geometry):
slot_dia = 0.05
try:
slot_dia = float(self.tools[current_tool]['C'])
except Exception as e:
except Exception:
pass
log.debug(
'Milling/Drilling slot with tool %s, diam=%f' % (
@ -893,9 +894,8 @@ class Excellon(Geometry):
log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
except Exception:
log.error("Excellon PARSING FAILED. Line %d: %s" % (line_num, eline))
msg = '[ERROR_NOTCL] %s' % \
_("An internal error has ocurred. See shell.\n")
msg += ('{e_code} {tx} {l_nr}: {line}\n').format(
msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
msg += '{e_code} {tx} {l_nr}: {line}\n'.format(
e_code='[ERROR]',
tx=_("Excellon Parser error.\nParsing Failed. Line"),
l_nr=line_num,
@ -1010,13 +1010,13 @@ class Excellon(Geometry):
"Excellon geometry creation failed due of ERROR: %s" % str(e))
return "fail"
def bounds(self):
def bounds(self, flatten=None):
"""
Returns coordinates of rectangular bounds
of Excellon geometry: (xmin, ymin, xmax, ymax).
:param flatten: No used
"""
# fixed issue of getting bounds only for one level lists of objects
# now it can get bounds for nested lists of objects
log.debug("flatcamParsers.ParseExcellon.Excellon.bounds()")
@ -1056,11 +1056,11 @@ class Excellon(Geometry):
maxy_list = []
for tool in self.tools:
minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
minx_list.append(minx)
miny_list.append(miny)
maxx_list.append(maxx)
maxy_list.append(maxy)
eminx, eminy, emaxx, emaxy = bounds_rec(self.tools[tool]['solid_geometry'])
minx_list.append(eminx)
miny_list.append(eminy)
maxx_list.append(emaxx)
maxy_list.append(emaxy)
return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
@ -1075,8 +1075,9 @@ class Excellon(Geometry):
Kind of convolute way to make the conversion and it is based on the assumption that the Excellon file
will have detected the units before the tools are parsed and stored in self.tools
:param units:
:type str: IN or MM
:param units: 'IN' or 'MM'. String
:return:
"""
@ -1109,12 +1110,13 @@ class Excellon(Geometry):
Scales geometry on the XY plane in the object by a given factor.
Tool sizes, feedrates an Z-plane dimensions are untouched.
:param xfactor: Number by which to scale the object.
:type xfactor: float
:param yfactor: Number by which to scale the object.
:type yfactor: float
:return: None
:rtype: NOne
:param xfactor: Number by which to scale the object.
:type xfactor: float
:param yfactor: Number by which to scale the object.
:type yfactor: float
:param point: Origin point for scale
:return: None
:rtype: None
"""
log.debug("flatcamParsers.ParseExcellon.Excellon.scale()")
@ -1145,8 +1147,7 @@ class Excellon(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for g in self.drills:
self.geo_len += 1
self.geo_len = len(self.drills)
except TypeError:
self.geo_len = 1
self.old_disp_number = 0
@ -1190,12 +1191,12 @@ class Excellon(Geometry):
return
def offset_geom(obj):
if type(obj) is list:
try:
new_obj = []
for g in obj:
new_obj.append(offset_geom(g))
for geo in obj:
new_obj.append(offset_geom(geo))
return new_obj
else:
except TypeError:
try:
return affinity.translate(obj, xoff=dx, yoff=dy)
except AttributeError:
@ -1204,8 +1205,7 @@ class Excellon(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for g in self.drills:
self.geo_len += 1
self.geo_len = len(self.drills)
except TypeError:
self.geo_len = 1
self.old_disp_number = 0
@ -1237,11 +1237,11 @@ class Excellon(Geometry):
def mirror(self, axis, point):
"""
:param axis: "X" or "Y" indicates around which axis to mirror.
:type axis: str
:param point: [x, y] point belonging to the mirror axis.
:type point: list
:return: None
:param axis: "X" or "Y" indicates around which axis to mirror.
:type axis: str
:param point: [x, y] point belonging to the mirror axis.
:type point: list
:return: None
"""
log.debug("flatcamParsers.ParseExcellon.Excellon.mirror()")
@ -1249,12 +1249,12 @@ class Excellon(Geometry):
xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
def mirror_geom(obj):
if type(obj) is list:
try:
new_obj = []
for g in obj:
new_obj.append(mirror_geom(g))
for geo in obj:
new_obj.append(mirror_geom(geo))
return new_obj
else:
except TypeError:
try:
return affinity.scale(obj, xscale, yscale, origin=(px, py))
except AttributeError:
@ -1265,8 +1265,7 @@ class Excellon(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for g in self.drills:
self.geo_len += 1
self.geo_len = len(self.drills)
except TypeError:
self.geo_len = 1
self.old_disp_number = 0
@ -1300,12 +1299,12 @@ class Excellon(Geometry):
Shear/Skew the geometries of an object by angles along x and y dimensions.
Tool sizes, feedrates an Z-plane dimensions are untouched.
Parameters
----------
xs, ys : float, float
:param angle_x:
:param angle_y:
The shear angle(s) for the x and y axes respectively. These can be
specified in either degrees (default) or radians by setting
use_radians=True.
:param point: Origin point for Skew
See shapely manual for more information:
http://toblerity.org/shapely/manual.html#affine-transformations
@ -1322,12 +1321,12 @@ class Excellon(Geometry):
return
def skew_geom(obj):
if type(obj) is list:
try:
new_obj = []
for g in obj:
new_obj.append(skew_geom(g))
return new_obj
else:
except TypeError:
try:
return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
except AttributeError:
@ -1336,8 +1335,7 @@ class Excellon(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for g in self.drills:
self.geo_len += 1
self.geo_len = len(self.drills)
except TypeError:
self.geo_len = 1
self.old_disp_number = 0
@ -1393,9 +1391,10 @@ class Excellon(Geometry):
def rotate(self, angle, point=None):
"""
Rotate the geometry of an object by an angle around the 'point' coordinates
:param angle:
:param point: tuple of coordinates (x, y)
:return:
:param point: tuple of coordinates (x, y)
:return: None
"""
log.debug("flatcamParsers.ParseExcellon.Excellon.rotate()")
@ -1423,8 +1422,7 @@ class Excellon(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for g in self.drills:
self.geo_len += 1
self.geo_len = len(self.drills)
except TypeError:
self.geo_len = 1
self.old_disp_number = 0
@ -1476,9 +1474,10 @@ class Excellon(Geometry):
def buffer(self, distance, join, factor):
"""
:param distance: if 'factor' is True then distance is the factor
:param factor: True or False (None)
:return:
:param distance: if 'factor' is True then distance is the factor
:param factor: True or False (None)
:param join: The type of line joint used by the shapely buffer method: round, square, bevel
:return: None
"""
log.debug("flatcamParsers.ParseExcellon.Excellon.buffer()")
@ -1486,12 +1485,12 @@ class Excellon(Geometry):
return
def buffer_geom(obj):
if type(obj) is list:
try:
new_obj = []
for g in obj:
new_obj.append(buffer_geom(g))
return new_obj
else:
except TypeError:
try:
if factor is None:
return obj.buffer(distance, resolution=self.geo_steps_per_circle)

View File

@ -1,6 +1,5 @@
from PyQt5 import QtWidgets
from camlib import Geometry, arc, arc_angle, ApertureMacro
import FlatCAMApp
import numpy as np
import re
@ -9,15 +8,16 @@ import traceback
from copy import deepcopy
import sys
from shapely.ops import cascaded_union, unary_union
from shapely.geometry import Polygon, MultiPolygon, LineString, Point
from shapely.ops import cascaded_union
from shapely.affinity import scale, translate
import shapely.affinity as affinity
from shapely.geometry import box as shply_box
from shapely.geometry import box as shply_box, Polygon, LineString, Point, MultiPolygon
from lxml import etree as ET
from flatcamParsers.ParseSVG import *
from flatcamParsers.ParseSVG import svgparselength, getsvggeo
from FlatCAMCommon import GracefulException as grace
import FlatCAMTranslation as fcTranslate
import gettext
import builtins
@ -255,7 +255,7 @@ class Gerber(Geometry):
"""
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# Found some Gerber with a leading zero in the aperture id and the
# referenced it without the zero, so this is a hack to handle that.
@ -403,7 +403,7 @@ class Gerber(Geometry):
# Absolute or Relative/Incremental coordinates
# Not implemented
absolute = True
# absolute = True
# How to interpret circular interpolation: SINGLE or MULTI
quadrant_mode = None
@ -428,7 +428,7 @@ class Gerber(Geometry):
for gline in glines:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
line_num += 1
self.source_file += gline + '\n'
@ -986,7 +986,7 @@ class Gerber(Geometry):
if 'geometry' not in self.apertures[current_aperture]:
self.apertures[current_aperture]['geometry'] = []
self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
except Exception as e:
except Exception:
pass
last_path_aperture = current_aperture
# we do this for the case that a region is done without having defined any aperture
@ -1229,25 +1229,25 @@ class Gerber(Geometry):
try:
circular_x = parse_gerber_number(circular_x,
self.int_digits, self.frac_digits, self.gerber_zeros)
except Exception as e:
except Exception:
circular_x = current_x
try:
circular_y = parse_gerber_number(circular_y,
self.int_digits, self.frac_digits, self.gerber_zeros)
except Exception as e:
except Exception:
circular_y = current_y
# According to Gerber specification i and j are not modal, which means that when i or j are missing,
# they are to be interpreted as being zero
try:
i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
except Exception as e:
except Exception:
i = 0
try:
j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
except Exception as e:
except Exception:
j = 0
if quadrant_mode is None:
@ -1668,13 +1668,14 @@ class Gerber(Geometry):
bbox = bbox.envelope
return bbox
def bounds(self):
def bounds(self, flatten=None):
"""
Returns coordinates of rectangular bounds
of Gerber geometry: (xmin, ymin, xmax, ymax).
:param flatten: Not used, it is here for compatibility with base class method
:return: None
"""
# fixed issue of getting bounds only for one level lists of objects
# now it can get bounds for nested lists of objects
log.debug("parseGerber.Gerber.bounds()")
@ -1999,8 +2000,7 @@ class Gerber(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for __ in self.solid_geometry:
self.geo_len += 1
self.geo_len = len(self.solid_geometry)
except TypeError:
self.geo_len = 1
@ -2078,8 +2078,7 @@ class Gerber(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for __ in self.solid_geometry:
self.geo_len += 1
self.geo_len = len(self.solid_geometry)
except TypeError:
self.geo_len = 1
@ -2217,8 +2216,7 @@ class Gerber(Geometry):
# variables to display the percentage of work done
self.geo_len = 0
try:
for __ in self.solid_geometry:
self.geo_len += 1
self.geo_len = len(self.solid_geometry)
except TypeError:
self.geo_len = 1
@ -2266,8 +2264,9 @@ class Gerber(Geometry):
def buffer(self, distance, join, factor=None):
"""
:param distance: if 'factor' is True then distance is the factor
:param factor: True or False (None)
:param distance: If 'factor' is True then distance is the factor
:param join: The type of joining used by the Shapely buffer method. Can be: round, square and bevel
:param factor: True or False (None)
:return:
"""
log.debug("parseGerber.Gerber.buffer()")

View File

@ -7,7 +7,6 @@
# ############################################################
from camlib import arc, three_point_circle
import FlatCAMApp
import numpy as np
import re
@ -19,6 +18,7 @@ import sys
from shapely.ops import unary_union
from shapely.geometry import LineString, Point
from FlatCAMCommon import GracefulException as grace
import FlatCAMTranslation as fcTranslate
import gettext
import builtins
@ -180,7 +180,7 @@ class HPGL2:
for gline in glines:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
line_num += 1
self.source_file += gline + '\n'
@ -304,7 +304,7 @@ class HPGL2:
(_("Coordinates missing, line ignored"), str(gline)))
if current_x is not None and current_y is not None:
radius = match.group(1)
radius = float(match.group(1))
geo = Point((current_x, current_y)).buffer(radius, int(self.steps_per_circle))
geo_line = geo.exterior
self.tools[current_tool]['solid_geometry'].append(geo_line)

View File

@ -7,10 +7,9 @@
from PyQt5 import QtWidgets, QtCore
import FlatCAMApp
from FlatCAMCommon import GracefulException as grace
from FlatCAMTool import FlatCAMTool
from flatcamGUI.GUIElements import FCDoubleSpinner, RadioSet, FCEntry, FCComboBox
from FlatCAMObj import FlatCAMGerber, FlatCAMGeometry, FlatCAMExcellon
import shapely.geometry.base as base
from shapely.ops import cascaded_union, unary_union
@ -994,7 +993,7 @@ class ToolCopperThieving(FlatCAMTool):
for pol in app_obj.grb_object.solid_geometry:
if app_obj.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
clearance_geometry.append(
pol.buffer(c_val, int(int(app_obj.geo_steps_per_circle) / 4))
@ -1073,7 +1072,7 @@ class ToolCopperThieving(FlatCAMTool):
for poly in working_obj:
if app_obj.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
except TypeError:
geo_buff_list.append(working_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
@ -1082,7 +1081,7 @@ class ToolCopperThieving(FlatCAMTool):
else: # ref_selected == 'box'
geo_n = working_obj.solid_geometry
if isinstance(working_obj, FlatCAMGeometry):
if working_obj.kind == 'geometry':
try:
__ = iter(geo_n)
except Exception as e:
@ -1093,11 +1092,11 @@ class ToolCopperThieving(FlatCAMTool):
for poly in geo_n:
if app_obj.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
bounding_box = cascaded_union(geo_buff_list)
elif isinstance(working_obj, FlatCAMGerber):
elif working_obj.kind == 'gerber':
geo_n = cascaded_union(geo_n).convex_hull
bounding_box = cascaded_union(thieving_obj.solid_geometry).convex_hull.intersection(geo_n)
bounding_box = bounding_box.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
@ -1192,7 +1191,7 @@ class ToolCopperThieving(FlatCAMTool):
for pol in app_obj.grb_object.solid_geometry:
if app_obj.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
outline_geometry.append(
pol.buffer(c_val+half_thick_line, int(int(app_obj.geo_steps_per_circle) / 4))

View File

@ -8,7 +8,6 @@
from PyQt5 import QtWidgets, QtGui, QtCore
from FlatCAMTool import FlatCAMTool
from flatcamGUI.GUIElements import FCDoubleSpinner, FCCheckBox, RadioSet, FCComboBox, OptionalInputSection, FCButton
from FlatCAMObj import FlatCAMGerber
from shapely.geometry import box, MultiPolygon, Polygon, LineString, LinearRing
from shapely.ops import cascaded_union, unary_union
@ -270,7 +269,7 @@ class CutOut(FlatCAMTool):
form_layout_2.addRow(gaps_label, self.gaps)
# Buttons
self.ff_cutout_object_btn = QtWidgets.QPushButton(_("Generate Freeform Geometry"))
self.ff_cutout_object_btn = FCButton(_("Generate Freeform Geometry"))
self.ff_cutout_object_btn.setToolTip(
_("Cutout the selected object.\n"
"The cutout shape can be of any shape.\n"
@ -284,7 +283,7 @@ class CutOut(FlatCAMTool):
""")
grid0.addWidget(self.ff_cutout_object_btn, 20, 0, 1, 2)
self.rect_cutout_object_btn = QtWidgets.QPushButton(_("Generate Rectangular Geometry"))
self.rect_cutout_object_btn = FCButton(_("Generate Rectangular Geometry"))
self.rect_cutout_object_btn.setToolTip(
_("Cutout the selected object.\n"
"The resulting cutout shape is\n"
@ -335,7 +334,7 @@ class CutOut(FlatCAMTool):
# form_layout_3.addRow(e_lab_0)
self.man_geo_creation_btn = QtWidgets.QPushButton(_("Generate Manual Geometry"))
self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
self.man_geo_creation_btn.setToolTip(
_("If the object to be cutout is a Gerber\n"
"first create a Geometry that surrounds it,\n"
@ -350,7 +349,7 @@ class CutOut(FlatCAMTool):
""")
grid0.addWidget(self.man_geo_creation_btn, 24, 0, 1, 2)
self.man_gaps_creation_btn = QtWidgets.QPushButton(_("Manual Add Bridge Gaps"))
self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
self.man_gaps_creation_btn.setToolTip(
_("Use the left mouse button (LMB) click\n"
"to create a bridge gap to separate the PCB from\n"
@ -369,7 +368,7 @@ class CutOut(FlatCAMTool):
self.layout.addStretch()
# ## Reset Tool
self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
self.reset_button = FCButton(_("Reset Tool"))
self.reset_button.setToolTip(
_("Will reset the tool parameters.")
)
@ -525,7 +524,7 @@ class CutOut(FlatCAMTool):
def geo_init(geo_obj, app_obj):
solid_geo = []
if isinstance(cutout_obj, FlatCAMGerber):
if cutout_obj.kind == 'gerber':
if isinstance(cutout_obj.solid_geometry, list):
cutout_obj.solid_geometry = MultiPolygon(cutout_obj.solid_geometry)
@ -542,12 +541,12 @@ class CutOut(FlatCAMTool):
def cutout_handler(geom):
# Get min and max data for each object as we just cut rectangles across X or Y
xmin, ymin, xmax, ymax = recursive_bounds(geom)
xxmin, yymin, xxmax, yymax = recursive_bounds(geom)
px = 0.5 * (xmin + xmax) + margin
py = 0.5 * (ymin + ymax) + margin
lenx = (xmax - xmin) + (margin * 2)
leny = (ymax - ymin) + (margin * 2)
px = 0.5 * (xxmin + xxmax) + margin
py = 0.5 * (yymin + yymax) + margin
lenx = (xxmax - xxmin) + (margin * 2)
leny = (yymax - yymin) + (margin * 2)
proc_geometry = []
if gaps == 'None':
@ -555,41 +554,41 @@ class CutOut(FlatCAMTool):
else:
if gaps == '8' or gaps == '2LR':
geom = self.subtract_poly_from_geo(geom,
xmin - gapsize, # botleft_x
xxmin - gapsize, # botleft_x
py - gapsize + leny / 4, # botleft_y
xmax + gapsize, # topright_x
xxmax + gapsize, # topright_x
py + gapsize + leny / 4) # topright_y
geom = self.subtract_poly_from_geo(geom,
xmin - gapsize,
xxmin - gapsize,
py - gapsize - leny / 4,
xmax + gapsize,
xxmax + gapsize,
py + gapsize - leny / 4)
if gaps == '8' or gaps == '2TB':
geom = self.subtract_poly_from_geo(geom,
px - gapsize + lenx / 4,
ymin - gapsize,
yymin - gapsize,
px + gapsize + lenx / 4,
ymax + gapsize)
yymax + gapsize)
geom = self.subtract_poly_from_geo(geom,
px - gapsize - lenx / 4,
ymin - gapsize,
yymin - gapsize,
px + gapsize - lenx / 4,
ymax + gapsize)
yymax + gapsize)
if gaps == '4' or gaps == 'LR':
geom = self.subtract_poly_from_geo(geom,
xmin - gapsize,
xxmin - gapsize,
py - gapsize,
xmax + gapsize,
xxmax + gapsize,
py + gapsize)
if gaps == '4' or gaps == 'TB':
geom = self.subtract_poly_from_geo(geom,
px - gapsize,
ymin - gapsize,
yymin - gapsize,
px + gapsize,
ymax + gapsize)
yymax + gapsize)
try:
for g in geom:
@ -603,7 +602,7 @@ class CutOut(FlatCAMTool):
object_geo = unary_union(object_geo)
# for geo in object_geo:
if isinstance(cutout_obj, FlatCAMGerber):
if cutout_obj.kind == 'gerber':
if isinstance(object_geo, MultiPolygon):
x0, y0, x1, y1 = object_geo.bounds
object_geo = box(x0, y0, x1, y1)
@ -623,7 +622,7 @@ class CutOut(FlatCAMTool):
object_geo = [object_geo]
for geom_struct in object_geo:
if isinstance(cutout_obj, FlatCAMGerber):
if cutout_obj.kind == 'gerber':
if margin >= 0:
geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
else:
@ -775,7 +774,7 @@ class CutOut(FlatCAMTool):
# if Gerber create a buffer at a distance
# if Geometry then cut through the geometry
if isinstance(cutout_obj, FlatCAMGerber):
if cutout_obj.kind == 'gerber':
if margin >= 0:
geo = geo.buffer(margin + abs(dia / 2))
else:
@ -909,7 +908,7 @@ class CutOut(FlatCAMTool):
"Select one and try again."))
return
if not isinstance(cutout_obj, FlatCAMGerber):
if cutout_obj.kind != 'gerber':
self.app.inform.emit('[ERROR_NOTCL] %s' %
_("The selected object has to be of Gerber type.\n"
"Select a Gerber file and try again."))
@ -988,11 +987,11 @@ class CutOut(FlatCAMTool):
if self.app.is_legacy is False:
event_pos = event.pos
event_is_dragging = event.is_dragging
# event_is_dragging = event.is_dragging
right_button = 2
else:
event_pos = (event.xdata, event.ydata)
event_is_dragging = self.app.plotcanvas.is_dragging
# event_is_dragging = self.app.plotcanvas.is_dragging
right_button = 3
try:
@ -1038,11 +1037,11 @@ class CutOut(FlatCAMTool):
if self.app.is_legacy is False:
event_pos = event.pos
event_is_dragging = event.is_dragging
right_button = 2
# right_button = 2
else:
event_pos = (event.xdata, event.ydata)
event_is_dragging = self.app.plotcanvas.is_dragging
right_button = 3
# right_button = 3
try:
x = float(event_pos[0])
@ -1159,13 +1158,17 @@ class CutOut(FlatCAMTool):
if '+' in key_string:
mod, __, key_text = key_string.rpartition('+')
if mod.lower() == 'ctrl':
modifiers = QtCore.Qt.ControlModifier
# modifiers = QtCore.Qt.ControlModifier
pass
elif mod.lower() == 'alt':
modifiers = QtCore.Qt.AltModifier
# modifiers = QtCore.Qt.AltModifier
pass
elif mod.lower() == 'shift':
modifiers = QtCore.Qt.ShiftModifier
# modifiers = QtCore.Qt.ShiftModifier
pass
else:
modifiers = QtCore.Qt.NoModifier
# modifiers = QtCore.Qt.NoModifier
pass
key = QtGui.QKeySequence(key_text)
# events from Vispy are of type KeyEvent
else:
@ -1203,7 +1206,8 @@ class CutOut(FlatCAMTool):
geo = self.cutting_geo(pos=(l_x, l_y))
self.draw_utility_geometry(geo=geo)
def subtract_poly_from_geo(self, solid_geo, x0, y0, x1, y1):
@staticmethod
def subtract_poly_from_geo(solid_geo, x0, y0, x1, y1):
"""
Subtract polygon made from points from the given object.
This only operates on the paths in the original geometry,
@ -1270,8 +1274,9 @@ def flatten(geometry):
def recursive_bounds(geometry):
"""
Returns coordinates of rectangular bounds
of geometry: (xmin, ymin, xmax, ymax).
:param geometry: a iterable object that holds geometry
:return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
"""
# now it can get bounds for nested lists of objects

View File

@ -3,7 +3,6 @@ from PyQt5 import QtWidgets, QtCore
from FlatCAMTool import FlatCAMTool
from flatcamGUI.GUIElements import RadioSet, FCDoubleSpinner, EvalEntry, FCEntry, FCButton, FCComboBox
from FlatCAMObj import FlatCAMGerber, FlatCAMExcellon, FlatCAMGeometry
from numpy import Inf
@ -658,7 +657,7 @@ class DblSidedTool(FlatCAMTool):
self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
return
if not isinstance(fcobj, FlatCAMGerber):
if fcobj.kind != 'gerber':
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Only Gerber, Excellon and Geometry objects can be mirrored."))
return
@ -701,7 +700,7 @@ class DblSidedTool(FlatCAMTool):
self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Excellon object loaded ..."))
return
if not isinstance(fcobj, FlatCAMExcellon):
if fcobj.kind != 'excellon':
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Only Gerber, Excellon and Geometry objects can be mirrored."))
return
@ -745,7 +744,7 @@ class DblSidedTool(FlatCAMTool):
self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Geometry object loaded ..."))
return
if not isinstance(fcobj, FlatCAMGeometry):
if fcobj.kind != 'geometry':
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Only Gerber, Excellon and Geometry objects can be mirrored."))
return

View File

@ -8,7 +8,6 @@
from PyQt5 import QtWidgets, QtCore
from FlatCAMTool import FlatCAMTool
from flatcamGUI.VisPyVisuals import *
from FlatCAMObj import FlatCAMGerber
from copy import copy
import logging
@ -128,7 +127,7 @@ class ToolMove(FlatCAMTool):
pos_canvas = self.app.plotcanvas.translate_coords(event_pos)
# if GRID is active we need to get the snapped positions
if self.app.grid_status() == True:
if self.app.grid_status():
pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
else:
pos = pos_canvas
@ -148,7 +147,7 @@ class ToolMove(FlatCAMTool):
self.delete_shape()
# if GRID is active we need to get the snapped positions
if self.app.grid_status() == True:
if self.app.grid_status():
pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
else:
pos = pos_canvas
@ -171,7 +170,7 @@ class ToolMove(FlatCAMTool):
# remove any mark aperture shape that may be displayed
for sel_obj in obj_list:
# if the Gerber mark shapes are enabled they need to be disabled before move
if isinstance(sel_obj, FlatCAMGerber):
if sel_obj.kind == 'gerber':
sel_obj.ui.aperture_table_visibility_cb.setChecked(False)
try:
@ -198,8 +197,8 @@ class ToolMove(FlatCAMTool):
elif sel_obj.kind == 'excellon':
sel_obj.source_file = self.app.export_excellon(
obj_name=out_name, filename=None, local_use=sel_obj, use_thread=False)
except Exception as e:
log.debug('[ERROR_NOTCL] %s --> %s' % ('ToolMove.on_left_click()', str(e)))
except Exception as err:
log.debug('[ERROR_NOTCL] %s --> %s' % ('ToolMove.on_left_click()', str(err)))
return "fail"
# time to plot the moved objects
@ -249,7 +248,7 @@ class ToolMove(FlatCAMTool):
pos_canvas = self.app.plotcanvas.translate_coords((x, y))
# if GRID is active we need to get the snapped positions
if self.app.grid_status() == True:
if self.app.grid_status():
pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
else:
pos = pos_canvas

View File

@ -12,7 +12,7 @@ from flatcamGUI.GUIElements import FCCheckBox, FCDoubleSpinner, RadioSet, FCTabl
FCComboBox, OptionalInputSection
from flatcamParsers.ParseGerber import Gerber
import FlatCAMApp
from FlatCAMCommon import GracefulException as grace
from copy import deepcopy
@ -1987,7 +1987,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for poly in env_obj:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
bounding_box = cascaded_union(geo_buff_list)
elif ncc_select == _("Reference Object"):
@ -1996,7 +1996,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for poly in env_obj:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
bounding_box = cascaded_union(geo_buff_list)
@ -2090,7 +2090,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if isinstance(geo_elem, Polygon):
for ring in self.poly2rings(geo_elem):
@ -2312,7 +2312,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
log.debug("Starting geometry processing for tool: %s" % str(tool))
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# provide the app with a way to process the GUI events when in a blocking loop
QtWidgets.QApplication.processEvents()
@ -2377,7 +2377,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# clean the polygon
p = p.buffer(0)
@ -2595,7 +2595,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
log.debug("Starting geometry processing for tool: %s" % str(tool))
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# provide the app with a way to process the GUI events when in a blocking loop
QtWidgets.QApplication.processEvents()
@ -2644,7 +2644,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
try:
area = area.difference(poly)
except Exception:
@ -2674,7 +2674,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for p in area.geoms:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# clean the polygon
p = p.buffer(0)
@ -2753,7 +2753,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# check if there is a geometry at all in the cleared geometry
if cleared_geo:
@ -2771,7 +2771,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for p in cleared_area:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
poly = p.buffer(buffer_value)
cleared_by_last_tool.append(poly)
@ -2836,7 +2836,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
app_obj.new_object("geometry", name, gen_clear_area_rest)
else:
app_obj.new_object("geometry", name, gen_clear_area)
except FlatCAMApp.GracefulException:
except grace:
if run_threaded:
proc.done()
return
@ -2999,7 +2999,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for poly in geo_n:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
bounding_box = cascaded_union(geo_buff_list)
@ -3017,7 +3017,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for poly in geo_n:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
bounding_box = cascaded_union(geo_buff_list)
@ -3141,7 +3141,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if isinstance(geo_elem, Polygon):
for ring in self.poly2rings(geo_elem):
@ -3242,7 +3242,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
log.debug("Starting geometry processing for tool: %s" % str(tool))
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# provide the app with a way to process the GUI events when in a blocking loop
QtWidgets.QApplication.processEvents()
@ -3283,7 +3283,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# clean the polygon
p = p.buffer(0)
@ -3520,7 +3520,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if isinstance(geo_elem, Polygon):
for ring in self.poly2rings(geo_elem):
@ -3614,7 +3614,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if type(empty) is Polygon:
empty = MultiPolygon([empty])
@ -3628,7 +3628,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
while sorted_tools:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
tool = sorted_tools.pop(0)
log.debug("Starting geometry processing for tool: %s" % str(tool))
@ -3648,7 +3648,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
try:
area = area.difference(poly_r)
except Exception:
@ -3678,7 +3678,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for p in area.geoms:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# clean the polygon
p = p.buffer(0)
@ -3754,7 +3754,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# check if there is a geometry at all in the cleared geometry
if cleared_geo:
@ -3772,7 +3772,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
for p in cleared_area:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
r_poly = p.buffer(buffer_value)
cleared_by_last_tool.append(r_poly)
@ -3833,7 +3833,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
else:
app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
except FlatCAMApp.GracefulException:
except grace:
if run_threaded:
proc.done()
return
@ -3887,7 +3887,7 @@ class NonCopperClear(FlatCAMTool, Gerber):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
boundary = boundary.difference(el)
pol_nr += 1
disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))

View File

@ -9,8 +9,7 @@ from PyQt5 import QtWidgets, QtCore, QtGui
from FlatCAMTool import FlatCAMTool
from flatcamGUI.GUIElements import OptionalHideInputSection, FCTextArea, FCEntry, FCSpinner, FCCheckBox, FCComboBox
from FlatCAMObj import FlatCAMGerber
import FlatCAMApp
from FlatCAMCommon import GracefulException as grace
from shapely.geometry import MultiPolygon
from shapely.ops import nearest_points
@ -343,7 +342,7 @@ class ToolOptimal(FlatCAMTool):
self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
return
if not isinstance(fcobj, FlatCAMGerber):
if fcobj.kind != 'gerber':
self.app.inform.emit('[ERROR_NOTCL] %s' % _("Only Gerber objects can be evaluated."))
return
@ -365,7 +364,7 @@ class ToolOptimal(FlatCAMTool):
for geo_el in fcobj.apertures[ap]['geometry']:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if 'solid' in geo_el and geo_el['solid'] is not None and geo_el['solid'].is_valid:
total_geo.append(geo_el['solid'])
@ -395,7 +394,7 @@ class ToolOptimal(FlatCAMTool):
for s_geo in total_geo[idx:]:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# minimize the number of distances by not taking into considerations those that are too small
dist = geo.distance(s_geo)
@ -459,7 +458,7 @@ class ToolOptimal(FlatCAMTool):
log.debug("ToolOptimal.on_locate_position() --> first try %s" % str(e))
self.app.inform.emit("[ERROR_NOTCL] The selected text is no valid location in the format "
"((x0, y0), (x1, y1)).")
return 'fail'
return
try:
loc_1 = loc[0]
@ -471,7 +470,7 @@ class ToolOptimal(FlatCAMTool):
self.app.on_jump_to(custom_location=loc)
except Exception as e:
log.debug("ToolOptimal.on_locate_position() --> sec try %s" % str(e))
return 'fail'
return
def on_update_text(self, data):
txt = ''
@ -567,12 +566,12 @@ class ToolOptimal(FlatCAMTool):
if self.selected_locations_text != '':
loc = eval(self.selected_locations_text)
else:
return 'fail'
return
except Exception as e:
log.debug("ToolOptimal.on_locate_sec_position() --> first try %s" % str(e))
self.app.inform.emit("[ERROR_NOTCL] The selected text is no valid location in the format "
"((x0, y0), (x1, y1)).")
return 'fail'
return
try:
loc_1 = loc[0]
@ -584,7 +583,7 @@ class ToolOptimal(FlatCAMTool):
self.app.on_jump_to(custom_location=loc)
except Exception as e:
log.debug("ToolOptimal.on_locate_sec_position() --> sec try %s" % str(e))
return 'fail'
return
def reset_fields(self):
self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))

View File

@ -8,7 +8,7 @@
from PyQt5 import QtWidgets, QtCore
from FlatCAMTool import FlatCAMTool
import FlatCAMApp
from FlatCAMCommon import GracefulException as grace
from shapely.geometry import Point, Polygon, LineString, MultiPolygon
from shapely.ops import unary_union
@ -190,7 +190,7 @@ class ToolPDF(FlatCAMTool):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
with self.app.proc_container.new(_("Parsing PDF file ...")):
with open(filename, "rb") as f:
@ -200,7 +200,7 @@ class ToolPDF(FlatCAMTool):
for s in re.findall(self.stream_re, pdf):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
stream_nr += 1
log.debug(" PDF STREAM: %d\n" % stream_nr)
@ -291,7 +291,7 @@ class ToolPDF(FlatCAMTool):
def layer_rendering_as_gerber(self, filename, ap_dict, layer_nr):
outname = filename.split('/')[-1].split('\\')[-1] + "_%s" % str(layer_nr)
def obj_init(grb_obj, app_obj):
def obj_init(grb_obj):
grb_obj.apertures = ap_dict
@ -404,7 +404,7 @@ class ToolPDF(FlatCAMTool):
for object_name in self.pdf_parsed:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
filename = deepcopy(self.pdf_parsed[object_name]['filename'])
pdf_content = deepcopy(self.pdf_parsed[object_name]['pdf'])
@ -412,7 +412,7 @@ class ToolPDF(FlatCAMTool):
for k in pdf_content:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
ap_dict = pdf_content[k]
if ap_dict:
@ -493,7 +493,7 @@ class ToolPDF(FlatCAMTool):
for pline in lines:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
line_nr += 1
log.debug("line %d: %s" % (line_nr, pline))
@ -868,7 +868,6 @@ class ToolPDF(FlatCAMTool):
new_el['solid'] = pdf_geo
new_el['follow'] = pdf_geo.exterior
apertures_dict[copy(found_aperture)]['geometry'].append(deepcopy(new_el))
found_aperture = None
else:
if str(aperture) in apertures_dict.keys():
aperture += 1
@ -1231,7 +1230,6 @@ class ToolPDF(FlatCAMTool):
new_el['solid'] = pdf_geo
new_el['follow'] = pdf_geo.exterior
apertures_dict[copy(found_aperture)]['geometry'].append(deepcopy(new_el))
found_aperture = None
else:
if str(aperture) in apertures_dict.keys():
aperture += 1
@ -1355,7 +1353,7 @@ class ToolPDF(FlatCAMTool):
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
return object_dict

View File

@ -14,7 +14,7 @@ from copy import deepcopy
from flatcamParsers.ParseGerber import Gerber
from camlib import Geometry, FlatCAMRTreeStorage
from flatcamGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet, FCButton, FCComboBox
import FlatCAMApp
from FlatCAMCommon import GracefulException as grace
from shapely.geometry import base, Polygon, MultiPolygon, LinearRing, Point
from shapely.ops import cascaded_union, unary_union, linemerge
@ -1836,7 +1836,7 @@ class ToolPaint(FlatCAMTool, Gerber):
contour=cont,
connect=conn,
prog_plot=prog_plot)
except FlatCAMApp.GracefulException:
except grace:
return "fail"
except Exception as ee:
log.debug("ToolPaint.paint_polygon_worker() Standard --> %s" % str(ee))
@ -1850,7 +1850,7 @@ class ToolPaint(FlatCAMTool, Gerber):
contour=cont,
connect=conn,
prog_plot=prog_plot)
except FlatCAMApp.GracefulException:
except grace:
return "fail"
except Exception as ee:
log.debug("ToolPaint.paint_polygon_worker() Seed --> %s" % str(ee))
@ -1864,7 +1864,7 @@ class ToolPaint(FlatCAMTool, Gerber):
contour=cont,
connect=conn,
prog_plot=prog_plot)
except FlatCAMApp.GracefulException:
except grace:
return "fail"
except Exception as ee:
log.debug("ToolPaint.paint_polygon_worker() Lines --> %s" % str(ee))
@ -2015,7 +2015,7 @@ class ToolPaint(FlatCAMTool, Gerber):
# contour=cont,
# connect=conn,
# prog_plot=prog_plot)
except FlatCAMApp.GracefulException:
except grace:
return "fail"
except Exception as ee:
log.debug("ToolPaint.paint_polygon_worker() Laser Lines --> %s" % str(ee))
@ -2052,7 +2052,7 @@ class ToolPaint(FlatCAMTool, Gerber):
contour=cont,
connect=conn,
prog_plot=prog_plot)
except FlatCAMApp.GracefulException:
except grace:
return "fail"
except Exception as ee:
log.debug("ToolPaint.paint_polygon_worker() Combo --> %s" % str(ee))
@ -2199,7 +2199,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
prog_plot=prog_plot)
@ -2217,7 +2217,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -2230,7 +2230,7 @@ class ToolPaint(FlatCAMTool, Gerber):
for x in cp:
total_geometry += list(x.get_objects())
final_solid_geometry += total_geometry
except FlatCAMApp.GracefulException:
except grace:
return "fail"
except Exception as e:
log.debug("Could not Paint the polygons. %s" % str(e))
@ -2305,7 +2305,7 @@ class ToolPaint(FlatCAMTool, Gerber):
def job_thread(app_obj):
try:
ret = app_obj.new_object("geometry", name, job_init, plot=plot)
except FlatCAMApp.GracefulException:
except grace:
proc.done()
return
except Exception as er:
@ -2376,7 +2376,7 @@ class ToolPaint(FlatCAMTool, Gerber):
"""
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if geometry is None:
return
@ -2517,7 +2517,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -2542,7 +2542,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -2705,7 +2705,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
prog_plot=prog_plot)
@ -2723,7 +2723,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -2735,7 +2735,7 @@ class ToolPaint(FlatCAMTool, Gerber):
for x in cp:
cleared_geo += list(x.get_objects())
final_solid_geometry += cleared_geo
except FlatCAMApp.GracefulException:
except grace:
return "fail"
except Exception as e:
log.debug("Could not Paint the polygons. %s" % str(e))
@ -2815,7 +2815,7 @@ class ToolPaint(FlatCAMTool, Gerber):
ret = app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
else:
ret = app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
except FlatCAMApp.GracefulException:
except grace:
proc.done()
return
except Exception as err:
@ -2873,7 +2873,7 @@ class ToolPaint(FlatCAMTool, Gerber):
"""
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if geometry is None:
return
@ -3015,7 +3015,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -3040,7 +3040,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -3193,7 +3193,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -3218,7 +3218,7 @@ class ToolPaint(FlatCAMTool, Gerber):
QtWidgets.QApplication.processEvents()
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
cont=cont, paint_method=paint_method, obj=obj,
@ -3312,7 +3312,7 @@ class ToolPaint(FlatCAMTool, Gerber):
ret = app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
else:
ret = app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
except FlatCAMApp.GracefulException:
except grace:
proc.done()
return
except Exception as err:

View File

@ -9,10 +9,8 @@ from PyQt5 import QtWidgets, QtGui, QtCore
from FlatCAMTool import FlatCAMTool
from flatcamGUI.GUIElements import FCSpinner, FCDoubleSpinner, RadioSet, FCCheckBox, OptionalInputSection, FCComboBox
from FlatCAMObj import FlatCAMGeometry, FlatCAMGerber, FlatCAMExcellon
import FlatCAMApp
from FlatCAMCommon import GracefulException as grace
from copy import deepcopy
# from ObjectCollection import *
import numpy as np
import shapely.affinity as affinity
@ -480,13 +478,13 @@ class Panelize(FlatCAMTool):
rows -= 1
panel_lengthy = ((ymax - ymin) * rows) + (spacing_rows * (rows - 1))
if isinstance(panel_obj, FlatCAMExcellon) or isinstance(panel_obj, FlatCAMGeometry):
if panel_obj.kind == 'excellon' or panel_obj.kind == 'geometry':
# make a copy of the panelized Excellon or Geometry tools
copied_tools = {}
for tt, tt_val in list(panel_obj.tools.items()):
copied_tools[tt] = deepcopy(tt_val)
if isinstance(panel_obj, FlatCAMGerber):
if panel_obj.kind == 'gerber':
# make a copy of the panelized Gerber apertures
copied_apertures = {}
for tt, tt_val in list(panel_obj.apertures.items()):
@ -525,7 +523,7 @@ class Panelize(FlatCAMTool):
for tool_dict in panel_obj.drills:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
point_offseted = affinity.translate(tool_dict['point'], currentx, currenty)
obj_fin.drills.append(
@ -550,7 +548,7 @@ class Panelize(FlatCAMTool):
for tool_dict in panel_obj.slots:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
start_offseted = affinity.translate(tool_dict['start'], currentx, currenty)
stop_offseted = affinity.translate(tool_dict['stop'], currentx, currenty)
@ -600,20 +598,20 @@ class Panelize(FlatCAMTool):
obj_fin.solid_geometry = []
# create the initial structure on which to create the panel
if isinstance(panel_obj, FlatCAMGeometry):
if panel_obj.kind == 'geometry':
obj_fin.multigeo = panel_obj.multigeo
obj_fin.tools = copied_tools
if panel_obj.multigeo is True:
for tool in panel_obj.tools:
obj_fin.tools[tool]['solid_geometry'][:] = []
elif isinstance(panel_obj, FlatCAMGerber):
elif panel_obj.kind == 'gerber':
obj_fin.apertures = copied_apertures
for ap in obj_fin.apertures:
obj_fin.apertures[ap]['geometry'] = []
# find the number of polygons in the source solid_geometry
geo_len = 0
if isinstance(panel_obj, FlatCAMGeometry):
if panel_obj.kind == 'geometry':
if panel_obj.multigeo is True:
for tool in panel_obj.tools:
try:
@ -625,7 +623,7 @@ class Panelize(FlatCAMTool):
geo_len = len(panel_obj.solid_geometry)
except TypeError:
geo_len = 1
elif isinstance(panel_obj, FlatCAMGerber):
elif panel_obj.kind == 'gerber':
for ap in panel_obj.apertures:
if 'geometry' in panel_obj.apertures[ap]:
try:
@ -641,12 +639,12 @@ class Panelize(FlatCAMTool):
element += 1
old_disp_number = 0
if isinstance(panel_obj, FlatCAMGeometry):
if panel_obj.kind == 'geometry':
if panel_obj.multigeo is True:
for tool in panel_obj.tools:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
# geo = translate_recursion(panel_obj.tools[tool]['solid_geometry'])
# if isinstance(geo, list):
@ -678,7 +676,7 @@ class Panelize(FlatCAMTool):
# obj_fin.solid_geometry.append(geo)
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
try:
# calculate the number of polygons
@ -690,7 +688,7 @@ class Panelize(FlatCAMTool):
for geo_el in panel_obj.solid_geometry:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
trans_geo = translate_recursion(geo_el)
obj_fin.solid_geometry.append(trans_geo)
@ -715,13 +713,13 @@ class Panelize(FlatCAMTool):
# obj_fin.solid_geometry.append(geo)
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
try:
for geo_el in panel_obj.solid_geometry:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
trans_geo = translate_recursion(geo_el)
obj_fin.solid_geometry.append(trans_geo)
@ -732,7 +730,7 @@ class Panelize(FlatCAMTool):
for apid in panel_obj.apertures:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
if 'geometry' in panel_obj.apertures[apid]:
try:
# calculate the number of polygons
@ -743,7 +741,7 @@ class Panelize(FlatCAMTool):
for el in panel_obj.apertures[apid]['geometry']:
if self.app.abort_flag:
# graceful abort requested by the user
raise FlatCAMApp.GracefulException
raise grace
new_el = {}
if 'solid' in el:
@ -786,7 +784,7 @@ class Panelize(FlatCAMTool):
self.app.proc_container.update_view_text('')
self.app.inform.emit('%s: %d' % (_("Generating panel... Spawning copies"), (int(rows * columns))))
if isinstance(panel_obj, FlatCAMExcellon):
if panel_obj.kind == 'excellon':
self.app.new_object("excellon", self.outname, job_init_excellon, plot=True, autoselected=True)
else:
self.app.new_object(panel_type, self.outname, job_init_geometry, plot=True, autoselected=True)

View File

@ -11,7 +11,6 @@ from flatcamGUI.GUIElements import FCComboBox, FCEntry, FCTable, \
FCInputDialog, FCDoubleSpinner, FCSpinner, FCFileSaveDialog
from FlatCAMApp import log
from camlib import distance
from FlatCAMObj import FlatCAMCNCjob
from flatcamEditors.FlatCAMTextEditor import TextEditor
from PyQt5 import QtGui, QtCore, QtWidgets
@ -506,7 +505,8 @@ class SolderPaste(FlatCAMTool):
self.flat_geometry = []
# action to be added in the combobox context menu
self.combo_context_del_action = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/trash16.png'), _("Delete Object"))
self.combo_context_del_action = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/trash16.png'),
_("Delete Object"))
# ## Signals
self.combo_context_del_action.triggered.connect(self.on_delete_object)
@ -966,6 +966,7 @@ class SolderPaste(FlatCAMTool):
self.build_ui()
return
else:
old_tool_dia = ''
# identify the old tool_dia and restore the text in tool table
for k, v in self.tooltable_tools.items():
if k == tooluid:
@ -1332,8 +1333,8 @@ class SolderPaste(FlatCAMTool):
# Object initialization function for app.new_object()
# RUNNING ON SEPARATE THREAD!
def job_init(job_obj, app_obj):
assert isinstance(job_obj, FlatCAMCNCjob), \
def job_init(job_obj):
assert job_obj.kind == 'cncjob', \
"Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
# this turn on the FlatCAMCNCJob plot for multiple tools

View File

@ -8,7 +8,6 @@
from PyQt5 import QtWidgets
from FlatCAMTool import FlatCAMTool
from flatcamGUI.GUIElements import FCDoubleSpinner, FCCheckBox, FCButton, OptionalInputSection, EvalEntry2
from FlatCAMObj import FlatCAMCNCjob
import gettext
import FlatCAMTranslation as fcTranslate
@ -681,7 +680,7 @@ class ToolTransform(FlatCAMTool):
try:
# first get a bounding box to fit all
for obj in obj_list:
if isinstance(obj, FlatCAMCNCjob):
if obj.kind == 'cncjob':
pass
else:
xmin, ymin, xmax, ymax = obj.bounds()
@ -699,7 +698,7 @@ class ToolTransform(FlatCAMTool):
px = 0.5 * (xminimal + xmaximal)
py = 0.5 * (yminimal + ymaximal)
for sel_obj in obj_list:
if isinstance(sel_obj, FlatCAMCNCjob):
if sel_obj.kind == 'cncjob':
self.app.inform.emit(_("CNCJob objects can't be rotated."))
else:
sel_obj.rotate(-num, point=(px, py))
@ -735,7 +734,7 @@ class ToolTransform(FlatCAMTool):
else:
# first get a bounding box to fit all
for obj in obj_list:
if isinstance(obj, FlatCAMCNCjob):
if obj.kind == 'cncjob':
pass
else:
xmin, ymin, xmax, ymax = obj.bounds()
@ -755,7 +754,7 @@ class ToolTransform(FlatCAMTool):
# execute mirroring
for sel_obj in obj_list:
if isinstance(sel_obj, FlatCAMCNCjob):
if sel_obj.kind == 'cncjob':
self.app.inform.emit(_("CNCJob objects can't be mirrored/flipped."))
else:
if axis == 'X':
@ -803,7 +802,7 @@ class ToolTransform(FlatCAMTool):
try:
# first get a bounding box to fit all
for obj in obj_list:
if isinstance(obj, FlatCAMCNCjob):
if obj.kind == 'cncjob':
pass
else:
xmin, ymin, xmax, ymax = obj.bounds()
@ -815,7 +814,7 @@ class ToolTransform(FlatCAMTool):
yminimal = min(yminlist)
for sel_obj in obj_list:
if isinstance(sel_obj, FlatCAMCNCjob):
if sel_obj.kind == 'cncjob':
self.app.inform.emit(_("CNCJob objects can't be skewed."))
else:
if axis == 'X':
@ -842,15 +841,14 @@ class ToolTransform(FlatCAMTool):
ymaxlist = []
if not obj_list:
self.app.inform.emit('[WARNING_NOTCL] %s' %
_("No object selected. Please Select an object to scale!"))
self.app.inform.emit('[WARNING_NOTCL] %s' % _("No object selected. Please Select an object to scale!"))
return
else:
with self.app.proc_container.new(_("Applying Scale")):
try:
# first get a bounding box to fit all
for obj in obj_list:
if isinstance(obj, FlatCAMCNCjob):
if obj.kind == 'cncjob':
pass
else:
xmin, ymin, xmax, ymax = obj.bounds()
@ -873,7 +871,7 @@ class ToolTransform(FlatCAMTool):
py = 0
for sel_obj in obj_list:
if isinstance(sel_obj, FlatCAMCNCjob):
if sel_obj.kind == 'cncjob':
self.app.inform.emit(_("CNCJob objects can't be scaled."))
else:
sel_obj.scale(xfactor, yfactor, point=(px, py))
@ -883,8 +881,7 @@ class ToolTransform(FlatCAMTool):
self.app.object_changed.emit(sel_obj)
sel_obj.plot()
self.app.inform.emit('[success] %s %s %s...' %
(_('Scale on the'), str(axis), _('axis done')))
self.app.inform.emit('[success] %s %s %s...' % (_('Scale on the'), str(axis), _('axis done')))
except Exception as e:
self.app.inform.emit('[ERROR_NOTCL] %s %s, %s.' %
(_("Due of"), str(e), _("action was not executed.")))
@ -894,14 +891,13 @@ class ToolTransform(FlatCAMTool):
obj_list = self.app.collection.get_selected()
if not obj_list:
self.app.inform.emit('[WARNING_NOTCL] %s' %
_("No object selected. Please Select an object to offset!"))
self.app.inform.emit('[WARNING_NOTCL] %s' % _("No object selected. Please Select an object to offset!"))
return
else:
with self.app.proc_container.new(_("Applying Offset")):
try:
for sel_obj in obj_list:
if isinstance(sel_obj, FlatCAMCNCjob):
if sel_obj.kind == 'cncjob':
self.app.inform.emit(_("CNCJob objects can't be offset."))
else:
if axis == 'X':
@ -915,8 +911,7 @@ class ToolTransform(FlatCAMTool):
self.app.object_changed.emit(sel_obj)
sel_obj.plot()
self.app.inform.emit('[success] %s %s %s...' %
(_('Offset on the'), str(axis), _('axis done')))
self.app.inform.emit('[success] %s %s %s...' % (_('Offset on the'), str(axis), _('axis done')))
except Exception as e:
self.app.inform.emit('[ERROR_NOTCL] %s %s, %s.' %
(_("Due of"), str(e), _("action was not executed.")))
@ -932,7 +927,7 @@ class ToolTransform(FlatCAMTool):
with self.app.proc_container.new(_("Applying Buffer")):
try:
for sel_obj in obj_list:
if isinstance(sel_obj, FlatCAMCNCjob):
if sel_obj.kind == 'cncjob':
self.app.inform.emit(_("CNCJob objects can't be buffered."))
elif sel_obj.kind.lower() == 'gerber':
sel_obj.buffer(value, join, factor)