ToolDrilling.py 113 KB

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