FlatCAMExcellon.py 55 KB

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