FlatCAMCNCJob.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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 matplotlib.backend_bases import KeyEvent as mpl_key_event
  17. from camlib import CNCjob
  18. from shapely.ops import unary_union
  19. from shapely.geometry import Point
  20. try:
  21. from shapely.ops import voronoi_diagram
  22. except Exception:
  23. pass
  24. import os
  25. import sys
  26. import serial
  27. import glob
  28. import math
  29. import gettext
  30. import appTranslation as fcTranslate
  31. import builtins
  32. fcTranslate.apply_language('strings')
  33. if '_' not in builtins.__dict__:
  34. _ = gettext.gettext
  35. class CNCJobObject(FlatCAMObj, CNCjob):
  36. """
  37. Represents G-Code.
  38. """
  39. optionChanged = QtCore.pyqtSignal(str)
  40. build_al_table_sig = QtCore.pyqtSignal()
  41. ui_type = CNCObjectUI
  42. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  43. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  44. spindlespeed=None):
  45. log.debug("Creating CNCJob object...")
  46. self.decimals = self.app.decimals
  47. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  48. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  49. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  50. FlatCAMObj.__init__(self, name)
  51. self.kind = "cncjob"
  52. self.options.update({
  53. "plot": True,
  54. "tooldia": 0.03937, # 0.4mm in inches
  55. "append": "",
  56. "prepend": "",
  57. "dwell": False,
  58. "dwelltime": 1,
  59. "type": 'Geometry',
  60. # "toolchange_macro": '',
  61. # "toolchange_macro_enable": False
  62. })
  63. '''
  64. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  65. diameter of the tools and the value is another dict that will hold the data under the following form:
  66. {tooldia: {
  67. 'tooluid': 1,
  68. 'offset': 'Path',
  69. 'type_item': 'Rough',
  70. 'tool_type': 'C1',
  71. 'data': {} # a dict to hold the parameters
  72. 'gcode': "" # a string with the actual GCODE
  73. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  74. (cut or move)
  75. 'solid_geometry': []
  76. },
  77. ...
  78. }
  79. It is populated in the GeometryObject.mtool_gen_cncjob()
  80. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  81. '''
  82. self.cnc_tools = {}
  83. '''
  84. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  85. diameter of the tools and the value is another dict that will hold the data under the following form:
  86. {tooldia: {
  87. 'tool': int,
  88. 'nr_drills': int,
  89. 'nr_slots': int,
  90. 'offset': float,
  91. 'data': {}, a dict to hold the parameters
  92. 'gcode': "", a string with the actual GCODE
  93. 'gcode_parsed': [], list of dicts holding the CNCJob geometry and
  94. type of geometry (cut or move)
  95. 'solid_geometry': [],
  96. },
  97. ...
  98. }
  99. It is populated in the ExcellonObject.on_create_cncjob_click() but actually
  100. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  101. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  102. '''
  103. self.exc_cnc_tools = {}
  104. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  105. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  106. self.special_group = None
  107. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  108. # (like the one in the TCL Command), False
  109. self.multitool = False
  110. # determine if the GCode was generated out of a Excellon object or a Geometry object
  111. self.origin_kind = None
  112. self.coords_decimals = 4
  113. self.fr_decimals = 2
  114. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  115. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  116. self.g_x_re = re.compile(gcodex_re_string)
  117. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  118. self.g_y_re = re.compile(gcodey_re_string)
  119. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  120. self.g_z_re = re.compile(gcodez_re_string)
  121. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  122. self.g_f_re = re.compile(gcodef_re_string)
  123. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  124. self.g_t_re = re.compile(gcodet_re_string)
  125. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  126. self.g_nr_re = re.compile(gcodenr_re_string)
  127. if self.app.is_legacy is False:
  128. self.text_col = self.app.plotcanvas.new_text_collection()
  129. self.text_col.enabled = True
  130. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  131. self.gcode_editor_tab = None
  132. self.gcode_viewer_tab = None
  133. self.source_file = ''
  134. self.units_found = self.app.defaults['units']
  135. self.probing_gcode_text = ''
  136. # store the current selection shape status to be restored after manual adding test points
  137. self.old_selection_state = self.app.defaults['global_selection_shape']
  138. # if mouse is dragging set the object True
  139. self.mouse_is_dragging = False
  140. # if mouse events are bound to local methods
  141. self.mouse_events_connected = False
  142. # event handlers references
  143. self.kp = None
  144. self.mm = None
  145. self.mr = None
  146. self.append_snippet = ''
  147. self.prepend_snippet = ''
  148. self.gc_header = self.gcode_header()
  149. self.gc_start = ''
  150. self.gc_end = ''
  151. '''
  152. dictionary of dictionaries to store the informations for the autolevelling
  153. format:
  154. {
  155. id: {
  156. 'point': Shapely Point
  157. 'geo': Shapely Polygon from Voronoi diagram,
  158. 'height': float
  159. }
  160. }
  161. '''
  162. self.al_geometry_dict = {}
  163. self.grbl_ser_port = None
  164. # Attributes to be included in serialization
  165. # Always append to it because it carries contents
  166. # from predecessors.
  167. self.ser_attrs += [
  168. 'options', 'kind', 'origin_kind', 'cnc_tools', 'exc_cnc_tools', 'multitool', 'append_snippet',
  169. 'prepend_snippet', 'gc_header'
  170. ]
  171. def build_ui(self):
  172. self.ui_disconnect()
  173. FlatCAMObj.build_ui(self)
  174. self.units = self.app.defaults['units'].upper()
  175. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  176. self.ui.cnc_tools_table.hide()
  177. if self.cnc_tools:
  178. self.ui.cnc_tools_table.show()
  179. self.build_cnc_tools_table()
  180. self.ui.exc_cnc_tools_table.hide()
  181. if self.exc_cnc_tools:
  182. self.ui.exc_cnc_tools_table.show()
  183. self.build_excellon_cnc_tools()
  184. if self.ui.sal_cb.get_value():
  185. self.build_al_table()
  186. self.ui_connect()
  187. def build_cnc_tools_table(self):
  188. tool_idx = 0
  189. n = len(self.cnc_tools)
  190. self.ui.cnc_tools_table.setRowCount(n)
  191. for dia_key, dia_value in self.cnc_tools.items():
  192. tool_idx += 1
  193. row_no = tool_idx - 1
  194. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  195. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  196. self.ui.cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  197. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  198. # There are no tool bits in MM with more than 2 decimals diameter.
  199. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  200. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  201. offset_txt = list(str(dia_value['offset']))
  202. offset_txt[0] = offset_txt[0].upper()
  203. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  204. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  205. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  206. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  207. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  208. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  209. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  210. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  211. # hack so the checkbox stay centered in the table cell
  212. # used this:
  213. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  214. # plot_item = QtWidgets.QWidget()
  215. # checkbox = FCCheckBox()
  216. # checkbox.setCheckState(QtCore.Qt.Checked)
  217. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  218. # qhboxlayout.addWidget(checkbox)
  219. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  220. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  221. plot_item = FCCheckBox()
  222. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  223. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  224. if self.ui.plot_cb.isChecked():
  225. plot_item.setChecked(True)
  226. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  227. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  228. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  229. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  230. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  231. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  232. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  233. # make the diameter column editable
  234. # for row in range(tool_idx):
  235. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  236. # QtCore.Qt.ItemIsEnabled)
  237. for row in range(tool_idx):
  238. self.ui.cnc_tools_table.item(row, 0).setFlags(
  239. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  240. self.ui.cnc_tools_table.resizeColumnsToContents()
  241. self.ui.cnc_tools_table.resizeRowsToContents()
  242. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  243. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  244. vertical_header.hide()
  245. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  246. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  247. horizontal_header.setMinimumSectionSize(10)
  248. horizontal_header.setDefaultSectionSize(70)
  249. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  250. horizontal_header.resizeSection(0, 20)
  251. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  252. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  253. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  254. horizontal_header.resizeSection(4, 40)
  255. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  256. horizontal_header.resizeSection(4, 17)
  257. # horizontal_header.setStretchLastSection(True)
  258. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  259. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  260. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  261. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  262. # self.ui.geo_tools_table.setSortingEnabled(True)
  263. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  264. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  265. def build_excellon_cnc_tools(self):
  266. tool_idx = 0
  267. n = len(self.exc_cnc_tools)
  268. self.ui.exc_cnc_tools_table.setRowCount(n)
  269. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  270. tool_idx += 1
  271. row_no = tool_idx - 1
  272. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  273. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  274. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  275. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  276. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset']) + self.z_cut))
  277. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  278. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  279. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  280. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  281. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  282. # hack so the checkbox stay centered in the table cell
  283. # used this:
  284. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  285. # plot_item = QtWidgets.QWidget()
  286. # checkbox = FCCheckBox()
  287. # checkbox.setCheckState(QtCore.Qt.Checked)
  288. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  289. # qhboxlayout.addWidget(checkbox)
  290. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  291. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  292. plot_item = FCCheckBox()
  293. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  294. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  295. if self.ui.plot_cb.isChecked():
  296. plot_item.setChecked(True)
  297. self.ui.exc_cnc_tools_table.setItem(row_no, 0, t_id) # Tool name/id
  298. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  299. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  300. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  301. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  302. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  303. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  304. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  305. for row in range(tool_idx):
  306. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  307. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  308. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  309. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  310. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  311. vertical_header.hide()
  312. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  313. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  314. horizontal_header.setMinimumSectionSize(10)
  315. horizontal_header.setDefaultSectionSize(70)
  316. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  317. horizontal_header.resizeSection(0, 20)
  318. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  319. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  320. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  321. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  322. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  323. # horizontal_header.setStretchLastSection(True)
  324. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  325. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  326. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  327. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  328. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  329. def build_al_table(self):
  330. tool_idx = 0
  331. n = len(self.al_geometry_dict)
  332. self.ui.al_probe_points_table.setRowCount(n)
  333. for id_key, value in self.al_geometry_dict.items():
  334. tool_idx += 1
  335. row_no = tool_idx - 1
  336. t_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  337. x = value['point'].x
  338. y = value['point'].y
  339. xy_coords = self.app.dec_format(x, dec=self.app.decimals), self.app.dec_format(y, dec=self.app.decimals)
  340. coords_item = QtWidgets.QTableWidgetItem(str(xy_coords))
  341. height = self.app.dec_format(value['height'], dec=self.app.decimals)
  342. height_item = QtWidgets.QTableWidgetItem(str(height))
  343. t_id.setFlags(QtCore.Qt.ItemIsEnabled)
  344. coords_item.setFlags(QtCore.Qt.ItemIsEnabled)
  345. height_item.setFlags(QtCore.Qt.ItemIsEnabled)
  346. self.ui.al_probe_points_table.setItem(row_no, 0, t_id) # Tool name/id
  347. self.ui.al_probe_points_table.setItem(row_no, 1, coords_item) # X-Y coords
  348. self.ui.al_probe_points_table.setItem(row_no, 2, height_item) # Determined Height
  349. self.ui.al_probe_points_table.resizeColumnsToContents()
  350. self.ui.al_probe_points_table.resizeRowsToContents()
  351. h_header = self.ui.al_probe_points_table.horizontalHeader()
  352. h_header.setMinimumSectionSize(10)
  353. h_header.setDefaultSectionSize(70)
  354. h_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  355. h_header.resizeSection(0, 20)
  356. h_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  357. h_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  358. self.ui.al_probe_points_table.setMinimumHeight(self.ui.al_probe_points_table.getHeight())
  359. self.ui.al_probe_points_table.setMaximumHeight(self.ui.al_probe_points_table.getHeight())
  360. if self.ui.al_probe_points_table.model().rowCount():
  361. self.ui.voronoi_cb.setDisabled(False)
  362. self.ui.grbl_get_heightmap_button.setDisabled(False)
  363. self.ui.h_gcode_button.setDisabled(False)
  364. self.ui.view_h_gcode_button.setDisabled(False)
  365. else:
  366. self.ui.voronoi_cb.setDisabled(True)
  367. self.ui.grbl_get_heightmap_button.setDisabled(True)
  368. self.ui.h_gcode_button.setDisabled(True)
  369. self.ui.view_h_gcode_button.setDisabled(True)
  370. def set_ui(self, ui):
  371. FlatCAMObj.set_ui(self, ui)
  372. log.debug("FlatCAMCNCJob.set_ui()")
  373. assert isinstance(self.ui, CNCObjectUI), \
  374. "Expected a CNCObjectUI, got %s" % type(self.ui)
  375. self.units = self.app.defaults['units'].upper()
  376. self.units_found = self.app.defaults['units']
  377. # this signal has to be connected to it's slot before the defaults are populated
  378. # the decision done in the slot has to override the default value set below
  379. # self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  380. self.form_fields.update({
  381. "plot": self.ui.plot_cb,
  382. "tooldia": self.ui.tooldia_entry,
  383. # "append": self.ui.append_text,
  384. # "prepend": self.ui.prepend_text,
  385. # "toolchange_macro": self.ui.toolchange_text,
  386. # "toolchange_macro_enable": self.ui.toolchange_cb,
  387. "al_travelz": self.ui.ptravelz_entry,
  388. "al_probe_depth": self.ui.pdepth_entry,
  389. "al_probe_fr": self.ui.feedrate_probe_entry,
  390. "al_controller": self.ui.al_controller_combo,
  391. "al_mode": self.ui.al_mode_radio,
  392. "al_rows": self.ui.al_rows_entry,
  393. "al_columns": self.ui.al_columns_entry,
  394. })
  395. self.append_snippet = self.app.defaults['cncjob_append']
  396. self.prepend_snippet = self.app.defaults['cncjob_prepend']
  397. if self.append_snippet != '' or self.prepend_snippet:
  398. self.ui.snippets_cb.set_value(True)
  399. # Fill form fields only on object create
  400. self.to_form()
  401. # this means that the object that created this CNCJob was an Excellon or Geometry
  402. try:
  403. if self.travel_distance:
  404. self.ui.t_distance_label.show()
  405. self.ui.t_distance_entry.setVisible(True)
  406. self.ui.t_distance_entry.setDisabled(True)
  407. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  408. self.ui.units_label.setText(str(self.units).lower())
  409. self.ui.units_label.setDisabled(True)
  410. self.ui.t_time_label.show()
  411. self.ui.t_time_entry.setVisible(True)
  412. self.ui.t_time_entry.setDisabled(True)
  413. # if time is more than 1 then we have minutes, else we have seconds
  414. if self.routing_time > 1:
  415. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  416. self.ui.units_time_label.setText('min')
  417. else:
  418. time_r = self.routing_time * 60
  419. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  420. self.ui.units_time_label.setText('sec')
  421. self.ui.units_time_label.setDisabled(True)
  422. except AttributeError:
  423. pass
  424. if self.multitool is False:
  425. self.ui.tooldia_entry.show()
  426. self.ui.updateplot_button.show()
  427. else:
  428. self.ui.tooldia_entry.hide()
  429. self.ui.updateplot_button.hide()
  430. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  431. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  432. try:
  433. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  434. except (TypeError, AttributeError):
  435. pass
  436. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  437. # set if to display text annotations
  438. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  439. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  440. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  441. self.ui.review_gcode_button.clicked.connect(self.on_edit_code_click)
  442. self.ui.editor_button.clicked.connect(lambda: self.app.object2editor())
  443. # autolevelling signals
  444. self.ui.sal_cb.stateChanged.connect(self.on_autolevelling)
  445. self.ui.al_mode_radio.activated_custom.connect(self.on_mode_radio)
  446. self.ui.al_controller_combo.currentIndexChanged.connect(self.on_controller_change)
  447. self.ui.com_search_button.clicked.connect(self.on_search_ports)
  448. self.ui.add_bd_button.clicked.connect(self.on_add_baudrate_grbl)
  449. self.ui.del_bd_button.clicked.connect(self.on_delete_baudrate_grbl)
  450. self.ui.com_connect_button.clicked.connect(self.on_connect_grbl)
  451. self.ui.view_h_gcode_button.clicked.connect(self.on_view_probing_gcode)
  452. self.ui.h_gcode_button.clicked.connect(self.on_generate_probing_gcode)
  453. self.ui.import_heights_button.clicked.connect(self.on_import_height_map)
  454. self.build_al_table_sig.connect(self.build_al_table)
  455. # self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  456. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  457. # Show/Hide Advanced Options
  458. if self.app.defaults["global_app_level"] == 'b':
  459. self.ui.level.setText(_(
  460. '<span style="color:green;"><b>Basic</b></span>'
  461. ))
  462. self.ui.sal_cb.hide()
  463. self.ui.sal_cb.set_value(False)
  464. else:
  465. self.ui.level.setText(_(
  466. '<span style="color:red;"><b>Advanced</b></span>'
  467. ))
  468. self.ui.sal_cb.show()
  469. self.ui.sal_cb.set_value(self.app.defaults["cncjob_al_status"])
  470. preamble = self.append_snippet
  471. postamble = self.prepend_snippet
  472. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  473. self.source_file = gc.getvalue()
  474. self.ui.al_mode_radio.set_value(self.options['al_mode'])
  475. self.on_controller_change()
  476. # def on_cnc_custom_parameters(self, signal_text):
  477. # if signal_text == 'Parameters':
  478. # return
  479. # else:
  480. # self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  481. def ui_connect(self):
  482. for row in range(self.ui.cnc_tools_table.rowCount()):
  483. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  484. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  485. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  486. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  487. self.ui.al_add_button.clicked.connect(self.on_add_al_probepoints)
  488. self.ui.show_al_table.stateChanged.connect(self.on_show_al_table)
  489. def ui_disconnect(self):
  490. for row in range(self.ui.cnc_tools_table.rowCount()):
  491. try:
  492. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  493. except (TypeError, AttributeError):
  494. pass
  495. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  496. try:
  497. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  498. except (TypeError, AttributeError):
  499. pass
  500. try:
  501. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  502. except (TypeError, AttributeError):
  503. pass
  504. try:
  505. self.ui.al_add_button.clicked.disconnect()
  506. except (TypeError, AttributeError):
  507. pass
  508. try:
  509. self.ui.show_al_table.stateChanged.disconnect()
  510. except (TypeError, AttributeError):
  511. pass
  512. def on_add_al_probepoints(self):
  513. # create the solid_geo
  514. solid_geo = [geo['geom'] for geo in self.gcode_parsed if geo['kind'][0] == 'C']
  515. solid_geo = unary_union(solid_geo)
  516. # reset al table
  517. self.ui.al_probe_points_table.setRowCount(0)
  518. # reset the al dict
  519. self.al_geometry_dict.clear()
  520. xmin, ymin, xmax, ymax = solid_geo.bounds
  521. if self.ui.al_mode_radio.get_value() == 'grid':
  522. width = abs(xmax - xmin)
  523. height = abs(ymax - ymin)
  524. cols = self.ui.al_columns_entry.get_value()
  525. rows = self.ui.al_rows_entry.get_value()
  526. dx = width / (cols + 1)
  527. dy = height / (rows + 1)
  528. points = []
  529. new_y = ymin
  530. for x in range(rows):
  531. new_y += dy
  532. new_x = xmin
  533. for x in range(cols):
  534. new_x += dx
  535. points.append((new_x, new_y))
  536. pt_id = 0
  537. for point in points:
  538. pt_id += 1
  539. new_dict = {
  540. 'point': Point(point),
  541. 'geo': None,
  542. 'height': 0.0
  543. }
  544. self.al_geometry_dict[pt_id] = deepcopy(new_dict)
  545. else:
  546. self.app.inform.emit(_("Click on canvas to add a Test Point..."))
  547. if self.app.is_legacy is False:
  548. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  549. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  550. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  551. else:
  552. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  553. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  554. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  555. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  556. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  557. self.mouse_events_connected = True
  558. self.calculate_voronoi_diagram()
  559. self.build_al_table_sig.emit()
  560. def calculate_voronoi_diagram(self):
  561. pass
  562. # return voronoi_diagram()
  563. # To be called after clicking on the plot.
  564. def on_mouse_click_release(self, event):
  565. if self.app.is_legacy is False:
  566. event_pos = event.pos
  567. # event_is_dragging = event.is_dragging
  568. right_button = 2
  569. else:
  570. event_pos = (event.xdata, event.ydata)
  571. # event_is_dragging = self.app.plotcanvas.is_dragging
  572. right_button = 3
  573. try:
  574. x = float(event_pos[0])
  575. y = float(event_pos[1])
  576. except TypeError:
  577. return
  578. event_pos = (x, y)
  579. # do paint single only for left mouse clicks
  580. if event.button == 1:
  581. pos = self.app.plotcanvas.translate_coords(event_pos)
  582. # use the snapped position as reference
  583. snapped_pos = self.app.geo_editor.snap(pos[0], pos[1])
  584. if not self.al_geometry_dict:
  585. new_dict = {
  586. 'point': Point(snapped_pos),
  587. 'geo': None,
  588. 'height': 0.0
  589. }
  590. self.al_geometry_dict[1] = deepcopy(new_dict)
  591. else:
  592. int_keys = [int(k) for k in self.al_geometry_dict.keys()]
  593. new_id = max(int_keys) + 1
  594. new_dict = {
  595. 'point': Point(snapped_pos),
  596. 'geo': None,
  597. 'height': 0.0
  598. }
  599. self.al_geometry_dict[new_id] = deepcopy(new_dict)
  600. # rebuild the al table
  601. self.build_al_table_sig.emit()
  602. self.app.inform.emit(_("Added Test Point... Click again to add another or right click to finish ..."))
  603. # if RMB then we exit
  604. elif event.button == right_button and self.mouse_is_dragging is False:
  605. if self.app.is_legacy is False:
  606. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  607. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  608. else:
  609. self.app.plotcanvas.graph_event_disconnect(self.kp)
  610. self.app.plotcanvas.graph_event_disconnect(self.mr)
  611. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  612. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  613. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  614. self.app.on_mouse_click_release_over_plot)
  615. # signal that the mouse events are disconnected from local methods
  616. self.mouse_events_connected = False
  617. # restore selection
  618. self.app.defaults['global_selection_shape'] = self.old_selection_state
  619. self.app.inform.emit(_("Finished manual adding of Test Point..."))
  620. # rebuild the al table
  621. self.build_al_table_sig.emit()
  622. def on_key_press(self, event):
  623. # events out of the self.app.collection view (it's about Project Tab) are of type int
  624. if type(event) is int:
  625. key = event
  626. # events from the GUI are of type QKeyEvent
  627. elif type(event) == QtGui.QKeyEvent:
  628. key = event.key()
  629. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  630. key = event.key
  631. key = QtGui.QKeySequence(key)
  632. # check for modifiers
  633. key_string = key.toString().lower()
  634. if '+' in key_string:
  635. mod, __, key_text = key_string.rpartition('+')
  636. if mod.lower() == 'ctrl':
  637. # modifiers = QtCore.Qt.ControlModifier
  638. pass
  639. elif mod.lower() == 'alt':
  640. # modifiers = QtCore.Qt.AltModifier
  641. pass
  642. elif mod.lower() == 'shift':
  643. # modifiers = QtCore.Qt.ShiftModifier
  644. pass
  645. else:
  646. # modifiers = QtCore.Qt.NoModifier
  647. pass
  648. key = QtGui.QKeySequence(key_text)
  649. # events from Vispy are of type KeyEvent
  650. else:
  651. key = event.key
  652. # Escape = Deselect All
  653. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  654. if self.mouse_events_connected is True:
  655. self.mouse_events_connected = False
  656. if self.app.is_legacy is False:
  657. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  658. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  659. else:
  660. self.app.plotcanvas.graph_event_disconnect(self.kp)
  661. self.app.plotcanvas.graph_event_disconnect(self.mr)
  662. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  663. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  664. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  665. self.app.on_mouse_click_release_over_plot)
  666. if self.ui.big_cursor_cb.get_value():
  667. # restore cursor
  668. self.app.on_cursor_type(val=self.old_cursor_type)
  669. # restore selection
  670. self.app.defaults['global_selection_shape'] = self.old_selection_state
  671. # Grid toggle
  672. if key == QtCore.Qt.Key_G or key == 'G':
  673. self.app.ui.grid_snap_btn.trigger()
  674. # Jump to coords
  675. if key == QtCore.Qt.Key_J or key == 'J':
  676. l_x, l_y = self.app.on_jump_to()
  677. def on_autolevelling(self, state):
  678. self.ui.al_frame.show() if state else self.ui.al_frame.hide()
  679. self.app.defaults["cncjob_al_status"] = True if state else False
  680. def on_show_al_table(self, state):
  681. self.ui.al_probe_points_table.show() if state else self.ui.al_probe_points_table.hide()
  682. def on_mode_radio(self, val):
  683. # reset al table
  684. self.ui.al_probe_points_table.setRowCount(0)
  685. # reset the al dict
  686. self.al_geometry_dict.clear()
  687. # build AL table
  688. self.build_al_table()
  689. if val == "manual":
  690. self.ui.al_rows_entry.setDisabled(True)
  691. self.ui.al_rows_label.setDisabled(True)
  692. self.ui.al_columns_entry.setDisabled(True)
  693. self.ui.al_columns_label.setDisabled(True)
  694. else:
  695. self.ui.al_rows_entry.setDisabled(False)
  696. self.ui.al_rows_label.setDisabled(False)
  697. self.ui.al_columns_entry.setDisabled(False)
  698. self.ui.al_columns_label.setDisabled(False)
  699. def on_controller_change(self):
  700. if self.ui.al_controller_combo.get_value() == 'GRBL':
  701. self.ui.h_gcode_button.hide()
  702. self.ui.view_h_gcode_button.hide()
  703. self.ui.import_heights_button.hide()
  704. self.ui.grbl_frame.show()
  705. self.on_search_ports(muted=True)
  706. else:
  707. self.ui.h_gcode_button.show()
  708. self.ui.view_h_gcode_button.show()
  709. self.ui.import_heights_button.show()
  710. self.ui.grbl_frame.hide()
  711. def list_serial_ports(self):
  712. """
  713. Lists serial port names.
  714. From here: https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
  715. :raises EnvironmentError: On unsupported or unknown platforms
  716. :returns: A list of the serial ports available on the system
  717. """
  718. if sys.platform.startswith('win'):
  719. ports = ['COM%s' % (i + 1) for i in range(256)]
  720. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  721. # this excludes your current terminal "/dev/tty"
  722. ports = glob.glob('/dev/tty[A-Za-z]*')
  723. elif sys.platform.startswith('darwin'):
  724. ports = glob.glob('/dev/tty.*')
  725. else:
  726. raise EnvironmentError('Unsupported platform')
  727. result = []
  728. s = serial.Serial()
  729. for port in ports:
  730. s.port = port
  731. try:
  732. s.open()
  733. s.close()
  734. result.append(port)
  735. except (OSError, serial.SerialException):
  736. # result.append(port + " (in use)")
  737. pass
  738. return result
  739. def on_search_ports(self, muted=None):
  740. port_list = self.list_serial_ports()
  741. self.ui.com_list_combo.clear()
  742. self.ui.com_list_combo.addItems(port_list)
  743. if muted is not True:
  744. self.app.inform.emit('[WARNING_NOTCL] %s' % _("COM list updated ..."))
  745. def on_connect_grbl(self):
  746. port_name = self.ui.com_list_combo.currentText()
  747. if " (" in port_name:
  748. port_name = port_name.rpartition(" (")[0]
  749. baudrate = int(self.ui.baudrates_list_combo.currentText())
  750. try:
  751. self.grbl_ser_port = serial.serial_for_url(port_name, baudrate,
  752. bytesize=serial.EIGHTBITS,
  753. parity=serial.PARITY_NONE,
  754. stopbits=serial.STOPBITS_ONE,
  755. timeout=0.1,
  756. xonxoff=False,
  757. rtscts=False)
  758. self.app.inform.emit("%s: %s" % (_("Port connected"), port_name))
  759. self.ui.com_connect_button.setStyleSheet("QPushButton {color: seagreen;}")
  760. # Toggle DTR to reset the controller loaded with GRBL (Arduino, ESP32, etc)
  761. try:
  762. self.grbl_ser_port.dtr = False
  763. except IOError:
  764. pass
  765. self.grbl_ser_port.reset_input_buffer()
  766. try:
  767. self.grbl_ser_port.dtr = True
  768. except IOError:
  769. pass
  770. except serial.SerialException:
  771. self.grbl_ser_port = serial.Serial()
  772. self.grbl_ser_port.port = port_name
  773. self.grbl_ser_port.close()
  774. self.ui.com_connect_button.setStyleSheet("")
  775. self.app.inform.emit("%s: %s" % (_("Port is connected. Disconnecting"), port_name))
  776. except Exception:
  777. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to port"), port_name))
  778. def on_add_baudrate_grbl(self):
  779. new_bd = str(self.ui.new_baudrate_entry.get_value())
  780. if int(new_bd) >= 40 and new_bd not in self.ui.baudrates_list_combo.model().stringList():
  781. self.ui.baudrates_list_combo.addItem(new_bd)
  782. self.ui.baudrates_list_combo.setCurrentText(new_bd)
  783. def on_delete_baudrate_grbl(self):
  784. current_idx = self.ui.baudrates_list_combo.currentIndex()
  785. self.ui.baudrates_list_combo.removeItem(current_idx)
  786. def probing_gcode(self, coords, pr_travel, probe_fr, pr_depth, controller):
  787. """
  788. :param coords: a list of (x, y) tuples of probe points coordinates
  789. :type coords: list
  790. :param pr_travel: the height (z) where the probe travel between probe points
  791. :type pr_travel: float
  792. :param probe_fr: feedrate when probing
  793. :type probe_fr: float
  794. :param pr_depth: how much to lower the probe searching for contact
  795. :type pr_depth: float
  796. :param controller: a string with the name of the GCode sender for which to create the probing GCode.
  797. Can be: 'MACH3', 'MACH4', 'LinuxCNC', 'GRBL'
  798. :type controller: str
  799. :return: Probing GCode
  800. :rtype: str
  801. """
  802. p_gcode = ''
  803. header = ''
  804. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  805. header += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  806. (str(self.app.version), str(self.app.version_date)) + '\n'
  807. header += '(This is a autolevelling probing GCode.)\n' \
  808. '(Make sure that before you start the job you first do a zero for all axis.)\n\n'
  809. header += '(Name: ' + str(self.options['name']) + ')\n'
  810. header += '(Type: ' + "Autolevelling Probing GCode " + ')\n'
  811. header += '(Units: ' + self.units.upper() + ')\n'
  812. header += '(Created on ' + time_str + ')\n'
  813. # commands
  814. if controller == 'MACH3':
  815. probing_command = 'G31'
  816. probing_var = '#2002'
  817. openfile_command = 'M40'
  818. closefile_command = 'M41'
  819. elif controller == 'MACH4':
  820. probing_command = 'G31'
  821. probing_var = '#5063'
  822. openfile_command = 'M40'
  823. closefile_command = 'M41'
  824. elif controller == 'LinuxCNC':
  825. probing_command = 'G38.2'
  826. probing_var = '#5422'
  827. openfile_command = '(PROBEOPEN a_probing_points_file.txt)'
  828. closefile_command = '(PROBECLOSE)'
  829. else:
  830. log.debug("CNCJobObject.probing_gcode() -> controller not supported")
  831. return
  832. # #############################################################################################################
  833. # ########################### GCODE construction ##############################################################
  834. # #############################################################################################################
  835. # header
  836. p_gcode += header + '\n'
  837. # supplementary message for LinuxCNC
  838. if controller == 'LinuxCNC':
  839. probing_var += "The file with the stored probing points can be found\n" \
  840. "in the configuration folder for LinuxCNC.\n" \
  841. "The name of the file is: a_probing_points_file.txt.\n"
  842. # units
  843. p_gcode += 'G21\n' if self.units == 'MM' else 'G20\n'
  844. # reference mode = absolute
  845. p_gcode += 'G90\n'
  846. # open a new file
  847. p_gcode += openfile_command + '\n'
  848. # move to safe height (probe travel Z)
  849. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  850. # probing points
  851. for idx, xy_tuple in enumerate(coords, 1): # index starts from 1
  852. x = xy_tuple[0]
  853. y = xy_tuple[1]
  854. # move to probing point
  855. p_gcode += "G0 X%sY%s\n" % (
  856. str(self.app.dec_format(x, self.coords_decimals)),
  857. str(self.app.dec_format(y, self.coords_decimals))
  858. )
  859. # do the probing
  860. p_gcode += "%s Z%s F%s\n" % (
  861. probing_command,
  862. str(self.app.dec_format(pr_depth, self.coords_decimals)),
  863. str(self.app.dec_format(probe_fr, self.fr_decimals)),
  864. )
  865. # store in a global numeric variable the value of the detected probe Z
  866. # I offset the global numeric variable by 500 so it does not conflict with something else
  867. temp_var = int(idx + 500)
  868. p_gcode += "#%d = %s\n" % (temp_var, probing_var)
  869. # move to safe height (probe travel Z)
  870. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  871. # close the file
  872. p_gcode += closefile_command + '\n'
  873. # finish the GCode
  874. p_gcode += 'M2'
  875. return p_gcode
  876. def on_generate_probing_gcode(self):
  877. coords = []
  878. for id_key, value in self.al_geometry_dict.items():
  879. x = value['point'].x
  880. y = value['point'].y
  881. coords.append(
  882. (
  883. self.app.dec_format(x, dec=self.app.decimals),
  884. self.app.dec_format(y, dec=self.app.decimals)
  885. )
  886. )
  887. pr_travel = self.ui.ptravelz_entry.get_value()
  888. probe_fr = self.ui.feedrate_probe_entry.get_value()
  889. pr_depth = self.ui.pdepth_entry.get_value()
  890. controller = self.ui.al_controller_combo.get_value()
  891. self.probing_gcode_text = self.probing_gcode(coords, pr_travel, probe_fr, pr_depth, controller)
  892. def on_view_probing_gcode(self):
  893. self.app.proc_container.view.set_busy(_("Loading..."))
  894. gco = self.probing_gcode_text
  895. if gco is None or gco == '':
  896. self.app.inform.emit('[WARNING_NOTCL] %s...' % _('There is nothing to view'))
  897. return
  898. self.gcode_viewer_tab = AppTextEditor(app=self.app, plain_text=True)
  899. # add the tab if it was closed
  900. self.app.ui.plot_tab_area.addTab(self.gcode_viewer_tab, '%s' % _("Code Viewer"))
  901. self.gcode_viewer_tab.setObjectName('code_viewer_tab')
  902. # delete the absolute and relative position and messages in the infobar
  903. self.app.ui.position_label.setText("")
  904. self.app.ui.rel_position_label.setText("")
  905. self.gcode_viewer_tab.code_editor.completer_enable = False
  906. self.gcode_viewer_tab.buttonRun.hide()
  907. # Switch plot_area to CNCJob tab
  908. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_viewer_tab)
  909. self.gcode_viewer_tab.t_frame.hide()
  910. # then append the text from GCode to the text editor
  911. try:
  912. self.gcode_viewer_tab.load_text(gco, move_to_start=True, clear_text=True)
  913. except Exception as e:
  914. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  915. return
  916. self.gcode_viewer_tab.t_frame.show()
  917. self.app.proc_container.view.set_idle()
  918. self.gcode_viewer_tab.buttonSave.hide()
  919. self.gcode_viewer_tab.buttonOpen.hide()
  920. self.gcode_viewer_tab.buttonPrint.hide()
  921. self.gcode_viewer_tab.buttonPreview.hide()
  922. self.gcode_viewer_tab.buttonReplace.hide()
  923. self.gcode_viewer_tab.sel_all_cb.hide()
  924. self.gcode_viewer_tab.entryReplace.hide()
  925. self.gcode_viewer_tab.code_editor.setReadOnly(True)
  926. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Viewer'))
  927. def on_import_height_map(self):
  928. """
  929. Import the height map file into the app
  930. :return:
  931. :rtype:
  932. """
  933. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  934. try:
  935. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  936. directory=self.app.get_last_folder(),
  937. filter=_filter_)
  938. except TypeError:
  939. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  940. filter=_filter_)
  941. filename = str(filename)
  942. if filename == '':
  943. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  944. else:
  945. self.app.worker_task.emit({'fcn': self.import_height_map, 'params': [filename]})
  946. def import_height_map(self, filename):
  947. """
  948. :param filename:
  949. :type filename:
  950. :return:
  951. :rtype:
  952. """
  953. stream = ''
  954. try:
  955. if filename:
  956. with open(filename, 'r') as f:
  957. stream = f.readlines()
  958. else:
  959. return
  960. except IOError:
  961. log.error("Failed to open height map file: %s" % filename)
  962. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open height map file"), filename))
  963. return
  964. idx = 0
  965. for line in stream:
  966. if line != '':
  967. idx += 1
  968. line = line.replace(' ', ',').replace('\n', '').split(',')
  969. if idx not in self.al_geometry_dict:
  970. self.al_geometry_dict[idx] = {}
  971. self.al_geometry_dict[idx]['height'] = float(line[2])
  972. if 'point' not in self.al_geometry_dict[idx]:
  973. x = float(line[0])
  974. y = float(line[1])
  975. self.al_geometry_dict[idx]['point'] = Point((x, y))
  976. self.build_al_table_sig.emit()
  977. def on_updateplot_button_click(self, *args):
  978. """
  979. Callback for the "Updata Plot" button. Reads the form for updates
  980. and plots the object.
  981. """
  982. self.read_form()
  983. self.on_plot_kind_change()
  984. def on_plot_kind_change(self):
  985. kind = self.ui.cncplot_method_combo.get_value()
  986. def worker_task():
  987. with self.app.proc_container.new(_("Plotting...")):
  988. self.plot(kind=kind)
  989. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  990. def on_exportgcode_button_click(self):
  991. """
  992. Handler activated by a button clicked when exporting GCode.
  993. :param args:
  994. :return:
  995. """
  996. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  997. self.read_form()
  998. name = self.app.collection.get_active().options['name']
  999. save_gcode = False
  1000. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  1001. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  1002. elif 'hpgl' in self.pp_geometry_name:
  1003. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  1004. else:
  1005. save_gcode = True
  1006. _filter_ = self.app.defaults['cncjob_save_filters']
  1007. try:
  1008. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1009. filename, _f = FCFileSaveDialog.get_saved_filename(
  1010. caption=_("Export Code ..."),
  1011. directory=dir_file_to_save,
  1012. ext_filter=_filter_
  1013. )
  1014. except TypeError:
  1015. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1016. self.export_gcode_handler(filename, is_gcode=save_gcode)
  1017. def export_gcode_handler(self, filename, is_gcode=True):
  1018. preamble = ''
  1019. postamble = ''
  1020. filename = str(filename)
  1021. if filename == '':
  1022. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1023. return
  1024. else:
  1025. if is_gcode is True:
  1026. used_extension = filename.rpartition('.')[2]
  1027. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  1028. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  1029. self.ui.name_entry.set_value(new_name)
  1030. self.on_name_activate(silent=True)
  1031. try:
  1032. if self.ui.snippets_cb.get_value():
  1033. preamble = self.append_snippet
  1034. postamble = self.prepend_snippet
  1035. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  1036. except Exception as err:
  1037. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  1038. gc = self.export_gcode(filename)
  1039. if gc == 'fail':
  1040. return
  1041. if self.app.defaults["global_open_style"] is False:
  1042. self.app.file_opened.emit("gcode", filename)
  1043. self.app.file_saved.emit("gcode", filename)
  1044. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  1045. def on_edit_code_click(self, *args):
  1046. """
  1047. Handler activated by a button clicked when reviewing GCode.
  1048. :param args:
  1049. :return:
  1050. """
  1051. self.app.proc_container.view.set_busy(_("Loading..."))
  1052. preamble = self.append_snippet
  1053. postamble = self.prepend_snippet
  1054. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  1055. if gco == 'fail':
  1056. return
  1057. else:
  1058. self.app.gcode_edited = gco
  1059. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  1060. # add the tab if it was closed
  1061. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Review"))
  1062. self.gcode_editor_tab.setObjectName('code_editor_tab')
  1063. # delete the absolute and relative position and messages in the infobar
  1064. self.app.ui.position_label.setText("")
  1065. self.app.ui.rel_position_label.setText("")
  1066. self.gcode_editor_tab.code_editor.completer_enable = False
  1067. self.gcode_editor_tab.buttonRun.hide()
  1068. # Switch plot_area to CNCJob tab
  1069. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  1070. self.gcode_editor_tab.t_frame.hide()
  1071. # then append the text from GCode to the text editor
  1072. try:
  1073. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  1074. except Exception as e:
  1075. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1076. return
  1077. self.gcode_editor_tab.t_frame.show()
  1078. self.app.proc_container.view.set_idle()
  1079. self.gcode_editor_tab.buttonSave.hide()
  1080. self.gcode_editor_tab.buttonOpen.hide()
  1081. self.gcode_editor_tab.buttonPrint.hide()
  1082. self.gcode_editor_tab.buttonPreview.hide()
  1083. self.gcode_editor_tab.buttonReplace.hide()
  1084. self.gcode_editor_tab.sel_all_cb.hide()
  1085. self.gcode_editor_tab.entryReplace.hide()
  1086. self.gcode_editor_tab.code_editor.setReadOnly(True)
  1087. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  1088. def on_update_source_file(self):
  1089. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  1090. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  1091. """
  1092. Will create a header to be added to all GCode files generated by FlatCAM
  1093. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  1094. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  1095. :return: A string with a GCode header
  1096. """
  1097. log.debug("FlatCAMCNCJob.gcode_header()")
  1098. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1099. marlin = False
  1100. hpgl = False
  1101. probe_pp = False
  1102. gcode = ''
  1103. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  1104. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  1105. try:
  1106. for key in self.cnc_tools:
  1107. ppg = self.cnc_tools[key]['data']['ppname_g']
  1108. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  1109. marlin = True
  1110. break
  1111. if ppg == 'hpgl':
  1112. hpgl = True
  1113. break
  1114. if "toolchange_probe" in ppg.lower():
  1115. probe_pp = True
  1116. break
  1117. except KeyError:
  1118. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  1119. pass
  1120. try:
  1121. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  1122. marlin = True
  1123. except KeyError:
  1124. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1125. pass
  1126. try:
  1127. if "toolchange_probe" in self.options['ppname_e'].lower():
  1128. probe_pp = True
  1129. except KeyError:
  1130. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1131. pass
  1132. if marlin is True:
  1133. gcode += ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  1134. (str(self.app.version), str(self.app.version_date)) + '\n'
  1135. gcode += ';Name: ' + str(self.options['name']) + '\n'
  1136. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  1137. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1138. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1139. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  1140. gcode += ';Created on ' + time_str + '\n' + '\n'
  1141. elif hpgl is True:
  1142. gcode += 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  1143. (str(self.app.version), str(self.app.version_date)) + '";\n'
  1144. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  1145. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  1146. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1147. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1148. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  1149. gcode += 'CO "Created on ' + time_str + '";\n'
  1150. elif probe_pp is True:
  1151. gcode += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1152. (str(self.app.version), str(self.app.version_date)) + '\n'
  1153. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  1154. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  1155. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  1156. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  1157. 'Then zero the Z axis.)\n' + '\n'
  1158. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  1159. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  1160. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1161. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1162. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1163. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1164. else:
  1165. gcode += '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  1166. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  1167. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  1168. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  1169. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1170. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1171. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  1172. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  1173. return gcode
  1174. @staticmethod
  1175. def gcode_footer(end_command=None):
  1176. """
  1177. Will add the M02 to the end of GCode, if requested.
  1178. :param end_command: 'M02' or 'M30' - String
  1179. :return:
  1180. """
  1181. if end_command:
  1182. return end_command
  1183. else:
  1184. return 'M02'
  1185. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  1186. """
  1187. This will save the GCode from the Gcode object to a file on the OS filesystem
  1188. :param filename: filename for the GCode file
  1189. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  1190. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  1191. :param to_file: if False then no actual file is saved but the app will know that a file was created
  1192. :param from_tcl: True if run from Tcl Shell
  1193. :return: None
  1194. """
  1195. # gcode = ''
  1196. # roland = False
  1197. # hpgl = False
  1198. # isel_icp = False
  1199. include_header = True
  1200. if preamble == '':
  1201. preamble = self.app.defaults["cncjob_prepend"]
  1202. if postamble == '':
  1203. preamble = self.app.defaults["cncjob_append"]
  1204. try:
  1205. if self.special_group:
  1206. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  1207. (_("This CNCJob object can't be processed because it is a"),
  1208. str(self.special_group),
  1209. _("CNCJob object")))
  1210. return 'fail'
  1211. except AttributeError:
  1212. pass
  1213. # if this dict is not empty then the object is a Geometry object
  1214. if self.cnc_tools:
  1215. first_key = next(iter(self.cnc_tools))
  1216. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  1217. # if this dict is not empty then the object is an Excellon object
  1218. if self.exc_cnc_tools:
  1219. first_key = next(iter(self.exc_cnc_tools))
  1220. include_header = self.app.preprocessors[
  1221. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  1222. ].include_header
  1223. gcode = ''
  1224. if include_header is False:
  1225. g = preamble
  1226. # detect if using multi-tool and make the Gcode summation correctly for each case
  1227. if self.multitool is True:
  1228. for tooluid_key in self.cnc_tools:
  1229. for key, value in self.cnc_tools[tooluid_key].items():
  1230. if key == 'gcode':
  1231. gcode += value
  1232. break
  1233. else:
  1234. gcode += self.gcode
  1235. g = g + gcode + postamble
  1236. else:
  1237. # search for the GCode beginning which is usually a G20 or G21
  1238. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  1239. # g_idx = gcode.rfind('G20')
  1240. #
  1241. # # if it did not find 'G20' then search for 'G21'
  1242. # if g_idx == -1:
  1243. # g_idx = gcode.rfind('G21')
  1244. #
  1245. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  1246. # if g_idx == -1:
  1247. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  1248. # return
  1249. # detect if using multi-tool and make the Gcode summation correctly for each case
  1250. if self.multitool is True:
  1251. if self.origin_kind == 'excellon':
  1252. for tooluid_key in self.exc_cnc_tools:
  1253. for key, value in self.exc_cnc_tools[tooluid_key].items():
  1254. if key == 'gcode' and value:
  1255. gcode += value
  1256. break
  1257. else:
  1258. for tooluid_key in self.cnc_tools:
  1259. for key, value in self.cnc_tools[tooluid_key].items():
  1260. if key == 'gcode' and value:
  1261. gcode += value
  1262. break
  1263. else:
  1264. gcode += self.gcode
  1265. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  1266. # detect if using a HPGL preprocessor
  1267. hpgl = False
  1268. if self.cnc_tools:
  1269. for key in self.cnc_tools:
  1270. if 'ppname_g' in self.cnc_tools[key]['data']:
  1271. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  1272. hpgl = True
  1273. break
  1274. elif self.exc_cnc_tools:
  1275. for key in self.cnc_tools:
  1276. if 'ppname_e' in self.cnc_tools[key]['data']:
  1277. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  1278. hpgl = True
  1279. break
  1280. if hpgl:
  1281. processed_gcode = ''
  1282. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  1283. for gline in gcode.splitlines():
  1284. match = pa_re.search(gline)
  1285. if match:
  1286. x_int = int(float(match.group(1)))
  1287. y_int = int(float(match.group(2)))
  1288. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  1289. processed_gcode += new_line
  1290. else:
  1291. processed_gcode += gline + '\n'
  1292. gcode = processed_gcode
  1293. g = self.gc_header + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  1294. else:
  1295. try:
  1296. g_idx = gcode.index('G94')
  1297. if preamble != '' and postamble != '':
  1298. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1299. gcode[(g_idx + 3):] + postamble + end_gcode
  1300. elif preamble == '':
  1301. g = self.gc_header + gcode[:g_idx + 3] + '\n' + \
  1302. gcode[(g_idx + 3):] + postamble + end_gcode
  1303. elif postamble == '':
  1304. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1305. gcode[(g_idx + 3):] + end_gcode
  1306. else:
  1307. g = self.gc_header + gcode[:g_idx + 3] + gcode[(g_idx + 3):] + end_gcode
  1308. except ValueError:
  1309. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1310. _("G-code does not have a G94 code.\n"
  1311. "Append Code snippet will not be used.."))
  1312. g = self.gc_header + '\n' + gcode + postamble + end_gcode
  1313. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  1314. # if self.ui.toolchange_cb.get_value() is True:
  1315. # # match = self.re_toolchange.search(g)
  1316. # if 'M6' in g:
  1317. # m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  1318. # if m6_code is None or m6_code == '':
  1319. # self.app.inform.emit(
  1320. # '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  1321. # )
  1322. # return 'fail'
  1323. #
  1324. # g = g.replace('M6', m6_code)
  1325. # self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  1326. lines = StringIO(g)
  1327. # Write
  1328. if filename is not None:
  1329. try:
  1330. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1331. if force_windows_line_endings and sys.platform != 'win32':
  1332. with open(filename, 'w', newline='\r\n') as f:
  1333. for line in lines:
  1334. f.write(line)
  1335. else:
  1336. with open(filename, 'w') as f:
  1337. for line in lines:
  1338. f.write(line)
  1339. except FileNotFoundError:
  1340. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1341. return
  1342. except PermissionError:
  1343. self.app.inform.emit(
  1344. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1345. "Most likely another app is holding the file open and not accessible.")
  1346. )
  1347. return 'fail'
  1348. elif to_file is False:
  1349. # Just for adding it to the recent files list.
  1350. if self.app.defaults["global_open_style"] is False:
  1351. self.app.file_opened.emit("cncjob", filename)
  1352. self.app.file_saved.emit("cncjob", filename)
  1353. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  1354. else:
  1355. return lines
  1356. # def on_toolchange_custom_clicked(self, signal):
  1357. # """
  1358. # Handler for clicking toolchange custom.
  1359. #
  1360. # :param signal:
  1361. # :return:
  1362. # """
  1363. #
  1364. # try:
  1365. # if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  1366. # if self.ui.toolchange_cb.get_value():
  1367. # self.ui.toolchange_cb.set_value(False)
  1368. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1369. # _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  1370. # except KeyError:
  1371. # try:
  1372. # for key in self.cnc_tools:
  1373. # ppg = self.cnc_tools[key]['data']['ppname_g']
  1374. # if 'toolchange_custom' not in str(ppg).lower():
  1375. # if self.ui.toolchange_cb.get_value():
  1376. # self.ui.toolchange_cb.set_value(False)
  1377. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1378. # _("The used preprocessor file has to have in it's name: "
  1379. # "'toolchange_custom'"))
  1380. # except KeyError:
  1381. # self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  1382. def get_gcode(self, preamble='', postamble=''):
  1383. """
  1384. We need this to be able to get_gcode separately for shell command export_gcode
  1385. :param preamble: Extra GCode added to the beginning of the GCode
  1386. :param postamble: Extra GCode added at the end of the GCode
  1387. :return: The modified GCode
  1388. """
  1389. return preamble + '\n' + self.gcode + "\n" + postamble
  1390. def get_svg(self):
  1391. # we need this to be able get_svg separately for shell command export_svg
  1392. pass
  1393. def on_plot_cb_click(self, *args):
  1394. """
  1395. Handler for clicking on the Plot checkbox.
  1396. :param args:
  1397. :return:
  1398. """
  1399. if self.muted_ui:
  1400. return
  1401. kind = self.ui.cncplot_method_combo.get_value()
  1402. self.plot(kind=kind)
  1403. self.read_form_item('plot')
  1404. self.ui_disconnect()
  1405. cb_flag = self.ui.plot_cb.isChecked()
  1406. for row in range(self.ui.cnc_tools_table.rowCount()):
  1407. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  1408. if cb_flag:
  1409. table_cb.setChecked(True)
  1410. else:
  1411. table_cb.setChecked(False)
  1412. self.ui_connect()
  1413. def on_plot_cb_click_table(self):
  1414. """
  1415. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  1416. tool/aperture found on that row.
  1417. :return:
  1418. """
  1419. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1420. self.ui_disconnect()
  1421. # cw = self.sender()
  1422. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  1423. # cw_row = cw_index.row()
  1424. kind = self.ui.cncplot_method_combo.get_value()
  1425. self.shapes.clear(update=True)
  1426. if self.origin_kind == "excellon":
  1427. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  1428. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  1429. for tooluid_key in self.exc_cnc_tools:
  1430. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  1431. if row_dia == tooldia:
  1432. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  1433. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  1434. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1435. else:
  1436. for tooluid_key in self.cnc_tools:
  1437. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1438. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1439. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  1440. for r in range(self.ui.cnc_tools_table.rowCount()):
  1441. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  1442. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  1443. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1444. self.shapes.redraw()
  1445. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1446. # if all the row plot's are enabled also enable the general plot checkbox
  1447. cb_cnt = 0
  1448. total_row = self.ui.cnc_tools_table.rowCount()
  1449. for row in range(total_row):
  1450. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  1451. cb_cnt += 1
  1452. else:
  1453. cb_cnt -= 1
  1454. if cb_cnt < total_row:
  1455. self.ui.plot_cb.setChecked(False)
  1456. else:
  1457. self.ui.plot_cb.setChecked(True)
  1458. self.ui_connect()
  1459. def plot(self, visible=None, kind='all'):
  1460. """
  1461. # Does all the required setup and returns False
  1462. # if the 'ptint' option is set to False.
  1463. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  1464. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  1465. :return: None
  1466. """
  1467. if not FlatCAMObj.plot(self):
  1468. return
  1469. visible = visible if visible else self.options['plot']
  1470. if self.app.is_legacy is False:
  1471. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  1472. self.text_col.enabled = True
  1473. else:
  1474. self.text_col.enabled = False
  1475. self.annotation.redraw()
  1476. try:
  1477. if self.multitool is False: # single tool usage
  1478. try:
  1479. dia_plot = float(self.options["tooldia"])
  1480. except ValueError:
  1481. # we may have a tuple with only one element and a comma
  1482. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  1483. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  1484. else:
  1485. # I do this so the travel lines thickness will reflect the tool diameter
  1486. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  1487. # don't know the origin
  1488. if self.origin_kind == "excellon":
  1489. if self.exc_cnc_tools:
  1490. for tooldia_key in self.exc_cnc_tools:
  1491. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  1492. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  1493. if not gcode_parsed:
  1494. continue
  1495. # gcode_parsed = self.gcode_parsed
  1496. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1497. else:
  1498. # multiple tools usage
  1499. if self.cnc_tools:
  1500. for tooluid_key in self.cnc_tools:
  1501. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1502. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1503. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1504. self.shapes.redraw()
  1505. except (ObjectDeleted, AttributeError):
  1506. self.shapes.clear(update=True)
  1507. if self.app.is_legacy is False:
  1508. self.annotation.clear(update=True)
  1509. def on_annotation_change(self):
  1510. """
  1511. Handler for toggling the annotation display by clicking a checkbox.
  1512. :return:
  1513. """
  1514. if self.app.is_legacy is False:
  1515. if self.ui.annotation_cb.get_value():
  1516. self.text_col.enabled = True
  1517. else:
  1518. self.text_col.enabled = False
  1519. # kind = self.ui.cncplot_method_combo.get_value()
  1520. # self.plot(kind=kind)
  1521. self.annotation.redraw()
  1522. else:
  1523. kind = self.ui.cncplot_method_combo.get_value()
  1524. self.plot(kind=kind)
  1525. def convert_units(self, units):
  1526. """
  1527. Units conversion used by the CNCJob objects.
  1528. :param units: Can be "MM" or "IN"
  1529. :return:
  1530. """
  1531. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  1532. factor = CNCjob.convert_units(self, units)
  1533. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  1534. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  1535. 'endz', 'toolchangez']
  1536. temp_tools_dict = {}
  1537. tool_dia_copy = {}
  1538. data_copy = {}
  1539. for tooluid_key, tooluid_value in self.cnc_tools.items():
  1540. for dia_key, dia_value in tooluid_value.items():
  1541. if dia_key == 'tooldia':
  1542. dia_value *= factor
  1543. dia_value = float('%.*f' % (self.decimals, dia_value))
  1544. tool_dia_copy[dia_key] = dia_value
  1545. if dia_key == 'offset':
  1546. tool_dia_copy[dia_key] = dia_value
  1547. if dia_key == 'offset_value':
  1548. dia_value *= factor
  1549. tool_dia_copy[dia_key] = dia_value
  1550. if dia_key == 'type':
  1551. tool_dia_copy[dia_key] = dia_value
  1552. if dia_key == 'tool_type':
  1553. tool_dia_copy[dia_key] = dia_value
  1554. if dia_key == 'data':
  1555. for data_key, data_value in dia_value.items():
  1556. # convert the form fields that are convertible
  1557. for param in param_list:
  1558. if data_key == param and data_value is not None:
  1559. data_copy[data_key] = data_value * factor
  1560. # copy the other dict entries that are not convertible
  1561. if data_key not in param_list:
  1562. data_copy[data_key] = data_value
  1563. tool_dia_copy[dia_key] = deepcopy(data_copy)
  1564. data_copy.clear()
  1565. if dia_key == 'gcode':
  1566. tool_dia_copy[dia_key] = dia_value
  1567. if dia_key == 'gcode_parsed':
  1568. tool_dia_copy[dia_key] = dia_value
  1569. if dia_key == 'solid_geometry':
  1570. tool_dia_copy[dia_key] = dia_value
  1571. # if dia_key == 'solid_geometry':
  1572. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  1573. # if dia_key == 'gcode_parsed':
  1574. # for g in dia_value:
  1575. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1576. #
  1577. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  1578. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  1579. temp_tools_dict.update({
  1580. tooluid_key: deepcopy(tool_dia_copy)
  1581. })
  1582. tool_dia_copy.clear()
  1583. self.cnc_tools.clear()
  1584. self.cnc_tools = deepcopy(temp_tools_dict)