FlatCAMExcellon.py 57 KB

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