FlatCAMCNCJob.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from copy import deepcopy
  12. from io import StringIO
  13. from datetime import datetime
  14. from appEditors.AppTextEditor import AppTextEditor
  15. from appObjects.FlatCAMObj import *
  16. from camlib import CNCjob
  17. import os
  18. import sys
  19. import math
  20. import gettext
  21. import appTranslation as fcTranslate
  22. import builtins
  23. fcTranslate.apply_language('strings')
  24. if '_' not in builtins.__dict__:
  25. _ = gettext.gettext
  26. class CNCJobObject(FlatCAMObj, CNCjob):
  27. """
  28. Represents G-Code.
  29. """
  30. optionChanged = QtCore.pyqtSignal(str)
  31. ui_type = CNCObjectUI
  32. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  33. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  34. spindlespeed=None):
  35. log.debug("Creating CNCJob object...")
  36. self.decimals = self.app.decimals
  37. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  38. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  39. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  40. FlatCAMObj.__init__(self, name)
  41. self.kind = "cncjob"
  42. self.options.update({
  43. "plot": True,
  44. "tooldia": 0.03937, # 0.4mm in inches
  45. "append": "",
  46. "prepend": "",
  47. "dwell": False,
  48. "dwelltime": 1,
  49. "type": 'Geometry',
  50. "toolchange_macro": '',
  51. "toolchange_macro_enable": False
  52. })
  53. '''
  54. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  55. diameter of the tools and the value is another dict that will hold the data under the following form:
  56. {tooldia: {
  57. 'tooluid': 1,
  58. 'offset': 'Path',
  59. 'type_item': 'Rough',
  60. 'tool_type': 'C1',
  61. 'data': {} # a dict to hold the parameters
  62. 'gcode': "" # a string with the actual GCODE
  63. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  64. (cut or move)
  65. 'solid_geometry': []
  66. },
  67. ...
  68. }
  69. It is populated in the GeometryObject.mtool_gen_cncjob()
  70. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  71. '''
  72. self.cnc_tools = {}
  73. '''
  74. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  75. diameter of the tools and the value is another dict that will hold the data under the following form:
  76. {tooldia: {
  77. 'tool': int,
  78. 'nr_drills': int,
  79. 'nr_slots': int,
  80. 'offset': float,
  81. 'data': {}, a dict to hold the parameters
  82. 'gcode': "", a string with the actual GCODE
  83. 'gcode_parsed': [], list of dicts holding the CNCJob geometry and
  84. type of geometry (cut or move)
  85. 'solid_geometry': [],
  86. },
  87. ...
  88. }
  89. It is populated in the ExcellonObject.on_create_cncjob_click() but actually
  90. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  91. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  92. '''
  93. self.exc_cnc_tools = {}
  94. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  95. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  96. self.special_group = None
  97. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  98. # (like the one in the TCL Command), False
  99. self.multitool = False
  100. # determine if the GCode was generated out of a Excellon object or a Geometry object
  101. self.origin_kind = None
  102. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  103. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  104. self.g_x_re = re.compile(gcodex_re_string)
  105. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  106. self.g_y_re = re.compile(gcodey_re_string)
  107. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  108. self.g_z_re = re.compile(gcodez_re_string)
  109. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  110. self.g_f_re = re.compile(gcodef_re_string)
  111. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  112. self.g_t_re = re.compile(gcodet_re_string)
  113. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  114. self.g_nr_re = re.compile(gcodenr_re_string)
  115. # Attributes to be included in serialization
  116. # Always append to it because it carries contents
  117. # from predecessors.
  118. self.ser_attrs += ['options', 'kind', 'origin_kind', 'cnc_tools', 'exc_cnc_tools', 'multitool']
  119. if self.app.is_legacy is False:
  120. self.text_col = self.app.plotcanvas.new_text_collection()
  121. self.text_col.enabled = True
  122. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  123. self.gcode_editor_tab = None
  124. self.source_file = ''
  125. self.units_found = self.app.defaults['units']
  126. def build_ui(self):
  127. self.ui_disconnect()
  128. FlatCAMObj.build_ui(self)
  129. self.units = self.app.defaults['units'].upper()
  130. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  131. self.ui.cnc_tools_table.hide()
  132. if self.cnc_tools:
  133. self.ui.cnc_tools_table.show()
  134. self.build_cnc_tools_table()
  135. self.ui.exc_cnc_tools_table.hide()
  136. if self.exc_cnc_tools:
  137. self.ui.exc_cnc_tools_table.show()
  138. self.build_excellon_cnc_tools()
  139. #
  140. self.ui_connect()
  141. def build_cnc_tools_table(self):
  142. tool_idx = 0
  143. n = len(self.cnc_tools)
  144. self.ui.cnc_tools_table.setRowCount(n)
  145. for dia_key, dia_value in self.cnc_tools.items():
  146. tool_idx += 1
  147. row_no = tool_idx - 1
  148. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  149. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  150. self.ui.cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  151. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  152. # There are no tool bits in MM with more than 2 decimals diameter.
  153. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  154. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  155. offset_txt = list(str(dia_value['offset']))
  156. offset_txt[0] = offset_txt[0].upper()
  157. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  158. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  159. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  160. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  161. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  162. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  163. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  164. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  165. # hack so the checkbox stay centered in the table cell
  166. # used this:
  167. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  168. # plot_item = QtWidgets.QWidget()
  169. # checkbox = FCCheckBox()
  170. # checkbox.setCheckState(QtCore.Qt.Checked)
  171. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  172. # qhboxlayout.addWidget(checkbox)
  173. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  174. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  175. plot_item = FCCheckBox()
  176. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  177. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  178. if self.ui.plot_cb.isChecked():
  179. plot_item.setChecked(True)
  180. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  181. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  182. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  183. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  184. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  185. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  186. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  187. # make the diameter column editable
  188. # for row in range(tool_idx):
  189. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  190. # QtCore.Qt.ItemIsEnabled)
  191. for row in range(tool_idx):
  192. self.ui.cnc_tools_table.item(row, 0).setFlags(
  193. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  194. self.ui.cnc_tools_table.resizeColumnsToContents()
  195. self.ui.cnc_tools_table.resizeRowsToContents()
  196. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  197. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  198. vertical_header.hide()
  199. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  200. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  201. horizontal_header.setMinimumSectionSize(10)
  202. horizontal_header.setDefaultSectionSize(70)
  203. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  204. horizontal_header.resizeSection(0, 20)
  205. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  206. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  207. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  208. horizontal_header.resizeSection(4, 40)
  209. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  210. horizontal_header.resizeSection(4, 17)
  211. # horizontal_header.setStretchLastSection(True)
  212. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  213. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  214. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  215. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  216. # self.ui.geo_tools_table.setSortingEnabled(True)
  217. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  218. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  219. def build_excellon_cnc_tools(self):
  220. tool_idx = 0
  221. n = len(self.exc_cnc_tools)
  222. self.ui.exc_cnc_tools_table.setRowCount(n)
  223. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  224. tool_idx += 1
  225. row_no = tool_idx - 1
  226. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  227. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  228. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  229. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  230. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset']) + self.z_cut))
  231. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  232. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  233. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  234. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  235. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  236. # hack so the checkbox stay centered in the table cell
  237. # used this:
  238. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  239. # plot_item = QtWidgets.QWidget()
  240. # checkbox = FCCheckBox()
  241. # checkbox.setCheckState(QtCore.Qt.Checked)
  242. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  243. # qhboxlayout.addWidget(checkbox)
  244. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  245. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  246. plot_item = FCCheckBox()
  247. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  248. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  249. if self.ui.plot_cb.isChecked():
  250. plot_item.setChecked(True)
  251. self.ui.exc_cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  252. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  253. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  254. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  255. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  256. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  257. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  258. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  259. for row in range(tool_idx):
  260. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  261. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  262. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  263. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  264. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  265. vertical_header.hide()
  266. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  267. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  268. horizontal_header.setMinimumSectionSize(10)
  269. horizontal_header.setDefaultSectionSize(70)
  270. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  271. horizontal_header.resizeSection(0, 20)
  272. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  273. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  274. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  275. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  276. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  277. # horizontal_header.setStretchLastSection(True)
  278. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  279. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  280. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  281. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  282. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  283. def set_ui(self, ui):
  284. FlatCAMObj.set_ui(self, ui)
  285. log.debug("FlatCAMCNCJob.set_ui()")
  286. assert isinstance(self.ui, CNCObjectUI), \
  287. "Expected a CNCObjectUI, got %s" % type(self.ui)
  288. self.units = self.app.defaults['units'].upper()
  289. self.units_found = self.app.defaults['units']
  290. # this signal has to be connected to it's slot before the defaults are populated
  291. # the decision done in the slot has to override the default value set below
  292. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  293. self.form_fields.update({
  294. "plot": self.ui.plot_cb,
  295. "tooldia": self.ui.tooldia_entry,
  296. "append": self.ui.append_text,
  297. "prepend": self.ui.prepend_text,
  298. "toolchange_macro": self.ui.toolchange_text,
  299. "toolchange_macro_enable": self.ui.toolchange_cb
  300. })
  301. # Fill form fields only on object create
  302. self.to_form()
  303. # this means that the object that created this CNCJob was an Excellon or Geometry
  304. try:
  305. if self.travel_distance:
  306. self.ui.t_distance_label.show()
  307. self.ui.t_distance_entry.setVisible(True)
  308. self.ui.t_distance_entry.setDisabled(True)
  309. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  310. self.ui.units_label.setText(str(self.units).lower())
  311. self.ui.units_label.setDisabled(True)
  312. self.ui.t_time_label.show()
  313. self.ui.t_time_entry.setVisible(True)
  314. self.ui.t_time_entry.setDisabled(True)
  315. # if time is more than 1 then we have minutes, else we have seconds
  316. if self.routing_time > 1:
  317. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  318. self.ui.units_time_label.setText('min')
  319. else:
  320. time_r = self.routing_time * 60
  321. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  322. self.ui.units_time_label.setText('sec')
  323. self.ui.units_time_label.setDisabled(True)
  324. except AttributeError:
  325. pass
  326. if self.multitool is False:
  327. self.ui.tooldia_entry.show()
  328. self.ui.updateplot_button.show()
  329. else:
  330. self.ui.tooldia_entry.hide()
  331. self.ui.updateplot_button.hide()
  332. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  333. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  334. try:
  335. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  336. except (TypeError, AttributeError):
  337. pass
  338. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  339. # set if to display text annotations
  340. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  341. # Show/Hide Advanced Options
  342. if self.app.defaults["global_app_level"] == 'b':
  343. self.ui.level.setText(_(
  344. '<span style="color:green;"><b>Basic</b></span>'
  345. ))
  346. self.ui.cnc_frame.hide()
  347. else:
  348. self.ui.level.setText(_(
  349. '<span style="color:red;"><b>Advanced</b></span>'
  350. ))
  351. self.ui.cnc_frame.show()
  352. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  353. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  354. self.ui.editor_button.clicked.connect(self.on_edit_code_click)
  355. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  356. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  357. def on_cnc_custom_parameters(self, signal_text):
  358. if signal_text == 'Parameters':
  359. return
  360. else:
  361. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  362. def ui_connect(self):
  363. for row in range(self.ui.cnc_tools_table.rowCount()):
  364. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  365. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  366. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  367. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  368. def ui_disconnect(self):
  369. for row in range(self.ui.cnc_tools_table.rowCount()):
  370. try:
  371. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  372. except (TypeError, AttributeError):
  373. pass
  374. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  375. try:
  376. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  377. except (TypeError, AttributeError):
  378. pass
  379. try:
  380. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  381. except (TypeError, AttributeError):
  382. pass
  383. def on_updateplot_button_click(self, *args):
  384. """
  385. Callback for the "Updata Plot" button. Reads the form for updates
  386. and plots the object.
  387. """
  388. self.read_form()
  389. self.on_plot_kind_change()
  390. def on_plot_kind_change(self):
  391. kind = self.ui.cncplot_method_combo.get_value()
  392. def worker_task():
  393. with self.app.proc_container.new(_("Plotting...")):
  394. self.plot(kind=kind)
  395. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  396. def on_exportgcode_button_click(self):
  397. """
  398. Handler activated by a button clicked when exporting GCode.
  399. :param args:
  400. :return:
  401. """
  402. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  403. self.read_form()
  404. name = self.app.collection.get_active().options['name']
  405. save_gcode = False
  406. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  407. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  408. elif 'hpgl' in self.pp_geometry_name:
  409. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  410. else:
  411. save_gcode = True
  412. _filter_ = self.app.defaults['cncjob_save_filters']
  413. try:
  414. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  415. filename, _f = FCFileSaveDialog.get_saved_filename(
  416. caption=_("Export Code ..."),
  417. directory=dir_file_to_save,
  418. ext_filter=_filter_
  419. )
  420. except TypeError:
  421. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  422. self.export_gcode_handler(filename, is_gcode=save_gcode)
  423. def export_gcode_handler(self, filename, is_gcode=True):
  424. filename = str(filename)
  425. if filename == '':
  426. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  427. return
  428. else:
  429. if is_gcode is True:
  430. used_extension = filename.rpartition('.')[2]
  431. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  432. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  433. self.ui.name_entry.set_value(new_name)
  434. self.on_name_activate(silent=True)
  435. try:
  436. preamble = str(self.ui.prepend_text.get_value())
  437. postamble = str(self.ui.append_text.get_value())
  438. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  439. except Exception as err:
  440. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  441. gc = self.export_gcode(filename)
  442. if gc == 'fail':
  443. return
  444. if self.app.defaults["global_open_style"] is False:
  445. self.app.file_opened.emit("gcode", filename)
  446. self.app.file_saved.emit("gcode", filename)
  447. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  448. def on_edit_code_click(self, *args):
  449. """
  450. Handler activated by a button clicked when editing GCode.
  451. :param args:
  452. :return:
  453. """
  454. self.app.proc_container.view.set_busy(_("Loading..."))
  455. preamble = str(self.ui.prepend_text.get_value())
  456. postamble = str(self.ui.append_text.get_value())
  457. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  458. if gco == 'fail':
  459. return
  460. else:
  461. self.app.gcode_edited = gco
  462. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  463. # add the tab if it was closed
  464. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Editor"))
  465. self.gcode_editor_tab.setObjectName('code_editor_tab')
  466. # delete the absolute and relative position and messages in the infobar
  467. self.app.ui.position_label.setText("")
  468. self.app.ui.rel_position_label.setText("")
  469. self.gcode_editor_tab.code_editor.completer_enable = False
  470. self.gcode_editor_tab.buttonRun.hide()
  471. # Switch plot_area to CNCJob tab
  472. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  473. self.gcode_editor_tab.t_frame.hide()
  474. # then append the text from GCode to the text editor
  475. try:
  476. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  477. except Exception as e:
  478. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  479. self.app.inform.emit('[ERROR] %s %s' % ('FlatCAMCNNJob.on_edit_code_click() -->', str(e)))
  480. return
  481. self.gcode_editor_tab.t_frame.show()
  482. self.app.proc_container.view.set_idle()
  483. self.gcode_editor_tab.buttonSave.clicked.connect(self.on_update_source_file)
  484. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  485. def on_update_source_file(self):
  486. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  487. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  488. """
  489. Will create a header to be added to all GCode files generated by FlatCAM
  490. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  491. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  492. :return: A string with a GCode header
  493. """
  494. log.debug("FlatCAMCNCJob.gcode_header()")
  495. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  496. marlin = False
  497. hpgl = False
  498. probe_pp = False
  499. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  500. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  501. try:
  502. for key in self.cnc_tools:
  503. ppg = self.cnc_tools[key]['data']['ppname_g']
  504. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  505. marlin = True
  506. break
  507. if ppg == 'hpgl':
  508. hpgl = True
  509. break
  510. if "toolchange_probe" in ppg.lower():
  511. probe_pp = True
  512. break
  513. except KeyError:
  514. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  515. pass
  516. try:
  517. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  518. marlin = True
  519. except KeyError:
  520. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  521. pass
  522. try:
  523. if "toolchange_probe" in self.options['ppname_e'].lower():
  524. probe_pp = True
  525. except KeyError:
  526. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  527. pass
  528. if marlin is True:
  529. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  530. (str(self.app.version), str(self.app.version_date)) + '\n'
  531. gcode += ';Name: ' + str(self.options['name']) + '\n'
  532. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  533. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  534. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  535. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  536. gcode += ';Created on ' + time_str + '\n' + '\n'
  537. elif hpgl is True:
  538. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  539. (str(self.app.version), str(self.app.version_date)) + '";\n'
  540. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  541. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  542. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  543. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  544. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  545. gcode += 'CO "Created on ' + time_str + '";\n'
  546. elif probe_pp is True:
  547. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  548. (str(self.app.version), str(self.app.version_date)) + '\n'
  549. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  550. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  551. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  552. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  553. 'Then zero the Z axis.)\n' + '\n'
  554. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  555. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  556. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  557. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  558. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  559. gcode += '(Created on ' + time_str + ')\n' + '\n'
  560. else:
  561. gcode = '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  562. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  563. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  564. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  565. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  566. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  567. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  568. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  569. return gcode
  570. @staticmethod
  571. def gcode_footer(end_command=None):
  572. """
  573. Will add the M02 to the end of GCode, if requested.
  574. :param end_command: 'M02' or 'M30' - String
  575. :return:
  576. """
  577. if end_command:
  578. return end_command
  579. else:
  580. return 'M02'
  581. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  582. """
  583. This will save the GCode from the Gcode object to a file on the OS filesystem
  584. :param filename: filename for the GCode file
  585. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  586. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  587. :param to_file: if False then no actual file is saved but the app will know that a file was created
  588. :param from_tcl: True if run from Tcl Shell
  589. :return: None
  590. """
  591. # gcode = ''
  592. # roland = False
  593. # hpgl = False
  594. # isel_icp = False
  595. include_header = True
  596. if preamble == '':
  597. preamble = self.app.defaults["cncjob_prepend"]
  598. if postamble == '':
  599. preamble = self.app.defaults["cncjob_append"]
  600. try:
  601. if self.special_group:
  602. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  603. (_("This CNCJob object can't be processed because it is a"),
  604. str(self.special_group),
  605. _("CNCJob object")))
  606. return 'fail'
  607. except AttributeError:
  608. pass
  609. # if this dict is not empty then the object is a Geometry object
  610. if self.cnc_tools:
  611. first_key = next(iter(self.cnc_tools))
  612. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  613. # if this dict is not empty then the object is an Excellon object
  614. if self.exc_cnc_tools:
  615. first_key = next(iter(self.exc_cnc_tools))
  616. include_header = self.app.preprocessors[
  617. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  618. ].include_header
  619. gcode = ''
  620. if include_header is False:
  621. g = preamble
  622. # detect if using multi-tool and make the Gcode summation correctly for each case
  623. if self.multitool is True:
  624. for tooluid_key in self.cnc_tools:
  625. for key, value in self.cnc_tools[tooluid_key].items():
  626. if key == 'gcode':
  627. gcode += value
  628. break
  629. else:
  630. gcode += self.gcode
  631. g = g + gcode + postamble
  632. else:
  633. # search for the GCode beginning which is usually a G20 or G21
  634. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  635. # g_idx = gcode.rfind('G20')
  636. #
  637. # # if it did not find 'G20' then search for 'G21'
  638. # if g_idx == -1:
  639. # g_idx = gcode.rfind('G21')
  640. #
  641. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  642. # if g_idx == -1:
  643. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  644. # return
  645. # detect if using multi-tool and make the Gcode summation correctly for each case
  646. if self.multitool is True:
  647. if self.origin_kind == 'excellon':
  648. for tooluid_key in self.exc_cnc_tools:
  649. for key, value in self.exc_cnc_tools[tooluid_key].items():
  650. if key == 'gcode' and value:
  651. gcode += value
  652. break
  653. else:
  654. for tooluid_key in self.cnc_tools:
  655. for key, value in self.cnc_tools[tooluid_key].items():
  656. if key == 'gcode' and value:
  657. gcode += value
  658. break
  659. else:
  660. gcode += self.gcode
  661. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  662. # detect if using a HPGL preprocessor
  663. hpgl = False
  664. if self.cnc_tools:
  665. for key in self.cnc_tools:
  666. if 'ppname_g' in self.cnc_tools[key]['data']:
  667. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  668. hpgl = True
  669. break
  670. elif self.exc_cnc_tools:
  671. for key in self.cnc_tools:
  672. if 'ppname_e' in self.cnc_tools[key]['data']:
  673. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  674. hpgl = True
  675. break
  676. if hpgl:
  677. processed_gcode = ''
  678. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  679. for gline in gcode.splitlines():
  680. match = pa_re.search(gline)
  681. if match:
  682. x_int = int(float(match.group(1)))
  683. y_int = int(float(match.group(2)))
  684. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  685. processed_gcode += new_line
  686. else:
  687. processed_gcode += gline + '\n'
  688. gcode = processed_gcode
  689. g = self.gcode_header() + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  690. else:
  691. try:
  692. g_idx = gcode.index('G94')
  693. g = self.gcode_header() + gcode[:g_idx + 3] + '\n\n' + preamble + '\n' + \
  694. gcode[(g_idx + 3):] + postamble + end_gcode
  695. except ValueError:
  696. self.app.inform.emit('[ERROR_NOTCL] %s' %
  697. _("G-code does not have a G94 code and we will not include the code in the "
  698. "'Prepend to GCode' text box"))
  699. g = self.gcode_header() + '\n' + gcode + postamble + end_gcode
  700. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  701. if self.ui.toolchange_cb.get_value() is True:
  702. # match = self.re_toolchange.search(g)
  703. if 'M6' in g:
  704. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  705. if m6_code is None or m6_code == '':
  706. self.app.inform.emit(
  707. '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  708. )
  709. return 'fail'
  710. g = g.replace('M6', m6_code)
  711. self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  712. lines = StringIO(g)
  713. # Write
  714. if filename is not None:
  715. try:
  716. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  717. if force_windows_line_endings and sys.platform != 'win32':
  718. with open(filename, 'w', newline='\r\n') as f:
  719. for line in lines:
  720. f.write(line)
  721. else:
  722. with open(filename, 'w') as f:
  723. for line in lines:
  724. f.write(line)
  725. except FileNotFoundError:
  726. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  727. return
  728. except PermissionError:
  729. self.app.inform.emit(
  730. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  731. "Most likely another app is holding the file open and not accessible.")
  732. )
  733. return 'fail'
  734. elif to_file is False:
  735. # Just for adding it to the recent files list.
  736. if self.app.defaults["global_open_style"] is False:
  737. self.app.file_opened.emit("cncjob", filename)
  738. self.app.file_saved.emit("cncjob", filename)
  739. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  740. else:
  741. return lines
  742. def on_toolchange_custom_clicked(self, signal):
  743. """
  744. Handler for clicking toolchange custom.
  745. :param signal:
  746. :return:
  747. """
  748. try:
  749. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  750. if self.ui.toolchange_cb.get_value():
  751. self.ui.toolchange_cb.set_value(False)
  752. self.app.inform.emit('[WARNING_NOTCL] %s' %
  753. _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  754. except KeyError:
  755. try:
  756. for key in self.cnc_tools:
  757. ppg = self.cnc_tools[key]['data']['ppname_g']
  758. if 'toolchange_custom' not in str(ppg).lower():
  759. if self.ui.toolchange_cb.get_value():
  760. self.ui.toolchange_cb.set_value(False)
  761. self.app.inform.emit('[WARNING_NOTCL] %s' %
  762. _("The used preprocessor file has to have in it's name: "
  763. "'toolchange_custom'"))
  764. except KeyError:
  765. self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  766. def get_gcode(self, preamble='', postamble=''):
  767. """
  768. We need this to be able to get_gcode separately for shell command export_gcode
  769. :param preamble: Extra GCode added to the beginning of the GCode
  770. :param postamble: Extra GCode added at the end of the GCode
  771. :return: The modified GCode
  772. """
  773. return preamble + '\n' + self.gcode + "\n" + postamble
  774. def get_svg(self):
  775. # we need this to be able get_svg separately for shell command export_svg
  776. pass
  777. def on_plot_cb_click(self, *args):
  778. """
  779. Handler for clicking on the Plot checkbox.
  780. :param args:
  781. :return:
  782. """
  783. if self.muted_ui:
  784. return
  785. kind = self.ui.cncplot_method_combo.get_value()
  786. self.plot(kind=kind)
  787. self.read_form_item('plot')
  788. self.ui_disconnect()
  789. cb_flag = self.ui.plot_cb.isChecked()
  790. for row in range(self.ui.cnc_tools_table.rowCount()):
  791. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  792. if cb_flag:
  793. table_cb.setChecked(True)
  794. else:
  795. table_cb.setChecked(False)
  796. self.ui_connect()
  797. def on_plot_cb_click_table(self):
  798. """
  799. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  800. tool/aperture found on that row.
  801. :return:
  802. """
  803. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  804. self.ui_disconnect()
  805. # cw = self.sender()
  806. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  807. # cw_row = cw_index.row()
  808. kind = self.ui.cncplot_method_combo.get_value()
  809. self.shapes.clear(update=True)
  810. if self.origin_kind == "excellon":
  811. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  812. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  813. for tooluid_key in self.exc_cnc_tools:
  814. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  815. if row_dia == tooldia:
  816. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  817. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  818. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  819. else:
  820. for tooluid_key in self.cnc_tools:
  821. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  822. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  823. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  824. for r in range(self.ui.cnc_tools_table.rowCount()):
  825. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  826. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  827. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  828. self.shapes.redraw()
  829. # make sure that the general plot is disabled if one of the row plot's are disabled and
  830. # if all the row plot's are enabled also enable the general plot checkbox
  831. cb_cnt = 0
  832. total_row = self.ui.cnc_tools_table.rowCount()
  833. for row in range(total_row):
  834. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  835. cb_cnt += 1
  836. else:
  837. cb_cnt -= 1
  838. if cb_cnt < total_row:
  839. self.ui.plot_cb.setChecked(False)
  840. else:
  841. self.ui.plot_cb.setChecked(True)
  842. self.ui_connect()
  843. def plot(self, visible=None, kind='all'):
  844. """
  845. # Does all the required setup and returns False
  846. # if the 'ptint' option is set to False.
  847. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  848. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  849. :return: None
  850. """
  851. if not FlatCAMObj.plot(self):
  852. return
  853. visible = visible if visible else self.options['plot']
  854. if self.app.is_legacy is False:
  855. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  856. self.text_col.enabled = True
  857. else:
  858. self.text_col.enabled = False
  859. self.annotation.redraw()
  860. try:
  861. if self.multitool is False: # single tool usage
  862. try:
  863. dia_plot = float(self.options["tooldia"])
  864. except ValueError:
  865. # we may have a tuple with only one element and a comma
  866. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  867. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  868. else:
  869. # I do this so the travel lines thickness will reflect the tool diameter
  870. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  871. # don't know the origin
  872. if self.origin_kind == "excellon":
  873. if self.exc_cnc_tools:
  874. for tooldia_key in self.exc_cnc_tools:
  875. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  876. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  877. if not gcode_parsed:
  878. continue
  879. # gcode_parsed = self.gcode_parsed
  880. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  881. else:
  882. # multiple tools usage
  883. if self.cnc_tools:
  884. for tooluid_key in self.cnc_tools:
  885. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  886. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  887. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  888. self.shapes.redraw()
  889. except (ObjectDeleted, AttributeError):
  890. self.shapes.clear(update=True)
  891. if self.app.is_legacy is False:
  892. self.annotation.clear(update=True)
  893. def on_annotation_change(self):
  894. """
  895. Handler for toggling the annotation display by clicking a checkbox.
  896. :return:
  897. """
  898. if self.app.is_legacy is False:
  899. if self.ui.annotation_cb.get_value():
  900. self.text_col.enabled = True
  901. else:
  902. self.text_col.enabled = False
  903. # kind = self.ui.cncplot_method_combo.get_value()
  904. # self.plot(kind=kind)
  905. self.annotation.redraw()
  906. else:
  907. kind = self.ui.cncplot_method_combo.get_value()
  908. self.plot(kind=kind)
  909. def convert_units(self, units):
  910. """
  911. Units conversion used by the CNCJob objects.
  912. :param units: Can be "MM" or "IN"
  913. :return:
  914. """
  915. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  916. factor = CNCjob.convert_units(self, units)
  917. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  918. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  919. 'endz', 'toolchangez']
  920. temp_tools_dict = {}
  921. tool_dia_copy = {}
  922. data_copy = {}
  923. for tooluid_key, tooluid_value in self.cnc_tools.items():
  924. for dia_key, dia_value in tooluid_value.items():
  925. if dia_key == 'tooldia':
  926. dia_value *= factor
  927. dia_value = float('%.*f' % (self.decimals, dia_value))
  928. tool_dia_copy[dia_key] = dia_value
  929. if dia_key == 'offset':
  930. tool_dia_copy[dia_key] = dia_value
  931. if dia_key == 'offset_value':
  932. dia_value *= factor
  933. tool_dia_copy[dia_key] = dia_value
  934. if dia_key == 'type':
  935. tool_dia_copy[dia_key] = dia_value
  936. if dia_key == 'tool_type':
  937. tool_dia_copy[dia_key] = dia_value
  938. if dia_key == 'data':
  939. for data_key, data_value in dia_value.items():
  940. # convert the form fields that are convertible
  941. for param in param_list:
  942. if data_key == param and data_value is not None:
  943. data_copy[data_key] = data_value * factor
  944. # copy the other dict entries that are not convertible
  945. if data_key not in param_list:
  946. data_copy[data_key] = data_value
  947. tool_dia_copy[dia_key] = deepcopy(data_copy)
  948. data_copy.clear()
  949. if dia_key == 'gcode':
  950. tool_dia_copy[dia_key] = dia_value
  951. if dia_key == 'gcode_parsed':
  952. tool_dia_copy[dia_key] = dia_value
  953. if dia_key == 'solid_geometry':
  954. tool_dia_copy[dia_key] = dia_value
  955. # if dia_key == 'solid_geometry':
  956. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  957. # if dia_key == 'gcode_parsed':
  958. # for g in dia_value:
  959. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  960. #
  961. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  962. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  963. temp_tools_dict.update({
  964. tooluid_key: deepcopy(tool_dia_copy)
  965. })
  966. tool_dia_copy.clear()
  967. self.cnc_tools.clear()
  968. self.cnc_tools = deepcopy(temp_tools_dict)