ToolSolderPaste.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  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 FlatCAMTool import FlatCAMTool
  8. from FlatCAMCommon import LoudDict
  9. from flatcamGUI.GUIElements import FCComboBox, FCEntry, FCTable, \
  10. FCInputDialog, FCDoubleSpinner, FCSpinner, FCFileSaveDialog
  11. from FlatCAMApp import log
  12. from camlib import distance
  13. from FlatCAMObj import FlatCAMCNCjob
  14. from flatcamEditors.FlatCAMTextEditor import TextEditor
  15. from PyQt5 import QtGui, QtCore, QtWidgets
  16. from PyQt5.QtCore import Qt
  17. from copy import deepcopy
  18. from datetime import datetime
  19. from shapely.geometry import Polygon, LineString
  20. from shapely.ops import cascaded_union
  21. import traceback
  22. from io import StringIO
  23. import gettext
  24. import FlatCAMTranslation as fcTranslate
  25. import builtins
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. class SolderPaste(FlatCAMTool):
  30. toolName = _("Solder Paste Tool")
  31. def __init__(self, app):
  32. FlatCAMTool.__init__(self, app)
  33. # Number of decimals to be used for tools/nozzles in this FlatCAM Tool
  34. self.decimals = self.app.decimals
  35. # ## Title
  36. title_label = QtWidgets.QLabel("%s" % self.toolName)
  37. title_label.setStyleSheet("""
  38. QLabel
  39. {
  40. font-size: 16px;
  41. font-weight: bold;
  42. }
  43. """)
  44. self.layout.addWidget(title_label)
  45. # ## Form Layout
  46. obj_form_layout = QtWidgets.QFormLayout()
  47. self.layout.addLayout(obj_form_layout)
  48. # ## Gerber Object to be used for solderpaste dispensing
  49. self.obj_combo = FCComboBox(callback=self.on_rmb_combo)
  50. self.obj_combo.setModel(self.app.collection)
  51. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  52. self.obj_combo.is_last = True
  53. self.obj_combo.obj_type = "Gerber"
  54. self.object_label = QtWidgets.QLabel("Gerber: ")
  55. self.object_label.setToolTip(
  56. _("Gerber Solder paste object. ")
  57. )
  58. obj_form_layout.addRow(self.object_label, self.obj_combo)
  59. # ### Tools ## ##
  60. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  61. self.tools_table_label.setToolTip(
  62. _("Tools pool from which the algorithm\n"
  63. "will pick the ones used for dispensing solder paste.")
  64. )
  65. self.layout.addWidget(self.tools_table_label)
  66. self.tools_table = FCTable()
  67. self.layout.addWidget(self.tools_table)
  68. self.tools_table.setColumnCount(3)
  69. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), ''])
  70. self.tools_table.setColumnHidden(2, True)
  71. self.tools_table.setSortingEnabled(False)
  72. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  73. self.tools_table.horizontalHeaderItem(0).setToolTip(
  74. _("This is the Tool Number.\n"
  75. "The solder dispensing will start with the tool with the biggest \n"
  76. "diameter, continuing until there are no more Nozzle tools.\n"
  77. "If there are no longer tools but there are still pads not covered\n "
  78. "with solder paste, the app will issue a warning message box.")
  79. )
  80. self.tools_table.horizontalHeaderItem(1).setToolTip(
  81. _("Nozzle tool Diameter. It's value (in current FlatCAM units)\n"
  82. "is the width of the solder paste dispensed."))
  83. # ### Add a new Tool ## ##
  84. hlay_tools = QtWidgets.QHBoxLayout()
  85. self.layout.addLayout(hlay_tools)
  86. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('New Nozzle Tool'))
  87. self.addtool_entry_lbl.setToolTip(
  88. _("Diameter for the new Nozzle tool to add in the Tool Table")
  89. )
  90. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  91. self.addtool_entry.set_range(0.0000001, 9999.9999)
  92. self.addtool_entry.set_precision(self.decimals)
  93. self.addtool_entry.setSingleStep(0.1)
  94. # hlay.addWidget(self.addtool_label)
  95. # hlay.addStretch()
  96. hlay_tools.addWidget(self.addtool_entry_lbl)
  97. hlay_tools.addWidget(self.addtool_entry)
  98. grid0 = QtWidgets.QGridLayout()
  99. self.layout.addLayout(grid0)
  100. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  101. self.addtool_btn.setToolTip(
  102. _("Add a new nozzle tool to the Tool Table\n"
  103. "with the diameter specified above.")
  104. )
  105. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  106. self.deltool_btn.setToolTip(
  107. _("Delete a selection of tools in the Tool Table\n"
  108. "by first selecting a row(s) in the Tool Table.")
  109. )
  110. self.soldergeo_btn = QtWidgets.QPushButton(_("Generate Geo"))
  111. self.soldergeo_btn.setToolTip(
  112. _("Generate solder paste dispensing geometry.")
  113. )
  114. self.soldergeo_btn.setStyleSheet("""
  115. QPushButton
  116. {
  117. font-weight: bold;
  118. }
  119. """)
  120. grid0.addWidget(self.addtool_btn, 0, 0)
  121. # grid2.addWidget(self.copytool_btn, 0, 1)
  122. grid0.addWidget(self.deltool_btn, 0, 2)
  123. self.layout.addSpacing(10)
  124. # ## Buttons
  125. grid0_1 = QtWidgets.QGridLayout()
  126. self.layout.addLayout(grid0_1)
  127. step1_lbl = QtWidgets.QLabel("<b>%s:</b>" % _('STEP 1'))
  128. step1_lbl.setToolTip(
  129. _("First step is to select a number of nozzle tools for usage\n"
  130. "and then optionally modify the GCode parameters bellow.")
  131. )
  132. step1_description_lbl = QtWidgets.QLabel(_("Select tools.\n"
  133. "Modify parameters."))
  134. grid0_1.addWidget(step1_lbl, 0, 0, alignment=Qt.AlignTop)
  135. grid0_1.addWidget(step1_description_lbl, 0, 2, alignment=Qt.AlignBottom)
  136. self.gcode_frame = QtWidgets.QFrame()
  137. self.gcode_frame.setContentsMargins(0, 0, 0, 0)
  138. self.layout.addWidget(self.gcode_frame)
  139. self.gcode_box = QtWidgets.QVBoxLayout()
  140. self.gcode_box.setContentsMargins(0, 0, 0, 0)
  141. self.gcode_frame.setLayout(self.gcode_box)
  142. # ## Form Layout
  143. self.gcode_form_layout = QtWidgets.QFormLayout()
  144. self.gcode_box.addLayout(self.gcode_form_layout)
  145. # Z dispense start
  146. self.z_start_entry = FCDoubleSpinner(callback=self.confirmation_message)
  147. self.z_start_entry.set_range(0.0000001, 9999.9999)
  148. self.z_start_entry.set_precision(self.decimals)
  149. self.z_start_entry.setSingleStep(0.1)
  150. self.z_start_label = QtWidgets.QLabel('%s:' % _("Z Dispense Start"))
  151. self.z_start_label.setToolTip(
  152. _("The height (Z) when solder paste dispensing starts.")
  153. )
  154. self.gcode_form_layout.addRow(self.z_start_label, self.z_start_entry)
  155. # Z dispense
  156. self.z_dispense_entry = FCDoubleSpinner(callback=self.confirmation_message)
  157. self.z_dispense_entry.set_range(0.0000001, 9999.9999)
  158. self.z_dispense_entry.set_precision(self.decimals)
  159. self.z_dispense_entry.setSingleStep(0.1)
  160. self.z_dispense_label = QtWidgets.QLabel('%s:' % _("Z Dispense"))
  161. self.z_dispense_label.setToolTip(
  162. _("The height (Z) when doing solder paste dispensing.")
  163. )
  164. self.gcode_form_layout.addRow(self.z_dispense_label, self.z_dispense_entry)
  165. # Z dispense stop
  166. self.z_stop_entry = FCDoubleSpinner(callback=self.confirmation_message)
  167. self.z_stop_entry.set_range(0.0000001, 9999.9999)
  168. self.z_stop_entry.set_precision(self.decimals)
  169. self.z_stop_entry.setSingleStep(0.1)
  170. self.z_stop_label = QtWidgets.QLabel('%s:' % _("Z Dispense Stop"))
  171. self.z_stop_label.setToolTip(
  172. _("The height (Z) when solder paste dispensing stops.")
  173. )
  174. self.gcode_form_layout.addRow(self.z_stop_label, self.z_stop_entry)
  175. # Z travel
  176. self.z_travel_entry = FCDoubleSpinner(callback=self.confirmation_message)
  177. self.z_travel_entry.set_range(0.0000001, 9999.9999)
  178. self.z_travel_entry.set_precision(self.decimals)
  179. self.z_travel_entry.setSingleStep(0.1)
  180. self.z_travel_label = QtWidgets.QLabel('%s:' % _("Z Travel"))
  181. self.z_travel_label.setToolTip(
  182. _("The height (Z) for travel between pads\n"
  183. "(without dispensing solder paste).")
  184. )
  185. self.gcode_form_layout.addRow(self.z_travel_label, self.z_travel_entry)
  186. # Z toolchange location
  187. self.z_toolchange_entry = FCDoubleSpinner(callback=self.confirmation_message)
  188. self.z_toolchange_entry.set_range(0.0000001, 9999.9999)
  189. self.z_toolchange_entry.set_precision(self.decimals)
  190. self.z_toolchange_entry.setSingleStep(0.1)
  191. self.z_toolchange_label = QtWidgets.QLabel('%s:' % _("Z Toolchange"))
  192. self.z_toolchange_label.setToolTip(
  193. _("The height (Z) for tool (nozzle) change.")
  194. )
  195. self.gcode_form_layout.addRow(self.z_toolchange_label, self.z_toolchange_entry)
  196. # X,Y Toolchange location
  197. self.xy_toolchange_entry = FCEntry()
  198. self.xy_toolchange_label = QtWidgets.QLabel('%s:' % _("Toolchange X-Y"))
  199. self.xy_toolchange_label.setToolTip(
  200. _("The X,Y location for tool (nozzle) change.\n"
  201. "The format is (x, y) where x and y are real numbers.")
  202. )
  203. self.gcode_form_layout.addRow(self.xy_toolchange_label, self.xy_toolchange_entry)
  204. # Feedrate X-Y
  205. self.frxy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  206. self.frxy_entry.set_range(0.0000, 99999.9999)
  207. self.frxy_entry.set_precision(self.decimals)
  208. self.frxy_entry.setSingleStep(0.1)
  209. self.frxy_label = QtWidgets.QLabel('%s:' % _("Feedrate X-Y"))
  210. self.frxy_label.setToolTip(
  211. _("Feedrate (speed) while moving on the X-Y plane.")
  212. )
  213. self.gcode_form_layout.addRow(self.frxy_label, self.frxy_entry)
  214. # Feedrate Z
  215. self.frz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  216. self.frz_entry.set_range(0.0000, 99999.9999)
  217. self.frz_entry.set_precision(self.decimals)
  218. self.frz_entry.setSingleStep(0.1)
  219. self.frz_label = QtWidgets.QLabel('%s:' % _("Feedrate Z"))
  220. self.frz_label.setToolTip(
  221. _("Feedrate (speed) while moving vertically\n"
  222. "(on Z plane).")
  223. )
  224. self.gcode_form_layout.addRow(self.frz_label, self.frz_entry)
  225. # Feedrate Z Dispense
  226. self.frz_dispense_entry = FCDoubleSpinner(callback=self.confirmation_message)
  227. self.frz_dispense_entry.set_range(0.0000, 99999.9999)
  228. self.frz_dispense_entry.set_precision(self.decimals)
  229. self.frz_dispense_entry.setSingleStep(0.1)
  230. self.frz_dispense_label = QtWidgets.QLabel('%s:' % _("Feedrate Z Dispense"))
  231. self.frz_dispense_label.setToolTip(
  232. _("Feedrate (speed) while moving up vertically\n"
  233. " to Dispense position (on Z plane).")
  234. )
  235. self.gcode_form_layout.addRow(self.frz_dispense_label, self.frz_dispense_entry)
  236. # Spindle Speed Forward
  237. self.speedfwd_entry = FCSpinner(callback=self.confirmation_message_int)
  238. self.speedfwd_entry.set_range(0, 999999)
  239. self.speedfwd_entry.set_step(1000)
  240. self.speedfwd_label = QtWidgets.QLabel('%s:' % _("Spindle Speed FWD"))
  241. self.speedfwd_label.setToolTip(
  242. _("The dispenser speed while pushing solder paste\n"
  243. "through the dispenser nozzle.")
  244. )
  245. self.gcode_form_layout.addRow(self.speedfwd_label, self.speedfwd_entry)
  246. # Dwell Forward
  247. self.dwellfwd_entry = FCDoubleSpinner(callback=self.confirmation_message)
  248. self.dwellfwd_entry.set_range(0.0000001, 9999.9999)
  249. self.dwellfwd_entry.set_precision(self.decimals)
  250. self.dwellfwd_entry.setSingleStep(0.1)
  251. self.dwellfwd_label = QtWidgets.QLabel('%s:' % _("Dwell FWD"))
  252. self.dwellfwd_label.setToolTip(
  253. _("Pause after solder dispensing.")
  254. )
  255. self.gcode_form_layout.addRow(self.dwellfwd_label, self.dwellfwd_entry)
  256. # Spindle Speed Reverse
  257. self.speedrev_entry = FCSpinner(callback=self.confirmation_message_int)
  258. self.speedrev_entry.set_range(0, 999999)
  259. self.speedrev_entry.set_step(1000)
  260. self.speedrev_label = QtWidgets.QLabel('%s:' % _("Spindle Speed REV"))
  261. self.speedrev_label.setToolTip(
  262. _("The dispenser speed while retracting solder paste\n"
  263. "through the dispenser nozzle.")
  264. )
  265. self.gcode_form_layout.addRow(self.speedrev_label, self.speedrev_entry)
  266. # Dwell Reverse
  267. self.dwellrev_entry = FCDoubleSpinner(callback=self.confirmation_message)
  268. self.dwellrev_entry.set_range(0.0000001, 9999.9999)
  269. self.dwellrev_entry.set_precision(self.decimals)
  270. self.dwellrev_entry.setSingleStep(0.1)
  271. self.dwellrev_label = QtWidgets.QLabel('%s:' % _("Dwell REV"))
  272. self.dwellrev_label.setToolTip(
  273. _("Pause after solder paste dispenser retracted,\n"
  274. "to allow pressure equilibrium.")
  275. )
  276. self.gcode_form_layout.addRow(self.dwellrev_label, self.dwellrev_entry)
  277. # Preprocessors
  278. pp_label = QtWidgets.QLabel('%s:' % _('Preprocessor'))
  279. pp_label.setToolTip(
  280. _("Files that control the GCode generation.")
  281. )
  282. self.pp_combo = FCComboBox()
  283. # self.pp_combo.setStyleSheet('background-color: rgb(255,255,255)')
  284. self.gcode_form_layout.addRow(pp_label, self.pp_combo)
  285. # ## Buttons
  286. # grid1 = QtWidgets.QGridLayout()
  287. # self.gcode_box.addLayout(grid1)
  288. self.solder_gcode_btn = QtWidgets.QPushButton(_("Generate GCode"))
  289. self.solder_gcode_btn.setToolTip(
  290. _("Generate GCode for Solder Paste dispensing\n"
  291. "on PCB pads.")
  292. )
  293. self.solder_gcode_btn.setStyleSheet("""
  294. QPushButton
  295. {
  296. font-weight: bold;
  297. }
  298. """)
  299. self.generation_frame = QtWidgets.QFrame()
  300. self.generation_frame.setContentsMargins(0, 0, 0, 0)
  301. self.layout.addWidget(self.generation_frame)
  302. self.generation_box = QtWidgets.QVBoxLayout()
  303. self.generation_box.setContentsMargins(0, 0, 0, 0)
  304. self.generation_frame.setLayout(self.generation_box)
  305. # ## Buttons
  306. grid2 = QtWidgets.QGridLayout()
  307. self.generation_box.addLayout(grid2)
  308. step2_lbl = QtWidgets.QLabel("<b>%s:</b>" % _('STEP 2'))
  309. step2_lbl.setToolTip(
  310. _("Second step is to create a solder paste dispensing\n"
  311. "geometry out of an Solder Paste Mask Gerber file.")
  312. )
  313. grid2.addWidget(step2_lbl, 0, 0)
  314. grid2.addWidget(self.soldergeo_btn, 0, 2)
  315. # ## Form Layout
  316. geo_form_layout = QtWidgets.QFormLayout()
  317. self.generation_box.addLayout(geo_form_layout)
  318. # ## Geometry Object to be used for solderpaste dispensing
  319. self.geo_obj_combo = FCComboBox(callback=self.on_rmb_combo)
  320. self.geo_obj_combo.setModel(self.app.collection)
  321. self.geo_obj_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  322. self.geo_obj_combo.is_last = True
  323. self.geo_obj_combo.obj_type = "Geometry"
  324. self.geo_object_label = QtWidgets.QLabel('%s:' % _("Geo Result"))
  325. self.geo_object_label.setToolTip(
  326. _("Geometry Solder Paste object.\n"
  327. "The name of the object has to end in:\n"
  328. "'_solderpaste' as a protection.")
  329. )
  330. geo_form_layout.addRow(self.geo_object_label, self.geo_obj_combo)
  331. grid3 = QtWidgets.QGridLayout()
  332. self.generation_box.addLayout(grid3)
  333. step3_lbl = QtWidgets.QLabel("<b>%s:</b>" % _('STEP 3'))
  334. step3_lbl.setToolTip(
  335. _("Third step is to select a solder paste dispensing geometry,\n"
  336. "and then generate a CNCJob object.\n\n"
  337. "REMEMBER: if you want to create a CNCJob with new parameters,\n"
  338. "first you need to generate a geometry with those new params,\n"
  339. "and only after that you can generate an updated CNCJob.")
  340. )
  341. grid3.addWidget(step3_lbl, 0, 0)
  342. grid3.addWidget(self.solder_gcode_btn, 0, 2)
  343. # ## Form Layout
  344. cnc_form_layout = QtWidgets.QFormLayout()
  345. self.generation_box.addLayout(cnc_form_layout)
  346. # ## Gerber Object to be used for solderpaste dispensing
  347. self.cnc_obj_combo = FCComboBox(callback=self.on_rmb_combo)
  348. self.cnc_obj_combo.setModel(self.app.collection)
  349. self.cnc_obj_combo.setRootModelIndex(self.app.collection.index(3, 0, QtCore.QModelIndex()))
  350. self.cnc_obj_combo.is_last = True
  351. self.geo_obj_combo.obj_type = "CNCJob"
  352. self.cnc_object_label = QtWidgets.QLabel('%s:' % _("CNC Result"))
  353. self.cnc_object_label.setToolTip(
  354. _("CNCJob Solder paste object.\n"
  355. "In order to enable the GCode save section,\n"
  356. "the name of the object has to end in:\n"
  357. "'_solderpaste' as a protection.")
  358. )
  359. cnc_form_layout.addRow(self.cnc_object_label, self.cnc_obj_combo)
  360. grid4 = QtWidgets.QGridLayout()
  361. self.generation_box.addLayout(grid4)
  362. self.solder_gcode_view_btn = QtWidgets.QPushButton(_("View GCode"))
  363. self.solder_gcode_view_btn.setToolTip(
  364. _("View the generated GCode for Solder Paste dispensing\n"
  365. "on PCB pads.")
  366. )
  367. self.solder_gcode_view_btn.setStyleSheet("""
  368. QPushButton
  369. {
  370. font-weight: bold;
  371. }
  372. """)
  373. self.solder_gcode_save_btn = QtWidgets.QPushButton(_("Save GCode"))
  374. self.solder_gcode_save_btn.setToolTip(
  375. _("Save the generated GCode for Solder Paste dispensing\n"
  376. "on PCB pads, to a file.")
  377. )
  378. self.solder_gcode_save_btn.setStyleSheet("""
  379. QPushButton
  380. {
  381. font-weight: bold;
  382. }
  383. """)
  384. step4_lbl = QtWidgets.QLabel("<b>%s:</b>" % _('STEP 4'))
  385. step4_lbl.setToolTip(
  386. _("Fourth step (and last) is to select a CNCJob made from \n"
  387. "a solder paste dispensing geometry, and then view/save it's GCode.")
  388. )
  389. grid4.addWidget(step4_lbl, 0, 0)
  390. grid4.addWidget(self.solder_gcode_view_btn, 0, 2)
  391. grid4.addWidget(self.solder_gcode_save_btn, 1, 0, 1, 3)
  392. self.layout.addStretch()
  393. # ## Reset Tool
  394. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  395. self.reset_button.setToolTip(
  396. _("Will reset the tool parameters.")
  397. )
  398. self.reset_button.setStyleSheet("""
  399. QPushButton
  400. {
  401. font-weight: bold;
  402. }
  403. """)
  404. self.layout.addWidget(self.reset_button)
  405. # self.gcode_frame.setDisabled(True)
  406. # self.save_gcode_frame.setDisabled(True)
  407. self.tooltable_tools = {}
  408. self.tooluid = 0
  409. self.options = LoudDict()
  410. self.form_fields = {}
  411. self.units = ''
  412. self.name = ""
  413. self.obj = None
  414. self.text_editor_tab = None
  415. # this will be used in the combobox context menu, for delete entry
  416. self.obj_to_be_deleted_name = ''
  417. # stpre here the flattened geometry
  418. self.flat_geometry = []
  419. # action to be added in the combobox context menu
  420. self.combo_context_del_action = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/trash16.png'), _("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.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. FlatCAMTool.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. FlatCAMTool.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. # identify the old tool_dia and restore the text in tool table
  805. for k, v in self.tooltable_tools.items():
  806. if k == tooluid:
  807. old_tool_dia = v['tooldia']
  808. break
  809. restore_dia_item = self.tools_table.item(row, 1)
  810. restore_dia_item.setText(str(old_tool_dia))
  811. self.app.inform.emit('[WARNING_NOTCL] %s' %
  812. _("Cancelled. New diameter value is already in the Tool Table."))
  813. self.build_ui()
  814. def on_tool_delete(self, rows_to_delete=None, all=None):
  815. """
  816. Will delete tool(s) in the Tool Table
  817. :param rows_to_delete: tell which row (tool) to delete
  818. :param all: to delete all tools at once
  819. :return:
  820. """
  821. self.ui_disconnect()
  822. deleted_tools_list = []
  823. if all:
  824. self.tooltable_tools.clear()
  825. self.build_ui()
  826. return
  827. if rows_to_delete:
  828. try:
  829. for row in rows_to_delete:
  830. tooluid_del = int(self.tools_table.item(row, 2).text())
  831. deleted_tools_list.append(tooluid_del)
  832. except TypeError:
  833. deleted_tools_list.append(rows_to_delete)
  834. for t in deleted_tools_list:
  835. self.tooltable_tools.pop(t, None)
  836. self.build_ui()
  837. return
  838. try:
  839. if self.tools_table.selectedItems():
  840. for row_sel in self.tools_table.selectedItems():
  841. row = row_sel.row()
  842. if row < 0:
  843. continue
  844. tooluid_del = int(self.tools_table.item(row, 2).text())
  845. deleted_tools_list.append(tooluid_del)
  846. for t in deleted_tools_list:
  847. self.tooltable_tools.pop(t, None)
  848. except AttributeError:
  849. self.app.inform.emit('[WARNING_NOTCL] %s' %
  850. _("Delete failed. Select a Nozzle tool to delete."))
  851. return
  852. except Exception as e:
  853. log.debug(str(e))
  854. self.app.inform.emit('[success] %s' %
  855. _("Nozzle tool(s) deleted from Tool Table."))
  856. self.build_ui()
  857. def on_rmb_combo(self, pos, combo):
  858. """
  859. Will create a context menu on the combobox items
  860. :param pos: mouse click position passed by the signal that called this slot
  861. :param combo: the actual combo from where the signal was triggered
  862. :return:
  863. """
  864. view = combo.view
  865. idx = view.indexAt(pos)
  866. if not idx.isValid():
  867. return
  868. self.obj_to_be_deleted_name = combo.model().itemData(idx)[0]
  869. menu = QtWidgets.QMenu()
  870. menu.addAction(self.combo_context_del_action)
  871. menu.exec(view.mapToGlobal(pos))
  872. def on_delete_object(self):
  873. """
  874. Slot for the 'delete' action triggered in the combobox context menu.
  875. The name of the object to be deleted is collected when the combobox context menu is created.
  876. :return:
  877. """
  878. if self.obj_to_be_deleted_name != '':
  879. self.app.collection.set_active(self.obj_to_be_deleted_name)
  880. self.app.collection.delete_active(select_project=False)
  881. self.obj_to_be_deleted_name = ''
  882. def on_geo_select(self):
  883. # if self.geo_obj_combo.currentText().rpartition('_')[2] == 'solderpaste':
  884. # self.gcode_frame.setDisabled(False)
  885. # else:
  886. # self.gcode_frame.setDisabled(True)
  887. pass
  888. def on_cncjob_select(self):
  889. # if self.cnc_obj_combo.currentText().rpartition('_')[2] == 'solderpaste':
  890. # self.save_gcode_frame.setDisabled(False)
  891. # else:
  892. # self.save_gcode_frame.setDisabled(True)
  893. pass
  894. def on_create_geo_click(self, signal):
  895. """
  896. Will create a solderpaste dispensing geometry.
  897. :param signal: passed by the signal that called this slot
  898. :return:
  899. """
  900. name = self.obj_combo.currentText()
  901. if name == '':
  902. self.app.inform.emit('[WARNING_NOTCL] %s' %
  903. _("No SolderPaste mask Gerber object loaded."))
  904. return
  905. obj = self.app.collection.get_by_name(name)
  906. # update the self.options
  907. self.read_form_to_options()
  908. self.on_create_geo(name=name, work_object=obj)
  909. def on_create_geo(self, name, work_object, use_thread=True):
  910. """
  911. The actual work for creating solderpaste dispensing geometry is done here.
  912. :param name: the outname for the resulting geometry object
  913. :param work_object: the source Gerber object from which the geometry is created
  914. :param use_thread: use thread, True or False
  915. :return: a Geometry type object
  916. """
  917. proc = self.app.proc_container.new(_("Creating Solder Paste dispensing geometry."))
  918. obj = work_object
  919. # Sort tools in descending order
  920. sorted_tools = []
  921. for k, v in self.tooltable_tools.items():
  922. # make sure that the tools diameter is more than zero and not zero
  923. if float(v['tooldia']) > 0:
  924. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  925. sorted_tools.sort(reverse=True)
  926. if not sorted_tools:
  927. self.app.inform.emit('[WARNING_NOTCL] %s' %
  928. _("No Nozzle tools in the tool table."))
  929. return 'fail'
  930. def flatten(geometry=None, reset=True, pathonly=False):
  931. """
  932. Creates a list of non-iterable linear geometry objects.
  933. Polygons are expanded into its exterior pathonly param if specified.
  934. Results are placed in flat_geometry
  935. :param geometry: Shapely type or list or list of list of such.
  936. :param reset: Clears the contents of self.flat_geometry.
  937. :param pathonly: Expands polygons into linear elements from the exterior attribute.
  938. """
  939. if reset:
  940. self.flat_geometry = []
  941. # ## If iterable, expand recursively.
  942. try:
  943. for geo in geometry:
  944. if geo is not None:
  945. flatten(geometry=geo,
  946. reset=False,
  947. pathonly=pathonly)
  948. # ## Not iterable, do the actual indexing and add.
  949. except TypeError:
  950. if pathonly and type(geometry) == Polygon:
  951. self.flat_geometry.append(geometry.exterior)
  952. else:
  953. self.flat_geometry.append(geometry)
  954. return self.flat_geometry
  955. # TODO when/if the Gerber files will have solid_geometry in the self.apertures I will have to take care here
  956. flatten(geometry=obj.solid_geometry, pathonly=True)
  957. def geo_init(geo_obj, app_obj):
  958. geo_obj.options.update(self.options)
  959. geo_obj.solid_geometry = []
  960. geo_obj.tools = {}
  961. geo_obj.multigeo = True
  962. geo_obj.multitool = True
  963. geo_obj.special_group = 'solder_paste_tool'
  964. geo = LineString()
  965. work_geo = self.flat_geometry
  966. rest_geo = []
  967. tooluid = 1
  968. for tool in sorted_tools:
  969. offset = tool / 2
  970. for uid, vl in self.tooltable_tools.items():
  971. if float('%.*f' % (self.decimals, float(vl['tooldia']))) == tool:
  972. tooluid = int(uid)
  973. break
  974. geo_obj.tools[tooluid] = {}
  975. geo_obj.tools[tooluid]['tooldia'] = tool
  976. geo_obj.tools[tooluid]['data'] = deepcopy(self.tooltable_tools[tooluid]['data'])
  977. geo_obj.tools[tooluid]['solid_geometry'] = []
  978. geo_obj.tools[tooluid]['offset'] = 'Path'
  979. geo_obj.tools[tooluid]['offset_value'] = 0.0
  980. geo_obj.tools[tooluid]['type'] = 'SolderPaste'
  981. geo_obj.tools[tooluid]['tool_type'] = 'DN'
  982. # self.flat_geometry is a list of LinearRings produced by flatten() from the exteriors of the Polygons
  983. # We get possible issues if we try to directly use the Polygons, due of possible the interiors,
  984. # so we do a hack: get first the exterior in a form of LinearRings and then convert back to Polygon
  985. # because intersection does not work on LinearRings
  986. for g in work_geo:
  987. # for whatever reason intersection on LinearRings does not work so we convert back to Polygons
  988. poly = Polygon(g)
  989. x_min, y_min, x_max, y_max = poly.bounds
  990. diag_1_intersect = LineString([(x_min, y_min), (x_max, y_max)]).intersection(poly)
  991. diag_2_intersect = LineString([(x_min, y_max), (x_max, y_min)]).intersection(poly)
  992. if self.units == 'MM':
  993. round_diag_1 = round(diag_1_intersect.length, 1)
  994. round_diag_2 = round(diag_2_intersect.length, 1)
  995. else:
  996. round_diag_1 = round(diag_1_intersect.length, 2)
  997. round_diag_2 = round(diag_2_intersect.length, 2)
  998. if round_diag_1 == round_diag_2:
  999. length = distance((x_min, y_min), (x_max, y_min))
  1000. h = distance((x_min, y_min), (x_min, y_max))
  1001. if offset >= length / 2 or offset >= h / 2:
  1002. pass
  1003. else:
  1004. if length > h:
  1005. h_half = h / 2
  1006. start = [x_min, (y_min + h_half)]
  1007. stop = [(x_min + length), (y_min + h_half)]
  1008. geo = LineString([start, stop])
  1009. else:
  1010. l_half = length / 2
  1011. start = [(x_min + l_half), y_min]
  1012. stop = [(x_min + l_half), (y_min + h)]
  1013. geo = LineString([start, stop])
  1014. elif round_diag_1 > round_diag_2:
  1015. geo = diag_1_intersect
  1016. else:
  1017. geo = diag_2_intersect
  1018. offseted_poly = poly.buffer(-offset)
  1019. geo = geo.intersection(offseted_poly)
  1020. if not geo.is_empty:
  1021. try:
  1022. geo_obj.tools[tooluid]['solid_geometry'].append(geo)
  1023. except Exception as e:
  1024. log.debug('ToolSolderPaste.on_create_geo() --> %s' % str(e))
  1025. else:
  1026. rest_geo.append(g)
  1027. work_geo = deepcopy(rest_geo)
  1028. rest_geo[:] = []
  1029. if not work_geo:
  1030. a = 0
  1031. for tooluid_key in geo_obj.tools:
  1032. if not geo_obj.tools[tooluid_key]['solid_geometry']:
  1033. a += 1
  1034. if a == len(geo_obj.tools):
  1035. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Cancelled. Empty file, it has no geometry...'))
  1036. return 'fail'
  1037. app_obj.inform.emit('[success] %s...' % _("Solder Paste geometry generated successfully"))
  1038. return
  1039. # if we still have geometry not processed at the end of the tools then we failed
  1040. # some or all the pads are not covered with solder paste
  1041. if work_geo:
  1042. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  1043. _("Some or all pads have no solder "
  1044. "due of inadequate nozzle diameters..."))
  1045. return 'fail'
  1046. if use_thread:
  1047. def job_thread(app_obj):
  1048. try:
  1049. app_obj.new_object("geometry", name + "_solderpaste", geo_init)
  1050. except Exception as e:
  1051. log.error("SolderPaste.on_create_geo() --> %s" % str(e))
  1052. proc.done()
  1053. return
  1054. proc.done()
  1055. self.app.inform.emit(_("Generating Solder Paste dispensing geometry..."))
  1056. # Promise object with the new name
  1057. self.app.collection.promise(name)
  1058. # Background
  1059. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1060. else:
  1061. self.app.new_object("geometry", name + "_solderpaste", geo_init)
  1062. def on_create_gcode_click(self, signal):
  1063. """
  1064. Will create a CNCJob object from the solderpaste dispensing geometry.
  1065. :param signal: parameter passed by the signal that called this slot
  1066. :return:
  1067. """
  1068. name = self.geo_obj_combo.currentText()
  1069. obj = self.app.collection.get_by_name(name)
  1070. if name == '':
  1071. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Geometry object available."))
  1072. return 'fail'
  1073. if obj.special_group != 'solder_paste_tool':
  1074. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1075. _("This Geometry can't be processed. "
  1076. "NOT a solder_paste_tool geometry."))
  1077. return 'fail'
  1078. a = 0
  1079. for tooluid_key in obj.tools:
  1080. if obj.tools[tooluid_key]['solid_geometry'] is None:
  1081. a += 1
  1082. if a == len(obj.tools):
  1083. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('Cancelled. Empty file, it has no geometry'))
  1084. return 'fail'
  1085. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  1086. originar_name = obj.options['name'].partition('_')[0]
  1087. outname = "%s_%s" % (originar_name, 'cnc_solderpaste')
  1088. self.on_create_gcode(name=outname, workobject=obj)
  1089. def on_create_gcode(self, name, workobject, use_thread=True):
  1090. """
  1091. Creates a multi-tool CNCJob. The actual work is done here.
  1092. :param name: outname for the resulting CNCJob object
  1093. :param workobject: the solderpaste dispensing Geometry object that is the source
  1094. :param use_thread: True if threaded execution is desired
  1095. :return:
  1096. """
  1097. obj = workobject
  1098. try:
  1099. xmin = obj.options['xmin']
  1100. ymin = obj.options['ymin']
  1101. xmax = obj.options['xmax']
  1102. ymax = obj.options['ymax']
  1103. except Exception as e:
  1104. log.debug("SolderPaste.on_create_gcode() --> %s\n" % str(e))
  1105. msg = '[ERROR] %s' % _("An internal error has ocurred. See shell.\n")
  1106. msg += 'SolderPaste.on_create_gcode() --> %s' % str(e)
  1107. msg += traceback.format_exc()
  1108. self.app.inform.emit(msg)
  1109. return
  1110. # Object initialization function for app.new_object()
  1111. # RUNNING ON SEPARATE THREAD!
  1112. def job_init(job_obj, app_obj):
  1113. assert isinstance(job_obj, FlatCAMCNCjob), \
  1114. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1115. # this turn on the FlatCAMCNCJob plot for multiple tools
  1116. job_obj.multitool = True
  1117. job_obj.multigeo = True
  1118. job_obj.cnc_tools.clear()
  1119. job_obj.special_group = 'solder_paste_tool'
  1120. job_obj.options['xmin'] = xmin
  1121. job_obj.options['ymin'] = ymin
  1122. job_obj.options['xmax'] = xmax
  1123. job_obj.options['ymax'] = ymax
  1124. for tooluid_key, tooluid_value in obj.tools.items():
  1125. # find the tool_dia associated with the tooluid_key
  1126. tool_dia = tooluid_value['tooldia']
  1127. tool_cnc_dict = deepcopy(tooluid_value)
  1128. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1129. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1130. job_obj.tool = int(tooluid_key)
  1131. # Propagate options
  1132. job_obj.options["tooldia"] = tool_dia
  1133. job_obj.options['tool_dia'] = tool_dia
  1134. # ## CREATE GCODE # ##
  1135. res = job_obj.generate_gcode_from_solderpaste_geo(**tooluid_value)
  1136. if res == 'fail':
  1137. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  1138. return 'fail'
  1139. else:
  1140. tool_cnc_dict['gcode'] = res
  1141. # ## PARSE GCODE # ##
  1142. tool_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  1143. # TODO this serve for bounding box creation only; should be optimized
  1144. tool_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in tool_cnc_dict['gcode_parsed']])
  1145. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  1146. # object is the source of gcode
  1147. job_obj.toolchange_xy_type = "geometry"
  1148. job_obj.cnc_tools.update({
  1149. tooluid_key: deepcopy(tool_cnc_dict)
  1150. })
  1151. tool_cnc_dict.clear()
  1152. if use_thread:
  1153. # To be run in separate thread
  1154. def job_thread(app_obj):
  1155. with self.app.proc_container.new("Generating CNC Code"):
  1156. if app_obj.new_object("cncjob", name, job_init) != 'fail':
  1157. app_obj.inform.emit('[success] [success] %s: %s' %
  1158. (_("ToolSolderPaste CNCjob created"), name))
  1159. # Create a promise with the name
  1160. self.app.collection.promise(name)
  1161. # Send to worker
  1162. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1163. else:
  1164. self.app.new_object("cncjob", name, job_init)
  1165. def on_view_gcode(self):
  1166. """
  1167. View GCode in the Editor Tab.
  1168. :return:
  1169. """
  1170. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1171. self.text_editor_tab = TextEditor(app=self.app)
  1172. # add the tab if it was closed
  1173. self.app.ui.plot_tab_area.addTab(self.text_editor_tab, _("SP GCode Editor"))
  1174. self.text_editor_tab.setObjectName('solderpaste_gcode_editor_tab')
  1175. # Switch plot_area to CNCJob tab
  1176. self.app.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  1177. name = self.cnc_obj_combo.currentText()
  1178. obj = self.app.collection.get_by_name(name)
  1179. try:
  1180. if obj.special_group != 'solder_paste_tool':
  1181. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1182. _("This CNCJob object can't be processed. "
  1183. "NOT a solder_paste_tool CNCJob object."))
  1184. return
  1185. except AttributeError:
  1186. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1187. _("This CNCJob object can't be processed. "
  1188. "NOT a solder_paste_tool CNCJob object."))
  1189. return
  1190. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1191. (str(self.app.version), str(self.app.version_date)) + '\n'
  1192. gcode += '(Name: ' + str(name) + ')\n'
  1193. gcode += '(Type: ' + "G-code from " + str(obj.options['type']) + " for Solder Paste dispenser" + ')\n'
  1194. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1195. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1196. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1197. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1198. for tool in obj.cnc_tools:
  1199. gcode += obj.cnc_tools[tool]['gcode']
  1200. # then append the text from GCode to the text editor
  1201. try:
  1202. lines = StringIO(gcode)
  1203. except Exception as e:
  1204. log.debug("ToolSolderpaste.on_view_gcode() --> %s" % str(e))
  1205. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  1206. _("No Gcode in the object"))
  1207. return
  1208. try:
  1209. for line in lines:
  1210. proc_line = str(line).strip('\n')
  1211. self.text_editor_tab.code_editor.append(proc_line)
  1212. except Exception as e:
  1213. log.debug('ToolSolderPaste.on_view_gcode() -->%s' % str(e))
  1214. self.app.inform.emit('[ERROR] %s --> %s' %
  1215. ('ToolSolderPaste.on_view_gcode()', str(e)))
  1216. return
  1217. self.text_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  1218. self.text_editor_tab.handleTextChanged()
  1219. # self.app.ui.show()
  1220. def on_save_gcode(self):
  1221. """
  1222. Save solderpaste dispensing GCode to a file on HDD.
  1223. :return:
  1224. """
  1225. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1226. name = self.cnc_obj_combo.currentText()
  1227. obj = self.app.collection.get_by_name(name)
  1228. if obj.special_group != 'solder_paste_tool':
  1229. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1230. _("This CNCJob object can't be processed. "
  1231. "NOT a solder_paste_tool CNCJob object."))
  1232. return
  1233. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  1234. "G-Code Files (*.g-code);;All Files (*.*);;G-Code Files (*.gcode);;G-Code Files (*.ngc)"
  1235. try:
  1236. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1237. filename, _f = FCFileSaveDialog.get_saved_filename(
  1238. caption=_("Export GCode ..."),
  1239. directory=dir_file_to_save,
  1240. filter=_filter_
  1241. )
  1242. except TypeError:
  1243. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Machine Code ..."), filter=_filter_)
  1244. if filename == '':
  1245. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1246. _("Export Machine Code cancelled ..."))
  1247. return
  1248. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1249. (str(self.app.version), str(self.app.version_date)) + '\n'
  1250. gcode += '(Name: ' + str(name) + ')\n'
  1251. gcode += '(Type: ' + "G-code from " + str(obj.options['type']) + " for Solder Paste dispenser" + ')\n'
  1252. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1253. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1254. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1255. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1256. for tool in obj.cnc_tools:
  1257. gcode += obj.cnc_tools[tool]['gcode']
  1258. lines = StringIO(gcode)
  1259. # ## Write
  1260. if filename is not None:
  1261. try:
  1262. with open(filename, 'w') as f:
  1263. for line in lines:
  1264. f.write(line)
  1265. except FileNotFoundError:
  1266. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1267. _("No such file or directory"))
  1268. return
  1269. except PermissionError:
  1270. self.app.inform.emit('[WARNING] %s' %
  1271. _("Permission denied, saving not possible.\n"
  1272. "Most likely another app is holding the file open and not accessible."))
  1273. return 'fail'
  1274. if self.app.defaults["global_open_style"] is False:
  1275. self.app.file_opened.emit("gcode", filename)
  1276. self.app.file_saved.emit("gcode", filename)
  1277. self.app.inform.emit('[success] %s: %s' %
  1278. (_("Solder paste dispenser GCode file saved to"), filename))
  1279. def reset_fields(self):
  1280. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1281. self.geo_obj_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1282. self.cnc_obj_combo.setRootModelIndex(self.app.collection.index(3, 0, QtCore.QModelIndex()))