FlatCAMCNCJob.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168
  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. cmd = '$10=0'
  968. self.send_grbl_command(command=cmd, echo=False)
  969. if axis == 'x':
  970. cmd = 'G10 L2 P1 X0'
  971. elif axis == 'y':
  972. cmd = 'G10 L2 P1 Y0'
  973. elif axis == 'z':
  974. cmd = 'G10 L2 P1 Z0'
  975. else:
  976. # all
  977. cmd = 'G10 L2 P1 X0 Y0 Z0'
  978. self.send_grbl_command(command=cmd, echo=False)
  979. # restore previous mode
  980. cmd = '$10=%d' % int(current_mode)
  981. self.send_grbl_command(command=cmd, echo=False)
  982. def on_grbl_homing(self):
  983. cmd = '$H'
  984. self.wake_grbl()
  985. self.send_grbl_command(command=cmd)
  986. self.app.inform.emit("%s" % _("GRBL is doing a home cycle."))
  987. def on_grbl_reset(self):
  988. cmd = '\x18'
  989. self.wake_grbl()
  990. self.send_grbl_command(command=cmd)
  991. self.app.inform.emit("%s" % _("GRBL software reset was sent."))
  992. def on_grbl_pause_resume(self, checked):
  993. if checked is False:
  994. cmd = '~'
  995. self.send_grbl_command(command=cmd)
  996. self.app.inform.emit("%s" % _("GRBL resumed."))
  997. else:
  998. cmd = '!'
  999. self.send_grbl_command(command=cmd)
  1000. self.app.inform.emit("%s" % _("GRBL paused."))
  1001. def probing_gcode(self, coords, pr_travel, probe_fr, pr_depth, controller):
  1002. """
  1003. :param coords: a list of (x, y) tuples of probe points coordinates
  1004. :type coords: list
  1005. :param pr_travel: the height (z) where the probe travel between probe points
  1006. :type pr_travel: float
  1007. :param probe_fr: feedrate when probing
  1008. :type probe_fr: float
  1009. :param pr_depth: how much to lower the probe searching for contact
  1010. :type pr_depth: float
  1011. :param controller: a string with the name of the GCode sender for which to create the probing GCode.
  1012. Can be: 'MACH3', 'MACH4', 'LinuxCNC', 'GRBL'
  1013. :type controller: str
  1014. :return: Probing GCode
  1015. :rtype: str
  1016. """
  1017. p_gcode = ''
  1018. header = ''
  1019. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1020. header += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1021. (str(self.app.version), str(self.app.version_date)) + '\n'
  1022. header += '(This is a autolevelling probing GCode.)\n' \
  1023. '(Make sure that before you start the job you first do a zero for all axis.)\n\n'
  1024. header += '(Name: ' + str(self.options['name']) + ')\n'
  1025. header += '(Type: ' + "Autolevelling Probing GCode " + ')\n'
  1026. header += '(Units: ' + self.units.upper() + ')\n'
  1027. header += '(Created on ' + time_str + ')\n'
  1028. # commands
  1029. if controller == 'MACH3':
  1030. probing_command = 'G31'
  1031. # probing_var = '#2002'
  1032. openfile_command = 'M40'
  1033. closefile_command = 'M41'
  1034. elif controller == 'MACH4':
  1035. probing_command = 'G31'
  1036. # probing_var = '#5063'
  1037. openfile_command = 'M40'
  1038. closefile_command = 'M41'
  1039. elif controller == 'LinuxCNC':
  1040. probing_command = 'G38.2'
  1041. # probing_var = '#5422'
  1042. openfile_command = '(PROBEOPEN a_probing_points_file.txt)'
  1043. closefile_command = '(PROBECLOSE)'
  1044. else:
  1045. log.debug("CNCJobObject.probing_gcode() -> controller not supported")
  1046. return
  1047. # #############################################################################################################
  1048. # ########################### GCODE construction ##############################################################
  1049. # #############################################################################################################
  1050. # header
  1051. p_gcode += header + '\n'
  1052. # supplementary message for LinuxCNC
  1053. if controller == 'LinuxCNC':
  1054. p_gcode += "The file with the stored probing points can be found\n" \
  1055. "in the configuration folder for LinuxCNC.\n" \
  1056. "The name of the file is: a_probing_points_file.txt.\n"
  1057. # units
  1058. p_gcode += 'G21\n' if self.units == 'MM' else 'G20\n'
  1059. # reference mode = absolute
  1060. p_gcode += 'G90\n'
  1061. # open a new file
  1062. p_gcode += openfile_command + '\n'
  1063. # move to safe height (probe travel Z)
  1064. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1065. # probing points
  1066. for idx, xy_tuple in enumerate(coords, 1): # index starts from 1
  1067. x = xy_tuple[0]
  1068. y = xy_tuple[1]
  1069. # move to probing point
  1070. p_gcode += "G0 X%sY%s\n" % (
  1071. str(self.app.dec_format(x, self.coords_decimals)),
  1072. str(self.app.dec_format(y, self.coords_decimals))
  1073. )
  1074. # do the probing
  1075. p_gcode += "%s Z%s F%s\n" % (
  1076. probing_command,
  1077. str(self.app.dec_format(pr_depth, self.coords_decimals)),
  1078. str(self.app.dec_format(probe_fr, self.fr_decimals)),
  1079. )
  1080. # store in a global numeric variable the value of the detected probe Z
  1081. # I offset the global numeric variable by 500 so it does not conflict with something else
  1082. # temp_var = int(idx + 500)
  1083. # p_gcode += "#%d = %s\n" % (temp_var, probing_var)
  1084. # move to safe height (probe travel Z)
  1085. p_gcode += 'G0 Z%s\n' % str(self.app.dec_format(pr_travel, self.coords_decimals))
  1086. # close the file
  1087. p_gcode += closefile_command + '\n'
  1088. # finish the GCode
  1089. p_gcode += 'M2'
  1090. return p_gcode
  1091. def on_generate_probing_gcode(self):
  1092. coords = []
  1093. for id_key, value in self.al_geometry_dict.items():
  1094. x = value['point'].x
  1095. y = value['point'].y
  1096. coords.append(
  1097. (
  1098. self.app.dec_format(x, dec=self.app.decimals),
  1099. self.app.dec_format(y, dec=self.app.decimals)
  1100. )
  1101. )
  1102. pr_travel = self.ui.ptravelz_entry.get_value()
  1103. probe_fr = self.ui.feedrate_probe_entry.get_value()
  1104. pr_depth = self.ui.pdepth_entry.get_value()
  1105. controller = self.ui.al_controller_combo.get_value()
  1106. self.probing_gcode_text = self.probing_gcode(coords, pr_travel, probe_fr, pr_depth, controller)
  1107. def on_view_probing_gcode(self):
  1108. self.app.proc_container.view.set_busy(_("Loading..."))
  1109. gco = self.probing_gcode_text
  1110. if gco is None or gco == '':
  1111. self.app.inform.emit('[WARNING_NOTCL] %s...' % _('There is nothing to view'))
  1112. return
  1113. self.gcode_viewer_tab = AppTextEditor(app=self.app, plain_text=True)
  1114. # add the tab if it was closed
  1115. self.app.ui.plot_tab_area.addTab(self.gcode_viewer_tab, '%s' % _("Code Viewer"))
  1116. self.gcode_viewer_tab.setObjectName('code_viewer_tab')
  1117. # delete the absolute and relative position and messages in the infobar
  1118. self.app.ui.position_label.setText("")
  1119. self.app.ui.rel_position_label.setText("")
  1120. self.gcode_viewer_tab.code_editor.completer_enable = False
  1121. self.gcode_viewer_tab.buttonRun.hide()
  1122. # Switch plot_area to CNCJob tab
  1123. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_viewer_tab)
  1124. self.gcode_viewer_tab.t_frame.hide()
  1125. # then append the text from GCode to the text editor
  1126. try:
  1127. self.gcode_viewer_tab.load_text(gco, move_to_start=True, clear_text=True)
  1128. except Exception as e:
  1129. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1130. return
  1131. self.gcode_viewer_tab.t_frame.show()
  1132. self.app.proc_container.view.set_idle()
  1133. self.gcode_viewer_tab.buttonSave.hide()
  1134. self.gcode_viewer_tab.buttonOpen.hide()
  1135. self.gcode_viewer_tab.buttonPrint.hide()
  1136. self.gcode_viewer_tab.buttonPreview.hide()
  1137. self.gcode_viewer_tab.buttonReplace.hide()
  1138. self.gcode_viewer_tab.sel_all_cb.hide()
  1139. self.gcode_viewer_tab.entryReplace.hide()
  1140. self.gcode_viewer_tab.code_editor.setReadOnly(True)
  1141. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Viewer'))
  1142. def on_import_height_map(self):
  1143. """
  1144. Import the height map file into the app
  1145. :return:
  1146. :rtype:
  1147. """
  1148. _filter_ = "Text File .txt (*.txt);;All Files (*.*)"
  1149. try:
  1150. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1151. directory=self.app.get_last_folder(),
  1152. filter=_filter_)
  1153. except TypeError:
  1154. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import Height Map"),
  1155. filter=_filter_)
  1156. filename = str(filename)
  1157. if filename == '':
  1158. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1159. else:
  1160. self.app.worker_task.emit({'fcn': self.import_height_map, 'params': [filename]})
  1161. def import_height_map(self, filename):
  1162. """
  1163. :param filename:
  1164. :type filename:
  1165. :return:
  1166. :rtype:
  1167. """
  1168. stream = ''
  1169. try:
  1170. if filename:
  1171. with open(filename, 'r') as f:
  1172. stream = f.readlines()
  1173. else:
  1174. return
  1175. except IOError:
  1176. log.error("Failed to open height map file: %s" % filename)
  1177. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open height map file"), filename))
  1178. return
  1179. idx = 0
  1180. for line in stream:
  1181. if line != '':
  1182. idx += 1
  1183. line = line.replace(' ', ',').replace('\n', '').split(',')
  1184. if idx not in self.al_geometry_dict:
  1185. self.al_geometry_dict[idx] = {}
  1186. self.al_geometry_dict[idx]['height'] = float(line[2])
  1187. if 'point' not in self.al_geometry_dict[idx]:
  1188. x = float(line[0])
  1189. y = float(line[1])
  1190. self.al_geometry_dict[idx]['point'] = Point((x, y))
  1191. self.build_al_table_sig.emit()
  1192. def on_updateplot_button_click(self, *args):
  1193. """
  1194. Callback for the "Updata Plot" button. Reads the form for updates
  1195. and plots the object.
  1196. """
  1197. self.read_form()
  1198. self.on_plot_kind_change()
  1199. def on_plot_kind_change(self):
  1200. kind = self.ui.cncplot_method_combo.get_value()
  1201. def worker_task():
  1202. with self.app.proc_container.new(_("Plotting...")):
  1203. self.plot(kind=kind)
  1204. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  1205. def on_exportgcode_button_click(self):
  1206. """
  1207. Handler activated by a button clicked when exporting GCode.
  1208. :param args:
  1209. :return:
  1210. """
  1211. self.app.defaults.report_usage("cncjob_on_exportgcode_button")
  1212. self.read_form()
  1213. name = self.app.collection.get_active().options['name']
  1214. save_gcode = False
  1215. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  1216. _filter_ = "RML1 Files .rol (*.rol);;All Files (*.*)"
  1217. elif 'hpgl' in self.pp_geometry_name:
  1218. _filter_ = "HPGL Files .plt (*.plt);;All Files (*.*)"
  1219. else:
  1220. save_gcode = True
  1221. _filter_ = self.app.defaults['cncjob_save_filters']
  1222. try:
  1223. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1224. filename, _f = FCFileSaveDialog.get_saved_filename(
  1225. caption=_("Export Code ..."),
  1226. directory=dir_file_to_save,
  1227. ext_filter=_filter_
  1228. )
  1229. except TypeError:
  1230. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."), ext_filter=_filter_)
  1231. self.export_gcode_handler(filename, is_gcode=save_gcode)
  1232. def export_gcode_handler(self, filename, is_gcode=True):
  1233. preamble = ''
  1234. postamble = ''
  1235. filename = str(filename)
  1236. if filename == '':
  1237. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export cancelled ..."))
  1238. return
  1239. else:
  1240. if is_gcode is True:
  1241. used_extension = filename.rpartition('.')[2]
  1242. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  1243. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  1244. self.ui.name_entry.set_value(new_name)
  1245. self.on_name_activate(silent=True)
  1246. try:
  1247. if self.ui.snippets_cb.get_value():
  1248. preamble = self.append_snippet
  1249. postamble = self.prepend_snippet
  1250. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  1251. except Exception as err:
  1252. log.debug("CNCJobObject.export_gcode_handler() --> %s" % str(err))
  1253. gc = self.export_gcode(filename)
  1254. if gc == 'fail':
  1255. return
  1256. if self.app.defaults["global_open_style"] is False:
  1257. self.app.file_opened.emit("gcode", filename)
  1258. self.app.file_saved.emit("gcode", filename)
  1259. self.app.inform.emit('[success] %s: %s' % (_("File saved to"), filename))
  1260. def on_edit_code_click(self, *args):
  1261. """
  1262. Handler activated by a button clicked when reviewing GCode.
  1263. :param args:
  1264. :return:
  1265. """
  1266. self.app.proc_container.view.set_busy(_("Loading..."))
  1267. preamble = self.append_snippet
  1268. postamble = self.prepend_snippet
  1269. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  1270. if gco == 'fail':
  1271. return
  1272. else:
  1273. self.app.gcode_edited = gco
  1274. self.gcode_editor_tab = AppTextEditor(app=self.app, plain_text=True)
  1275. # add the tab if it was closed
  1276. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Review"))
  1277. self.gcode_editor_tab.setObjectName('code_editor_tab')
  1278. # delete the absolute and relative position and messages in the infobar
  1279. self.app.ui.position_label.setText("")
  1280. self.app.ui.rel_position_label.setText("")
  1281. self.gcode_editor_tab.code_editor.completer_enable = False
  1282. self.gcode_editor_tab.buttonRun.hide()
  1283. # Switch plot_area to CNCJob tab
  1284. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  1285. self.gcode_editor_tab.t_frame.hide()
  1286. # then append the text from GCode to the text editor
  1287. try:
  1288. self.gcode_editor_tab.load_text(self.app.gcode_edited.getvalue(), move_to_start=True, clear_text=True)
  1289. except Exception as e:
  1290. log.debug('FlatCAMCNCJob.on_edit_code_click() -->%s' % str(e))
  1291. return
  1292. self.gcode_editor_tab.t_frame.show()
  1293. self.app.proc_container.view.set_idle()
  1294. self.gcode_editor_tab.buttonSave.hide()
  1295. self.gcode_editor_tab.buttonOpen.hide()
  1296. self.gcode_editor_tab.buttonPrint.hide()
  1297. self.gcode_editor_tab.buttonPreview.hide()
  1298. self.gcode_editor_tab.buttonReplace.hide()
  1299. self.gcode_editor_tab.sel_all_cb.hide()
  1300. self.gcode_editor_tab.entryReplace.hide()
  1301. self.gcode_editor_tab.code_editor.setReadOnly(True)
  1302. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  1303. def on_update_source_file(self):
  1304. self.source_file = self.gcode_editor_tab.code_editor.toPlainText()
  1305. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  1306. """
  1307. Will create a header to be added to all GCode files generated by FlatCAM
  1308. :param comment_start_symbol: A symbol to be used as the first symbol in a comment
  1309. :param comment_stop_symbol: A symbol to be used as the last symbol in a comment
  1310. :return: A string with a GCode header
  1311. """
  1312. log.debug("FlatCAMCNCJob.gcode_header()")
  1313. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1314. marlin = False
  1315. hpgl = False
  1316. probe_pp = False
  1317. gcode = ''
  1318. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  1319. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  1320. try:
  1321. for key in self.cnc_tools:
  1322. ppg = self.cnc_tools[key]['data']['ppname_g']
  1323. if 'marlin' in ppg.lower() or 'repetier' in ppg.lower():
  1324. marlin = True
  1325. break
  1326. if ppg == 'hpgl':
  1327. hpgl = True
  1328. break
  1329. if "toolchange_probe" in ppg.lower():
  1330. probe_pp = True
  1331. break
  1332. except KeyError:
  1333. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  1334. pass
  1335. try:
  1336. if 'marlin' in self.options['ppname_e'].lower() or 'repetier' in self.options['ppname_e'].lower():
  1337. marlin = True
  1338. except KeyError:
  1339. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1340. pass
  1341. try:
  1342. if "toolchange_probe" in self.options['ppname_e'].lower():
  1343. probe_pp = True
  1344. except KeyError:
  1345. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  1346. pass
  1347. if marlin is True:
  1348. gcode += ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  1349. (str(self.app.version), str(self.app.version_date)) + '\n'
  1350. gcode += ';Name: ' + str(self.options['name']) + '\n'
  1351. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  1352. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1353. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1354. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  1355. gcode += ';Created on ' + time_str + '\n' + '\n'
  1356. elif hpgl is True:
  1357. gcode += 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  1358. (str(self.app.version), str(self.app.version_date)) + '";\n'
  1359. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  1360. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  1361. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1362. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1363. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  1364. gcode += 'CO "Created on ' + time_str + '";\n'
  1365. elif probe_pp is True:
  1366. gcode += '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1367. (str(self.app.version), str(self.app.version_date)) + '\n'
  1368. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  1369. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  1370. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  1371. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  1372. 'Then zero the Z axis.)\n' + '\n'
  1373. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  1374. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  1375. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1376. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1377. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1378. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1379. else:
  1380. gcode += '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  1381. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  1382. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  1383. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  1384. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1385. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1386. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  1387. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  1388. return gcode
  1389. @staticmethod
  1390. def gcode_footer(end_command=None):
  1391. """
  1392. Will add the M02 to the end of GCode, if requested.
  1393. :param end_command: 'M02' or 'M30' - String
  1394. :return:
  1395. """
  1396. if end_command:
  1397. return end_command
  1398. else:
  1399. return 'M02'
  1400. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False, from_tcl=False):
  1401. """
  1402. This will save the GCode from the Gcode object to a file on the OS filesystem
  1403. :param filename: filename for the GCode file
  1404. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  1405. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  1406. :param to_file: if False then no actual file is saved but the app will know that a file was created
  1407. :param from_tcl: True if run from Tcl Shell
  1408. :return: None
  1409. """
  1410. # gcode = ''
  1411. # roland = False
  1412. # hpgl = False
  1413. # isel_icp = False
  1414. include_header = True
  1415. if preamble == '':
  1416. preamble = self.app.defaults["cncjob_prepend"]
  1417. if postamble == '':
  1418. preamble = self.app.defaults["cncjob_append"]
  1419. try:
  1420. if self.special_group:
  1421. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  1422. (_("This CNCJob object can't be processed because it is a"),
  1423. str(self.special_group),
  1424. _("CNCJob object")))
  1425. return 'fail'
  1426. except AttributeError:
  1427. pass
  1428. # if this dict is not empty then the object is a Geometry object
  1429. if self.cnc_tools:
  1430. first_key = next(iter(self.cnc_tools))
  1431. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  1432. # if this dict is not empty then the object is an Excellon object
  1433. if self.exc_cnc_tools:
  1434. first_key = next(iter(self.exc_cnc_tools))
  1435. include_header = self.app.preprocessors[
  1436. self.exc_cnc_tools[first_key]['data']['tools_drill_ppname_e']
  1437. ].include_header
  1438. gcode = ''
  1439. if include_header is False:
  1440. g = preamble
  1441. # detect if using multi-tool and make the Gcode summation correctly for each case
  1442. if self.multitool is True:
  1443. for tooluid_key in self.cnc_tools:
  1444. for key, value in self.cnc_tools[tooluid_key].items():
  1445. if key == 'gcode':
  1446. gcode += value
  1447. break
  1448. else:
  1449. gcode += self.gcode
  1450. g = g + gcode + postamble
  1451. else:
  1452. # search for the GCode beginning which is usually a G20 or G21
  1453. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  1454. # g_idx = gcode.rfind('G20')
  1455. #
  1456. # # if it did not find 'G20' then search for 'G21'
  1457. # if g_idx == -1:
  1458. # g_idx = gcode.rfind('G21')
  1459. #
  1460. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  1461. # if g_idx == -1:
  1462. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  1463. # return
  1464. # detect if using multi-tool and make the Gcode summation correctly for each case
  1465. if self.multitool is True:
  1466. if self.origin_kind == 'excellon':
  1467. for tooluid_key in self.exc_cnc_tools:
  1468. for key, value in self.exc_cnc_tools[tooluid_key].items():
  1469. if key == 'gcode' and value:
  1470. gcode += value
  1471. break
  1472. else:
  1473. for tooluid_key in self.cnc_tools:
  1474. for key, value in self.cnc_tools[tooluid_key].items():
  1475. if key == 'gcode' and value:
  1476. gcode += value
  1477. break
  1478. else:
  1479. gcode += self.gcode
  1480. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  1481. # detect if using a HPGL preprocessor
  1482. hpgl = False
  1483. if self.cnc_tools:
  1484. for key in self.cnc_tools:
  1485. if 'ppname_g' in self.cnc_tools[key]['data']:
  1486. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  1487. hpgl = True
  1488. break
  1489. elif self.exc_cnc_tools:
  1490. for key in self.cnc_tools:
  1491. if 'ppname_e' in self.cnc_tools[key]['data']:
  1492. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  1493. hpgl = True
  1494. break
  1495. if hpgl:
  1496. processed_gcode = ''
  1497. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  1498. for gline in gcode.splitlines():
  1499. match = pa_re.search(gline)
  1500. if match:
  1501. x_int = int(float(match.group(1)))
  1502. y_int = int(float(match.group(2)))
  1503. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  1504. processed_gcode += new_line
  1505. else:
  1506. processed_gcode += gline + '\n'
  1507. gcode = processed_gcode
  1508. g = self.gc_header + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  1509. else:
  1510. try:
  1511. g_idx = gcode.index('G94')
  1512. if preamble != '' and postamble != '':
  1513. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1514. gcode[(g_idx + 3):] + postamble + end_gcode
  1515. elif preamble == '':
  1516. g = self.gc_header + gcode[:g_idx + 3] + '\n' + \
  1517. gcode[(g_idx + 3):] + postamble + end_gcode
  1518. elif postamble == '':
  1519. g = self.gc_header + gcode[:g_idx + 3] + '\n' + preamble + '\n' + \
  1520. gcode[(g_idx + 3):] + end_gcode
  1521. else:
  1522. g = self.gc_header + gcode[:g_idx + 3] + gcode[(g_idx + 3):] + end_gcode
  1523. except ValueError:
  1524. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1525. _("G-code does not have a G94 code.\n"
  1526. "Append Code snippet will not be used.."))
  1527. g = self.gc_header + '\n' + gcode + postamble + end_gcode
  1528. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  1529. # if self.ui.toolchange_cb.get_value() is True:
  1530. # # match = self.re_toolchange.search(g)
  1531. # if 'M6' in g:
  1532. # m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  1533. # if m6_code is None or m6_code == '':
  1534. # self.app.inform.emit(
  1535. # '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  1536. # )
  1537. # return 'fail'
  1538. #
  1539. # g = g.replace('M6', m6_code)
  1540. # self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  1541. lines = StringIO(g)
  1542. # Write
  1543. if filename is not None:
  1544. try:
  1545. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  1546. if force_windows_line_endings and sys.platform != 'win32':
  1547. with open(filename, 'w', newline='\r\n') as f:
  1548. for line in lines:
  1549. f.write(line)
  1550. else:
  1551. with open(filename, 'w') as f:
  1552. for line in lines:
  1553. f.write(line)
  1554. except FileNotFoundError:
  1555. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  1556. return
  1557. except PermissionError:
  1558. self.app.inform.emit(
  1559. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  1560. "Most likely another app is holding the file open and not accessible.")
  1561. )
  1562. return 'fail'
  1563. elif to_file is False:
  1564. # Just for adding it to the recent files list.
  1565. if self.app.defaults["global_open_style"] is False:
  1566. self.app.file_opened.emit("cncjob", filename)
  1567. self.app.file_saved.emit("cncjob", filename)
  1568. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  1569. else:
  1570. return lines
  1571. # def on_toolchange_custom_clicked(self, signal):
  1572. # """
  1573. # Handler for clicking toolchange custom.
  1574. #
  1575. # :param signal:
  1576. # :return:
  1577. # """
  1578. #
  1579. # try:
  1580. # if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  1581. # if self.ui.toolchange_cb.get_value():
  1582. # self.ui.toolchange_cb.set_value(False)
  1583. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1584. # _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  1585. # except KeyError:
  1586. # try:
  1587. # for key in self.cnc_tools:
  1588. # ppg = self.cnc_tools[key]['data']['ppname_g']
  1589. # if 'toolchange_custom' not in str(ppg).lower():
  1590. # if self.ui.toolchange_cb.get_value():
  1591. # self.ui.toolchange_cb.set_value(False)
  1592. # self.app.inform.emit('[WARNING_NOTCL] %s' %
  1593. # _("The used preprocessor file has to have in it's name: "
  1594. # "'toolchange_custom'"))
  1595. # except KeyError:
  1596. # self.app.inform.emit('[ERROR] %s' % _("There is no preprocessor file."))
  1597. def get_gcode(self, preamble='', postamble=''):
  1598. """
  1599. We need this to be able to get_gcode separately for shell command export_gcode
  1600. :param preamble: Extra GCode added to the beginning of the GCode
  1601. :param postamble: Extra GCode added at the end of the GCode
  1602. :return: The modified GCode
  1603. """
  1604. return preamble + '\n' + self.gcode + "\n" + postamble
  1605. def get_svg(self):
  1606. # we need this to be able get_svg separately for shell command export_svg
  1607. pass
  1608. def on_plot_cb_click(self, *args):
  1609. """
  1610. Handler for clicking on the Plot checkbox.
  1611. :param args:
  1612. :return:
  1613. """
  1614. if self.muted_ui:
  1615. return
  1616. kind = self.ui.cncplot_method_combo.get_value()
  1617. self.plot(kind=kind)
  1618. self.read_form_item('plot')
  1619. self.ui_disconnect()
  1620. cb_flag = self.ui.plot_cb.isChecked()
  1621. for row in range(self.ui.cnc_tools_table.rowCount()):
  1622. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  1623. if cb_flag:
  1624. table_cb.setChecked(True)
  1625. else:
  1626. table_cb.setChecked(False)
  1627. self.ui_connect()
  1628. def on_plot_cb_click_table(self):
  1629. """
  1630. Handler for clicking the plot checkboxes added into a Table on each row. Purpose: toggle visibility for the
  1631. tool/aperture found on that row.
  1632. :return:
  1633. """
  1634. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1635. self.ui_disconnect()
  1636. # cw = self.sender()
  1637. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  1638. # cw_row = cw_index.row()
  1639. kind = self.ui.cncplot_method_combo.get_value()
  1640. self.shapes.clear(update=True)
  1641. if self.origin_kind == "excellon":
  1642. for r in range(self.ui.exc_cnc_tools_table.rowCount()):
  1643. row_dia = float('%.*f' % (self.decimals, float(self.ui.exc_cnc_tools_table.item(r, 1).text())))
  1644. for tooluid_key in self.exc_cnc_tools:
  1645. tooldia = float('%.*f' % (self.decimals, float(tooluid_key)))
  1646. if row_dia == tooldia:
  1647. gcode_parsed = self.exc_cnc_tools[tooluid_key]['gcode_parsed']
  1648. if self.ui.exc_cnc_tools_table.cellWidget(r, 6).isChecked():
  1649. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1650. else:
  1651. for tooluid_key in self.cnc_tools:
  1652. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1653. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1654. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  1655. for r in range(self.ui.cnc_tools_table.rowCount()):
  1656. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  1657. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  1658. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  1659. self.shapes.redraw()
  1660. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1661. # if all the row plot's are enabled also enable the general plot checkbox
  1662. cb_cnt = 0
  1663. total_row = self.ui.cnc_tools_table.rowCount()
  1664. for row in range(total_row):
  1665. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  1666. cb_cnt += 1
  1667. else:
  1668. cb_cnt -= 1
  1669. if cb_cnt < total_row:
  1670. self.ui.plot_cb.setChecked(False)
  1671. else:
  1672. self.ui.plot_cb.setChecked(True)
  1673. self.ui_connect()
  1674. def plot(self, visible=None, kind='all'):
  1675. """
  1676. # Does all the required setup and returns False
  1677. # if the 'ptint' option is set to False.
  1678. :param visible: Boolean to decide if the object will be plotted as visible or disabled on canvas
  1679. :param kind: String. Can be "all" or "travel" or "cut". For CNCJob plotting
  1680. :return: None
  1681. """
  1682. if not FlatCAMObj.plot(self):
  1683. return
  1684. visible = visible if visible else self.options['plot']
  1685. if self.app.is_legacy is False:
  1686. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  1687. self.text_col.enabled = True
  1688. else:
  1689. self.text_col.enabled = False
  1690. self.annotation.redraw()
  1691. try:
  1692. if self.multitool is False: # single tool usage
  1693. try:
  1694. dia_plot = float(self.options["tooldia"])
  1695. except ValueError:
  1696. # we may have a tuple with only one element and a comma
  1697. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  1698. self.plot2(tooldia=dia_plot, obj=self, visible=visible, kind=kind)
  1699. else:
  1700. # I do this so the travel lines thickness will reflect the tool diameter
  1701. # may work only for objects created within the app and not Gcode imported from elsewhere for which we
  1702. # don't know the origin
  1703. if self.origin_kind == "excellon":
  1704. if self.exc_cnc_tools:
  1705. for tooldia_key in self.exc_cnc_tools:
  1706. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  1707. gcode_parsed = self.exc_cnc_tools[tooldia_key]['gcode_parsed']
  1708. if not gcode_parsed:
  1709. continue
  1710. # gcode_parsed = self.gcode_parsed
  1711. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1712. else:
  1713. # multiple tools usage
  1714. if self.cnc_tools:
  1715. for tooluid_key in self.cnc_tools:
  1716. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  1717. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  1718. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  1719. self.shapes.redraw()
  1720. except (ObjectDeleted, AttributeError):
  1721. self.shapes.clear(update=True)
  1722. if self.app.is_legacy is False:
  1723. self.annotation.clear(update=True)
  1724. def on_annotation_change(self):
  1725. """
  1726. Handler for toggling the annotation display by clicking a checkbox.
  1727. :return:
  1728. """
  1729. if self.app.is_legacy is False:
  1730. if self.ui.annotation_cb.get_value():
  1731. self.text_col.enabled = True
  1732. else:
  1733. self.text_col.enabled = False
  1734. # kind = self.ui.cncplot_method_combo.get_value()
  1735. # self.plot(kind=kind)
  1736. self.annotation.redraw()
  1737. else:
  1738. kind = self.ui.cncplot_method_combo.get_value()
  1739. self.plot(kind=kind)
  1740. def convert_units(self, units):
  1741. """
  1742. Units conversion used by the CNCJob objects.
  1743. :param units: Can be "MM" or "IN"
  1744. :return:
  1745. """
  1746. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  1747. factor = CNCjob.convert_units(self, units)
  1748. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  1749. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  1750. 'endz', 'toolchangez']
  1751. temp_tools_dict = {}
  1752. tool_dia_copy = {}
  1753. data_copy = {}
  1754. for tooluid_key, tooluid_value in self.cnc_tools.items():
  1755. for dia_key, dia_value in tooluid_value.items():
  1756. if dia_key == 'tooldia':
  1757. dia_value *= factor
  1758. dia_value = float('%.*f' % (self.decimals, dia_value))
  1759. tool_dia_copy[dia_key] = dia_value
  1760. if dia_key == 'offset':
  1761. tool_dia_copy[dia_key] = dia_value
  1762. if dia_key == 'offset_value':
  1763. dia_value *= factor
  1764. tool_dia_copy[dia_key] = dia_value
  1765. if dia_key == 'type':
  1766. tool_dia_copy[dia_key] = dia_value
  1767. if dia_key == 'tool_type':
  1768. tool_dia_copy[dia_key] = dia_value
  1769. if dia_key == 'data':
  1770. for data_key, data_value in dia_value.items():
  1771. # convert the form fields that are convertible
  1772. for param in param_list:
  1773. if data_key == param and data_value is not None:
  1774. data_copy[data_key] = data_value * factor
  1775. # copy the other dict entries that are not convertible
  1776. if data_key not in param_list:
  1777. data_copy[data_key] = data_value
  1778. tool_dia_copy[dia_key] = deepcopy(data_copy)
  1779. data_copy.clear()
  1780. if dia_key == 'gcode':
  1781. tool_dia_copy[dia_key] = dia_value
  1782. if dia_key == 'gcode_parsed':
  1783. tool_dia_copy[dia_key] = dia_value
  1784. if dia_key == 'solid_geometry':
  1785. tool_dia_copy[dia_key] = dia_value
  1786. # if dia_key == 'solid_geometry':
  1787. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  1788. # if dia_key == 'gcode_parsed':
  1789. # for g in dia_value:
  1790. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1791. #
  1792. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  1793. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  1794. temp_tools_dict.update({
  1795. tooluid_key: deepcopy(tool_dia_copy)
  1796. })
  1797. tool_dia_copy.clear()
  1798. self.cnc_tools.clear()
  1799. self.cnc_tools = deepcopy(temp_tools_dict)