- some PEP8 cleanup in FlatCAMApp.py

This commit is contained in:
Marius Stanciu
2019-05-22 23:40:26 +03:00
parent 8a273b3a6f
commit 4c49348aef
2 changed files with 146 additions and 138 deletions

View File

@@ -52,9 +52,9 @@ import tclCommands
import gettext import gettext
import FlatCAMTranslation as fcTranslate import FlatCAMTranslation as fcTranslate
import builtins
fcTranslate.apply_language('strings') fcTranslate.apply_language('strings')
import builtins
if '_' not in builtins.__dict__: if '_' not in builtins.__dict__:
_ = gettext.gettext _ = gettext.gettext
@@ -285,7 +285,6 @@ class App(QtCore.QObject):
QtCore.QObject.__init__(self) QtCore.QObject.__init__(self)
self.ui = FlatCAMGUI(self.version, self.beta, self) self.ui = FlatCAMGUI(self.version, self.beta, self)
# self.connect(self.ui, # self.connect(self.ui,
# QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"), # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
# self.save_geometry) PyQt4 # self.save_geometry) PyQt4
@@ -644,7 +643,7 @@ class App(QtCore.QObject):
"global_background_timeout": 300000, # Default value is 5 minutes "global_background_timeout": 300000, # Default value is 5 minutes
"global_verbose_error_level": 0, # Shell verbosity 0 = default "global_verbose_error_level": 0, # Shell verbosity 0 = default
# (python trace only for unknown errors), # (python trace only for unknown errors),
# 1 = show trace(show trace allways), # 1 = show trace(show trace always),
# 2 = (For the future). # 2 = (For the future).
# Persistence # Persistence
@@ -1242,7 +1241,6 @@ class App(QtCore.QObject):
self.defaults['global_proj_item_dis_color']) self.defaults['global_proj_item_dis_color'])
self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet( self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
"background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7]) "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
# ### End of Data #### # ### End of Data ####
# ### Plot Area #### # ### Plot Area ####
@@ -1291,9 +1289,8 @@ class App(QtCore.QObject):
self.workers = WorkerStack(workers_number=2) self.workers = WorkerStack(workers_number=2)
self.worker_task.connect(self.workers.add_task) self.worker_task.connect(self.workers.add_task)
# ## Signal handling ### # ## Signal handling ###
## Custom signals # ## Custom signals
self.inform.connect(self.info) self.inform.connect(self.info)
self.app_quit.connect(self.quit_application) self.app_quit.connect(self.quit_application)
self.message.connect(self.message_dialog) self.message.connect(self.message_dialog)
@@ -1306,9 +1303,8 @@ class App(QtCore.QObject):
self.file_opened.connect(lambda kind, filename: self.register_folder(filename)) self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename)) self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
# ## Standard signals
## Standard signals # ## Menu
# Menu
self.ui.menufilenewproject.triggered.connect(self.on_file_new_click) self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object) self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object) self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
@@ -1562,7 +1558,6 @@ class App(QtCore.QObject):
else: else:
self.ui.splitter.setSizes([0, 1]) self.ui.splitter.setSizes([0, 1])
# ################### # ###################
# ## Other setups ### # ## Other setups ###
# ################### # ###################
@@ -1592,14 +1587,14 @@ class App(QtCore.QObject):
] ]
self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis', self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx', 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid', 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin', 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange', 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename', 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y', 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x', 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
'angle_y', 'gridx', 'gridy', 'True', 'False' 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
] ]
self.tcl_keywords = [ self.tcl_keywords = [
@@ -1817,6 +1812,23 @@ class App(QtCore.QObject):
# ## Tools and Plugins ### # ## Tools and Plugins ###
# ######################## # ########################
self.dblsidedtool = None
self.measurement_tool = None
self.panelize_tool = None
self.film_tool = None
self.paste_tool = None
self.calculator_tool = None
self.sub_tool = None
self.move_tool = None
self.cutout_tool = None
self.ncclear_tool = None
self.paint_tool = None
self.transform_tool = None
self.properties_tool = None
self.pdf_tool = None
self.image_tool = None
self.pcb_wizard_tool = None
# always install tools only after the shell is initialized because the self.inform.emit() depends on shell # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
self.install_tools() self.install_tools()
@@ -1849,7 +1861,6 @@ class App(QtCore.QObject):
'params': []}) 'params': []})
self.thr2.start(QtCore.QThread.LowPriority) self.thr2.start(QtCore.QThread.LowPriority)
# ################################### # ###################################
# ### Variables for global usage #### # ### Variables for global usage ####
# ################################### # ###################################
@@ -1908,7 +1919,8 @@ class App(QtCore.QObject):
self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd'] self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din', self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp', 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
'mpf'] 'mpf'
]
self.svg_list = ['svg'] self.svg_list = ['svg']
self.dxf_list = ['dxf'] self.dxf_list = ['dxf']
self.pdf_list = ['pdf'] self.pdf_list = ['pdf']
@@ -2000,8 +2012,8 @@ class App(QtCore.QObject):
for option in self.defaults_form_fields: for option in self.defaults_form_fields:
try: try:
self.defaults[option] = self.defaults_form_fields[option].get_value() self.defaults[option] = self.defaults_form_fields[option].get_value()
except: except Exception as e:
pass log.debug("App.defaults_read_form() --> %s" % str(e))
def defaults_write_form(self, factor=None): def defaults_write_form(self, factor=None):
for option in self.defaults: for option in self.defaults:
@@ -2019,7 +2031,6 @@ class App(QtCore.QObject):
self.defaults_form_fields[field].set_value(self.defaults[field]) self.defaults_form_fields[field].set_value(self.defaults[field])
else: else:
self.defaults_form_fields[field].set_value(self.defaults[field] * factor) self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
except KeyError: except KeyError:
# self.log.debug("defaults_write_form(): No field for: %s" % option) # self.log.debug("defaults_write_form(): No field for: %s" % option)
# TODO: Rethink this? # TODO: Rethink this?
@@ -2055,7 +2066,6 @@ class App(QtCore.QObject):
self.calculator_tool = ToolCalculator(self) self.calculator_tool = ToolCalculator(self)
self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png')) self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
self.sub_tool = ToolSub(self) self.sub_tool = ToolSub(self)
self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert, self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert,
before=self.ui.menuedit_convert_sg2mg) before=self.ui.menuedit_convert_sg2mg)
@@ -2247,7 +2257,6 @@ class App(QtCore.QObject):
# do not update a geometry or excellon object unless it comes out of an editor # do not update a geometry or excellon object unless it comes out of an editor
if self.call_source != 'app': if self.call_source != 'app':
edited_obj = self.collection.get_active() edited_obj = self.collection.get_active()
obj_type = ""
if cleanup is None: if cleanup is None:
msgbox = QtWidgets.QMessageBox() msgbox = QtWidgets.QMessageBox()
@@ -2395,7 +2404,7 @@ class App(QtCore.QObject):
# TODO: This shouldn't be here. # TODO: This shouldn't be here.
class TclErrorException(Exception): class TclErrorException(Exception):
""" """
this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
""" """
pass pass
@@ -2406,6 +2415,9 @@ class App(QtCore.QObject):
:param msg: Message to display. :param msg: Message to display.
:param show: Opens the shell. :param show: Opens the shell.
:param error: Shows the message as an error. :param error: Shows the message as an error.
:param warning: Shows the message as an warning.
:param warning: Shows the message as an success.
:param selected: Indicate that something was selected on canvas
:return: None :return: None
""" """
if show: if show:
@@ -2440,14 +2452,15 @@ class App(QtCore.QObject):
def display_tcl_error(self, error, error_info=None): def display_tcl_error(self, error, error_info=None):
""" """
escape bracket [ with \ otherwise there is error Escape bracket [ with '\' otherwise there is error
"ERROR: missing close-bracket" instead of real error "ERROR: missing close-bracket" instead of real error
:param error: it may be text or exception :param error: it may be text or exception
:param error_info: Some informations about the error
:return: None :return: None
""" """
if isinstance(error, Exception): if isinstance(error, Exception):
exc_type, exc_value, exc_traceback = error_info exc_type, exc_value, exc_traceback = error_info
if not isinstance(error, self.TclErrorException): if not isinstance(error, self.TclErrorException):
show_trace = 1 show_trace = 1
@@ -2459,22 +2472,19 @@ class App(QtCore.QObject):
trc_formated = [] trc_formated = []
for a in reversed(trc): for a in reversed(trc):
trc_formated.append(a.replace(" ", " > ").replace("\n", "")) trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
text = "%s\nPython traceback: %s\n%s" % (exc_value, text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
exc_type,
"\n".join(trc_formated))
else: else:
text = "%s" % error text = "%s" % error
else: else:
text = error text = error
text = text.replace('[', '\\[').replace('"', '\\"') text = text.replace('[', '\\[').replace('"', '\\"')
self.tcl.eval('return -code error "%s"' % text) self.tcl.eval('return -code error "%s"' % text)
def raise_tcl_error(self, text): def raise_tcl_error(self, text):
""" """
this method pass exception from python into TCL as error, so we get stacktrace and reason This method pass exception from python into TCL as error, so we get stacktrace and reason
:param text: text of error :param text: text of error
:return: raise exception :return: raise exception
""" """
@@ -2495,8 +2505,7 @@ class App(QtCore.QObject):
result = self.exec_command_test(text, False) result = self.exec_command_test(text, False)
#MS: added this method call so the geometry is updated once the TCL # MS: added this method call so the geometry is updated once the TCL command is executed
#command is executed
self.plot_all() self.plot_all()
return result return result
@@ -2579,7 +2588,7 @@ class App(QtCore.QObject):
:return: None :return: None
""" """
# Type of message in brackets at the begining of the message. # Type of message in brackets at the beginning of the message.
match = re.search("\[([^\]]+)\](.*)", msg) match = re.search("\[([^\]]+)\](.*)", msg)
if match: if match:
level = match.group(1) level = match.group(1)
@@ -2708,9 +2717,11 @@ class App(QtCore.QObject):
filter = "Config File (*.FlatConfig);;All Files (*.*)" filter = "Config File (*.FlatConfig);;All Files (*.*)"
try: try:
filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
directory=self.data_path, filter=filter) directory=self.data_path,
filter=filter)
except TypeError: except TypeError:
filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter) filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
filter=filter)
filename = str(filename) filename = str(filename)
@@ -2741,14 +2752,18 @@ class App(QtCore.QObject):
self.report_usage("on_export_preferences") self.report_usage("on_export_preferences")
App.log.debug("on_export_preferences()") App.log.debug("on_export_preferences()")
defaults_file_content = None
filter = "Config File (*.FlatConfig);;All Files (*.*)" filter = "Config File (*.FlatConfig);;All Files (*.*)"
try: try:
filename, _f = QtWidgets.QFileDialog.getSaveFileName( filename, _f = QtWidgets.QFileDialog.getSaveFileName(
caption=_("Export FlatCAM Preferences"), caption=_("Export FlatCAM Preferences"),
directory=self.data_path + '/preferences_' + self.date, filter=filter directory=self.data_path + '/preferences_' + self.date,
filter=filter
) )
except TypeError: except TypeError:
filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter) filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
filter=filter)
filename = str(filename) filename = str(filename)
defaults_from_file = {} defaults_from_file = {}
@@ -2845,16 +2860,10 @@ class App(QtCore.QObject):
self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.')) self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
return return
#try:
json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True) json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
# except:
# App.log.error("Failed to write to recent items file.")
# self.inform.emit('ERROR: Failed to write to recent items file.')
# f.close()
f.close() f.close()
# Re-buid the recent items menu # Re-build the recent items menu
self.setup_recent_items() self.setup_recent_items()
def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True): def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
@@ -2868,14 +2877,12 @@ class App(QtCore.QObject):
when appending it to the collection. There is no need to handle when appending it to the collection. There is no need to handle
name conflicts here. name conflicts here.
:param kind: The kind of object to create. One of 'gerber', :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
'excellon', 'cncjob' and 'geometry'.
:type kind: str :type kind: str
:param name: Name for the object. :param name: Name for the object.
:type name: str :type name: str
:param initialize: Function to run after creation of the object :param initialize: Function to run after creation of the object but before it is attached to the application.
but before it is attached to the application. The function is The function is called with 2 parameters: the new object and the App instance.
called with 2 parameters: the new object and the App instance.
:type initialize: function :type initialize: function
:return: None :return: None
:rtype: None :rtype: None

View File

@@ -13,6 +13,7 @@ CAD program, and create G-Code for Isolation routing.
- fixed bug in Gerber editor FCDisk and FCSemiDisc that the resulting geometry was not stored into the '0' aperture where all the solids are stored - fixed bug in Gerber editor FCDisk and FCSemiDisc that the resulting geometry was not stored into the '0' aperture where all the solids are stored
- fixed minor issue in Gerber Editor where apertures were included in the saved object even if there was no geometric data for that aperture - fixed minor issue in Gerber Editor where apertures were included in the saved object even if there was no geometric data for that aperture
- some PEP8 cleanup in FlatCAMApp.py
22.05.2019 22.05.2019