ToolDrilling.py 138 KB

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