ToolDrilling.py 112 KB

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