ToolMilling.py 95 KB

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