ToolDrilling.py 107 KB

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