FlatCAMExcellon.py 55 KB

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