FlatCAMExcellon.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Point, LineString
  12. from copy import deepcopy
  13. from appParsers.ParseExcellon import Excellon
  14. from appObjects.FlatCAMObj import *
  15. import itertools
  16. import numpy as np
  17. from collections import defaultdict
  18. import gettext
  19. import appTranslation as fcTranslate
  20. import builtins
  21. fcTranslate.apply_language('strings')
  22. if '_' not in builtins.__dict__:
  23. _ = gettext.gettext
  24. class ExcellonObject(FlatCAMObj, Excellon):
  25. """
  26. Represents Excellon/Drill code. An object stored in the FlatCAM objects collection (a dict)
  27. """
  28. ui_type = ExcellonObjectUI
  29. optionChanged = QtCore.pyqtSignal(str)
  30. def __init__(self, name):
  31. self.decimals = self.app.decimals
  32. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  33. Excellon.__init__(self, geo_steps_per_circle=self.circle_steps)
  34. FlatCAMObj.__init__(self, name)
  35. self.kind = "excellon"
  36. self.options.update({
  37. "plot": True,
  38. "solid": False,
  39. "multicolored": False,
  40. "merge_fuse_tools": True,
  41. "tooldia": 0.1,
  42. "milling_dia": 0.04,
  43. "slot_tooldia": 0.1,
  44. "format_upper_in": 2,
  45. "format_lower_in": 4,
  46. "format_upper_mm": 3,
  47. "lower_mm": 3,
  48. "zeros": "T",
  49. "units": "INCH",
  50. "update": True,
  51. "optimization_type": "B",
  52. "search_time": 3
  53. })
  54. # TODO: Document this.
  55. self.tool_cbs = {}
  56. # dict that holds the object names and the option name
  57. # the key is the object name (defines in ObjectUI) for each UI element that is a parameter
  58. # particular for a tool and the value is the actual name of the option that the UI element is changing
  59. self.name2option = {}
  60. # default set of data to be added to each tool in self.tools as self.tools[tool]['data'] = self.default_data
  61. self.default_data = {}
  62. # variable to store the total amount of drills per job
  63. self.tot_drill_cnt = 0
  64. self.tool_row = 0
  65. # variable to store the total amount of slots per job
  66. self.tot_slot_cnt = 0
  67. self.tool_row_slots = 0
  68. # variable to store the distance travelled
  69. self.travel_distance = 0.0
  70. # store the source file here
  71. self.source_file = ""
  72. self.multigeo = False
  73. self.units_found = self.app.defaults['units']
  74. self.fill_color = self.app.defaults['excellon_plot_fill']
  75. self.outline_color = self.app.defaults['excellon_plot_line']
  76. self.alpha_level = 'bf'
  77. # Attributes to be included in serialization
  78. # Always append to it because it carries contents
  79. # from predecessors.
  80. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  81. def set_ui(self, ui):
  82. """
  83. Configures the user interface for this object.
  84. Connects options to form fields.
  85. :param ui: User interface object.
  86. :type ui: ExcellonObjectUI
  87. :return: None
  88. """
  89. FlatCAMObj.set_ui(self, ui)
  90. log.debug("ExcellonObject.set_ui()")
  91. self.units = self.app.defaults['units'].upper()
  92. # fill in self.options values for the Drilling Tool from self.app.options
  93. for opt_key, opt_val in self.app.options.items():
  94. if opt_key.find('tools_drill_') == 0:
  95. self.options[opt_key] = deepcopy(opt_val)
  96. # fill in self.default_data values from self.options
  97. for opt_key, opt_val in self.app.options.items():
  98. if opt_key.find('excellon_') == 0 or opt_key.find('tools_drill_') == 0:
  99. self.default_data[opt_key] = deepcopy(opt_val)
  100. self.form_fields.update({
  101. "plot": self.ui.plot_cb,
  102. "solid": self.ui.solid_cb,
  103. "multicolored": self.ui.multicolored_cb,
  104. "autoload_db": self.ui.autoload_db_cb,
  105. "tooldia": self.ui.tooldia_entry,
  106. "slot_tooldia": self.ui.slot_tooldia_entry,
  107. })
  108. self.to_form()
  109. # Show/Hide Advanced Options
  110. if self.app.defaults["global_app_level"] == 'b':
  111. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  112. self.ui.tools_table.setColumnHidden(4, True)
  113. self.ui.tools_table.setColumnHidden(5, True)
  114. self.ui.table_visibility_cb.set_value(True)
  115. self.ui.table_visibility_cb.hide()
  116. self.ui.autoload_db_cb.set_value(False)
  117. self.ui.autoload_db_cb.hide()
  118. else:
  119. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  120. self.ui.table_visibility_cb.show()
  121. self.ui.table_visibility_cb.set_value(self.app.defaults["excellon_tools_table_display"])
  122. self.on_table_visibility_toggle(state=self.app.defaults["excellon_tools_table_display"])
  123. self.ui.autoload_db_cb.show()
  124. assert isinstance(self.ui, ExcellonObjectUI), \
  125. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  126. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  127. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  128. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  129. self.ui.autoload_db_cb.stateChanged.connect(self.on_autoload_db_toggled)
  130. # Editor
  131. self.ui.editor_button.clicked.connect(lambda: self.app.object2editor())
  132. self.ui.drill_button.clicked.connect(lambda: self.app.drilling_tool.run(toggle=True))
  133. # self.ui.milling_button.clicked.connect(lambda: self.app.milling_tool.run(toggle=True))
  134. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  135. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  136. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_rows)
  137. self.ui.table_visibility_cb.stateChanged.connect(self.on_table_visibility_toggle)
  138. self.units_found = self.app.defaults['units']
  139. def build_ui(self):
  140. """
  141. Will (re)build the Excellon UI updating it (the tool table)
  142. :return: None
  143. :rtype:
  144. """
  145. FlatCAMObj.build_ui(self)
  146. self.units = self.app.defaults['units'].upper()
  147. for row in range(self.ui.tools_table.rowCount()):
  148. try:
  149. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  150. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  151. offset_spin_widget.valueChanged.disconnect()
  152. except (TypeError, AttributeError):
  153. pass
  154. n = len(self.tools)
  155. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  156. self.ui.tools_table.setRowCount(n + 2)
  157. self.tot_drill_cnt = 0
  158. self.tot_slot_cnt = 0
  159. self.tool_row = 0
  160. sort = []
  161. for k, v in list(self.tools.items()):
  162. try:
  163. sort.append((k, v['tooldia']))
  164. except KeyError:
  165. # for old projects to be opened
  166. sort.append((k, v['C']))
  167. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  168. tools = [i[0] for i in sorted_tools]
  169. new_options = {}
  170. for opt in self.options:
  171. new_options[opt] = self.options[opt]
  172. for tool_no in tools:
  173. try:
  174. dia_val = self.tools[tool_no]['tooldia']
  175. except KeyError:
  176. # for old projects to be opened
  177. dia_val = self.tools[tool_no]['C']
  178. # add the data dictionary for each tool with the default values
  179. self.tools[tool_no]['data'] = deepcopy(new_options)
  180. drill_cnt = 0 # variable to store the nr of drills per tool
  181. slot_cnt = 0 # variable to store the nr of slots per tool
  182. # Find no of drills for the current tool
  183. try:
  184. drill_cnt = len(self.tools[tool_no]['drills'])
  185. except KeyError:
  186. drill_cnt = 0
  187. self.tot_drill_cnt += drill_cnt
  188. # Find no of slots for the current tool
  189. try:
  190. slot_cnt = len(self.tools[tool_no]['slots'])
  191. except KeyError:
  192. slot_cnt = 0
  193. self.tot_slot_cnt += slot_cnt
  194. # Tool ID
  195. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  196. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  197. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item) # Tool name/id
  198. # Diameter
  199. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, dia_val))
  200. dia_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  201. self.ui.tools_table.setItem(self.tool_row, 1, dia_item) # Diameter
  202. # Drill count
  203. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  204. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  205. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item) # Number of drills per tool
  206. # Slot Count
  207. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  208. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  209. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  210. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  211. self.ui.tools_table.setItem(self.tool_row, 3, slot_count_item) # Number of drills per tool
  212. # Empty Plot Item
  213. empty_plot_item = QtWidgets.QTableWidgetItem('')
  214. empty_plot_item.setFlags(QtCore.Qt.ItemIsEnabled)
  215. self.ui.tools_table.setItem(self.tool_row, 5, empty_plot_item)
  216. # Plot Item
  217. plot_item = FCCheckBox()
  218. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  219. if self.ui.plot_cb.isChecked():
  220. plot_item.setChecked(True)
  221. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  222. self.tool_row += 1
  223. # add a last row with the Total number of drills
  224. empty_1 = QtWidgets.QTableWidgetItem('')
  225. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  226. empty_1_1 = QtWidgets.QTableWidgetItem('')
  227. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  228. empty_1_2 = QtWidgets.QTableWidgetItem('')
  229. empty_1_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  230. empty_1_3 = QtWidgets.QTableWidgetItem('')
  231. empty_1_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  232. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  233. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  234. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  235. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  236. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  237. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  238. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  239. self.ui.tools_table.setItem(self.tool_row, 3, empty_1_1)
  240. self.ui.tools_table.setItem(self.tool_row, 5, empty_1_3)
  241. font = QtGui.QFont()
  242. font.setBold(True)
  243. font.setWeight(75)
  244. for k in [1, 2]:
  245. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  246. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  247. self.tool_row += 1
  248. # add a last row with the Total number of slots
  249. empty_2 = QtWidgets.QTableWidgetItem('')
  250. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  251. empty_2_1 = QtWidgets.QTableWidgetItem('')
  252. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  253. empty_2_2 = QtWidgets.QTableWidgetItem('')
  254. empty_2_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  255. empty_2_3 = QtWidgets.QTableWidgetItem('')
  256. empty_2_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  257. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  258. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  259. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  260. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  261. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  262. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  263. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  264. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  265. self.ui.tools_table.setItem(self.tool_row, 5, empty_2_3)
  266. for kl in [1, 2, 3]:
  267. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  268. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  269. # sort the tool diameter column
  270. # self.ui.tools_table.sortItems(1)
  271. # all the tools are selected by default
  272. self.ui.tools_table.selectColumn(0)
  273. self.ui.tools_table.resizeColumnsToContents()
  274. self.ui.tools_table.resizeRowsToContents()
  275. vertical_header = self.ui.tools_table.verticalHeader()
  276. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  277. vertical_header.hide()
  278. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  279. horizontal_header = self.ui.tools_table.horizontalHeader()
  280. horizontal_header.setMinimumSectionSize(10)
  281. horizontal_header.setDefaultSectionSize(70)
  282. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  283. horizontal_header.resizeSection(0, 20)
  284. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  285. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  286. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  287. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  288. horizontal_header.resizeSection(5, 17)
  289. self.ui.tools_table.setColumnWidth(5, 17)
  290. # horizontal_header.setStretchLastSection(True)
  291. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  292. # horizontal_header.setStretchLastSection(True)
  293. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  294. self.ui.tools_table.setSortingEnabled(False)
  295. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  296. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  297. # find if we have drills:
  298. has_drills = None
  299. for tt in self.tools:
  300. if 'drills' in self.tools[tt] and self.tools[tt]['drills']:
  301. has_drills = True
  302. break
  303. if has_drills is None:
  304. self.ui.tooldia_entry.setDisabled(True)
  305. self.ui.generate_milling_button.setDisabled(True)
  306. else:
  307. self.ui.tooldia_entry.setDisabled(False)
  308. self.ui.generate_milling_button.setDisabled(False)
  309. # find if we have slots
  310. has_slots = None
  311. for tt in self.tools:
  312. if 'slots' in self.tools[tt] and self.tools[tt]['slots']:
  313. has_slots = True
  314. break
  315. if has_slots is None:
  316. self.ui.slot_tooldia_entry.setDisabled(True)
  317. self.ui.generate_milling_slots_button.setDisabled(True)
  318. else:
  319. self.ui.slot_tooldia_entry.setDisabled(False)
  320. self.ui.generate_milling_slots_button.setDisabled(False)
  321. self.ui_connect()
  322. def ui_connect(self):
  323. """
  324. Will connect all signals in the Excellon UI that needs to be connected
  325. :return: None
  326. :rtype:
  327. """
  328. # selective plotting
  329. for row in range(self.ui.tools_table.rowCount() - 2):
  330. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  331. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  332. # rows selected
  333. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  334. def ui_disconnect(self):
  335. """
  336. Will disconnect all signals in the Excellon UI that needs to be disconnected
  337. :return: None
  338. :rtype:
  339. """
  340. # selective plotting
  341. for row in range(self.ui.tools_table.rowCount()):
  342. try:
  343. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  344. except (TypeError, AttributeError):
  345. pass
  346. try:
  347. self.ui.plot_cb.stateChanged.disconnect()
  348. except (TypeError, AttributeError):
  349. pass
  350. # rows selected
  351. try:
  352. self.ui.tools_table.clicked.disconnect()
  353. except (TypeError, AttributeError):
  354. pass
  355. def on_row_selection_change(self):
  356. """
  357. Called when the user clicks on a row in Tools Table
  358. :return: None
  359. :rtype:
  360. """
  361. self.ui_disconnect()
  362. sel_model = self.ui.tools_table.selectionModel()
  363. sel_indexes = sel_model.selectedIndexes()
  364. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  365. sel_rows = set()
  366. for idx in sel_indexes:
  367. sel_rows.add(idx.row())
  368. if not sel_rows:
  369. self.ui.tooldia_entry.setDisabled(True)
  370. self.ui.generate_milling_button.setDisabled(True)
  371. self.ui.slot_tooldia_entry.setDisabled(True)
  372. self.ui.generate_milling_slots_button.setDisabled(True)
  373. self.ui_connect()
  374. return
  375. else:
  376. self.ui.tooldia_entry.setDisabled(False)
  377. self.ui.generate_milling_button.setDisabled(False)
  378. self.ui.slot_tooldia_entry.setDisabled(False)
  379. self.ui.generate_milling_slots_button.setDisabled(False)
  380. # find if we have drills:
  381. has_drills = None
  382. for tt in self.tools:
  383. if 'drills' in self.tools[tt] and self.tools[tt]['drills']:
  384. has_drills = True
  385. break
  386. if has_drills is None:
  387. self.ui.tooldia_entry.setDisabled(True)
  388. self.ui.generate_milling_button.setDisabled(True)
  389. else:
  390. self.ui.tooldia_entry.setDisabled(False)
  391. self.ui.generate_milling_button.setDisabled(False)
  392. # find if we have slots
  393. has_slots = None
  394. for tt in self.tools:
  395. if 'slots' in self.tools[tt] and self.tools[tt]['slots']:
  396. has_slots = True
  397. break
  398. if has_slots is None:
  399. self.ui.slot_tooldia_entry.setDisabled(True)
  400. self.ui.generate_milling_slots_button.setDisabled(True)
  401. else:
  402. self.ui.slot_tooldia_entry.setDisabled(False)
  403. self.ui.generate_milling_slots_button.setDisabled(False)
  404. self.ui_connect()
  405. def on_toggle_rows(self):
  406. sel_model = self.ui.tools_table.selectionModel()
  407. sel_indexes = sel_model.selectedIndexes()
  408. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  409. sel_rows = set()
  410. for idx in sel_indexes:
  411. sel_rows.add(idx.row())
  412. if len(sel_rows) == self.ui.tools_table.rowCount():
  413. self.ui.tools_table.clearSelection()
  414. else:
  415. self.ui.tools_table.selectAll()
  416. def get_selected_tools_list(self):
  417. """
  418. Returns the keys to the self.tools dictionary corresponding
  419. to the selections on the tool list in the appGUI.
  420. :return: List of tools.
  421. :rtype: list
  422. """
  423. rows = set()
  424. for item in self.ui.tools_table.selectedItems():
  425. rows.add(item.row())
  426. tool_ids = []
  427. for row in rows:
  428. tool_ids.append(int(self.ui.tools_table.item(row, 0).text()))
  429. return tool_ids
  430. # return [x.text() for x in self.ui.tools_table.selectedItems()]
  431. def get_selected_tools_table_items(self):
  432. """
  433. Returns a list of lists, each list in the list is made out of row elements
  434. :return: List of table_tools items.
  435. :rtype: list
  436. """
  437. table_tools_items = []
  438. for x in self.ui.tools_table.selectedItems():
  439. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  440. # which does not have text
  441. txt = ''
  442. elem = []
  443. for column in range(0, self.ui.tools_table.columnCount() - 1):
  444. try:
  445. txt = self.ui.tools_table.item(x.row(), column).text()
  446. except AttributeError:
  447. try:
  448. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  449. except AttributeError:
  450. pass
  451. elem.append(txt)
  452. table_tools_items.append(deepcopy(elem))
  453. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  454. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  455. for item in table_tools_items:
  456. item[0] = str(item[0])
  457. return table_tools_items
  458. def on_table_visibility_toggle(self, state):
  459. self.ui.tools_table.show() if state else self.ui.tools_table.hide()
  460. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1, slot_type='routing'):
  461. """
  462. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  463. :param whole: Integer part digits
  464. :type whole: int
  465. :param fract: Fractional part digits
  466. :type fract: int
  467. :param e_zeros: Excellon zeros suppression: LZ or TZ
  468. :type e_zeros: str
  469. :param form: Excellon format: 'dec',
  470. :type form: str
  471. :param factor: Conversion factor
  472. :type factor: float
  473. :param slot_type: How to treat slots: "routing" or "drilling"
  474. :type slot_type: str
  475. :return: A tuple: (has_slots, Excellon_code) -> (bool, str)
  476. :rtype: tuple
  477. """
  478. excellon_code = ''
  479. # store here if the file has slots, return 1 if any slots, 0 if only drills
  480. slots_in_file = 0
  481. # find if we have drills:
  482. has_drills = None
  483. for tt in self.tools:
  484. if 'drills' in self.tools[tt] and self.tools[tt]['drills']:
  485. has_drills = True
  486. break
  487. # find if we have slots:
  488. has_slots = None
  489. for tt in self.tools:
  490. if 'slots' in self.tools[tt] and self.tools[tt]['slots']:
  491. has_slots = True
  492. slots_in_file = 1
  493. break
  494. # drills processing
  495. try:
  496. if has_drills:
  497. length = whole + fract
  498. for tool in self.tools:
  499. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  500. for drill in self.tools[tool]['drills']:
  501. if form == 'dec':
  502. drill_x = drill.x * factor
  503. drill_y = drill.y * factor
  504. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  505. elif e_zeros == 'LZ':
  506. drill_x = drill.x * factor
  507. drill_y = drill.y * factor
  508. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  509. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  510. # extract whole part and decimal part
  511. exc_x_formatted = exc_x_formatted.partition('.')
  512. exc_y_formatted = exc_y_formatted.partition('.')
  513. # left padd the 'whole' part with zeros
  514. x_whole = exc_x_formatted[0].rjust(whole, '0')
  515. y_whole = exc_y_formatted[0].rjust(whole, '0')
  516. # restore the coordinate padded in the left with 0 and added the decimal part
  517. # without the decinal dot
  518. exc_x_formatted = x_whole + exc_x_formatted[2]
  519. exc_y_formatted = y_whole + exc_y_formatted[2]
  520. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  521. yform=exc_y_formatted)
  522. else:
  523. drill_x = drill.x * factor
  524. drill_y = drill.y * factor
  525. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  526. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  527. # pad with rear zeros
  528. exc_x_formatted.ljust(length, '0')
  529. exc_y_formatted.ljust(length, '0')
  530. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  531. yform=exc_y_formatted)
  532. except Exception as e:
  533. log.debug(str(e))
  534. # slots processing
  535. try:
  536. if has_slots:
  537. for tool in self.tools:
  538. excellon_code += 'G05\n'
  539. if int(tool) < 10:
  540. excellon_code += 'T0' + str(tool) + '\n'
  541. else:
  542. excellon_code += 'T' + str(tool) + '\n'
  543. for slot in self.tools[tool]['slots']:
  544. if form == 'dec':
  545. start_slot_x = slot.x * factor
  546. start_slot_y = slot.y * factor
  547. stop_slot_x = slot.x * factor
  548. stop_slot_y = slot.y * factor
  549. if slot_type == 'routing':
  550. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  551. start_slot_y,
  552. dec=fract)
  553. excellon_code += "G01X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  554. stop_slot_y,
  555. dec=fract)
  556. elif slot_type == 'drilling':
  557. excellon_code += "X{:.{dec}f}Y{:.{dec}f}G85X{:.{dec}f}Y{:.{dec}f}\nG05\n".format(
  558. start_slot_x, start_slot_y, stop_slot_x, stop_slot_y, dec=fract
  559. )
  560. elif e_zeros == 'LZ':
  561. start_slot_x = slot.x * factor
  562. start_slot_y = slot.y * factor
  563. stop_slot_x = slot.x * factor
  564. stop_slot_y = slot.y * factor
  565. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  566. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  567. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  568. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  569. # extract whole part and decimal part
  570. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  571. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  572. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  573. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  574. # left padd the 'whole' part with zeros
  575. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  576. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  577. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  578. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  579. # restore the coordinate padded in the left with 0 and added the decimal part
  580. # without the decinal dot
  581. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  582. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  583. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  584. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  585. if slot_type == 'routing':
  586. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  587. ystart=start_slot_y_formatted)
  588. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  589. ystop=stop_slot_y_formatted)
  590. elif slot_type == 'drilling':
  591. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  592. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  593. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  594. )
  595. else:
  596. start_slot_x = slot.x * factor
  597. start_slot_y = slot.y * factor
  598. stop_slot_x = slot.x * factor
  599. stop_slot_y = slot.y * factor
  600. length = whole + fract
  601. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  602. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  603. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  604. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  605. # pad with rear zeros
  606. start_slot_x_formatted.ljust(length, '0')
  607. start_slot_y_formatted.ljust(length, '0')
  608. stop_slot_x_formatted.ljust(length, '0')
  609. stop_slot_y_formatted.ljust(length, '0')
  610. if slot_type == 'routing':
  611. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  612. ystart=start_slot_y_formatted)
  613. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  614. ystop=stop_slot_y_formatted)
  615. elif slot_type == 'drilling':
  616. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  617. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  618. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  619. )
  620. except Exception as e:
  621. log.debug(str(e))
  622. if not has_drills and not has_slots:
  623. log.debug("FlatCAMObj.ExcellonObject.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  624. return 'fail'
  625. return slots_in_file, excellon_code
  626. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  627. """
  628. Will generate an Geometry Object allowing to cut a drill hole instead of drilling it.
  629. Note: This method is a good template for generic operations as
  630. it takes it's options from parameters or otherwise from the
  631. object's options and returns a (success, msg) tuple as feedback
  632. for shell operations.
  633. :param tools: A list of tools where the drills are to be milled or a string: "all"
  634. :type tools:
  635. :param outname: the name of the resulting Geometry object
  636. :type outname: str
  637. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  638. :type tooldia: float
  639. :param plot: if to plot the resulting object
  640. :type plot: bool
  641. :param use_thread: if to use threading for creation of the Geometry object
  642. :type use_thread: bool
  643. :return: Success/failure condition tuple (bool, str).
  644. :rtype: tuple
  645. """
  646. # Get the tools from the list. These are keys
  647. # to self.tools
  648. if tools is None:
  649. tools = self.get_selected_tools_list()
  650. if outname is None:
  651. outname = self.options["name"] + "_mill"
  652. if tooldia is None:
  653. tooldia = self.ui.tooldia_entry.get_value()
  654. # Sort tools by diameter. items() -> [('name', diameter), ...]
  655. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  656. sort = []
  657. for k, v in self.tools.items():
  658. sort.append((k, v['tooldia']))
  659. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  660. if tools == "all":
  661. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  662. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  663. if len(tools) == 0:
  664. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Please select one or more tools from the list and try again."))
  665. return False, "Error: No tools."
  666. for tool in tools:
  667. if tooldia > self.tools[tool]["tooldia"]:
  668. mseg = '[ERROR_NOTCL] %s %s: %s' % (_("Milling tool for DRILLS is larger than hole size. Cancelled."),
  669. _("Tool"),
  670. str(tool))
  671. self.app.inform.emit(mseg)
  672. return False, "Error: Milling tool is larger than hole."
  673. def geo_init(geo_obj, app_obj):
  674. """
  675. :param geo_obj: New object
  676. :type geo_obj: GeometryObject
  677. :param app_obj: App
  678. :type app_obj: FlatCAMApp.App
  679. :return:
  680. :rtype:
  681. """
  682. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  683. # ## Add properties to the object
  684. # get the tool_table items in a list of row items
  685. tool_table_items = self.get_selected_tools_table_items()
  686. # insert an information only element in the front
  687. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  688. geo_obj.options['Tools_in_use'] = tool_table_items
  689. geo_obj.options['type'] = 'Excellon Geometry'
  690. geo_obj.options["cnctooldia"] = str(tooldia)
  691. geo_obj.options["multidepth"] = self.options["multidepth"]
  692. geo_obj.solid_geometry = []
  693. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  694. # for FlatCAM is 6 decimals,
  695. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  696. for etool in tools:
  697. for drill in self.tools[etool]['drills']:
  698. buffer_value = self.tools[etool]['tooldia'] / 2 - tooldia / 2
  699. if buffer_value == 0:
  700. geo_obj.solid_geometry.append(drill.buffer(0.0000001).exterior)
  701. else:
  702. geo_obj.solid_geometry.append(drill.buffer(buffer_value).exterior)
  703. if use_thread:
  704. def geo_thread(a_obj):
  705. a_obj.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  706. # Create a promise with the new name
  707. self.app.collection.promise(outname)
  708. # Send to worker
  709. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  710. else:
  711. self.app.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  712. return True, ""
  713. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  714. """
  715. Will generate an Geometry Object allowing to cut/mill a slot hole.
  716. Note: This method is a good template for generic operations as
  717. it takes it's options from parameters or otherwise from the
  718. object's options and returns a (success, msg) tuple as feedback
  719. for shell operations.
  720. :param tools: A list of tools where the drills are to be milled or a string: "all"
  721. :type tools:
  722. :param outname: the name of the resulting Geometry object
  723. :type outname: str
  724. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  725. :type tooldia: float
  726. :param plot: if to plot the resulting object
  727. :type plot: bool
  728. :param use_thread: if to use threading for creation of the Geometry object
  729. :type use_thread: bool
  730. :return: Success/failure condition tuple (bool, str).
  731. :rtype: tuple
  732. """
  733. # Get the tools from the list. These are keys
  734. # to self.tools
  735. if tools is None:
  736. tools = self.get_selected_tools_list()
  737. if outname is None:
  738. outname = self.options["name"] + "_mill"
  739. if tooldia is None:
  740. tooldia = float(self.options["slot_tooldia"])
  741. # Sort tools by diameter. items() -> [('name', diameter), ...]
  742. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  743. sort = []
  744. for k, v in self.tools.items():
  745. sort.append((k, v['tooldia']))
  746. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  747. if tools == "all":
  748. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  749. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  750. if len(tools) == 0:
  751. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Please select one or more tools from the list and try again."))
  752. return False, "Error: No tools."
  753. for tool in tools:
  754. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  755. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  756. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["tooldia"])))
  757. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  758. self.app.inform.emit('[ERROR_NOTCL] %s' %
  759. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  760. return False, "Error: Milling tool is larger than hole."
  761. def geo_init(geo_obj, app_obj):
  762. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  763. # ## Add properties to the object
  764. # get the tool_table items in a list of row items
  765. tool_table_items = self.get_selected_tools_table_items()
  766. # insert an information only element in the front
  767. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  768. geo_obj.options['Tools_in_use'] = tool_table_items
  769. geo_obj.options['type'] = 'Excellon Geometry'
  770. geo_obj.options["cnctooldia"] = str(tooldia)
  771. geo_obj.options["multidepth"] = self.options["multidepth"]
  772. geo_obj.solid_geometry = []
  773. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  774. # for FlatCAM is 6 decimals,
  775. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  776. for tool in tools:
  777. for slot in self.tools[tool]['slots']:
  778. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  779. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["tooldia"])))
  780. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  781. # for the file_tool (tooldia actually)
  782. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  783. if buffer_value == 0:
  784. start = slot[0]
  785. stop = slot[1]
  786. lines_string = LineString([start, stop])
  787. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  788. geo_obj.solid_geometry.append(poly)
  789. else:
  790. start = slot[0]
  791. stop = slot[1]
  792. lines_string = LineString([start, stop])
  793. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  794. geo_obj.solid_geometry.append(poly)
  795. if use_thread:
  796. def geo_thread(a_obj):
  797. a_obj.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  798. # Create a promise with the new name
  799. self.app.collection.promise(outname)
  800. # Send to worker
  801. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  802. else:
  803. self.app.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  804. return True, ""
  805. def on_generate_milling_button_click(self, *args):
  806. self.app.defaults.report_usage("excellon_on_create_milling_drills button")
  807. self.read_form()
  808. self.generate_milling_drills(use_thread=False, plot=True)
  809. def on_generate_milling_slots_button_click(self, *args):
  810. self.app.defaults.report_usage("excellon_on_create_milling_slots_button")
  811. self.read_form()
  812. self.generate_milling_slots(use_thread=False, plot=True)
  813. def convert_units(self, units):
  814. log.debug("FlatCAMObj.ExcellonObject.convert_units()")
  815. Excellon.convert_units(self, units)
  816. # factor = Excellon.convert_units(self, units)
  817. # self.options['drillz'] = float(self.options['drillz']) * factor
  818. # self.options['travelz'] = float(self.options['travelz']) * factor
  819. # self.options['feedrate'] = float(self.options['feedrate']) * factor
  820. # self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  821. # self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  822. #
  823. # if self.app.defaults["excellon_toolchangexy"] == '':
  824. # self.options['toolchangexy'] = "0.0, 0.0"
  825. # else:
  826. # coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  827. # if len(coords_xy) < 2:
  828. # self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  829. # "in the format (x, y) \n"
  830. # "but now there is only one value, not two. "))
  831. # return 'fail'
  832. # coords_xy[0] *= factor
  833. # coords_xy[1] *= factor
  834. # self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  835. #
  836. # if self.options['startz'] is not None:
  837. # self.options['startz'] = float(self.options['startz']) * factor
  838. # self.options['endz'] = float(self.options['endz']) * factor
  839. def on_solid_cb_click(self, *args):
  840. if self.muted_ui:
  841. return
  842. self.read_form_item('solid')
  843. self.plot()
  844. def on_multicolored_cb_click(self, *args):
  845. if self.muted_ui:
  846. return
  847. self.read_form_item('multicolored')
  848. self.plot()
  849. def on_autoload_db_toggled(self, state):
  850. self.app.defaults["excellon_autoload_db"] = True if state else False
  851. def on_plot_cb_click(self, *args):
  852. if self.muted_ui:
  853. return
  854. self.plot()
  855. self.read_form_item('plot')
  856. self.ui_disconnect()
  857. cb_flag = self.ui.plot_cb.isChecked()
  858. for row in range(self.ui.tools_table.rowCount() - 2):
  859. table_cb = self.ui.tools_table.cellWidget(row, 5)
  860. if cb_flag:
  861. table_cb.setChecked(True)
  862. else:
  863. table_cb.setChecked(False)
  864. self.ui_connect()
  865. def on_plot_cb_click_table(self):
  866. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  867. self.ui_disconnect()
  868. # cw = self.sender()
  869. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  870. # cw_row = cw_index.row()
  871. check_row = 0
  872. self.shapes.clear(update=True)
  873. for tool_key in self.tools:
  874. solid_geometry = self.tools[tool_key]['solid_geometry']
  875. # find the geo_tool_table row associated with the tool_key
  876. for row in range(self.ui.tools_table.rowCount()):
  877. tool_item = int(self.ui.tools_table.item(row, 0).text())
  878. if tool_item == int(tool_key):
  879. check_row = row
  880. break
  881. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  882. self.options['plot'] = True
  883. # self.plot_element(element=solid_geometry, visible=True)
  884. # Plot excellon (All polygons?)
  885. if self.options["solid"]:
  886. for geo in solid_geometry:
  887. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  888. visible=self.options['plot'],
  889. layer=2)
  890. else:
  891. for geo in solid_geometry:
  892. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  893. for ints in geo.interiors:
  894. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  895. self.shapes.redraw()
  896. # make sure that the general plot is disabled if one of the row plot's are disabled and
  897. # if all the row plot's are enabled also enable the general plot checkbox
  898. cb_cnt = 0
  899. total_row = self.ui.tools_table.rowCount()
  900. for row in range(total_row - 2):
  901. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  902. cb_cnt += 1
  903. else:
  904. cb_cnt -= 1
  905. if cb_cnt < total_row - 2:
  906. self.ui.plot_cb.setChecked(False)
  907. else:
  908. self.ui.plot_cb.setChecked(True)
  909. self.ui_connect()
  910. def plot(self, visible=None, kind=None):
  911. # Does all the required setup and returns False
  912. # if the 'ptint' option is set to False.
  913. if not FlatCAMObj.plot(self):
  914. return
  915. if self.app.is_legacy is False:
  916. def random_color():
  917. r_color = np.random.rand(4)
  918. r_color[3] = 1
  919. return r_color
  920. else:
  921. def random_color():
  922. while True:
  923. r_color = np.random.rand(4)
  924. r_color[3] = 1
  925. new_color = '#'
  926. for idx in range(len(r_color)):
  927. new_color += '%x' % int(r_color[idx] * 255)
  928. # do it until a valid color is generated
  929. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  930. # for a total of 9 chars
  931. if len(new_color) == 9:
  932. break
  933. return new_color
  934. # try:
  935. # # Plot Excellon (All polygons?)
  936. # if self.options["solid"]:
  937. # for tool in self.tools:
  938. # for geo in self.tools[tool]['solid_geometry']:
  939. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  940. # visible=self.options['plot'],
  941. # layer=2)
  942. # else:
  943. # for tool in self.tools:
  944. # for geo in self.tools[tool]['solid_geometry']:
  945. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  946. # for ints in geo.interiors:
  947. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  948. #
  949. # self.shapes.redraw()
  950. # return
  951. # except (ObjectDeleted, AttributeError, KeyError):
  952. # self.shapes.clear(update=True)
  953. # this stays for compatibility reasons, in case we try to open old projects
  954. try:
  955. __ = iter(self.solid_geometry)
  956. except TypeError:
  957. self.solid_geometry = [self.solid_geometry]
  958. visible = visible if visible else self.ui.plot_cb.get_value()
  959. try:
  960. # Plot Excellon (All polygons?)
  961. if self.ui.solid_cb.get_value():
  962. # for geo in self.solid_geometry:
  963. # self.add_shape(shape=geo,
  964. # color=self.outline_color,
  965. # face_color=random_color() if self.options['multicolored'] else self.fill_color,
  966. # visible=visible,
  967. # layer=2)
  968. # plot polygons for each tool separately
  969. for tool in self.tools:
  970. # set the color here so we have one color for each tool
  971. geo_color = random_color()
  972. multicolored = self.ui.multicolored_cb.get_value()
  973. # tool is a dict also
  974. for geo in self.tools[tool]["solid_geometry"]:
  975. self.add_shape(shape=geo,
  976. color=geo_color if multicolored else self.outline_color,
  977. face_color=geo_color if multicolored else self.fill_color,
  978. visible=visible,
  979. layer=2)
  980. else:
  981. for geo in self.solid_geometry:
  982. self.add_shape(shape=geo.exterior, color='red', visible=visible)
  983. for ints in geo.interiors:
  984. self.add_shape(shape=ints, color='orange', visible=visible)
  985. self.shapes.redraw()
  986. except (ObjectDeleted, AttributeError):
  987. self.shapes.clear(update=True)
  988. @staticmethod
  989. def merge(exc_list, exc_final, decimals=None, fuse_tools=True):
  990. """
  991. Merge Excellon objects found in exc_list parameter into exc_final object.
  992. Options are always copied from source .
  993. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  994. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  995. tool_name to be used in the final Excellon object, exc_final.
  996. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  997. :param exc_list: List or one object of ExcellonObject Objects to join.
  998. :type exc_list: list
  999. :param exc_final: Destination ExcellonObject object.
  1000. :type exc_final: class
  1001. :param decimals: The number of decimals to be used for diameters
  1002. :type decimals: int
  1003. :param fuse_tools: If True will try to fuse tools of the same diameter for the Excellon objects
  1004. :type fuse_tools: bool
  1005. :return: None
  1006. """
  1007. if exc_final.tools is None:
  1008. exc_final.tools = {}
  1009. if decimals is None:
  1010. decimals = 4
  1011. decimals_exc = decimals
  1012. try:
  1013. flattened_list = list(itertools.chain(*exc_list))
  1014. except TypeError:
  1015. flattened_list = exc_list
  1016. new_tools = {}
  1017. total_geo = []
  1018. toolid = 0
  1019. for exc in flattened_list:
  1020. # copy options of the current excellon obj to the final excellon obj
  1021. # only the last object options will survive
  1022. for option in exc.options:
  1023. if option != 'name':
  1024. try:
  1025. exc_final.options[option] = exc.options[option]
  1026. except Exception:
  1027. exc.app.log.warning("Failed to copy option.", option)
  1028. for tool in exc.tools:
  1029. toolid += 1
  1030. new_tools[toolid] = exc.tools[tool]
  1031. exc_final.tools = deepcopy(new_tools)
  1032. # add the zeros and units to the exc_final object
  1033. exc_final.zeros = exc.zeros
  1034. exc_final.units = exc.units
  1035. total_geo += exc.solid_geometry
  1036. exc_final.solid_geometry = total_geo
  1037. fused_tools_dict = {}
  1038. if exc_final.tools and fuse_tools:
  1039. toolid = 0
  1040. for tool, tool_dict in exc_final.tools.items():
  1041. current_tooldia = float('%.*f' % (decimals_exc, tool_dict['tooldia']))
  1042. toolid += 1
  1043. # calculate all diameters in fused_tools_dict
  1044. all_dia = []
  1045. if fused_tools_dict:
  1046. for f_tool in fused_tools_dict:
  1047. all_dia.append(float('%.*f' % (decimals_exc, fused_tools_dict[f_tool]['tooldia'])))
  1048. if current_tooldia in all_dia:
  1049. # find tool for current_tooldia in fuse_tools
  1050. t = None
  1051. for f_tool in fused_tools_dict:
  1052. if fused_tools_dict[f_tool]['tooldia'] == current_tooldia:
  1053. t = f_tool
  1054. break
  1055. if t:
  1056. fused_tools_dict[t]['drills'] += tool_dict['drills']
  1057. fused_tools_dict[t]['slots'] += tool_dict['slots']
  1058. fused_tools_dict[t]['solid_geometry'] += tool_dict['solid_geometry']
  1059. else:
  1060. fused_tools_dict[toolid] = tool_dict
  1061. fused_tools_dict[toolid]['tooldia'] = current_tooldia
  1062. exc_final.tools = fused_tools_dict
  1063. # create the geometry for the exc_final object
  1064. exc_final.create_geometry()