FlatCAMCNCJob.py 54 KB

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