ToolSolderPaste.py 55 KB

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