FlatCAMExcellon.py 80 KB

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