FlatCAMCNCJob.py 52 KB

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