ToolSolderPaste.py 62 KB

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