ToolSolderPaste.py 54 KB

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