ToolDrilling.py 95 KB

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