FlatCAMExcellon.py 55 KB

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