ToolDrilling.py 144 KB

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