FlatCAMExcellon.py 69 KB

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