FlatCAMCNCJob.py 53 KB

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