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