FlatCAMExcellon.py 56 KB

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