FlatCAMCNCJob.py 90 KB

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