ToolDrilling.py 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096
  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. import math
  15. from shapely.ops import unary_union
  16. from shapely.geometry import Point, LineString
  17. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  18. import logging
  19. import gettext
  20. import appTranslation as fcTranslate
  21. import builtins
  22. import platform
  23. import re
  24. import traceback
  25. from Common import GracefulException as grace
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. if platform.architecture()[0] == '64bit':
  30. from ortools.constraint_solver import pywrapcp
  31. from ortools.constraint_solver import routing_enums_pb2
  32. log = logging.getLogger('base')
  33. settings = QtCore.QSettings("Open Source", "FlatCAM")
  34. if settings.contains("machinist"):
  35. machinist_setting = settings.value('machinist', type=int)
  36. else:
  37. machinist_setting = 0
  38. class ToolDrilling(AppTool, Excellon):
  39. def __init__(self, app):
  40. self.app = app
  41. self.decimals = self.app.decimals
  42. AppTool.__init__(self, app)
  43. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  44. # #############################################################################
  45. # ######################### Tool GUI ##########################################
  46. # #############################################################################
  47. self.t_ui = DrillingUI(layout=self.layout, app=self.app)
  48. self.toolName = self.t_ui.toolName
  49. # #############################################################################
  50. # ########################## VARIABLES ########################################
  51. # #############################################################################
  52. self.units = ''
  53. self.excellon_tools = {}
  54. self.tooluid = 0
  55. self.kind = "excellon"
  56. # dict that holds the object names and the option name
  57. # the key is the object name (defines in ObjectUI) for each UI element that is a parameter
  58. # particular for a tool and the value is the actual name of the option that the UI element is changing
  59. self.name2option = {}
  60. # store here the default data for Geometry Data
  61. self.default_data = {}
  62. self.obj_name = ""
  63. self.excellon_obj = None
  64. # this holds the resulting GCode
  65. self.total_gcode = ''
  66. self.first_click = False
  67. self.cursor_pos = None
  68. self.mouse_is_dragging = False
  69. # store here the points for the "Polygon" area selection shape
  70. self.points = []
  71. self.mm = None
  72. self.mr = None
  73. self.kp = None
  74. # variable to store the total amount of drills per job
  75. self.tot_drill_cnt = 0
  76. self.tool_row = 0
  77. # variable to store the total amount of slots per job
  78. self.tot_slot_cnt = 0
  79. self.tool_row_slots = 0
  80. # variable to store the distance travelled
  81. self.travel_distance = 0.0
  82. self.grid_status_memory = self.app.ui.grid_snap_btn.isChecked()
  83. # store here the state of the exclusion checkbox state to be restored after building the UI
  84. # TODO add this in the sel.app.defaults dict and in Preferences
  85. self.exclusion_area_cb_is_checked = False
  86. # store here solid_geometry when there are tool with isolation job
  87. self.solid_geometry = []
  88. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  89. self.tooldia = None
  90. # multiprocessing
  91. self.pool = self.app.pool
  92. self.results = []
  93. # disconnect flags
  94. self.area_sel_disconnect_flag = False
  95. self.poly_sel_disconnect_flag = False
  96. self.form_fields = {
  97. "cutz": self.t_ui.cutz_entry,
  98. "multidepth": self.t_ui.mpass_cb,
  99. "depthperpass": self.t_ui.maxdepth_entry,
  100. "travelz": self.t_ui.travelz_entry,
  101. "feedrate_z": self.t_ui.feedrate_z_entry,
  102. "feedrate_rapid": self.t_ui.feedrate_rapid_entry,
  103. "spindlespeed": self.t_ui.spindlespeed_entry,
  104. "dwell": self.t_ui.dwell_cb,
  105. "dwelltime": self.t_ui.dwelltime_entry,
  106. "offset": self.t_ui.offset_entry,
  107. "drill_slots": self.t_ui.drill_slots_cb,
  108. "drill_overlap": self.t_ui.drill_overlap_entry,
  109. "last_drill": self.t_ui.last_drill_cb
  110. }
  111. self.name2option = {
  112. "e_cutz": "cutz",
  113. "e_multidepth": "multidepth",
  114. "e_depthperpass": "depthperpass",
  115. "e_travelz": "travelz",
  116. "e_feedratez": "feedrate_z",
  117. "e_fr_rapid": "feedrate_rapid",
  118. "e_spindlespeed": "spindlespeed",
  119. "e_dwell": "dwell",
  120. "e_dwelltime": "dwelltime",
  121. "e_offset": "offset",
  122. "e_drill_slots": "drill_slots",
  123. "e_drill_slots_overlap": "drill_overlap",
  124. "e_drill_last_drill": "last_drill",
  125. }
  126. self.old_tool_dia = None
  127. self.poly_drawn = False
  128. self.connect_signals_at_init()
  129. def install(self, icon=None, separator=None, **kwargs):
  130. AppTool.install(self, icon, separator, shortcut='Alt+D', **kwargs)
  131. def run(self, toggle=True):
  132. self.app.defaults.report_usage("ToolDrilling()")
  133. log.debug("ToolDrilling().run() was launched ...")
  134. if toggle:
  135. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  136. if self.app.ui.splitter.sizes()[0] == 0:
  137. self.app.ui.splitter.setSizes([1, 1])
  138. else:
  139. try:
  140. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  141. # if tab is populated with the tool but it does not have the focus, focus on it
  142. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  143. # focus on Tool Tab
  144. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  145. else:
  146. self.app.ui.splitter.setSizes([0, 1])
  147. except AttributeError:
  148. pass
  149. else:
  150. if self.app.ui.splitter.sizes()[0] == 0:
  151. self.app.ui.splitter.setSizes([1, 1])
  152. AppTool.run(self)
  153. self.set_tool_ui()
  154. self.on_object_changed()
  155. # self.build_tool_ui()
  156. # all the tools are selected by default
  157. self.t_ui.tools_table.selectAll()
  158. self.app.ui.notebook.setTabText(2, _("Drilling Tool"))
  159. def connect_signals_at_init(self):
  160. # #############################################################################
  161. # ############################ SIGNALS ########################################
  162. # #############################################################################
  163. self.t_ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  164. self.t_ui.generate_cnc_button.clicked.connect(self.on_cnc_button_click)
  165. self.t_ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  166. # Exclusion areas signals
  167. self.t_ui.exclusion_table.horizontalHeader().sectionClicked.connect(self.exclusion_table_toggle_all)
  168. self.t_ui.exclusion_table.lost_focus.connect(self.clear_selection)
  169. self.t_ui.exclusion_table.itemClicked.connect(self.draw_sel_shape)
  170. self.t_ui.add_area_button.clicked.connect(self.on_add_area_click)
  171. self.t_ui.delete_area_button.clicked.connect(self.on_clear_area_click)
  172. self.t_ui.delete_sel_area_button.clicked.connect(self.on_delete_sel_areas)
  173. self.t_ui.strategy_radio.activated_custom.connect(self.on_strategy)
  174. self.t_ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  175. self.t_ui.reset_button.clicked.connect(self.set_tool_ui)
  176. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  177. self.app.cleanup.connect(self.set_tool_ui)
  178. def set_tool_ui(self):
  179. self.units = self.app.defaults['units'].upper()
  180. self.old_tool_dia = self.app.defaults["tools_iso_newdia"]
  181. # try to select in the Excellon combobox the active object
  182. try:
  183. selected_obj = self.app.collection.get_active()
  184. if selected_obj.kind == 'excellon':
  185. current_name = selected_obj.options['name']
  186. self.t_ui.object_combo.set_value(current_name)
  187. except Exception:
  188. pass
  189. # reset the Excellon preprocessor combo
  190. self.t_ui.pp_excellon_name_cb.clear()
  191. # populate Excellon preprocessor combobox list
  192. for name in list(self.app.preprocessors.keys()):
  193. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  194. if name == 'hpgl':
  195. continue
  196. self.t_ui.pp_excellon_name_cb.addItem(name)
  197. # add tooltips
  198. for it in range(self.t_ui.pp_excellon_name_cb.count()):
  199. self.t_ui.pp_excellon_name_cb.setItemData(
  200. it, self.t_ui.pp_excellon_name_cb.itemText(it), QtCore.Qt.ToolTipRole)
  201. # update the changes in UI depending on the selected preprocessor in Preferences
  202. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  203. # self.t_ui.pp_excellon_name_cb combobox
  204. self.on_pp_changed()
  205. app_mode = self.app.defaults["global_app_level"]
  206. # Show/Hide Advanced Options
  207. if app_mode == 'b':
  208. self.t_ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  209. self.t_ui.estartz_label.hide()
  210. self.t_ui.estartz_entry.hide()
  211. self.t_ui.feedrate_rapid_label.hide()
  212. self.t_ui.feedrate_rapid_entry.hide()
  213. self.t_ui.pdepth_label.hide()
  214. self.t_ui.pdepth_entry.hide()
  215. self.t_ui.feedrate_probe_label.hide()
  216. self.t_ui.feedrate_probe_entry.hide()
  217. else:
  218. self.t_ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  219. self.t_ui.estartz_label.show()
  220. self.t_ui.estartz_entry.show()
  221. self.t_ui.feedrate_rapid_label.show()
  222. self.t_ui.feedrate_rapid_entry.show()
  223. self.t_ui.pdepth_label.show()
  224. self.t_ui.pdepth_entry.show()
  225. self.t_ui.feedrate_probe_label.show()
  226. self.t_ui.feedrate_probe_entry.show()
  227. self.t_ui.tools_frame.show()
  228. self.t_ui.order_radio.set_value(self.app.defaults["excellon_tool_order"])
  229. loaded_obj = self.app.collection.get_by_name(self.t_ui.object_combo.get_value())
  230. if loaded_obj:
  231. outname = loaded_obj.options['name']
  232. else:
  233. outname = ''
  234. # init the working variables
  235. self.default_data.clear()
  236. self.default_data = {
  237. "name": outname + '_drill',
  238. "plot": self.app.defaults["excellon_plot"],
  239. "solid": self.app.defaults["excellon_solid"],
  240. "multicolored": self.app.defaults["excellon_multicolored"],
  241. "merge_fuse_tools": self.app.defaults["excellon_merge_fuse_tools"],
  242. "format_upper_in": self.app.defaults["excellon_format_upper_in"],
  243. "format_lower_in": self.app.defaults["excellon_format_lower_in"],
  244. "format_upper_mm": self.app.defaults["excellon_format_upper_mm"],
  245. "lower_mm": self.app.defaults["excellon_format_lower_mm"],
  246. "zeros": self.app.defaults["excellon_zeros"],
  247. "excellon_units": self.app.defaults["excellon_units"],
  248. "excellon_update": self.app.defaults["excellon_update"],
  249. "excellon_optimization_type": self.app.defaults["excellon_optimization_type"],
  250. "excellon_search_time": self.app.defaults["excellon_search_time"],
  251. "excellon_plot_fill": self.app.defaults["excellon_plot_fill"],
  252. "excellon_plot_line": self.app.defaults["excellon_plot_line"],
  253. # Excellon Options
  254. "excellon_tool_order": self.app.defaults["excellon_tool_order"],
  255. "cutz": self.app.defaults["excellon_cutz"],
  256. "multidepth": self.app.defaults["excellon_multidepth"],
  257. "depthperpass": self.app.defaults["excellon_depthperpass"],
  258. "travelz": self.app.defaults["excellon_travelz"],
  259. "endz": self.app.defaults["excellon_endz"],
  260. "endxy": self.app.defaults["excellon_endxy"],
  261. "feedrate_z": self.app.defaults["excellon_feedrate_z"],
  262. "spindlespeed": self.app.defaults["excellon_spindlespeed"],
  263. "dwell": self.app.defaults["excellon_dwell"],
  264. "dwelltime": self.app.defaults["excellon_dwelltime"],
  265. "toolchange": self.app.defaults["excellon_toolchange"],
  266. "toolchangez": self.app.defaults["excellon_toolchangez"],
  267. "ppname_e": self.app.defaults["excellon_ppname_e"],
  268. "tooldia": self.app.defaults["excellon_tooldia"],
  269. "slot_tooldia": self.app.defaults["excellon_slot_tooldia"],
  270. "gcode_type": self.app.defaults["excellon_gcode_type"],
  271. "excellon_area_exclusion": self.app.defaults["excellon_area_exclusion"],
  272. "excellon_area_shape": self.app.defaults["excellon_area_shape"],
  273. "excellon_area_strategy": self.app.defaults["excellon_area_strategy"],
  274. "excellon_area_overz": self.app.defaults["excellon_area_overz"],
  275. # Excellon Advanced Options
  276. "offset": self.app.defaults["excellon_offset"],
  277. "toolchangexy": self.app.defaults["excellon_toolchangexy"],
  278. "startz": self.app.defaults["excellon_startz"],
  279. "feedrate_rapid": self.app.defaults["excellon_feedrate_rapid"],
  280. "z_pdepth": self.app.defaults["excellon_z_pdepth"],
  281. "feedrate_probe": self.app.defaults["excellon_feedrate_probe"],
  282. "spindledir": self.app.defaults["excellon_spindledir"],
  283. "f_plunge": self.app.defaults["excellon_f_plunge"],
  284. "f_retract": self.app.defaults["excellon_f_retract"],
  285. # Drill Slots
  286. "drill_slots": self.app.defaults["excellon_drill_slots"],
  287. "drill_overlap": self.app.defaults["excellon_drill_overlap"],
  288. "last_drill": self.app.defaults["excellon_last_drill"],
  289. "gcode": '',
  290. "gcode_parsed": '',
  291. "geometry": [],
  292. }
  293. # fill in self.default_data values from self.options
  294. for opt_key, opt_val in self.app.options.items():
  295. if opt_key.find('excellon_') == 0:
  296. self.default_data[opt_key] = deepcopy(opt_val)
  297. self.first_click = False
  298. self.cursor_pos = None
  299. self.mouse_is_dragging = False
  300. self.units = self.app.defaults['units'].upper()
  301. # ########################################
  302. # #######3 TEMP SETTINGS #################
  303. # ########################################
  304. self.t_ui.tools_table.setRowCount(2)
  305. self.t_ui.tools_table.setMinimumHeight(self.t_ui.tools_table.getHeight())
  306. self.t_ui.tools_table.setMaximumHeight(self.t_ui.tools_table.getHeight())
  307. # make sure to update the UI on init
  308. try:
  309. self.excellon_tools = self.excellon_obj.tools
  310. except AttributeError:
  311. # no object loaded
  312. pass
  313. self.build_tool_ui()
  314. # ########################################
  315. # ########################################
  316. # ####### Fill in the parameters #########
  317. # ########################################
  318. # ########################################
  319. self.t_ui.cutz_entry.set_value(self.app.defaults["excellon_cutz"])
  320. self.t_ui.mpass_cb.set_value(self.app.defaults["excellon_multidepth"])
  321. self.t_ui.maxdepth_entry.set_value(self.app.defaults["excellon_depthperpass"])
  322. self.t_ui.travelz_entry.set_value(self.app.defaults["excellon_travelz"])
  323. self.t_ui.feedrate_z_entry.set_value(self.app.defaults["excellon_feedrate_z"])
  324. self.t_ui.feedrate_rapid_entry.set_value(self.app.defaults["excellon_feedrate_rapid"])
  325. self.t_ui.spindlespeed_entry.set_value(self.app.defaults["excellon_spindlespeed"])
  326. self.t_ui.dwell_cb.set_value(self.app.defaults["excellon_dwell"])
  327. self.t_ui.dwelltime_entry.set_value(self.app.defaults["excellon_dwelltime"])
  328. self.t_ui.offset_entry.set_value(self.app.defaults["excellon_offset"])
  329. self.t_ui.toolchange_cb.set_value(self.app.defaults["excellon_toolchange"])
  330. self.t_ui.toolchangez_entry.set_value(self.app.defaults["excellon_toolchangez"])
  331. self.t_ui.estartz_entry.set_value(self.app.defaults["excellon_startz"])
  332. self.t_ui.endz_entry.set_value(self.app.defaults["excellon_endz"])
  333. self.t_ui.endxy_entry.set_value(self.app.defaults["excellon_endxy"])
  334. self.t_ui.pdepth_entry.set_value(self.app.defaults["excellon_z_pdepth"])
  335. self.t_ui.feedrate_probe_entry.set_value(self.app.defaults["excellon_feedrate_probe"])
  336. self.t_ui.exclusion_cb.set_value(self.app.defaults["excellon_area_exclusion"])
  337. self.t_ui.strategy_radio.set_value(self.app.defaults["excellon_area_strategy"])
  338. self.t_ui.over_z_entry.set_value(self.app.defaults["excellon_area_overz"])
  339. self.t_ui.area_shape_radio.set_value(self.app.defaults["excellon_area_shape"])
  340. # Drill slots - part of the Advanced Excellon params
  341. self.t_ui.drill_slots_cb.set_value(self.app.defaults["excellon_drill_slots"])
  342. self.t_ui.drill_overlap_entry.set_value(self.app.defaults["excellon_drill_overlap"])
  343. self.t_ui.last_drill_cb.set_value(self.app.defaults["excellon_last_drill"])
  344. # if the app mode is Basic then disable this feature
  345. if app_mode == 'b':
  346. self.t_ui.drill_slots_cb.set_value(False)
  347. self.t_ui.drill_slots_cb.hide()
  348. self.t_ui.drill_overlap_label.hide()
  349. self.t_ui.drill_overlap_entry.hide()
  350. self.t_ui.last_drill_cb.hide()
  351. else:
  352. self.t_ui.drill_slots_cb.show()
  353. self.t_ui.drill_overlap_label.show()
  354. self.t_ui.drill_overlap_entry.show()
  355. self.t_ui.last_drill_cb.show()
  356. try:
  357. self.t_ui.object_combo.currentTextChanged.disconnect()
  358. except (AttributeError, TypeError):
  359. pass
  360. self.t_ui.object_combo.currentTextChanged.connect(self.on_object_changed)
  361. def rebuild_ui(self):
  362. # read the table tools uid
  363. current_uid_list = []
  364. for row in range(self.t_ui.tools_table.rowCount()):
  365. try:
  366. uid = int(self.t_ui.tools_table.item(row, 3).text())
  367. current_uid_list.append(uid)
  368. except AttributeError:
  369. continue
  370. new_tools = {}
  371. new_uid = 1
  372. for current_uid in current_uid_list:
  373. new_tools[new_uid] = deepcopy(self.excellon_tools[current_uid])
  374. new_uid += 1
  375. self.excellon_tools = new_tools
  376. # the tools table changed therefore we need to rebuild it
  377. QtCore.QTimer.singleShot(20, self.build_tool_ui)
  378. def build_tool_ui(self):
  379. log.debug("ToolDrilling.build_tool_ui()")
  380. self.ui_disconnect()
  381. # order the tools by tool diameter if it's the case
  382. sorted_tools = []
  383. for k, v in self.excellon_tools.items():
  384. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  385. order = self.t_ui.order_radio.get_value()
  386. if order == 'fwd':
  387. sorted_tools.sort(reverse=False)
  388. elif order == 'rev':
  389. sorted_tools.sort(reverse=True)
  390. else:
  391. pass
  392. # remake the excellon_tools dict in the order above
  393. new_id = 1
  394. new_tools = {}
  395. for tooldia in sorted_tools:
  396. for old_tool in self.excellon_tools:
  397. if float('%.*f' % (self.decimals, float(self.excellon_tools[old_tool]['tooldia']))) == tooldia:
  398. new_tools[new_id] = deepcopy(self.excellon_tools[old_tool])
  399. new_id += 1
  400. self.excellon_tools = new_tools
  401. if self.excellon_obj and self.excellon_tools:
  402. self.t_ui.exc_param_frame.setDisabled(False)
  403. tools = [k for k in self.excellon_tools]
  404. else:
  405. self.t_ui.exc_param_frame.setDisabled(True)
  406. self.t_ui.tools_table.setRowCount(2)
  407. tools = []
  408. n = len(tools)
  409. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  410. self.t_ui.tools_table.setRowCount(n + 2)
  411. self.tool_row = 0
  412. tot_drill_cnt = 0
  413. tot_slot_cnt = 0
  414. for tool_no in tools:
  415. # Find no of drills for the current tool
  416. try:
  417. drill_cnt = len(self.excellon_tools[tool_no]["drills"]) # variable to store the nr of drills per tool
  418. except KeyError:
  419. drill_cnt = 0
  420. tot_drill_cnt += drill_cnt
  421. # Find no of slots for the current tool
  422. try:
  423. slot_cnt = len(self.excellon_tools[tool_no]["slots"]) # variable to store the nr of slots per tool
  424. except KeyError:
  425. slot_cnt = 0
  426. tot_slot_cnt += slot_cnt
  427. # Tool name/id
  428. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  429. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  430. self.t_ui.tools_table.setItem(self.tool_row, 0, exc_id_item)
  431. # Tool Diameter
  432. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.excellon_tools[tool_no]['tooldia']))
  433. dia_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  434. self.t_ui.tools_table.setItem(self.tool_row, 1, dia_item)
  435. # Number of drills per tool
  436. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  437. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  438. self.t_ui.tools_table.setItem(self.tool_row, 2, drill_count_item)
  439. # Tool unique ID
  440. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tool_no)))
  441. # ## REMEMBER: THIS COLUMN IS HIDDEN in UI
  442. self.t_ui.tools_table.setItem(self.tool_row, 3, tool_uid_item)
  443. # Number of slots per tool
  444. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  445. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  446. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  447. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled)
  448. self.t_ui.tools_table.setItem(self.tool_row, 4, slot_count_item)
  449. self.tool_row += 1
  450. # add a last row with the Total number of drills
  451. empty_1 = QtWidgets.QTableWidgetItem('')
  452. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  453. empty_1_1 = QtWidgets.QTableWidgetItem('')
  454. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  455. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  456. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  457. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % tot_drill_cnt)
  458. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  459. self.t_ui.tools_table.setItem(self.tool_row, 0, empty_1)
  460. self.t_ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  461. self.t_ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  462. self.t_ui.tools_table.setItem(self.tool_row, 4, empty_1_1)
  463. font = QtGui.QFont()
  464. font.setBold(True)
  465. font.setWeight(75)
  466. for k in [1, 2]:
  467. self.t_ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  468. self.t_ui.tools_table.item(self.tool_row, k).setFont(font)
  469. self.tool_row += 1
  470. # add a last row with the Total number of slots
  471. empty_2 = QtWidgets.QTableWidgetItem('')
  472. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  473. empty_2_1 = QtWidgets.QTableWidgetItem('')
  474. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  475. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  476. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % tot_slot_cnt)
  477. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  478. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  479. self.t_ui.tools_table.setItem(self.tool_row, 0, empty_2)
  480. self.t_ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  481. self.t_ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  482. self.t_ui.tools_table.setItem(self.tool_row, 4, tot_slot_count) # Total number of slots
  483. for kl in [1, 2, 4]:
  484. self.t_ui.tools_table.item(self.tool_row, kl).setFont(font)
  485. self.t_ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  486. # make the diameter column editable
  487. # for row in range(self.t_ui.tools_table.rowCount() - 2):
  488. # self.t_ui.tools_table.item(row, 1).setFlags(
  489. # QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  490. self.t_ui.tools_table.resizeColumnsToContents()
  491. self.t_ui.tools_table.resizeRowsToContents()
  492. vertical_header = self.t_ui.tools_table.verticalHeader()
  493. vertical_header.hide()
  494. self.t_ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  495. horizontal_header = self.t_ui.tools_table.horizontalHeader()
  496. self.t_ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  497. horizontal_header.setMinimumSectionSize(10)
  498. horizontal_header.setDefaultSectionSize(70)
  499. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  500. horizontal_header.resizeSection(0, 20)
  501. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  502. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  503. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  504. self.t_ui.tools_table.setSortingEnabled(False)
  505. self.t_ui.tools_table.setMinimumHeight(self.t_ui.tools_table.getHeight())
  506. self.t_ui.tools_table.setMaximumHeight(self.t_ui.tools_table.getHeight())
  507. # all the tools are selected by default
  508. self.t_ui.tools_table.selectAll()
  509. # Build Exclusion Areas section
  510. e_len = len(self.app.exc_areas.exclusion_areas_storage)
  511. self.t_ui.exclusion_table.setRowCount(e_len)
  512. area_id = 0
  513. for area in range(e_len):
  514. area_id += 1
  515. area_dict = self.app.exc_areas.exclusion_areas_storage[area]
  516. area_id_item = QtWidgets.QTableWidgetItem('%d' % int(area_id))
  517. area_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  518. self.t_ui.exclusion_table.setItem(area, 0, area_id_item) # Area id
  519. object_item = QtWidgets.QTableWidgetItem('%s' % area_dict["obj_type"])
  520. object_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  521. self.t_ui.exclusion_table.setItem(area, 1, object_item) # Origin Object
  522. strategy_item = QtWidgets.QTableWidgetItem('%s' % area_dict["strategy"])
  523. strategy_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  524. self.t_ui.exclusion_table.setItem(area, 2, strategy_item) # Strategy
  525. overz_item = QtWidgets.QTableWidgetItem('%s' % area_dict["overz"])
  526. overz_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  527. self.t_ui.exclusion_table.setItem(area, 3, overz_item) # Over Z
  528. self.t_ui.exclusion_table.resizeColumnsToContents()
  529. self.t_ui.exclusion_table.resizeRowsToContents()
  530. area_vheader = self.t_ui.exclusion_table.verticalHeader()
  531. area_vheader.hide()
  532. self.t_ui.exclusion_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  533. area_hheader = self.t_ui.exclusion_table.horizontalHeader()
  534. area_hheader.setMinimumSectionSize(10)
  535. area_hheader.setDefaultSectionSize(70)
  536. area_hheader.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  537. area_hheader.resizeSection(0, 20)
  538. area_hheader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  539. area_hheader.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  540. area_hheader.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  541. # area_hheader.setStretchLastSection(True)
  542. self.t_ui.exclusion_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  543. self.t_ui.exclusion_table.setColumnWidth(0, 20)
  544. self.t_ui.exclusion_table.setMinimumHeight(self.t_ui.exclusion_table.getHeight())
  545. self.t_ui.exclusion_table.setMaximumHeight(self.t_ui.exclusion_table.getHeight())
  546. self.ui_connect()
  547. # set the text on tool_data_label after loading the object
  548. sel_rows = set()
  549. sel_items = self.t_ui.tools_table.selectedItems()
  550. for it in sel_items:
  551. sel_rows.add(it.row())
  552. if len(sel_rows) > 1:
  553. self.t_ui.tool_data_label.setText(
  554. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  555. )
  556. elif len(sel_rows) == 1:
  557. # update the QLabel that shows for which Tool we have the parameters in the UI form
  558. toolnr = int(self.t_ui.tools_table.item(list(sel_rows)[0], 0).text())
  559. self.t_ui.tool_data_label.setText(
  560. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), toolnr)
  561. )
  562. def on_object_changed(self):
  563. log.debug("ToolDrilling.on_object_changed()")
  564. # updated units
  565. self.units = self.app.defaults['units'].upper()
  566. # load the Excellon object
  567. self.obj_name = self.t_ui.object_combo.currentText()
  568. # Get source object.
  569. try:
  570. self.excellon_obj = self.app.collection.get_by_name(self.obj_name)
  571. except Exception:
  572. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  573. return
  574. if self.excellon_obj is None:
  575. self.excellon_tools = {}
  576. self.t_ui.exc_param_frame.setDisabled(True)
  577. self.set_tool_ui()
  578. else:
  579. self.excellon_tools = self.excellon_obj.tools
  580. self.app.collection.set_active(self.obj_name)
  581. self.t_ui.exc_param_frame.setDisabled(False)
  582. self.excellon_tools = self.excellon_obj.tools
  583. self.build_tool_ui()
  584. sel_rows = set()
  585. table_items = self.t_ui.tools_table.selectedItems()
  586. if table_items:
  587. for it in table_items:
  588. sel_rows.add(it.row())
  589. if not sel_rows or len(sel_rows) == 0:
  590. self.t_ui.generate_cnc_button.setDisabled(True)
  591. self.t_ui.tool_data_label.setText(
  592. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  593. )
  594. else:
  595. self.t_ui.generate_cnc_button.setDisabled(False)
  596. def ui_connect(self):
  597. # Area Exception - exclusion shape added signal
  598. # first disconnect it from any other object
  599. try:
  600. self.app.exc_areas.e_shape_modified.disconnect()
  601. except (TypeError, AttributeError):
  602. pass
  603. # then connect it to the current build_tool_ui() method
  604. self.app.exc_areas.e_shape_modified.connect(self.update_exclusion_table)
  605. # rows selected
  606. self.t_ui.tools_table.clicked.connect(self.on_row_selection_change)
  607. self.t_ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  608. # Tool Parameters
  609. for opt in self.form_fields:
  610. current_widget = self.form_fields[opt]
  611. if isinstance(current_widget, FCCheckBox):
  612. current_widget.stateChanged.connect(self.form_to_storage)
  613. if isinstance(current_widget, RadioSet):
  614. current_widget.activated_custom.connect(self.form_to_storage)
  615. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  616. current_widget.returnPressed.connect(self.form_to_storage)
  617. elif isinstance(current_widget, FCComboBox):
  618. current_widget.currentIndexChanged.connect(self.form_to_storage)
  619. self.t_ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  620. def ui_disconnect(self):
  621. # rows selected
  622. try:
  623. self.t_ui.tools_table.clicked.disconnect(self.on_row_selection_change)
  624. except (TypeError, AttributeError):
  625. pass
  626. try:
  627. self.t_ui.tools_table.horizontalHeader().sectionClicked.disconnect(self.on_toggle_all_rows)
  628. except (TypeError, AttributeError):
  629. pass
  630. # tool table widgets
  631. for row in range(self.t_ui.tools_table.rowCount()):
  632. try:
  633. self.t_ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  634. except (TypeError, AttributeError):
  635. pass
  636. # Tool Parameters
  637. for opt in self.form_fields:
  638. current_widget = self.form_fields[opt]
  639. if isinstance(current_widget, FCCheckBox):
  640. try:
  641. current_widget.stateChanged.disconnect(self.form_to_storage)
  642. except (TypeError, ValueError):
  643. pass
  644. if isinstance(current_widget, RadioSet):
  645. try:
  646. current_widget.activated_custom.disconnect(self.form_to_storage)
  647. except (TypeError, ValueError):
  648. pass
  649. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  650. try:
  651. current_widget.returnPressed.disconnect(self.form_to_storage)
  652. except (TypeError, ValueError):
  653. pass
  654. elif isinstance(current_widget, FCComboBox):
  655. try:
  656. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  657. except (TypeError, ValueError):
  658. pass
  659. try:
  660. self.t_ui.order_radio.activated_custom[str].disconnect()
  661. except (TypeError, ValueError):
  662. pass
  663. def on_toggle_all_rows(self):
  664. """
  665. will toggle the selection of all rows in Tools table
  666. :return:
  667. """
  668. sel_model = self.t_ui.tools_table.selectionModel()
  669. sel_indexes = sel_model.selectedIndexes()
  670. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  671. sel_rows = set()
  672. for idx in sel_indexes:
  673. sel_rows.add(idx.row())
  674. if len(sel_rows) == self.t_ui.tools_table.rowCount():
  675. self.t_ui.tools_table.clearSelection()
  676. self.t_ui.exc_param_frame.setDisabled(True)
  677. else:
  678. self.t_ui.tools_table.selectAll()
  679. self.t_ui.exc_param_frame.setDisabled(False)
  680. self.update_ui()
  681. def on_row_selection_change(self):
  682. self.update_ui()
  683. def update_ui(self):
  684. self.blockSignals(True)
  685. sel_rows = set()
  686. table_items = self.t_ui.tools_table.selectedItems()
  687. if table_items:
  688. for it in table_items:
  689. sel_rows.add(it.row())
  690. # sel_rows = sorted(set(index.row() for index in self.t_ui.tools_table.selectedIndexes()))
  691. if not sel_rows or len(sel_rows) == 0:
  692. self.t_ui.generate_cnc_button.setDisabled(True)
  693. self.t_ui.exc_param_frame.setDisabled(True)
  694. self.t_ui.tool_data_label.setText(
  695. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  696. )
  697. self.blockSignals(False)
  698. return
  699. else:
  700. self.t_ui.generate_cnc_button.setDisabled(False)
  701. self.t_ui.exc_param_frame.setDisabled(False)
  702. if len(sel_rows) == 1:
  703. # update the QLabel that shows for which Tool we have the parameters in the UI form
  704. tooluid = int(self.t_ui.tools_table.item(list(sel_rows)[0], 0).text())
  705. self.t_ui.tool_data_label.setText(
  706. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  707. )
  708. else:
  709. self.t_ui.tool_data_label.setText(
  710. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  711. )
  712. for c_row in sel_rows:
  713. # populate the form with the data from the tool associated with the row parameter
  714. try:
  715. item = self.t_ui.tools_table.item(c_row, 3)
  716. if type(item) is not None:
  717. tooluid = int(item.text())
  718. self.storage_to_form(self.excellon_tools[tooluid]['data'])
  719. else:
  720. self.blockSignals(False)
  721. return
  722. except Exception as e:
  723. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  724. self.blockSignals(False)
  725. return
  726. self.blockSignals(False)
  727. def storage_to_form(self, dict_storage):
  728. """
  729. Will update the GUI with data from the "storage" in this case the dict self.tools
  730. :param dict_storage: A dictionary holding the data relevant for gnerating Gcode from Excellon
  731. :type dict_storage: dict
  732. :return: None
  733. :rtype:
  734. """
  735. for form_key in self.form_fields:
  736. for storage_key in dict_storage:
  737. if form_key == storage_key and form_key not in \
  738. ["toolchange", "toolchangez", "startz", "endz", "ppname_e", "ppname_g"]:
  739. try:
  740. self.form_fields[form_key].set_value(dict_storage[form_key])
  741. except Exception as e:
  742. log.debug("ToolDrilling.storage_to_form() --> %s" % str(e))
  743. pass
  744. def form_to_storage(self):
  745. """
  746. Will update the 'storage' attribute which is the dict self.tools with data collected from GUI
  747. :return: None
  748. :rtype:
  749. """
  750. if self.t_ui.tools_table.rowCount() == 2:
  751. # there is no tool in tool table so we can't save the GUI elements values to storage
  752. # Excellon Tool Table has 2 rows by default
  753. return
  754. self.blockSignals(True)
  755. widget_changed = self.sender()
  756. wdg_objname = widget_changed.objectName()
  757. option_changed = self.name2option[wdg_objname]
  758. # row = self.t_ui.tools_table.currentRow()
  759. rows = sorted(list(set(index.row() for index in self.t_ui.tools_table.selectedIndexes())))
  760. for row in rows:
  761. if row < 0:
  762. row = 0
  763. tooluid_item = int(self.t_ui.tools_table.item(row, 3).text())
  764. for tooluid_key, tooluid_val in self.excellon_tools.items():
  765. if int(tooluid_key) == tooluid_item:
  766. new_option_value = self.form_fields[option_changed].get_value()
  767. if option_changed in tooluid_val:
  768. tooluid_val[option_changed] = new_option_value
  769. if option_changed in tooluid_val['data']:
  770. tooluid_val['data'][option_changed] = new_option_value
  771. self.blockSignals(False)
  772. def get_selected_tools_list(self):
  773. """
  774. Returns the keys to the self.tools dictionary corresponding
  775. to the selections on the tool list in the appGUI.
  776. :return: List of tools.
  777. :rtype: list
  778. """
  779. return [str(x.text()) for x in self.t_ui.tools_table.selectedItems()]
  780. def get_selected_tools_table_items(self):
  781. """
  782. Returns a list of lists, each list in the list is made out of row elements
  783. :return: List of table_tools items.
  784. :rtype: list
  785. """
  786. table_tools_items = []
  787. for x in self.t_ui.tools_table.selectedItems():
  788. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  789. # which does not have text
  790. txt = ''
  791. elem = []
  792. for column in range(0, self.t_ui.tools_table.columnCount() - 1):
  793. try:
  794. txt = self.t_ui.tools_table.item(x.row(), column).text()
  795. except AttributeError:
  796. try:
  797. txt = self.t_ui.tools_table.cellWidget(x.row(), column).currentText()
  798. except AttributeError:
  799. pass
  800. elem.append(txt)
  801. table_tools_items.append(deepcopy(elem))
  802. # table_tools_items.append([self.t_ui.tools_table.item(x.row(), column).text()
  803. # for column in range(0, self.t_ui.tools_table.columnCount() - 1)])
  804. for item in table_tools_items:
  805. item[0] = str(item[0])
  806. return table_tools_items
  807. def on_apply_param_to_all_clicked(self):
  808. if self.t_ui.tools_table.rowCount() == 0:
  809. # there is no tool in tool table so we can't save the GUI elements values to storage
  810. log.debug("ToolDrilling.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  811. return
  812. self.blockSignals(True)
  813. row = self.t_ui.tools_table.currentRow()
  814. if row < 0:
  815. row = 0
  816. tooluid_item = int(self.t_ui.tools_table.item(row, 3).text())
  817. temp_tool_data = {}
  818. for tooluid_key, tooluid_val in self.excellon_tools.items():
  819. if int(tooluid_key) == tooluid_item:
  820. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  821. # the current row in the tool table
  822. temp_tool_data = tooluid_val['data']
  823. break
  824. for tooluid_key, tooluid_val in self.excellon_tools.items():
  825. tooluid_val['data'] = deepcopy(temp_tool_data)
  826. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  827. self.blockSignals(False)
  828. def on_order_changed(self, order):
  829. if order != 'no':
  830. self.build_tool_ui()
  831. def on_tooltable_cellwidget_change(self):
  832. cw = self.sender()
  833. assert isinstance(cw, QtWidgets.QComboBox), \
  834. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  835. cw_index = self.t_ui.tools_table.indexAt(cw.pos())
  836. cw_row = cw_index.row()
  837. cw_col = cw_index.column()
  838. current_uid = int(self.t_ui.tools_table.item(cw_row, 3).text())
  839. # if the sender is in the column with index 2 then we update the tool_type key
  840. if cw_col == 2:
  841. tt = cw.currentText()
  842. typ = 'Iso' if tt == 'V' else "Rough"
  843. self.excellon_tools[current_uid].update({
  844. 'type': typ,
  845. 'tool_type': tt,
  846. })
  847. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  848. """
  849. Will generate an Geometry Object allowing to cut a drill hole instead of drilling it.
  850. Note: This method is a good template for generic operations as
  851. it takes it's options from parameters or otherwise from the
  852. object's options and returns a (success, msg) tuple as feedback
  853. for shell operations.
  854. :param tools: A list of tools where the drills are to be milled or a string: "all"
  855. :type tools:
  856. :param outname: the name of the resulting Geometry object
  857. :type outname: str
  858. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  859. :type tooldia: float
  860. :param plot: if to plot the resulting object
  861. :type plot: bool
  862. :param use_thread: if to use threading for creation of the Geometry object
  863. :type use_thread: bool
  864. :return: Success/failure condition tuple (bool, str).
  865. :rtype: tuple
  866. """
  867. # Get the tools from the list. These are keys
  868. # to self.tools
  869. if tools is None:
  870. tools = self.get_selected_tools_list()
  871. if outname is None:
  872. outname = self.options["name"] + "_mill"
  873. if tooldia is None:
  874. tooldia = float(self.options["tooldia"])
  875. # Sort tools by diameter. items() -> [('name', diameter), ...]
  876. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  877. sort = []
  878. for k, v in self.tools.items():
  879. sort.append((k, v.get('tooldia')))
  880. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  881. if tools == "all":
  882. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  883. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  884. if len(tools) == 0:
  885. self.app.inform.emit('[ERROR_NOTCL] %s' %
  886. _("Please select one or more tools from the list and try again."))
  887. return False, "Error: No tools."
  888. for tool in tools:
  889. if tooldia > self.tools[tool]["C"]:
  890. self.app.inform.emit(
  891. '[ERROR_NOTCL] %s %s: %s' % (
  892. _("Milling tool for DRILLS is larger than hole size. Cancelled."),
  893. _("Tool"),
  894. str(tool)
  895. )
  896. )
  897. return False, "Error: Milling tool is larger than hole."
  898. def geo_init(geo_obj, app_obj):
  899. """
  900. :param geo_obj: New object
  901. :type geo_obj: GeometryObject
  902. :param app_obj: App
  903. :type app_obj: FlatCAMApp.App
  904. :return:
  905. :rtype:
  906. """
  907. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  908. app_obj.inform.emit(_("Generating drills milling geometry..."))
  909. # ## Add properties to the object
  910. # get the tool_table items in a list of row items
  911. tool_table_items = self.get_selected_tools_table_items()
  912. # insert an information only element in the front
  913. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  914. geo_obj.options['Tools_in_use'] = tool_table_items
  915. geo_obj.options['type'] = 'Excellon Geometry'
  916. geo_obj.options["cnctooldia"] = str(tooldia)
  917. geo_obj.options["multidepth"] = self.options["multidepth"]
  918. geo_obj.solid_geometry = []
  919. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  920. # for FlatCAM is 6 decimals,
  921. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  922. for hole in self.drills:
  923. if hole['tool'] in tools:
  924. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  925. if buffer_value == 0:
  926. geo_obj.solid_geometry.append(
  927. Point(hole['point']).buffer(0.0000001).exterior)
  928. else:
  929. geo_obj.solid_geometry.append(
  930. Point(hole['point']).buffer(buffer_value).exterior)
  931. if use_thread:
  932. def geo_thread(a_obj):
  933. a_obj.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  934. # Create a promise with the new name
  935. self.app.collection.promise(outname)
  936. # Send to worker
  937. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  938. else:
  939. self.app.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  940. return True, ""
  941. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  942. """
  943. Will generate an Geometry Object allowing to cut/mill a slot hole.
  944. Note: This method is a good template for generic operations as
  945. it takes it's options from parameters or otherwise from the
  946. object's options and returns a (success, msg) tuple as feedback
  947. for shell operations.
  948. :param tools: A list of tools where the drills are to be milled or a string: "all"
  949. :type tools:
  950. :param outname: the name of the resulting Geometry object
  951. :type outname: str
  952. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  953. :type tooldia: float
  954. :param plot: if to plot the resulting object
  955. :type plot: bool
  956. :param use_thread: if to use threading for creation of the Geometry object
  957. :type use_thread: bool
  958. :return: Success/failure condition tuple (bool, str).
  959. :rtype: tuple
  960. """
  961. # Get the tools from the list. These are keys
  962. # to self.tools
  963. if tools is None:
  964. tools = self.get_selected_tools_list()
  965. if outname is None:
  966. outname = self.options["name"] + "_mill"
  967. if tooldia is None:
  968. tooldia = float(self.options["slot_tooldia"])
  969. # Sort tools by diameter. items() -> [('name', diameter), ...]
  970. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  971. sort = []
  972. for k, v in self.tools.items():
  973. sort.append((k, v.get('tooldia')))
  974. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  975. if tools == "all":
  976. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  977. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  978. if len(tools) == 0:
  979. self.app.inform.emit('[ERROR_NOTCL] %s' %
  980. _("Please select one or more tools from the list and try again."))
  981. return False, "Error: No tools."
  982. for tool in tools:
  983. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  984. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  985. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  986. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  987. self.app.inform.emit('[ERROR_NOTCL] %s' %
  988. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  989. return False, "Error: Milling tool is larger than hole."
  990. def geo_init(geo_obj, app_obj):
  991. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  992. app_obj.inform.emit(_("Generating slot milling geometry..."))
  993. # ## Add properties to the object
  994. # get the tool_table items in a list of row items
  995. tool_table_items = self.get_selected_tools_table_items()
  996. # insert an information only element in the front
  997. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  998. geo_obj.options['Tools_in_use'] = tool_table_items
  999. geo_obj.options['type'] = 'Excellon Geometry'
  1000. geo_obj.options["cnctooldia"] = str(tooldia)
  1001. geo_obj.options["multidepth"] = self.options["multidepth"]
  1002. geo_obj.solid_geometry = []
  1003. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1004. # for FlatCAM is 6 decimals,
  1005. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1006. for slot in self.slots:
  1007. if slot['tool'] in tools:
  1008. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  1009. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  1010. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1011. # for the file_tool (tooldia actually)
  1012. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  1013. if buffer_value == 0:
  1014. start = slot['start']
  1015. stop = slot['stop']
  1016. lines_string = LineString([start, stop])
  1017. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  1018. geo_obj.solid_geometry.append(poly)
  1019. else:
  1020. start = slot['start']
  1021. stop = slot['stop']
  1022. lines_string = LineString([start, stop])
  1023. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  1024. geo_obj.solid_geometry.append(poly)
  1025. if use_thread:
  1026. def geo_thread(a_obj):
  1027. a_obj.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  1028. # Create a promise with the new name
  1029. self.app.collection.promise(outname)
  1030. # Send to worker
  1031. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1032. else:
  1033. self.app.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  1034. return True, ""
  1035. def on_pp_changed(self):
  1036. current_pp = self.t_ui.pp_excellon_name_cb.get_value()
  1037. if "toolchange_probe" in current_pp.lower():
  1038. self.t_ui.pdepth_entry.setVisible(True)
  1039. self.t_ui.pdepth_label.show()
  1040. self.t_ui.feedrate_probe_entry.setVisible(True)
  1041. self.t_ui.feedrate_probe_label.show()
  1042. else:
  1043. self.t_ui.pdepth_entry.setVisible(False)
  1044. self.t_ui.pdepth_label.hide()
  1045. self.t_ui.feedrate_probe_entry.setVisible(False)
  1046. self.t_ui.feedrate_probe_label.hide()
  1047. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  1048. self.t_ui.feedrate_rapid_label.show()
  1049. self.t_ui.feedrate_rapid_entry.show()
  1050. else:
  1051. self.t_ui.feedrate_rapid_label.hide()
  1052. self.t_ui.feedrate_rapid_entry.hide()
  1053. if 'laser' in current_pp.lower():
  1054. self.t_ui.cutzlabel.hide()
  1055. self.t_ui.cutz_entry.hide()
  1056. try:
  1057. self.t_ui.mpass_cb.hide()
  1058. self.t_ui.maxdepth_entry.hide()
  1059. except AttributeError:
  1060. pass
  1061. if 'marlin' in current_pp.lower():
  1062. self.t_ui.travelzlabel.setText('%s:' % _("Focus Z"))
  1063. self.t_ui.endz_label.show()
  1064. self.t_ui.endz_entry.show()
  1065. else:
  1066. self.t_ui.travelzlabel.hide()
  1067. self.t_ui.travelz_entry.hide()
  1068. self.t_ui.endz_label.hide()
  1069. self.t_ui.endz_entry.hide()
  1070. try:
  1071. self.t_ui.frzlabel.hide()
  1072. self.t_ui.feedrate_z_entry.hide()
  1073. except AttributeError:
  1074. pass
  1075. self.t_ui.dwell_cb.hide()
  1076. self.t_ui.dwelltime_entry.hide()
  1077. self.t_ui.spindle_label.setText('%s:' % _("Laser Power"))
  1078. try:
  1079. self.t_ui.tool_offset_label.hide()
  1080. self.t_ui.offset_entry.hide()
  1081. except AttributeError:
  1082. pass
  1083. else:
  1084. self.t_ui.cutzlabel.show()
  1085. self.t_ui.cutz_entry.show()
  1086. try:
  1087. self.t_ui.mpass_cb.show()
  1088. self.t_ui.maxdepth_entry.show()
  1089. except AttributeError:
  1090. pass
  1091. self.t_ui.travelzlabel.setText('%s:' % _('Travel Z'))
  1092. self.t_ui.travelzlabel.show()
  1093. self.t_ui.travelz_entry.show()
  1094. self.t_ui.endz_label.show()
  1095. self.t_ui.endz_entry.show()
  1096. try:
  1097. self.t_ui.frzlabel.show()
  1098. self.t_ui.feedrate_z_entry.show()
  1099. except AttributeError:
  1100. pass
  1101. self.t_ui.dwell_cb.show()
  1102. self.t_ui.dwelltime_entry.show()
  1103. self.t_ui.spindle_label.setText('%s:' % _('Spindle speed'))
  1104. try:
  1105. # self.t_ui.tool_offset_lbl.show()
  1106. self.t_ui.offset_entry.show()
  1107. except AttributeError:
  1108. pass
  1109. def on_key_press(self, event):
  1110. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1111. # matplotlib_key_flag = False
  1112. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1113. if type(event) is int:
  1114. key = event
  1115. # events from the GUI are of type QKeyEvent
  1116. elif type(event) == QtGui.QKeyEvent:
  1117. key = event.key()
  1118. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1119. # matplotlib_key_flag = True
  1120. key = event.key
  1121. key = QtGui.QKeySequence(key)
  1122. # check for modifiers
  1123. key_string = key.toString().lower()
  1124. if '+' in key_string:
  1125. mod, __, key_text = key_string.rpartition('+')
  1126. if mod.lower() == 'ctrl':
  1127. # modifiers = QtCore.Qt.ControlModifier
  1128. pass
  1129. elif mod.lower() == 'alt':
  1130. # modifiers = QtCore.Qt.AltModifier
  1131. pass
  1132. elif mod.lower() == 'shift':
  1133. # modifiers = QtCore.Qt.ShiftModifier
  1134. pass
  1135. else:
  1136. # modifiers = QtCore.Qt.NoModifier
  1137. pass
  1138. key = QtGui.QKeySequence(key_text)
  1139. # events from Vispy are of type KeyEvent
  1140. else:
  1141. key = event.key
  1142. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1143. self.points = []
  1144. self.poly_drawn = False
  1145. self.delete_moving_selection_shape()
  1146. self.delete_tool_selection_shape()
  1147. def on_add_area_click(self):
  1148. shape_button = self.t_ui.area_shape_radio
  1149. overz_button = self.t_ui.over_z_entry
  1150. strategy_radio = self.t_ui.strategy_radio
  1151. cnc_button = self.t_ui.generate_cnc_button
  1152. solid_geo = self.excellon_obj.solid_geometry
  1153. obj_type = self.excellon_obj.kind
  1154. self.app.exc_areas.on_add_area_click(
  1155. shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio,
  1156. solid_geo=solid_geo, obj_type=obj_type)
  1157. def on_clear_area_click(self):
  1158. if not self.app.exc_areas.exclusion_areas_storage:
  1159. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. There are no exclusion areas to delete."))
  1160. return
  1161. self.app.exc_areas.on_clear_area_click()
  1162. self.app.exc_areas.e_shape_modified.emit()
  1163. def on_delete_sel_areas(self):
  1164. sel_model = self.t_ui.exclusion_table.selectionModel()
  1165. sel_indexes = sel_model.selectedIndexes()
  1166. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1167. # so the duplicate rows will not be added
  1168. sel_rows = set()
  1169. for idx in sel_indexes:
  1170. sel_rows.add(idx.row())
  1171. if not sel_rows:
  1172. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. Nothing is selected."))
  1173. return
  1174. self.app.exc_areas.delete_sel_shapes(idxs=list(sel_rows))
  1175. self.app.exc_areas.e_shape_modified.emit()
  1176. def draw_sel_shape(self):
  1177. sel_model = self.t_ui.exclusion_table.selectionModel()
  1178. sel_indexes = sel_model.selectedIndexes()
  1179. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1180. sel_rows = set()
  1181. for idx in sel_indexes:
  1182. sel_rows.add(idx.row())
  1183. self.delete_sel_shape()
  1184. if self.app.is_legacy is False:
  1185. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  1186. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  1187. else:
  1188. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  1189. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  1190. for row in sel_rows:
  1191. sel_rect = self.app.exc_areas.exclusion_areas_storage[row]['shape']
  1192. self.app.move_tool.sel_shapes.add(sel_rect, color=outline, face_color=face, update=True, layer=0,
  1193. tolerance=None)
  1194. if self.app.is_legacy is True:
  1195. self.app.move_tool.sel_shapes.redraw()
  1196. def clear_selection(self):
  1197. self.app.delete_selection_shape()
  1198. # self.t_ui.exclusion_table.clearSelection()
  1199. def delete_sel_shape(self):
  1200. self.app.delete_selection_shape()
  1201. def update_exclusion_table(self):
  1202. self.exclusion_area_cb_is_checked = True if self.t_ui.exclusion_cb.isChecked() else False
  1203. self.build_tool_ui()
  1204. self.t_ui.exclusion_cb.set_value(self.exclusion_area_cb_is_checked)
  1205. def on_strategy(self, val):
  1206. if val == 'around':
  1207. self.t_ui.over_z_label.setDisabled(True)
  1208. self.t_ui.over_z_entry.setDisabled(True)
  1209. else:
  1210. self.t_ui.over_z_label.setDisabled(False)
  1211. self.t_ui.over_z_entry.setDisabled(False)
  1212. def exclusion_table_toggle_all(self):
  1213. """
  1214. will toggle the selection of all rows in Exclusion Areas table
  1215. :return:
  1216. """
  1217. sel_model = self.t_ui.exclusion_table.selectionModel()
  1218. sel_indexes = sel_model.selectedIndexes()
  1219. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1220. sel_rows = set()
  1221. for idx in sel_indexes:
  1222. sel_rows.add(idx.row())
  1223. if sel_rows:
  1224. self.t_ui.exclusion_table.clearSelection()
  1225. self.delete_sel_shape()
  1226. else:
  1227. self.t_ui.exclusion_table.selectAll()
  1228. self.draw_sel_shape()
  1229. def process_slots_as_drills(self):
  1230. pass
  1231. def on_cnc_button_click(self):
  1232. obj_name = self.t_ui.object_combo.currentText()
  1233. # Get source object.
  1234. try:
  1235. obj = self.app.collection.get_by_name(obj_name)
  1236. except Exception:
  1237. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  1238. return
  1239. if obj is None:
  1240. self.app.inform.emit('[ERROR_NOTCL] %s.' % _("Object not found"))
  1241. return
  1242. has_drills = None
  1243. for tool, tool_dict in obj.tools.items():
  1244. if 'drills' in tool_dict and tool_dict['drills']:
  1245. has_drills = True
  1246. break
  1247. if not has_drills:
  1248. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  1249. "The loaded Excellon file has no drills ...")
  1250. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  1251. return
  1252. # Get the tools from the Tool Table
  1253. selected_uid = set()
  1254. for it in self.t_ui.tools_table.selectedItems():
  1255. uid = self.t_ui.tools_table.item(it.row(), 3).text()
  1256. selected_uid.add(uid)
  1257. sel_tools = list(selected_uid)
  1258. if len(sel_tools) == 0:
  1259. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1260. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1261. # in this case regardless of the selection status of that tool, use it.
  1262. if self.t_ui.tools_table.rowCount() >= 3:
  1263. sel_tools.append(self.t_ui.tools_table.item(0, 0).text())
  1264. else:
  1265. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1266. _("Please select one or more tools from the list and try again."))
  1267. return
  1268. # add slots as drills
  1269. self.process_slots_as_drills()
  1270. xmin = obj.options['xmin']
  1271. ymin = obj.options['ymin']
  1272. xmax = obj.options['xmax']
  1273. ymax = obj.options['ymax']
  1274. job_name = obj.options["name"] + "_cnc"
  1275. pp_excellon_name = self.t_ui.pp_excellon_name_cb.get_value()
  1276. settings = QtCore.QSettings("Open Source", "FlatCAM")
  1277. if settings.contains("machinist"):
  1278. machinist_setting = settings.value('machinist', type=int)
  1279. else:
  1280. machinist_setting = 0
  1281. # #############################################################################################################
  1282. # #############################################################################################################
  1283. # TOOLS
  1284. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  1285. # so we actually are sorting the tools by diameter
  1286. # #############################################################################################################
  1287. # #############################################################################################################
  1288. all_tools = []
  1289. for tool_as_key, v in list(obj.tools.items()):
  1290. all_tools.append((int(tool_as_key), float(v['tooldia'])))
  1291. order = self.t_ui.order_radio.get_value()
  1292. if order == 'fwd':
  1293. all_tools.sort(reverse=False)
  1294. elif order == 'rev':
  1295. all_tools.sort(reverse=True)
  1296. else:
  1297. pass
  1298. if order == 'fwd':
  1299. sorted_tools = sorted(all_tools, key=lambda t1: t1[1])
  1300. elif order == 'rev':
  1301. sorted_tools = sorted(all_tools, key=lambda t1: t1[1], reverse=True)
  1302. else:
  1303. sorted_tools = all_tools
  1304. # Create a sorted list of selected sel_tools from the sorted_tools list
  1305. sel_tools = [i for i, j in sorted_tools for k in sel_tools if i == k]
  1306. log.debug("Tools sorted are: %s" % str(sel_tools))
  1307. # #############################################################################################################
  1308. # #############################################################################################################
  1309. # #############################################################################################################
  1310. # #############################################################################################################
  1311. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  1312. # running this method from a Tcl Command
  1313. # #############################################################################################################
  1314. # #############################################################################################################
  1315. build_tools_in_use_list = False
  1316. if 'Tools_in_use' not in obj.options:
  1317. obj.options['Tools_in_use'] = []
  1318. # if the list is empty (either we just added the key or it was already there but empty) signal to build it
  1319. if not obj.options['Tools_in_use']:
  1320. build_tools_in_use_list = True
  1321. # #############################################################################################################
  1322. # #############################################################################################################
  1323. # fill the data into the self.exc_cnc_tools dictionary
  1324. # #############################################################################################################
  1325. # #############################################################################################################
  1326. for it in all_tools:
  1327. for to_ol in sel_tools:
  1328. if to_ol == it[0]:
  1329. sol_geo = []
  1330. drill_no = 0
  1331. if 'drills' in obj.tools[to_ol]:
  1332. drill_no = len(obj.tools[to_ol]['drills'])
  1333. for drill in obj.tools[to_ol]['drills']:
  1334. sol_geo.append(drill.buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle))
  1335. slot_no = 0
  1336. if 'slots' in obj.tools[to_ol]:
  1337. slot_no = len(obj.tools[to_ol]['slots'])
  1338. for slot in obj.tools[to_ol]['slots']:
  1339. start = (slot[0].x, slot[0].y)
  1340. stop = (slot[1].x, slot[1].y)
  1341. sol_geo.append(
  1342. LineString([start, stop]).buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle)
  1343. )
  1344. if self.use_ui:
  1345. try:
  1346. z_off = float(obj.tools[it[0]]['data']['offset']) * (-1)
  1347. except KeyError:
  1348. z_off = 0
  1349. else:
  1350. z_off = 0
  1351. default_data = {}
  1352. for k, v in list(self.options.items()):
  1353. default_data[k] = deepcopy(v)
  1354. obj.exc_cnc_tools[it[1]] = {}
  1355. obj.exc_cnc_tools[it[1]]['tool'] = it[0]
  1356. obj.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  1357. obj.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  1358. obj.exc_cnc_tools[it[1]]['offset'] = z_off
  1359. obj.exc_cnc_tools[it[1]]['data'] = default_data
  1360. obj.exc_cnc_tools[it[1]]['gcode'] = ''
  1361. obj.exc_cnc_tools[it[1]]['gcode_parsed'] = []
  1362. obj.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  1363. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  1364. # running this method from a Tcl Command
  1365. if build_tools_in_use_list is True:
  1366. self.options['Tools_in_use'].append(
  1367. [it[0], it[1], drill_no, slot_no]
  1368. )
  1369. # #############################################################################################################
  1370. # #############################################################################################################
  1371. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  1372. # #############################################################################################################
  1373. # #############################################################################################################
  1374. self.app.inform.emit(_("Creating a list of points to drill..."))
  1375. points = {}
  1376. for tool, tl_dict in obj.tools.items():
  1377. if tool in sel_tools:
  1378. if self.app.abort_flag:
  1379. # graceful abort requested by the user
  1380. raise grace
  1381. if 'drills' in tl_dict and tl_dict['drills']:
  1382. for drill_pt in tl_dict['drills']:
  1383. try:
  1384. points[tool].append(drill_pt)
  1385. except KeyError:
  1386. points[tool] = [drill_pt]
  1387. log.debug("Found %d TOOLS with drills." % len(points))
  1388. # check if there are drill points in the exclusion areas.
  1389. # If we find any within the exclusion areas return 'fail'
  1390. for tool in points:
  1391. for pt in points[tool]:
  1392. for area in self.app.exc_areas.exclusion_areas_storage:
  1393. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  1394. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  1395. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  1396. return 'fail'
  1397. # #############################################################################################################
  1398. # General Parameters
  1399. # #############################################################################################################
  1400. used_excellon_optimization_type = self.app.defaults["excellon_optimization_type"]
  1401. current_platform = platform.architecture()[0]
  1402. if current_platform != '64bit':
  1403. used_excellon_optimization_type = 'T'
  1404. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  1405. self.f_retract = self.app.defaults["excellon_f_retract"]
  1406. # Prepprocessor
  1407. pp_excellon_name = self.default_data["excellon_ppname_e"]
  1408. self.pp_excellon = self.app.preprocessors[pp_excellon_name]
  1409. p = self.pp_excellon
  1410. # #############################################################################################################
  1411. # #############################################################################################################
  1412. # Initialization
  1413. # #############################################################################################################
  1414. # #############################################################################################################
  1415. start_gcode = ''
  1416. start_gcode += self.doformat(p.start_code)
  1417. if self.xy_toolchange is not None:
  1418. self.oldx = self.xy_toolchange[0]
  1419. self.oldy = self.xy_toolchange[1]
  1420. else:
  1421. self.oldx = 0.0
  1422. self.oldy = 0.0
  1423. if self.toolchange is False:
  1424. if self.xy_toolchange is not None:
  1425. start_gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1426. start_gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1427. else:
  1428. start_gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  1429. start_gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  1430. else:
  1431. start_gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  1432. self.total_gcode += start_gcode
  1433. # #############################################################################################################
  1434. # #############################################################################################################
  1435. # GCODE creation
  1436. # #############################################################################################################
  1437. # #############################################################################################################
  1438. self.app.inform.emit('%s...' % _("Starting G-Code"))
  1439. # Object initialization function for app.app_obj.new_object()
  1440. def job_init(job_obj, app_obj):
  1441. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1442. app_obj.inform.emit(_("Generating Excellon CNCJob..."))
  1443. measured_distance = 0.0
  1444. measured_down_distance = 0.0
  1445. measured_up_to_zero_distance = 0.0
  1446. measured_lift_distance = 0.0
  1447. # get the tool_table items in a list of row items
  1448. tool_table_items = self.get_selected_tools_table_items()
  1449. # insert an information only element in the front
  1450. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1451. # ## Add properties to the object
  1452. job_obj.origin_kind = 'excellon'
  1453. job_obj.options['Tools_in_use'] = tool_table_items
  1454. job_obj.options['type'] = 'Excellon'
  1455. self.options['type'] = 'Excellon'
  1456. job_obj.options['ppname_e'] = pp_excellon_name
  1457. self.options['ppname_e'] = pp_excellon_name
  1458. job_obj.pp_excellon_name = pp_excellon_name
  1459. job_obj.toolchange_xy_type = "excellon"
  1460. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1461. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1462. job_obj.options['xmin'] = xmin
  1463. job_obj.options['ymin'] = ymin
  1464. job_obj.options['xmax'] = xmax
  1465. job_obj.options['ymax'] = ymax
  1466. if self.toolchange is True:
  1467. for tool in sel_tools:
  1468. tool_points = points[tool]
  1469. tool_gcode = self.generate_from_excellon_by_tool(tool, tool_points, obj.tools,
  1470. opt_type=used_excellon_optimization_type,
  1471. toolchange=True)
  1472. obj.exc_cnc_tools[tool]['gcode'] = tool_gcode
  1473. self.total_gcode += tool_gcode
  1474. else:
  1475. tool_points = []
  1476. for tool in sel_tools:
  1477. tool_points += points[tool]
  1478. used_tool = sel_tools[0]
  1479. tool_gcode = self.generate_from_excellon_by_tool(used_tool, tool_points, obj.tools,
  1480. opt_type=used_excellon_optimization_type,
  1481. toolchange=False)
  1482. obj.exc_cnc_tools[used_tool]['gcode'] = tool_gcode
  1483. self.total_gcode += tool_gcode
  1484. if used_excellon_optimization_type == 'M':
  1485. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  1486. elif used_excellon_optimization_type == 'B':
  1487. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  1488. elif used_excellon_optimization_type == 'T':
  1489. log.debug(
  1490. "The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  1491. else:
  1492. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  1493. # #########################################################################################################
  1494. # ############################# Calculate DISTANCE and ESTIMATED TIME #####################################
  1495. # #########################################################################################################
  1496. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, job_obj.xy_end[0], job_obj.xy_end[1]))
  1497. log.debug("The total travel distance including travel to end position is: %s" %
  1498. str(measured_distance) + '\n')
  1499. self.travel_distance = measured_distance
  1500. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  1501. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  1502. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only
  1503. # with Marlin preprocessor and derivatives.
  1504. job_obj.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  1505. lift_time = measured_lift_distance / self.feedrate_rapid
  1506. traveled_time = measured_distance / self.feedrate_rapid
  1507. job_obj.routing_time += lift_time + traveled_time
  1508. job_obj.gcode = self.total_gcode
  1509. if job_obj.gcode == 'fail':
  1510. return 'fail'
  1511. job_obj.gcode_parse()
  1512. job_obj.create_geometry()
  1513. # To be run in separate thread
  1514. def job_thread(a_obj):
  1515. with self.app.proc_container.new(_("Generating CNC Code")):
  1516. a_obj.app_obj.new_object("cncjob", job_name, job_init)
  1517. # Create promise for the new name.
  1518. self.app.collection.promise(job_name)
  1519. # Send to worker
  1520. # self.app.worker.add_task(job_thread, [self.app])
  1521. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1522. def drilling_handler(self, obj):
  1523. pass
  1524. # Distance callback
  1525. class CreateDistanceCallback(object):
  1526. """Create callback to calculate distances between points."""
  1527. def __init__(self, locs, manager):
  1528. self.manager = manager
  1529. self.matrix = {}
  1530. if locs:
  1531. size = len(locs)
  1532. for from_node in range(size):
  1533. self.matrix[from_node] = {}
  1534. for to_node in range(size):
  1535. if from_node == to_node:
  1536. self.matrix[from_node][to_node] = 0
  1537. else:
  1538. x1 = locs[from_node][0]
  1539. y1 = locs[from_node][1]
  1540. x2 = locs[to_node][0]
  1541. y2 = locs[to_node][1]
  1542. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  1543. # def Distance(self, from_node, to_node):
  1544. # return int(self.matrix[from_node][to_node])
  1545. def Distance(self, from_index, to_index):
  1546. # Convert from routing variable Index to distance matrix NodeIndex.
  1547. from_node = self.manager.IndexToNode(from_index)
  1548. to_node = self.manager.IndexToNode(to_index)
  1549. return self.matrix[from_node][to_node]
  1550. @staticmethod
  1551. def create_tool_data_array(points):
  1552. # Create the data.
  1553. loc_list = []
  1554. for pt in points:
  1555. loc_list.append((pt.coords.xy[0][0], pt.coords.xy[1][0]))
  1556. return loc_list
  1557. def optimized_ortools_meta(self, locations, start=None):
  1558. optimized_path = []
  1559. tsp_size = len(locations)
  1560. num_routes = 1 # The number of routes, which is 1 in the TSP.
  1561. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  1562. depot = 0 if start is None else start
  1563. # Create routing model.
  1564. if tsp_size > 0:
  1565. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  1566. routing = pywrapcp.RoutingModel(manager)
  1567. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  1568. search_parameters.local_search_metaheuristic = (
  1569. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  1570. # Set search time limit in milliseconds.
  1571. if float(self.app.defaults["excellon_search_time"]) != 0:
  1572. search_parameters.time_limit.seconds = int(
  1573. float(self.app.defaults["excellon_search_time"]))
  1574. else:
  1575. search_parameters.time_limit.seconds = 3
  1576. # Callback to the distance function. The callback takes two
  1577. # arguments (the from and to node indices) and returns the distance between them.
  1578. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  1579. # if there are no distances then go to the next tool
  1580. if not dist_between_locations:
  1581. return
  1582. dist_callback = dist_between_locations.Distance
  1583. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  1584. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  1585. # Solve, returns a solution if any.
  1586. assignment = routing.SolveWithParameters(search_parameters)
  1587. if assignment:
  1588. # Solution cost.
  1589. log.info("OR-tools metaheuristics - Total distance: " + str(assignment.ObjectiveValue()))
  1590. # Inspect solution.
  1591. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  1592. route_number = 0
  1593. node = routing.Start(route_number)
  1594. start_node = node
  1595. while not routing.IsEnd(node):
  1596. if self.app.abort_flag:
  1597. # graceful abort requested by the user
  1598. raise grace
  1599. optimized_path.append(node)
  1600. node = assignment.Value(routing.NextVar(node))
  1601. else:
  1602. log.warning('OR-tools metaheuristics - No solution found.')
  1603. else:
  1604. log.warning('OR-tools metaheuristics - Specify an instance greater than 0.')
  1605. return optimized_path
  1606. # ############################################# ##
  1607. def optimized_ortools_basic(self, locations, start=None):
  1608. optimized_path = []
  1609. tsp_size = len(locations)
  1610. num_routes = 1 # The number of routes, which is 1 in the TSP.
  1611. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  1612. depot = 0 if start is None else start
  1613. # Create routing model.
  1614. if tsp_size > 0:
  1615. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  1616. routing = pywrapcp.RoutingModel(manager)
  1617. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  1618. # Callback to the distance function. The callback takes two
  1619. # arguments (the from and to node indices) and returns the distance between them.
  1620. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  1621. # if there are no distances then go to the next tool
  1622. if not dist_between_locations:
  1623. return
  1624. dist_callback = dist_between_locations.Distance
  1625. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  1626. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  1627. # Solve, returns a solution if any.
  1628. assignment = routing.SolveWithParameters(search_parameters)
  1629. if assignment:
  1630. # Solution cost.
  1631. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  1632. # Inspect solution.
  1633. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  1634. route_number = 0
  1635. node = routing.Start(route_number)
  1636. start_node = node
  1637. while not routing.IsEnd(node):
  1638. optimized_path.append(node)
  1639. node = assignment.Value(routing.NextVar(node))
  1640. else:
  1641. log.warning('No solution found.')
  1642. else:
  1643. log.warning('Specify an instance greater than 0.')
  1644. return optimized_path
  1645. # ############################################# ##
  1646. @staticmethod
  1647. def optimized_travelling_salesman(points, start=None):
  1648. """
  1649. As solving the problem in the brute force way is too slow,
  1650. this function implements a simple heuristic: always
  1651. go to the nearest city.
  1652. Even if this algorithm is extremely simple, it works pretty well
  1653. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  1654. and runs very fast in O(N^2) time complexity.
  1655. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  1656. [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2],
  1657. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  1658. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  1659. [[0, 0], [6, 0], [10, 0]]
  1660. :param points: List of tuples with x, y coordinates
  1661. :type points: list
  1662. :param start: a tuple with a x,y coordinates of the start point
  1663. :type start: tuple
  1664. :return: List of points ordered in a optimized way
  1665. :rtype: list
  1666. """
  1667. if start is None:
  1668. start = points[0]
  1669. must_visit = points
  1670. path = [start]
  1671. # must_visit.remove(start)
  1672. while must_visit:
  1673. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  1674. path.append(nearest)
  1675. must_visit.remove(nearest)
  1676. return path
  1677. def check_zcut(self, zcut):
  1678. if zcut > 0:
  1679. self.app.inform.emit('[WARNING] %s' %
  1680. _("The Cut Z parameter has positive value. "
  1681. "It is the depth value to drill into material.\n"
  1682. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  1683. "therefore the app will convert the value to negative. "
  1684. "Check the resulting CNC code (Gcode etc)."))
  1685. return -zcut
  1686. elif zcut == 0:
  1687. self.app.inform.emit('[WARNING] %s.' % _("The Cut Z parameter is zero. There will be no cut, aborting"))
  1688. return 'fail'
  1689. def generate_from_excellon_by_tool(self, tool, points, tools, opt_type='T', toolchange=False):
  1690. """
  1691. Creates Gcode for this object from an Excellon object
  1692. for the specified tools.
  1693. :return: Tool GCode
  1694. :rtype: str
  1695. """
  1696. log.debug("Creating CNC Job from Excellon...")
  1697. t_gcode = ''
  1698. p = self.pp_excellon
  1699. measured_distance = 0.0
  1700. measured_down_distance = 0.0
  1701. measured_up_to_zero_distance = 0.0
  1702. measured_lift_distance = 0.0
  1703. # #############################################################################################################
  1704. # #############################################################################################################
  1705. # ################################## DRILLING !!! #########################################################
  1706. # #############################################################################################################
  1707. # #############################################################################################################
  1708. if opt_type == 'M':
  1709. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  1710. elif opt_type == 'B':
  1711. log.debug("Using OR-Tools Basic drill path optimization.")
  1712. elif opt_type == 'T':
  1713. log.debug("Using Travelling Salesman drill path optimization.")
  1714. else:
  1715. log.debug("Using no path optimization.")
  1716. if toolchange is True:
  1717. tool_dict = tools[tool]['data']
  1718. # check if it has drills
  1719. if not tools[tool]['drills']:
  1720. return 'fail'
  1721. if self.app.abort_flag:
  1722. # graceful abort requested by the user
  1723. raise grace
  1724. self.tool = tool
  1725. self.tooldia = tools[tool]["tooldia"]
  1726. self.postdata['toolC'] = self.tooldia
  1727. self.z_feedrate = tool_dict['feedrate_z']
  1728. self.feedrate = tool_dict['feedrate']
  1729. self.z_cut = tool_dict['cutz']
  1730. t_gcode += self.doformat(p.z_feedrate_code)
  1731. # Z_cut parameter
  1732. if machinist_setting == 0:
  1733. self.z_cut = self.check_zcut(zcut=tool_dict["excellon_cutz"])
  1734. if self.z_cut == 'fail':
  1735. return 'fail'
  1736. # multidepth use this
  1737. old_zcut = tool_dict["excellon_cutz"]
  1738. self.z_move = tool_dict['travelz']
  1739. self.spindlespeed = tool_dict['spindlespeed']
  1740. self.dwell = tool_dict['dwell']
  1741. self.dwelltime = tool_dict['dwelltime']
  1742. self.multidepth = tool_dict['multidepth']
  1743. self.z_depthpercut = tool_dict['depthperpass']
  1744. # XY_toolchange parameter
  1745. self.xy_toolchange = tool_dict["excellon_toolchangexy"]
  1746. try:
  1747. if self.xy_toolchange == '':
  1748. self.xy_toolchange = None
  1749. else:
  1750. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  1751. if self.xy_toolchange:
  1752. self.xy_toolchange = [
  1753. float(eval(a)) for a in self.xy_toolchange.split(",")
  1754. ]
  1755. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  1756. self.app.inform.emit('[ERROR]%s' %
  1757. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  1758. "in the format (x, y) \nbut now there is only one value, not two. "))
  1759. return 'fail'
  1760. except Exception as e:
  1761. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  1762. pass
  1763. # XY_end parameter
  1764. self.xy_end = tool_dict["excellon_endxy"]
  1765. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  1766. if self.xy_end and self.xy_end != '':
  1767. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  1768. if self.xy_end and len(self.xy_end) < 2:
  1769. self.app.inform.emit(
  1770. '[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  1771. "in the format (x, y) but now there is only one value, not two."))
  1772. return 'fail'
  1773. # #########################################################################################################
  1774. # ############ Create the data. #################
  1775. # #########################################################################################################
  1776. locations = []
  1777. altPoints = []
  1778. optimized_path = []
  1779. if opt_type == 'M':
  1780. if tool in points:
  1781. locations = self.create_tool_data_array(points=points[tool])
  1782. # if there are no locations then go to the next tool
  1783. if not locations:
  1784. return 'fail'
  1785. optimized_path = self.optimized_ortools_meta(locations=locations)
  1786. elif opt_type == 'B':
  1787. if tool in points:
  1788. locations = self.create_tool_data_array(points=points[tool])
  1789. # if there are no locations then go to the next tool
  1790. if not locations:
  1791. return 'fail'
  1792. optimized_path = self.optimized_ortools_basic(locations=locations)
  1793. elif opt_type == 'T':
  1794. for point in points[tool]:
  1795. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  1796. # if there are no locations then go to the next tool
  1797. if not altPoints:
  1798. return 'fail'
  1799. optimized_path = self.optimized_travelling_salesman(altPoints)
  1800. else:
  1801. # it's actually not optimized path but here we build a list of (x,y) coordinates
  1802. # out of the tool's drills
  1803. for drill in tools[tool]['drills']:
  1804. unoptimized_coords = (
  1805. drill.x,
  1806. drill.y
  1807. )
  1808. optimized_path.append(unoptimized_coords)
  1809. # #########################################################################################################
  1810. # #########################################################################################################
  1811. # Only if there are locations to drill
  1812. if not optimized_path:
  1813. return 'fail'
  1814. if self.app.abort_flag:
  1815. # graceful abort requested by the user
  1816. raise grace
  1817. # Tool change sequence (optional)
  1818. if toolchange:
  1819. t_gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  1820. # Spindle start
  1821. t_gcode += self.doformat(p.spindle_code)
  1822. # Dwell time
  1823. if self.dwell is True:
  1824. t_gcode += self.doformat(p.dwell_code)
  1825. current_tooldia = float('%.*f' % (self.decimals, float(tools[tool]["tooldia"])))
  1826. self.app.inform.emit(
  1827. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  1828. str(current_tooldia),
  1829. str(self.units))
  1830. )
  1831. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  1832. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  1833. # because the values for Z offset are created in build_tool_ui()
  1834. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  1835. try:
  1836. z_offset = float(tool_dict['offset']) * (-1)
  1837. except KeyError:
  1838. z_offset = 0
  1839. self.z_cut = z_offset + old_zcut
  1840. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1841. if self.coordinates_type == "G90":
  1842. # Drillling! for Absolute coordinates type G90
  1843. # variables to display the percentage of work done
  1844. geo_len = len(optimized_path)
  1845. old_disp_number = 0
  1846. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  1847. loc_nr = 0
  1848. for point in optimized_path:
  1849. if self.app.abort_flag:
  1850. # graceful abort requested by the user
  1851. raise grace
  1852. if opt_type == 'T':
  1853. locx = point[0]
  1854. locy = point[1]
  1855. else:
  1856. locx = locations[point][0]
  1857. locy = locations[point][1]
  1858. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  1859. end_point=(locx, locy),
  1860. tooldia=current_tooldia)
  1861. prev_z = None
  1862. for travel in travels:
  1863. locx = travel[1][0]
  1864. locy = travel[1][1]
  1865. if travel[0] is not None:
  1866. # move to next point
  1867. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1868. # raise to safe Z (travel[0]) each time because safe Z may be different
  1869. self.z_move = travel[0]
  1870. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1871. # restore z_move
  1872. self.z_move = tool_dict['travelz']
  1873. else:
  1874. if prev_z is not None:
  1875. # move to next point
  1876. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1877. # we assume that previously the z_move was altered therefore raise to
  1878. # the travel_z (z_move)
  1879. self.z_move = tool_dict['travelz']
  1880. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1881. else:
  1882. # move to next point
  1883. t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1884. # store prev_z
  1885. prev_z = travel[0]
  1886. # t_gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1887. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  1888. doc = deepcopy(self.z_cut)
  1889. self.z_cut = 0.0
  1890. while abs(self.z_cut) < abs(doc):
  1891. self.z_cut -= self.z_depthpercut
  1892. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  1893. self.z_cut = doc
  1894. t_gcode += self.doformat(p.down_code, x=locx, y=locy)
  1895. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1896. if self.f_retract is False:
  1897. t_gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1898. measured_up_to_zero_distance += abs(self.z_cut)
  1899. measured_lift_distance += abs(self.z_move)
  1900. else:
  1901. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1902. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1903. else:
  1904. t_gcode += self.doformat(p.down_code, x=locx, y=locy)
  1905. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1906. if self.f_retract is False:
  1907. t_gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1908. measured_up_to_zero_distance += abs(self.z_cut)
  1909. measured_lift_distance += abs(self.z_move)
  1910. else:
  1911. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1912. t_gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1913. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  1914. self.oldx = locx
  1915. self.oldy = locy
  1916. loc_nr += 1
  1917. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  1918. if old_disp_number < disp_number <= 100:
  1919. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1920. old_disp_number = disp_number
  1921. else:
  1922. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  1923. return 'fail'
  1924. self.z_cut = deepcopy(old_zcut)
  1925. t_gcode += self.doformat(p.spindle_stop_code)
  1926. # Move to End position
  1927. t_gcode += self.doformat(p.end_code, x=0, y=0)
  1928. self.app.inform.emit(_("Finished G-Code generation..."))
  1929. return t_gcode
  1930. def reset_fields(self):
  1931. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1932. def doformat(self, fun, **kwargs):
  1933. return self.doformat2(fun, **kwargs) + "\n"
  1934. def doformat2(self, fun, **kwargs):
  1935. """
  1936. This method will call one of the current preprocessor methods having as parameters all the attributes of
  1937. current class to which will add the kwargs parameters
  1938. :param fun: One of the methods inside the preprocessor classes which get loaded here in the 'p' object
  1939. :type fun: class 'function'
  1940. :param kwargs: keyword args which will update attributes of the current class
  1941. :type kwargs: dict
  1942. :return: Gcode line
  1943. :rtype: str
  1944. """
  1945. attributes = AttrDict()
  1946. attributes.update(self.postdata)
  1947. attributes.update(kwargs)
  1948. try:
  1949. returnvalue = fun(attributes)
  1950. return returnvalue
  1951. except Exception:
  1952. self.app.log.error('Exception occurred within a preprocessor: ' + traceback.format_exc())
  1953. return ''
  1954. @property
  1955. def postdata(self):
  1956. """
  1957. This will return all the attributes of the class in the form of a dictionary
  1958. :return: Class attributes
  1959. :rtype: dict
  1960. """
  1961. return self.__dict__
  1962. class DrillingUI:
  1963. toolName = _("Drilling Tool")
  1964. def __init__(self, layout, app):
  1965. self.app = app
  1966. self.decimals = self.app.decimals
  1967. self.layout = layout
  1968. self.tools_frame = QtWidgets.QFrame()
  1969. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  1970. self.layout.addWidget(self.tools_frame)
  1971. self.tools_box = QtWidgets.QVBoxLayout()
  1972. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1973. self.tools_frame.setLayout(self.tools_box)
  1974. self.title_box = QtWidgets.QHBoxLayout()
  1975. self.tools_box.addLayout(self.title_box)
  1976. # ## Title
  1977. title_label = QtWidgets.QLabel("%s" % self.toolName)
  1978. title_label.setStyleSheet("""
  1979. QLabel
  1980. {
  1981. font-size: 16px;
  1982. font-weight: bold;
  1983. }
  1984. """)
  1985. title_label.setToolTip(
  1986. _("Create CNCJob with toolpaths for drilling or milling holes.")
  1987. )
  1988. self.title_box.addWidget(title_label)
  1989. # App Level label
  1990. self.level = QtWidgets.QLabel("")
  1991. self.level.setToolTip(
  1992. _(
  1993. "BASIC is suitable for a beginner. Many parameters\n"
  1994. "are hidden from the user in this mode.\n"
  1995. "ADVANCED mode will make available all parameters.\n\n"
  1996. "To change the application LEVEL, go to:\n"
  1997. "Edit -> Preferences -> General and check:\n"
  1998. "'APP. LEVEL' radio button."
  1999. )
  2000. )
  2001. self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2002. self.title_box.addWidget(self.level)
  2003. # Grid Layout
  2004. grid0 = QtWidgets.QGridLayout()
  2005. grid0.setColumnStretch(0, 0)
  2006. grid0.setColumnStretch(1, 1)
  2007. self.tools_box.addLayout(grid0)
  2008. self.obj_combo_label = QtWidgets.QLabel('<b>%s</b>:' % _("EXCELLON"))
  2009. self.obj_combo_label.setToolTip(
  2010. _("Excellon object for drilling/milling operation.")
  2011. )
  2012. grid0.addWidget(self.obj_combo_label, 0, 0, 1, 2)
  2013. # ################################################
  2014. # ##### The object to be drilled #################
  2015. # ################################################
  2016. self.object_combo = FCComboBox()
  2017. self.object_combo.setModel(self.app.collection)
  2018. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  2019. # self.object_combo.setCurrentIndex(1)
  2020. self.object_combo.is_last = True
  2021. grid0.addWidget(self.object_combo, 1, 0, 1, 2)
  2022. separator_line = QtWidgets.QFrame()
  2023. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2024. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2025. grid0.addWidget(separator_line, 2, 0, 1, 2)
  2026. # ################################################
  2027. # ########## Excellon Tool Table #################
  2028. # ################################################
  2029. self.tools_table = FCTable(drag_drop=True)
  2030. grid0.addWidget(self.tools_table, 3, 0, 1, 2)
  2031. self.tools_table.setColumnCount(5)
  2032. self.tools_table.setColumnHidden(3, True)
  2033. self.tools_table.setSortingEnabled(False)
  2034. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('Drills'), '', _('Slots')])
  2035. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2036. _("This is the Tool Number.\n"
  2037. "When ToolChange is checked, on toolchange event this value\n"
  2038. "will be showed as a T1, T2 ... Tn in the Machine Code.\n\n"
  2039. "Here the tools are selected for G-code generation."))
  2040. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2041. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  2042. "is the cut width into the material."))
  2043. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2044. _("The number of Drill holes. Holes that are drilled with\n"
  2045. "a drill bit."))
  2046. self.tools_table.horizontalHeaderItem(4).setToolTip(
  2047. _("The number of Slot holes. Holes that are created by\n"
  2048. "milling them with an endmill bit."))
  2049. # Tool order
  2050. self.order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  2051. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2052. "'No' --> means that the used order is the one in the tool table\n"
  2053. "'Forward' --> means that the tools will be ordered from small to big\n"
  2054. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2055. "WARNING: using rest machining will automatically set the order\n"
  2056. "in reverse and disable this control."))
  2057. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2058. {'label': _('Forward'), 'value': 'fwd'},
  2059. {'label': _('Reverse'), 'value': 'rev'}])
  2060. grid0.addWidget(self.order_label, 4, 0)
  2061. grid0.addWidget(self.order_radio, 4, 1)
  2062. separator_line = QtWidgets.QFrame()
  2063. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2064. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2065. grid0.addWidget(separator_line, 5, 0, 1, 2)
  2066. # ###########################################################
  2067. # ############# Create CNC Job ##############################
  2068. # ###########################################################
  2069. self.tool_data_label = QtWidgets.QLabel(
  2070. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2071. self.tool_data_label.setToolTip(
  2072. _(
  2073. "The data used for creating GCode.\n"
  2074. "Each tool store it's own set of such data."
  2075. )
  2076. )
  2077. grid0.addWidget(self.tool_data_label, 6, 0, 1, 2)
  2078. self.exc_param_frame = QtWidgets.QFrame()
  2079. self.exc_param_frame.setContentsMargins(0, 0, 0, 0)
  2080. grid0.addWidget(self.exc_param_frame, 7, 0, 1, 2)
  2081. self.exc_tools_box = QtWidgets.QVBoxLayout()
  2082. self.exc_tools_box.setContentsMargins(0, 0, 0, 0)
  2083. self.exc_param_frame.setLayout(self.exc_tools_box)
  2084. # #################################################################
  2085. # ################# GRID LAYOUT 3 ###############################
  2086. # #################################################################
  2087. self.grid1 = QtWidgets.QGridLayout()
  2088. self.grid1.setColumnStretch(0, 0)
  2089. self.grid1.setColumnStretch(1, 1)
  2090. self.exc_tools_box.addLayout(self.grid1)
  2091. # Cut Z
  2092. self.cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  2093. self.cutzlabel.setToolTip(
  2094. _("Drill depth (negative)\n"
  2095. "below the copper surface.")
  2096. )
  2097. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2098. self.cutz_entry.set_precision(self.decimals)
  2099. if machinist_setting == 0:
  2100. self.cutz_entry.set_range(-9999.9999, 0.0000)
  2101. else:
  2102. self.cutz_entry.set_range(-9999.9999, 9999.9999)
  2103. self.cutz_entry.setSingleStep(0.1)
  2104. self.cutz_entry.setObjectName("e_cutz")
  2105. self.grid1.addWidget(self.cutzlabel, 4, 0)
  2106. self.grid1.addWidget(self.cutz_entry, 4, 1)
  2107. # Multi-Depth
  2108. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  2109. self.mpass_cb.setToolTip(
  2110. _(
  2111. "Use multiple passes to limit\n"
  2112. "the cut depth in each pass. Will\n"
  2113. "cut multiple times until Cut Z is\n"
  2114. "reached."
  2115. )
  2116. )
  2117. self.mpass_cb.setObjectName("e_multidepth")
  2118. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2119. self.maxdepth_entry.set_precision(self.decimals)
  2120. self.maxdepth_entry.set_range(0, 9999.9999)
  2121. self.maxdepth_entry.setSingleStep(0.1)
  2122. self.maxdepth_entry.setToolTip(_("Depth of each pass (positive)."))
  2123. self.maxdepth_entry.setObjectName("e_depthperpass")
  2124. self.mis_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  2125. self.grid1.addWidget(self.mpass_cb, 5, 0)
  2126. self.grid1.addWidget(self.maxdepth_entry, 5, 1)
  2127. # Travel Z (z_move)
  2128. self.travelzlabel = QtWidgets.QLabel('%s:' % _('Travel Z'))
  2129. self.travelzlabel.setToolTip(
  2130. _("Tool height when travelling\n"
  2131. "across the XY plane.")
  2132. )
  2133. self.travelz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2134. self.travelz_entry.set_precision(self.decimals)
  2135. if machinist_setting == 0:
  2136. self.travelz_entry.set_range(0.00001, 9999.9999)
  2137. else:
  2138. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  2139. self.travelz_entry.setSingleStep(0.1)
  2140. self.travelz_entry.setObjectName("e_travelz")
  2141. self.grid1.addWidget(self.travelzlabel, 6, 0)
  2142. self.grid1.addWidget(self.travelz_entry, 6, 1)
  2143. # Excellon Feedrate Z
  2144. self.frzlabel = QtWidgets.QLabel('%s:' % _('Feedrate Z'))
  2145. self.frzlabel.setToolTip(
  2146. _("Tool speed while drilling\n"
  2147. "(in units per minute).\n"
  2148. "So called 'Plunge' feedrate.\n"
  2149. "This is for linear move G01.")
  2150. )
  2151. self.feedrate_z_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2152. self.feedrate_z_entry.set_precision(self.decimals)
  2153. self.feedrate_z_entry.set_range(0.0, 99999.9999)
  2154. self.feedrate_z_entry.setSingleStep(0.1)
  2155. self.feedrate_z_entry.setObjectName("e_feedratez")
  2156. self.grid1.addWidget(self.frzlabel, 14, 0)
  2157. self.grid1.addWidget(self.feedrate_z_entry, 14, 1)
  2158. # Excellon Rapid Feedrate
  2159. self.feedrate_rapid_label = QtWidgets.QLabel('%s:' % _('Feedrate Rapids'))
  2160. self.feedrate_rapid_label.setToolTip(
  2161. _("Tool speed while drilling\n"
  2162. "(in units per minute).\n"
  2163. "This is for the rapid move G00.\n"
  2164. "It is useful only for Marlin,\n"
  2165. "ignore for any other cases.")
  2166. )
  2167. self.feedrate_rapid_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2168. self.feedrate_rapid_entry.set_precision(self.decimals)
  2169. self.feedrate_rapid_entry.set_range(0.0, 99999.9999)
  2170. self.feedrate_rapid_entry.setSingleStep(0.1)
  2171. self.feedrate_rapid_entry.setObjectName("e_fr_rapid")
  2172. self.grid1.addWidget(self.feedrate_rapid_label, 16, 0)
  2173. self.grid1.addWidget(self.feedrate_rapid_entry, 16, 1)
  2174. # default values is to hide
  2175. self.feedrate_rapid_label.hide()
  2176. self.feedrate_rapid_entry.hide()
  2177. # Spindlespeed
  2178. self.spindle_label = QtWidgets.QLabel('%s:' % _('Spindle speed'))
  2179. self.spindle_label.setToolTip(
  2180. _("Speed of the spindle\n"
  2181. "in RPM (optional)")
  2182. )
  2183. self.spindlespeed_entry = FCSpinner(callback=self.confirmation_message_int)
  2184. self.spindlespeed_entry.set_range(0, 1000000)
  2185. self.spindlespeed_entry.set_step(100)
  2186. self.spindlespeed_entry.setObjectName("e_spindlespeed")
  2187. self.grid1.addWidget(self.spindle_label, 19, 0)
  2188. self.grid1.addWidget(self.spindlespeed_entry, 19, 1)
  2189. # Dwell
  2190. self.dwell_cb = FCCheckBox('%s:' % _('Dwell'))
  2191. self.dwell_cb.setToolTip(
  2192. _("Pause to allow the spindle to reach its\n"
  2193. "speed before cutting.")
  2194. )
  2195. self.dwell_cb.setObjectName("e_dwell")
  2196. # Dwelltime
  2197. self.dwelltime_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2198. self.dwelltime_entry.set_precision(self.decimals)
  2199. self.dwelltime_entry.set_range(0.0, 9999.9999)
  2200. self.dwelltime_entry.setSingleStep(0.1)
  2201. self.dwelltime_entry.setToolTip(
  2202. _("Number of time units for spindle to dwell.")
  2203. )
  2204. self.dwelltime_entry.setObjectName("e_dwelltime")
  2205. self.grid1.addWidget(self.dwell_cb, 20, 0)
  2206. self.grid1.addWidget(self.dwelltime_entry, 20, 1)
  2207. self.ois_dwell = OptionalInputSection(self.dwell_cb, [self.dwelltime_entry])
  2208. # Tool Offset
  2209. self.tool_offset_label = QtWidgets.QLabel('%s:' % _('Offset Z'))
  2210. self.tool_offset_label.setToolTip(
  2211. _("Some drill bits (the larger ones) need to drill deeper\n"
  2212. "to create the desired exit hole diameter due of the tip shape.\n"
  2213. "The value here can compensate the Cut Z parameter.")
  2214. )
  2215. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2216. self.offset_entry.set_precision(self.decimals)
  2217. self.offset_entry.set_range(-9999.9999, 9999.9999)
  2218. self.offset_entry.setObjectName("e_offset")
  2219. self.grid1.addWidget(self.tool_offset_label, 25, 0)
  2220. self.grid1.addWidget(self.offset_entry, 25, 1)
  2221. # Drill slots
  2222. self.drill_slots_cb = FCCheckBox('%s' % _('Drill slots'))
  2223. self.drill_slots_cb.setToolTip(
  2224. _("If the selected tool has slots then they will be drilled.")
  2225. )
  2226. self.drill_slots_cb.setObjectName("e_drill_slots")
  2227. self.grid1.addWidget(self.drill_slots_cb, 27, 0, 1, 2)
  2228. # Drill Overlap
  2229. self.drill_overlap_label = QtWidgets.QLabel('%s:' % _('Overlap'))
  2230. self.drill_overlap_label.setToolTip(
  2231. _("How much (percentage) of the tool diameter to overlap previous drill hole.")
  2232. )
  2233. self.drill_overlap_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2234. self.drill_overlap_entry.set_precision(self.decimals)
  2235. self.drill_overlap_entry.set_range(0.0, 9999.9999)
  2236. self.drill_overlap_entry.setSingleStep(0.1)
  2237. self.drill_overlap_entry.setObjectName("e_drill_slots_overlap")
  2238. self.grid1.addWidget(self.drill_overlap_label, 28, 0)
  2239. self.grid1.addWidget(self.drill_overlap_entry, 28, 1)
  2240. # Last drill in slot
  2241. self.last_drill_cb = FCCheckBox('%s' % _('Last drill'))
  2242. self.last_drill_cb.setToolTip(
  2243. _("If the slot length is not completely covered by drill holes,\n"
  2244. "add a drill hole on the slot end point.")
  2245. )
  2246. self.last_drill_cb.setObjectName("e_drill_last_drill")
  2247. self.grid1.addWidget(self.last_drill_cb, 30, 0, 1, 2)
  2248. self.ois_drill_overlap = OptionalInputSection(
  2249. self.drill_slots_cb,
  2250. [
  2251. self.drill_overlap_label,
  2252. self.drill_overlap_entry,
  2253. self.last_drill_cb
  2254. ]
  2255. )
  2256. # #################################################################
  2257. # ################# GRID LAYOUT 5 ###############################
  2258. # #################################################################
  2259. # ################# COMMON PARAMETERS #############################
  2260. self.grid3 = QtWidgets.QGridLayout()
  2261. self.grid3.setColumnStretch(0, 0)
  2262. self.grid3.setColumnStretch(1, 1)
  2263. self.exc_tools_box.addLayout(self.grid3)
  2264. separator_line2 = QtWidgets.QFrame()
  2265. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  2266. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  2267. self.grid3.addWidget(separator_line2, 0, 0, 1, 2)
  2268. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  2269. self.apply_param_to_all.setToolTip(
  2270. _("The parameters in the current form will be applied\n"
  2271. "on all the tools from the Tool Table.")
  2272. )
  2273. self.grid3.addWidget(self.apply_param_to_all, 1, 0, 1, 2)
  2274. separator_line2 = QtWidgets.QFrame()
  2275. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  2276. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  2277. self.grid3.addWidget(separator_line2, 2, 0, 1, 2)
  2278. # General Parameters
  2279. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  2280. self.gen_param_label.setToolTip(
  2281. _("Parameters that are common for all tools.")
  2282. )
  2283. self.grid3.addWidget(self.gen_param_label, 3, 0, 1, 2)
  2284. # Tool change Z:
  2285. self.toolchange_cb = FCCheckBox('%s:' % _("Tool change Z"))
  2286. self.toolchange_cb.setToolTip(
  2287. _("Include tool-change sequence\n"
  2288. "in G-Code (Pause for tool change).")
  2289. )
  2290. self.toolchangez_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2291. self.toolchangez_entry.set_precision(self.decimals)
  2292. self.toolchangez_entry.setToolTip(
  2293. _("Z-axis position (height) for\n"
  2294. "tool change.")
  2295. )
  2296. if machinist_setting == 0:
  2297. self.toolchangez_entry.set_range(0.0, 9999.9999)
  2298. else:
  2299. self.toolchangez_entry.set_range(-9999.9999, 9999.9999)
  2300. self.toolchangez_entry.setSingleStep(0.1)
  2301. self.ois_tcz_e = OptionalInputSection(self.toolchange_cb, [self.toolchangez_entry])
  2302. self.grid3.addWidget(self.toolchange_cb, 8, 0)
  2303. self.grid3.addWidget(self.toolchangez_entry, 8, 1)
  2304. # Start move Z:
  2305. self.estartz_label = QtWidgets.QLabel('%s:' % _("Start Z"))
  2306. self.estartz_label.setToolTip(
  2307. _("Height of the tool just after start.\n"
  2308. "Delete the value if you don't need this feature.")
  2309. )
  2310. self.estartz_entry = NumericalEvalEntry(border_color='#0069A9')
  2311. self.grid3.addWidget(self.estartz_label, 9, 0)
  2312. self.grid3.addWidget(self.estartz_entry, 9, 1)
  2313. # End move Z:
  2314. self.endz_label = QtWidgets.QLabel('%s:' % _("End move Z"))
  2315. self.endz_label.setToolTip(
  2316. _("Height of the tool after\n"
  2317. "the last move at the end of the job.")
  2318. )
  2319. self.endz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2320. self.endz_entry.set_precision(self.decimals)
  2321. if machinist_setting == 0:
  2322. self.endz_entry.set_range(0.0, 9999.9999)
  2323. else:
  2324. self.endz_entry.set_range(-9999.9999, 9999.9999)
  2325. self.endz_entry.setSingleStep(0.1)
  2326. self.grid3.addWidget(self.endz_label, 11, 0)
  2327. self.grid3.addWidget(self.endz_entry, 11, 1)
  2328. # End Move X,Y
  2329. endmove_xy_label = QtWidgets.QLabel('%s:' % _('End move X,Y'))
  2330. endmove_xy_label.setToolTip(
  2331. _("End move X,Y position. In format (x,y).\n"
  2332. "If no value is entered then there is no move\n"
  2333. "on X,Y plane at the end of the job.")
  2334. )
  2335. self.endxy_entry = NumericalEvalEntry(border_color='#0069A9')
  2336. self.endxy_entry.setPlaceholderText(_("X,Y coordinates"))
  2337. self.grid3.addWidget(endmove_xy_label, 12, 0)
  2338. self.grid3.addWidget(self.endxy_entry, 12, 1)
  2339. # Probe depth
  2340. self.pdepth_label = QtWidgets.QLabel('%s:' % _("Probe Z depth"))
  2341. self.pdepth_label.setToolTip(
  2342. _("The maximum depth that the probe is allowed\n"
  2343. "to probe. Negative value, in current units.")
  2344. )
  2345. self.pdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2346. self.pdepth_entry.set_precision(self.decimals)
  2347. self.pdepth_entry.set_range(-9999.9999, 9999.9999)
  2348. self.pdepth_entry.setSingleStep(0.1)
  2349. self.pdepth_entry.setObjectName("e_depth_probe")
  2350. self.grid3.addWidget(self.pdepth_label, 13, 0)
  2351. self.grid3.addWidget(self.pdepth_entry, 13, 1)
  2352. self.pdepth_label.hide()
  2353. self.pdepth_entry.setVisible(False)
  2354. # Probe feedrate
  2355. self.feedrate_probe_label = QtWidgets.QLabel('%s:' % _("Feedrate Probe"))
  2356. self.feedrate_probe_label.setToolTip(
  2357. _("The feedrate used while the probe is probing.")
  2358. )
  2359. self.feedrate_probe_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2360. self.feedrate_probe_entry.set_precision(self.decimals)
  2361. self.feedrate_probe_entry.set_range(0.0, 9999.9999)
  2362. self.feedrate_probe_entry.setSingleStep(0.1)
  2363. self.feedrate_probe_entry.setObjectName("e_fr_probe")
  2364. self.grid3.addWidget(self.feedrate_probe_label, 14, 0)
  2365. self.grid3.addWidget(self.feedrate_probe_entry, 14, 1)
  2366. self.feedrate_probe_label.hide()
  2367. self.feedrate_probe_entry.setVisible(False)
  2368. # Preprocessor Excellon selection
  2369. pp_excellon_label = QtWidgets.QLabel('%s:' % _("Preprocessor"))
  2370. pp_excellon_label.setToolTip(
  2371. _("The preprocessor JSON file that dictates\n"
  2372. "Gcode output for Excellon Objects.")
  2373. )
  2374. self.pp_excellon_name_cb = FCComboBox()
  2375. self.pp_excellon_name_cb.setFocusPolicy(QtCore.Qt.StrongFocus)
  2376. self.grid3.addWidget(pp_excellon_label, 15, 0)
  2377. self.grid3.addWidget(self.pp_excellon_name_cb, 15, 1)
  2378. # ------------------------------------------------------------------------------------------------------------
  2379. # ------------------------- EXCLUSION AREAS ------------------------------------------------------------------
  2380. # ------------------------------------------------------------------------------------------------------------
  2381. # Exclusion Areas
  2382. self.exclusion_cb = FCCheckBox('%s' % _("Add exclusion areas"))
  2383. self.exclusion_cb.setToolTip(
  2384. _(
  2385. "Include exclusion areas.\n"
  2386. "In those areas the travel of the tools\n"
  2387. "is forbidden."
  2388. )
  2389. )
  2390. self.grid3.addWidget(self.exclusion_cb, 20, 0, 1, 2)
  2391. self.exclusion_frame = QtWidgets.QFrame()
  2392. self.exclusion_frame.setContentsMargins(0, 0, 0, 0)
  2393. self.grid3.addWidget(self.exclusion_frame, 22, 0, 1, 2)
  2394. self.exclusion_box = QtWidgets.QVBoxLayout()
  2395. self.exclusion_box.setContentsMargins(0, 0, 0, 0)
  2396. self.exclusion_frame.setLayout(self.exclusion_box)
  2397. self.exclusion_table = FCTable()
  2398. self.exclusion_box.addWidget(self.exclusion_table)
  2399. self.exclusion_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  2400. self.exclusion_table.setColumnCount(4)
  2401. self.exclusion_table.setColumnWidth(0, 20)
  2402. self.exclusion_table.setHorizontalHeaderLabels(['#', _('Object'), _('Strategy'), _('Over Z')])
  2403. self.exclusion_table.horizontalHeaderItem(0).setToolTip(_("This is the Area ID."))
  2404. self.exclusion_table.horizontalHeaderItem(1).setToolTip(
  2405. _("Type of the object where the exclusion area was added."))
  2406. self.exclusion_table.horizontalHeaderItem(2).setToolTip(
  2407. _("The strategy used for exclusion area. Go around the exclusion areas or over it."))
  2408. self.exclusion_table.horizontalHeaderItem(3).setToolTip(
  2409. _("If the strategy is to go over the area then this is the height at which the tool will go to avoid the "
  2410. "exclusion area."))
  2411. self.exclusion_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2412. grid_a1 = QtWidgets.QGridLayout()
  2413. grid_a1.setColumnStretch(0, 0)
  2414. grid_a1.setColumnStretch(1, 1)
  2415. self.exclusion_box.addLayout(grid_a1)
  2416. # Chose Strategy
  2417. self.strategy_label = FCLabel('%s:' % _("Strategy"))
  2418. self.strategy_label.setToolTip(_("The strategy followed when encountering an exclusion area.\n"
  2419. "Can be:\n"
  2420. "- Over -> when encountering the area, the tool will go to a set height\n"
  2421. "- Around -> will avoid the exclusion area by going around the area"))
  2422. self.strategy_radio = RadioSet([{'label': _('Over'), 'value': 'over'},
  2423. {'label': _('Around'), 'value': 'around'}])
  2424. grid_a1.addWidget(self.strategy_label, 1, 0)
  2425. grid_a1.addWidget(self.strategy_radio, 1, 1)
  2426. # Over Z
  2427. self.over_z_label = FCLabel('%s:' % _("Over Z"))
  2428. self.over_z_label.setToolTip(_("The height Z to which the tool will rise in order to avoid\n"
  2429. "an interdiction area."))
  2430. self.over_z_entry = FCDoubleSpinner()
  2431. self.over_z_entry.set_range(0.000, 9999.9999)
  2432. self.over_z_entry.set_precision(self.decimals)
  2433. grid_a1.addWidget(self.over_z_label, 2, 0)
  2434. grid_a1.addWidget(self.over_z_entry, 2, 1)
  2435. # Button Add Area
  2436. self.add_area_button = QtWidgets.QPushButton(_('Add area:'))
  2437. self.add_area_button.setToolTip(_("Add an Exclusion Area."))
  2438. # Area Selection shape
  2439. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  2440. {'label': _("Polygon"), 'value': 'polygon'}])
  2441. self.area_shape_radio.setToolTip(
  2442. _("The kind of selection shape used for area selection.")
  2443. )
  2444. grid_a1.addWidget(self.add_area_button, 4, 0)
  2445. grid_a1.addWidget(self.area_shape_radio, 4, 1)
  2446. h_lay_1 = QtWidgets.QHBoxLayout()
  2447. self.exclusion_box.addLayout(h_lay_1)
  2448. # Button Delete All Areas
  2449. self.delete_area_button = QtWidgets.QPushButton(_('Delete All'))
  2450. self.delete_area_button.setToolTip(_("Delete all exclusion areas."))
  2451. # Button Delete Selected Areas
  2452. self.delete_sel_area_button = QtWidgets.QPushButton(_('Delete Selected'))
  2453. self.delete_sel_area_button.setToolTip(_("Delete all exclusion areas that are selected in the table."))
  2454. h_lay_1.addWidget(self.delete_area_button)
  2455. h_lay_1.addWidget(self.delete_sel_area_button)
  2456. self.ois_exclusion_exc = OptionalHideInputSection(self.exclusion_cb, [self.exclusion_frame])
  2457. # -------------------------- EXCLUSION AREAS END -------------------------------------------------------------
  2458. # ------------------------------------------------------------------------------------------------------------
  2459. separator_line = QtWidgets.QFrame()
  2460. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2461. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2462. self.grid3.addWidget(separator_line, 25, 0, 1, 2)
  2463. # #################################################################
  2464. # ################# GRID LAYOUT 6 ###############################
  2465. # #################################################################
  2466. self.grid4 = QtWidgets.QGridLayout()
  2467. self.grid4.setColumnStretch(0, 0)
  2468. self.grid4.setColumnStretch(1, 1)
  2469. self.tools_box.addLayout(self.grid4)
  2470. self.generate_cnc_button = QtWidgets.QPushButton(_('Generate CNCJob object'))
  2471. self.generate_cnc_button.setToolTip(
  2472. _("Generate the CNC Job.\n"
  2473. "If milling then an additional Geometry object will be created.\n"
  2474. "Add / Select at least one tool in the tool-table.\n"
  2475. "Click the # header to select all, or Ctrl + LMB\n"
  2476. "for custom selection of tools.")
  2477. )
  2478. self.generate_cnc_button.setStyleSheet("""
  2479. QPushButton
  2480. {
  2481. font-weight: bold;
  2482. }
  2483. """)
  2484. self.grid4.addWidget(self.generate_cnc_button, 3, 0, 1, 3)
  2485. self.tools_box.addStretch()
  2486. # ## Reset Tool
  2487. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  2488. self.reset_button.setToolTip(
  2489. _("Will reset the tool parameters.")
  2490. )
  2491. self.reset_button.setStyleSheet("""
  2492. QPushButton
  2493. {
  2494. font-weight: bold;
  2495. }
  2496. """)
  2497. self.tools_box.addWidget(self.reset_button)
  2498. # ############################ FINSIHED GUI ###################################
  2499. # #############################################################################
  2500. def confirmation_message(self, accepted, minval, maxval):
  2501. if accepted is False:
  2502. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2503. self.decimals,
  2504. minval,
  2505. self.decimals,
  2506. maxval), False)
  2507. else:
  2508. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2509. def confirmation_message_int(self, accepted, minval, maxval):
  2510. if accepted is False:
  2511. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2512. (_("Edited value is out of range"), minval, maxval), False)
  2513. else:
  2514. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2515. def distance(pt1, pt2):
  2516. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  2517. def distance_euclidian(x1, y1, x2, y2):
  2518. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  2519. class AttrDict(dict):
  2520. def __init__(self, *args, **kwargs):
  2521. super(AttrDict, self).__init__(*args, **kwargs)
  2522. self.__dict__ = self