FlatCAMExcellon.py 56 KB

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