FlatCAMExcellon.py 56 KB

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