FlatCAMExcellon.py 57 KB

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