FlatCAMExcellon.py 56 KB

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