ToolDrilling.py 144 KB

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