FlatCAMCNCJob.py 100 KB

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