ToolDrilling.py 111 KB

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