ToolDrilling.py 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359
  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 cascaded_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. fcTranslate.apply_language('strings')
  23. if '_' not in builtins.__dict__:
  24. _ = gettext.gettext
  25. log = logging.getLogger('base')
  26. settings = QtCore.QSettings("Open Source", "FlatCAM")
  27. if settings.contains("machinist"):
  28. machinist_setting = settings.value('machinist', type=int)
  29. else:
  30. machinist_setting = 0
  31. class ToolDrilling(AppTool, Excellon):
  32. def __init__(self, app):
  33. self.app = app
  34. self.decimals = self.app.decimals
  35. AppTool.__init__(self, app)
  36. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  37. # #############################################################################
  38. # ######################### Tool GUI ##########################################
  39. # #############################################################################
  40. self.ui = DrillingUI(layout=self.layout, app=self.app)
  41. # #############################################################################
  42. # ########################## VARIABLES ########################################
  43. # #############################################################################
  44. self.units = ''
  45. self.excellon_tools = {}
  46. self.tooluid = 0
  47. # dict that holds the object names and the option name
  48. # the key is the object name (defines in ObjectUI) for each UI element that is a parameter
  49. # particular for a tool and the value is the actual name of the option that the UI element is changing
  50. self.name2option = {}
  51. # store here the default data for Geometry Data
  52. self.default_data = {}
  53. self.obj_name = ""
  54. self.excellon_obj = None
  55. self.first_click = False
  56. self.cursor_pos = None
  57. self.mouse_is_dragging = False
  58. # store here the points for the "Polygon" area selection shape
  59. self.points = []
  60. self.mm = None
  61. self.mr = None
  62. self.kp = None
  63. # variable to store the total amount of drills per job
  64. self.tot_drill_cnt = 0
  65. self.tool_row = 0
  66. # variable to store the total amount of slots per job
  67. self.tot_slot_cnt = 0
  68. self.tool_row_slots = 0
  69. # variable to store the distance travelled
  70. self.travel_distance = 0.0
  71. self.grid_status_memory = self.app.ui.grid_snap_btn.isChecked()
  72. # store here the state of the exclusion checkbox state to be restored after building the UI
  73. # TODO add this in the sel.app.defaults dict and in Preferences
  74. self.exclusion_area_cb_is_checked = False
  75. # store here solid_geometry when there are tool with isolation job
  76. self.solid_geometry = []
  77. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  78. self.tooldia = None
  79. # multiprocessing
  80. self.pool = self.app.pool
  81. self.results = []
  82. # disconnect flags
  83. self.area_sel_disconnect_flag = False
  84. self.poly_sel_disconnect_flag = False
  85. self.form_fields = {
  86. "excellon_milling_type": self.ui.milling_type_radio,
  87. }
  88. self.name2option = {
  89. "e_milling_type": "excellon_milling_type",
  90. }
  91. self.old_tool_dia = None
  92. self.poly_drawn = False
  93. self.connect_signals_at_init()
  94. def install(self, icon=None, separator=None, **kwargs):
  95. AppTool.install(self, icon, separator, shortcut='Alt+D', **kwargs)
  96. def run(self, toggle=True):
  97. self.app.defaults.report_usage("ToolDrilling()")
  98. log.debug("ToolDrilling().run() was launched ...")
  99. if toggle:
  100. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  101. if self.app.ui.splitter.sizes()[0] == 0:
  102. self.app.ui.splitter.setSizes([1, 1])
  103. else:
  104. try:
  105. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  106. # if tab is populated with the tool but it does not have the focus, focus on it
  107. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  108. # focus on Tool Tab
  109. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  110. else:
  111. self.app.ui.splitter.setSizes([0, 1])
  112. except AttributeError:
  113. pass
  114. else:
  115. if self.app.ui.splitter.sizes()[0] == 0:
  116. self.app.ui.splitter.setSizes([1, 1])
  117. AppTool.run(self)
  118. self.set_tool_ui()
  119. # reset those objects on a new run
  120. self.excellon_obj = None
  121. self.obj_name = ''
  122. self.build_ui()
  123. # all the tools are selected by default
  124. self.ui.tools_table.selectAll()
  125. self.app.ui.notebook.setTabText(2, _("Drilling Tool"))
  126. def connect_signals_at_init(self):
  127. # #############################################################################
  128. # ############################ SIGNALS ########################################
  129. # #############################################################################
  130. self.ui.object_combo.currentIndexChanged.connect(self.on_object_changed)
  131. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  132. self.ui.generate_cnc_button.clicked.connect(self.on_cnc_button_click)
  133. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  134. # Exclusion areas signals
  135. self.ui.exclusion_table.horizontalHeader().sectionClicked.connect(self.exclusion_table_toggle_all)
  136. self.ui.exclusion_table.lost_focus.connect(self.clear_selection)
  137. self.ui.exclusion_table.itemClicked.connect(self.draw_sel_shape)
  138. self.ui.add_area_button.clicked.connect(self.on_add_area_click)
  139. self.ui.delete_area_button.clicked.connect(self.on_clear_area_click)
  140. self.ui.delete_sel_area_button.clicked.connect(self.on_delete_sel_areas)
  141. self.ui.strategy_radio.activated_custom.connect(self.on_strategy)
  142. self.on_operation_type(val='drill')
  143. self.ui.operation_radio.activated_custom.connect(self.on_operation_type)
  144. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  145. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  146. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  147. self.app.cleanup.connect(self.set_tool_ui)
  148. def set_tool_ui(self):
  149. self.units = self.app.defaults['units'].upper()
  150. self.old_tool_dia = self.app.defaults["tools_iso_newdia"]
  151. # try to select in the Gerber combobox the active object
  152. try:
  153. selected_obj = self.app.collection.get_active()
  154. if selected_obj.kind == 'excellon':
  155. current_name = selected_obj.options['name']
  156. self.ui.object_combo.set_value(current_name)
  157. except Exception:
  158. pass
  159. self.form_fields.update({
  160. "operation": self.ui.operation_radio,
  161. "milling_type": self.ui.milling_type_radio,
  162. "milling_dia": self.ui.mill_dia_entry,
  163. "cutz": self.ui.cutz_entry,
  164. "multidepth": self.ui.mpass_cb,
  165. "depthperpass": self.ui.maxdepth_entry,
  166. "travelz": self.ui.travelz_entry,
  167. "feedrate_z": self.ui.feedrate_z_entry,
  168. "feedrate": self.ui.xyfeedrate_entry,
  169. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  170. # "tooldia": self.ui.tooldia_entry,
  171. # "slot_tooldia": self.ui.slot_tooldia_entry,
  172. "toolchange": self.ui.toolchange_cb,
  173. "toolchangez": self.ui.toolchangez_entry,
  174. "extracut": self.ui.extracut_cb,
  175. "extracut_length": self.ui.e_cut_entry,
  176. "spindlespeed": self.ui.spindlespeed_entry,
  177. "dwell": self.ui.dwell_cb,
  178. "dwelltime": self.ui.dwelltime_entry,
  179. "startz": self.ui.estartz_entry,
  180. "endz": self.ui.endz_entry,
  181. "endxy": self.ui.endxy_entry,
  182. "offset": self.ui.offset_entry,
  183. "ppname_e": self.ui.pp_excellon_name_cb,
  184. "ppname_g": self.ui.pp_geo_name_cb,
  185. "z_pdepth": self.ui.pdepth_entry,
  186. "feedrate_probe": self.ui.feedrate_probe_entry,
  187. # "gcode_type": self.ui.excellon_gcode_type_radio,
  188. "area_exclusion": self.ui.exclusion_cb,
  189. "area_shape": self.ui.area_shape_radio,
  190. "area_strategy": self.ui.strategy_radio,
  191. "area_overz": self.ui.over_z_entry,
  192. })
  193. self.name2option = {
  194. "e_operation": "operation",
  195. "e_milling_type": "milling_type",
  196. "e_milling_dia": "milling_dia",
  197. "e_cutz": "cutz",
  198. "e_multidepth": "multidepth",
  199. "e_depthperpass": "depthperpass",
  200. "e_travelz": "travelz",
  201. "e_feedratexy": "feedrate",
  202. "e_feedratez": "feedrate_z",
  203. "e_fr_rapid": "feedrate_rapid",
  204. "e_extracut": "extracut",
  205. "e_extracut_length": "extracut_length",
  206. "e_spindlespeed": "spindlespeed",
  207. "e_dwell": "dwell",
  208. "e_dwelltime": "dwelltime",
  209. "e_offset": "offset",
  210. }
  211. # populate Excellon preprocessor combobox list
  212. for name in list(self.app.preprocessors.keys()):
  213. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  214. if name == 'hpgl':
  215. continue
  216. self.ui.pp_excellon_name_cb.addItem(name)
  217. # populate Geometry (milling) preprocessor combobox list
  218. for name in list(self.app.preprocessors.keys()):
  219. self.ui.pp_geo_name_cb.addItem(name)
  220. # Fill form fields
  221. # self.to_form()
  222. # update the changes in UI depending on the selected preprocessor in Preferences
  223. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  224. # self.ui.pp_excellon_name_cb combobox
  225. self.on_pp_changed()
  226. app_mode = self.app.defaults["global_app_level"]
  227. # Show/Hide Advanced Options
  228. if app_mode == 'b':
  229. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  230. self.ui.estartz_label.hide()
  231. self.ui.estartz_entry.hide()
  232. self.ui.feedrate_rapid_label.hide()
  233. self.ui.feedrate_rapid_entry.hide()
  234. self.ui.pdepth_label.hide()
  235. self.ui.pdepth_entry.hide()
  236. self.ui.feedrate_probe_label.hide()
  237. self.ui.feedrate_probe_entry.hide()
  238. else:
  239. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  240. self.ui.tools_frame.show()
  241. self.ui.order_radio.set_value(self.app.defaults["excellon_tool_order"])
  242. self.ui.milling_type_radio.set_value(self.app.defaults["excellon_milling_type"])
  243. loaded_obj = self.app.collection.get_by_name(self.ui.object_combo.get_value())
  244. if loaded_obj:
  245. outname = loaded_obj.options['name']
  246. else:
  247. outname = ''
  248. # init the working variables
  249. self.default_data.clear()
  250. self.default_data = {
  251. "name": outname + '_iso',
  252. "plot": self.app.defaults["excellon_plot"],
  253. "solid": False,
  254. "multicolored": False,
  255. "operation": "drill",
  256. "milling_type": "drills",
  257. "milling_dia": 0.04,
  258. "cutz": -0.1,
  259. "multidepth": False,
  260. "depthperpass": 0.7,
  261. "travelz": 0.1,
  262. "feedrate": self.app.defaults["geometry_feedrate"],
  263. "feedrate_z": 5.0,
  264. "feedrate_rapid": 5.0,
  265. "tooldia": 0.1,
  266. "slot_tooldia": 0.1,
  267. "toolchange": False,
  268. "toolchangez": 1.0,
  269. "toolchangexy": "0.0, 0.0",
  270. "extracut": self.app.defaults["geometry_extracut"],
  271. "extracut_length": self.app.defaults["geometry_extracut_length"],
  272. "endz": 2.0,
  273. "endxy": '',
  274. "startz": None,
  275. "offset": 0.0,
  276. "spindlespeed": 0,
  277. "dwell": True,
  278. "dwelltime": 1000,
  279. "ppname_e": 'default',
  280. "ppname_g": self.app.defaults["geometry_ppname_g"],
  281. "z_pdepth": -0.02,
  282. "feedrate_probe": 3.0,
  283. "optimization_type": "B",
  284. }
  285. # fill in self.default_data values from self.options
  286. for opt_key, opt_val in self.app.options.items():
  287. if opt_key.find('excellon_') == 0:
  288. self.default_data[opt_key] = deepcopy(opt_val)
  289. for opt_key, opt_val in self.app.options.items():
  290. if opt_key.find('geometry_') == 0:
  291. self.default_data[opt_key] = deepcopy(opt_val)
  292. self.on_object_changed()
  293. self.obj_name = ""
  294. self.excellon_obj = None
  295. self.first_click = False
  296. self.cursor_pos = None
  297. self.mouse_is_dragging = False
  298. self.units = self.app.defaults['units'].upper()
  299. # ########################################
  300. # #######3 TEMP SETTINGS #################
  301. # ########################################
  302. self.ui.operation_radio.set_value("drill")
  303. self.ui.operation_radio.setEnabled(False)
  304. def rebuild_ui(self):
  305. # read the table tools uid
  306. current_uid_list = []
  307. for row in range(self.ui.tools_table.rowCount()):
  308. uid = int(self.ui.tools_table.item(row, 3).text())
  309. current_uid_list.append(uid)
  310. new_tools = {}
  311. new_uid = 1
  312. for current_uid in current_uid_list:
  313. new_tools[new_uid] = deepcopy(self.iso_tools[current_uid])
  314. new_uid += 1
  315. self.iso_tools = new_tools
  316. # the tools table changed therefore we need to rebuild it
  317. QtCore.QTimer.singleShot(20, self.build_ui)
  318. def build_ui(self):
  319. self.ui_disconnect()
  320. # updated units
  321. self.units = self.app.defaults['units'].upper()
  322. self.obj_name = self.ui.object_combo.currentText()
  323. # Get source object.
  324. try:
  325. self.excellon_obj = self.app.collection.get_by_name(self.obj_name)
  326. except Exception as e:
  327. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  328. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  329. if self.excellon_obj:
  330. self.ui.exc_param_frame.setDisabled(False)
  331. sort = []
  332. for k, v in list(self.excellon_obj.tools.items()):
  333. sort.append((k, float('%.*f' % (self.decimals, float(v.get('C'))))))
  334. order = self.ui.order_radio.get_value()
  335. if order == 'fwd':
  336. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  337. elif order == 'rev':
  338. sorted_tools = sorted(sort, key=lambda t1: t1[1], reverse=True)
  339. else:
  340. sorted_tools = sort
  341. tools = [i[0] for i in sorted_tools]
  342. else:
  343. tools = []
  344. n = len(tools)
  345. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  346. self.ui.tools_table.setRowCount(n + 2)
  347. self.tool_row = 0
  348. new_options = {}
  349. if self.excellon_obj:
  350. for opt in self.excellon_obj.options:
  351. new_options[opt] = self.excellon_obj.options[opt]
  352. for tool_no in tools:
  353. # add the data dictionary for each tool with the default values
  354. self.tools[tool_no]['data'] = deepcopy(new_options)
  355. drill_cnt = 0 # variable to store the nr of drills per tool
  356. slot_cnt = 0 # variable to store the nr of slots per tool
  357. # Find no of drills for the current tool
  358. for drill in self.drills:
  359. if drill['tool'] == tool_no:
  360. drill_cnt += 1
  361. self.tot_drill_cnt += drill_cnt
  362. # Find no of slots for the current tool
  363. for slot in self.slots:
  364. if slot['tool'] == tool_no:
  365. slot_cnt += 1
  366. self.tot_slot_cnt += slot_cnt
  367. # Tool name/id
  368. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  369. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  370. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item)
  371. # Tool Diameter
  372. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.tools[tool_no]['C']))
  373. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  374. self.ui.tools_table.setItem(self.tool_row, 1, dia_item)
  375. # Number of drills per tool
  376. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  377. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  378. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item)
  379. # Tool unique ID
  380. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tool_no)))
  381. # ## REMEMBER: THIS COLUMN IS HIDDEN in UI
  382. self.ui.tools_table.setItem(self.tool_row, 3, tool_uid_item)
  383. # Number of slots per tool
  384. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  385. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  386. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  387. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  388. self.ui.tools_table.setItem(self.tool_row, 4, slot_count_item)
  389. self.tool_row += 1
  390. # add a last row with the Total number of drills
  391. empty_1 = QtWidgets.QTableWidgetItem('')
  392. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  393. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  394. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  395. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  396. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  397. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  398. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  399. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  400. font = QtGui.QFont()
  401. font.setBold(True)
  402. font.setWeight(75)
  403. for k in [1, 2]:
  404. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  405. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  406. self.tool_row += 1
  407. # add a last row with the Total number of slots
  408. empty_2 = QtWidgets.QTableWidgetItem('')
  409. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  410. empty_2_1 = QtWidgets.QTableWidgetItem('')
  411. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  412. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  413. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  414. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  415. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  416. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  417. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  418. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  419. self.ui.tools_table.setItem(self.tool_row, 4, tot_slot_count) # Total number of slots
  420. for kl in [1, 2, 4]:
  421. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  422. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  423. # make the diameter column editable
  424. for row in range(self.ui.tools_table.rowCount() - 2):
  425. self.ui.tools_table.item(row, 1).setFlags(
  426. QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  427. self.ui.tools_table.resizeColumnsToContents()
  428. self.ui.tools_table.resizeRowsToContents()
  429. vertical_header = self.ui.tools_table.verticalHeader()
  430. vertical_header.hide()
  431. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  432. horizontal_header = self.ui.tools_table.horizontalHeader()
  433. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  434. horizontal_header.setMinimumSectionSize(10)
  435. horizontal_header.setDefaultSectionSize(70)
  436. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  437. horizontal_header.resizeSection(0, 20)
  438. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  439. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  440. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  441. self.ui.tools_table.setSortingEnabled(False)
  442. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  443. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  444. # all the tools are selected by default
  445. self.ui.tools_table.selectAll()
  446. # Build Exclusion Areas section
  447. e_len = len(self.app.exc_areas.exclusion_areas_storage)
  448. self.ui.exclusion_table.setRowCount(e_len)
  449. area_id = 0
  450. for area in range(e_len):
  451. area_id += 1
  452. area_dict = self.app.exc_areas.exclusion_areas_storage[area]
  453. area_id_item = QtWidgets.QTableWidgetItem('%d' % int(area_id))
  454. area_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  455. self.ui.exclusion_table.setItem(area, 0, area_id_item) # Area id
  456. object_item = QtWidgets.QTableWidgetItem('%s' % area_dict["obj_type"])
  457. object_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  458. self.ui.exclusion_table.setItem(area, 1, object_item) # Origin Object
  459. strategy_item = QtWidgets.QTableWidgetItem('%s' % area_dict["strategy"])
  460. strategy_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  461. self.ui.exclusion_table.setItem(area, 2, strategy_item) # Strategy
  462. overz_item = QtWidgets.QTableWidgetItem('%s' % area_dict["overz"])
  463. overz_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  464. self.ui.exclusion_table.setItem(area, 3, overz_item) # Over Z
  465. self.ui.exclusion_table.resizeColumnsToContents()
  466. self.ui.exclusion_table.resizeRowsToContents()
  467. area_vheader = self.ui.exclusion_table.verticalHeader()
  468. area_vheader.hide()
  469. self.ui.exclusion_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  470. area_hheader = self.ui.exclusion_table.horizontalHeader()
  471. area_hheader.setMinimumSectionSize(10)
  472. area_hheader.setDefaultSectionSize(70)
  473. area_hheader.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  474. area_hheader.resizeSection(0, 20)
  475. area_hheader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  476. area_hheader.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  477. area_hheader.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  478. # area_hheader.setStretchLastSection(True)
  479. self.ui.exclusion_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  480. self.ui.exclusion_table.setColumnWidth(0, 20)
  481. self.ui.exclusion_table.setMinimumHeight(self.ui.exclusion_table.getHeight())
  482. self.ui.exclusion_table.setMaximumHeight(self.ui.exclusion_table.getHeight())
  483. self.ui_connect()
  484. # set the text on tool_data_label after loading the object
  485. sel_rows = set()
  486. sel_items = self.ui.tools_table.selectedItems()
  487. for it in sel_items:
  488. sel_rows.add(it.row())
  489. if len(sel_rows) > 1:
  490. self.ui.tool_data_label.setText(
  491. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  492. )
  493. def on_object_changed(self):
  494. # load the Excellon object
  495. self.obj_name = self.ui.object_combo.currentText()
  496. # Get source object.
  497. try:
  498. self.excellon_obj = self.app.collection.get_by_name(self.obj_name)
  499. except Exception as e:
  500. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  501. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  502. if self.excellon_obj is None:
  503. self.ui.exc_param_frame.setDisabled(True)
  504. else:
  505. self.ui.exc_param_frame.setDisabled(False)
  506. sort = []
  507. for k, v in list(self.excellon_obj.tools.items()):
  508. sort.append((k, float('%.*f' % (self.decimals, float(v.get('C'))))))
  509. dias = [i[0] for i in sort]
  510. if not dias:
  511. log.error("At least one tool diameter needed. Excellon object might be empty.")
  512. return
  513. tooluid = 0
  514. self.excellon_tools.clear()
  515. for tool_dia in dias:
  516. tooluid += 1
  517. self.excellon_tools.update({
  518. int(tooluid): {
  519. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  520. 'data': deepcopy(self.default_data),
  521. 'solid_geometry': []
  522. }
  523. })
  524. self.build_ui()
  525. def ui_connect(self):
  526. # Area Exception - exclusion shape added signal
  527. # first disconnect it from any other object
  528. try:
  529. self.app.exc_areas.e_shape_modified.disconnect()
  530. except (TypeError, AttributeError):
  531. pass
  532. # then connect it to the current build_ui() method
  533. self.app.exc_areas.e_shape_modified.connect(self.update_exclusion_table)
  534. # rows selected
  535. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  536. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  537. # Tool Parameters
  538. for opt in self.form_fields:
  539. current_widget = self.form_fields[opt]
  540. if isinstance(current_widget, FCCheckBox):
  541. current_widget.stateChanged.connect(self.form_to_storage)
  542. if isinstance(current_widget, RadioSet):
  543. current_widget.activated_custom.connect(self.form_to_storage)
  544. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  545. current_widget.returnPressed.connect(self.form_to_storage)
  546. elif isinstance(current_widget, FCComboBox):
  547. current_widget.currentIndexChanged.connect(self.form_to_storage)
  548. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  549. def ui_disconnect(self):
  550. # rows selected
  551. try:
  552. self.ui.tools_table.clicked.disconnect()
  553. except (TypeError, AttributeError):
  554. pass
  555. try:
  556. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  557. except (TypeError, AttributeError):
  558. pass
  559. # tool table widgets
  560. for row in range(self.ui.tools_table.rowCount()):
  561. try:
  562. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  563. except (TypeError, AttributeError):
  564. pass
  565. # Tool Parameters
  566. for opt in self.form_fields:
  567. current_widget = self.form_fields[opt]
  568. if isinstance(current_widget, FCCheckBox):
  569. try:
  570. current_widget.stateChanged.disconnect(self.form_to_storage)
  571. except (TypeError, ValueError):
  572. pass
  573. if isinstance(current_widget, RadioSet):
  574. try:
  575. current_widget.activated_custom.disconnect(self.form_to_storage)
  576. except (TypeError, ValueError):
  577. pass
  578. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  579. try:
  580. current_widget.returnPressed.disconnect(self.form_to_storage)
  581. except (TypeError, ValueError):
  582. pass
  583. elif isinstance(current_widget, FCComboBox):
  584. try:
  585. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  586. except (TypeError, ValueError):
  587. pass
  588. try:
  589. self.ui.order_radio.activated_custom[str].disconnect()
  590. except (TypeError, ValueError):
  591. pass
  592. def on_toggle_all_rows(self):
  593. """
  594. will toggle the selection of all rows in Tools table
  595. :return:
  596. """
  597. sel_model = self.ui.tools_table.selectionModel()
  598. sel_indexes = sel_model.selectedIndexes()
  599. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  600. sel_rows = set()
  601. for idx in sel_indexes:
  602. sel_rows.add(idx.row())
  603. if len(sel_rows) == self.ui.tools_table.rowCount():
  604. self.ui.tools_table.clearSelection()
  605. else:
  606. self.ui.tools_table.selectAll()
  607. self.update_ui()
  608. def on_row_selection_change(self):
  609. self.update_ui()
  610. def update_ui(self):
  611. self.blockSignals(True)
  612. sel_rows = set()
  613. table_items = self.ui.tools_table.selectedItems()
  614. if table_items:
  615. for it in table_items:
  616. sel_rows.add(it.row())
  617. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  618. if not sel_rows or len(sel_rows) == 0:
  619. self.ui.generate_cnc_button.setDisabled(True)
  620. self.ui.tool_data_label.setText(
  621. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  622. )
  623. self.blockSignals(False)
  624. return
  625. else:
  626. self.ui.generate_cnc_button.setDisabled(False)
  627. if len(sel_rows) == 1:
  628. # update the QLabel that shows for which Tool we have the parameters in the UI form
  629. tooluid = int(self.ui.tools_table.item(list(sel_rows)[0], 0).text())
  630. self.ui.tool_data_label.setText(
  631. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  632. )
  633. else:
  634. self.ui.tool_data_label.setText(
  635. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  636. )
  637. for c_row in sel_rows:
  638. # populate the form with the data from the tool associated with the row parameter
  639. try:
  640. item = self.ui.tools_table.item(c_row, 3)
  641. if type(item) is not None:
  642. tooluid = item.text()
  643. self.storage_to_form(self.drilling_tools[str(tooluid)]['data'])
  644. else:
  645. self.blockSignals(False)
  646. return
  647. except Exception as e:
  648. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  649. self.blockSignals(False)
  650. return
  651. self.blockSignals(False)
  652. def storage_to_form(self, dict_storage):
  653. """
  654. Will update the GUI with data from the "storage" in this case the dict self.tools
  655. :param dict_storage: A dictionary holding the data relevant for gnerating Gcode from Excellon
  656. :type dict_storage: dict
  657. :return: None
  658. :rtype:
  659. """
  660. for form_key in self.form_fields:
  661. for storage_key in dict_storage:
  662. if form_key == storage_key and form_key not in \
  663. ["toolchange", "toolchangez", "startz", "endz", "ppname_e", "ppname_g"]:
  664. try:
  665. self.form_fields[form_key].set_value(dict_storage[form_key])
  666. except Exception as e:
  667. log.debug("ToolDrilling.storage_to_form() --> %s" % str(e))
  668. pass
  669. def form_to_storage(self):
  670. """
  671. Will update the 'storage' attribute which is the dict self.tools with data collected from GUI
  672. :return: None
  673. :rtype:
  674. """
  675. if self.ui.tools_table.rowCount() == 0:
  676. # there is no tool in tool table so we can't save the GUI elements values to storage
  677. return
  678. self.blockSignals(True)
  679. widget_changed = self.sender()
  680. wdg_objname = widget_changed.objectName()
  681. option_changed = self.name2option[wdg_objname]
  682. # row = self.ui.tools_table.currentRow()
  683. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  684. for row in rows:
  685. if row < 0:
  686. row = 0
  687. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  688. for tooluid_key, tooluid_val in self.iso_tools.items():
  689. if int(tooluid_key) == tooluid_item:
  690. new_option_value = self.form_fields[option_changed].get_value()
  691. if option_changed in tooluid_val:
  692. tooluid_val[option_changed] = new_option_value
  693. if option_changed in tooluid_val['data']:
  694. tooluid_val['data'][option_changed] = new_option_value
  695. self.blockSignals(False)
  696. def on_operation_type(self, val):
  697. """
  698. Called by a RadioSet activated_custom signal
  699. :param val: Parameter passes by the signal that called this method
  700. :type val: str
  701. :return: None
  702. :rtype:
  703. """
  704. if val == 'mill':
  705. self.ui.mill_type_label.show()
  706. self.ui.milling_type_radio.show()
  707. self.ui.mill_dia_label.show()
  708. self.ui.mill_dia_entry.show()
  709. self.ui.frxylabel.show()
  710. self.ui.xyfeedrate_entry.show()
  711. self.ui.extracut_cb.show()
  712. self.ui.e_cut_entry.show()
  713. else:
  714. self.ui.mill_type_label.hide()
  715. self.ui.milling_type_radio.hide()
  716. self.ui.mill_dia_label.hide()
  717. self.ui.mill_dia_entry.hide()
  718. self.ui.frxylabel.hide()
  719. self.ui.xyfeedrate_entry.hide()
  720. self.ui.extracut_cb.hide()
  721. self.ui.e_cut_entry.hide()
  722. def get_selected_tools_list(self):
  723. """
  724. Returns the keys to the self.tools dictionary corresponding
  725. to the selections on the tool list in the appGUI.
  726. :return: List of tools.
  727. :rtype: list
  728. """
  729. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  730. def get_selected_tools_table_items(self):
  731. """
  732. Returns a list of lists, each list in the list is made out of row elements
  733. :return: List of table_tools items.
  734. :rtype: list
  735. """
  736. table_tools_items = []
  737. for x in self.ui.tools_table.selectedItems():
  738. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  739. # which does not have text
  740. txt = ''
  741. elem = []
  742. for column in range(0, self.ui.tools_table.columnCount() - 1):
  743. try:
  744. txt = self.ui.tools_table.item(x.row(), column).text()
  745. except AttributeError:
  746. try:
  747. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  748. except AttributeError:
  749. pass
  750. elem.append(txt)
  751. table_tools_items.append(deepcopy(elem))
  752. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  753. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  754. for item in table_tools_items:
  755. item[0] = str(item[0])
  756. return table_tools_items
  757. def on_apply_param_to_all_clicked(self):
  758. if self.ui.tools_table.rowCount() == 0:
  759. # there is no tool in tool table so we can't save the GUI elements values to storage
  760. log.debug("ToolDrilling.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  761. return
  762. self.blockSignals(True)
  763. row = self.ui.tools_table.currentRow()
  764. if row < 0:
  765. row = 0
  766. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  767. temp_tool_data = {}
  768. for tooluid_key, tooluid_val in self.iso_tools.items():
  769. if int(tooluid_key) == tooluid_item:
  770. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  771. # the current row in the tool table
  772. temp_tool_data = tooluid_val['data']
  773. break
  774. for tooluid_key, tooluid_val in self.iso_tools.items():
  775. tooluid_val['data'] = deepcopy(temp_tool_data)
  776. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  777. self.blockSignals(False)
  778. def on_order_changed(self, order):
  779. if order != 'no':
  780. self.build_ui()
  781. def on_tooltable_cellwidget_change(self):
  782. cw = self.sender()
  783. assert isinstance(cw, QtWidgets.QComboBox), \
  784. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  785. cw_index = self.ui.tools_table.indexAt(cw.pos())
  786. cw_row = cw_index.row()
  787. cw_col = cw_index.column()
  788. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  789. # if the sender is in the column with index 2 then we update the tool_type key
  790. if cw_col == 2:
  791. tt = cw.currentText()
  792. typ = 'Iso' if tt == 'V' else "Rough"
  793. self.iso_tools[current_uid].update({
  794. 'type': typ,
  795. 'tool_type': tt,
  796. })
  797. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  798. """
  799. Will generate an Geometry Object allowing to cut a drill hole instead of drilling it.
  800. Note: This method is a good template for generic operations as
  801. it takes it's options from parameters or otherwise from the
  802. object's options and returns a (success, msg) tuple as feedback
  803. for shell operations.
  804. :param tools: A list of tools where the drills are to be milled or a string: "all"
  805. :type tools:
  806. :param outname: the name of the resulting Geometry object
  807. :type outname: str
  808. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  809. :type tooldia: float
  810. :param plot: if to plot the resulting object
  811. :type plot: bool
  812. :param use_thread: if to use threading for creation of the Geometry object
  813. :type use_thread: bool
  814. :return: Success/failure condition tuple (bool, str).
  815. :rtype: tuple
  816. """
  817. # Get the tools from the list. These are keys
  818. # to self.tools
  819. if tools is None:
  820. tools = self.get_selected_tools_list()
  821. if outname is None:
  822. outname = self.options["name"] + "_mill"
  823. if tooldia is None:
  824. tooldia = float(self.options["tooldia"])
  825. # Sort tools by diameter. items() -> [('name', diameter), ...]
  826. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  827. sort = []
  828. for k, v in self.tools.items():
  829. sort.append((k, v.get('C')))
  830. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  831. if tools == "all":
  832. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  833. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  834. if len(tools) == 0:
  835. self.app.inform.emit('[ERROR_NOTCL] %s' %
  836. _("Please select one or more tools from the list and try again."))
  837. return False, "Error: No tools."
  838. for tool in tools:
  839. if tooldia > self.tools[tool]["C"]:
  840. self.app.inform.emit(
  841. '[ERROR_NOTCL] %s %s: %s' % (
  842. _("Milling tool for DRILLS is larger than hole size. Cancelled."),
  843. _("Tool"),
  844. str(tool)
  845. )
  846. )
  847. return False, "Error: Milling tool is larger than hole."
  848. def geo_init(geo_obj, app_obj):
  849. """
  850. :param geo_obj: New object
  851. :type geo_obj: GeometryObject
  852. :param app_obj: App
  853. :type app_obj: FlatCAMApp.App
  854. :return:
  855. :rtype:
  856. """
  857. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  858. app_obj.inform.emit(_("Generating drills milling geometry..."))
  859. # ## Add properties to the object
  860. # get the tool_table items in a list of row items
  861. tool_table_items = self.get_selected_tools_table_items()
  862. # insert an information only element in the front
  863. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  864. geo_obj.options['Tools_in_use'] = tool_table_items
  865. geo_obj.options['type'] = 'Excellon Geometry'
  866. geo_obj.options["cnctooldia"] = str(tooldia)
  867. geo_obj.options["multidepth"] = self.options["multidepth"]
  868. geo_obj.solid_geometry = []
  869. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  870. # for FlatCAM is 6 decimals,
  871. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  872. for hole in self.drills:
  873. if hole['tool'] in tools:
  874. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  875. if buffer_value == 0:
  876. geo_obj.solid_geometry.append(
  877. Point(hole['point']).buffer(0.0000001).exterior)
  878. else:
  879. geo_obj.solid_geometry.append(
  880. Point(hole['point']).buffer(buffer_value).exterior)
  881. if use_thread:
  882. def geo_thread(a_obj):
  883. a_obj.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  884. # Create a promise with the new name
  885. self.app.collection.promise(outname)
  886. # Send to worker
  887. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  888. else:
  889. self.app.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  890. return True, ""
  891. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  892. """
  893. Will generate an Geometry Object allowing to cut/mill a slot hole.
  894. Note: This method is a good template for generic operations as
  895. it takes it's options from parameters or otherwise from the
  896. object's options and returns a (success, msg) tuple as feedback
  897. for shell operations.
  898. :param tools: A list of tools where the drills are to be milled or a string: "all"
  899. :type tools:
  900. :param outname: the name of the resulting Geometry object
  901. :type outname: str
  902. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  903. :type tooldia: float
  904. :param plot: if to plot the resulting object
  905. :type plot: bool
  906. :param use_thread: if to use threading for creation of the Geometry object
  907. :type use_thread: bool
  908. :return: Success/failure condition tuple (bool, str).
  909. :rtype: tuple
  910. """
  911. # Get the tools from the list. These are keys
  912. # to self.tools
  913. if tools is None:
  914. tools = self.get_selected_tools_list()
  915. if outname is None:
  916. outname = self.options["name"] + "_mill"
  917. if tooldia is None:
  918. tooldia = float(self.options["slot_tooldia"])
  919. # Sort tools by diameter. items() -> [('name', diameter), ...]
  920. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  921. sort = []
  922. for k, v in self.tools.items():
  923. sort.append((k, v.get('C')))
  924. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  925. if tools == "all":
  926. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  927. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  928. if len(tools) == 0:
  929. self.app.inform.emit('[ERROR_NOTCL] %s' %
  930. _("Please select one or more tools from the list and try again."))
  931. return False, "Error: No tools."
  932. for tool in tools:
  933. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  934. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  935. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  936. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  937. self.app.inform.emit('[ERROR_NOTCL] %s' %
  938. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  939. return False, "Error: Milling tool is larger than hole."
  940. def geo_init(geo_obj, app_obj):
  941. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  942. app_obj.inform.emit(_("Generating slot milling geometry..."))
  943. # ## Add properties to the object
  944. # get the tool_table items in a list of row items
  945. tool_table_items = self.get_selected_tools_table_items()
  946. # insert an information only element in the front
  947. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  948. geo_obj.options['Tools_in_use'] = tool_table_items
  949. geo_obj.options['type'] = 'Excellon Geometry'
  950. geo_obj.options["cnctooldia"] = str(tooldia)
  951. geo_obj.options["multidepth"] = self.options["multidepth"]
  952. geo_obj.solid_geometry = []
  953. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  954. # for FlatCAM is 6 decimals,
  955. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  956. for slot in self.slots:
  957. if slot['tool'] in tools:
  958. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  959. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  960. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  961. # for the file_tool (tooldia actually)
  962. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  963. if buffer_value == 0:
  964. start = slot['start']
  965. stop = slot['stop']
  966. lines_string = LineString([start, stop])
  967. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  968. geo_obj.solid_geometry.append(poly)
  969. else:
  970. start = slot['start']
  971. stop = slot['stop']
  972. lines_string = LineString([start, stop])
  973. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  974. geo_obj.solid_geometry.append(poly)
  975. if use_thread:
  976. def geo_thread(a_obj):
  977. a_obj.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  978. # Create a promise with the new name
  979. self.app.collection.promise(outname)
  980. # Send to worker
  981. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  982. else:
  983. self.app.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  984. return True, ""
  985. def on_pp_changed(self):
  986. current_pp = self.ui.pp_excellon_name_cb.get_value()
  987. if "toolchange_probe" in current_pp.lower():
  988. self.ui.pdepth_entry.setVisible(True)
  989. self.ui.pdepth_label.show()
  990. self.ui.feedrate_probe_entry.setVisible(True)
  991. self.ui.feedrate_probe_label.show()
  992. else:
  993. self.ui.pdepth_entry.setVisible(False)
  994. self.ui.pdepth_label.hide()
  995. self.ui.feedrate_probe_entry.setVisible(False)
  996. self.ui.feedrate_probe_label.hide()
  997. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  998. self.ui.feedrate_rapid_label.show()
  999. self.ui.feedrate_rapid_entry.show()
  1000. else:
  1001. self.ui.feedrate_rapid_label.hide()
  1002. self.ui.feedrate_rapid_entry.hide()
  1003. if 'laser' in current_pp.lower():
  1004. self.ui.cutzlabel.hide()
  1005. self.ui.cutz_entry.hide()
  1006. try:
  1007. self.ui.mpass_cb.hide()
  1008. self.ui.maxdepth_entry.hide()
  1009. except AttributeError:
  1010. pass
  1011. if 'marlin' in current_pp.lower():
  1012. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  1013. self.ui.endz_label.show()
  1014. self.ui.endz_entry.show()
  1015. else:
  1016. self.ui.travelzlabel.hide()
  1017. self.ui.travelz_entry.hide()
  1018. self.ui.endz_label.hide()
  1019. self.ui.endz_entry.hide()
  1020. try:
  1021. self.ui.frzlabel.hide()
  1022. self.ui.feedrate_z_entry.hide()
  1023. except AttributeError:
  1024. pass
  1025. self.ui.dwell_cb.hide()
  1026. self.ui.dwelltime_entry.hide()
  1027. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  1028. try:
  1029. self.ui.tool_offset_label.hide()
  1030. self.ui.offset_entry.hide()
  1031. except AttributeError:
  1032. pass
  1033. else:
  1034. self.ui.cutzlabel.show()
  1035. self.ui.cutz_entry.show()
  1036. try:
  1037. self.ui.mpass_cb.show()
  1038. self.ui.maxdepth_entry.show()
  1039. except AttributeError:
  1040. pass
  1041. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  1042. self.ui.travelzlabel.show()
  1043. self.ui.travelz_entry.show()
  1044. self.ui.endz_label.show()
  1045. self.ui.endz_entry.show()
  1046. try:
  1047. self.ui.frzlabel.show()
  1048. self.ui.feedrate_z_entry.show()
  1049. except AttributeError:
  1050. pass
  1051. self.ui.dwell_cb.show()
  1052. self.ui.dwelltime_entry.show()
  1053. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  1054. try:
  1055. # self.ui.tool_offset_lbl.show()
  1056. self.ui.offset_entry.show()
  1057. except AttributeError:
  1058. pass
  1059. def on_cnc_button_click(self):
  1060. self.obj_name = self.ui.object_combo.currentText()
  1061. # Get source object.
  1062. try:
  1063. self.excellon_obj = self.app.collection.get_by_name(self.obj_name)
  1064. except Exception as e:
  1065. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1066. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1067. if self.excellon_obj is None:
  1068. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1069. return
  1070. # Get the tools from the list
  1071. tools = self.get_selected_tools_list()
  1072. if len(tools) == 0:
  1073. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1074. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1075. # in this case regardless of the selection status of that tool, use it.
  1076. if self.ui.tools_table.rowCount() == 3:
  1077. tools.append(self.ui.tools_table.item(0, 0).text())
  1078. else:
  1079. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1080. _("Please select one or more tools from the list and try again."))
  1081. return
  1082. xmin = self.options['xmin']
  1083. ymin = self.options['ymin']
  1084. xmax = self.options['xmax']
  1085. ymax = self.options['ymax']
  1086. job_name = self.options["name"] + "_cnc"
  1087. pp_excellon_name = self.options["ppname_e"]
  1088. # Object initialization function for app.app_obj.new_object()
  1089. def job_init(job_obj, app_obj):
  1090. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1091. app_obj.inform.emit(_("Generating Excellon CNCJob..."))
  1092. # get the tool_table items in a list of row items
  1093. tool_table_items = self.get_selected_tools_table_items()
  1094. # insert an information only element in the front
  1095. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1096. # ## Add properties to the object
  1097. job_obj.origin_kind = 'excellon'
  1098. job_obj.options['Tools_in_use'] = tool_table_items
  1099. job_obj.options['type'] = 'Excellon'
  1100. job_obj.options['ppname_e'] = pp_excellon_name
  1101. job_obj.multidepth = self.options["multidepth"]
  1102. job_obj.z_depthpercut = self.options["depthperpass"]
  1103. job_obj.z_move = float(self.options["travelz"])
  1104. job_obj.feedrate = float(self.options["feedrate_z"])
  1105. job_obj.z_feedrate = float(self.options["feedrate_z"])
  1106. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  1107. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] != 0 else None
  1108. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  1109. job_obj.dwell = self.options["dwell"]
  1110. job_obj.dwelltime = float(self.options["dwelltime"])
  1111. job_obj.pp_excellon_name = pp_excellon_name
  1112. job_obj.toolchange_xy_type = "excellon"
  1113. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1114. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1115. job_obj.options['xmin'] = xmin
  1116. job_obj.options['ymin'] = ymin
  1117. job_obj.options['xmax'] = xmax
  1118. job_obj.options['ymax'] = ymax
  1119. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1120. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1121. job_obj.z_cut = float(self.options['cutz'])
  1122. job_obj.toolchange = self.options["toolchange"]
  1123. job_obj.xy_toolchange = self.app.defaults["excellon_toolchangexy"]
  1124. job_obj.z_toolchange = float(self.options["toolchangez"])
  1125. job_obj.startz = float(self.options["startz"]) if self.options["startz"] else None
  1126. job_obj.endz = float(self.options["endz"])
  1127. job_obj.xy_end = self.options["endxy"]
  1128. job_obj.excellon_optimization_type = self.app.defaults["excellon_optimization_type"]
  1129. tools_csv = ','.join(tools)
  1130. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv, use_ui=True)
  1131. if ret_val == 'fail':
  1132. return 'fail'
  1133. job_obj.gcode_parse()
  1134. job_obj.create_geometry()
  1135. # To be run in separate thread
  1136. def job_thread(a_obj):
  1137. with self.app.proc_container.new(_("Generating CNC Code")):
  1138. a_obj.app_obj.new_object("cncjob", job_name, job_init)
  1139. # Create promise for the new name.
  1140. self.app.collection.promise(job_name)
  1141. # Send to worker
  1142. # self.app.worker.add_task(job_thread, [self.app])
  1143. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1144. def drilling_handler(self, obj):
  1145. pass
  1146. def on_key_press(self, event):
  1147. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1148. # matplotlib_key_flag = False
  1149. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1150. if type(event) is int:
  1151. key = event
  1152. # events from the GUI are of type QKeyEvent
  1153. elif type(event) == QtGui.QKeyEvent:
  1154. key = event.key()
  1155. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1156. # matplotlib_key_flag = True
  1157. key = event.key
  1158. key = QtGui.QKeySequence(key)
  1159. # check for modifiers
  1160. key_string = key.toString().lower()
  1161. if '+' in key_string:
  1162. mod, __, key_text = key_string.rpartition('+')
  1163. if mod.lower() == 'ctrl':
  1164. # modifiers = QtCore.Qt.ControlModifier
  1165. pass
  1166. elif mod.lower() == 'alt':
  1167. # modifiers = QtCore.Qt.AltModifier
  1168. pass
  1169. elif mod.lower() == 'shift':
  1170. # modifiers = QtCore.Qt.ShiftModifier
  1171. pass
  1172. else:
  1173. # modifiers = QtCore.Qt.NoModifier
  1174. pass
  1175. key = QtGui.QKeySequence(key_text)
  1176. # events from Vispy are of type KeyEvent
  1177. else:
  1178. key = event.key
  1179. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1180. self.points = []
  1181. self.poly_drawn = False
  1182. self.delete_moving_selection_shape()
  1183. self.delete_tool_selection_shape()
  1184. def on_add_area_click(self):
  1185. shape_button = self.ui.area_shape_radio
  1186. overz_button = self.ui.over_z_entry
  1187. strategy_radio = self.ui.strategy_radio
  1188. cnc_button = self.ui.generate_cnc_button
  1189. solid_geo = self.solid_geometry
  1190. obj_type = self.kind
  1191. self.app.exc_areas.on_add_area_click(
  1192. shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio,
  1193. solid_geo=solid_geo, obj_type=obj_type)
  1194. def on_clear_area_click(self):
  1195. if not self.app.exc_areas.exclusion_areas_storage:
  1196. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. There are no exclusion areas to delete."))
  1197. return
  1198. self.app.exc_areas.on_clear_area_click()
  1199. self.app.exc_areas.e_shape_modified.emit()
  1200. def on_delete_sel_areas(self):
  1201. sel_model = self.ui.exclusion_table.selectionModel()
  1202. sel_indexes = sel_model.selectedIndexes()
  1203. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1204. # so the duplicate rows will not be added
  1205. sel_rows = set()
  1206. for idx in sel_indexes:
  1207. sel_rows.add(idx.row())
  1208. if not sel_rows:
  1209. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. Nothing is selected."))
  1210. return
  1211. self.app.exc_areas.delete_sel_shapes(idxs=list(sel_rows))
  1212. self.app.exc_areas.e_shape_modified.emit()
  1213. def draw_sel_shape(self):
  1214. sel_model = self.ui.exclusion_table.selectionModel()
  1215. sel_indexes = sel_model.selectedIndexes()
  1216. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1217. sel_rows = set()
  1218. for idx in sel_indexes:
  1219. sel_rows.add(idx.row())
  1220. self.delete_sel_shape()
  1221. if self.app.is_legacy is False:
  1222. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  1223. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  1224. else:
  1225. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  1226. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  1227. for row in sel_rows:
  1228. sel_rect = self.app.exc_areas.exclusion_areas_storage[row]['shape']
  1229. self.app.move_tool.sel_shapes.add(sel_rect, color=outline, face_color=face, update=True, layer=0,
  1230. tolerance=None)
  1231. if self.app.is_legacy is True:
  1232. self.app.move_tool.sel_shapes.redraw()
  1233. def clear_selection(self):
  1234. self.app.delete_selection_shape()
  1235. # self.ui.exclusion_table.clearSelection()
  1236. def delete_sel_shape(self):
  1237. self.app.delete_selection_shape()
  1238. def update_exclusion_table(self):
  1239. self.exclusion_area_cb_is_checked = True if self.ui.exclusion_cb.isChecked() else False
  1240. self.build_ui()
  1241. self.ui.exclusion_cb.set_value(self.exclusion_area_cb_is_checked)
  1242. def on_strategy(self, val):
  1243. if val == 'around':
  1244. self.ui.over_z_label.setDisabled(True)
  1245. self.ui.over_z_entry.setDisabled(True)
  1246. else:
  1247. self.ui.over_z_label.setDisabled(False)
  1248. self.ui.over_z_entry.setDisabled(False)
  1249. def exclusion_table_toggle_all(self):
  1250. """
  1251. will toggle the selection of all rows in Exclusion Areas table
  1252. :return:
  1253. """
  1254. sel_model = self.ui.exclusion_table.selectionModel()
  1255. sel_indexes = sel_model.selectedIndexes()
  1256. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1257. sel_rows = set()
  1258. for idx in sel_indexes:
  1259. sel_rows.add(idx.row())
  1260. if sel_rows:
  1261. self.ui.exclusion_table.clearSelection()
  1262. self.delete_sel_shape()
  1263. else:
  1264. self.ui.exclusion_table.selectAll()
  1265. self.draw_sel_shape()
  1266. def reset_fields(self):
  1267. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1268. class DrillingUI:
  1269. toolName = _("Drilling Tool")
  1270. def __init__(self, layout, app):
  1271. self.app = app
  1272. self.decimals = self.app.decimals
  1273. self.layout = layout
  1274. self.tools_frame = QtWidgets.QFrame()
  1275. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  1276. self.layout.addWidget(self.tools_frame)
  1277. self.tools_box = QtWidgets.QVBoxLayout()
  1278. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1279. self.tools_frame.setLayout(self.tools_box)
  1280. self.title_box = QtWidgets.QHBoxLayout()
  1281. self.tools_box.addLayout(self.title_box)
  1282. # ## Title
  1283. title_label = QtWidgets.QLabel("%s" % self.toolName)
  1284. title_label.setStyleSheet("""
  1285. QLabel
  1286. {
  1287. font-size: 16px;
  1288. font-weight: bold;
  1289. }
  1290. """)
  1291. title_label.setToolTip(
  1292. _("Create CNCJob with toolpaths for drilling or milling holes.")
  1293. )
  1294. self.title_box.addWidget(title_label)
  1295. # App Level label
  1296. self.level = QtWidgets.QLabel("")
  1297. self.level.setToolTip(
  1298. _(
  1299. "BASIC is suitable for a beginner. Many parameters\n"
  1300. "are hidden from the user in this mode.\n"
  1301. "ADVANCED mode will make available all parameters.\n\n"
  1302. "To change the application LEVEL, go to:\n"
  1303. "Edit -> Preferences -> General and check:\n"
  1304. "'APP. LEVEL' radio button."
  1305. )
  1306. )
  1307. self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  1308. self.title_box.addWidget(self.level)
  1309. # Grid Layout
  1310. grid0 = QtWidgets.QGridLayout()
  1311. grid0.setColumnStretch(0, 0)
  1312. grid0.setColumnStretch(1, 1)
  1313. self.tools_box.addLayout(grid0)
  1314. self.obj_combo_label = QtWidgets.QLabel('<b>%s</b>:' % _("EXCELLON"))
  1315. self.obj_combo_label.setToolTip(
  1316. _("Excellon object for drilling/milling operation.")
  1317. )
  1318. grid0.addWidget(self.obj_combo_label, 0, 0, 1, 2)
  1319. # ################################################
  1320. # ##### The object to be drilled #################
  1321. # ################################################
  1322. self.object_combo = FCComboBox()
  1323. self.object_combo.setModel(self.app.collection)
  1324. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  1325. # self.object_combo.setCurrentIndex(1)
  1326. self.object_combo.is_last = True
  1327. grid0.addWidget(self.object_combo, 1, 0, 1, 2)
  1328. separator_line = QtWidgets.QFrame()
  1329. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1330. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1331. grid0.addWidget(separator_line, 2, 0, 1, 2)
  1332. # ################################################
  1333. # ########## Excellon Tool Table #################
  1334. # ################################################
  1335. self.tools_table = FCTable(drag_drop=True)
  1336. grid0.addWidget(self.tools_table, 3, 0, 1, 2)
  1337. self.tools_table.setColumnCount(5)
  1338. self.tools_table.setColumnHidden(3, True)
  1339. self.tools_table.setSortingEnabled(False)
  1340. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('Drills'), '', _('Slots')])
  1341. self.tools_table.horizontalHeaderItem(0).setToolTip(
  1342. _("This is the Tool Number.\n"
  1343. "When ToolChange is checked, on toolchange event this value\n"
  1344. "will be showed as a T1, T2 ... Tn in the Machine Code.\n\n"
  1345. "Here the tools are selected for G-code generation."))
  1346. self.tools_table.horizontalHeaderItem(1).setToolTip(
  1347. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  1348. "is the cut width into the material."))
  1349. self.tools_table.horizontalHeaderItem(2).setToolTip(
  1350. _("The number of Drill holes. Holes that are drilled with\n"
  1351. "a drill bit."))
  1352. self.tools_table.horizontalHeaderItem(3).setToolTip(
  1353. _("The number of Slot holes. Holes that are created by\n"
  1354. "milling them with an endmill bit."))
  1355. # Tool order
  1356. self.order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  1357. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  1358. "'No' --> means that the used order is the one in the tool table\n"
  1359. "'Forward' --> means that the tools will be ordered from small to big\n"
  1360. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  1361. "WARNING: using rest machining will automatically set the order\n"
  1362. "in reverse and disable this control."))
  1363. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  1364. {'label': _('Forward'), 'value': 'fwd'},
  1365. {'label': _('Reverse'), 'value': 'rev'}])
  1366. grid0.addWidget(self.order_label, 4, 0)
  1367. grid0.addWidget(self.order_radio, 4, 1)
  1368. separator_line = QtWidgets.QFrame()
  1369. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1370. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1371. grid0.addWidget(separator_line, 5, 0, 1, 2)
  1372. # ###########################################################
  1373. # ############# Create CNC Job ##############################
  1374. # ###########################################################
  1375. self.tool_data_label = QtWidgets.QLabel(
  1376. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  1377. self.tool_data_label.setToolTip(
  1378. _(
  1379. "The data used for creating GCode.\n"
  1380. "Each tool store it's own set of such data."
  1381. )
  1382. )
  1383. grid0.addWidget(self.tool_data_label, 6, 0, 1, 2)
  1384. self.exc_param_frame = QtWidgets.QFrame()
  1385. self.exc_param_frame.setContentsMargins(0, 0, 0, 0)
  1386. grid0.addWidget(self.exc_param_frame, 7, 0, 1, 2)
  1387. self.exc_tools_box = QtWidgets.QVBoxLayout()
  1388. self.exc_tools_box.setContentsMargins(0, 0, 0, 0)
  1389. self.exc_param_frame.setLayout(self.exc_tools_box)
  1390. # #################################################################
  1391. # ################# GRID LAYOUT 3 ###############################
  1392. # #################################################################
  1393. self.grid1 = QtWidgets.QGridLayout()
  1394. self.grid1.setColumnStretch(0, 0)
  1395. self.grid1.setColumnStretch(1, 1)
  1396. self.exc_tools_box.addLayout(self.grid1)
  1397. # Operation Type
  1398. self.operation_label = QtWidgets.QLabel('<b>%s:</b>' % _('Operation'))
  1399. self.operation_label.setToolTip(
  1400. _("Operation type:\n"
  1401. "- Drilling -> will drill the drills/slots associated with this tool\n"
  1402. "- Milling -> will mill the drills/slots")
  1403. )
  1404. self.operation_radio = RadioSet(
  1405. [
  1406. {'label': _('Drilling'), 'value': 'drill'},
  1407. {'label': _("Milling"), 'value': 'mill'}
  1408. ]
  1409. )
  1410. self.operation_radio.setObjectName("e_operation")
  1411. self.grid1.addWidget(self.operation_label, 0, 0)
  1412. self.grid1.addWidget(self.operation_radio, 0, 1)
  1413. # separator_line = QtWidgets.QFrame()
  1414. # separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1415. # separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1416. # self.grid3.addWidget(separator_line, 1, 0, 1, 2)
  1417. self.mill_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  1418. self.mill_type_label.setToolTip(
  1419. _("Milling type:\n"
  1420. "- Drills -> will mill the drills associated with this tool\n"
  1421. "- Slots -> will mill the slots associated with this tool\n"
  1422. "- Both -> will mill both drills and mills or whatever is available")
  1423. )
  1424. self.milling_type_radio = RadioSet(
  1425. [
  1426. {'label': _('Drills'), 'value': 'drills'},
  1427. {'label': _("Slots"), 'value': 'slots'},
  1428. {'label': _("Both"), 'value': 'both'},
  1429. ]
  1430. )
  1431. self.milling_type_radio.setObjectName("e_milling_type")
  1432. self.grid1.addWidget(self.mill_type_label, 2, 0)
  1433. self.grid1.addWidget(self.milling_type_radio, 2, 1)
  1434. self.mill_dia_label = QtWidgets.QLabel('%s:' % _('Milling Diameter'))
  1435. self.mill_dia_label.setToolTip(
  1436. _("The diameter of the tool who will do the milling")
  1437. )
  1438. self.mill_dia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1439. self.mill_dia_entry.set_precision(self.decimals)
  1440. self.mill_dia_entry.set_range(0.0000, 9999.9999)
  1441. self.mill_dia_entry.setObjectName("e_milling_dia")
  1442. self.grid1.addWidget(self.mill_dia_label, 3, 0)
  1443. self.grid1.addWidget(self.mill_dia_entry, 3, 1)
  1444. # Cut Z
  1445. self.cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  1446. self.cutzlabel.setToolTip(
  1447. _("Drill depth (negative)\n"
  1448. "below the copper surface.")
  1449. )
  1450. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1451. self.cutz_entry.set_precision(self.decimals)
  1452. if machinist_setting == 0:
  1453. self.cutz_entry.set_range(-9999.9999, 0.0000)
  1454. else:
  1455. self.cutz_entry.set_range(-9999.9999, 9999.9999)
  1456. self.cutz_entry.setSingleStep(0.1)
  1457. self.cutz_entry.setObjectName("e_cutz")
  1458. self.grid1.addWidget(self.cutzlabel, 4, 0)
  1459. self.grid1.addWidget(self.cutz_entry, 4, 1)
  1460. # Multi-Depth
  1461. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  1462. self.mpass_cb.setToolTip(
  1463. _(
  1464. "Use multiple passes to limit\n"
  1465. "the cut depth in each pass. Will\n"
  1466. "cut multiple times until Cut Z is\n"
  1467. "reached."
  1468. )
  1469. )
  1470. self.mpass_cb.setObjectName("e_multidepth")
  1471. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1472. self.maxdepth_entry.set_precision(self.decimals)
  1473. self.maxdepth_entry.set_range(0, 9999.9999)
  1474. self.maxdepth_entry.setSingleStep(0.1)
  1475. self.maxdepth_entry.setToolTip(_("Depth of each pass (positive)."))
  1476. self.maxdepth_entry.setObjectName("e_depthperpass")
  1477. self.mis_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  1478. self.grid1.addWidget(self.mpass_cb, 5, 0)
  1479. self.grid1.addWidget(self.maxdepth_entry, 5, 1)
  1480. # Travel Z (z_move)
  1481. self.travelzlabel = QtWidgets.QLabel('%s:' % _('Travel Z'))
  1482. self.travelzlabel.setToolTip(
  1483. _("Tool height when travelling\n"
  1484. "across the XY plane.")
  1485. )
  1486. self.travelz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1487. self.travelz_entry.set_precision(self.decimals)
  1488. if machinist_setting == 0:
  1489. self.travelz_entry.set_range(0.00001, 9999.9999)
  1490. else:
  1491. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  1492. self.travelz_entry.setSingleStep(0.1)
  1493. self.travelz_entry.setObjectName("e_travelz")
  1494. self.grid1.addWidget(self.travelzlabel, 6, 0)
  1495. self.grid1.addWidget(self.travelz_entry, 6, 1)
  1496. # Feedrate X-Y
  1497. self.frxylabel = QtWidgets.QLabel('%s:' % _('Feedrate X-Y'))
  1498. self.frxylabel.setToolTip(
  1499. _("Cutting speed in the XY\n"
  1500. "plane in units per minute")
  1501. )
  1502. self.xyfeedrate_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1503. self.xyfeedrate_entry.set_precision(self.decimals)
  1504. self.xyfeedrate_entry.set_range(0, 9999.9999)
  1505. self.xyfeedrate_entry.setSingleStep(0.1)
  1506. self.xyfeedrate_entry.setObjectName("e_feedratexy")
  1507. self.grid1.addWidget(self.frxylabel, 12, 0)
  1508. self.grid1.addWidget(self.xyfeedrate_entry, 12, 1)
  1509. # Excellon Feedrate Z
  1510. self.frzlabel = QtWidgets.QLabel('%s:' % _('Feedrate Z'))
  1511. self.frzlabel.setToolTip(
  1512. _("Tool speed while drilling\n"
  1513. "(in units per minute).\n"
  1514. "So called 'Plunge' feedrate.\n"
  1515. "This is for linear move G01.")
  1516. )
  1517. self.feedrate_z_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1518. self.feedrate_z_entry.set_precision(self.decimals)
  1519. self.feedrate_z_entry.set_range(0.0, 99999.9999)
  1520. self.feedrate_z_entry.setSingleStep(0.1)
  1521. self.feedrate_z_entry.setObjectName("e_feedratez")
  1522. self.grid1.addWidget(self.frzlabel, 14, 0)
  1523. self.grid1.addWidget(self.feedrate_z_entry, 14, 1)
  1524. # Excellon Rapid Feedrate
  1525. self.feedrate_rapid_label = QtWidgets.QLabel('%s:' % _('Feedrate Rapids'))
  1526. self.feedrate_rapid_label.setToolTip(
  1527. _("Tool speed while drilling\n"
  1528. "(in units per minute).\n"
  1529. "This is for the rapid move G00.\n"
  1530. "It is useful only for Marlin,\n"
  1531. "ignore for any other cases.")
  1532. )
  1533. self.feedrate_rapid_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1534. self.feedrate_rapid_entry.set_precision(self.decimals)
  1535. self.feedrate_rapid_entry.set_range(0.0, 99999.9999)
  1536. self.feedrate_rapid_entry.setSingleStep(0.1)
  1537. self.feedrate_rapid_entry.setObjectName("e_fr_rapid")
  1538. self.grid1.addWidget(self.feedrate_rapid_label, 16, 0)
  1539. self.grid1.addWidget(self.feedrate_rapid_entry, 16, 1)
  1540. # default values is to hide
  1541. self.feedrate_rapid_label.hide()
  1542. self.feedrate_rapid_entry.hide()
  1543. # Cut over 1st point in path
  1544. self.extracut_cb = FCCheckBox('%s:' % _('Re-cut'))
  1545. self.extracut_cb.setToolTip(
  1546. _("In order to remove possible\n"
  1547. "copper leftovers where first cut\n"
  1548. "meet with last cut, we generate an\n"
  1549. "extended cut over the first cut section.")
  1550. )
  1551. self.extracut_cb.setObjectName("e_extracut")
  1552. self.e_cut_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1553. self.e_cut_entry.set_range(0, 99999)
  1554. self.e_cut_entry.set_precision(self.decimals)
  1555. self.e_cut_entry.setSingleStep(0.1)
  1556. self.e_cut_entry.setWrapping(True)
  1557. self.e_cut_entry.setToolTip(
  1558. _("In order to remove possible\n"
  1559. "copper leftovers where first cut\n"
  1560. "meet with last cut, we generate an\n"
  1561. "extended cut over the first cut section.")
  1562. )
  1563. self.e_cut_entry.setObjectName("e_extracut_length")
  1564. self.ois_recut = OptionalInputSection(self.extracut_cb, [self.e_cut_entry])
  1565. self.grid1.addWidget(self.extracut_cb, 17, 0)
  1566. self.grid1.addWidget(self.e_cut_entry, 17, 1)
  1567. # Spindlespeed
  1568. self.spindle_label = QtWidgets.QLabel('%s:' % _('Spindle speed'))
  1569. self.spindle_label.setToolTip(
  1570. _("Speed of the spindle\n"
  1571. "in RPM (optional)")
  1572. )
  1573. self.spindlespeed_entry = FCSpinner(callback=self.confirmation_message_int)
  1574. self.spindlespeed_entry.set_range(0, 1000000)
  1575. self.spindlespeed_entry.set_step(100)
  1576. self.spindlespeed_entry.setObjectName("e_spindlespeed")
  1577. self.grid1.addWidget(self.spindle_label, 19, 0)
  1578. self.grid1.addWidget(self.spindlespeed_entry, 19, 1)
  1579. # Dwell
  1580. self.dwell_cb = FCCheckBox('%s:' % _('Dwell'))
  1581. self.dwell_cb.setToolTip(
  1582. _("Pause to allow the spindle to reach its\n"
  1583. "speed before cutting.")
  1584. )
  1585. self.dwell_cb.setObjectName("e_dwell")
  1586. self.dwelltime_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1587. self.dwelltime_entry.set_precision(self.decimals)
  1588. self.dwelltime_entry.set_range(0.0, 9999.9999)
  1589. self.dwelltime_entry.setSingleStep(0.1)
  1590. self.dwelltime_entry.setToolTip(
  1591. _("Number of time units for spindle to dwell.")
  1592. )
  1593. self.dwelltime_entry.setObjectName("e_dwelltime")
  1594. self.grid1.addWidget(self.dwell_cb, 20, 0)
  1595. self.grid1.addWidget(self.dwelltime_entry, 20, 1)
  1596. self.ois_dwell = OptionalInputSection(self.dwell_cb, [self.dwelltime_entry])
  1597. # Tool Offset
  1598. self.tool_offset_label = QtWidgets.QLabel('%s:' % _('Offset Z'))
  1599. self.tool_offset_label.setToolTip(
  1600. _("Some drill bits (the larger ones) need to drill deeper\n"
  1601. "to create the desired exit hole diameter due of the tip shape.\n"
  1602. "The value here can compensate the Cut Z parameter.")
  1603. )
  1604. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1605. self.offset_entry.set_precision(self.decimals)
  1606. self.offset_entry.set_range(-9999.9999, 9999.9999)
  1607. self.offset_entry.setObjectName("e_offset")
  1608. self.grid1.addWidget(self.tool_offset_label, 25, 0)
  1609. self.grid1.addWidget(self.offset_entry, 25, 1)
  1610. # #################################################################
  1611. # ################# GRID LAYOUT 4 ###############################
  1612. # #################################################################
  1613. # self.grid4 = QtWidgets.QGridLayout()
  1614. # self.exc_tools_box.addLayout(self.grid4)
  1615. # self.grid4.setColumnStretch(0, 0)
  1616. # self.grid4.setColumnStretch(1, 1)
  1617. #
  1618. # # choose_tools_label = QtWidgets.QLabel(
  1619. # # _("Select from the Tools Table above the hole dias to be\n"
  1620. # # "drilled. Use the # column to make the selection.")
  1621. # # )
  1622. # # grid2.addWidget(choose_tools_label, 0, 0, 1, 3)
  1623. #
  1624. # # ### Choose what to use for Gcode creation: Drills, Slots or Both
  1625. # gcode_type_label = QtWidgets.QLabel('<b>%s</b>' % _('Gcode'))
  1626. # gcode_type_label.setToolTip(
  1627. # _("Choose what to use for GCode generation:\n"
  1628. # "'Drills', 'Slots' or 'Both'.\n"
  1629. # "When choosing 'Slots' or 'Both', slots will be\n"
  1630. # "converted to a series of drills.")
  1631. # )
  1632. # self.excellon_gcode_type_radio = RadioSet([{'label': 'Drills', 'value': 'drills'},
  1633. # {'label': 'Slots', 'value': 'slots'},
  1634. # {'label': 'Both', 'value': 'both'}])
  1635. # self.grid4.addWidget(gcode_type_label, 1, 0)
  1636. # self.grid4.addWidget(self.excellon_gcode_type_radio, 1, 1)
  1637. # # temporary action until I finish the feature
  1638. # self.excellon_gcode_type_radio.setVisible(False)
  1639. # gcode_type_label.hide()
  1640. # #################################################################
  1641. # ################# GRID LAYOUT 5 ###############################
  1642. # #################################################################
  1643. # ################# COMMON PARAMETERS #############################
  1644. self.grid3 = QtWidgets.QGridLayout()
  1645. self.grid3.setColumnStretch(0, 0)
  1646. self.grid3.setColumnStretch(1, 1)
  1647. self.exc_tools_box.addLayout(self.grid3)
  1648. separator_line2 = QtWidgets.QFrame()
  1649. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  1650. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  1651. self.grid3.addWidget(separator_line2, 0, 0, 1, 2)
  1652. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  1653. self.apply_param_to_all.setToolTip(
  1654. _("The parameters in the current form will be applied\n"
  1655. "on all the tools from the Tool Table.")
  1656. )
  1657. self.grid3.addWidget(self.apply_param_to_all, 1, 0, 1, 2)
  1658. separator_line2 = QtWidgets.QFrame()
  1659. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  1660. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  1661. self.grid3.addWidget(separator_line2, 2, 0, 1, 2)
  1662. # General Parameters
  1663. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  1664. self.gen_param_label.setToolTip(
  1665. _("Parameters that are common for all tools.")
  1666. )
  1667. self.grid3.addWidget(self.gen_param_label, 3, 0, 1, 2)
  1668. # Tool change Z:
  1669. self.toolchange_cb = FCCheckBox('%s:' % _("Tool change Z"))
  1670. self.toolchange_cb.setToolTip(
  1671. _("Include tool-change sequence\n"
  1672. "in G-Code (Pause for tool change).")
  1673. )
  1674. self.toolchangez_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1675. self.toolchangez_entry.set_precision(self.decimals)
  1676. self.toolchangez_entry.setToolTip(
  1677. _("Z-axis position (height) for\n"
  1678. "tool change.")
  1679. )
  1680. if machinist_setting == 0:
  1681. self.toolchangez_entry.set_range(0.0, 9999.9999)
  1682. else:
  1683. self.toolchangez_entry.set_range(-9999.9999, 9999.9999)
  1684. self.toolchangez_entry.setSingleStep(0.1)
  1685. self.ois_tcz_e = OptionalInputSection(self.toolchange_cb, [self.toolchangez_entry])
  1686. self.grid3.addWidget(self.toolchange_cb, 8, 0)
  1687. self.grid3.addWidget(self.toolchangez_entry, 8, 1)
  1688. # Start move Z:
  1689. self.estartz_label = QtWidgets.QLabel('%s:' % _("Start Z"))
  1690. self.estartz_label.setToolTip(
  1691. _("Height of the tool just after start.\n"
  1692. "Delete the value if you don't need this feature.")
  1693. )
  1694. self.estartz_entry = NumericalEvalEntry(border_color='#0069A9')
  1695. self.grid3.addWidget(self.estartz_label, 9, 0)
  1696. self.grid3.addWidget(self.estartz_entry, 9, 1)
  1697. # End move Z:
  1698. self.endz_label = QtWidgets.QLabel('%s:' % _("End move Z"))
  1699. self.endz_label.setToolTip(
  1700. _("Height of the tool after\n"
  1701. "the last move at the end of the job.")
  1702. )
  1703. self.endz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1704. self.endz_entry.set_precision(self.decimals)
  1705. if machinist_setting == 0:
  1706. self.endz_entry.set_range(0.0, 9999.9999)
  1707. else:
  1708. self.endz_entry.set_range(-9999.9999, 9999.9999)
  1709. self.endz_entry.setSingleStep(0.1)
  1710. self.grid3.addWidget(self.endz_label, 11, 0)
  1711. self.grid3.addWidget(self.endz_entry, 11, 1)
  1712. # End Move X,Y
  1713. endmove_xy_label = QtWidgets.QLabel('%s:' % _('End move X,Y'))
  1714. endmove_xy_label.setToolTip(
  1715. _("End move X,Y position. In format (x,y).\n"
  1716. "If no value is entered then there is no move\n"
  1717. "on X,Y plane at the end of the job.")
  1718. )
  1719. self.endxy_entry = NumericalEvalEntry(border_color='#0069A9')
  1720. self.endxy_entry.setPlaceholderText(_("X,Y coordinates"))
  1721. self.grid3.addWidget(endmove_xy_label, 12, 0)
  1722. self.grid3.addWidget(self.endxy_entry, 12, 1)
  1723. # Probe depth
  1724. self.pdepth_label = QtWidgets.QLabel('%s:' % _("Probe Z depth"))
  1725. self.pdepth_label.setToolTip(
  1726. _("The maximum depth that the probe is allowed\n"
  1727. "to probe. Negative value, in current units.")
  1728. )
  1729. self.pdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1730. self.pdepth_entry.set_precision(self.decimals)
  1731. self.pdepth_entry.set_range(-9999.9999, 9999.9999)
  1732. self.pdepth_entry.setSingleStep(0.1)
  1733. self.pdepth_entry.setObjectName("e_depth_probe")
  1734. self.grid3.addWidget(self.pdepth_label, 13, 0)
  1735. self.grid3.addWidget(self.pdepth_entry, 13, 1)
  1736. self.pdepth_label.hide()
  1737. self.pdepth_entry.setVisible(False)
  1738. # Probe feedrate
  1739. self.feedrate_probe_label = QtWidgets.QLabel('%s:' % _("Feedrate Probe"))
  1740. self.feedrate_probe_label.setToolTip(
  1741. _("The feedrate used while the probe is probing.")
  1742. )
  1743. self.feedrate_probe_entry = FCDoubleSpinner(callback=self.confirmation_message)
  1744. self.feedrate_probe_entry.set_precision(self.decimals)
  1745. self.feedrate_probe_entry.set_range(0.0, 9999.9999)
  1746. self.feedrate_probe_entry.setSingleStep(0.1)
  1747. self.feedrate_probe_entry.setObjectName("e_fr_probe")
  1748. self.grid3.addWidget(self.feedrate_probe_label, 14, 0)
  1749. self.grid3.addWidget(self.feedrate_probe_entry, 14, 1)
  1750. self.feedrate_probe_label.hide()
  1751. self.feedrate_probe_entry.setVisible(False)
  1752. # Preprocessor Excellon selection
  1753. pp_excellon_label = QtWidgets.QLabel('%s:' % _("Preprocessor E"))
  1754. pp_excellon_label.setToolTip(
  1755. _("The preprocessor JSON file that dictates\n"
  1756. "Gcode output for Excellon Objects.")
  1757. )
  1758. self.pp_excellon_name_cb = FCComboBox()
  1759. self.pp_excellon_name_cb.setFocusPolicy(QtCore.Qt.StrongFocus)
  1760. self.grid3.addWidget(pp_excellon_label, 15, 0)
  1761. self.grid3.addWidget(self.pp_excellon_name_cb, 15, 1)
  1762. # Preprocessor Geometry selection
  1763. pp_geo_label = QtWidgets.QLabel('%s:' % _("Preprocessor G"))
  1764. pp_geo_label.setToolTip(
  1765. _("The preprocessor JSON file that dictates\n"
  1766. "Gcode output for Geometry (Milling) Objects.")
  1767. )
  1768. self.pp_geo_name_cb = FCComboBox()
  1769. self.pp_geo_name_cb.setFocusPolicy(QtCore.Qt.StrongFocus)
  1770. self.grid3.addWidget(pp_geo_label, 16, 0)
  1771. self.grid3.addWidget(self.pp_geo_name_cb, 16, 1)
  1772. # ------------------------------------------------------------------------------------------------------------
  1773. # ------------------------- EXCLUSION AREAS ------------------------------------------------------------------
  1774. # ------------------------------------------------------------------------------------------------------------
  1775. # Exclusion Areas
  1776. self.exclusion_cb = FCCheckBox('%s' % _("Add exclusion areas"))
  1777. self.exclusion_cb.setToolTip(
  1778. _(
  1779. "Include exclusion areas.\n"
  1780. "In those areas the travel of the tools\n"
  1781. "is forbidden."
  1782. )
  1783. )
  1784. self.grid3.addWidget(self.exclusion_cb, 20, 0, 1, 2)
  1785. self.exclusion_frame = QtWidgets.QFrame()
  1786. self.exclusion_frame.setContentsMargins(0, 0, 0, 0)
  1787. self.grid3.addWidget(self.exclusion_frame, 22, 0, 1, 2)
  1788. self.exclusion_box = QtWidgets.QVBoxLayout()
  1789. self.exclusion_box.setContentsMargins(0, 0, 0, 0)
  1790. self.exclusion_frame.setLayout(self.exclusion_box)
  1791. self.exclusion_table = FCTable()
  1792. self.exclusion_box.addWidget(self.exclusion_table)
  1793. self.exclusion_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  1794. self.exclusion_table.setColumnCount(4)
  1795. self.exclusion_table.setColumnWidth(0, 20)
  1796. self.exclusion_table.setHorizontalHeaderLabels(['#', _('Object'), _('Strategy'), _('Over Z')])
  1797. self.exclusion_table.horizontalHeaderItem(0).setToolTip(_("This is the Area ID."))
  1798. self.exclusion_table.horizontalHeaderItem(1).setToolTip(
  1799. _("Type of the object where the exclusion area was added."))
  1800. self.exclusion_table.horizontalHeaderItem(2).setToolTip(
  1801. _("The strategy used for exclusion area. Go around the exclusion areas or over it."))
  1802. self.exclusion_table.horizontalHeaderItem(3).setToolTip(
  1803. _("If the strategy is to go over the area then this is the height at which the tool will go to avoid the "
  1804. "exclusion area."))
  1805. self.exclusion_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1806. grid_a1 = QtWidgets.QGridLayout()
  1807. grid_a1.setColumnStretch(0, 0)
  1808. grid_a1.setColumnStretch(1, 1)
  1809. self.exclusion_box.addLayout(grid_a1)
  1810. # Chose Strategy
  1811. self.strategy_label = FCLabel('%s:' % _("Strategy"))
  1812. self.strategy_label.setToolTip(_("The strategy followed when encountering an exclusion area.\n"
  1813. "Can be:\n"
  1814. "- Over -> when encountering the area, the tool will go to a set height\n"
  1815. "- Around -> will avoid the exclusion area by going around the area"))
  1816. self.strategy_radio = RadioSet([{'label': _('Over'), 'value': 'over'},
  1817. {'label': _('Around'), 'value': 'around'}])
  1818. grid_a1.addWidget(self.strategy_label, 1, 0)
  1819. grid_a1.addWidget(self.strategy_radio, 1, 1)
  1820. # Over Z
  1821. self.over_z_label = FCLabel('%s:' % _("Over Z"))
  1822. self.over_z_label.setToolTip(_("The height Z to which the tool will rise in order to avoid\n"
  1823. "an interdiction area."))
  1824. self.over_z_entry = FCDoubleSpinner()
  1825. self.over_z_entry.set_range(0.000, 9999.9999)
  1826. self.over_z_entry.set_precision(self.decimals)
  1827. grid_a1.addWidget(self.over_z_label, 2, 0)
  1828. grid_a1.addWidget(self.over_z_entry, 2, 1)
  1829. # Button Add Area
  1830. self.add_area_button = QtWidgets.QPushButton(_('Add area:'))
  1831. self.add_area_button.setToolTip(_("Add an Exclusion Area."))
  1832. # Area Selection shape
  1833. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  1834. {'label': _("Polygon"), 'value': 'polygon'}])
  1835. self.area_shape_radio.setToolTip(
  1836. _("The kind of selection shape used for area selection.")
  1837. )
  1838. grid_a1.addWidget(self.add_area_button, 4, 0)
  1839. grid_a1.addWidget(self.area_shape_radio, 4, 1)
  1840. h_lay_1 = QtWidgets.QHBoxLayout()
  1841. self.exclusion_box.addLayout(h_lay_1)
  1842. # Button Delete All Areas
  1843. self.delete_area_button = QtWidgets.QPushButton(_('Delete All'))
  1844. self.delete_area_button.setToolTip(_("Delete all exclusion areas."))
  1845. # Button Delete Selected Areas
  1846. self.delete_sel_area_button = QtWidgets.QPushButton(_('Delete Selected'))
  1847. self.delete_sel_area_button.setToolTip(_("Delete all exclusion areas that are selected in the table."))
  1848. h_lay_1.addWidget(self.delete_area_button)
  1849. h_lay_1.addWidget(self.delete_sel_area_button)
  1850. self.ois_exclusion_exc = OptionalHideInputSection(self.exclusion_cb, [self.exclusion_frame])
  1851. # -------------------------- EXCLUSION AREAS END -------------------------------------------------------------
  1852. # ------------------------------------------------------------------------------------------------------------
  1853. separator_line = QtWidgets.QFrame()
  1854. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  1855. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  1856. self.grid3.addWidget(separator_line, 25, 0, 1, 2)
  1857. # #################################################################
  1858. # ################# GRID LAYOUT 6 ###############################
  1859. # #################################################################
  1860. self.grid4 = QtWidgets.QGridLayout()
  1861. self.grid4.setColumnStretch(0, 0)
  1862. self.grid4.setColumnStretch(1, 1)
  1863. self.tools_box.addLayout(self.grid4)
  1864. self.generate_cnc_button = QtWidgets.QPushButton(_('Generate CNCJob object'))
  1865. self.generate_cnc_button.setToolTip(
  1866. _("Generate the CNC Job.\n"
  1867. "If milling then an additional Geometry object will be created.\n"
  1868. "Add / Select at least one tool in the tool-table.\n"
  1869. "Click the # header to select all, or Ctrl + LMB\n"
  1870. "for custom selection of tools.")
  1871. )
  1872. self.generate_cnc_button.setStyleSheet("""
  1873. QPushButton
  1874. {
  1875. font-weight: bold;
  1876. }
  1877. """)
  1878. self.grid4.addWidget(self.generate_cnc_button, 3, 0, 1, 3)
  1879. self.tools_box.addStretch()
  1880. # ## Reset Tool
  1881. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  1882. self.reset_button.setToolTip(
  1883. _("Will reset the tool parameters.")
  1884. )
  1885. self.reset_button.setStyleSheet("""
  1886. QPushButton
  1887. {
  1888. font-weight: bold;
  1889. }
  1890. """)
  1891. self.tools_box.addWidget(self.reset_button)
  1892. # ############################ FINSIHED GUI ###################################
  1893. # #############################################################################
  1894. def confirmation_message(self, accepted, minval, maxval):
  1895. if accepted is False:
  1896. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  1897. self.decimals,
  1898. minval,
  1899. self.decimals,
  1900. maxval), False)
  1901. else:
  1902. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  1903. def confirmation_message_int(self, accepted, minval, maxval):
  1904. if accepted is False:
  1905. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  1906. (_("Edited value is out of range"), minval, maxval), False)
  1907. else:
  1908. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)