ToolSolderPaste.py 55 KB

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