FlatCAMExcellon.py 77 KB

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