ToolSolderPaste.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. from FlatCAMTool import FlatCAMTool
  2. from ObjectCollection import *
  3. from FlatCAMApp import *
  4. from GUIElements import IntEntry, RadioSet, LengthEntry
  5. from FlatCAMCommon import LoudDict
  6. from FlatCAMObj import FlatCAMGeometry, FlatCAMExcellon, FlatCAMGerber
  7. from PyQt5 import QtGui, QtCore, QtWidgets
  8. from copy import copy,deepcopy
  9. class SolderPaste(FlatCAMTool):
  10. toolName = "Solder Paste Tool"
  11. def __init__(self, app):
  12. FlatCAMTool.__init__(self, app)
  13. ## Title
  14. title_label = QtWidgets.QLabel("%s" % self.toolName)
  15. title_label.setStyleSheet("""
  16. QLabel
  17. {
  18. font-size: 16px;
  19. font-weight: bold;
  20. }
  21. """)
  22. self.layout.addWidget(title_label)
  23. ## Form Layout
  24. obj_form_layout = QtWidgets.QFormLayout()
  25. self.layout.addLayout(obj_form_layout)
  26. ## Gerber Object to be used for solderpaste dispensing
  27. self.obj_combo = FCComboBox(callback=self.on_rmb_combo)
  28. self.obj_combo.setModel(self.app.collection)
  29. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  30. self.obj_combo.setCurrentIndex(1)
  31. self.object_label = QtWidgets.QLabel("Gerber: ")
  32. self.object_label.setToolTip(
  33. "Gerber Solder paste object. "
  34. )
  35. obj_form_layout.addRow(self.object_label, self.obj_combo)
  36. #### Tools ####
  37. self.tools_table_label = QtWidgets.QLabel('<b>Tools Table</b>')
  38. self.tools_table_label.setToolTip(
  39. "Tools pool from which the algorithm\n"
  40. "will pick the ones used for dispensing solder paste."
  41. )
  42. self.layout.addWidget(self.tools_table_label)
  43. self.tools_table = FCTable()
  44. self.layout.addWidget(self.tools_table)
  45. self.tools_table.setColumnCount(3)
  46. self.tools_table.setHorizontalHeaderLabels(['#', 'Diameter', ''])
  47. self.tools_table.setColumnHidden(2, True)
  48. self.tools_table.setSortingEnabled(False)
  49. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  50. self.tools_table.horizontalHeaderItem(0).setToolTip(
  51. "This is the Tool Number.\n"
  52. "The solder dispensing will start with the tool with the biggest \n"
  53. "diameter, continuing until there are no more Nozzle tools.\n"
  54. "If there are no longer tools but there are still pads not covered\n "
  55. "with solder paste, the app will issue a warning message box."
  56. )
  57. self.tools_table.horizontalHeaderItem(1).setToolTip(
  58. "Nozzle tool Diameter. It's value (in current FlatCAM units)\n"
  59. "is the width of the solder paste dispensed.")
  60. #### Add a new Tool ####
  61. hlay_tools = QtWidgets.QHBoxLayout()
  62. self.layout.addLayout(hlay_tools)
  63. self.addtool_entry_lbl = QtWidgets.QLabel('<b>New Nozzle Tool:</b>')
  64. self.addtool_entry_lbl.setToolTip(
  65. "Diameter for the new Nozzle tool to add in the Tool Table"
  66. )
  67. self.addtool_entry = FCEntry()
  68. # hlay.addWidget(self.addtool_label)
  69. # hlay.addStretch()
  70. hlay_tools.addWidget(self.addtool_entry_lbl)
  71. hlay_tools.addWidget(self.addtool_entry)
  72. grid0 = QtWidgets.QGridLayout()
  73. self.layout.addLayout(grid0)
  74. self.addtool_btn = QtWidgets.QPushButton('Add')
  75. self.addtool_btn.setToolTip(
  76. "Add a new nozzle tool to the Tool Table\n"
  77. "with the diameter specified above."
  78. )
  79. self.deltool_btn = QtWidgets.QPushButton('Delete')
  80. self.deltool_btn.setToolTip(
  81. "Delete a selection of tools in the Tool Table\n"
  82. "by first selecting a row(s) in the Tool Table."
  83. )
  84. self.soldergeo_btn = QtWidgets.QPushButton("Generate Geo")
  85. self.soldergeo_btn.setToolTip(
  86. "Generate solder paste dispensing geometry."
  87. )
  88. grid0.addWidget(self.addtool_btn, 0, 0)
  89. # grid2.addWidget(self.copytool_btn, 0, 1)
  90. grid0.addWidget(self.deltool_btn, 0, 2)
  91. self.layout.addSpacing(10)
  92. ## Buttons
  93. grid0_1 = QtWidgets.QGridLayout()
  94. self.layout.addLayout(grid0_1)
  95. step1_lbl = QtWidgets.QLabel("<b>STEP 1:</b>")
  96. step1_lbl.setToolTip(
  97. "First step is to select a number of nozzle tools for usage\n"
  98. "and then optionally modify the GCode parameters bellow."
  99. )
  100. step1_description_lbl = QtWidgets.QLabel("Select tools.\n"
  101. "Modify parameters.")
  102. grid0_1.addWidget(step1_lbl, 0, 0, alignment=Qt.AlignTop)
  103. grid0_1.addWidget(step1_description_lbl, 0, 2, alignment=Qt.AlignBottom)
  104. self.gcode_frame = QtWidgets.QFrame()
  105. self.gcode_frame.setContentsMargins(0, 0, 0, 0)
  106. self.layout.addWidget(self.gcode_frame)
  107. self.gcode_box = QtWidgets.QVBoxLayout()
  108. self.gcode_box.setContentsMargins(0, 0, 0, 0)
  109. self.gcode_frame.setLayout(self.gcode_box)
  110. ## Form Layout
  111. self.gcode_form_layout = QtWidgets.QFormLayout()
  112. self.gcode_box.addLayout(self.gcode_form_layout)
  113. # Z dispense start
  114. self.z_start_entry = FCEntry()
  115. self.z_start_label = QtWidgets.QLabel("Z Dispense Start:")
  116. self.z_start_label.setToolTip(
  117. "The height (Z) when solder paste dispensing starts."
  118. )
  119. self.gcode_form_layout.addRow(self.z_start_label, self.z_start_entry)
  120. # Z dispense
  121. self.z_dispense_entry = FCEntry()
  122. self.z_dispense_label = QtWidgets.QLabel("Z Dispense:")
  123. self.z_dispense_label.setToolTip(
  124. "The height (Z) when doing solder paste dispensing."
  125. )
  126. self.gcode_form_layout.addRow(self.z_dispense_label, self.z_dispense_entry)
  127. # Z dispense stop
  128. self.z_stop_entry = FCEntry()
  129. self.z_stop_label = QtWidgets.QLabel("Z Dispense Stop:")
  130. self.z_stop_label.setToolTip(
  131. "The height (Z) when solder paste dispensing stops."
  132. )
  133. self.gcode_form_layout.addRow(self.z_stop_label, self.z_stop_entry)
  134. # Z travel
  135. self.z_travel_entry = FCEntry()
  136. self.z_travel_label = QtWidgets.QLabel("Z Travel:")
  137. self.z_travel_label.setToolTip(
  138. "The height (Z) for travel between pads\n"
  139. "(without dispensing solder paste)."
  140. )
  141. self.gcode_form_layout.addRow(self.z_travel_label, self.z_travel_entry)
  142. # Z toolchange location
  143. self.z_toolchange_entry = FCEntry()
  144. self.z_toolchange_label = QtWidgets.QLabel("Z Toolchange:")
  145. self.z_toolchange_label.setToolTip(
  146. "The height (Z) for tool (nozzle) change."
  147. )
  148. self.gcode_form_layout.addRow(self.z_toolchange_label, self.z_toolchange_entry)
  149. # X,Y Toolchange location
  150. self.xy_toolchange_entry = FCEntry()
  151. self.xy_toolchange_label = QtWidgets.QLabel("XY Toolchange:")
  152. self.xy_toolchange_label.setToolTip(
  153. "The X,Y location for tool (nozzle) change.\n"
  154. "The format is (x, y) where x and y are real numbers."
  155. )
  156. self.gcode_form_layout.addRow(self.xy_toolchange_label, self.xy_toolchange_entry)
  157. # Feedrate X-Y
  158. self.frxy_entry = FCEntry()
  159. self.frxy_label = QtWidgets.QLabel("Feedrate X-Y:")
  160. self.frxy_label.setToolTip(
  161. "Feedrate (speed) while moving on the X-Y plane."
  162. )
  163. self.gcode_form_layout.addRow(self.frxy_label, self.frxy_entry)
  164. # Feedrate Z
  165. self.frz_entry = FCEntry()
  166. self.frz_label = QtWidgets.QLabel("Feedrate Z:")
  167. self.frz_label.setToolTip(
  168. "Feedrate (speed) while moving vertically\n"
  169. "(on Z plane)."
  170. )
  171. self.gcode_form_layout.addRow(self.frz_label, self.frz_entry)
  172. # Feedrate Z Dispense
  173. self.frz_dispense_entry = FCEntry()
  174. self.frz_dispense_label = QtWidgets.QLabel("Feedrate Z Dispense:")
  175. self.frz_dispense_label.setToolTip(
  176. "Feedrate (speed) while moving up vertically\n"
  177. " to Dispense position (on Z plane)."
  178. )
  179. self.gcode_form_layout.addRow(self.frz_dispense_label, self.frz_dispense_entry)
  180. # Spindle Speed Forward
  181. self.speedfwd_entry = FCEntry()
  182. self.speedfwd_label = QtWidgets.QLabel("Spindle Speed FWD:")
  183. self.speedfwd_label.setToolTip(
  184. "The dispenser speed while pushing solder paste\n"
  185. "through the dispenser nozzle."
  186. )
  187. self.gcode_form_layout.addRow(self.speedfwd_label, self.speedfwd_entry)
  188. # Dwell Forward
  189. self.dwellfwd_entry = FCEntry()
  190. self.dwellfwd_label = QtWidgets.QLabel("Dwell FWD:")
  191. self.dwellfwd_label.setToolTip(
  192. "Pause after solder dispensing."
  193. )
  194. self.gcode_form_layout.addRow(self.dwellfwd_label, self.dwellfwd_entry)
  195. # Spindle Speed Reverse
  196. self.speedrev_entry = FCEntry()
  197. self.speedrev_label = QtWidgets.QLabel("Spindle Speed REV:")
  198. self.speedrev_label.setToolTip(
  199. "The dispenser speed while retracting solder paste\n"
  200. "through the dispenser nozzle."
  201. )
  202. self.gcode_form_layout.addRow(self.speedrev_label, self.speedrev_entry)
  203. # Dwell Reverse
  204. self.dwellrev_entry = FCEntry()
  205. self.dwellrev_label = QtWidgets.QLabel("Dwell REV:")
  206. self.dwellrev_label.setToolTip(
  207. "Pause after solder paste dispenser retracted,\n"
  208. "to allow pressure equilibrium."
  209. )
  210. self.gcode_form_layout.addRow(self.dwellrev_label, self.dwellrev_entry)
  211. # Postprocessors
  212. pp_label = QtWidgets.QLabel('PostProcessors:')
  213. pp_label.setToolTip(
  214. "Files that control the GCode generation."
  215. )
  216. self.pp_combo = FCComboBox()
  217. self.pp_combo.setStyleSheet('background-color: rgb(255,255,255)')
  218. self.gcode_form_layout.addRow(pp_label, self.pp_combo)
  219. ## Buttons
  220. grid1 = QtWidgets.QGridLayout()
  221. self.gcode_box.addLayout(grid1)
  222. self.solder_gcode_btn = QtWidgets.QPushButton("Generate GCode")
  223. self.solder_gcode_btn.setToolTip(
  224. "Generate GCode for Solder Paste dispensing\n"
  225. "on PCB pads."
  226. )
  227. self.generation_frame = QtWidgets.QFrame()
  228. self.generation_frame.setContentsMargins(0, 0, 0, 0)
  229. self.layout.addWidget(self.generation_frame)
  230. self.generation_box = QtWidgets.QVBoxLayout()
  231. self.generation_box.setContentsMargins(0, 0, 0, 0)
  232. self.generation_frame.setLayout(self.generation_box)
  233. ## Buttons
  234. grid2 = QtWidgets.QGridLayout()
  235. self.generation_box.addLayout(grid2)
  236. step2_lbl = QtWidgets.QLabel("<b>STEP 2:</b>")
  237. step2_lbl.setToolTip(
  238. "Second step is to create a solder paste dispensing\n"
  239. "geometry out of an Solder Paste Mask Gerber file."
  240. )
  241. grid2.addWidget(step2_lbl, 0, 0)
  242. grid2.addWidget(self.soldergeo_btn, 0, 2)
  243. ## Form Layout
  244. geo_form_layout = QtWidgets.QFormLayout()
  245. self.generation_box.addLayout(geo_form_layout)
  246. ## Geometry Object to be used for solderpaste dispensing
  247. self.geo_obj_combo = FCComboBox(callback=self.on_rmb_combo)
  248. self.geo_obj_combo.setModel(self.app.collection)
  249. self.geo_obj_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  250. self.geo_obj_combo.setCurrentIndex(1)
  251. self.geo_object_label = QtWidgets.QLabel("Geo Result:")
  252. self.geo_object_label.setToolTip(
  253. "Geometry Solder Paste object.\n"
  254. "The name of the object has to end in:\n"
  255. "'_solderpaste' as a protection."
  256. )
  257. geo_form_layout.addRow(self.geo_object_label, self.geo_obj_combo)
  258. grid3 = QtWidgets.QGridLayout()
  259. self.generation_box.addLayout(grid3)
  260. step3_lbl = QtWidgets.QLabel("<b>STEP 3:</b>")
  261. step3_lbl.setToolTip(
  262. "Third step is to select a solder paste dispensing geometry,\n"
  263. "and then generate a CNCJob object.\n\n"
  264. "REMEMBER: if you want to create a CNCJob with new parameters,\n"
  265. "first you need to generate a geometry with those new params,\n"
  266. "and only after that you can generate an updated CNCJob."
  267. )
  268. grid3.addWidget(step3_lbl, 0, 0)
  269. grid3.addWidget(self.solder_gcode_btn, 0, 2)
  270. ## Form Layout
  271. cnc_form_layout = QtWidgets.QFormLayout()
  272. self.generation_box.addLayout(cnc_form_layout)
  273. ## Gerber Object to be used for solderpaste dispensing
  274. self.cnc_obj_combo = FCComboBox(callback=self.on_rmb_combo)
  275. self.cnc_obj_combo.setModel(self.app.collection)
  276. self.cnc_obj_combo.setRootModelIndex(self.app.collection.index(3, 0, QtCore.QModelIndex()))
  277. self.cnc_obj_combo.setCurrentIndex(1)
  278. self.cnc_object_label = QtWidgets.QLabel("CNC Result:")
  279. self.cnc_object_label.setToolTip(
  280. "CNCJob Solder paste object.\n"
  281. "In order to enable the GCode save section,\n"
  282. "the name of the object has to end in:\n"
  283. "'_solderpaste' as a protection."
  284. )
  285. cnc_form_layout.addRow(self.cnc_object_label, self.cnc_obj_combo)
  286. grid4 = QtWidgets.QGridLayout()
  287. self.generation_box.addLayout(grid4)
  288. self.solder_gcode_view_btn = QtWidgets.QPushButton("View GCode")
  289. self.solder_gcode_view_btn.setToolTip(
  290. "View the generated GCode for Solder Paste dispensing\n"
  291. "on PCB pads."
  292. )
  293. self.solder_gcode_save_btn = QtWidgets.QPushButton("Save GCode")
  294. self.solder_gcode_save_btn.setToolTip(
  295. "Save the generated GCode for Solder Paste dispensing\n"
  296. "on PCB pads, to a file."
  297. )
  298. step4_lbl = QtWidgets.QLabel("<b>STEP 4:</b>")
  299. step4_lbl.setToolTip(
  300. "Fourth step (and last) is to select a CNCJob made from \n"
  301. "a solder paste dispensing geometry, and then view/save it's GCode."
  302. )
  303. grid4.addWidget(step4_lbl, 0, 0)
  304. grid4.addWidget(self.solder_gcode_view_btn, 0, 2)
  305. grid4.addWidget(self.solder_gcode_save_btn, 1, 2)
  306. self.layout.addStretch()
  307. # self.gcode_frame.setDisabled(True)
  308. # self.save_gcode_frame.setDisabled(True)
  309. self.tooltable_tools = {}
  310. self.tooluid = 0
  311. self.options = LoudDict()
  312. self.form_fields = {}
  313. self.units = ''
  314. # this will be used in the combobox context menu, for delete entry
  315. self.obj_to_be_deleted_name = ''
  316. # action to be added in the combobox context menu
  317. self.combo_context_del_action = QtWidgets.QAction(QtGui.QIcon('share/trash16.png'), "Delete Object")
  318. ## Signals
  319. self.combo_context_del_action.triggered.connect(self.on_delete_object)
  320. self.addtool_btn.clicked.connect(self.on_tool_add)
  321. self.deltool_btn.clicked.connect(self.on_tool_delete)
  322. self.soldergeo_btn.clicked.connect(self.on_create_geo_click)
  323. self.solder_gcode_btn.clicked.connect(self.on_create_gcode_click)
  324. self.solder_gcode_view_btn.clicked.connect(self.on_view_gcode)
  325. self.solder_gcode_save_btn.clicked.connect(self.on_save_gcode)
  326. self.geo_obj_combo.currentIndexChanged.connect(self.on_geo_select)
  327. self.cnc_obj_combo.currentIndexChanged.connect(self.on_cncjob_select)
  328. self.app.object_status_changed.connect(self.update_comboboxes)
  329. def run(self):
  330. self.app.report_usage("ToolSolderPaste()")
  331. FlatCAMTool.run(self)
  332. self.set_tool_ui()
  333. self.build_ui()
  334. # if the splitter us hidden, display it
  335. if self.app.ui.splitter.sizes()[0] == 0:
  336. self.app.ui.splitter.setSizes([1, 1])
  337. self.app.ui.notebook.setTabText(2, "SolderPaste Tool")
  338. def install(self, icon=None, separator=None, **kwargs):
  339. FlatCAMTool.install(self, icon, separator, shortcut='ALT+K', **kwargs)
  340. def set_tool_ui(self):
  341. self.form_fields.update({
  342. "tools_solderpaste_new": self.addtool_entry,
  343. "tools_solderpaste_z_start": self.z_start_entry,
  344. "tools_solderpaste_z_dispense": self.z_dispense_entry,
  345. "tools_solderpaste_z_stop": self.z_stop_entry,
  346. "tools_solderpaste_z_travel": self.z_travel_entry,
  347. "tools_solderpaste_z_toolchange": self.z_toolchange_entry,
  348. "tools_solderpaste_xy_toolchange": self.xy_toolchange_entry,
  349. "tools_solderpaste_frxy": self.frxy_entry,
  350. "tools_solderpaste_frz": self.frz_entry,
  351. "tools_solderpaste_frz_dispense": self.frz_dispense_entry,
  352. "tools_solderpaste_speedfwd": self.speedfwd_entry,
  353. "tools_solderpaste_dwellfwd": self.dwellfwd_entry,
  354. "tools_solderpaste_speedrev": self.speedrev_entry,
  355. "tools_solderpaste_dwellrev": self.dwellrev_entry,
  356. "tools_solderpaste_pp": self.pp_combo
  357. })
  358. self.set_form_from_defaults()
  359. self.read_form_to_options()
  360. self.tools_table.setupContextMenu()
  361. self.tools_table.addContextMenu(
  362. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  363. self.tools_table.addContextMenu(
  364. "Delete", lambda:
  365. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  366. try:
  367. dias = [float(eval(dia)) for dia in self.app.defaults["tools_solderpaste_tools"].split(",")]
  368. except:
  369. log.error("At least one Nozzle tool diameter needed. "
  370. "Verify in Edit -> Preferences -> TOOLS -> Solder Paste Tools.")
  371. return
  372. self.tooluid = 0
  373. self.tooltable_tools.clear()
  374. for tool_dia in dias:
  375. self.tooluid += 1
  376. self.tooltable_tools.update({
  377. int(self.tooluid): {
  378. 'tooldia': float('%.4f' % tool_dia),
  379. 'data': deepcopy(self.options),
  380. 'solid_geometry': []
  381. }
  382. })
  383. self.name = ""
  384. self.obj = None
  385. self.units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  386. for name in list(self.app.postprocessors.keys()):
  387. # populate only with postprocessor files that start with 'Paste_'
  388. if name.partition('_')[0] != 'Paste':
  389. continue
  390. self.pp_combo.addItem(name)
  391. self.reset_fields()
  392. def build_ui(self):
  393. """
  394. Will rebuild the UI populating it (tools table)
  395. :return:
  396. """
  397. self.ui_disconnect()
  398. # updated units
  399. self.units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  400. sorted_tools = []
  401. for k, v in self.tooltable_tools.items():
  402. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  403. sorted_tools.sort(reverse=True)
  404. n = len(sorted_tools)
  405. self.tools_table.setRowCount(n)
  406. tool_id = 0
  407. for tool_sorted in sorted_tools:
  408. for tooluid_key, tooluid_value in self.tooltable_tools.items():
  409. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  410. tool_id += 1
  411. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  412. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  413. row_no = tool_id - 1
  414. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  415. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  416. # There are no drill bits in MM with more than 3 decimals diameter
  417. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  418. if self.units == 'MM':
  419. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  420. else:
  421. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  422. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  423. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  424. self.tools_table.setItem(row_no, 1, dia) # Diameter
  425. self.tools_table.setItem(row_no, 2, tool_uid_item) # Tool unique ID
  426. # make the diameter column editable
  427. for row in range(tool_id):
  428. self.tools_table.item(row, 1).setFlags(
  429. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  430. # all the tools are selected by default
  431. self.tools_table.selectColumn(0)
  432. #
  433. self.tools_table.resizeColumnsToContents()
  434. self.tools_table.resizeRowsToContents()
  435. vertical_header = self.tools_table.verticalHeader()
  436. vertical_header.hide()
  437. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  438. horizontal_header = self.tools_table.horizontalHeader()
  439. horizontal_header.setMinimumSectionSize(10)
  440. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  441. horizontal_header.resizeSection(0, 20)
  442. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  443. # self.tools_table.setSortingEnabled(True)
  444. # sort by tool diameter
  445. # self.tools_table.sortItems(1)
  446. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  447. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  448. self.ui_connect()
  449. def update_ui(self, row=None):
  450. """
  451. Will update the UI form with the data from obj.tools
  452. :param row: the row (tool) from which to extract information's used to populate the form
  453. :return:
  454. """
  455. self.ui_disconnect()
  456. if row is None:
  457. try:
  458. current_row = self.tools_table.currentRow()
  459. except:
  460. current_row = 0
  461. else:
  462. current_row = row
  463. if current_row < 0:
  464. current_row = 0
  465. # populate the form with the data from the tool associated with the row parameter
  466. try:
  467. tooluid = int(self.tools_table.item(current_row, 2).text())
  468. except Exception as e:
  469. log.debug("Tool missing. Add a tool in Tool Table. %s" % str(e))
  470. return
  471. # update the form
  472. try:
  473. # set the form with data from the newly selected tool
  474. for tooluid_key, tooluid_value in self.tooltable_tools.items():
  475. if int(tooluid_key) == tooluid:
  476. self.set_form(deepcopy(tooluid_value['data']))
  477. except Exception as e:
  478. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  479. self.ui_connect()
  480. def on_row_selection_change(self):
  481. self.update_ui()
  482. def ui_connect(self):
  483. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  484. # changes in geometry UI
  485. for i in range(self.gcode_form_layout.count()):
  486. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCComboBox):
  487. self.gcode_form_layout.itemAt(i).widget().currentIndexChanged.connect(self.read_form_to_tooldata)
  488. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCEntry):
  489. self.gcode_form_layout.itemAt(i).widget().editingFinished.connect(self.read_form_to_tooldata)
  490. self.tools_table.itemChanged.connect(self.on_tool_edit)
  491. self.tools_table.currentItemChanged.connect(self.on_row_selection_change)
  492. def ui_disconnect(self):
  493. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  494. try:
  495. for i in range(self.gcode_form_layout.count()):
  496. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCComboBox):
  497. self.gcode_form_layout.itemAt(i).widget().currentIndexChanged.disconnect()
  498. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCEntry):
  499. self.gcode_form_layout.itemAt(i).widget().editingFinished.disconnect()
  500. except:
  501. pass
  502. try:
  503. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  504. except:
  505. pass
  506. try:
  507. self.tools_table.currentItemChanged.disconnect(self.on_row_selection_change)
  508. except:
  509. pass
  510. def update_comboboxes(self, obj, status):
  511. """
  512. Modify the current text of the comboboxes to show the last object
  513. that was created.
  514. :param obj: object that was changed and called this PyQt slot
  515. :param status: what kind of change happened: 'append' or 'delete'
  516. :return:
  517. """
  518. obj_name = obj.options['name']
  519. if status == 'append':
  520. idx = self.obj_combo.findText(obj_name)
  521. if idx != -1:
  522. self.obj_combo.setCurrentIndex(idx)
  523. idx = self.geo_obj_combo.findText(obj_name)
  524. if idx != -1:
  525. self.geo_obj_combo.setCurrentIndex(idx)
  526. idx = self.cnc_obj_combo.findText(obj_name)
  527. if idx != -1:
  528. self.cnc_obj_combo.setCurrentIndex(idx)
  529. print(obj_name)
  530. def read_form_to_options(self):
  531. """
  532. Will read all the parameters from Solder Paste Tool UI and update the self.options dictionary
  533. :return:
  534. """
  535. for key in self.form_fields:
  536. self.options[key] = self.form_fields[key].get_value()
  537. def read_form_to_tooldata(self, tooluid=None):
  538. """
  539. Will read all the items in the UI form and set the self.tools data accordingly
  540. :param tooluid: the uid of the tool to be updated in the obj.tools
  541. :return:
  542. """
  543. current_row = self.tools_table.currentRow()
  544. uid = tooluid if tooluid else int(self.tools_table.item(current_row, 2).text())
  545. for key in self.form_fields:
  546. self.tooltable_tools[uid]['data'].update({
  547. key: self.form_fields[key].get_value()
  548. })
  549. def set_form_from_defaults(self):
  550. """
  551. Will read all the parameters of Solder Paste Tool from the app self.defaults and update the UI
  552. :return:
  553. """
  554. for key in self.form_fields:
  555. if key in self.app.defaults:
  556. self.form_fields[key].set_value(self.app.defaults[key])
  557. def set_form(self, val):
  558. """
  559. Will read all the parameters of Solder Paste Tool from the provided val parameter and update the UI
  560. :param val: dictionary with values to store in the form
  561. param_type: dictionary
  562. :return:
  563. """
  564. if not isinstance(val, dict):
  565. log.debug("ToolSoderPaste.set_form() --> parameter not a dict")
  566. return
  567. for key in self.form_fields:
  568. if key in val:
  569. self.form_fields[key].set_value(val[key])
  570. def on_tool_add(self, dia=None, muted=None):
  571. """
  572. Add a Tool in the Tool Table
  573. :param dia: diameter of the tool to be added
  574. :param muted: if True will not send status bar messages about adding tools
  575. :return:
  576. """
  577. self.ui_disconnect()
  578. if dia:
  579. tool_dia = dia
  580. else:
  581. try:
  582. tool_dia = float(self.addtool_entry.get_value())
  583. except ValueError:
  584. # try to convert comma to decimal point. if it's still not working error message and return
  585. try:
  586. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  587. except ValueError:
  588. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  589. "use a number.")
  590. return
  591. if tool_dia is None:
  592. self.build_ui()
  593. self.app.inform.emit("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format.")
  594. return
  595. if tool_dia == 0:
  596. self.app.inform.emit("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  597. return
  598. # construct a list of all 'tooluid' in the self.tooltable_tools
  599. tool_uid_list = []
  600. for tooluid_key in self.tooltable_tools:
  601. tool_uid_item = int(tooluid_key)
  602. tool_uid_list.append(tool_uid_item)
  603. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  604. if not tool_uid_list:
  605. max_uid = 0
  606. else:
  607. max_uid = max(tool_uid_list)
  608. self.tooluid = int(max_uid + 1)
  609. tool_dias = []
  610. for k, v in self.tooltable_tools.items():
  611. for tool_v in v.keys():
  612. if tool_v == 'tooldia':
  613. tool_dias.append(float('%.4f' % v[tool_v]))
  614. if float('%.4f' % tool_dia) in tool_dias:
  615. if muted is None:
  616. self.app.inform.emit("[WARNING_NOTCL]Adding Nozzle tool cancelled. Tool already in Tool Table.")
  617. self.tools_table.itemChanged.connect(self.on_tool_edit)
  618. return
  619. else:
  620. if muted is None:
  621. self.app.inform.emit("[success] New Nozzle tool added to Tool Table.")
  622. self.tooltable_tools.update({
  623. int(self.tooluid): {
  624. 'tooldia': float('%.4f' % tool_dia),
  625. 'data': deepcopy(self.options),
  626. 'solid_geometry': []
  627. }
  628. })
  629. self.build_ui()
  630. def on_tool_edit(self):
  631. """
  632. Edit a tool in the Tool Table
  633. :return:
  634. """
  635. self.ui_disconnect()
  636. tool_dias = []
  637. for k, v in self.tooltable_tools.items():
  638. for tool_v in v.keys():
  639. if tool_v == 'tooldia':
  640. tool_dias.append(float('%.4f' % v[tool_v]))
  641. for row in range(self.tools_table.rowCount()):
  642. try:
  643. new_tool_dia = float(self.tools_table.item(row, 1).text())
  644. except ValueError:
  645. # try to convert comma to decimal point. if it's still not working error message and return
  646. try:
  647. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  648. except ValueError:
  649. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  650. "use a number.")
  651. return
  652. tooluid = int(self.tools_table.item(row, 2).text())
  653. # identify the tool that was edited and get it's tooluid
  654. if new_tool_dia not in tool_dias:
  655. self.tooltable_tools[tooluid]['tooldia'] = new_tool_dia
  656. self.app.inform.emit("[success] Nozzle tool from Tool Table was edited.")
  657. self.build_ui()
  658. return
  659. else:
  660. # identify the old tool_dia and restore the text in tool table
  661. for k, v in self.tooltable_tools.items():
  662. if k == tooluid:
  663. old_tool_dia = v['tooldia']
  664. break
  665. restore_dia_item = self.tools_table.item(row, 1)
  666. restore_dia_item.setText(str(old_tool_dia))
  667. self.app.inform.emit("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table.")
  668. self.build_ui()
  669. def on_tool_delete(self, rows_to_delete=None, all=None):
  670. """
  671. Will delete tool(s) in the Tool Table
  672. :param rows_to_delete: tell which row (tool) to delete
  673. :param all: to delete all tools at once
  674. :return:
  675. """
  676. self.ui_disconnect()
  677. deleted_tools_list = []
  678. if all:
  679. self.tooltable_tools.clear()
  680. self.build_ui()
  681. return
  682. if rows_to_delete:
  683. try:
  684. for row in rows_to_delete:
  685. tooluid_del = int(self.tools_table.item(row, 2).text())
  686. deleted_tools_list.append(tooluid_del)
  687. except TypeError:
  688. deleted_tools_list.append(rows_to_delete)
  689. for t in deleted_tools_list:
  690. self.tooltable_tools.pop(t, None)
  691. self.build_ui()
  692. return
  693. try:
  694. if self.tools_table.selectedItems():
  695. for row_sel in self.tools_table.selectedItems():
  696. row = row_sel.row()
  697. if row < 0:
  698. continue
  699. tooluid_del = int(self.tools_table.item(row, 2).text())
  700. deleted_tools_list.append(tooluid_del)
  701. for t in deleted_tools_list:
  702. self.tooltable_tools.pop(t, None)
  703. except AttributeError:
  704. self.app.inform.emit("[WARNING_NOTCL] Delete failed. Select a Nozzle tool to delete.")
  705. return
  706. except Exception as e:
  707. log.debug(str(e))
  708. self.app.inform.emit("[success] Nozzle tool(s) deleted from Tool Table.")
  709. self.build_ui()
  710. def on_rmb_combo(self, pos, combo):
  711. """
  712. Will create a context menu on the combobox items
  713. :param pos: mouse click position passed by the signal that called this slot
  714. :param combo: the actual combo from where the signal was triggered
  715. :return:
  716. """
  717. view = combo.view
  718. idx = view.indexAt(pos)
  719. if not idx.isValid():
  720. return
  721. self.obj_to_be_deleted_name = combo.model().itemData(idx)[0]
  722. menu = QtWidgets.QMenu()
  723. menu.addAction(self.combo_context_del_action)
  724. menu.exec(view.mapToGlobal(pos))
  725. def on_delete_object(self):
  726. """
  727. Slot for the 'delete' action triggered in the combobox context menu.
  728. The name of the object to be deleted is collected when the combobox context menu is created.
  729. :return:
  730. """
  731. if self.obj_to_be_deleted_name != '':
  732. self.app.collection.set_active(self.obj_to_be_deleted_name)
  733. self.app.collection.delete_active(select_project=False)
  734. self.obj_to_be_deleted_name = ''
  735. def on_geo_select(self):
  736. # if self.geo_obj_combo.currentText().rpartition('_')[2] == 'solderpaste':
  737. # self.gcode_frame.setDisabled(False)
  738. # else:
  739. # self.gcode_frame.setDisabled(True)
  740. pass
  741. def on_cncjob_select(self):
  742. # if self.cnc_obj_combo.currentText().rpartition('_')[2] == 'solderpaste':
  743. # self.save_gcode_frame.setDisabled(False)
  744. # else:
  745. # self.save_gcode_frame.setDisabled(True)
  746. pass
  747. @staticmethod
  748. def distance(pt1, pt2):
  749. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  750. def on_create_geo_click(self, signal):
  751. """
  752. Will create a solderpaste dispensing geometry.
  753. :param signal: passed by the signal that called this slot
  754. :return:
  755. """
  756. name = self.obj_combo.currentText()
  757. if name == '':
  758. self.app.inform.emit("[WARNING_NOTCL] No SolderPaste mask Gerber object loaded.")
  759. return
  760. obj = self.app.collection.get_by_name(name)
  761. # update the self.options
  762. self.read_form_to_options()
  763. self.on_create_geo(name=name, work_object=obj)
  764. def on_create_geo(self, name, work_object):
  765. """
  766. The actual work for creating solderpaste dispensing geometry is done here.
  767. :param name: the outname for the resulting geometry object
  768. :param work_object: the source Gerber object from which the geometry is created
  769. :return: a Geometry type object
  770. """
  771. proc = self.app.proc_container.new("Creating Solder Paste dispensing geometry.")
  772. obj = work_object
  773. # Sort tools in descending order
  774. sorted_tools = []
  775. for k, v in self.tooltable_tools.items():
  776. # make sure that the tools diameter is more than zero and not zero
  777. if float(v['tooldia']) > 0:
  778. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  779. sorted_tools.sort(reverse=True)
  780. if not sorted_tools:
  781. self.app.inform.emit("[WARNING_NOTCL] No Nozzle tools in the tool table.")
  782. return 'fail'
  783. def geo_init(geo_obj, app_obj):
  784. geo_obj.options.update(self.options)
  785. geo_obj.solid_geometry = []
  786. geo_obj.tools = {}
  787. geo_obj.multigeo = True
  788. geo_obj.multitool = True
  789. geo_obj.special_group = 'solder_paste_tool'
  790. def solder_line(p, offset):
  791. xmin, ymin, xmax, ymax = p.bounds
  792. min = [xmin, ymin]
  793. max = [xmax, ymax]
  794. min_r = [xmin, ymax]
  795. max_r = [xmax, ymin]
  796. diagonal_1 = LineString([min, max])
  797. diagonal_2 = LineString([min_r, max_r])
  798. if self.units == 'MM':
  799. round_diag_1 = round(diagonal_1.intersection(p).length, 1)
  800. round_diag_2 = round(diagonal_2.intersection(p).length, 1)
  801. else:
  802. round_diag_1 = round(diagonal_1.intersection(p).length, 2)
  803. round_diag_2 = round(diagonal_2.intersection(p).length, 2)
  804. if round_diag_1 == round_diag_2:
  805. l = distance((xmin, ymin), (xmax, ymin))
  806. h = distance((xmin, ymin), (xmin, ymax))
  807. if offset >= l /2 or offset >= h / 2:
  808. return "fail"
  809. if l > h:
  810. h_half = h / 2
  811. start = [xmin, (ymin + h_half)]
  812. stop = [(xmin + l), (ymin + h_half)]
  813. else:
  814. l_half = l / 2
  815. start = [(xmin + l_half), ymin]
  816. stop = [(xmin + l_half), (ymin + h)]
  817. geo = LineString([start, stop])
  818. elif round_diag_1 > round_diag_2:
  819. geo = diagonal_1.intersection(p)
  820. else:
  821. geo = diagonal_2.intersection(p)
  822. offseted_poly = p.buffer(-offset)
  823. geo = geo.intersection(offseted_poly)
  824. return geo
  825. work_geo = obj.solid_geometry
  826. rest_geo = []
  827. tooluid = 1
  828. for tool in sorted_tools:
  829. offset = tool / 2
  830. for uid, v in self.tooltable_tools.items():
  831. if float('%.4f' % float(v['tooldia'])) == tool:
  832. tooluid = int(uid)
  833. break
  834. geo_obj.tools[tooluid] = {}
  835. geo_obj.tools[tooluid]['tooldia'] = tool
  836. geo_obj.tools[tooluid]['data'] = deepcopy(self.tooltable_tools[tooluid]['data'])
  837. geo_obj.tools[tooluid]['solid_geometry'] = []
  838. geo_obj.tools[tooluid]['offset'] = 'Path'
  839. geo_obj.tools[tooluid]['offset_value'] = 0.0
  840. geo_obj.tools[tooluid]['type'] = 'SolderPaste'
  841. geo_obj.tools[tooluid]['tool_type'] = 'DN'
  842. for g in work_geo:
  843. if type(g) == MultiPolygon:
  844. for poly in g:
  845. geom = solder_line(poly, offset=offset)
  846. if geom != 'fail':
  847. try:
  848. geo_obj.tools[tooluid]['solid_geometry'].append(geom)
  849. except Exception as e:
  850. log.debug('ToolSoderPaste.on_create_geo() --> %s' % str(e))
  851. else:
  852. rest_geo.append(poly)
  853. elif type(g) == Polygon:
  854. geom = solder_line(g, offset=offset)
  855. if geom != 'fail':
  856. try:
  857. geo_obj.tools[tooluid]['solid_geometry'].append(geom)
  858. except Exception as e:
  859. log.debug('ToolSoderPaste.on_create_geo() --> %s' % str(e))
  860. else:
  861. rest_geo.append(g)
  862. work_geo = deepcopy(rest_geo)
  863. rest_geo[:] = []
  864. if not work_geo:
  865. app_obj.inform.emit("[success] Solder Paste geometry generated successfully...")
  866. return
  867. # if we still have geometry not processed at the end of the tools then we failed
  868. # some or all the pads are not covered with solder paste
  869. if rest_geo:
  870. app_obj.inform.emit("[WARNING_NOTCL] Some or all pads have no solder "
  871. "due of inadequate nozzle diameters...")
  872. return 'fail'
  873. def job_thread(app_obj):
  874. try:
  875. app_obj.new_object("geometry", name + "_solderpaste", geo_init)
  876. except Exception as e:
  877. log.error("SolderPaste.on_create_geo() --> %s" % str(e))
  878. proc.done()
  879. return
  880. proc.done()
  881. self.app.inform.emit("Generating Solder Paste dispensing geometry...")
  882. # Promise object with the new name
  883. self.app.collection.promise(name)
  884. # Background
  885. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  886. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  887. def on_create_gcode_click(self, signal):
  888. """
  889. Will create a CNCJob object from the solderpaste dispensing geometry.
  890. :param signal: parameter passed by the signal that called this slot
  891. :return:
  892. """
  893. name = self.geo_obj_combo.currentText()
  894. obj = self.app.collection.get_by_name(name)
  895. if obj.special_group != 'solder_paste_tool':
  896. self.app.inform.emit("[WARNING_NOTCL]This Geometry can't be processed. NOT a solder_paste_tool geometry.")
  897. return 'fail'
  898. a = 0
  899. for tooluid_key in obj.tools:
  900. if obj.tools[tooluid_key]['solid_geometry'] is None:
  901. a += 1
  902. if a == len(obj.tools):
  903. self.app.inform.emit('[ERROR_NOTCL]Cancelled. Empty file, it has no geometry...')
  904. return 'fail'
  905. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  906. originar_name = obj.options['name'].partition('_')[0]
  907. outname = "%s_%s" % (originar_name, 'cnc_solderpaste')
  908. self.on_create_gcode(name=outname, workobject=obj)
  909. def on_create_gcode(self, name, workobject, use_thread=True):
  910. """
  911. Creates a multi-tool CNCJob. The actual work is done here.
  912. :param name: outname for the resulting CNCJob object
  913. :param workobject: the solderpaste dispensing Geometry object that is the source
  914. :param use_thread: True if threaded execution is desired
  915. :return:
  916. """
  917. obj = workobject
  918. try:
  919. xmin = obj.options['xmin']
  920. ymin = obj.options['ymin']
  921. xmax = obj.options['xmax']
  922. ymax = obj.options['ymax']
  923. except Exception as e:
  924. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  925. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  926. msg += 'FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s' % str(e)
  927. msg += traceback.format_exc()
  928. self.app.inform.emit(msg)
  929. return
  930. # Object initialization function for app.new_object()
  931. # RUNNING ON SEPARATE THREAD!
  932. def job_init(job_obj, app_obj):
  933. assert isinstance(job_obj, FlatCAMCNCjob), \
  934. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  935. tool_cnc_dict = {}
  936. # this turn on the FlatCAMCNCJob plot for multiple tools
  937. job_obj.multitool = True
  938. job_obj.multigeo = True
  939. job_obj.cnc_tools.clear()
  940. job_obj.special_group = 'solder_paste_tool'
  941. job_obj.options['xmin'] = xmin
  942. job_obj.options['ymin'] = ymin
  943. job_obj.options['xmax'] = xmax
  944. job_obj.options['ymax'] = ymax
  945. for tooluid_key, tooluid_value in obj.tools.items():
  946. app_obj.progress.emit(20)
  947. # find the tool_dia associated with the tooluid_key
  948. tool_dia = tooluid_value['tooldia']
  949. tool_cnc_dict = deepcopy(tooluid_value)
  950. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  951. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  952. job_obj.tool = int(tooluid_key)
  953. # Propagate options
  954. job_obj.options["tooldia"] = tool_dia
  955. job_obj.options['tool_dia'] = tool_dia
  956. ### CREATE GCODE ###
  957. res = job_obj.generate_gcode_from_solderpaste_geo(**tooluid_value)
  958. if res == 'fail':
  959. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  960. return 'fail'
  961. else:
  962. tool_cnc_dict['gcode'] = res
  963. ### PARSE GCODE ###
  964. tool_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  965. # TODO this serve for bounding box creation only; should be optimized
  966. tool_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in tool_cnc_dict['gcode_parsed']])
  967. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  968. # object is the source of gcode
  969. job_obj.toolchange_xy_type = "geometry"
  970. app_obj.progress.emit(80)
  971. job_obj.cnc_tools.update({
  972. tooluid_key: deepcopy(tool_cnc_dict)
  973. })
  974. tool_cnc_dict.clear()
  975. if use_thread:
  976. # To be run in separate thread
  977. def job_thread(app_obj):
  978. with self.app.proc_container.new("Generating CNC Code"):
  979. if app_obj.new_object("cncjob", name, job_init) != 'fail':
  980. app_obj.inform.emit("[success]ToolSolderPaste CNCjob created: %s" % name)
  981. app_obj.progress.emit(100)
  982. # Create a promise with the name
  983. self.app.collection.promise(name)
  984. # Send to worker
  985. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  986. else:
  987. self.app.new_object("cncjob", name, job_init)
  988. def on_view_gcode(self):
  989. """
  990. View GCode in the Editor Tab.
  991. :return:
  992. """
  993. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  994. # add the tab if it was closed
  995. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "Code Editor")
  996. # first clear previous text in text editor (if any)
  997. self.app.ui.code_editor.clear()
  998. # Switch plot_area to CNCJob tab
  999. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  1000. name = self.cnc_obj_combo.currentText()
  1001. obj = self.app.collection.get_by_name(name)
  1002. try:
  1003. if obj.special_group != 'solder_paste_tool':
  1004. self.app.inform.emit("[WARNING_NOTCL]This CNCJob object can't be processed. "
  1005. "NOT a solder_paste_tool CNCJob object.")
  1006. return
  1007. except AttributeError:
  1008. self.app.inform.emit("[WARNING_NOTCL]This CNCJob object can't be processed. "
  1009. "NOT a solder_paste_tool CNCJob object.")
  1010. return
  1011. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1012. (str(self.app.version), str(self.app.version_date)) + '\n'
  1013. gcode += '(Name: ' + str(name) + ')\n'
  1014. gcode += '(Type: ' + "G-code from " + str(obj.options['type']) + " for Solder Paste dispenser" + ')\n'
  1015. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1016. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1017. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1018. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1019. for tool in obj.cnc_tools:
  1020. gcode += obj.cnc_tools[tool]['gcode']
  1021. # then append the text from GCode to the text editor
  1022. try:
  1023. lines = StringIO(gcode)
  1024. except:
  1025. self.app.inform.emit("[ERROR_NOTCL] No Gcode in the object...")
  1026. return
  1027. try:
  1028. for line in lines:
  1029. proc_line = str(line).strip('\n')
  1030. self.app.ui.code_editor.append(proc_line)
  1031. except Exception as e:
  1032. log.debug('ToolSolderPaste.on_view_gcode() -->%s' % str(e))
  1033. self.app.inform.emit('[ERROR]ToolSolderPaste.on_view_gcode() -->%s' % str(e))
  1034. return
  1035. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  1036. self.app.handleTextChanged()
  1037. self.app.ui.show()
  1038. def on_save_gcode(self):
  1039. """
  1040. Save sodlerpaste dispensing GCode to a file on HDD.
  1041. :return:
  1042. """
  1043. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1044. name = self.cnc_obj_combo.currentText()
  1045. obj = self.app.collection.get_by_name(name)
  1046. if obj.special_group != 'solder_paste_tool':
  1047. self.app.inform.emit("[WARNING_NOTCL]This CNCJob object can't be processed. "
  1048. "NOT a solder_paste_tool CNCJob object.")
  1049. return
  1050. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  1051. "G-Code Files (*.g-code);;All Files (*.*)"
  1052. try:
  1053. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1054. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1055. caption="Export GCode ...",
  1056. directory=dir_file_to_save,
  1057. filter=_filter_
  1058. )
  1059. except TypeError:
  1060. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)
  1061. if filename == '':
  1062. self.app.inform.emit("[WARNING_NOTCL]Export Machine Code cancelled ...")
  1063. return
  1064. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1065. (str(self.app.version), str(self.app.version_date)) + '\n'
  1066. gcode += '(Name: ' + str(name) + ')\n'
  1067. gcode += '(Type: ' + "G-code from " + str(obj.options['type']) + " for Solder Paste dispenser" + ')\n'
  1068. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1069. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1070. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1071. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1072. for tool in obj.cnc_tools:
  1073. gcode += obj.cnc_tools[tool]['gcode']
  1074. lines = StringIO(gcode)
  1075. ## Write
  1076. if filename is not None:
  1077. try:
  1078. with open(filename, 'w') as f:
  1079. for line in lines:
  1080. f.write(line)
  1081. except FileNotFoundError:
  1082. self.app.inform.emit("[WARNING_NOTCL] No such file or directory")
  1083. return
  1084. self.app.file_saved.emit("gcode", filename)
  1085. self.app.inform.emit("[success] Solder paste dispenser GCode file saved to: %s" % filename)
  1086. def reset_fields(self):
  1087. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1088. self.geo_obj_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1089. self.cnc_obj_combo.setRootModelIndex(self.app.collection.index(3, 0, QtCore.QModelIndex()))