FlatCAMExcellon.py 57 KB

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