ToolDrilling.py 138 KB

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