FlatCAMCNCJob.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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.FlatCAMTextEditor import TextEditor
  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': {} # 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 below
  292. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  293. self.form_fields.update({
  294. "plot": self.ui.plot_cb,
  295. "tooldia": self.ui.tooldia_entry,
  296. "append": self.ui.append_text,
  297. "prepend": self.ui.prepend_text,
  298. "toolchange_macro": self.ui.toolchange_text,
  299. "toolchange_macro_enable": self.ui.toolchange_cb
  300. })
  301. # Fill form fields only on object create
  302. self.to_form()
  303. # this means that the object that created this CNCJob was an Excellon or Geometry
  304. try:
  305. if self.travel_distance:
  306. self.ui.t_distance_label.show()
  307. self.ui.t_distance_entry.setVisible(True)
  308. self.ui.t_distance_entry.setDisabled(True)
  309. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  310. self.ui.units_label.setText(str(self.units).lower())
  311. self.ui.units_label.setDisabled(True)
  312. self.ui.t_time_label.show()
  313. self.ui.t_time_entry.setVisible(True)
  314. self.ui.t_time_entry.setDisabled(True)
  315. # if time is more than 1 then we have minutes, else we have seconds
  316. if self.routing_time > 1:
  317. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  318. self.ui.units_time_label.setText('min')
  319. else:
  320. time_r = self.routing_time * 60
  321. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  322. self.ui.units_time_label.setText('sec')
  323. self.ui.units_time_label.setDisabled(True)
  324. except AttributeError:
  325. pass
  326. if self.multitool is False:
  327. self.ui.tooldia_entry.show()
  328. self.ui.updateplot_button.show()
  329. else:
  330. self.ui.tooldia_entry.hide()
  331. self.ui.updateplot_button.hide()
  332. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  333. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  334. try:
  335. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  336. except (TypeError, AttributeError):
  337. pass
  338. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  339. # set if to display text annotations
  340. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  341. # Show/Hide Advanced Options
  342. if self.app.defaults["global_app_level"] == 'b':
  343. self.ui.level.setText(_(
  344. '<span style="color:green;"><b>Basic</b></span>'
  345. ))
  346. self.ui.cnc_frame.hide()
  347. else:
  348. self.ui.level.setText(_(
  349. '<span style="color:red;"><b>Advanced</b></span>'
  350. ))
  351. self.ui.cnc_frame.show()
  352. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  353. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  354. self.ui.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.defaults.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 Code ..."),
  407. directory=dir_file_to_save,
  408. ext_filter=_filter_
  409. )
  410. except TypeError:
  411. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  412. filename = str(filename)
  413. if filename == '':
  414. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export 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' % (_("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, from_tcl=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. :param from_tcl: True if run from Tcl Shell
  580. :return: None
  581. """
  582. # gcode = ''
  583. # roland = False
  584. # hpgl = False
  585. # isel_icp = False
  586. include_header = True
  587. try:
  588. if self.special_group:
  589. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  590. (_("This CNCJob object can't be processed because it is a"),
  591. str(self.special_group),
  592. _("CNCJob object")))
  593. return 'fail'
  594. except AttributeError:
  595. pass
  596. # if this dict is not empty then the object is a Geometry object
  597. if self.cnc_tools:
  598. first_key = next(iter(self.cnc_tools))
  599. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  600. # if this dict is not empty then the object is an Excellon object
  601. if self.exc_cnc_tools:
  602. first_key = next(iter(self.exc_cnc_tools))
  603. include_header = self.app.preprocessors[self.exc_cnc_tools[first_key]['data']['ppname_e']].include_header
  604. # # detect if using Roland preprocessor
  605. # try:
  606. # for key in self.cnc_tools:
  607. # if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  608. # roland = True
  609. # break
  610. # except Exception:
  611. # try:
  612. # for key in self.cnc_tools:
  613. # if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  614. # roland = True
  615. # break
  616. # except Exception:
  617. # pass
  618. #
  619. # # detect if using HPGL preprocessor
  620. # try:
  621. # for key in self.cnc_tools:
  622. # if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  623. # hpgl = True
  624. # break
  625. # except Exception:
  626. # try:
  627. # for key in self.cnc_tools:
  628. # if self.cnc_tools[key]['data']['ppname_e'] == 'hpgl':
  629. # hpgl = True
  630. # break
  631. # except Exception:
  632. # pass
  633. #
  634. # # detect if using ISEL_ICP_CNC preprocessor
  635. # try:
  636. # for key in self.cnc_tools:
  637. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_g'].upper():
  638. # isel_icp = True
  639. # break
  640. # except Exception:
  641. # try:
  642. # for key in self.cnc_tools:
  643. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_e'].upper():
  644. # isel_icp = True
  645. # break
  646. # except Exception:
  647. # pass
  648. # do not add gcode_header when using the Roland preprocessor, add it for every other preprocessor
  649. # if roland is False and hpgl is False and isel_icp is False:
  650. # gcode = self.gcode_header()
  651. # do not add gcode_header when using the Roland, HPGL or ISEP_ICP_CNC preprocessor (or any other preprocessor
  652. # that has the include_header attribute set as False, add it for every other preprocessor
  653. # if include_header:
  654. # gcode = self.gcode_header()
  655. # else:
  656. # gcode = ''
  657. # # detect if using multi-tool and make the Gcode summation correctly for each case
  658. # if self.multitool is True:
  659. # for tooluid_key in self.cnc_tools:
  660. # for key, value in self.cnc_tools[tooluid_key].items():
  661. # if key == 'gcode':
  662. # gcode += value
  663. # break
  664. # else:
  665. # gcode += self.gcode
  666. # if roland is True:
  667. # g = preamble + gcode + postamble
  668. # elif hpgl is True:
  669. # g = self.gcode_header() + preamble + gcode + postamble
  670. # else:
  671. # # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  672. # g_idx = gcode.rfind('G20')
  673. #
  674. # # if it did not find 'G20' then search for 'G21'
  675. # if g_idx == -1:
  676. # g_idx = gcode.rfind('G21')
  677. #
  678. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  679. # # but only when the preprocessor is not ISEL_ICP who is allowed not to have the G20/G21 command
  680. # if g_idx == -1 and isel_icp is False:
  681. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  682. # return
  683. #
  684. # footer = self.app.defaults['cncjob_footer']
  685. # end_gcode = self.gcode_footer() if footer is True else ''
  686. # g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + end_gcode
  687. gcode = ''
  688. if include_header is False:
  689. g = preamble
  690. # detect if using multi-tool and make the Gcode summation correctly for each case
  691. if self.multitool is True:
  692. for tooluid_key in self.cnc_tools:
  693. for key, value in self.cnc_tools[tooluid_key].items():
  694. if key == 'gcode':
  695. gcode += value
  696. break
  697. else:
  698. gcode += self.gcode
  699. g = g + gcode + postamble
  700. else:
  701. # search for the GCode beginning which is usually a G20 or G21
  702. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  703. # g_idx = gcode.rfind('G20')
  704. #
  705. # # if it did not find 'G20' then search for 'G21'
  706. # if g_idx == -1:
  707. # g_idx = gcode.rfind('G21')
  708. #
  709. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  710. # if g_idx == -1:
  711. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  712. # return
  713. # detect if using multi-tool and make the Gcode summation correctly for each case
  714. if self.multitool is True:
  715. for tooluid_key in self.cnc_tools:
  716. for key, value in self.cnc_tools[tooluid_key].items():
  717. if key == 'gcode':
  718. gcode += value
  719. break
  720. else:
  721. gcode += self.gcode
  722. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  723. # detect if using a HPGL preprocessor
  724. hpgl = False
  725. if self.cnc_tools:
  726. for key in self.cnc_tools:
  727. if 'ppname_g' in self.cnc_tools[key]['data']:
  728. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  729. hpgl = True
  730. break
  731. elif self.exc_cnc_tools:
  732. for key in self.cnc_tools:
  733. if 'ppname_e' in self.cnc_tools[key]['data']:
  734. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  735. hpgl = True
  736. break
  737. if hpgl:
  738. processed_gcode = ''
  739. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  740. for gline in gcode.splitlines():
  741. match = pa_re.search(gline)
  742. if match:
  743. x_int = int(float(match.group(1)))
  744. y_int = int(float(match.group(2)))
  745. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  746. processed_gcode += new_line
  747. else:
  748. processed_gcode += gline + '\n'
  749. gcode = processed_gcode
  750. g = self.gcode_header() + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  751. else:
  752. try:
  753. g_idx = gcode.index('G94')
  754. g = self.gcode_header() + gcode[:g_idx + 3] + '\n\n' + preamble + '\n' + \
  755. gcode[(g_idx + 3):] + postamble + end_gcode
  756. except ValueError:
  757. self.app.inform.emit('[ERROR_NOTCL] %s' %
  758. _("G-code does not have a G94 code and we will not include the code in the "
  759. "'Prepend to GCode' text box"))
  760. g = self.gcode_header() + '\n' + gcode + postamble + end_gcode
  761. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  762. if self.ui.toolchange_cb.get_value() is True:
  763. # match = self.re_toolchange.search(g)
  764. if 'M6' in g:
  765. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  766. if m6_code is None or m6_code == '':
  767. self.app.inform.emit(
  768. '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  769. )
  770. return 'fail'
  771. g = g.replace('M6', m6_code)
  772. self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  773. lines = StringIO(g)
  774. # Write
  775. if filename is not None:
  776. try:
  777. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  778. if force_windows_line_endings and sys.platform != 'win32':
  779. with open(filename, 'w', newline='\r\n') as f:
  780. for line in lines:
  781. f.write(line)
  782. else:
  783. with open(filename, 'w') as f:
  784. for line in lines:
  785. f.write(line)
  786. except FileNotFoundError:
  787. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  788. return
  789. except PermissionError:
  790. self.app.inform.emit(
  791. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  792. "Most likely another app is holding the file open and not accessible.")
  793. )
  794. return 'fail'
  795. elif to_file is False:
  796. # Just for adding it to the recent files list.
  797. if self.app.defaults["global_open_style"] is False:
  798. self.app.file_opened.emit("cncjob", filename)
  799. self.app.file_saved.emit("cncjob", filename)
  800. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  801. else:
  802. return lines
  803. def on_toolchange_custom_clicked(self, signal):
  804. """
  805. Handler for clicking toolchange custom.
  806. :param signal:
  807. :return:
  808. """
  809. try:
  810. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  811. if self.ui.toolchange_cb.get_value():
  812. self.ui.toolchange_cb.set_value(False)
  813. self.app.inform.emit('[WARNING_NOTCL] %s' %
  814. _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  815. except KeyError:
  816. try:
  817. for key in self.cnc_tools:
  818. ppg = self.cnc_tools[key]['data']['ppname_g']
  819. if 'toolchange_custom' not in str(ppg).lower():
  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(tooldia=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. # I do this so the travel lines thickness will reflect the tool diameter
  928. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  929. # don't know the origin
  930. if self.origin_kind == "excellon":
  931. if self.exc_cnc_tools:
  932. for tooldia_key in self.exc_cnc_tools:
  933. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  934. # gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  935. gcode_parsed = self.gcode_parsed
  936. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  937. self.shapes.redraw()
  938. except (ObjectDeleted, AttributeError):
  939. self.shapes.clear(update=True)
  940. if self.app.is_legacy is False:
  941. self.annotation.clear(update=True)
  942. def on_annotation_change(self):
  943. """
  944. Handler for toggling the annotation display by clicking a checkbox.
  945. :return:
  946. """
  947. if self.app.is_legacy is False:
  948. if self.ui.annotation_cb.get_value():
  949. self.text_col.enabled = True
  950. else:
  951. self.text_col.enabled = False
  952. # kind = self.ui.cncplot_method_combo.get_value()
  953. # self.plot(kind=kind)
  954. self.annotation.redraw()
  955. else:
  956. kind = self.ui.cncplot_method_combo.get_value()
  957. self.plot(kind=kind)
  958. def convert_units(self, units):
  959. """
  960. Units conversion used by the CNCJob objects.
  961. :param units: Can be "MM" or "IN"
  962. :return:
  963. """
  964. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  965. factor = CNCjob.convert_units(self, units)
  966. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  967. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  968. 'endz', 'toolchangez']
  969. temp_tools_dict = {}
  970. tool_dia_copy = {}
  971. data_copy = {}
  972. for tooluid_key, tooluid_value in self.cnc_tools.items():
  973. for dia_key, dia_value in tooluid_value.items():
  974. if dia_key == 'tooldia':
  975. dia_value *= factor
  976. dia_value = float('%.*f' % (self.decimals, dia_value))
  977. tool_dia_copy[dia_key] = dia_value
  978. if dia_key == 'offset':
  979. tool_dia_copy[dia_key] = dia_value
  980. if dia_key == 'offset_value':
  981. dia_value *= factor
  982. tool_dia_copy[dia_key] = dia_value
  983. if dia_key == 'type':
  984. tool_dia_copy[dia_key] = dia_value
  985. if dia_key == 'tool_type':
  986. tool_dia_copy[dia_key] = dia_value
  987. if dia_key == 'data':
  988. for data_key, data_value in dia_value.items():
  989. # convert the form fields that are convertible
  990. for param in param_list:
  991. if data_key == param and data_value is not None:
  992. data_copy[data_key] = data_value * factor
  993. # copy the other dict entries that are not convertible
  994. if data_key not in param_list:
  995. data_copy[data_key] = data_value
  996. tool_dia_copy[dia_key] = deepcopy(data_copy)
  997. data_copy.clear()
  998. if dia_key == 'gcode':
  999. tool_dia_copy[dia_key] = dia_value
  1000. if dia_key == 'gcode_parsed':
  1001. tool_dia_copy[dia_key] = dia_value
  1002. if dia_key == 'solid_geometry':
  1003. tool_dia_copy[dia_key] = dia_value
  1004. # if dia_key == 'solid_geometry':
  1005. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  1006. # if dia_key == 'gcode_parsed':
  1007. # for g in dia_value:
  1008. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1009. #
  1010. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  1011. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  1012. temp_tools_dict.update({
  1013. tooluid_key: deepcopy(tool_dia_copy)
  1014. })
  1015. tool_dia_copy.clear()
  1016. self.cnc_tools.clear()
  1017. self.cnc_tools = deepcopy(temp_tools_dict)