ToolSolderPaste.py 54 KB

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