ToolDrilling.py 119 KB

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