ToolDrilling.py 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File by: Marius Adrian Stanciu (c) #
  4. # Date: 6/15/2020 #
  5. # License: MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCCheckBox, FCDoubleSpinner, RadioSet, FCTable, FCButton, \
  10. FCComboBox, OptionalInputSection, FCSpinner, NumericalEvalEntry, OptionalHideInputSection, FCLabel
  11. from appParsers.ParseExcellon import Excellon
  12. from copy import deepcopy
  13. import numpy as np
  14. from shapely.geometry import Point, LineString
  15. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  16. import logging
  17. import gettext
  18. import appTranslation as fcTranslate
  19. import builtins
  20. import platform
  21. from Common import GracefulException as grace
  22. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. log = logging.getLogger('base')
  26. settings = QtCore.QSettings("Open Source", "FlatCAM")
  27. if settings.contains("machinist"):
  28. machinist_setting = settings.value('machinist', type=int)
  29. else:
  30. machinist_setting = 0
  31. class ToolDrilling(AppTool, Excellon):
  32. def __init__(self, app):
  33. self.app = app
  34. self.decimals = self.app.decimals
  35. AppTool.__init__(self, app)
  36. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  37. # #############################################################################
  38. # ######################### Tool GUI ##########################################
  39. # #############################################################################
  40. self.t_ui = DrillingUI(layout=self.layout, app=self.app)
  41. self.toolName = self.t_ui.toolName
  42. # #############################################################################
  43. # ########################## VARIABLES ########################################
  44. # #############################################################################
  45. self.units = ''
  46. self.excellon_tools = {}
  47. self.tooluid = 0
  48. self.kind = "excellon"
  49. # dict that holds the object names and the option name
  50. # the key is the object name (defines in ObjectUI) for each UI element that is a parameter
  51. # particular for a tool and the value is the actual name of the option that the UI element is changing
  52. self.name2option = {}
  53. # store here the default data for Geometry Data
  54. self.default_data = {}
  55. self.obj_name = ""
  56. self.excellon_obj = None
  57. # this holds the resulting GCode
  58. self.total_gcode = ''
  59. # this holds the resulting Parsed Gcode
  60. self.total_gcode_parsed = []
  61. self.first_click = False
  62. self.cursor_pos = None
  63. self.mouse_is_dragging = False
  64. # store here the points for the "Polygon" area selection shape
  65. self.points = []
  66. self.mm = None
  67. self.mr = None
  68. self.kp = None
  69. # variable to store the total amount of drills per job
  70. self.tot_drill_cnt = 0
  71. self.tool_row = 0
  72. # variable to store the total amount of slots per job
  73. self.tot_slot_cnt = 0
  74. self.tool_row_slots = 0
  75. # variable to store the distance travelled
  76. self.travel_distance = 0.0
  77. self.grid_status_memory = self.app.ui.grid_snap_btn.isChecked()
  78. # store here the state of the exclusion checkbox state to be restored after building the UI
  79. # TODO add this in the sel.app.defaults dict and in Preferences
  80. self.exclusion_area_cb_is_checked = False
  81. # store here solid_geometry when there are tool with isolation job
  82. self.solid_geometry = []
  83. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  84. self.tooldia = None
  85. # multiprocessing
  86. self.pool = self.app.pool
  87. self.results = []
  88. # disconnect flags
  89. self.area_sel_disconnect_flag = False
  90. self.poly_sel_disconnect_flag = False
  91. self.form_fields = {
  92. "cutz": self.t_ui.cutz_entry,
  93. "multidepth": self.t_ui.mpass_cb,
  94. "depthperpass": self.t_ui.maxdepth_entry,
  95. "travelz": self.t_ui.travelz_entry,
  96. "feedrate_z": self.t_ui.feedrate_z_entry,
  97. "feedrate_rapid": self.t_ui.feedrate_rapid_entry,
  98. "spindlespeed": self.t_ui.spindlespeed_entry,
  99. "dwell": self.t_ui.dwell_cb,
  100. "dwelltime": self.t_ui.dwelltime_entry,
  101. "offset": self.t_ui.offset_entry,
  102. "drill_slots": self.t_ui.drill_slots_cb,
  103. "drill_overlap": self.t_ui.drill_overlap_entry,
  104. "last_drill": self.t_ui.last_drill_cb
  105. }
  106. self.name2option = {
  107. "e_cutz": "cutz",
  108. "e_multidepth": "multidepth",
  109. "e_depthperpass": "depthperpass",
  110. "e_travelz": "travelz",
  111. "e_feedratez": "feedrate_z",
  112. "e_fr_rapid": "feedrate_rapid",
  113. "e_spindlespeed": "spindlespeed",
  114. "e_dwell": "dwell",
  115. "e_dwelltime": "dwelltime",
  116. "e_offset": "offset",
  117. "e_drill_slots": "drill_slots",
  118. "e_drill_slots_overlap": "drill_overlap",
  119. "e_drill_last_drill": "last_drill",
  120. }
  121. self.poly_drawn = False
  122. self.connect_signals_at_init()
  123. def install(self, icon=None, separator=None, **kwargs):
  124. AppTool.install(self, icon, separator, shortcut='Alt+D', **kwargs)
  125. def run(self, toggle=True):
  126. self.app.defaults.report_usage("ToolDrilling()")
  127. log.debug("ToolDrilling().run() was launched ...")
  128. if toggle:
  129. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  130. if self.app.ui.splitter.sizes()[0] == 0:
  131. self.app.ui.splitter.setSizes([1, 1])
  132. else:
  133. try:
  134. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  135. # if tab is populated with the tool but it does not have the focus, focus on it
  136. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  137. # focus on Tool Tab
  138. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  139. else:
  140. self.app.ui.splitter.setSizes([0, 1])
  141. except AttributeError:
  142. pass
  143. else:
  144. if self.app.ui.splitter.sizes()[0] == 0:
  145. self.app.ui.splitter.setSizes([1, 1])
  146. AppTool.run(self)
  147. self.set_tool_ui()
  148. self.on_object_changed()
  149. # self.build_tool_ui()
  150. # all the tools are selected by default
  151. self.t_ui.tools_table.selectAll()
  152. self.app.ui.notebook.setTabText(2, _("Drilling Tool"))
  153. def connect_signals_at_init(self):
  154. # #############################################################################
  155. # ############################ SIGNALS ########################################
  156. # #############################################################################
  157. self.t_ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  158. self.t_ui.generate_cnc_button.clicked.connect(self.on_cnc_button_click)
  159. self.t_ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  160. # Exclusion areas signals
  161. self.t_ui.exclusion_table.horizontalHeader().sectionClicked.connect(self.exclusion_table_toggle_all)
  162. self.t_ui.exclusion_table.lost_focus.connect(self.clear_selection)
  163. self.t_ui.exclusion_table.itemClicked.connect(self.draw_sel_shape)
  164. self.t_ui.add_area_button.clicked.connect(self.on_add_area_click)
  165. self.t_ui.delete_area_button.clicked.connect(self.on_clear_area_click)
  166. self.t_ui.delete_sel_area_button.clicked.connect(self.on_delete_sel_areas)
  167. self.t_ui.strategy_radio.activated_custom.connect(self.on_strategy)
  168. self.t_ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  169. self.t_ui.reset_button.clicked.connect(self.set_tool_ui)
  170. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  171. self.app.cleanup.connect(self.set_tool_ui)
  172. def set_tool_ui(self):
  173. self.units = self.app.defaults['units'].upper()
  174. # try to select in the Excellon combobox the active object
  175. try:
  176. selected_obj = self.app.collection.get_active()
  177. if selected_obj.kind == 'excellon':
  178. current_name = selected_obj.options['name']
  179. self.t_ui.object_combo.set_value(current_name)
  180. except Exception:
  181. pass
  182. # reset the Excellon preprocessor combo
  183. self.t_ui.pp_excellon_name_cb.clear()
  184. # populate Excellon preprocessor combobox list
  185. for name in list(self.app.preprocessors.keys()):
  186. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  187. if name == 'hpgl':
  188. continue
  189. self.t_ui.pp_excellon_name_cb.addItem(name)
  190. # add tooltips
  191. for it in range(self.t_ui.pp_excellon_name_cb.count()):
  192. self.t_ui.pp_excellon_name_cb.setItemData(
  193. it, self.t_ui.pp_excellon_name_cb.itemText(it), QtCore.Qt.ToolTipRole)
  194. # update the changes in UI depending on the selected preprocessor in Preferences
  195. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  196. # self.t_ui.pp_excellon_name_cb combobox
  197. self.on_pp_changed()
  198. app_mode = self.app.defaults["global_app_level"]
  199. # Show/Hide Advanced Options
  200. if app_mode == 'b':
  201. self.t_ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  202. self.t_ui.estartz_label.hide()
  203. self.t_ui.estartz_entry.hide()
  204. self.t_ui.feedrate_rapid_label.hide()
  205. self.t_ui.feedrate_rapid_entry.hide()
  206. self.t_ui.pdepth_label.hide()
  207. self.t_ui.pdepth_entry.hide()
  208. self.t_ui.feedrate_probe_label.hide()
  209. self.t_ui.feedrate_probe_entry.hide()
  210. else:
  211. self.t_ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  212. self.t_ui.estartz_label.show()
  213. self.t_ui.estartz_entry.show()
  214. self.t_ui.feedrate_rapid_label.show()
  215. self.t_ui.feedrate_rapid_entry.show()
  216. self.t_ui.pdepth_label.show()
  217. self.t_ui.pdepth_entry.show()
  218. self.t_ui.feedrate_probe_label.show()
  219. self.t_ui.feedrate_probe_entry.show()
  220. self.t_ui.tools_frame.show()
  221. self.t_ui.order_radio.set_value(self.app.defaults["tools_drill_tool_order"])
  222. loaded_obj = self.app.collection.get_by_name(self.t_ui.object_combo.get_value())
  223. if loaded_obj:
  224. outname = loaded_obj.options['name']
  225. else:
  226. outname = ''
  227. # init the working variables
  228. self.default_data.clear()
  229. self.default_data = {
  230. "name": outname + '_drill',
  231. "plot": self.app.defaults["excellon_plot"],
  232. "solid": self.app.defaults["excellon_solid"],
  233. "multicolored": self.app.defaults["excellon_multicolored"],
  234. "merge_fuse_tools": self.app.defaults["excellon_merge_fuse_tools"],
  235. "format_upper_in": self.app.defaults["excellon_format_upper_in"],
  236. "format_lower_in": self.app.defaults["excellon_format_lower_in"],
  237. "format_upper_mm": self.app.defaults["excellon_format_upper_mm"],
  238. "lower_mm": self.app.defaults["excellon_format_lower_mm"],
  239. "zeros": self.app.defaults["excellon_zeros"],
  240. "excellon_units": self.app.defaults["excellon_units"],
  241. "excellon_update": self.app.defaults["excellon_update"],
  242. "excellon_optimization_type": self.app.defaults["excellon_optimization_type"],
  243. "excellon_search_time": self.app.defaults["excellon_search_time"],
  244. "excellon_plot_fill": self.app.defaults["excellon_plot_fill"],
  245. "excellon_plot_line": self.app.defaults["excellon_plot_line"],
  246. # Excellon Options
  247. "tooldia": self.app.defaults["excellon_tooldia"],
  248. "slot_tooldia": self.app.defaults["excellon_slot_tooldia"],
  249. # Excellon Advanced Options
  250. "offset": self.app.defaults["excellon_offset"],
  251. "toolchangexy": self.app.defaults["excellon_toolchangexy"],
  252. "startz": self.app.defaults["excellon_startz"],
  253. "feedrate_rapid": self.app.defaults["excellon_feedrate_rapid"],
  254. "z_pdepth": self.app.defaults["excellon_z_pdepth"],
  255. "feedrate_probe": self.app.defaults["excellon_feedrate_probe"],
  256. "spindledir": self.app.defaults["excellon_spindledir"],
  257. "f_plunge": self.app.defaults["excellon_f_plunge"],
  258. "f_retract": self.app.defaults["excellon_f_retract"],
  259. "excellon_area_exclusion": self.app.defaults["excellon_area_exclusion"],
  260. "excellon_area_shape": self.app.defaults["excellon_area_shape"],
  261. "excellon_area_strategy": self.app.defaults["excellon_area_strategy"],
  262. "excellon_area_overz": self.app.defaults["excellon_area_overz"],
  263. "tools_drill_tool_order": self.app.defaults["tools_drill_tool_order"],
  264. "tools_drill_cutz": self.app.defaults["tools_drill_cutz"],
  265. "tools_drill_multidepth": self.app.defaults["tools_drill_multidepth"],
  266. "tools_drill_depthperpass": self.app.defaults["tools_drill_depthperpass"],
  267. "tools_drill_travelz": self.app.defaults["tools_drill_travelz"],
  268. "tools_drill_endz": self.app.defaults["tools_drill_endz"],
  269. "tools_drill_endxy": self.app.defaults["tools_drill_endxy"],
  270. "tools_drill_feedrate_z": self.app.defaults["tools_drill_feedrate_z"],
  271. "tools_drill_spindlespeed": self.app.defaults["tools_drill_spindlespeed"],
  272. "tools_drill_dwell": self.app.defaults["tools_drill_dwell"],
  273. "tools_drill_dwelltime": self.app.defaults["tools_drill_dwelltime"],
  274. "tools_drill_toolchange": self.app.defaults["tools_drill_toolchange"],
  275. "tools_drill_toolchangez": self.app.defaults["tools_drill_toolchangez"],
  276. "tools_drill_ppname_e": self.app.defaults["tools_drill_ppname_e"],
  277. # Drill Slots
  278. "tools_drill_drill_slots": self.app.defaults["tools_drill_drill_slots"],
  279. "tools_drill_drill_overlap": self.app.defaults["tools_drill_drill_overlap"],
  280. "tools_drill_last_drill": self.app.defaults["tools_drill_last_drill"],
  281. }
  282. # fill in self.default_data values from self.options
  283. for opt_key, opt_val in self.app.options.items():
  284. if opt_key.find('excellon_') == 0:
  285. self.default_data[opt_key] = deepcopy(opt_val)
  286. self.first_click = False
  287. self.cursor_pos = None
  288. self.mouse_is_dragging = False
  289. self.units = self.app.defaults['units'].upper()
  290. # ########################################
  291. # #######3 TEMP SETTINGS #################
  292. # ########################################
  293. self.t_ui.tools_table.setRowCount(2)
  294. self.t_ui.tools_table.setMinimumHeight(self.t_ui.tools_table.getHeight())
  295. self.t_ui.tools_table.setMaximumHeight(self.t_ui.tools_table.getHeight())
  296. # make sure to update the UI on init
  297. try:
  298. self.excellon_tools = self.excellon_obj.tools
  299. except AttributeError:
  300. # no object loaded
  301. pass
  302. self.build_tool_ui()
  303. # ########################################
  304. # ########################################
  305. # ####### Fill in the parameters #########
  306. # ########################################
  307. # ########################################
  308. self.t_ui.cutz_entry.set_value(self.app.defaults["tools_drill_cutz"])
  309. self.t_ui.mpass_cb.set_value(self.app.defaults["tools_drill_multidepth"])
  310. self.t_ui.maxdepth_entry.set_value(self.app.defaults["tools_drill_depthperpass"])
  311. self.t_ui.travelz_entry.set_value(self.app.defaults["tools_drill_travelz"])
  312. self.t_ui.feedrate_z_entry.set_value(self.app.defaults["tools_drill_feedrate_z"])
  313. self.t_ui.feedrate_rapid_entry.set_value(self.app.defaults["excellon_feedrate_rapid"])
  314. self.t_ui.spindlespeed_entry.set_value(self.app.defaults["tools_drill_spindlespeed"])
  315. self.t_ui.dwell_cb.set_value(self.app.defaults["tools_drill_dwell"])
  316. self.t_ui.dwelltime_entry.set_value(self.app.defaults["tools_drill_dwelltime"])
  317. self.t_ui.offset_entry.set_value(self.app.defaults["excellon_offset"])
  318. self.t_ui.toolchange_cb.set_value(self.app.defaults["tools_drill_toolchange"])
  319. self.t_ui.toolchangez_entry.set_value(self.app.defaults["tools_drill_toolchangez"])
  320. self.t_ui.estartz_entry.set_value(self.app.defaults["excellon_startz"])
  321. self.t_ui.endz_entry.set_value(self.app.defaults["tools_drill_endz"])
  322. self.t_ui.endxy_entry.set_value(self.app.defaults["tools_drill_endxy"])
  323. self.t_ui.pdepth_entry.set_value(self.app.defaults["excellon_z_pdepth"])
  324. self.t_ui.feedrate_probe_entry.set_value(self.app.defaults["excellon_feedrate_probe"])
  325. self.t_ui.exclusion_cb.set_value(self.app.defaults["excellon_area_exclusion"])
  326. self.t_ui.strategy_radio.set_value(self.app.defaults["excellon_area_strategy"])
  327. self.t_ui.over_z_entry.set_value(self.app.defaults["excellon_area_overz"])
  328. self.t_ui.area_shape_radio.set_value(self.app.defaults["excellon_area_shape"])
  329. # Drill slots - part of the Advanced Excellon params
  330. self.t_ui.drill_slots_cb.set_value(self.app.defaults["tools_drill_drill_slots"])
  331. self.t_ui.drill_overlap_entry.set_value(self.app.defaults["tools_drill_drill_overlap"])
  332. self.t_ui.last_drill_cb.set_value(self.app.defaults["tools_drill_last_drill"])
  333. # if the app mode is Basic then disable this feature
  334. if app_mode == 'b':
  335. self.t_ui.drill_slots_cb.set_value(False)
  336. self.t_ui.drill_slots_cb.hide()
  337. self.t_ui.drill_overlap_label.hide()
  338. self.t_ui.drill_overlap_entry.hide()
  339. self.t_ui.last_drill_cb.hide()
  340. else:
  341. self.t_ui.drill_slots_cb.show()
  342. self.t_ui.drill_overlap_label.show()
  343. self.t_ui.drill_overlap_entry.show()
  344. self.t_ui.last_drill_cb.show()
  345. try:
  346. self.t_ui.object_combo.currentTextChanged.disconnect()
  347. except (AttributeError, TypeError):
  348. pass
  349. self.t_ui.object_combo.currentTextChanged.connect(self.on_object_changed)
  350. def rebuild_ui(self):
  351. # read the table tools uid
  352. current_uid_list = []
  353. for row in range(self.t_ui.tools_table.rowCount()):
  354. try:
  355. uid = int(self.t_ui.tools_table.item(row, 3).text())
  356. current_uid_list.append(uid)
  357. except AttributeError:
  358. continue
  359. new_tools = {}
  360. new_uid = 1
  361. for current_uid in current_uid_list:
  362. new_tools[new_uid] = deepcopy(self.excellon_tools[current_uid])
  363. new_uid += 1
  364. self.excellon_tools = new_tools
  365. # the tools table changed therefore we need to rebuild it
  366. QtCore.QTimer.singleShot(20, self.build_tool_ui)
  367. def build_tool_ui(self):
  368. log.debug("ToolDrilling.build_tool_ui()")
  369. self.ui_disconnect()
  370. # order the tools by tool diameter if it's the case
  371. sorted_tools = []
  372. for k, v in self.excellon_tools.items():
  373. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  374. order = self.t_ui.order_radio.get_value()
  375. if order == 'fwd':
  376. sorted_tools.sort(reverse=False)
  377. elif order == 'rev':
  378. sorted_tools.sort(reverse=True)
  379. else:
  380. pass
  381. # remake the excellon_tools dict in the order above
  382. new_id = 1
  383. new_tools = {}
  384. for tooldia in sorted_tools:
  385. for old_tool in self.excellon_tools:
  386. if float('%.*f' % (self.decimals, float(self.excellon_tools[old_tool]['tooldia']))) == tooldia:
  387. new_tools[new_id] = deepcopy(self.excellon_tools[old_tool])
  388. new_id += 1
  389. self.excellon_tools = new_tools
  390. if self.excellon_obj and self.excellon_tools:
  391. self.t_ui.exc_param_frame.setDisabled(False)
  392. tools = [k for k in self.excellon_tools]
  393. else:
  394. self.t_ui.exc_param_frame.setDisabled(True)
  395. self.t_ui.tools_table.setRowCount(2)
  396. tools = []
  397. n = len(tools)
  398. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  399. self.t_ui.tools_table.setRowCount(n + 2)
  400. self.tool_row = 0
  401. tot_drill_cnt = 0
  402. tot_slot_cnt = 0
  403. for tool_no in tools:
  404. # Find no of drills for the current tool
  405. try:
  406. drill_cnt = len(self.excellon_tools[tool_no]["drills"]) # variable to store the nr of drills per tool
  407. except KeyError:
  408. drill_cnt = 0
  409. tot_drill_cnt += drill_cnt
  410. # Find no of slots for the current tool
  411. try:
  412. slot_cnt = len(self.excellon_tools[tool_no]["slots"]) # variable to store the nr of slots per tool
  413. except KeyError:
  414. slot_cnt = 0
  415. tot_slot_cnt += slot_cnt
  416. # Tool name/id
  417. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  418. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  419. self.t_ui.tools_table.setItem(self.tool_row, 0, exc_id_item)
  420. # Tool Diameter
  421. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.excellon_tools[tool_no]['tooldia']))
  422. dia_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  423. self.t_ui.tools_table.setItem(self.tool_row, 1, dia_item)
  424. # Number of drills per tool
  425. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  426. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  427. self.t_ui.tools_table.setItem(self.tool_row, 2, drill_count_item)
  428. # Tool unique ID
  429. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tool_no)))
  430. # ## REMEMBER: THIS COLUMN IS HIDDEN in UI
  431. self.t_ui.tools_table.setItem(self.tool_row, 3, tool_uid_item)
  432. # Number of slots per tool
  433. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  434. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  435. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  436. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  437. self.t_ui.tools_table.setItem(self.tool_row, 4, slot_count_item)
  438. self.tool_row += 1
  439. # add a last row with the Total number of drills
  440. empty_1 = QtWidgets.QTableWidgetItem('')
  441. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  442. empty_1_1 = QtWidgets.QTableWidgetItem('')
  443. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  444. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  445. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  446. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % tot_drill_cnt)
  447. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  448. self.t_ui.tools_table.setItem(self.tool_row, 0, empty_1)
  449. self.t_ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  450. self.t_ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  451. self.t_ui.tools_table.setItem(self.tool_row, 4, empty_1_1)
  452. font = QtGui.QFont()
  453. font.setBold(True)
  454. font.setWeight(75)
  455. for k in [1, 2]:
  456. self.t_ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  457. self.t_ui.tools_table.item(self.tool_row, k).setFont(font)
  458. self.tool_row += 1
  459. # add a last row with the Total number of slots
  460. empty_2 = QtWidgets.QTableWidgetItem('')
  461. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  462. empty_2_1 = QtWidgets.QTableWidgetItem('')
  463. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  464. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  465. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % tot_slot_cnt)
  466. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  467. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  468. self.t_ui.tools_table.setItem(self.tool_row, 0, empty_2)
  469. self.t_ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  470. self.t_ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  471. self.t_ui.tools_table.setItem(self.tool_row, 4, tot_slot_count) # Total number of slots
  472. for kl in [1, 2, 4]:
  473. self.t_ui.tools_table.item(self.tool_row, kl).setFont(font)
  474. self.t_ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  475. # make the diameter column editable
  476. # for row in range(self.t_ui.tools_table.rowCount() - 2):
  477. # self.t_ui.tools_table.item(row, 1).setFlags(
  478. # QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  479. self.t_ui.tools_table.resizeColumnsToContents()
  480. self.t_ui.tools_table.resizeRowsToContents()
  481. vertical_header = self.t_ui.tools_table.verticalHeader()
  482. vertical_header.hide()
  483. self.t_ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  484. horizontal_header = self.t_ui.tools_table.horizontalHeader()
  485. self.t_ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  486. horizontal_header.setMinimumSectionSize(10)
  487. horizontal_header.setDefaultSectionSize(70)
  488. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  489. horizontal_header.resizeSection(0, 20)
  490. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  491. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  492. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  493. self.t_ui.tools_table.setSortingEnabled(False)
  494. self.t_ui.tools_table.setMinimumHeight(self.t_ui.tools_table.getHeight())
  495. self.t_ui.tools_table.setMaximumHeight(self.t_ui.tools_table.getHeight())
  496. # all the tools are selected by default
  497. self.t_ui.tools_table.selectAll()
  498. # Build Exclusion Areas section
  499. e_len = len(self.app.exc_areas.exclusion_areas_storage)
  500. self.t_ui.exclusion_table.setRowCount(e_len)
  501. area_id = 0
  502. for area in range(e_len):
  503. area_id += 1
  504. area_dict = self.app.exc_areas.exclusion_areas_storage[area]
  505. area_id_item = QtWidgets.QTableWidgetItem('%d' % int(area_id))
  506. area_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  507. self.t_ui.exclusion_table.setItem(area, 0, area_id_item) # Area id
  508. object_item = QtWidgets.QTableWidgetItem('%s' % area_dict["obj_type"])
  509. object_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  510. self.t_ui.exclusion_table.setItem(area, 1, object_item) # Origin Object
  511. strategy_item = QtWidgets.QTableWidgetItem('%s' % area_dict["strategy"])
  512. strategy_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  513. self.t_ui.exclusion_table.setItem(area, 2, strategy_item) # Strategy
  514. overz_item = QtWidgets.QTableWidgetItem('%s' % area_dict["overz"])
  515. overz_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  516. self.t_ui.exclusion_table.setItem(area, 3, overz_item) # Over Z
  517. self.t_ui.exclusion_table.resizeColumnsToContents()
  518. self.t_ui.exclusion_table.resizeRowsToContents()
  519. area_vheader = self.t_ui.exclusion_table.verticalHeader()
  520. area_vheader.hide()
  521. self.t_ui.exclusion_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  522. area_hheader = self.t_ui.exclusion_table.horizontalHeader()
  523. area_hheader.setMinimumSectionSize(10)
  524. area_hheader.setDefaultSectionSize(70)
  525. area_hheader.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  526. area_hheader.resizeSection(0, 20)
  527. area_hheader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  528. area_hheader.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  529. area_hheader.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  530. # area_hheader.setStretchLastSection(True)
  531. self.t_ui.exclusion_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  532. self.t_ui.exclusion_table.setColumnWidth(0, 20)
  533. self.t_ui.exclusion_table.setMinimumHeight(self.t_ui.exclusion_table.getHeight())
  534. self.t_ui.exclusion_table.setMaximumHeight(self.t_ui.exclusion_table.getHeight())
  535. self.ui_connect()
  536. # set the text on tool_data_label after loading the object
  537. sel_rows = set()
  538. sel_items = self.t_ui.tools_table.selectedItems()
  539. for it in sel_items:
  540. sel_rows.add(it.row())
  541. if len(sel_rows) > 1:
  542. self.t_ui.tool_data_label.setText(
  543. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  544. )
  545. elif len(sel_rows) == 1:
  546. # update the QLabel that shows for which Tool we have the parameters in the UI form
  547. toolnr = int(self.t_ui.tools_table.item(list(sel_rows)[0], 0).text())
  548. self.t_ui.tool_data_label.setText(
  549. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), toolnr)
  550. )
  551. def on_object_changed(self):
  552. log.debug("ToolDrilling.on_object_changed()")
  553. # updated units
  554. self.units = self.app.defaults['units'].upper()
  555. # load the Excellon object
  556. self.obj_name = self.t_ui.object_combo.currentText()
  557. # Get source object.
  558. try:
  559. self.excellon_obj = self.app.collection.get_by_name(self.obj_name)
  560. except Exception:
  561. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  562. return
  563. if self.excellon_obj is None:
  564. self.excellon_tools = {}
  565. self.t_ui.exc_param_frame.setDisabled(True)
  566. self.set_tool_ui()
  567. else:
  568. self.excellon_tools = self.excellon_obj.tools
  569. self.app.collection.set_active(self.obj_name)
  570. self.t_ui.exc_param_frame.setDisabled(False)
  571. self.excellon_tools = self.excellon_obj.tools
  572. self.build_tool_ui()
  573. sel_rows = set()
  574. table_items = self.t_ui.tools_table.selectedItems()
  575. if table_items:
  576. for it in table_items:
  577. sel_rows.add(it.row())
  578. if not sel_rows or len(sel_rows) == 0:
  579. self.t_ui.generate_cnc_button.setDisabled(True)
  580. self.t_ui.tool_data_label.setText(
  581. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  582. )
  583. else:
  584. self.t_ui.generate_cnc_button.setDisabled(False)
  585. def ui_connect(self):
  586. # Area Exception - exclusion shape added signal
  587. # first disconnect it from any other object
  588. try:
  589. self.app.exc_areas.e_shape_modified.disconnect()
  590. except (TypeError, AttributeError):
  591. pass
  592. # then connect it to the current build_tool_ui() method
  593. self.app.exc_areas.e_shape_modified.connect(self.update_exclusion_table)
  594. # rows selected
  595. self.t_ui.tools_table.clicked.connect(self.on_row_selection_change)
  596. self.t_ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  597. # Tool Parameters
  598. for opt in self.form_fields:
  599. current_widget = self.form_fields[opt]
  600. if isinstance(current_widget, FCCheckBox):
  601. current_widget.stateChanged.connect(self.form_to_storage)
  602. if isinstance(current_widget, RadioSet):
  603. current_widget.activated_custom.connect(self.form_to_storage)
  604. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  605. current_widget.returnPressed.connect(self.form_to_storage)
  606. elif isinstance(current_widget, FCComboBox):
  607. current_widget.currentIndexChanged.connect(self.form_to_storage)
  608. self.t_ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  609. def ui_disconnect(self):
  610. # rows selected
  611. try:
  612. self.t_ui.tools_table.clicked.disconnect(self.on_row_selection_change)
  613. except (TypeError, AttributeError):
  614. pass
  615. try:
  616. self.t_ui.tools_table.horizontalHeader().sectionClicked.disconnect(self.on_toggle_all_rows)
  617. except (TypeError, AttributeError):
  618. pass
  619. # tool table widgets
  620. for row in range(self.t_ui.tools_table.rowCount()):
  621. try:
  622. self.t_ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  623. except (TypeError, AttributeError):
  624. pass
  625. # Tool Parameters
  626. for opt in self.form_fields:
  627. current_widget = self.form_fields[opt]
  628. if isinstance(current_widget, FCCheckBox):
  629. try:
  630. current_widget.stateChanged.disconnect(self.form_to_storage)
  631. except (TypeError, ValueError):
  632. pass
  633. if isinstance(current_widget, RadioSet):
  634. try:
  635. current_widget.activated_custom.disconnect(self.form_to_storage)
  636. except (TypeError, ValueError):
  637. pass
  638. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  639. try:
  640. current_widget.returnPressed.disconnect(self.form_to_storage)
  641. except (TypeError, ValueError):
  642. pass
  643. elif isinstance(current_widget, FCComboBox):
  644. try:
  645. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  646. except (TypeError, ValueError):
  647. pass
  648. try:
  649. self.t_ui.order_radio.activated_custom[str].disconnect()
  650. except (TypeError, ValueError):
  651. pass
  652. def on_toggle_all_rows(self):
  653. """
  654. will toggle the selection of all rows in Tools table
  655. :return:
  656. """
  657. sel_model = self.t_ui.tools_table.selectionModel()
  658. sel_indexes = sel_model.selectedIndexes()
  659. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  660. sel_rows = set()
  661. for idx in sel_indexes:
  662. sel_rows.add(idx.row())
  663. if len(sel_rows) == self.t_ui.tools_table.rowCount():
  664. self.t_ui.tools_table.clearSelection()
  665. self.t_ui.exc_param_frame.setDisabled(True)
  666. else:
  667. self.t_ui.tools_table.selectAll()
  668. self.t_ui.exc_param_frame.setDisabled(False)
  669. self.update_ui()
  670. def on_row_selection_change(self):
  671. self.update_ui()
  672. def update_ui(self):
  673. self.blockSignals(True)
  674. sel_rows = set()
  675. table_items = self.t_ui.tools_table.selectedItems()
  676. if table_items:
  677. for it in table_items:
  678. sel_rows.add(it.row())
  679. # sel_rows = sorted(set(index.row() for index in self.t_ui.tools_table.selectedIndexes()))
  680. if not sel_rows or len(sel_rows) == 0:
  681. self.t_ui.generate_cnc_button.setDisabled(True)
  682. self.t_ui.exc_param_frame.setDisabled(True)
  683. self.t_ui.tool_data_label.setText(
  684. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  685. )
  686. self.blockSignals(False)
  687. return
  688. else:
  689. self.t_ui.generate_cnc_button.setDisabled(False)
  690. self.t_ui.exc_param_frame.setDisabled(False)
  691. if len(sel_rows) == 1:
  692. # update the QLabel that shows for which Tool we have the parameters in the UI form
  693. tooluid = int(self.t_ui.tools_table.item(list(sel_rows)[0], 0).text())
  694. self.t_ui.tool_data_label.setText(
  695. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  696. )
  697. else:
  698. self.t_ui.tool_data_label.setText(
  699. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  700. )
  701. for c_row in sel_rows:
  702. # populate the form with the data from the tool associated with the row parameter
  703. try:
  704. item = self.t_ui.tools_table.item(c_row, 3)
  705. if type(item) is not None:
  706. tooluid = int(item.text())
  707. self.storage_to_form(self.excellon_tools[tooluid]['data'])
  708. else:
  709. self.blockSignals(False)
  710. return
  711. except Exception as e:
  712. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  713. self.blockSignals(False)
  714. return
  715. self.blockSignals(False)
  716. def storage_to_form(self, dict_storage):
  717. """
  718. Will update the GUI with data from the "storage" in this case the dict self.tools
  719. :param dict_storage: A dictionary holding the data relevant for gnerating Gcode from Excellon
  720. :type dict_storage: dict
  721. :return: None
  722. :rtype:
  723. """
  724. for form_key in self.form_fields:
  725. for storage_key in dict_storage:
  726. if form_key == storage_key and form_key not in \
  727. ["tools_drill_toolchange", "tools_drill_toolchangez", "startz", "endz", "tools_drill_ppname_e"]:
  728. try:
  729. self.form_fields[form_key].set_value(dict_storage[form_key])
  730. except Exception as e:
  731. log.debug("ToolDrilling.storage_to_form() --> %s" % str(e))
  732. pass
  733. def form_to_storage(self):
  734. """
  735. Will update the 'storage' attribute which is the dict self.tools with data collected from GUI
  736. :return: None
  737. :rtype:
  738. """
  739. if self.t_ui.tools_table.rowCount() == 2:
  740. # there is no tool in tool table so we can't save the GUI elements values to storage
  741. # Excellon Tool Table has 2 rows by default
  742. return
  743. self.blockSignals(True)
  744. widget_changed = self.sender()
  745. wdg_objname = widget_changed.objectName()
  746. option_changed = self.name2option[wdg_objname]
  747. # row = self.t_ui.tools_table.currentRow()
  748. rows = sorted(list(set(index.row() for index in self.t_ui.tools_table.selectedIndexes())))
  749. for row in rows:
  750. if row < 0:
  751. row = 0
  752. tooluid_item = int(self.t_ui.tools_table.item(row, 3).text())
  753. for tooluid_key, tooluid_val in self.excellon_tools.items():
  754. if int(tooluid_key) == tooluid_item:
  755. new_option_value = self.form_fields[option_changed].get_value()
  756. if option_changed in tooluid_val:
  757. tooluid_val[option_changed] = new_option_value
  758. if option_changed in tooluid_val['data']:
  759. tooluid_val['data'][option_changed] = new_option_value
  760. self.blockSignals(False)
  761. def get_selected_tools_list(self):
  762. """
  763. Returns the keys to the self.tools dictionary corresponding
  764. to the selections on the tool list in the appGUI.
  765. :return: List of tools.
  766. :rtype: list
  767. """
  768. return [str(x.text()) for x in self.t_ui.tools_table.selectedItems()]
  769. def get_selected_tools_table_items(self):
  770. """
  771. Returns a list of lists, each list in the list is made out of row elements
  772. :return: List of table_tools items.
  773. :rtype: list
  774. """
  775. table_tools_items = []
  776. rows = set()
  777. for x in self.t_ui.tools_table.selectedItems():
  778. rows.add(x.row())
  779. for row in rows:
  780. txt = ''
  781. elem = []
  782. for column in range(self.t_ui.tools_table.columnCount()):
  783. if column == 3:
  784. # disregard this column since it's the toolID
  785. continue
  786. try:
  787. txt = self.t_ui.tools_table.item(row, column).text()
  788. except AttributeError:
  789. try:
  790. txt = self.t_ui.tools_table.cellWidget(row, column).currentText()
  791. except AttributeError:
  792. pass
  793. elem.append(txt)
  794. table_tools_items.append(deepcopy(elem))
  795. # table_tools_items.append([self.t_ui.tools_table.item(x.row(), column).text()
  796. # for column in range(0, self.t_ui.tools_table.columnCount() - 1)])
  797. for item in table_tools_items:
  798. item[0] = str(item[0])
  799. return table_tools_items
  800. def on_apply_param_to_all_clicked(self):
  801. if self.t_ui.tools_table.rowCount() == 0:
  802. # there is no tool in tool table so we can't save the GUI elements values to storage
  803. log.debug("ToolDrilling.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  804. return
  805. self.blockSignals(True)
  806. row = self.t_ui.tools_table.currentRow()
  807. if row < 0:
  808. row = 0
  809. tooluid_item = int(self.t_ui.tools_table.item(row, 3).text())
  810. temp_tool_data = {}
  811. for tooluid_key, tooluid_val in self.excellon_tools.items():
  812. if int(tooluid_key) == tooluid_item:
  813. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  814. # the current row in the tool table
  815. temp_tool_data = tooluid_val['data']
  816. break
  817. for tooluid_key, tooluid_val in self.excellon_tools.items():
  818. tooluid_val['data'] = deepcopy(temp_tool_data)
  819. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  820. self.blockSignals(False)
  821. def on_order_changed(self, order):
  822. if order != 'no':
  823. self.build_tool_ui()
  824. def on_tooltable_cellwidget_change(self):
  825. cw = self.sender()
  826. assert isinstance(cw, QtWidgets.QComboBox), \
  827. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  828. cw_index = self.t_ui.tools_table.indexAt(cw.pos())
  829. cw_row = cw_index.row()
  830. cw_col = cw_index.column()
  831. current_uid = int(self.t_ui.tools_table.item(cw_row, 3).text())
  832. # if the sender is in the column with index 2 then we update the tool_type key
  833. if cw_col == 2:
  834. tt = cw.currentText()
  835. typ = 'Iso' if tt == 'V' else "Rough"
  836. self.excellon_tools[current_uid].update({
  837. 'type': typ,
  838. 'tool_type': tt,
  839. })
  840. def on_pp_changed(self):
  841. current_pp = self.t_ui.pp_excellon_name_cb.get_value()
  842. if "toolchange_probe" in current_pp.lower():
  843. self.t_ui.pdepth_entry.setVisible(True)
  844. self.t_ui.pdepth_label.show()
  845. self.t_ui.feedrate_probe_entry.setVisible(True)
  846. self.t_ui.feedrate_probe_label.show()
  847. else:
  848. self.t_ui.pdepth_entry.setVisible(False)
  849. self.t_ui.pdepth_label.hide()
  850. self.t_ui.feedrate_probe_entry.setVisible(False)
  851. self.t_ui.feedrate_probe_label.hide()
  852. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  853. self.t_ui.feedrate_rapid_label.show()
  854. self.t_ui.feedrate_rapid_entry.show()
  855. else:
  856. self.t_ui.feedrate_rapid_label.hide()
  857. self.t_ui.feedrate_rapid_entry.hide()
  858. if 'laser' in current_pp.lower():
  859. self.t_ui.cutzlabel.hide()
  860. self.t_ui.cutz_entry.hide()
  861. try:
  862. self.t_ui.mpass_cb.hide()
  863. self.t_ui.maxdepth_entry.hide()
  864. except AttributeError:
  865. pass
  866. if 'marlin' in current_pp.lower():
  867. self.t_ui.travelzlabel.setText('%s:' % _("Focus Z"))
  868. self.t_ui.endz_label.show()
  869. self.t_ui.endz_entry.show()
  870. else:
  871. self.t_ui.travelzlabel.hide()
  872. self.t_ui.travelz_entry.hide()
  873. self.t_ui.endz_label.hide()
  874. self.t_ui.endz_entry.hide()
  875. try:
  876. self.t_ui.frzlabel.hide()
  877. self.t_ui.feedrate_z_entry.hide()
  878. except AttributeError:
  879. pass
  880. self.t_ui.dwell_cb.hide()
  881. self.t_ui.dwelltime_entry.hide()
  882. self.t_ui.spindle_label.setText('%s:' % _("Laser Power"))
  883. try:
  884. self.t_ui.tool_offset_label.hide()
  885. self.t_ui.offset_entry.hide()
  886. except AttributeError:
  887. pass
  888. else:
  889. self.t_ui.cutzlabel.show()
  890. self.t_ui.cutz_entry.show()
  891. try:
  892. self.t_ui.mpass_cb.show()
  893. self.t_ui.maxdepth_entry.show()
  894. except AttributeError:
  895. pass
  896. self.t_ui.travelzlabel.setText('%s:' % _('Travel Z'))
  897. self.t_ui.travelzlabel.show()
  898. self.t_ui.travelz_entry.show()
  899. self.t_ui.endz_label.show()
  900. self.t_ui.endz_entry.show()
  901. try:
  902. self.t_ui.frzlabel.show()
  903. self.t_ui.feedrate_z_entry.show()
  904. except AttributeError:
  905. pass
  906. self.t_ui.dwell_cb.show()
  907. self.t_ui.dwelltime_entry.show()
  908. self.t_ui.spindle_label.setText('%s:' % _('Spindle speed'))
  909. try:
  910. # self.t_ui.tool_offset_lbl.show()
  911. self.t_ui.offset_entry.show()
  912. except AttributeError:
  913. pass
  914. def on_key_press(self, event):
  915. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  916. # matplotlib_key_flag = False
  917. # events out of the self.app.collection view (it's about Project Tab) are of type int
  918. if type(event) is int:
  919. key = event
  920. # events from the GUI are of type QKeyEvent
  921. elif type(event) == QtGui.QKeyEvent:
  922. key = event.key()
  923. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  924. # matplotlib_key_flag = True
  925. key = event.key
  926. key = QtGui.QKeySequence(key)
  927. # check for modifiers
  928. key_string = key.toString().lower()
  929. if '+' in key_string:
  930. mod, __, key_text = key_string.rpartition('+')
  931. if mod.lower() == 'ctrl':
  932. # modifiers = QtCore.Qt.ControlModifier
  933. pass
  934. elif mod.lower() == 'alt':
  935. # modifiers = QtCore.Qt.AltModifier
  936. pass
  937. elif mod.lower() == 'shift':
  938. # modifiers = QtCore.Qt.ShiftModifier
  939. pass
  940. else:
  941. # modifiers = QtCore.Qt.NoModifier
  942. pass
  943. key = QtGui.QKeySequence(key_text)
  944. # events from Vispy are of type KeyEvent
  945. else:
  946. key = event.key
  947. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  948. self.points = []
  949. self.poly_drawn = False
  950. self.delete_moving_selection_shape()
  951. self.delete_tool_selection_shape()
  952. def on_add_area_click(self):
  953. shape_button = self.t_ui.area_shape_radio
  954. overz_button = self.t_ui.over_z_entry
  955. strategy_radio = self.t_ui.strategy_radio
  956. cnc_button = self.t_ui.generate_cnc_button
  957. solid_geo = self.excellon_obj.solid_geometry
  958. obj_type = self.excellon_obj.kind
  959. self.app.exc_areas.on_add_area_click(
  960. shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio,
  961. solid_geo=solid_geo, obj_type=obj_type)
  962. def on_clear_area_click(self):
  963. if not self.app.exc_areas.exclusion_areas_storage:
  964. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. There are no exclusion areas to delete."))
  965. return
  966. self.app.exc_areas.on_clear_area_click()
  967. self.app.exc_areas.e_shape_modified.emit()
  968. def on_delete_sel_areas(self):
  969. sel_model = self.t_ui.exclusion_table.selectionModel()
  970. sel_indexes = sel_model.selectedIndexes()
  971. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  972. # so the duplicate rows will not be added
  973. sel_rows = set()
  974. for idx in sel_indexes:
  975. sel_rows.add(idx.row())
  976. if not sel_rows:
  977. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. Nothing is selected."))
  978. return
  979. self.app.exc_areas.delete_sel_shapes(idxs=list(sel_rows))
  980. self.app.exc_areas.e_shape_modified.emit()
  981. def draw_sel_shape(self):
  982. sel_model = self.t_ui.exclusion_table.selectionModel()
  983. sel_indexes = sel_model.selectedIndexes()
  984. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  985. sel_rows = set()
  986. for idx in sel_indexes:
  987. sel_rows.add(idx.row())
  988. self.delete_sel_shape()
  989. if self.app.is_legacy is False:
  990. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  991. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  992. else:
  993. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  994. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  995. for row in sel_rows:
  996. sel_rect = self.app.exc_areas.exclusion_areas_storage[row]['shape']
  997. self.app.move_tool.sel_shapes.add(sel_rect, color=outline, face_color=face, update=True, layer=0,
  998. tolerance=None)
  999. if self.app.is_legacy is True:
  1000. self.app.move_tool.sel_shapes.redraw()
  1001. def clear_selection(self):
  1002. self.app.delete_selection_shape()
  1003. # self.t_ui.exclusion_table.clearSelection()
  1004. def delete_sel_shape(self):
  1005. self.app.delete_selection_shape()
  1006. def update_exclusion_table(self):
  1007. self.exclusion_area_cb_is_checked = True if self.t_ui.exclusion_cb.isChecked() else False
  1008. self.build_tool_ui()
  1009. self.t_ui.exclusion_cb.set_value(self.exclusion_area_cb_is_checked)
  1010. def on_strategy(self, val):
  1011. if val == 'around':
  1012. self.t_ui.over_z_label.setDisabled(True)
  1013. self.t_ui.over_z_entry.setDisabled(True)
  1014. else:
  1015. self.t_ui.over_z_label.setDisabled(False)
  1016. self.t_ui.over_z_entry.setDisabled(False)
  1017. def exclusion_table_toggle_all(self):
  1018. """
  1019. will toggle the selection of all rows in Exclusion Areas table
  1020. :return:
  1021. """
  1022. sel_model = self.t_ui.exclusion_table.selectionModel()
  1023. sel_indexes = sel_model.selectedIndexes()
  1024. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1025. sel_rows = set()
  1026. for idx in sel_indexes:
  1027. sel_rows.add(idx.row())
  1028. if sel_rows:
  1029. self.t_ui.exclusion_table.clearSelection()
  1030. self.delete_sel_shape()
  1031. else:
  1032. self.t_ui.exclusion_table.selectAll()
  1033. self.draw_sel_shape()
  1034. @staticmethod
  1035. def process_slot_as_drills(slot, overlap, add_last_pt=False):
  1036. drills_list = []
  1037. start_pt = slot[0]
  1038. stop_pt = slot[1]
  1039. slot_line = LineString([start_pt, stop_pt])
  1040. drills_list.append(start_pt)
  1041. ii = 0
  1042. while True:
  1043. ii += 1
  1044. target = overlap * ii
  1045. new_pt = slot_line.interpolate(target)
  1046. if new_pt.within(slot_line) is False:
  1047. break
  1048. drills_list.append(new_pt)
  1049. if add_last_pt and stop_pt.distance(drills_list[-1]) >= overlap/10:
  1050. drills_list.append(stop_pt)
  1051. return drills_list
  1052. def on_cnc_button_click(self):
  1053. obj_name = self.t_ui.object_combo.currentText()
  1054. toolchange = self.t_ui.toolchange_cb.get_value()
  1055. # Get source object.
  1056. try:
  1057. obj = self.app.collection.get_by_name(obj_name)
  1058. except Exception:
  1059. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  1060. return
  1061. if obj is None:
  1062. self.app.inform.emit('[ERROR_NOTCL] %s.' % _("Object not found"))
  1063. return
  1064. slots_as_drills = self.t_ui.drill_slots_cb.get_value()
  1065. has_drills = None
  1066. for tool_key, tool_dict in self.excellon_tools.items():
  1067. if 'drills' in tool_dict and tool_dict['drills']:
  1068. has_drills = True
  1069. break
  1070. has_slots = None
  1071. for tool_key, tool_dict in self.excellon_tools.items():
  1072. if 'slots' in tool_dict and tool_dict['slots']:
  1073. has_slots = True
  1074. break
  1075. if not has_drills:
  1076. if slots_as_drills and has_slots:
  1077. pass
  1078. else:
  1079. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  1080. "The loaded Excellon file has no drills ...")
  1081. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  1082. return
  1083. # Get the tools from the Tool Table
  1084. selected_uid = set()
  1085. for sel_it in self.t_ui.tools_table.selectedItems():
  1086. uid = int(self.t_ui.tools_table.item(sel_it.row(), 3).text())
  1087. selected_uid.add(uid)
  1088. selected_tools_id = list(selected_uid)
  1089. if len(selected_tools_id) == 0:
  1090. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1091. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1092. # in this case regardless of the selection status of that tool, use it.
  1093. if self.t_ui.tools_table.rowCount() >= 3:
  1094. selected_tools_id.append(int(self.t_ui.tools_table.item(0, 3).text()))
  1095. else:
  1096. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1097. _("Please select one or more tools from the list and try again."))
  1098. return
  1099. xmin = obj.options['xmin']
  1100. ymin = obj.options['ymin']
  1101. xmax = obj.options['xmax']
  1102. ymax = obj.options['ymax']
  1103. job_name = obj.options["name"] + "_cnc"
  1104. obj.pp_excellon_name = self.t_ui.pp_excellon_name_cb.get_value()
  1105. # #############################################################################################################
  1106. # #############################################################################################################
  1107. # TOOLS
  1108. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  1109. # so we actually are sorting the tools by diameter
  1110. # #############################################################################################################
  1111. # #############################################################################################################
  1112. all_tools = []
  1113. for tool_as_key, v in list(self.excellon_tools.items()):
  1114. all_tools.append((int(tool_as_key), float(v['tooldia'])))
  1115. order = self.t_ui.order_radio.get_value()
  1116. if order == 'fwd':
  1117. sorted_tools = sorted(all_tools, key=lambda t1: t1[1])
  1118. elif order == 'rev':
  1119. sorted_tools = sorted(all_tools, key=lambda t1: t1[1], reverse=True)
  1120. else:
  1121. sorted_tools = all_tools
  1122. # Create a sorted list of selected sel_tools from the sorted_tools list
  1123. sel_tools = [i for i, j in sorted_tools for k in selected_tools_id if i == k]
  1124. log.debug("Tools sorted are: %s" % str(sel_tools))
  1125. # #############################################################################################################
  1126. # #############################################################################################################
  1127. # #############################################################################################################
  1128. # #############################################################################################################
  1129. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  1130. # #############################################################################################################
  1131. # #############################################################################################################
  1132. self.app.inform.emit(_("Creating a list of points to drill..."))
  1133. points = {}
  1134. for tool_key, tl_dict in self.excellon_tools.items():
  1135. if tool_key in sel_tools:
  1136. if self.app.abort_flag:
  1137. # graceful abort requested by the user
  1138. raise grace
  1139. if 'drills' in tl_dict and tl_dict['drills']:
  1140. for drill_pt in tl_dict['drills']:
  1141. try:
  1142. points[tool_key].append(drill_pt)
  1143. except KeyError:
  1144. points[tool_key] = [drill_pt]
  1145. log.debug("Found %d TOOLS with drills." % len(points))
  1146. # add slots as drills
  1147. should_add_last_pt = self.t_ui.last_drill_cb.get_value()
  1148. if slots_as_drills:
  1149. for tool_key, tl_dict in self.excellon_tools.items():
  1150. if tool_key in sel_tools:
  1151. if self.app.abort_flag:
  1152. # graceful abort requested by the user
  1153. raise grace
  1154. overlap = 1 - (self.t_ui.drill_overlap_entry.get_value() / 100.0)
  1155. drill_overlap = 0.0
  1156. for i in sorted_tools:
  1157. if i[0] == tool_key:
  1158. slot_tool_dia = i[1]
  1159. drill_overlap = overlap * slot_tool_dia
  1160. break
  1161. new_drills = []
  1162. if 'slots' in tl_dict and tl_dict['slots']:
  1163. for slot in tl_dict['slots']:
  1164. new_drills += self.process_slot_as_drills(slot=slot, overlap=drill_overlap,
  1165. add_last_pt=should_add_last_pt)
  1166. if new_drills:
  1167. try:
  1168. points[tool_key] += new_drills
  1169. except Exception:
  1170. points[tool_key] = new_drills
  1171. log.debug("Found %d TOOLS with drills after converting slots to drills." % len(points))
  1172. # check if there are drill points in the exclusion areas.
  1173. # If we find any within the exclusion areas return 'fail'
  1174. for tool_key in points:
  1175. for pt in points[tool_key]:
  1176. for area in self.app.exc_areas.exclusion_areas_storage:
  1177. pt_buf = pt.buffer(self.exc_tools[tool_key]['tooldia'] / 2.0)
  1178. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  1179. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  1180. return 'fail'
  1181. # #############################################################################################################
  1182. # General Parameters
  1183. # #############################################################################################################
  1184. used_excellon_optimization_type = self.app.defaults["excellon_optimization_type"]
  1185. current_platform = platform.architecture()[0]
  1186. if current_platform != '64bit':
  1187. used_excellon_optimization_type = 'T'
  1188. # #############################################################################################################
  1189. # #############################################################################################################
  1190. # GCODE creation
  1191. # #############################################################################################################
  1192. # #############################################################################################################
  1193. self.app.inform.emit('%s...' % _("Starting G-Code"))
  1194. # Object initialization function for app.app_obj.new_object()
  1195. def job_init(job_obj, app_obj):
  1196. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1197. app_obj.inform.emit(_("Generating Excellon CNCJob..."))
  1198. # #########################################################################################################
  1199. # #########################################################################################################
  1200. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  1201. # running this method from a Tcl Command
  1202. # #########################################################################################################
  1203. # #########################################################################################################
  1204. build_tools_in_use_list = False
  1205. if 'Tools_in_use' not in job_obj.options:
  1206. job_obj.options['Tools_in_use'] = []
  1207. # if the list is empty (either we just added the key or it was already there but empty) signal to build it
  1208. if not job_obj.options['Tools_in_use']:
  1209. build_tools_in_use_list = True
  1210. # #########################################################################################################
  1211. # #########################################################################################################
  1212. # fill the data into the self.exc_cnc_tools dictionary
  1213. # #########################################################################################################
  1214. # #########################################################################################################
  1215. for it in all_tools:
  1216. for to_ol in sel_tools:
  1217. if to_ol == it[0]:
  1218. sol_geo = []
  1219. drill_no = 0
  1220. if 'drills' in self.excellon_tools[to_ol]:
  1221. drill_no = len(self.excellon_tools[to_ol]['drills'])
  1222. for drill in self.excellon_tools[to_ol]['drills']:
  1223. sol_geo.append(drill.buffer((it[1] / 2.0), resolution=job_obj.geo_steps_per_circle))
  1224. slot_no = 0
  1225. if 'slots' in self.excellon_tools[to_ol]:
  1226. slot_no = len(self.excellon_tools[to_ol]['slots'])
  1227. for eslot in self.excellon_tools[to_ol]['slots']:
  1228. start = (eslot[0].x, eslot[0].y)
  1229. stop = (eslot[1].x, eslot[1].y)
  1230. sol_geo.append(
  1231. LineString([start, stop]).buffer((it[1] / 2.0),
  1232. resolution=job_obj.geo_steps_per_circle)
  1233. )
  1234. try:
  1235. z_off = float(self.excellon_tools[it[0]]['data']['offset']) * (-1)
  1236. except KeyError:
  1237. z_off = 0
  1238. default_data = {}
  1239. for kk, vv in list(obj.options.items()):
  1240. default_data[kk] = deepcopy(vv)
  1241. job_obj.exc_cnc_tools[it[1]] = {}
  1242. job_obj.exc_cnc_tools[it[1]]['tool'] = it[0]
  1243. job_obj.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  1244. job_obj.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  1245. job_obj.exc_cnc_tools[it[1]]['offset'] = z_off
  1246. job_obj.exc_cnc_tools[it[1]]['data'] = default_data
  1247. job_obj.exc_cnc_tools[it[1]]['gcode'] = ''
  1248. job_obj.exc_cnc_tools[it[1]]['gcode_parsed'] = []
  1249. job_obj.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  1250. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case
  1251. # of running this method from a Tcl Command
  1252. if build_tools_in_use_list is True:
  1253. job_obj.options['Tools_in_use'].append(
  1254. [it[0], it[1], drill_no, slot_no]
  1255. )
  1256. # #########################################################################################################
  1257. # #########################################################################################################
  1258. # Initialization
  1259. # #########################################################################################################
  1260. # #########################################################################################################
  1261. # Prepprocessor
  1262. job_obj.pp_excellon_name = self.default_data["tools_drill_ppname_e"]
  1263. job_obj.pp_excellon = self.app.preprocessors[job_obj.pp_excellon_name]
  1264. p = job_obj.pp_excellon
  1265. job_obj.xy_toolchange = self.app.defaults["excellon_toolchangexy"]
  1266. if job_obj.xy_toolchange is not None:
  1267. job_obj.oldx = job_obj.xy_toolchange[0]
  1268. job_obj.oldy = job_obj.xy_toolchange[1]
  1269. else:
  1270. job_obj.oldx = 0.0
  1271. job_obj.oldy = 0.0
  1272. # get the tool_table items in a list of row items
  1273. tool_table_items = self.get_selected_tools_table_items()
  1274. # insert an information only element in the front
  1275. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1276. # ## Add properties to the object
  1277. job_obj.origin_kind = 'excellon'
  1278. job_obj.options['Tools_in_use'] = tool_table_items
  1279. job_obj.options['type'] = 'Excellon'
  1280. job_obj.options['ppname_e'] = obj.pp_excellon_name
  1281. job_obj.toolchange_xy_type = "excellon"
  1282. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1283. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1284. job_obj.options['xmin'] = xmin
  1285. job_obj.options['ymin'] = ymin
  1286. job_obj.options['xmax'] = xmax
  1287. job_obj.options['ymax'] = ymax
  1288. start_gcode = job_obj.doformat(p.start_code)
  1289. job_obj.multitool = True
  1290. if toolchange is True:
  1291. add_start_gcode = True
  1292. for tool in sel_tools:
  1293. tool_points = points[tool]
  1294. used_tooldia = self.excellon_tools[tool]['tooldia']
  1295. if slots_as_drills is True:
  1296. nr_drills = len(points[tool])
  1297. nr_slots = 0
  1298. job_obj.exc_cnc_tools[used_tooldia]['nr_drills'] = nr_drills
  1299. job_obj.exc_cnc_tools[used_tooldia]['nr_slots'] = nr_slots
  1300. for line in range(1, len(job_obj.options['Tools_in_use'])):
  1301. if float('%.*f' % (self.decimals, float(job_obj.options['Tools_in_use'][line][1]))) == \
  1302. float('%.*f' % (self.decimals, used_tooldia)):
  1303. job_obj.options['Tools_in_use'][line][2] = str(nr_drills)
  1304. job_obj.options['Tools_in_use'][line][3] = str(nr_slots)
  1305. tool_gcode = job_obj.gcode_from_excellon_by_tool(tool, tool_points, self.excellon_tools,
  1306. opt_type=used_excellon_optimization_type,
  1307. toolchange=True)
  1308. if add_start_gcode is True:
  1309. tool_gcode = start_gcode + tool_gcode
  1310. add_start_gcode = False
  1311. job_obj.exc_cnc_tools[used_tooldia]['gcode'] = tool_gcode
  1312. tool_gcode_parsed = job_obj.excellon_tool_gcode_parse(used_tooldia,
  1313. start_pt=(job_obj.oldx, job_obj.oldy))
  1314. job_obj.exc_cnc_tools[used_tooldia]['gcode_parsed'] = tool_gcode_parsed
  1315. self.total_gcode += tool_gcode
  1316. self.total_gcode_parsed += tool_gcode_parsed
  1317. else:
  1318. tool_points = []
  1319. for tool in sel_tools:
  1320. tool_points += points[tool]
  1321. used_tool = sel_tools[0]
  1322. used_tooldia = self.excellon_tools[used_tool]['tooldia']
  1323. # those are used by the preprocessors to display data on the toolchange line
  1324. job_obj.tool = str(used_tool)
  1325. job_obj.postdata['toolC'] = used_tooldia
  1326. # reconstitute the tool_table_items to hold the total number of drills and slots since we are going to
  1327. # process all in one go with no toolchange and with only one tool
  1328. nr_drills = 0
  1329. nr_slots = 0
  1330. if slots_as_drills is False:
  1331. for line in range(1, len(tool_table_items)):
  1332. # we may have exception ValueError if there are no drills/slots for the current tool/line
  1333. try:
  1334. nr_drills += int(tool_table_items[line][2])
  1335. except ValueError:
  1336. pass
  1337. try:
  1338. nr_slots += int(tool_table_items[line][3])
  1339. except ValueError:
  1340. pass
  1341. else:
  1342. # if the slots are converted to drills then make slots number = 0 and count the converted drills
  1343. for t in points:
  1344. nr_drills += len(points[t])
  1345. nr_slots = 0
  1346. job_obj.exc_cnc_tools[used_tooldia]['nr_drills'] = nr_drills
  1347. job_obj.exc_cnc_tools[used_tooldia]['nr_slots'] = nr_slots
  1348. tool_table_items.clear()
  1349. tool_table_items = [[str(used_tool), str(used_tooldia), str(nr_drills), str(nr_slots)]]
  1350. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1351. job_obj.options['Tools_in_use'] = tool_table_items
  1352. tool_gcode = start_gcode
  1353. # TODO set the oldx and oldy to start values
  1354. # add a Toolchange event here to load the first tool
  1355. tool_gcode += job_obj.doformat(p.toolchange_code, toolchangexy=(job_obj.oldx, job_obj.oldy))
  1356. tool_gcode += job_obj.gcode_from_excellon_by_tool(used_tool, tool_points, self.excellon_tools,
  1357. opt_type=used_excellon_optimization_type,
  1358. toolchange=False)
  1359. job_obj.exc_cnc_tools[used_tooldia]['gcode'] = tool_gcode
  1360. tool_gcode_parsed = job_obj.excellon_tool_gcode_parse(used_tooldia,
  1361. start_pt=(job_obj.oldx, job_obj.oldy))
  1362. job_obj.exc_cnc_tools[used_tooldia]['gcode_parsed'] = tool_gcode_parsed
  1363. self.total_gcode = tool_gcode
  1364. self.total_gcode_parsed = tool_gcode_parsed
  1365. job_obj.gcode = self.total_gcode
  1366. job_obj.gcode_parsed = self.total_gcode_parsed
  1367. if job_obj.gcode == 'fail':
  1368. return 'fail'
  1369. job_obj.create_geometry()
  1370. if used_excellon_optimization_type == 'M':
  1371. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" %
  1372. str(job_obj.measured_distance))
  1373. elif used_excellon_optimization_type == 'B':
  1374. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" %
  1375. str(job_obj.measured_distance))
  1376. elif used_excellon_optimization_type == 'T':
  1377. log.debug(
  1378. "The total travel distance with Travelling Salesman Algorithm is: %s" %
  1379. str(job_obj.measured_distance))
  1380. else:
  1381. log.debug("The total travel distance with with no optimization is: %s" %
  1382. str(job_obj.measured_distance))
  1383. # #########################################################################################################
  1384. # ############################# Calculate DISTANCE and ESTIMATED TIME #####################################
  1385. # #########################################################################################################
  1386. if job_obj.xy_end is None:
  1387. job_obj.xy_end = [job_obj.oldx, job_obj.oldy]
  1388. job_obj.measured_distance += abs(distance_euclidian(
  1389. job_obj.oldx, job_obj.oldy, job_obj.xy_end[0], job_obj.xy_end[1])
  1390. )
  1391. log.debug("The total travel distance including travel to end position is: %s" %
  1392. str(job_obj.measured_distance) + '\n')
  1393. job_obj.travel_distance = job_obj.measured_distance
  1394. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  1395. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  1396. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only
  1397. # with Marlin preprocessor and derivatives.
  1398. job_obj.routing_time = \
  1399. (job_obj.measured_down_distance + job_obj.measured_up_to_zero_distance) / job_obj.feedrate
  1400. lift_time = job_obj.measured_lift_distance / job_obj.feedrate_rapid
  1401. traveled_time = job_obj.measured_distance / job_obj.feedrate_rapid
  1402. job_obj.routing_time += lift_time + traveled_time
  1403. # To be run in separate thread
  1404. def job_thread(a_obj):
  1405. with self.app.proc_container.new(_("Generating CNC Code")):
  1406. a_obj.app_obj.new_object("cncjob", job_name, job_init)
  1407. # Create promise for the new name.
  1408. self.app.collection.promise(job_name)
  1409. # Send to worker
  1410. # self.app.worker.add_task(job_thread, [self.app])
  1411. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1412. def drilling_handler(self, obj):
  1413. pass
  1414. def reset_fields(self):
  1415. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1416. class DrillingUI:
  1417. toolName = _("Drilling Tool")
  1418. def __init__(self, layout, app):
  1419. self.app = app
  1420. self.decimals = self.app.decimals
  1421. self.layout = layout
  1422. self.tools_frame = QtWidgets.QFrame()
  1423. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  1424. self.layout.addWidget(self.tools_frame)
  1425. self.tools_box = QtWidgets.QVBoxLayout()
  1426. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1427. self.tools_frame.setLayout(self.tools_box)
  1428. self.title_box = QtWidgets.QHBoxLayout()
  1429. self.tools_box.addLayout(self.title_box)
  1430. # ## Title
  1431. title_label = QtWidgets.QLabel("%s" % self.toolName)
  1432. title_label.setStyleSheet("""
  1433. QLabel
  1434. {
  1435. font-size: 16px;
  1436. font-weight: bold;
  1437. }
  1438. """)
  1439. title_label.setToolTip(
  1440. _("Create CNCJob with toolpaths for drilling or milling holes.")
  1441. )
  1442. self.title_box.addWidget(title_label)
  1443. # App Level label
  1444. self.level = QtWidgets.QLabel("")
  1445. self.level.setToolTip(
  1446. _(
  1447. "BASIC is suitable for a beginner. Many parameters\n"
  1448. "are hidden from the user in this mode.\n"
  1449. "ADVANCED mode will make available all parameters.\n\n"
  1450. "To change the application LEVEL, go to:\n"
  1451. "Edit -> Preferences -> General and check:\n"
  1452. "'APP. LEVEL' radio button."
  1453. )
  1454. )
  1455. self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  1456. self.title_box.addWidget(self.level)
  1457. # Grid Layout
  1458. grid0 = QtWidgets.QGridLayout()
  1459. grid0.setColumnStretch(0, 0)
  1460. grid0.setColumnStretch(1, 1)
  1461. self.tools_box.addLayout(grid0)
  1462. self.obj_combo_label = QtWidgets.QLabel('<b>%s</b>:' % _("EXCELLON"))
  1463. self.obj_combo_label.setToolTip(
  1464. _("Excellon object for drilling/milling operation.")
  1465. )
  1466. grid0.addWidget(self.obj_combo_label, 0, 0, 1, 2)
  1467. # ################################################
  1468. # ##### The object to be drilled #################
  1469. # ################################################
  1470. self.object_combo = FCComboBox()
  1471. self.object_combo.setModel(self.app.collection)
  1472. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  1473. # self.object_combo.setCurrentIndex(1)
  1474. self.object_combo.is_last = True
  1475. grid0.addWidget(self.object_combo, 1, 0, 1, 2)
  1476. separator_line = QtWidgets.QFrame()
  1477. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1478. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1479. grid0.addWidget(separator_line, 2, 0, 1, 2)
  1480. # ################################################
  1481. # ########## Excellon Tool Table #################
  1482. # ################################################
  1483. self.tools_table = FCTable(drag_drop=True)
  1484. grid0.addWidget(self.tools_table, 3, 0, 1, 2)
  1485. self.tools_table.setColumnCount(5)
  1486. self.tools_table.setColumnHidden(3, True)
  1487. self.tools_table.setSortingEnabled(False)
  1488. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('Drills'), '', _('Slots')])
  1489. self.tools_table.horizontalHeaderItem(0).setToolTip(
  1490. _("This is the Tool Number.\n"
  1491. "When ToolChange is checked, on toolchange event this value\n"
  1492. "will be showed as a T1, T2 ... Tn in the Machine Code.\n\n"
  1493. "Here the tools are selected for G-code generation."))
  1494. self.tools_table.horizontalHeaderItem(1).setToolTip(
  1495. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  1496. "is the cut width into the material."))
  1497. self.tools_table.horizontalHeaderItem(2).setToolTip(
  1498. _("The number of Drill holes. Holes that are drilled with\n"
  1499. "a drill bit."))
  1500. self.tools_table.horizontalHeaderItem(4).setToolTip(
  1501. _("The number of Slot holes. Holes that are created by\n"
  1502. "milling them with an endmill bit."))
  1503. # Tool order
  1504. self.order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  1505. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  1506. "'No' --> means that the used order is the one in the tool table\n"
  1507. "'Forward' --> means that the tools will be ordered from small to big\n"
  1508. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  1509. "WARNING: using rest machining will automatically set the order\n"
  1510. "in reverse and disable this control."))
  1511. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  1512. {'label': _('Forward'), 'value': 'fwd'},
  1513. {'label': _('Reverse'), 'value': 'rev'}])
  1514. grid0.addWidget(self.order_label, 4, 0)
  1515. grid0.addWidget(self.order_radio, 4, 1)
  1516. separator_line = QtWidgets.QFrame()
  1517. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1518. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1519. grid0.addWidget(separator_line, 5, 0, 1, 2)
  1520. # ###########################################################
  1521. # ############# Create CNC Job ##############################
  1522. # ###########################################################
  1523. self.tool_data_label = QtWidgets.QLabel(
  1524. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  1525. self.tool_data_label.setToolTip(
  1526. _(
  1527. "The data used for creating GCode.\n"
  1528. "Each tool store it's own set of such data."
  1529. )
  1530. )
  1531. grid0.addWidget(self.tool_data_label, 6, 0, 1, 2)
  1532. self.exc_param_frame = QtWidgets.QFrame()
  1533. self.exc_param_frame.setContentsMargins(0, 0, 0, 0)
  1534. grid0.addWidget(self.exc_param_frame, 7, 0, 1, 2)
  1535. self.exc_tools_box = QtWidgets.QVBoxLayout()
  1536. self.exc_tools_box.setContentsMargins(0, 0, 0, 0)
  1537. self.exc_param_frame.setLayout(self.exc_tools_box)
  1538. # #################################################################
  1539. # ################# GRID LAYOUT 3 ###############################
  1540. # #################################################################
  1541. self.grid1 = QtWidgets.QGridLayout()
  1542. self.grid1.setColumnStretch(0, 0)
  1543. self.grid1.setColumnStretch(1, 1)
  1544. self.exc_tools_box.addLayout(self.grid1)
  1545. # Cut Z
  1546. self.cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  1547. self.cutzlabel.setToolTip(
  1548. _("Drill depth (negative)\n"
  1549. "below the copper surface.")
  1550. )
  1551. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1552. self.cutz_entry.set_precision(self.decimals)
  1553. if machinist_setting == 0:
  1554. self.cutz_entry.set_range(-9999.9999, 0.0000)
  1555. else:
  1556. self.cutz_entry.set_range(-9999.9999, 9999.9999)
  1557. self.cutz_entry.setSingleStep(0.1)
  1558. self.cutz_entry.setObjectName("e_cutz")
  1559. self.grid1.addWidget(self.cutzlabel, 4, 0)
  1560. self.grid1.addWidget(self.cutz_entry, 4, 1)
  1561. # Multi-Depth
  1562. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  1563. self.mpass_cb.setToolTip(
  1564. _(
  1565. "Use multiple passes to limit\n"
  1566. "the cut depth in each pass. Will\n"
  1567. "cut multiple times until Cut Z is\n"
  1568. "reached."
  1569. )
  1570. )
  1571. self.mpass_cb.setObjectName("e_multidepth")
  1572. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1573. self.maxdepth_entry.set_precision(self.decimals)
  1574. self.maxdepth_entry.set_range(0, 9999.9999)
  1575. self.maxdepth_entry.setSingleStep(0.1)
  1576. self.maxdepth_entry.setToolTip(_("Depth of each pass (positive)."))
  1577. self.maxdepth_entry.setObjectName("e_depthperpass")
  1578. self.mis_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  1579. self.grid1.addWidget(self.mpass_cb, 5, 0)
  1580. self.grid1.addWidget(self.maxdepth_entry, 5, 1)
  1581. # Travel Z (z_move)
  1582. self.travelzlabel = QtWidgets.QLabel('%s:' % _('Travel Z'))
  1583. self.travelzlabel.setToolTip(
  1584. _("Tool height when travelling\n"
  1585. "across the XY plane.")
  1586. )
  1587. self.travelz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1588. self.travelz_entry.set_precision(self.decimals)
  1589. if machinist_setting == 0:
  1590. self.travelz_entry.set_range(0.00001, 9999.9999)
  1591. else:
  1592. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  1593. self.travelz_entry.setSingleStep(0.1)
  1594. self.travelz_entry.setObjectName("e_travelz")
  1595. self.grid1.addWidget(self.travelzlabel, 6, 0)
  1596. self.grid1.addWidget(self.travelz_entry, 6, 1)
  1597. # Excellon Feedrate Z
  1598. self.frzlabel = QtWidgets.QLabel('%s:' % _('Feedrate Z'))
  1599. self.frzlabel.setToolTip(
  1600. _("Tool speed while drilling\n"
  1601. "(in units per minute).\n"
  1602. "So called 'Plunge' feedrate.\n"
  1603. "This is for linear move G01.")
  1604. )
  1605. self.feedrate_z_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1606. self.feedrate_z_entry.set_precision(self.decimals)
  1607. self.feedrate_z_entry.set_range(0.0, 99999.9999)
  1608. self.feedrate_z_entry.setSingleStep(0.1)
  1609. self.feedrate_z_entry.setObjectName("e_feedratez")
  1610. self.grid1.addWidget(self.frzlabel, 14, 0)
  1611. self.grid1.addWidget(self.feedrate_z_entry, 14, 1)
  1612. # Excellon Rapid Feedrate
  1613. self.feedrate_rapid_label = QtWidgets.QLabel('%s:' % _('Feedrate Rapids'))
  1614. self.feedrate_rapid_label.setToolTip(
  1615. _("Tool speed while drilling\n"
  1616. "(in units per minute).\n"
  1617. "This is for the rapid move G00.\n"
  1618. "It is useful only for Marlin,\n"
  1619. "ignore for any other cases.")
  1620. )
  1621. self.feedrate_rapid_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1622. self.feedrate_rapid_entry.set_precision(self.decimals)
  1623. self.feedrate_rapid_entry.set_range(0.0, 99999.9999)
  1624. self.feedrate_rapid_entry.setSingleStep(0.1)
  1625. self.feedrate_rapid_entry.setObjectName("e_fr_rapid")
  1626. self.grid1.addWidget(self.feedrate_rapid_label, 16, 0)
  1627. self.grid1.addWidget(self.feedrate_rapid_entry, 16, 1)
  1628. # default values is to hide
  1629. self.feedrate_rapid_label.hide()
  1630. self.feedrate_rapid_entry.hide()
  1631. # Spindlespeed
  1632. self.spindle_label = QtWidgets.QLabel('%s:' % _('Spindle speed'))
  1633. self.spindle_label.setToolTip(
  1634. _("Speed of the spindle\n"
  1635. "in RPM (optional)")
  1636. )
  1637. self.spindlespeed_entry = FCSpinner(callback=self.confirmation_message_int)
  1638. self.spindlespeed_entry.set_range(0, 1000000)
  1639. self.spindlespeed_entry.set_step(100)
  1640. self.spindlespeed_entry.setObjectName("e_spindlespeed")
  1641. self.grid1.addWidget(self.spindle_label, 19, 0)
  1642. self.grid1.addWidget(self.spindlespeed_entry, 19, 1)
  1643. # Dwell
  1644. self.dwell_cb = FCCheckBox('%s:' % _('Dwell'))
  1645. self.dwell_cb.setToolTip(
  1646. _("Pause to allow the spindle to reach its\n"
  1647. "speed before cutting.")
  1648. )
  1649. self.dwell_cb.setObjectName("e_dwell")
  1650. # Dwelltime
  1651. self.dwelltime_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1652. self.dwelltime_entry.set_precision(self.decimals)
  1653. self.dwelltime_entry.set_range(0.0, 9999.9999)
  1654. self.dwelltime_entry.setSingleStep(0.1)
  1655. self.dwelltime_entry.setToolTip(
  1656. _("Number of time units for spindle to dwell.")
  1657. )
  1658. self.dwelltime_entry.setObjectName("e_dwelltime")
  1659. self.grid1.addWidget(self.dwell_cb, 20, 0)
  1660. self.grid1.addWidget(self.dwelltime_entry, 20, 1)
  1661. self.ois_dwell = OptionalInputSection(self.dwell_cb, [self.dwelltime_entry])
  1662. # Tool Offset
  1663. self.tool_offset_label = QtWidgets.QLabel('%s:' % _('Offset Z'))
  1664. self.tool_offset_label.setToolTip(
  1665. _("Some drill bits (the larger ones) need to drill deeper\n"
  1666. "to create the desired exit hole diameter due of the tip shape.\n"
  1667. "The value here can compensate the Cut Z parameter.")
  1668. )
  1669. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1670. self.offset_entry.set_precision(self.decimals)
  1671. self.offset_entry.set_range(-9999.9999, 9999.9999)
  1672. self.offset_entry.setObjectName("e_offset")
  1673. self.grid1.addWidget(self.tool_offset_label, 25, 0)
  1674. self.grid1.addWidget(self.offset_entry, 25, 1)
  1675. # Drill slots
  1676. self.drill_slots_cb = FCCheckBox('%s' % _('Drill slots'))
  1677. self.drill_slots_cb.setToolTip(
  1678. _("If the selected tool has slots then they will be drilled.")
  1679. )
  1680. self.drill_slots_cb.setObjectName("e_drill_slots")
  1681. self.grid1.addWidget(self.drill_slots_cb, 27, 0, 1, 2)
  1682. # Drill Overlap
  1683. self.drill_overlap_label = QtWidgets.QLabel('%s:' % _('Overlap'))
  1684. self.drill_overlap_label.setToolTip(
  1685. _("How much (percentage) of the tool diameter to overlap previous drill hole.")
  1686. )
  1687. self.drill_overlap_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1688. self.drill_overlap_entry.set_precision(self.decimals)
  1689. self.drill_overlap_entry.set_range(0.0, 100.0000)
  1690. self.drill_overlap_entry.setSingleStep(0.1)
  1691. self.drill_overlap_entry.setObjectName("e_drill_slots_overlap")
  1692. self.grid1.addWidget(self.drill_overlap_label, 28, 0)
  1693. self.grid1.addWidget(self.drill_overlap_entry, 28, 1)
  1694. # Last drill in slot
  1695. self.last_drill_cb = FCCheckBox('%s' % _('Last drill'))
  1696. self.last_drill_cb.setToolTip(
  1697. _("If the slot length is not completely covered by drill holes,\n"
  1698. "add a drill hole on the slot end point.")
  1699. )
  1700. self.last_drill_cb.setObjectName("e_drill_last_drill")
  1701. self.grid1.addWidget(self.last_drill_cb, 30, 0, 1, 2)
  1702. self.ois_drill_overlap = OptionalInputSection(
  1703. self.drill_slots_cb,
  1704. [
  1705. self.drill_overlap_label,
  1706. self.drill_overlap_entry,
  1707. self.last_drill_cb
  1708. ]
  1709. )
  1710. # #################################################################
  1711. # ################# GRID LAYOUT 5 ###############################
  1712. # #################################################################
  1713. # ################# COMMON PARAMETERS #############################
  1714. self.grid3 = QtWidgets.QGridLayout()
  1715. self.grid3.setColumnStretch(0, 0)
  1716. self.grid3.setColumnStretch(1, 1)
  1717. self.exc_tools_box.addLayout(self.grid3)
  1718. separator_line2 = QtWidgets.QFrame()
  1719. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  1720. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  1721. self.grid3.addWidget(separator_line2, 0, 0, 1, 2)
  1722. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  1723. self.apply_param_to_all.setToolTip(
  1724. _("The parameters in the current form will be applied\n"
  1725. "on all the tools from the Tool Table.")
  1726. )
  1727. self.grid3.addWidget(self.apply_param_to_all, 1, 0, 1, 2)
  1728. separator_line2 = QtWidgets.QFrame()
  1729. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  1730. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  1731. self.grid3.addWidget(separator_line2, 2, 0, 1, 2)
  1732. # General Parameters
  1733. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  1734. self.gen_param_label.setToolTip(
  1735. _("Parameters that are common for all tools.")
  1736. )
  1737. self.grid3.addWidget(self.gen_param_label, 3, 0, 1, 2)
  1738. # Tool change Z:
  1739. self.toolchange_cb = FCCheckBox('%s:' % _("Tool change Z"))
  1740. self.toolchange_cb.setToolTip(
  1741. _("Include tool-change sequence\n"
  1742. "in G-Code (Pause for tool change).")
  1743. )
  1744. self.toolchangez_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1745. self.toolchangez_entry.set_precision(self.decimals)
  1746. self.toolchangez_entry.setToolTip(
  1747. _("Z-axis position (height) for\n"
  1748. "tool change.")
  1749. )
  1750. if machinist_setting == 0:
  1751. self.toolchangez_entry.set_range(0.0, 9999.9999)
  1752. else:
  1753. self.toolchangez_entry.set_range(-9999.9999, 9999.9999)
  1754. self.toolchangez_entry.setSingleStep(0.1)
  1755. self.ois_tcz_e = OptionalInputSection(self.toolchange_cb, [self.toolchangez_entry])
  1756. self.grid3.addWidget(self.toolchange_cb, 8, 0)
  1757. self.grid3.addWidget(self.toolchangez_entry, 8, 1)
  1758. # Start move Z:
  1759. self.estartz_label = QtWidgets.QLabel('%s:' % _("Start Z"))
  1760. self.estartz_label.setToolTip(
  1761. _("Height of the tool just after start.\n"
  1762. "Delete the value if you don't need this feature.")
  1763. )
  1764. self.estartz_entry = NumericalEvalEntry(border_color='#0069A9')
  1765. self.grid3.addWidget(self.estartz_label, 9, 0)
  1766. self.grid3.addWidget(self.estartz_entry, 9, 1)
  1767. # End move Z:
  1768. self.endz_label = QtWidgets.QLabel('%s:' % _("End move Z"))
  1769. self.endz_label.setToolTip(
  1770. _("Height of the tool after\n"
  1771. "the last move at the end of the job.")
  1772. )
  1773. self.endz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1774. self.endz_entry.set_precision(self.decimals)
  1775. if machinist_setting == 0:
  1776. self.endz_entry.set_range(0.0, 9999.9999)
  1777. else:
  1778. self.endz_entry.set_range(-9999.9999, 9999.9999)
  1779. self.endz_entry.setSingleStep(0.1)
  1780. self.grid3.addWidget(self.endz_label, 11, 0)
  1781. self.grid3.addWidget(self.endz_entry, 11, 1)
  1782. # End Move X,Y
  1783. endmove_xy_label = QtWidgets.QLabel('%s:' % _('End move X,Y'))
  1784. endmove_xy_label.setToolTip(
  1785. _("End move X,Y position. In format (x,y).\n"
  1786. "If no value is entered then there is no move\n"
  1787. "on X,Y plane at the end of the job.")
  1788. )
  1789. self.endxy_entry = NumericalEvalEntry(border_color='#0069A9')
  1790. self.endxy_entry.setPlaceholderText(_("X,Y coordinates"))
  1791. self.grid3.addWidget(endmove_xy_label, 12, 0)
  1792. self.grid3.addWidget(self.endxy_entry, 12, 1)
  1793. # Probe depth
  1794. self.pdepth_label = QtWidgets.QLabel('%s:' % _("Probe Z depth"))
  1795. self.pdepth_label.setToolTip(
  1796. _("The maximum depth that the probe is allowed\n"
  1797. "to probe. Negative value, in current units.")
  1798. )
  1799. self.pdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1800. self.pdepth_entry.set_precision(self.decimals)
  1801. self.pdepth_entry.set_range(-9999.9999, 9999.9999)
  1802. self.pdepth_entry.setSingleStep(0.1)
  1803. self.pdepth_entry.setObjectName("e_depth_probe")
  1804. self.grid3.addWidget(self.pdepth_label, 13, 0)
  1805. self.grid3.addWidget(self.pdepth_entry, 13, 1)
  1806. self.pdepth_label.hide()
  1807. self.pdepth_entry.setVisible(False)
  1808. # Probe feedrate
  1809. self.feedrate_probe_label = QtWidgets.QLabel('%s:' % _("Feedrate Probe"))
  1810. self.feedrate_probe_label.setToolTip(
  1811. _("The feedrate used while the probe is probing.")
  1812. )
  1813. self.feedrate_probe_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1814. self.feedrate_probe_entry.set_precision(self.decimals)
  1815. self.feedrate_probe_entry.set_range(0.0, 9999.9999)
  1816. self.feedrate_probe_entry.setSingleStep(0.1)
  1817. self.feedrate_probe_entry.setObjectName("e_fr_probe")
  1818. self.grid3.addWidget(self.feedrate_probe_label, 14, 0)
  1819. self.grid3.addWidget(self.feedrate_probe_entry, 14, 1)
  1820. self.feedrate_probe_label.hide()
  1821. self.feedrate_probe_entry.setVisible(False)
  1822. # Preprocessor Excellon selection
  1823. pp_excellon_label = QtWidgets.QLabel('%s:' % _("Preprocessor"))
  1824. pp_excellon_label.setToolTip(
  1825. _("The preprocessor JSON file that dictates\n"
  1826. "Gcode output for Excellon Objects.")
  1827. )
  1828. self.pp_excellon_name_cb = FCComboBox()
  1829. self.pp_excellon_name_cb.setFocusPolicy(QtCore.Qt.StrongFocus)
  1830. self.grid3.addWidget(pp_excellon_label, 15, 0)
  1831. self.grid3.addWidget(self.pp_excellon_name_cb, 15, 1)
  1832. # ------------------------------------------------------------------------------------------------------------
  1833. # ------------------------- EXCLUSION AREAS ------------------------------------------------------------------
  1834. # ------------------------------------------------------------------------------------------------------------
  1835. # Exclusion Areas
  1836. self.exclusion_cb = FCCheckBox('%s' % _("Add exclusion areas"))
  1837. self.exclusion_cb.setToolTip(
  1838. _(
  1839. "Include exclusion areas.\n"
  1840. "In those areas the travel of the tools\n"
  1841. "is forbidden."
  1842. )
  1843. )
  1844. self.grid3.addWidget(self.exclusion_cb, 20, 0, 1, 2)
  1845. self.exclusion_frame = QtWidgets.QFrame()
  1846. self.exclusion_frame.setContentsMargins(0, 0, 0, 0)
  1847. self.grid3.addWidget(self.exclusion_frame, 22, 0, 1, 2)
  1848. self.exclusion_box = QtWidgets.QVBoxLayout()
  1849. self.exclusion_box.setContentsMargins(0, 0, 0, 0)
  1850. self.exclusion_frame.setLayout(self.exclusion_box)
  1851. self.exclusion_table = FCTable()
  1852. self.exclusion_box.addWidget(self.exclusion_table)
  1853. self.exclusion_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  1854. self.exclusion_table.setColumnCount(4)
  1855. self.exclusion_table.setColumnWidth(0, 20)
  1856. self.exclusion_table.setHorizontalHeaderLabels(['#', _('Object'), _('Strategy'), _('Over Z')])
  1857. self.exclusion_table.horizontalHeaderItem(0).setToolTip(_("This is the Area ID."))
  1858. self.exclusion_table.horizontalHeaderItem(1).setToolTip(
  1859. _("Type of the object where the exclusion area was added."))
  1860. self.exclusion_table.horizontalHeaderItem(2).setToolTip(
  1861. _("The strategy used for exclusion area. Go around the exclusion areas or over it."))
  1862. self.exclusion_table.horizontalHeaderItem(3).setToolTip(
  1863. _("If the strategy is to go over the area then this is the height at which the tool will go to avoid the "
  1864. "exclusion area."))
  1865. self.exclusion_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1866. grid_a1 = QtWidgets.QGridLayout()
  1867. grid_a1.setColumnStretch(0, 0)
  1868. grid_a1.setColumnStretch(1, 1)
  1869. self.exclusion_box.addLayout(grid_a1)
  1870. # Chose Strategy
  1871. self.strategy_label = FCLabel('%s:' % _("Strategy"))
  1872. self.strategy_label.setToolTip(_("The strategy followed when encountering an exclusion area.\n"
  1873. "Can be:\n"
  1874. "- Over -> when encountering the area, the tool will go to a set height\n"
  1875. "- Around -> will avoid the exclusion area by going around the area"))
  1876. self.strategy_radio = RadioSet([{'label': _('Over'), 'value': 'over'},
  1877. {'label': _('Around'), 'value': 'around'}])
  1878. grid_a1.addWidget(self.strategy_label, 1, 0)
  1879. grid_a1.addWidget(self.strategy_radio, 1, 1)
  1880. # Over Z
  1881. self.over_z_label = FCLabel('%s:' % _("Over Z"))
  1882. self.over_z_label.setToolTip(_("The height Z to which the tool will rise in order to avoid\n"
  1883. "an interdiction area."))
  1884. self.over_z_entry = FCDoubleSpinner()
  1885. self.over_z_entry.set_range(0.000, 9999.9999)
  1886. self.over_z_entry.set_precision(self.decimals)
  1887. grid_a1.addWidget(self.over_z_label, 2, 0)
  1888. grid_a1.addWidget(self.over_z_entry, 2, 1)
  1889. # Button Add Area
  1890. self.add_area_button = QtWidgets.QPushButton(_('Add area:'))
  1891. self.add_area_button.setToolTip(_("Add an Exclusion Area."))
  1892. # Area Selection shape
  1893. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  1894. {'label': _("Polygon"), 'value': 'polygon'}])
  1895. self.area_shape_radio.setToolTip(
  1896. _("The kind of selection shape used for area selection.")
  1897. )
  1898. grid_a1.addWidget(self.add_area_button, 4, 0)
  1899. grid_a1.addWidget(self.area_shape_radio, 4, 1)
  1900. h_lay_1 = QtWidgets.QHBoxLayout()
  1901. self.exclusion_box.addLayout(h_lay_1)
  1902. # Button Delete All Areas
  1903. self.delete_area_button = QtWidgets.QPushButton(_('Delete All'))
  1904. self.delete_area_button.setToolTip(_("Delete all exclusion areas."))
  1905. # Button Delete Selected Areas
  1906. self.delete_sel_area_button = QtWidgets.QPushButton(_('Delete Selected'))
  1907. self.delete_sel_area_button.setToolTip(_("Delete all exclusion areas that are selected in the table."))
  1908. h_lay_1.addWidget(self.delete_area_button)
  1909. h_lay_1.addWidget(self.delete_sel_area_button)
  1910. self.ois_exclusion_exc = OptionalHideInputSection(self.exclusion_cb, [self.exclusion_frame])
  1911. # -------------------------- EXCLUSION AREAS END -------------------------------------------------------------
  1912. # ------------------------------------------------------------------------------------------------------------
  1913. separator_line = QtWidgets.QFrame()
  1914. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1915. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1916. self.grid3.addWidget(separator_line, 25, 0, 1, 2)
  1917. # #################################################################
  1918. # ################# GRID LAYOUT 6 ###############################
  1919. # #################################################################
  1920. self.grid4 = QtWidgets.QGridLayout()
  1921. self.grid4.setColumnStretch(0, 0)
  1922. self.grid4.setColumnStretch(1, 1)
  1923. self.tools_box.addLayout(self.grid4)
  1924. self.generate_cnc_button = QtWidgets.QPushButton(_('Generate CNCJob object'))
  1925. self.generate_cnc_button.setToolTip(
  1926. _("Generate the CNC Job.\n"
  1927. "If milling then an additional Geometry object will be created.\n"
  1928. "Add / Select at least one tool in the tool-table.\n"
  1929. "Click the # header to select all, or Ctrl + LMB\n"
  1930. "for custom selection of tools.")
  1931. )
  1932. self.generate_cnc_button.setStyleSheet("""
  1933. QPushButton
  1934. {
  1935. font-weight: bold;
  1936. }
  1937. """)
  1938. self.grid4.addWidget(self.generate_cnc_button, 3, 0, 1, 3)
  1939. self.tools_box.addStretch()
  1940. # ## Reset Tool
  1941. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  1942. self.reset_button.setToolTip(
  1943. _("Will reset the tool parameters.")
  1944. )
  1945. self.reset_button.setStyleSheet("""
  1946. QPushButton
  1947. {
  1948. font-weight: bold;
  1949. }
  1950. """)
  1951. self.tools_box.addWidget(self.reset_button)
  1952. # ############################ FINSIHED GUI ###################################
  1953. # #############################################################################
  1954. def confirmation_message(self, accepted, minval, maxval):
  1955. if accepted is False:
  1956. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  1957. self.decimals,
  1958. minval,
  1959. self.decimals,
  1960. maxval), False)
  1961. else:
  1962. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1963. def confirmation_message_int(self, accepted, minval, maxval):
  1964. if accepted is False:
  1965. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  1966. (_("Edited value is out of range"), minval, maxval), False)
  1967. else:
  1968. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1969. def distance(pt1, pt2):
  1970. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  1971. def distance_euclidian(x1, y1, x2, y2):
  1972. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  1973. class AttrDict(dict):
  1974. def __init__(self, *args, **kwargs):
  1975. super(AttrDict, self).__init__(*args, **kwargs)
  1976. self.__dict__ = self