FlatCAMExcellon.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  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. # store here the state of the exclusion checkbox state to be restored after building the UI
  101. # TODO add this in the sel.app.defaults dict and in Preferences
  102. self.exclusion_area_cb_is_checked = False
  103. # Attributes to be included in serialization
  104. # Always append to it because it carries contents
  105. # from predecessors.
  106. self.ser_attrs += ['options', 'kind']
  107. @staticmethod
  108. def merge(exc_list, exc_final, decimals=None, fuse_tools=True):
  109. """
  110. Merge Excellon objects found in exc_list parameter into exc_final object.
  111. Options are always copied from source .
  112. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  113. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  114. tool_name to be used in the final Excellon object, exc_final.
  115. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  116. :param exc_list: List or one object of ExcellonObject Objects to join.
  117. :type exc_list: list
  118. :param exc_final: Destination ExcellonObject object.
  119. :type exc_final: class
  120. :param decimals: The number of decimals to be used for diameters
  121. :type decimals: int
  122. :param fuse_tools: If True will try to fuse tools of the same diameter for the Excellon objects
  123. :type fuse_tools: bool
  124. :return: None
  125. """
  126. if exc_final.tools is None:
  127. exc_final.tools = {}
  128. if decimals is None:
  129. decimals = 4
  130. decimals_exc = decimals
  131. try:
  132. flattened_list = list(itertools.chain(*exc_list))
  133. except TypeError:
  134. flattened_list = exc_list
  135. new_tools = {}
  136. total_geo = []
  137. toolid = 0
  138. for exc in flattened_list:
  139. # copy options of the current excellon obj to the final excellon obj
  140. # only the last object options will survive
  141. for option in exc.options:
  142. if option != 'name':
  143. try:
  144. exc_final.options[option] = exc.options[option]
  145. except Exception:
  146. exc.app.log.warning("Failed to copy option.", option)
  147. for tool in exc.tools:
  148. toolid += 1
  149. new_tools[toolid] = exc.tools[tool]
  150. exc_final.tools = deepcopy(new_tools)
  151. # add the zeros and units to the exc_final object
  152. exc_final.zeros = exc.zeros
  153. exc_final.units = exc.units
  154. total_geo += exc.solid_geometry
  155. exc_final.solid_geometry = total_geo
  156. fused_tools_dict = {}
  157. if exc_final.tools and fuse_tools:
  158. toolid = 0
  159. for tool, tool_dict in exc_final.tools.items():
  160. current_tooldia = float('%.*f' % (decimals_exc, tool_dict['tooldia']))
  161. toolid += 1
  162. # calculate all diameters in fused_tools_dict
  163. all_dia = []
  164. if fused_tools_dict:
  165. for f_tool in fused_tools_dict:
  166. all_dia.append(float('%.*f' % (decimals_exc, fused_tools_dict[f_tool]['tooldia'])))
  167. if current_tooldia in all_dia:
  168. # find tool for current_tooldia in fuse_tools
  169. t = None
  170. for f_tool in fused_tools_dict:
  171. if fused_tools_dict[f_tool]['tooldia'] == current_tooldia:
  172. t = f_tool
  173. break
  174. if t:
  175. fused_tools_dict[t]['drills'] += tool_dict['drills']
  176. fused_tools_dict[t]['slots'] += tool_dict['slots']
  177. fused_tools_dict[t]['solid_geometry'] += tool_dict['solid_geometry']
  178. else:
  179. fused_tools_dict[toolid] = tool_dict
  180. fused_tools_dict[toolid]['tooldia'] = current_tooldia
  181. exc_final.tools = fused_tools_dict
  182. # create the geometry for the exc_final object
  183. exc_final.create_geometry()
  184. def build_ui(self):
  185. """
  186. Will (re)build the Excellon UI updating it (the tool table)
  187. :return: None
  188. :rtype:
  189. """
  190. FlatCAMObj.build_ui(self)
  191. # Area Exception - exclusion shape added signal
  192. # first disconnect it from any other object
  193. try:
  194. self.app.exc_areas.e_shape_modified.disconnect()
  195. except (TypeError, AttributeError):
  196. pass
  197. # then connect it to the current build_ui() method
  198. self.app.exc_areas.e_shape_modified.connect(self.update_exclusion_table)
  199. self.units = self.app.defaults['units'].upper()
  200. for row in range(self.ui.tools_table.rowCount()):
  201. try:
  202. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  203. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  204. offset_spin_widget.valueChanged.disconnect()
  205. except (TypeError, AttributeError):
  206. pass
  207. n = len(self.tools)
  208. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  209. self.ui.tools_table.setRowCount(n + 2)
  210. self.tot_drill_cnt = 0
  211. self.tot_slot_cnt = 0
  212. self.tool_row = 0
  213. sort = []
  214. for k, v in list(self.tools.items()):
  215. try:
  216. sort.append((k, v['tooldia']))
  217. except KeyError:
  218. # for old projects to be opened
  219. sort.append((k, v['C']))
  220. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  221. tools = [i[0] for i in sorted_tools]
  222. new_options = {}
  223. for opt in self.options:
  224. new_options[opt] = self.options[opt]
  225. for tool_no in tools:
  226. try:
  227. dia_val = self.tools[tool_no]['tooldia']
  228. except KeyError:
  229. # for old projects to be opened
  230. dia_val = self.tools[tool_no]['C']
  231. # add the data dictionary for each tool with the default values
  232. self.tools[tool_no]['data'] = deepcopy(new_options)
  233. drill_cnt = 0 # variable to store the nr of drills per tool
  234. slot_cnt = 0 # variable to store the nr of slots per tool
  235. # Find no of drills for the current tool
  236. try:
  237. drill_cnt = len(self.tools[tool_no]['drills'])
  238. except KeyError:
  239. drill_cnt = 0
  240. self.tot_drill_cnt += drill_cnt
  241. # Find no of slots for the current tool
  242. try:
  243. slot_cnt = len(self.tools[tool_no]['slots'])
  244. except KeyError:
  245. slot_cnt = 0
  246. self.tot_slot_cnt += slot_cnt
  247. # Tool ID
  248. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  249. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  250. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item) # Tool name/id
  251. # Diameter
  252. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, dia_val))
  253. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  254. self.ui.tools_table.setItem(self.tool_row, 1, dia_item) # Diameter
  255. # Drill count
  256. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  257. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  258. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item) # Number of drills per tool
  259. # Slot Count
  260. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  261. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  262. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  263. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  264. self.ui.tools_table.setItem(self.tool_row, 3, slot_count_item) # Number of drills per tool
  265. # Empty Plot Item
  266. empty_plot_item = QtWidgets.QTableWidgetItem('')
  267. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  268. self.ui.tools_table.setItem(self.tool_row, 5, empty_plot_item)
  269. # Plot Item
  270. plot_item = FCCheckBox()
  271. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  272. if self.ui.plot_cb.isChecked():
  273. plot_item.setChecked(True)
  274. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  275. self.tool_row += 1
  276. # add a last row with the Total number of drills
  277. empty_1 = QtWidgets.QTableWidgetItem('')
  278. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  279. empty_1_1 = QtWidgets.QTableWidgetItem('')
  280. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  281. empty_1_2 = QtWidgets.QTableWidgetItem('')
  282. empty_1_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  283. empty_1_3 = QtWidgets.QTableWidgetItem('')
  284. empty_1_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  285. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  286. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  287. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  288. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  289. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  290. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  291. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  292. self.ui.tools_table.setItem(self.tool_row, 3, empty_1_1)
  293. self.ui.tools_table.setItem(self.tool_row, 5, empty_1_3)
  294. font = QtGui.QFont()
  295. font.setBold(True)
  296. font.setWeight(75)
  297. for k in [1, 2]:
  298. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  299. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  300. self.tool_row += 1
  301. # add a last row with the Total number of slots
  302. empty_2 = QtWidgets.QTableWidgetItem('')
  303. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  304. empty_2_1 = QtWidgets.QTableWidgetItem('')
  305. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  306. empty_2_2 = QtWidgets.QTableWidgetItem('')
  307. empty_2_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  308. empty_2_3 = QtWidgets.QTableWidgetItem('')
  309. empty_2_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  310. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  311. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  312. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  313. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  314. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  315. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  316. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  317. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  318. self.ui.tools_table.setItem(self.tool_row, 5, empty_2_3)
  319. for kl in [1, 2, 3]:
  320. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  321. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  322. # sort the tool diameter column
  323. # self.ui.tools_table.sortItems(1)
  324. # all the tools are selected by default
  325. self.ui.tools_table.selectColumn(0)
  326. self.ui.tools_table.resizeColumnsToContents()
  327. self.ui.tools_table.resizeRowsToContents()
  328. vertical_header = self.ui.tools_table.verticalHeader()
  329. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  330. vertical_header.hide()
  331. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  332. horizontal_header = self.ui.tools_table.horizontalHeader()
  333. horizontal_header.setMinimumSectionSize(10)
  334. horizontal_header.setDefaultSectionSize(70)
  335. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  336. horizontal_header.resizeSection(0, 20)
  337. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  338. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  339. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  340. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  341. horizontal_header.resizeSection(5, 17)
  342. self.ui.tools_table.setColumnWidth(5, 17)
  343. # horizontal_header.setStretchLastSection(True)
  344. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  345. # horizontal_header.setStretchLastSection(True)
  346. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  347. self.ui.tools_table.setSortingEnabled(False)
  348. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  349. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  350. # find if we have drills:
  351. has_drills = None
  352. for tt in self.tools:
  353. if 'drills' in self.tools[tt] and self.tools[tt]['drills']:
  354. has_drills = True
  355. break
  356. if has_drills is None:
  357. self.ui.tooldia_entry.hide()
  358. self.ui.generate_milling_button.hide()
  359. else:
  360. self.ui.tooldia_entry.show()
  361. self.ui.generate_milling_button.show()
  362. # find if we have slots
  363. has_slots = None
  364. for tt in self.tools:
  365. if 'slots' in self.tools[tt] and self.tools[tt]['slots']:
  366. has_slots = True
  367. break
  368. if has_slots is None:
  369. self.ui.slot_tooldia_entry.hide()
  370. self.ui.generate_milling_slots_button.hide()
  371. else:
  372. self.ui.slot_tooldia_entry.show()
  373. self.ui.generate_milling_slots_button.show()
  374. # set the text on tool_data_label after loading the object
  375. sel_items = self.ui.tools_table.selectedItems()
  376. sel_rows = [it.row() for it in sel_items]
  377. if len(sel_rows) > 1:
  378. self.ui.tool_data_label.setText(
  379. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  380. )
  381. # Build Exclusion Areas section
  382. e_len = len(self.app.exc_areas.exclusion_areas_storage)
  383. self.ui.exclusion_table.setRowCount(e_len)
  384. area_id = 0
  385. for area in range(e_len):
  386. area_id += 1
  387. area_dict = self.app.exc_areas.exclusion_areas_storage[area]
  388. area_id_item = QtWidgets.QTableWidgetItem('%d' % int(area_id))
  389. area_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  390. self.ui.exclusion_table.setItem(area, 0, area_id_item) # Area id
  391. object_item = QtWidgets.QTableWidgetItem('%s' % area_dict["obj_type"])
  392. object_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  393. self.ui.exclusion_table.setItem(area, 1, object_item) # Origin Object
  394. strategy_item = QtWidgets.QTableWidgetItem('%s' % area_dict["strategy"])
  395. strategy_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  396. self.ui.exclusion_table.setItem(area, 2, strategy_item) # Strategy
  397. overz_item = QtWidgets.QTableWidgetItem('%s' % area_dict["overz"])
  398. overz_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  399. self.ui.exclusion_table.setItem(area, 3, overz_item) # Over Z
  400. self.ui.exclusion_table.resizeColumnsToContents()
  401. self.ui.exclusion_table.resizeRowsToContents()
  402. area_vheader = self.ui.exclusion_table.verticalHeader()
  403. area_vheader.hide()
  404. self.ui.exclusion_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  405. area_hheader = self.ui.exclusion_table.horizontalHeader()
  406. area_hheader.setMinimumSectionSize(10)
  407. area_hheader.setDefaultSectionSize(70)
  408. area_hheader.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  409. area_hheader.resizeSection(0, 20)
  410. area_hheader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  411. area_hheader.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  412. area_hheader.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  413. # area_hheader.setStretchLastSection(True)
  414. self.ui.exclusion_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  415. self.ui.exclusion_table.setColumnWidth(0, 20)
  416. self.ui.exclusion_table.setMinimumHeight(self.ui.exclusion_table.getHeight())
  417. self.ui.exclusion_table.setMaximumHeight(self.ui.exclusion_table.getHeight())
  418. self.ui_connect()
  419. def set_ui(self, ui):
  420. """
  421. Configures the user interface for this object.
  422. Connects options to form fields.
  423. :param ui: User interface object.
  424. :type ui: ExcellonObjectUI
  425. :return: None
  426. """
  427. FlatCAMObj.set_ui(self, ui)
  428. log.debug("ExcellonObject.set_ui()")
  429. self.units = self.app.defaults['units'].upper()
  430. self.form_fields.update({
  431. "plot": self.ui.plot_cb,
  432. "solid": self.ui.solid_cb,
  433. "multicolored": self.ui.multicolored_cb,
  434. "operation": self.ui.operation_radio,
  435. "milling_type": self.ui.milling_type_radio,
  436. "milling_dia": self.ui.mill_dia_entry,
  437. "cutz": self.ui.cutz_entry,
  438. "multidepth": self.ui.mpass_cb,
  439. "depthperpass": self.ui.maxdepth_entry,
  440. "travelz": self.ui.travelz_entry,
  441. "feedrate_z": self.ui.feedrate_z_entry,
  442. "feedrate": self.ui.xyfeedrate_entry,
  443. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  444. "tooldia": self.ui.tooldia_entry,
  445. "slot_tooldia": self.ui.slot_tooldia_entry,
  446. "toolchange": self.ui.toolchange_cb,
  447. "toolchangez": self.ui.toolchangez_entry,
  448. "extracut": self.ui.extracut_cb,
  449. "extracut_length": self.ui.e_cut_entry,
  450. "spindlespeed": self.ui.spindlespeed_entry,
  451. "dwell": self.ui.dwell_cb,
  452. "dwelltime": self.ui.dwelltime_entry,
  453. "startz": self.ui.estartz_entry,
  454. "endz": self.ui.endz_entry,
  455. "endxy": self.ui.endxy_entry,
  456. "offset": self.ui.offset_entry,
  457. "ppname_e": self.ui.pp_excellon_name_cb,
  458. "ppname_g": self.ui.pp_geo_name_cb,
  459. "z_pdepth": self.ui.pdepth_entry,
  460. "feedrate_probe": self.ui.feedrate_probe_entry,
  461. # "gcode_type": self.ui.excellon_gcode_type_radio,
  462. "area_exclusion": self.ui.exclusion_cb,
  463. "area_shape": self.ui.area_shape_radio,
  464. "area_strategy": self.ui.strategy_radio,
  465. "area_overz": self.ui.over_z_entry,
  466. })
  467. self.name2option = {
  468. "e_operation": "operation",
  469. "e_milling_type": "milling_type",
  470. "e_milling_dia": "milling_dia",
  471. "e_cutz": "cutz",
  472. "e_multidepth": "multidepth",
  473. "e_depthperpass": "depthperpass",
  474. "e_travelz": "travelz",
  475. "e_feedratexy": "feedrate",
  476. "e_feedratez": "feedrate_z",
  477. "e_fr_rapid": "feedrate_rapid",
  478. "e_extracut": "extracut",
  479. "e_extracut_length": "extracut_length",
  480. "e_spindlespeed": "spindlespeed",
  481. "e_dwell": "dwell",
  482. "e_dwelltime": "dwelltime",
  483. "e_offset": "offset",
  484. }
  485. # populate Excellon preprocessor combobox list
  486. for name in list(self.app.preprocessors.keys()):
  487. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  488. if name == 'hpgl':
  489. continue
  490. self.ui.pp_excellon_name_cb.addItem(name)
  491. # populate Geometry (milling) preprocessor combobox list
  492. for name in list(self.app.preprocessors.keys()):
  493. self.ui.pp_geo_name_cb.addItem(name)
  494. # Fill form fields
  495. self.to_form()
  496. # update the changes in UI depending on the selected preprocessor in Preferences
  497. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  498. # self.ui.pp_excellon_name_cb combobox
  499. self.on_pp_changed()
  500. # Show/Hide Advanced Options
  501. if self.app.defaults["global_app_level"] == 'b':
  502. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  503. self.ui.tools_table.setColumnHidden(4, True)
  504. self.ui.tools_table.setColumnHidden(5, True)
  505. self.ui.estartz_label.hide()
  506. self.ui.estartz_entry.hide()
  507. self.ui.feedrate_rapid_label.hide()
  508. self.ui.feedrate_rapid_entry.hide()
  509. self.ui.pdepth_label.hide()
  510. self.ui.pdepth_entry.hide()
  511. self.ui.feedrate_probe_label.hide()
  512. self.ui.feedrate_probe_entry.hide()
  513. else:
  514. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  515. assert isinstance(self.ui, ExcellonObjectUI), \
  516. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  517. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  518. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  519. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  520. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  521. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  522. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  523. # Exclusion areas signals
  524. self.ui.exclusion_table.horizontalHeader().sectionClicked.connect(self.exclusion_table_toggle_all)
  525. self.ui.exclusion_table.lost_focus.connect(self.clear_selection)
  526. self.ui.exclusion_table.itemClicked.connect(self.draw_sel_shape)
  527. self.ui.add_area_button.clicked.connect(self.on_add_area_click)
  528. self.ui.delete_area_button.clicked.connect(self.on_clear_area_click)
  529. self.ui.delete_sel_area_button.clicked.connect(self.on_delete_sel_areas)
  530. self.ui.strategy_radio.activated_custom.connect(self.on_strategy)
  531. self.on_operation_type(val='drill')
  532. self.ui.operation_radio.activated_custom.connect(self.on_operation_type)
  533. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  534. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  535. self.units_found = self.app.defaults['units']
  536. # ########################################
  537. # #######3 TEMP SETTINGS #################
  538. # ########################################
  539. self.ui.operation_radio.set_value("drill")
  540. self.ui.operation_radio.setEnabled(False)
  541. def ui_connect(self):
  542. """
  543. Will connect all signals in the Excellon UI that needs to be connected
  544. :return: None
  545. :rtype:
  546. """
  547. # selective plotting
  548. for row in range(self.ui.tools_table.rowCount() - 2):
  549. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  550. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  551. # rows selected
  552. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  553. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  554. # value changed in the particular parameters of a tool
  555. for key, option in self.name2option.items():
  556. current_widget = self.form_fields[option]
  557. if isinstance(current_widget, FCCheckBox):
  558. current_widget.stateChanged.connect(self.form_to_storage)
  559. if isinstance(current_widget, RadioSet):
  560. current_widget.activated_custom.connect(self.form_to_storage)
  561. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  562. current_widget.returnPressed.connect(self.form_to_storage)
  563. def ui_disconnect(self):
  564. """
  565. Will disconnect all signals in the Excellon UI that needs to be disconnected
  566. :return: None
  567. :rtype:
  568. """
  569. # selective plotting
  570. for row in range(self.ui.tools_table.rowCount()):
  571. try:
  572. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  573. except (TypeError, AttributeError):
  574. pass
  575. try:
  576. self.ui.plot_cb.stateChanged.disconnect()
  577. except (TypeError, AttributeError):
  578. pass
  579. # rows selected
  580. try:
  581. self.ui.tools_table.clicked.disconnect()
  582. except (TypeError, AttributeError):
  583. pass
  584. try:
  585. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  586. except (TypeError, AttributeError):
  587. pass
  588. # value changed in the particular parameters of a tool
  589. for key, option in self.name2option.items():
  590. current_widget = self.form_fields[option]
  591. if isinstance(current_widget, FCCheckBox):
  592. try:
  593. current_widget.stateChanged.disconnect(self.form_to_storage)
  594. except (TypeError, ValueError):
  595. pass
  596. if isinstance(current_widget, RadioSet):
  597. try:
  598. current_widget.activated_custom.disconnect(self.form_to_storage)
  599. except (TypeError, ValueError):
  600. pass
  601. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  602. try:
  603. current_widget.returnPressed.disconnect(self.form_to_storage)
  604. except (TypeError, ValueError):
  605. pass
  606. def on_row_selection_change(self):
  607. """
  608. Called when the user clicks on a row in Tools Table
  609. :return: None
  610. :rtype:
  611. """
  612. self.ui_disconnect()
  613. sel_rows = []
  614. sel_items = self.ui.tools_table.selectedItems()
  615. for it in sel_items:
  616. sel_rows.append(it.row())
  617. if not sel_rows:
  618. self.ui.tool_data_label.setText(
  619. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  620. )
  621. self.ui.generate_cnc_button.setDisabled(True)
  622. self.ui.generate_milling_button.setDisabled(True)
  623. self.ui.generate_milling_slots_button.setDisabled(True)
  624. self.ui_connect()
  625. return
  626. else:
  627. self.ui.generate_cnc_button.setDisabled(False)
  628. self.ui.generate_milling_button.setDisabled(False)
  629. self.ui.generate_milling_slots_button.setDisabled(False)
  630. if len(sel_rows) == 1:
  631. # update the QLabel that shows for which Tool we have the parameters in the UI form
  632. tooluid = int(self.ui.tools_table.item(sel_rows[0], 0).text())
  633. self.ui.tool_data_label.setText(
  634. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  635. )
  636. else:
  637. self.ui.tool_data_label.setText(
  638. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  639. )
  640. for c_row in sel_rows:
  641. # populate the form with the data from the tool associated with the row parameter
  642. try:
  643. item = self.ui.tools_table.item(c_row, 0)
  644. if type(item) is not None:
  645. tooluid = item.text()
  646. self.storage_to_form(self.tools[str(tooluid)]['data'])
  647. else:
  648. self.ui_connect()
  649. return
  650. except Exception as e:
  651. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  652. self.ui_connect()
  653. return
  654. self.ui_connect()
  655. def storage_to_form(self, dict_storage):
  656. """
  657. Will update the GUI with data from the "storage" in this case the dict self.tools
  658. :param dict_storage: A dictionary holding the data relevant for gnerating Gcode from Excellon
  659. :type dict_storage: dict
  660. :return: None
  661. :rtype:
  662. """
  663. for form_key in self.form_fields:
  664. for storage_key in dict_storage:
  665. if form_key == storage_key and form_key not in \
  666. ["toolchange", "toolchangez", "startz", "endz", "ppname_e", "ppname_g"]:
  667. try:
  668. self.form_fields[form_key].set_value(dict_storage[form_key])
  669. except Exception as e:
  670. log.debug("ExcellonObject.storage_to_form() --> %s" % str(e))
  671. pass
  672. def form_to_storage(self):
  673. """
  674. Will update the 'storage' attribute which is the dict self.tools with data collected from GUI
  675. :return: None
  676. :rtype:
  677. """
  678. if self.ui.tools_table.rowCount() == 0:
  679. # there is no tool in tool table so we can't save the GUI elements values to storage
  680. return
  681. self.ui_disconnect()
  682. widget_changed = self.sender()
  683. wdg_objname = widget_changed.objectName()
  684. option_changed = self.name2option[wdg_objname]
  685. # row = self.ui.tools_table.currentRow()
  686. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  687. for row in rows:
  688. if row < 0:
  689. row = 0
  690. tooluid_item = int(self.ui.tools_table.item(row, 0).text())
  691. for tooluid_key, tooluid_val in self.tools.items():
  692. if int(tooluid_key) == tooluid_item:
  693. new_option_value = self.form_fields[option_changed].get_value()
  694. if option_changed in tooluid_val:
  695. tooluid_val[option_changed] = new_option_value
  696. if option_changed in tooluid_val['data']:
  697. tooluid_val['data'][option_changed] = new_option_value
  698. self.ui_connect()
  699. def on_operation_type(self, val):
  700. """
  701. Called by a RadioSet activated_custom signal
  702. :param val: Parameter passes by the signal that called this method
  703. :type val: str
  704. :return: None
  705. :rtype:
  706. """
  707. if val == 'mill':
  708. self.ui.mill_type_label.show()
  709. self.ui.milling_type_radio.show()
  710. self.ui.mill_dia_label.show()
  711. self.ui.mill_dia_entry.show()
  712. self.ui.frxylabel.show()
  713. self.ui.xyfeedrate_entry.show()
  714. self.ui.extracut_cb.show()
  715. self.ui.e_cut_entry.show()
  716. # if 'laser' not in self.ui.pp_excellon_name_cb.get_value().lower():
  717. # self.ui.mpass_cb.show()
  718. # self.ui.maxdepth_entry.show()
  719. else:
  720. self.ui.mill_type_label.hide()
  721. self.ui.milling_type_radio.hide()
  722. self.ui.mill_dia_label.hide()
  723. self.ui.mill_dia_entry.hide()
  724. # self.ui.mpass_cb.hide()
  725. # self.ui.maxdepth_entry.hide()
  726. self.ui.frxylabel.hide()
  727. self.ui.xyfeedrate_entry.hide()
  728. self.ui.extracut_cb.hide()
  729. self.ui.e_cut_entry.hide()
  730. def get_selected_tools_list(self):
  731. """
  732. Returns the keys to the self.tools dictionary corresponding
  733. to the selections on the tool list in the appGUI.
  734. :return: List of tools.
  735. :rtype: list
  736. """
  737. return [x.text() for x in self.ui.tools_table.selectedItems()]
  738. def get_selected_tools_table_items(self):
  739. """
  740. Returns a list of lists, each list in the list is made out of row elements
  741. :return: List of table_tools items.
  742. :rtype: list
  743. """
  744. table_tools_items = []
  745. for x in self.ui.tools_table.selectedItems():
  746. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  747. # which does not have text
  748. txt = ''
  749. elem = []
  750. for column in range(0, self.ui.tools_table.columnCount() - 1):
  751. try:
  752. txt = self.ui.tools_table.item(x.row(), column).text()
  753. except AttributeError:
  754. try:
  755. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  756. except AttributeError:
  757. pass
  758. elem.append(txt)
  759. table_tools_items.append(deepcopy(elem))
  760. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  761. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  762. for item in table_tools_items:
  763. item[0] = str(item[0])
  764. return table_tools_items
  765. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1, slot_type='routing'):
  766. """
  767. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  768. :param whole: Integer part digits
  769. :type whole: int
  770. :param fract: Fractional part digits
  771. :type fract: int
  772. :param e_zeros: Excellon zeros suppression: LZ or TZ
  773. :type e_zeros: str
  774. :param form: Excellon format: 'dec',
  775. :type form: str
  776. :param factor: Conversion factor
  777. :type factor: float
  778. :param slot_type: How to treat slots: "routing" or "drilling"
  779. :type slot_type: str
  780. :return: A tuple: (has_slots, Excellon_code) -> (bool, str)
  781. :rtype: tuple
  782. """
  783. excellon_code = ''
  784. # store here if the file has slots, return 1 if any slots, 0 if only drills
  785. slots_in_file = 0
  786. # find if we have drills:
  787. has_drills = None
  788. for tt in self.tools:
  789. if 'drills' in self.tools[tt] and self.tools[tt]['drills']:
  790. has_drills = True
  791. break
  792. # find if we have slots:
  793. has_slots = None
  794. for tt in self.tools:
  795. if 'slots' in self.tools[tt] and self.tools[tt]['slots']:
  796. has_slots = True
  797. slots_in_file = 1
  798. break
  799. # drills processing
  800. try:
  801. if has_drills:
  802. length = whole + fract
  803. for tool in self.tools:
  804. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  805. for drill in self.tools[tool]['drills']:
  806. if form == 'dec':
  807. drill_x = drill.x * factor
  808. drill_y = drill.y * factor
  809. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  810. elif e_zeros == 'LZ':
  811. drill_x = drill.x * factor
  812. drill_y = drill.y * factor
  813. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  814. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  815. # extract whole part and decimal part
  816. exc_x_formatted = exc_x_formatted.partition('.')
  817. exc_y_formatted = exc_y_formatted.partition('.')
  818. # left padd the 'whole' part with zeros
  819. x_whole = exc_x_formatted[0].rjust(whole, '0')
  820. y_whole = exc_y_formatted[0].rjust(whole, '0')
  821. # restore the coordinate padded in the left with 0 and added the decimal part
  822. # without the decinal dot
  823. exc_x_formatted = x_whole + exc_x_formatted[2]
  824. exc_y_formatted = y_whole + exc_y_formatted[2]
  825. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  826. yform=exc_y_formatted)
  827. else:
  828. drill_x = drill.x * factor
  829. drill_y = drill.y * factor
  830. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  831. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  832. # pad with rear zeros
  833. exc_x_formatted.ljust(length, '0')
  834. exc_y_formatted.ljust(length, '0')
  835. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  836. yform=exc_y_formatted)
  837. except Exception as e:
  838. log.debug(str(e))
  839. # slots processing
  840. try:
  841. if has_slots:
  842. for tool in self.tools:
  843. excellon_code += 'G05\n'
  844. if int(tool) < 10:
  845. excellon_code += 'T0' + str(tool) + '\n'
  846. else:
  847. excellon_code += 'T' + str(tool) + '\n'
  848. for slot in self.tools[tool]['slots']:
  849. if form == 'dec':
  850. start_slot_x = slot.x * factor
  851. start_slot_y = slot.y * factor
  852. stop_slot_x = slot.x * factor
  853. stop_slot_y = slot.y * factor
  854. if slot_type == 'routing':
  855. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  856. start_slot_y,
  857. dec=fract)
  858. excellon_code += "G01X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  859. stop_slot_y,
  860. dec=fract)
  861. elif slot_type == 'drilling':
  862. excellon_code += "X{:.{dec}f}Y{:.{dec}f}G85X{:.{dec}f}Y{:.{dec}f}\nG05\n".format(
  863. start_slot_x, start_slot_y, stop_slot_x, stop_slot_y, dec=fract
  864. )
  865. elif e_zeros == 'LZ':
  866. start_slot_x = slot.x * factor
  867. start_slot_y = slot.y * factor
  868. stop_slot_x = slot.x * factor
  869. stop_slot_y = slot.y * factor
  870. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  871. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  872. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  873. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  874. # extract whole part and decimal part
  875. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  876. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  877. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  878. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  879. # left padd the 'whole' part with zeros
  880. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  881. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  882. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  883. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  884. # restore the coordinate padded in the left with 0 and added the decimal part
  885. # without the decinal dot
  886. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  887. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  888. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  889. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  890. if slot_type == 'routing':
  891. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  892. ystart=start_slot_y_formatted)
  893. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  894. ystop=stop_slot_y_formatted)
  895. elif slot_type == 'drilling':
  896. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  897. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  898. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  899. )
  900. else:
  901. start_slot_x = slot.x * factor
  902. start_slot_y = slot.y * factor
  903. stop_slot_x = slot.x * factor
  904. stop_slot_y = slot.y * factor
  905. length = whole + fract
  906. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  907. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  908. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  909. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  910. # pad with rear zeros
  911. start_slot_x_formatted.ljust(length, '0')
  912. start_slot_y_formatted.ljust(length, '0')
  913. stop_slot_x_formatted.ljust(length, '0')
  914. stop_slot_y_formatted.ljust(length, '0')
  915. if slot_type == 'routing':
  916. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  917. ystart=start_slot_y_formatted)
  918. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  919. ystop=stop_slot_y_formatted)
  920. elif slot_type == 'drilling':
  921. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  922. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  923. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  924. )
  925. except Exception as e:
  926. log.debug(str(e))
  927. if not has_drills and not has_slots:
  928. log.debug("FlatCAMObj.ExcellonObject.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  929. return 'fail'
  930. return slots_in_file, excellon_code
  931. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  932. """
  933. Will generate an Geometry Object allowing to cut a drill hole instead of drilling it.
  934. Note: This method is a good template for generic operations as
  935. it takes it's options from parameters or otherwise from the
  936. object's options and returns a (success, msg) tuple as feedback
  937. for shell operations.
  938. :param tools: A list of tools where the drills are to be milled or a string: "all"
  939. :type tools:
  940. :param outname: the name of the resulting Geometry object
  941. :type outname: str
  942. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  943. :type tooldia: float
  944. :param plot: if to plot the resulting object
  945. :type plot: bool
  946. :param use_thread: if to use threading for creation of the Geometry object
  947. :type use_thread: bool
  948. :return: Success/failure condition tuple (bool, str).
  949. :rtype: tuple
  950. """
  951. # Get the tools from the list. These are keys
  952. # to self.tools
  953. if tools is None:
  954. tools = self.get_selected_tools_list()
  955. if outname is None:
  956. outname = self.options["name"] + "_mill"
  957. if tooldia is None:
  958. tooldia = float(self.options["tooldia"])
  959. # Sort tools by diameter. items() -> [('name', diameter), ...]
  960. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  961. sort = []
  962. for k, v in self.tools.items():
  963. sort.append((k, v['tooldia']))
  964. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  965. if tools == "all":
  966. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  967. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  968. if len(tools) == 0:
  969. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Please select one or more tools from the list and try again."))
  970. return False, "Error: No tools."
  971. for tool in tools:
  972. if tooldia > self.tools[tool]["tooldia"]:
  973. mseg = '[ERROR_NOTCL] %s %s: %s' % (_("Milling tool for DRILLS is larger than hole size. Cancelled."),
  974. _("Tool"),
  975. str(tool))
  976. self.app.inform.emit(mseg)
  977. return False, "Error: Milling tool is larger than hole."
  978. def geo_init(geo_obj, app_obj):
  979. """
  980. :param geo_obj: New object
  981. :type geo_obj: GeometryObject
  982. :param app_obj: App
  983. :type app_obj: FlatCAMApp.App
  984. :return:
  985. :rtype:
  986. """
  987. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  988. # ## Add properties to the object
  989. # get the tool_table items in a list of row items
  990. tool_table_items = self.get_selected_tools_table_items()
  991. # insert an information only element in the front
  992. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  993. geo_obj.options['Tools_in_use'] = tool_table_items
  994. geo_obj.options['type'] = 'Excellon Geometry'
  995. geo_obj.options["cnctooldia"] = str(tooldia)
  996. geo_obj.options["multidepth"] = self.options["multidepth"]
  997. geo_obj.solid_geometry = []
  998. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  999. # for FlatCAM is 6 decimals,
  1000. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1001. for tool in tools:
  1002. for drill in self.tools[tool]['drills']:
  1003. buffer_value = self.tools[tool]['tooldia'] / 2 - tooldia / 2
  1004. if buffer_value == 0:
  1005. geo_obj.solid_geometry.append(drill.buffer(0.0000001).exterior)
  1006. else:
  1007. geo_obj.solid_geometry.append(drill.buffer(buffer_value).exterior)
  1008. if use_thread:
  1009. def geo_thread(a_obj):
  1010. a_obj.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  1011. # Create a promise with the new name
  1012. self.app.collection.promise(outname)
  1013. # Send to worker
  1014. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1015. else:
  1016. self.app.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  1017. return True, ""
  1018. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  1019. """
  1020. Will generate an Geometry Object allowing to cut/mill a slot hole.
  1021. Note: This method is a good template for generic operations as
  1022. it takes it's options from parameters or otherwise from the
  1023. object's options and returns a (success, msg) tuple as feedback
  1024. for shell operations.
  1025. :param tools: A list of tools where the drills are to be milled or a string: "all"
  1026. :type tools:
  1027. :param outname: the name of the resulting Geometry object
  1028. :type outname: str
  1029. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  1030. :type tooldia: float
  1031. :param plot: if to plot the resulting object
  1032. :type plot: bool
  1033. :param use_thread: if to use threading for creation of the Geometry object
  1034. :type use_thread: bool
  1035. :return: Success/failure condition tuple (bool, str).
  1036. :rtype: tuple
  1037. """
  1038. # Get the tools from the list. These are keys
  1039. # to self.tools
  1040. if tools is None:
  1041. tools = self.get_selected_tools_list()
  1042. if outname is None:
  1043. outname = self.options["name"] + "_mill"
  1044. if tooldia is None:
  1045. tooldia = float(self.options["slot_tooldia"])
  1046. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1047. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1048. sort = []
  1049. for k, v in self.tools.items():
  1050. sort.append((k, v['tooldia']))
  1051. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1052. if tools == "all":
  1053. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1054. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1055. if len(tools) == 0:
  1056. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Please select one or more tools from the list and try again."))
  1057. return False, "Error: No tools."
  1058. for tool in tools:
  1059. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1060. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  1061. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["tooldia"])))
  1062. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  1063. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1064. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  1065. return False, "Error: Milling tool is larger than hole."
  1066. def geo_init(geo_obj, app_obj):
  1067. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  1068. # ## Add properties to the object
  1069. # get the tool_table items in a list of row items
  1070. tool_table_items = self.get_selected_tools_table_items()
  1071. # insert an information only element in the front
  1072. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1073. geo_obj.options['Tools_in_use'] = tool_table_items
  1074. geo_obj.options['type'] = 'Excellon Geometry'
  1075. geo_obj.options["cnctooldia"] = str(tooldia)
  1076. geo_obj.options["multidepth"] = self.options["multidepth"]
  1077. geo_obj.solid_geometry = []
  1078. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1079. # for FlatCAM is 6 decimals,
  1080. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1081. for tool in tools:
  1082. for slot in self.tools[tool]['slots']:
  1083. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  1084. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["tooldia"])))
  1085. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1086. # for the file_tool (tooldia actually)
  1087. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  1088. if buffer_value == 0:
  1089. start = slot[0]
  1090. stop = slot[1]
  1091. lines_string = LineString([start, stop])
  1092. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  1093. geo_obj.solid_geometry.append(poly)
  1094. else:
  1095. start = slot[0]
  1096. stop = slot[1]
  1097. lines_string = LineString([start, stop])
  1098. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  1099. geo_obj.solid_geometry.append(poly)
  1100. if use_thread:
  1101. def geo_thread(a_obj):
  1102. a_obj.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  1103. # Create a promise with the new name
  1104. self.app.collection.promise(outname)
  1105. # Send to worker
  1106. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1107. else:
  1108. self.app.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  1109. return True, ""
  1110. def on_generate_milling_button_click(self, *args):
  1111. self.app.defaults.report_usage("excellon_on_create_milling_drills button")
  1112. self.read_form()
  1113. self.generate_milling_drills(use_thread=False, plot=True)
  1114. def on_generate_milling_slots_button_click(self, *args):
  1115. self.app.defaults.report_usage("excellon_on_create_milling_slots_button")
  1116. self.read_form()
  1117. self.generate_milling_slots(use_thread=False, plot=True)
  1118. def on_pp_changed(self):
  1119. current_pp = self.ui.pp_excellon_name_cb.get_value()
  1120. if "toolchange_probe" in current_pp.lower():
  1121. self.ui.pdepth_entry.setVisible(True)
  1122. self.ui.pdepth_label.show()
  1123. self.ui.feedrate_probe_entry.setVisible(True)
  1124. self.ui.feedrate_probe_label.show()
  1125. else:
  1126. self.ui.pdepth_entry.setVisible(False)
  1127. self.ui.pdepth_label.hide()
  1128. self.ui.feedrate_probe_entry.setVisible(False)
  1129. self.ui.feedrate_probe_label.hide()
  1130. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  1131. self.ui.feedrate_rapid_label.show()
  1132. self.ui.feedrate_rapid_entry.show()
  1133. else:
  1134. self.ui.feedrate_rapid_label.hide()
  1135. self.ui.feedrate_rapid_entry.hide()
  1136. if 'laser' in current_pp.lower():
  1137. self.ui.cutzlabel.hide()
  1138. self.ui.cutz_entry.hide()
  1139. try:
  1140. self.ui.mpass_cb.hide()
  1141. self.ui.maxdepth_entry.hide()
  1142. except AttributeError:
  1143. pass
  1144. if 'marlin' in current_pp.lower():
  1145. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  1146. self.ui.endz_label.show()
  1147. self.ui.endz_entry.show()
  1148. else:
  1149. self.ui.travelzlabel.hide()
  1150. self.ui.travelz_entry.hide()
  1151. self.ui.endz_label.hide()
  1152. self.ui.endz_entry.hide()
  1153. try:
  1154. self.ui.frzlabel.hide()
  1155. self.ui.feedrate_z_entry.hide()
  1156. except AttributeError:
  1157. pass
  1158. self.ui.dwell_cb.hide()
  1159. self.ui.dwelltime_entry.hide()
  1160. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  1161. try:
  1162. self.ui.tool_offset_label.hide()
  1163. self.ui.offset_entry.hide()
  1164. except AttributeError:
  1165. pass
  1166. else:
  1167. self.ui.cutzlabel.show()
  1168. self.ui.cutz_entry.show()
  1169. try:
  1170. self.ui.mpass_cb.show()
  1171. self.ui.maxdepth_entry.show()
  1172. except AttributeError:
  1173. pass
  1174. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  1175. self.ui.travelzlabel.show()
  1176. self.ui.travelz_entry.show()
  1177. self.ui.endz_label.show()
  1178. self.ui.endz_entry.show()
  1179. try:
  1180. self.ui.frzlabel.show()
  1181. self.ui.feedrate_z_entry.show()
  1182. except AttributeError:
  1183. pass
  1184. self.ui.dwell_cb.show()
  1185. self.ui.dwelltime_entry.show()
  1186. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  1187. try:
  1188. self.ui.tool_offset_lbl.show()
  1189. self.ui.offset_entry.show()
  1190. except AttributeError:
  1191. pass
  1192. def on_create_cncjob_button_click(self, *args):
  1193. self.app.defaults.report_usage("excellon_on_create_cncjob_button")
  1194. self.read_form()
  1195. # Get the tools from the list
  1196. tools = self.get_selected_tools_list()
  1197. if len(tools) == 0:
  1198. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1199. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1200. # in this case regardless of the selection status of that tool, use it.
  1201. if self.ui.tools_table.rowCount() == 3:
  1202. tools.append(int(self.ui.tools_table.item(0, 0).text()))
  1203. else:
  1204. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1205. _("Please select one or more tools from the list and try again."))
  1206. return
  1207. xmin = self.options['xmin']
  1208. ymin = self.options['ymin']
  1209. xmax = self.options['xmax']
  1210. ymax = self.options['ymax']
  1211. job_name = self.options["name"] + "_cnc"
  1212. pp_excellon_name = self.options["ppname_e"]
  1213. # Object initialization function for app.app_obj.new_object()
  1214. def job_init(job_obj, app_obj):
  1215. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1216. # get the tool_table items in a list of row items
  1217. tool_table_items = self.get_selected_tools_table_items()
  1218. # insert an information only element in the front
  1219. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1220. # ## Add properties to the object
  1221. job_obj.origin_kind = 'excellon'
  1222. job_obj.options['Tools_in_use'] = tool_table_items
  1223. job_obj.options['type'] = 'Excellon'
  1224. job_obj.options['ppname_e'] = pp_excellon_name
  1225. job_obj.multidepth = self.options["multidepth"]
  1226. job_obj.z_depthpercut = self.options["depthperpass"]
  1227. job_obj.z_move = float(self.options["travelz"])
  1228. job_obj.feedrate = float(self.options["feedrate_z"])
  1229. job_obj.z_feedrate = float(self.options["feedrate_z"])
  1230. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  1231. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] != 0 else None
  1232. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  1233. job_obj.dwell = self.options["dwell"]
  1234. job_obj.dwelltime = float(self.options["dwelltime"])
  1235. job_obj.pp_excellon_name = pp_excellon_name
  1236. job_obj.toolchange_xy_type = "excellon"
  1237. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1238. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1239. job_obj.options['xmin'] = xmin
  1240. job_obj.options['ymin'] = ymin
  1241. job_obj.options['xmax'] = xmax
  1242. job_obj.options['ymax'] = ymax
  1243. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1244. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1245. job_obj.z_cut = float(self.options['cutz'])
  1246. job_obj.toolchange = self.options["toolchange"]
  1247. job_obj.xy_toolchange = self.app.defaults["excellon_toolchangexy"]
  1248. job_obj.z_toolchange = float(self.options["toolchangez"])
  1249. job_obj.startz = float(self.options["startz"]) if self.options["startz"] else None
  1250. job_obj.endz = float(self.options["endz"])
  1251. job_obj.xy_end = self.options["endxy"]
  1252. job_obj.excellon_optimization_type = self.app.defaults["excellon_optimization_type"]
  1253. tools_csv = ','.join(tools)
  1254. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv, use_ui=True)
  1255. if ret_val == 'fail':
  1256. return 'fail'
  1257. job_obj.gcode_parse()
  1258. job_obj.create_geometry()
  1259. # To be run in separate thread
  1260. def job_thread(a_obj):
  1261. with self.app.proc_container.new(_("Generating CNC Code")):
  1262. a_obj.app_obj.new_object("cncjob", job_name, job_init)
  1263. # Create promise for the new name.
  1264. self.app.collection.promise(job_name)
  1265. # Send to worker
  1266. # self.app.worker.add_task(job_thread, [self.app])
  1267. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1268. def convert_units(self, units):
  1269. log.debug("FlatCAMObj.ExcellonObject.convert_units()")
  1270. Excellon.convert_units(self, units)
  1271. # factor = Excellon.convert_units(self, units)
  1272. # self.options['drillz'] = float(self.options['drillz']) * factor
  1273. # self.options['travelz'] = float(self.options['travelz']) * factor
  1274. # self.options['feedrate'] = float(self.options['feedrate']) * factor
  1275. # self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  1276. # self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  1277. #
  1278. # if self.app.defaults["excellon_toolchangexy"] == '':
  1279. # self.options['toolchangexy'] = "0.0, 0.0"
  1280. # else:
  1281. # coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1282. # if len(coords_xy) < 2:
  1283. # self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  1284. # "in the format (x, y) \n"
  1285. # "but now there is only one value, not two. "))
  1286. # return 'fail'
  1287. # coords_xy[0] *= factor
  1288. # coords_xy[1] *= factor
  1289. # self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1290. #
  1291. # if self.options['startz'] is not None:
  1292. # self.options['startz'] = float(self.options['startz']) * factor
  1293. # self.options['endz'] = float(self.options['endz']) * factor
  1294. def on_add_area_click(self):
  1295. shape_button = self.ui.area_shape_radio
  1296. overz_button = self.ui.over_z_entry
  1297. strategy_radio = self.ui.strategy_radio
  1298. cnc_button = self.ui.generate_cnc_button
  1299. solid_geo = self.solid_geometry
  1300. obj_type = self.kind
  1301. self.app.exc_areas.on_add_area_click(
  1302. shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio,
  1303. solid_geo=solid_geo, obj_type=obj_type)
  1304. def on_clear_area_click(self):
  1305. if not self.app.exc_areas.exclusion_areas_storage:
  1306. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. There are no exclusion areas to delete."))
  1307. return
  1308. self.app.exc_areas.on_clear_area_click()
  1309. self.app.exc_areas.e_shape_modified.emit()
  1310. def on_delete_sel_areas(self):
  1311. sel_model = self.ui.exclusion_table.selectionModel()
  1312. sel_indexes = sel_model.selectedIndexes()
  1313. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1314. # so the duplicate rows will not be added
  1315. sel_rows = set()
  1316. for idx in sel_indexes:
  1317. sel_rows.add(idx.row())
  1318. if not sel_rows:
  1319. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. Nothing is selected."))
  1320. return
  1321. self.app.exc_areas.delete_sel_shapes(idxs=list(sel_rows))
  1322. self.app.exc_areas.e_shape_modified.emit()
  1323. def draw_sel_shape(self):
  1324. sel_model = self.ui.exclusion_table.selectionModel()
  1325. sel_indexes = sel_model.selectedIndexes()
  1326. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1327. sel_rows = set()
  1328. for idx in sel_indexes:
  1329. sel_rows.add(idx.row())
  1330. self.delete_sel_shape()
  1331. if self.app.is_legacy is False:
  1332. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  1333. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  1334. else:
  1335. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  1336. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  1337. for row in sel_rows:
  1338. sel_rect = self.app.exc_areas.exclusion_areas_storage[row]['shape']
  1339. self.app.move_tool.sel_shapes.add(sel_rect, color=outline, face_color=face, update=True, layer=0,
  1340. tolerance=None)
  1341. if self.app.is_legacy is True:
  1342. self.app.move_tool.sel_shapes.redraw()
  1343. def clear_selection(self):
  1344. self.app.delete_selection_shape()
  1345. # self.ui.exclusion_table.clearSelection()
  1346. def delete_sel_shape(self):
  1347. self.app.delete_selection_shape()
  1348. def update_exclusion_table(self):
  1349. self.exclusion_area_cb_is_checked = True if self.ui.exclusion_cb.isChecked() else False
  1350. self.build_ui()
  1351. self.ui.exclusion_cb.set_value(self.exclusion_area_cb_is_checked)
  1352. def on_strategy(self, val):
  1353. if val == 'around':
  1354. self.ui.over_z_label.setDisabled(True)
  1355. self.ui.over_z_entry.setDisabled(True)
  1356. else:
  1357. self.ui.over_z_label.setDisabled(False)
  1358. self.ui.over_z_entry.setDisabled(False)
  1359. def exclusion_table_toggle_all(self):
  1360. """
  1361. will toggle the selection of all rows in Exclusion Areas table
  1362. :return:
  1363. """
  1364. sel_model = self.ui.exclusion_table.selectionModel()
  1365. sel_indexes = sel_model.selectedIndexes()
  1366. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1367. sel_rows = set()
  1368. for idx in sel_indexes:
  1369. sel_rows.add(idx.row())
  1370. if sel_rows:
  1371. self.ui.exclusion_table.clearSelection()
  1372. self.delete_sel_shape()
  1373. else:
  1374. self.ui.exclusion_table.selectAll()
  1375. self.draw_sel_shape()
  1376. def on_solid_cb_click(self, *args):
  1377. if self.muted_ui:
  1378. return
  1379. self.read_form_item('solid')
  1380. self.plot()
  1381. def on_multicolored_cb_click(self, *args):
  1382. if self.muted_ui:
  1383. return
  1384. self.read_form_item('multicolored')
  1385. self.plot()
  1386. def on_plot_cb_click(self, *args):
  1387. if self.muted_ui:
  1388. return
  1389. self.plot()
  1390. self.read_form_item('plot')
  1391. self.ui_disconnect()
  1392. cb_flag = self.ui.plot_cb.isChecked()
  1393. for row in range(self.ui.tools_table.rowCount() - 2):
  1394. table_cb = self.ui.tools_table.cellWidget(row, 5)
  1395. if cb_flag:
  1396. table_cb.setChecked(True)
  1397. else:
  1398. table_cb.setChecked(False)
  1399. self.ui_connect()
  1400. def on_plot_cb_click_table(self):
  1401. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1402. self.ui_disconnect()
  1403. # cw = self.sender()
  1404. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  1405. # cw_row = cw_index.row()
  1406. check_row = 0
  1407. self.shapes.clear(update=True)
  1408. for tool_key in self.tools:
  1409. solid_geometry = self.tools[tool_key]['solid_geometry']
  1410. # find the geo_tool_table row associated with the tool_key
  1411. for row in range(self.ui.tools_table.rowCount()):
  1412. tool_item = int(self.ui.tools_table.item(row, 0).text())
  1413. if tool_item == int(tool_key):
  1414. check_row = row
  1415. break
  1416. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  1417. self.options['plot'] = True
  1418. # self.plot_element(element=solid_geometry, visible=True)
  1419. # Plot excellon (All polygons?)
  1420. if self.options["solid"]:
  1421. for geo in solid_geometry:
  1422. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1423. visible=self.options['plot'],
  1424. layer=2)
  1425. else:
  1426. for geo in solid_geometry:
  1427. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1428. for ints in geo.interiors:
  1429. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1430. self.shapes.redraw()
  1431. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1432. # if all the row plot's are enabled also enable the general plot checkbox
  1433. cb_cnt = 0
  1434. total_row = self.ui.tools_table.rowCount()
  1435. for row in range(total_row - 2):
  1436. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  1437. cb_cnt += 1
  1438. else:
  1439. cb_cnt -= 1
  1440. if cb_cnt < total_row - 2:
  1441. self.ui.plot_cb.setChecked(False)
  1442. else:
  1443. self.ui.plot_cb.setChecked(True)
  1444. self.ui_connect()
  1445. def plot(self, visible=None, kind=None):
  1446. # Does all the required setup and returns False
  1447. # if the 'ptint' option is set to False.
  1448. if not FlatCAMObj.plot(self):
  1449. return
  1450. if self.app.is_legacy is False:
  1451. def random_color():
  1452. r_color = np.random.rand(4)
  1453. r_color[3] = 1
  1454. return r_color
  1455. else:
  1456. def random_color():
  1457. while True:
  1458. r_color = np.random.rand(4)
  1459. r_color[3] = 1
  1460. new_color = '#'
  1461. for idx in range(len(r_color)):
  1462. new_color += '%x' % int(r_color[idx] * 255)
  1463. # do it until a valid color is generated
  1464. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  1465. # for a total of 9 chars
  1466. if len(new_color) == 9:
  1467. break
  1468. return new_color
  1469. # try:
  1470. # # Plot Excellon (All polygons?)
  1471. # if self.options["solid"]:
  1472. # for tool in self.tools:
  1473. # for geo in self.tools[tool]['solid_geometry']:
  1474. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1475. # visible=self.options['plot'],
  1476. # layer=2)
  1477. # else:
  1478. # for tool in self.tools:
  1479. # for geo in self.tools[tool]['solid_geometry']:
  1480. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1481. # for ints in geo.interiors:
  1482. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  1483. #
  1484. # self.shapes.redraw()
  1485. # return
  1486. # except (ObjectDeleted, AttributeError, KeyError):
  1487. # self.shapes.clear(update=True)
  1488. # this stays for compatibility reasons, in case we try to open old projects
  1489. try:
  1490. __ = iter(self.solid_geometry)
  1491. except TypeError:
  1492. self.solid_geometry = [self.solid_geometry]
  1493. visible = visible if visible else self.options['plot']
  1494. try:
  1495. # Plot Excellon (All polygons?)
  1496. if self.options["solid"]:
  1497. # for geo in self.solid_geometry:
  1498. # self.add_shape(shape=geo,
  1499. # color=self.outline_color,
  1500. # face_color=random_color() if self.options['multicolored'] else self.fill_color,
  1501. # visible=visible,
  1502. # layer=2)
  1503. # plot polygons for each tool separately
  1504. for tool in self.tools:
  1505. # set the color here so we have one color for each tool
  1506. geo_color = random_color()
  1507. # tool is a dict also
  1508. for geo in self.tools[tool]["solid_geometry"]:
  1509. self.add_shape(shape=geo,
  1510. color=geo_color if self.options['multicolored'] else self.outline_color,
  1511. face_color=geo_color if self.options['multicolored'] else self.fill_color,
  1512. visible=visible,
  1513. layer=2)
  1514. else:
  1515. for geo in self.solid_geometry:
  1516. self.add_shape(shape=geo.exterior, color='red', visible=visible)
  1517. for ints in geo.interiors:
  1518. self.add_shape(shape=ints, color='orange', visible=visible)
  1519. self.shapes.redraw()
  1520. except (ObjectDeleted, AttributeError):
  1521. self.shapes.clear(update=True)
  1522. def on_apply_param_to_all_clicked(self):
  1523. if self.ui.tools_table.rowCount() == 0:
  1524. # there is no tool in tool table so we can't save the GUI elements values to storage
  1525. log.debug("ExcellonObject.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  1526. return
  1527. self.ui_disconnect()
  1528. row = self.ui.tools_table.currentRow()
  1529. if row < 0:
  1530. row = 0
  1531. tooluid_item = int(self.ui.tools_table.item(row, 0).text())
  1532. temp_tool_data = {}
  1533. for tooluid_key, tooluid_val in self.tools.items():
  1534. if int(tooluid_key) == tooluid_item:
  1535. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  1536. # the current row in the tool table
  1537. temp_tool_data = tooluid_val['data']
  1538. break
  1539. for tooluid_key, tooluid_val in self.tools.items():
  1540. tooluid_val['data'] = deepcopy(temp_tool_data)
  1541. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  1542. self.ui_connect()