FlatCAMCNCJob.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  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. # Zero
  483. self.ui.zero_axs_wdg.grbl_zerox_button.clicked.connect(lambda: self.on_grbl_zero(axis='x'))
  484. self.ui.zero_axs_wdg.grbl_zeroy_button.clicked.connect(lambda: self.on_grbl_zero(axis='y'))
  485. self.ui.zero_axs_wdg.grbl_zeroz_button.clicked.connect(lambda: self.on_grbl_zero(axis='z'))
  486. self.ui.zero_axs_wdg.grbl_zero_all_button.clicked.connect(lambda: self.on_grbl_zero(axis='all'))
  487. self.ui.zero_axs_wdg.grbl_homing_button.clicked.connect(self.on_grbl_homing)
  488. # Sender
  489. self.ui.grbl_report_button.clicked.connect(lambda: self.send_grbl_command(command='?'))
  490. self.ui.grbl_get_param_button.clicked.connect(
  491. lambda: self.get_grbl_parameter(param=self.ui.grbl_parameter_entry.get_value()))
  492. self.ui.view_h_gcode_button.clicked.connect(self.on_view_probing_gcode)
  493. self.ui.h_gcode_button.clicked.connect(self.on_generate_probing_gcode)
  494. self.ui.import_heights_button.clicked.connect(self.on_import_height_map)
  495. self.ui.pause_resume_button.clicked.connect(self.on_grbl_pause_resume)
  496. self.build_al_table_sig.connect(self.build_al_table)
  497. # self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  498. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  499. # Show/Hide Advanced Options
  500. if self.app.defaults["global_app_level"] == 'b':
  501. self.ui.level.setText(_(
  502. '<span style="color:green;"><b>Basic</b></span>'
  503. ))
  504. self.ui.sal_cb.hide()
  505. self.ui.sal_cb.set_value(False)
  506. else:
  507. self.ui.level.setText(_(
  508. '<span style="color:red;"><b>Advanced</b></span>'
  509. ))
  510. self.ui.sal_cb.show()
  511. self.ui.sal_cb.set_value(self.app.defaults["cncjob_al_status"])
  512. preamble = self.append_snippet
  513. postamble = self.prepend_snippet
  514. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  515. self.source_file = gc.getvalue()
  516. self.ui.al_mode_radio.set_value(self.options['al_mode'])
  517. self.on_controller_change()
  518. # def on_cnc_custom_parameters(self, signal_text):
  519. # if signal_text == 'Parameters':
  520. # return
  521. # else:
  522. # self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  523. def ui_connect(self):
  524. for row in range(self.ui.cnc_tools_table.rowCount()):
  525. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  526. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  527. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  528. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  529. self.ui.al_add_button.clicked.connect(self.on_add_al_probepoints)
  530. self.ui.show_al_table.stateChanged.connect(self.on_show_al_table)
  531. def ui_disconnect(self):
  532. for row in range(self.ui.cnc_tools_table.rowCount()):
  533. try:
  534. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  535. except (TypeError, AttributeError):
  536. pass
  537. for row in range(self.ui.exc_cnc_tools_table.rowCount()):
  538. try:
  539. self.ui.exc_cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  540. except (TypeError, AttributeError):
  541. pass
  542. try:
  543. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  544. except (TypeError, AttributeError):
  545. pass
  546. try:
  547. self.ui.al_add_button.clicked.disconnect()
  548. except (TypeError, AttributeError):
  549. pass
  550. try:
  551. self.ui.show_al_table.stateChanged.disconnect()
  552. except (TypeError, AttributeError):
  553. pass
  554. def on_add_al_probepoints(self):
  555. # create the solid_geo
  556. self.solid_geo = unary_union([geo['geom'] for geo in self.gcode_parsed if geo['kind'][0] == 'C'])
  557. # reset al table
  558. self.ui.al_probe_points_table.setRowCount(0)
  559. # reset the al dict
  560. self.al_geometry_dict.clear()
  561. xmin, ymin, xmax, ymax = self.solid_geo.bounds
  562. if self.ui.al_mode_radio.get_value() == 'grid':
  563. width = abs(xmax - xmin)
  564. height = abs(ymax - ymin)
  565. cols = self.ui.al_columns_entry.get_value()
  566. rows = self.ui.al_rows_entry.get_value()
  567. dx = width / (cols + 1)
  568. dy = height / (rows + 1)
  569. points = []
  570. new_y = ymin
  571. for x in range(rows):
  572. new_y += dy
  573. new_x = xmin
  574. for y in range(cols):
  575. new_x += dx
  576. formatted_point = (
  577. self.app.dec_format(new_x, self.app.decimals),
  578. self.app.dec_format(new_y, self.app.decimals)
  579. )
  580. points.append(formatted_point)
  581. pt_id = 0
  582. pts_list = []
  583. for point in points:
  584. pt_id += 1
  585. pt = Point(point)
  586. pts_list.append(pt)
  587. new_dict = {
  588. 'point': pt,
  589. 'geo': None,
  590. 'height': 0.0
  591. }
  592. self.al_geometry_dict[pt_id] = deepcopy(new_dict)
  593. self.calculate_voronoi_diagram(pts=pts_list)
  594. else:
  595. self.app.inform.emit(_("Click on canvas to add a Test Point..."))
  596. if self.app.is_legacy is False:
  597. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  598. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  599. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  600. else:
  601. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  602. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  603. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  604. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  605. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  606. self.mouse_events_connected = True
  607. self.build_al_table_sig.emit()
  608. def show_voronoi_diagram(self, state):
  609. if state:
  610. pass
  611. else:
  612. pass
  613. def calculate_voronoi_diagram(self, pts):
  614. pts_union = MultiPoint(pts)
  615. env = self.solid_geo.envelope
  616. print(pts_union.wkt)
  617. try:
  618. voronoi_union = voronoi_diagram(geom=pts_union, envelope=env)
  619. print(voronoi_union)
  620. except Exception as e:
  621. log.debug("CNCJobObject.calculate_voronoi_diagram() --> %s" % str(e))
  622. return
  623. for pt_key in list(self.al_geometry_dict.keys()):
  624. for poly in voronoi_union:
  625. if self.al_geometry_dict[pt_key]['point'].within(poly):
  626. self.al_geometry_dict[pt_key]['geo'] = poly
  627. # To be called after clicking on the plot.
  628. def on_mouse_click_release(self, event):
  629. if self.app.is_legacy is False:
  630. event_pos = event.pos
  631. # event_is_dragging = event.is_dragging
  632. right_button = 2
  633. else:
  634. event_pos = (event.xdata, event.ydata)
  635. # event_is_dragging = self.app.plotcanvas.is_dragging
  636. right_button = 3
  637. try:
  638. x = float(event_pos[0])
  639. y = float(event_pos[1])
  640. except TypeError:
  641. return
  642. event_pos = (x, y)
  643. # do paint single only for left mouse clicks
  644. if event.button == 1:
  645. pos = self.app.plotcanvas.translate_coords(event_pos)
  646. # use the snapped position as reference
  647. snapped_pos = self.app.geo_editor.snap(pos[0], pos[1])
  648. if not self.al_geometry_dict:
  649. new_dict = {
  650. 'point': Point(snapped_pos),
  651. 'geo': None,
  652. 'height': 0.0
  653. }
  654. self.al_geometry_dict[1] = deepcopy(new_dict)
  655. else:
  656. int_keys = [int(k) for k in self.al_geometry_dict.keys()]
  657. new_id = max(int_keys) + 1
  658. new_dict = {
  659. 'point': Point(snapped_pos),
  660. 'geo': None,
  661. 'height': 0.0
  662. }
  663. self.al_geometry_dict[new_id] = deepcopy(new_dict)
  664. # rebuild the al table
  665. self.build_al_table_sig.emit()
  666. self.app.inform.emit(_("Added Test Point... Click again to add another or right click to finish ..."))
  667. # if RMB then we exit
  668. elif event.button == right_button and self.mouse_is_dragging is False:
  669. if self.app.is_legacy is False:
  670. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  671. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  672. else:
  673. self.app.plotcanvas.graph_event_disconnect(self.kp)
  674. self.app.plotcanvas.graph_event_disconnect(self.mr)
  675. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  676. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  677. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  678. self.app.on_mouse_click_release_over_plot)
  679. # signal that the mouse events are disconnected from local methods
  680. self.mouse_events_connected = False
  681. # restore selection
  682. self.app.defaults['global_selection_shape'] = self.old_selection_state
  683. self.app.inform.emit(_("Finished manual adding of Test Point..."))
  684. pts_list = []
  685. for k in self.al_geometry_dict:
  686. pts_list.append(self.al_geometry_dict[k]['point'])
  687. self.calculate_voronoi_diagram(pts=pts_list)
  688. # rebuild the al table
  689. self.build_al_table_sig.emit()
  690. def on_key_press(self, event):
  691. # events out of the self.app.collection view (it's about Project Tab) are of type int
  692. if type(event) is int:
  693. key = event
  694. # events from the GUI are of type QKeyEvent
  695. elif type(event) == QtGui.QKeyEvent:
  696. key = event.key()
  697. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  698. key = event.key
  699. key = QtGui.QKeySequence(key)
  700. # check for modifiers
  701. key_string = key.toString().lower()
  702. if '+' in key_string:
  703. mod, __, key_text = key_string.rpartition('+')
  704. if mod.lower() == 'ctrl':
  705. # modifiers = QtCore.Qt.ControlModifier
  706. pass
  707. elif mod.lower() == 'alt':
  708. # modifiers = QtCore.Qt.AltModifier
  709. pass
  710. elif mod.lower() == 'shift':
  711. # modifiers = QtCore.Qt.ShiftModifier
  712. pass
  713. else:
  714. # modifiers = QtCore.Qt.NoModifier
  715. pass
  716. key = QtGui.QKeySequence(key_text)
  717. # events from Vispy are of type KeyEvent
  718. else:
  719. key = event.key
  720. # Escape = Deselect All
  721. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  722. if self.mouse_events_connected is True:
  723. self.mouse_events_connected = False
  724. if self.app.is_legacy is False:
  725. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  726. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  727. else:
  728. self.app.plotcanvas.graph_event_disconnect(self.kp)
  729. self.app.plotcanvas.graph_event_disconnect(self.mr)
  730. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  731. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  732. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  733. self.app.on_mouse_click_release_over_plot)
  734. if self.ui.big_cursor_cb.get_value():
  735. # restore cursor
  736. self.app.on_cursor_type(val=self.old_cursor_type)
  737. # restore selection
  738. self.app.defaults['global_selection_shape'] = self.old_selection_state
  739. # Grid toggle
  740. if key == QtCore.Qt.Key_G or key == 'G':
  741. self.app.ui.grid_snap_btn.trigger()
  742. # Jump to coords
  743. if key == QtCore.Qt.Key_J or key == 'J':
  744. l_x, l_y = self.app.on_jump_to()
  745. def on_autolevelling(self, state):
  746. self.ui.al_frame.show() if state else self.ui.al_frame.hide()
  747. self.app.defaults["cncjob_al_status"] = True if state else False
  748. def on_show_al_table(self, state):
  749. self.ui.al_probe_points_table.show() if state else self.ui.al_probe_points_table.hide()
  750. def on_mode_radio(self, val):
  751. # reset al table
  752. self.ui.al_probe_points_table.setRowCount(0)
  753. # reset the al dict
  754. self.al_geometry_dict.clear()
  755. # build AL table
  756. self.build_al_table()
  757. if val == "manual":
  758. self.ui.al_rows_entry.setDisabled(True)
  759. self.ui.al_rows_label.setDisabled(True)
  760. self.ui.al_columns_entry.setDisabled(True)
  761. self.ui.al_columns_label.setDisabled(True)
  762. else:
  763. self.ui.al_rows_entry.setDisabled(False)
  764. self.ui.al_rows_label.setDisabled(False)
  765. self.ui.al_columns_entry.setDisabled(False)
  766. self.ui.al_columns_label.setDisabled(False)
  767. def on_controller_change(self):
  768. if self.ui.al_controller_combo.get_value() == 'GRBL':
  769. self.ui.h_gcode_button.hide()
  770. self.ui.view_h_gcode_button.hide()
  771. self.ui.import_heights_button.hide()
  772. self.ui.grbl_frame.show()
  773. self.on_search_ports(muted=True)
  774. else:
  775. self.ui.h_gcode_button.show()
  776. self.ui.view_h_gcode_button.show()
  777. self.ui.import_heights_button.show()
  778. self.ui.grbl_frame.hide()
  779. def list_serial_ports(self):
  780. """
  781. Lists serial port names.
  782. From here: https://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
  783. :raises EnvironmentError: On unsupported or unknown platforms
  784. :returns: A list of the serial ports available on the system
  785. """
  786. if sys.platform.startswith('win'):
  787. ports = ['COM%s' % (i + 1) for i in range(256)]
  788. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  789. # this excludes your current terminal "/dev/tty"
  790. ports = glob.glob('/dev/tty[A-Za-z]*')
  791. elif sys.platform.startswith('darwin'):
  792. ports = glob.glob('/dev/tty.*')
  793. else:
  794. raise EnvironmentError('Unsupported platform')
  795. result = []
  796. s = serial.Serial()
  797. for port in ports:
  798. s.port = port
  799. try:
  800. s.open()
  801. s.close()
  802. result.append(port)
  803. except (OSError, serial.SerialException):
  804. # result.append(port + " (in use)")
  805. pass
  806. return result
  807. def on_search_ports(self, muted=None):
  808. port_list = self.list_serial_ports()
  809. self.ui.com_list_combo.clear()
  810. self.ui.com_list_combo.addItems(port_list)
  811. if muted is not True:
  812. self.app.inform.emit('[WARNING_NOTCL] %s' % _("COM list updated ..."))
  813. def on_connect_grbl(self):
  814. port_name = self.ui.com_list_combo.currentText()
  815. if " (" in port_name:
  816. port_name = port_name.rpartition(" (")[0]
  817. baudrate = int(self.ui.baudrates_list_combo.currentText())
  818. try:
  819. self.grbl_ser_port = serial.serial_for_url(port_name, baudrate,
  820. bytesize=serial.EIGHTBITS,
  821. parity=serial.PARITY_NONE,
  822. stopbits=serial.STOPBITS_ONE,
  823. timeout=0.1,
  824. xonxoff=False,
  825. rtscts=False)
  826. # Toggle DTR to reset the controller loaded with GRBL (Arduino, ESP32, etc)
  827. try:
  828. self.grbl_ser_port.dtr = False
  829. except IOError:
  830. pass
  831. self.grbl_ser_port.reset_input_buffer()
  832. try:
  833. self.grbl_ser_port.dtr = True
  834. except IOError:
  835. pass
  836. answer = self.wake_grbl()
  837. answer = ['ok'] # hack for development without a GRBL controller connected
  838. for line in answer:
  839. if 'ok' in line.lower():
  840. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: seagreen;}")
  841. self.ui.com_connect_button.setText(_("Connected"))
  842. self.ui.controller_reset_button.setDisabled(False)
  843. for idx in range(self.ui.al_toolbar.count()):
  844. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  845. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('seagreen'))
  846. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  847. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  848. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  849. self.ui.al_toolbar.tabBar.setTabEnabled(idx, True)
  850. self.app.inform.emit("%s: %s" % (_("Port connected"), port_name))
  851. return
  852. self.grbl_ser_port.close()
  853. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to GRBL on port"), port_name))
  854. except serial.SerialException:
  855. self.grbl_ser_port = serial.Serial()
  856. self.grbl_ser_port.port = port_name
  857. self.grbl_ser_port.close()
  858. self.ui.com_connect_button.setStyleSheet("QPushButton {background-color: red;}")
  859. self.ui.com_connect_button.setText(_("Disconnected"))
  860. self.ui.controller_reset_button.setDisabled(True)
  861. for idx in range(self.ui.al_toolbar.count()):
  862. if self.ui.al_toolbar.tabText(idx) == _("Connect"):
  863. self.ui.al_toolbar.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  864. if self.ui.al_toolbar.tabText(idx) == _("Control"):
  865. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  866. if self.ui.al_toolbar.tabText(idx) == _("Sender"):
  867. self.ui.al_toolbar.tabBar.setTabEnabled(idx, False)
  868. self.app.inform.emit("%s: %s" % (_("Port is connected. Disconnecting"), port_name))
  869. except Exception:
  870. self.app.inform.emit("[ERROR_NOTCL] %s: %s" % (_("Could not connect to port"), port_name))
  871. def on_add_baudrate_grbl(self):
  872. new_bd = str(self.ui.new_baudrate_entry.get_value())
  873. if int(new_bd) >= 40 and new_bd not in self.ui.baudrates_list_combo.model().stringList():
  874. self.ui.baudrates_list_combo.addItem(new_bd)
  875. self.ui.baudrates_list_combo.setCurrentText(new_bd)
  876. def on_delete_baudrate_grbl(self):
  877. current_idx = self.ui.baudrates_list_combo.currentIndex()
  878. self.ui.baudrates_list_combo.removeItem(current_idx)
  879. def wake_grbl(self):
  880. # Wake up grbl
  881. self.grbl_ser_port.write("\r\n\r\n".encode('utf-8'))
  882. # Wait for GRBL controller to initialize
  883. time.sleep(1)
  884. grbl_out = deepcopy(self.grbl_ser_port.readlines())
  885. self.grbl_ser_port.reset_input_buffer()
  886. return grbl_out
  887. def on_send_grbl_command(self):
  888. cmd = self.ui.grbl_command_entry.get_value()
  889. # show the Shell Dock
  890. self.app.ui.shell_dock.show()
  891. def worker_task():
  892. with self.app.proc_container.new(_("Sending GCode...")):
  893. self.send_grbl_command(command=cmd)
  894. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  895. def send_grbl_command(self, command, echo=True):
  896. stripped_cmd = command.strip()
  897. cmd = stripped_cmd.rpartition('\n')[0]
  898. if echo:
  899. self.app.inform_shell[str, bool].emit(cmd, False)
  900. # Send Gcode command to GRBL
  901. snd = cmd + '\n'
  902. self.grbl_ser_port.write(snd.encode('utf-8'))
  903. grbl_out = self.grbl_ser_port.readlines()
  904. result = False
  905. for line in grbl_out:
  906. if echo:
  907. try:
  908. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  909. except Exception as e:
  910. log.debug("CNCJobObject.send_grbl_command() --> %s" % str(e))
  911. if 'ok' in line:
  912. result = True
  913. return result
  914. def send_grbl_block(self, command, echo=True):
  915. stripped_cmd = command.strip()
  916. for l in stripped_cmd.split('\n'):
  917. if echo:
  918. self.app.inform_shell[str, bool].emit(l, False)
  919. # Send Gcode block to GRBL
  920. snd = l + '\n'
  921. self.grbl_ser_port.write(snd.encode('utf-8'))
  922. grbl_out = self.grbl_ser_port.readlines()
  923. for line in grbl_out:
  924. if echo:
  925. try:
  926. self.app.inform_shell.emit(' : ' + line.decode('utf-8').strip().upper())
  927. except Exception as e:
  928. log.debug("CNCJobObject.send_grbl_block() --> %s" % str(e))
  929. def get_grbl_parameter(self, param):
  930. if '$' in param:
  931. param = param.replace('$','')
  932. snd = '$$\n'
  933. self.grbl_ser_port.write(snd.encode('utf-8'))
  934. grbl_out = self.grbl_ser_port.readlines()
  935. for line in grbl_out:
  936. decoded_line = line.decode('utf-8')
  937. par = '$%s' % str(param)
  938. if par in decoded_line:
  939. result = float(decoded_line.rpartition('=')[2])
  940. self.app.shell_message("GRBL Parameter: %s = %s" % (str(param), str(result)), show=True)
  941. return result
  942. def on_jog(self, direction=None, step=5.0, feedrate=1000.0, travelz=15.0):
  943. if direction is None:
  944. return
  945. cmd = ''
  946. if direction == 'xplus':
  947. cmd = "$J=G91 %s X%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  948. if direction == 'xminus':
  949. cmd = "$J=G91 %s X-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  950. if direction == 'yplus':
  951. cmd = "$J=G91 %s Y%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  952. if direction == 'yminus':
  953. cmd = "$J=G91 %s Y-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  954. if direction == 'zplus':
  955. cmd = "$J=G91 %s Z%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  956. if direction == 'zminus':
  957. cmd = "$J=G91 %s Z-%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(step), str(feedrate))
  958. if direction == 'origin':
  959. cmd = "$J=G90 %s Z%s F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(travelz), str(feedrate))
  960. self.send_grbl_command(command=cmd, echo=False)
  961. cmd = "$J=G90 %s X0.0 Y0.0 F%s" % ({'IN': 'G20', 'MM': 'G21'}[self.units], str(feedrate))
  962. self.send_grbl_command(command=cmd, echo=False)
  963. return
  964. self.send_grbl_command(command=cmd, echo=False)
  965. def on_grbl_zero(self, axis):
  966. current_mode = self.get_grbl_parameter('10')
  967. if current_mode is None:
  968. return
  969. cmd = '$10=0'
  970. self.send_grbl_command(command=cmd, echo=False)
  971. if axis == 'x':
  972. cmd = 'G10 L2 P1 X0'
  973. elif axis == 'y':
  974. cmd = 'G10 L2 P1 Y0'
  975. elif axis == 'z':
  976. cmd = 'G10 L2 P1 Z0'
  977. else:
  978. # all
  979. cmd = 'G10 L2 P1 X0 Y0 Z0'
  980. self.send_grbl_command(command=cmd, echo=False)
  981. # restore previous mode
  982. cmd = '$10=%d' % int(current_mode)
  983. self.send_grbl_command(command=cmd, echo=False)
  984. def on_grbl_homing(self):
  985. cmd = '$H'
  986. self.app.inform.emit("%s" % _("GRBL is doing a home cycle."))
  987. self.wake_grbl()
  988. self.send_grbl_command(command=cmd)
  989. def on_grbl_reset(self):
  990. cmd = '\x18'
  991. self.app.inform.emit("%s" % _("GRBL software reset was sent."))
  992. self.wake_grbl()
  993. self.send_grbl_command(command=cmd)
  994. def on_grbl_pause_resume(self, checked):
  995. if checked is False:
  996. cmd = '~'
  997. self.send_grbl_command(command=cmd)
  998. self.app.inform.emit("%s" % _("GRBL resumed."))
  999. else:
  1000. cmd = '!'
  1001. self.send_grbl_command(command=cmd)
  1002. self.app.inform.emit("%s" % _("GRBL paused."))
  1003. def probing_gcode(self, coords, pr_travel, probe_fr, pr_depth, controller):
  1004. """
  1005. :param coords: a list of (x, y) tuples of probe points coordinates
  1006. :type coords: list
  1007. :param pr_travel: the height (z) where the probe travel between probe points
  1008. :type pr_travel: float
  1009. :param probe_fr: feedrate when probing
  1010. :type probe_fr: float
  1011. :param pr_depth: how much to lower the probe searching for contact
  1012. :type pr_depth: float
  1013. :param controller: a string with the name of the GCode sender for which to create the probing GCode.
  1014. Can be: 'MACH3', 'MACH4', 'LinuxCNC', 'GRBL'
  1015. :type controller: str
  1016. :return: Probing GCode
  1017. :rtype: str
  1018. """
  1019. p_gcode = ''
  1020. header = ''
  1021. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1022. header += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1023. (str(self.app.version), str(self.app.version_date)) + '\n'
  1024. header += '(This is a autolevelling probing GCode.)\n' \
  1025. '(Make sure that before you start the job you first do a zero for all axis.)\n\n'
  1026. header += '(Name: ' + str(self.options['name']) + ')\n'
  1027. header += '(Type: ' + "Autolevelling Probing GCode " + ')\n'
  1028. header += '(Units: ' + self.units.upper() + ')\n'
  1029. header += '(Created on ' + time_str + ')\n'
  1030. # commands
  1031. if controller == 'MACH3':
  1032. probing_command = 'G31'
  1033. # probing_var = '#2002'
  1034. openfile_command = 'M40'
  1035. closefile_command = 'M41'
  1036. elif controller == 'MACH4':
  1037. probing_command = 'G31'
  1038. # probing_var = '#5063'
  1039. openfile_command = 'M40'
  1040. closefile_command = 'M41'
  1041. elif controller == 'LinuxCNC':
  1042. probing_command = 'G38.2'
  1043. # probing_var = '#5422'
  1044. openfile_command = '(PROBEOPEN a_probing_points_file.txt)'
  1045. closefile_command = '(PROBECLOSE)'
  1046. else:
  1047. log.debug("CNCJobObject.probing_gcode() -> controller not supported")
  1048. return
  1049. # #############################################################################################################
  1050. # ########################### GCODE construction ##############################################################
  1051. # #############################################################################################################
  1052. # header
  1053. p_gcode += header + '\n'
  1054. # supplementary message for LinuxCNC
  1055. if controller == 'LinuxCNC':
  1056. p_gcode += "The file with the stored probing points can be found\n" \
  1057. "in the configuration folder for LinuxCNC.\n" \
  1058. "The name of the file is: a_probing_points_file.txt.\n"
  1059. # units
  1060. p_gcode += 'G21\n' if self.units == 'MM' else 'G20\n'
  1061. # reference mode = absolute
  1062. p_gcode += 'G90\n'
  1063. # open a new file
  1064. p_gcode += openfile_command + '\n'
  1065. # move to safe height (probe travel Z)
  1066. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1067. # probing points
  1068. for idx, xy_tuple in enumerate(coords, 1): # index starts from 1
  1069. x = xy_tuple[0]
  1070. y = xy_tuple[1]
  1071. # move to probing point
  1072. p_gcode += "G0 X%sY%s\n" % (
  1073. str(self.app.dec_format(x, self.coords_decimals)),
  1074. str(self.app.dec_format(y, self.coords_decimals))
  1075. )
  1076. # do the probing
  1077. p_gcode += "%s Z%s F%s\n" % (
  1078. probing_command,
  1079. str(self.app.dec_format(pr_depth, self.coords_decimals)),
  1080. str(self.app.dec_format(probe_fr, self.fr_decimals)),
  1081. )
  1082. # store in a global numeric variable the value of the detected probe Z
  1083. # I offset the global numeric variable by 500 so it does not conflict with something else
  1084. # temp_var = int(idx + 500)
  1085. # p_gcode += "#%d = %s\n" % (temp_var, probing_var)
  1086. # move to safe height (probe travel Z)
  1087. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1088. # close the file
  1089. p_gcode += closefile_command + '\n'
  1090. # finish the GCode
  1091. p_gcode += 'M2'
  1092. return p_gcode
  1093. def on_generate_probing_gcode(self):
  1094. coords = []
  1095. for id_key, value in self.al_geometry_dict.items():
  1096. x = value['point'].x
  1097. y = value['point'].y
  1098. coords.append(
  1099. (
  1100. self.app.dec_format(x, dec=self.app.decimals),
  1101. self.app.dec_format(y, dec=self.app.decimals)
  1102. )
  1103. )
  1104. pr_travel = self.ui.ptravelz_entry.get_value()
  1105. probe_fr = self.ui.feedrate_probe_entry.get_value()
  1106. pr_depth = self.ui.pdepth_entry.get_value()
  1107. controller = self.ui.al_controller_combo.get_value()
  1108. self.probing_gcode_text = self.probing_gcode(coords, pr_travel, probe_fr, pr_depth, controller)
  1109. def on_view_probing_gcode(self):
  1110. self.app.proc_container.view.set_busy(_("Loading..."))
  1111. gco = self.probing_gcode_text
  1112. if gco is None or gco == '':
  1113. self.app.inform.emit('[WARNING_NOTCL] %s...' % _('There is nothing to view'))
  1114. return
  1115. self.gcode_viewer_tab = AppTextEditor(app=self.app, plain_text=True)
  1116. # add the tab if it was closed
  1117. self.app.ui.plot_tab_area.addTab(self.gcode_viewer_tab, '%s' % _("Code Viewer"))
  1118. self.gcode_viewer_tab.setObjectName('code_viewer_tab')
  1119. # delete the absolute and relative position and messages in the infobar
  1120. self.app.ui.position_label.setText("")
  1121. self.app.ui.rel_position_label.setText("")
  1122. self.gcode_viewer_tab.code_editor.completer_enable = False
  1123. self.gcode_viewer_tab.buttonRun.hide()
  1124. # Switch plot_area to CNCJob tab
  1125. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_viewer_tab)
  1126. self.gcode_viewer_tab.t_frame.hide()
  1127. # then append the text from GCode to the text editor
  1128. try:
  1129. self.gcode_viewer_tab.load_text(gco, move_to_start=True, clear_text=True)
  1130. except Exception as e:
  1131. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1132. return
  1133. self.gcode_viewer_tab.t_frame.show()
  1134. self.app.proc_container.view.set_idle()
  1135. self.gcode_viewer_tab.buttonSave.hide()
  1136. self.gcode_viewer_tab.buttonOpen.hide()
  1137. self.gcode_viewer_tab.buttonPrint.hide()
  1138. self.gcode_viewer_tab.buttonPreview.hide()
  1139. self.gcode_viewer_tab.buttonReplace.hide()
  1140. self.gcode_viewer_tab.sel_all_cb.hide()
  1141. self.gcode_viewer_tab.entryReplace.hide()
  1142. self.gcode_viewer_tab.code_editor.setReadOnly(True)
  1143. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Viewer'))
  1144. def on_import_height_map(self):
  1145. """
  1146. Import the height map file into the app
  1147. :return:
  1148. :rtype:
  1149. """
  1150. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  1151. try:
  1152. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1153. directory=self.app.get_last_folder(),
  1154. filter=_filter_)
  1155. except TypeError:
  1156. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1157. filter=_filter_)
  1158. filename = str(filename)
  1159. if filename == '':
  1160. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1161. else:
  1162. self.app.worker_task.emit({'fcn': self.import_height_map, 'params': [filename]})
  1163. def import_height_map(self, filename):
  1164. """
  1165. :param filename:
  1166. :type filename:
  1167. :return:
  1168. :rtype:
  1169. """
  1170. stream = ''
  1171. try:
  1172. if filename:
  1173. with open(filename, 'r') as f:
  1174. stream = f.readlines()
  1175. else:
  1176. return
  1177. except IOError:
  1178. log.error("Failed to open height map file: %s" % filename)
  1179. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open height map file"), filename))
  1180. return
  1181. idx = 0
  1182. for line in stream:
  1183. if line != '':
  1184. idx += 1
  1185. line = line.replace(' ', ',').replace('\n', '').split(',')
  1186. if idx not in self.al_geometry_dict:
  1187. self.al_geometry_dict[idx] = {}
  1188. self.al_geometry_dict[idx]['height'] = float(line[2])
  1189. if 'point' not in self.al_geometry_dict[idx]:
  1190. x = float(line[0])
  1191. y = float(line[1])
  1192. self.al_geometry_dict[idx]['point'] = Point((x, y))
  1193. self.build_al_table_sig.emit()
  1194. def on_updateplot_button_click(self, *args):
  1195. """
  1196. Callback for the "Updata Plot" button. Reads the form for updates
  1197. and plots the object.
  1198. """
  1199. self.read_form()
  1200. self.on_plot_kind_change()
  1201. def on_plot_kind_change(self):
  1202. kind = self.ui.cncplot_method_combo.get_value()
  1203. def worker_task():
  1204. with self.app.proc_container.new(_("Plotting...")):
  1205. self.plot(kind=kind)
  1206. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1207. def on_exportgcode_button_click(self):
  1208. """
  1209. Handler activated by a button clicked when exporting GCode.
  1210. :param args:
  1211. :return:
  1212. """
  1213. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  1214. self.read_form()
  1215. name = self.app.collection.get_active().options['name']
  1216. save_gcode = False
  1217. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  1218. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  1219. elif 'hpgl' in self.pp_geometry_name:
  1220. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  1221. else:
  1222. save_gcode = True
  1223. _filter_ = self.app.defaults['cncjob_save_filters']
  1224. try:
  1225. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1226. filename, _f = FCFileSaveDialog.get_saved_filename(
  1227. caption=_("Export Code ..."),
  1228. directory=dir_file_to_save,
  1229. ext_filter=_filter_
  1230. )
  1231. except TypeError:
  1232. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1233. self.export_gcode_handler(filename, is_gcode=save_gcode)
  1234. def export_gcode_handler(self, filename, is_gcode=True):
  1235. preamble = ''
  1236. postamble = ''
  1237. filename = str(filename)
  1238. if filename == '':
  1239. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1240. return
  1241. else:
  1242. if is_gcode is True:
  1243. used_extension = filename.rpartition('.')[2]
  1244. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  1245. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  1246. self.ui.name_entry.set_value(new_name)
  1247. self.on_name_activate(silent=True)
  1248. try:
  1249. if self.ui.snippets_cb.get_value():
  1250. preamble = self.append_snippet
  1251. postamble = self.prepend_snippet
  1252. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  1253. except Exception as err:
  1254. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  1255. gc = self.export_gcode(filename)
  1256. if gc == 'fail':
  1257. return
  1258. if self.app.defaults["global_open_style"] is False:
  1259. self.app.file_opened.emit("gcode", filename)
  1260. self.app.file_saved.emit("gcode", filename)
  1261. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  1262. def on_edit_code_click(self, *args):
  1263. """
  1264. Handler activated by a button clicked when reviewing GCode.
  1265. :param args:
  1266. :return:
  1267. """
  1268. self.app.proc_container.view.set_busy(_("Loading..."))
  1269. preamble = self.append_snippet
  1270. postamble = self.prepend_snippet
  1271. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  1272. if gco == 'fail':
  1273. return
  1274. else:
  1275. self.app.gcode_edited = gco
  1276. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  1277. # add the tab if it was closed
  1278. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Review"))
  1279. self.gcode_editor_tab.setObjectName('code_editor_tab')
  1280. # delete the absolute and relative position and messages in the infobar
  1281. self.app.ui.position_label.setText("")
  1282. self.app.ui.rel_position_label.setText("")
  1283. self.gcode_editor_tab.code_editor.completer_enable = False
  1284. self.gcode_editor_tab.buttonRun.hide()
  1285. # Switch plot_area to CNCJob tab
  1286. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  1287. self.gcode_editor_tab.t_frame.hide()
  1288. # then append the text from GCode to the text editor
  1289. try:
  1290. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  1291. except Exception as e:
  1292. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1293. return
  1294. self.gcode_editor_tab.t_frame.show()
  1295. self.app.proc_container.view.set_idle()
  1296. self.gcode_editor_tab.buttonSave.hide()
  1297. self.gcode_editor_tab.buttonOpen.hide()
  1298. self.gcode_editor_tab.buttonPrint.hide()
  1299. self.gcode_editor_tab.buttonPreview.hide()
  1300. self.gcode_editor_tab.buttonReplace.hide()
  1301. self.gcode_editor_tab.sel_all_cb.hide()
  1302. self.gcode_editor_tab.entryReplace.hide()
  1303. self.gcode_editor_tab.code_editor.setReadOnly(True)
  1304. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  1305. def on_update_source_file(self):
  1306. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  1307. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  1308. """
  1309. Will create a header to be added to all GCode files generated by FlatCAM
  1310. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  1311. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  1312. :return: A string with a GCode header
  1313. """
  1314. log.debug("FlatCAMCNCJob.gcode_header()")
  1315. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1316. marlin = False
  1317. hpgl = False
  1318. probe_pp = False
  1319. gcode = ''
  1320. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  1321. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  1322. try:
  1323. for key in self.cnc_tools:
  1324. ppg = self.cnc_tools[key]['data']['ppname_g']
  1325. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  1326. marlin = True
  1327. break
  1328. if ppg == 'hpgl':
  1329. hpgl = True
  1330. break
  1331. if "toolchange_probe" in ppg.lower():
  1332. probe_pp = True
  1333. break
  1334. except KeyError:
  1335. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  1336. pass
  1337. try:
  1338. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  1339. marlin = True
  1340. except KeyError:
  1341. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1342. pass
  1343. try:
  1344. if "toolchange_probe" in self.options['ppname_e'].lower():
  1345. probe_pp = True
  1346. except KeyError:
  1347. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1348. pass
  1349. if marlin is True:
  1350. gcode += ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  1351. (str(self.app.version), str(self.app.version_date)) + '\n'
  1352. gcode += ';Name: ' + str(self.options['name']) + '\n'
  1353. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  1354. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1355. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1356. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  1357. gcode += ';Created on ' + time_str + '\n' + '\n'
  1358. elif hpgl is True:
  1359. gcode += 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  1360. (str(self.app.version), str(self.app.version_date)) + '";\n'
  1361. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  1362. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  1363. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1364. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1365. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  1366. gcode += 'CO "Created on ' + time_str + '";\n'
  1367. elif probe_pp is True:
  1368. gcode += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1369. (str(self.app.version), str(self.app.version_date)) + '\n'
  1370. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  1371. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  1372. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  1373. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  1374. 'Then zero the Z axis.)\n' + '\n'
  1375. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  1376. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  1377. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1378. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1379. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1380. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1381. else:
  1382. gcode += '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  1383. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  1384. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  1385. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  1386. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1387. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1388. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  1389. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  1390. return gcode
  1391. @staticmethod
  1392. def gcode_footer(end_command=None):
  1393. """
  1394. Will add the M02 to the end of GCode, if requested.
  1395. :param end_command: 'M02' or 'M30' - String
  1396. :return:
  1397. """
  1398. if end_command:
  1399. return end_command
  1400. else:
  1401. return 'M02'
  1402. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  1403. """
  1404. This will save the GCode from the Gcode object to a file on the OS filesystem
  1405. :param filename: filename for the GCode file
  1406. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  1407. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  1408. :param to_file: if False then no actual file is saved but the app will know that a file was created
  1409. :param from_tcl: True if run from Tcl Shell
  1410. :return: None
  1411. """
  1412. # gcode = ''
  1413. # roland = False
  1414. # hpgl = False
  1415. # isel_icp = False
  1416. include_header = True
  1417. if preamble == '':
  1418. preamble = self.app.defaults["cncjob_prepend"]
  1419. if postamble == '':
  1420. preamble = self.app.defaults["cncjob_append"]
  1421. try:
  1422. if self.special_group:
  1423. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  1424. (_("This CNCJob object can't be processed because it is a"),
  1425. str(self.special_group),
  1426. _("CNCJob object")))
  1427. return 'fail'
  1428. except AttributeError:
  1429. pass
  1430. # if this dict is not empty then the object is a Geometry object
  1431. if self.cnc_tools:
  1432. first_key = next(iter(self.cnc_tools))
  1433. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  1434. # if this dict is not empty then the object is an Excellon object
  1435. if self.exc_cnc_tools:
  1436. first_key = next(iter(self.exc_cnc_tools))
  1437. include_header = self.app.preprocessors[
  1438. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  1439. ].include_header
  1440. gcode = ''
  1441. if include_header is False:
  1442. g = preamble
  1443. # detect if using multi-tool and make the Gcode summation correctly for each case
  1444. if self.multitool is True:
  1445. for tooluid_key in self.cnc_tools:
  1446. for key, value in self.cnc_tools[tooluid_key].items():
  1447. if key == 'gcode':
  1448. gcode += value
  1449. break
  1450. else:
  1451. gcode += self.gcode
  1452. g = g + gcode + postamble
  1453. else:
  1454. # search for the GCode beginning which is usually a G20 or G21
  1455. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  1456. # g_idx = gcode.rfind('G20')
  1457. #
  1458. # # if it did not find 'G20' then search for 'G21'
  1459. # if g_idx == -1:
  1460. # g_idx = gcode.rfind('G21')
  1461. #
  1462. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  1463. # if g_idx == -1:
  1464. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  1465. # return
  1466. # detect if using multi-tool and make the Gcode summation correctly for each case
  1467. if self.multitool is True:
  1468. if self.origin_kind == 'excellon':
  1469. for tooluid_key in self.exc_cnc_tools:
  1470. for key, value in self.exc_cnc_tools[tooluid_key].items():
  1471. if key == 'gcode' and value:
  1472. gcode += value
  1473. break
  1474. else:
  1475. for tooluid_key in self.cnc_tools:
  1476. for key, value in self.cnc_tools[tooluid_key].items():
  1477. if key == 'gcode' and value:
  1478. gcode += value
  1479. break
  1480. else:
  1481. gcode += self.gcode
  1482. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  1483. # detect if using a HPGL preprocessor
  1484. hpgl = False
  1485. if self.cnc_tools:
  1486. for key in self.cnc_tools:
  1487. if 'ppname_g' in self.cnc_tools[key]['data']:
  1488. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  1489. hpgl = True
  1490. break
  1491. elif self.exc_cnc_tools:
  1492. for key in self.cnc_tools:
  1493. if 'ppname_e' in self.cnc_tools[key]['data']:
  1494. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  1495. hpgl = True
  1496. break
  1497. if hpgl:
  1498. processed_gcode = ''
  1499. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  1500. for gline in gcode.splitlines():
  1501. match = pa_re.search(gline)
  1502. if match:
  1503. x_int = int(float(match.group(1)))
  1504. y_int = int(float(match.group(2)))
  1505. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  1506. processed_gcode += new_line
  1507. else:
  1508. processed_gcode += gline + '\n'
  1509. gcode = processed_gcode
  1510. g = self.gc_header + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  1511. else:
  1512. try:
  1513. g_idx = gcode.index('G94')
  1514. if preamble != '' and postamble != '':
  1515. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1516. gcode[(g_idx + 3):] + postamble + end_gcode
  1517. elif preamble == '':
  1518. g = self.gc_header + gcode[:g_idx + 3] + '\n' + \
  1519. gcode[(g_idx + 3):] + postamble + end_gcode
  1520. elif postamble == '':
  1521. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1522. gcode[(g_idx + 3):] + end_gcode
  1523. else:
  1524. g = self.gc_header + gcode[:g_idx + 3] + gcode[(g_idx + 3):] + end_gcode
  1525. except ValueError:
  1526. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1527. _("G-code does not have a G94 code.\n"
  1528. "Append Code snippet will not be used.."))
  1529. g = self.gc_header + '\n' + gcode + postamble + end_gcode
  1530. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  1531. # if self.ui.toolchange_cb.get_value() is True:
  1532. # # match = self.re_toolchange.search(g)
  1533. # if 'M6' in g:
  1534. # m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  1535. # if m6_code is None or m6_code == '':
  1536. # self.app.inform.emit(
  1537. # '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  1538. # )
  1539. # return 'fail'
  1540. #
  1541. # g = g.replace('M6', m6_code)
  1542. # self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  1543. lines = StringIO(g)
  1544. # Write
  1545. if filename is not None:
  1546. try:
  1547. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1548. if force_windows_line_endings and sys.platform != 'win32':
  1549. with open(filename, 'w', newline='\r\n') as f:
  1550. for line in lines:
  1551. f.write(line)
  1552. else:
  1553. with open(filename, 'w') as f:
  1554. for line in lines:
  1555. f.write(line)
  1556. except FileNotFoundError:
  1557. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1558. return
  1559. except PermissionError:
  1560. self.app.inform.emit(
  1561. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1562. "Most likely another app is holding the file open and not accessible.")
  1563. )
  1564. return 'fail'
  1565. elif to_file is False:
  1566. # Just for adding it to the recent files list.
  1567. if self.app.defaults["global_open_style"] is False:
  1568. self.app.file_opened.emit("cncjob", filename)
  1569. self.app.file_saved.emit("cncjob", filename)
  1570. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  1571. else:
  1572. return lines
  1573. # def on_toolchange_custom_clicked(self, signal):
  1574. # """
  1575. # Handler for clicking toolchange custom.
  1576. #
  1577. # :param signal:
  1578. # :return:
  1579. # """
  1580. #
  1581. # try:
  1582. # if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  1583. # if self.ui.toolchange_cb.get_value():
  1584. # self.ui.toolchange_cb.set_value(False)
  1585. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1586. # _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  1587. # except KeyError:
  1588. # try:
  1589. # for key in self.cnc_tools:
  1590. # ppg = self.cnc_tools[key]['data']['ppname_g']
  1591. # if 'toolchange_custom' not in str(ppg).lower():
  1592. # if self.ui.toolchange_cb.get_value():
  1593. # self.ui.toolchange_cb.set_value(False)
  1594. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1595. # _("The used preprocessor file has to have in it's name: "
  1596. # "'toolchange_custom'"))
  1597. # except KeyError:
  1598. # self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  1599. def get_gcode(self, preamble='', postamble=''):
  1600. """
  1601. We need this to be able to get_gcode separately for shell command export_gcode
  1602. :param preamble: Extra GCode added to the beginning of the GCode
  1603. :param postamble: Extra GCode added at the end of the GCode
  1604. :return: The modified GCode
  1605. """
  1606. return preamble + '\n' + self.gcode + "\n" + postamble
  1607. def get_svg(self):
  1608. # we need this to be able get_svg separately for shell command export_svg
  1609. pass
  1610. def on_plot_cb_click(self, *args):
  1611. """
  1612. Handler for clicking on the Plot checkbox.
  1613. :param args:
  1614. :return:
  1615. """
  1616. if self.muted_ui:
  1617. return
  1618. kind = self.ui.cncplot_method_combo.get_value()
  1619. self.plot(kind=kind)
  1620. self.read_form_item('plot')
  1621. self.ui_disconnect()
  1622. cb_flag = self.ui.plot_cb.isChecked()
  1623. for row in range(self.ui.cnc_tools_table.rowCount()):
  1624. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  1625. if cb_flag:
  1626. table_cb.setChecked(True)
  1627. else:
  1628. table_cb.setChecked(False)
  1629. self.ui_connect()
  1630. def on_plot_cb_click_table(self):
  1631. """
  1632. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  1633. tool/aperture found on that row.
  1634. :return:
  1635. """
  1636. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1637. self.ui_disconnect()
  1638. # cw = self.sender()
  1639. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  1640. # cw_row = cw_index.row()
  1641. kind = self.ui.cncplot_method_combo.get_value()
  1642. self.shapes.clear(update=True)
  1643. if self.origin_kind == "excellon":
  1644. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  1645. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  1646. for tooluid_key in self.exc_cnc_tools:
  1647. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  1648. if row_dia == tooldia:
  1649. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  1650. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  1651. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1652. else:
  1653. for tooluid_key in self.cnc_tools:
  1654. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1655. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1656. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  1657. for r in range(self.ui.cnc_tools_table.rowCount()):
  1658. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  1659. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  1660. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1661. self.shapes.redraw()
  1662. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1663. # if all the row plot's are enabled also enable the general plot checkbox
  1664. cb_cnt = 0
  1665. total_row = self.ui.cnc_tools_table.rowCount()
  1666. for row in range(total_row):
  1667. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  1668. cb_cnt += 1
  1669. else:
  1670. cb_cnt -= 1
  1671. if cb_cnt < total_row:
  1672. self.ui.plot_cb.setChecked(False)
  1673. else:
  1674. self.ui.plot_cb.setChecked(True)
  1675. self.ui_connect()
  1676. def plot(self, visible=None, kind='all'):
  1677. """
  1678. # Does all the required setup and returns False
  1679. # if the 'ptint' option is set to False.
  1680. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  1681. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  1682. :return: None
  1683. """
  1684. if not FlatCAMObj.plot(self):
  1685. return
  1686. visible = visible if visible else self.options['plot']
  1687. if self.app.is_legacy is False:
  1688. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  1689. self.text_col.enabled = True
  1690. else:
  1691. self.text_col.enabled = False
  1692. self.annotation.redraw()
  1693. try:
  1694. if self.multitool is False: # single tool usage
  1695. try:
  1696. dia_plot = float(self.options["tooldia"])
  1697. except ValueError:
  1698. # we may have a tuple with only one element and a comma
  1699. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  1700. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  1701. else:
  1702. # I do this so the travel lines thickness will reflect the tool diameter
  1703. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  1704. # don't know the origin
  1705. if self.origin_kind == "excellon":
  1706. if self.exc_cnc_tools:
  1707. for tooldia_key in self.exc_cnc_tools:
  1708. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  1709. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  1710. if not gcode_parsed:
  1711. continue
  1712. # gcode_parsed = self.gcode_parsed
  1713. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1714. else:
  1715. # multiple tools usage
  1716. if self.cnc_tools:
  1717. for tooluid_key in self.cnc_tools:
  1718. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1719. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1720. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1721. self.shapes.redraw()
  1722. except (ObjectDeleted, AttributeError):
  1723. self.shapes.clear(update=True)
  1724. if self.app.is_legacy is False:
  1725. self.annotation.clear(update=True)
  1726. def on_annotation_change(self):
  1727. """
  1728. Handler for toggling the annotation display by clicking a checkbox.
  1729. :return:
  1730. """
  1731. if self.app.is_legacy is False:
  1732. if self.ui.annotation_cb.get_value():
  1733. self.text_col.enabled = True
  1734. else:
  1735. self.text_col.enabled = False
  1736. # kind = self.ui.cncplot_method_combo.get_value()
  1737. # self.plot(kind=kind)
  1738. self.annotation.redraw()
  1739. else:
  1740. kind = self.ui.cncplot_method_combo.get_value()
  1741. self.plot(kind=kind)
  1742. def convert_units(self, units):
  1743. """
  1744. Units conversion used by the CNCJob objects.
  1745. :param units: Can be "MM" or "IN"
  1746. :return:
  1747. """
  1748. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  1749. factor = CNCjob.convert_units(self, units)
  1750. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  1751. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  1752. 'endz', 'toolchangez']
  1753. temp_tools_dict = {}
  1754. tool_dia_copy = {}
  1755. data_copy = {}
  1756. for tooluid_key, tooluid_value in self.cnc_tools.items():
  1757. for dia_key, dia_value in tooluid_value.items():
  1758. if dia_key == 'tooldia':
  1759. dia_value *= factor
  1760. dia_value = float('%.*f' % (self.decimals, dia_value))
  1761. tool_dia_copy[dia_key] = dia_value
  1762. if dia_key == 'offset':
  1763. tool_dia_copy[dia_key] = dia_value
  1764. if dia_key == 'offset_value':
  1765. dia_value *= factor
  1766. tool_dia_copy[dia_key] = dia_value
  1767. if dia_key == 'type':
  1768. tool_dia_copy[dia_key] = dia_value
  1769. if dia_key == 'tool_type':
  1770. tool_dia_copy[dia_key] = dia_value
  1771. if dia_key == 'data':
  1772. for data_key, data_value in dia_value.items():
  1773. # convert the form fields that are convertible
  1774. for param in param_list:
  1775. if data_key == param and data_value is not None:
  1776. data_copy[data_key] = data_value * factor
  1777. # copy the other dict entries that are not convertible
  1778. if data_key not in param_list:
  1779. data_copy[data_key] = data_value
  1780. tool_dia_copy[dia_key] = deepcopy(data_copy)
  1781. data_copy.clear()
  1782. if dia_key == 'gcode':
  1783. tool_dia_copy[dia_key] = dia_value
  1784. if dia_key == 'gcode_parsed':
  1785. tool_dia_copy[dia_key] = dia_value
  1786. if dia_key == 'solid_geometry':
  1787. tool_dia_copy[dia_key] = dia_value
  1788. # if dia_key == 'solid_geometry':
  1789. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  1790. # if dia_key == 'gcode_parsed':
  1791. # for g in dia_value:
  1792. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1793. #
  1794. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  1795. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  1796. temp_tools_dict.update({
  1797. tooluid_key: deepcopy(tool_dia_copy)
  1798. })
  1799. tool_dia_copy.clear()
  1800. self.cnc_tools.clear()
  1801. self.cnc_tools = deepcopy(temp_tools_dict)