ToolDrilling.py 141 KB

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