FlatCAMExcellon.py 57 KB

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