FlatCAMExcellon.py 57 KB

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