ToolDrilling.py 95 KB

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