FlatCAMCNCJob.py 51 KB

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