FlatCAMExcellon.py 55 KB

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