ToolSolderPaste.py 55 KB

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