ToolSolderPaste.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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, 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('ToolSolderPaste')
  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 = FCEntry()
  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.deltool_btn.clicked.connect(self.on_tool_delete)
  343. self.soldergeo_btn.clicked.connect(self.on_create_geo_click)
  344. self.solder_gcode_btn.clicked.connect(self.on_create_gcode_click)
  345. self.solder_gcode_view_btn.clicked.connect(self.on_view_gcode)
  346. self.solder_gcode_save_btn.clicked.connect(self.on_save_gcode)
  347. self.geo_obj_combo.currentIndexChanged.connect(self.on_geo_select)
  348. self.cnc_obj_combo.currentIndexChanged.connect(self.on_cncjob_select)
  349. self.app.object_status_changed.connect(self.update_comboboxes)
  350. def run(self, toggle=True):
  351. self.app.report_usage("ToolSolderPaste()")
  352. if toggle:
  353. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  354. if self.app.ui.splitter.sizes()[0] == 0:
  355. self.app.ui.splitter.setSizes([1, 1])
  356. else:
  357. try:
  358. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  359. self.app.ui.splitter.setSizes([0, 1])
  360. except AttributeError:
  361. pass
  362. FlatCAMTool.run(self)
  363. self.set_tool_ui()
  364. self.build_ui()
  365. self.app.ui.notebook.setTabText(2, "SolderPaste Tool")
  366. def install(self, icon=None, separator=None, **kwargs):
  367. FlatCAMTool.install(self, icon, separator, shortcut='ALT+K', **kwargs)
  368. def set_tool_ui(self):
  369. self.form_fields.update({
  370. "tools_solderpaste_new": self.addtool_entry,
  371. "tools_solderpaste_z_start": self.z_start_entry,
  372. "tools_solderpaste_z_dispense": self.z_dispense_entry,
  373. "tools_solderpaste_z_stop": self.z_stop_entry,
  374. "tools_solderpaste_z_travel": self.z_travel_entry,
  375. "tools_solderpaste_z_toolchange": self.z_toolchange_entry,
  376. "tools_solderpaste_xy_toolchange": self.xy_toolchange_entry,
  377. "tools_solderpaste_frxy": self.frxy_entry,
  378. "tools_solderpaste_frz": self.frz_entry,
  379. "tools_solderpaste_frz_dispense": self.frz_dispense_entry,
  380. "tools_solderpaste_speedfwd": self.speedfwd_entry,
  381. "tools_solderpaste_dwellfwd": self.dwellfwd_entry,
  382. "tools_solderpaste_speedrev": self.speedrev_entry,
  383. "tools_solderpaste_dwellrev": self.dwellrev_entry,
  384. "tools_solderpaste_pp": self.pp_combo
  385. })
  386. self.set_form_from_defaults()
  387. self.read_form_to_options()
  388. self.tools_table.setupContextMenu()
  389. self.tools_table.addContextMenu(
  390. _("Add"), lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  391. self.tools_table.addContextMenu(
  392. _("Delete"), lambda:
  393. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  394. try:
  395. dias = [float(eval(dia)) for dia in self.app.defaults["tools_solderpaste_tools"].split(",")]
  396. except:
  397. log.error("At least one Nozzle tool diameter needed. "
  398. "Verify in Edit -> Preferences -> TOOLS -> Solder Paste Tools.")
  399. return
  400. self.tooluid = 0
  401. self.tooltable_tools.clear()
  402. for tool_dia in dias:
  403. self.tooluid += 1
  404. self.tooltable_tools.update({
  405. int(self.tooluid): {
  406. 'tooldia': float('%.4f' % tool_dia),
  407. 'data': deepcopy(self.options),
  408. 'solid_geometry': []
  409. }
  410. })
  411. self.name = ""
  412. self.obj = None
  413. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  414. for name in list(self.app.postprocessors.keys()):
  415. # populate only with postprocessor files that start with 'Paste_'
  416. if name.partition('_')[0] != 'Paste':
  417. continue
  418. self.pp_combo.addItem(name)
  419. self.reset_fields()
  420. def build_ui(self):
  421. """
  422. Will rebuild the UI populating it (tools table)
  423. :return:
  424. """
  425. self.ui_disconnect()
  426. # updated units
  427. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  428. sorted_tools = []
  429. for k, v in self.tooltable_tools.items():
  430. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  431. sorted_tools.sort(reverse=True)
  432. n = len(sorted_tools)
  433. self.tools_table.setRowCount(n)
  434. tool_id = 0
  435. for tool_sorted in sorted_tools:
  436. for tooluid_key, tooluid_value in self.tooltable_tools.items():
  437. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  438. tool_id += 1
  439. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  440. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  441. row_no = tool_id - 1
  442. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  443. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  444. # There are no drill bits in MM with more than 3 decimals diameter
  445. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  446. if self.units == 'MM':
  447. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  448. else:
  449. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  450. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  451. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  452. self.tools_table.setItem(row_no, 1, dia) # Diameter
  453. self.tools_table.setItem(row_no, 2, tool_uid_item) # Tool unique ID
  454. # make the diameter column editable
  455. for row in range(tool_id):
  456. self.tools_table.item(row, 1).setFlags(
  457. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  458. # all the tools are selected by default
  459. self.tools_table.selectColumn(0)
  460. #
  461. self.tools_table.resizeColumnsToContents()
  462. self.tools_table.resizeRowsToContents()
  463. vertical_header = self.tools_table.verticalHeader()
  464. vertical_header.hide()
  465. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  466. horizontal_header = self.tools_table.horizontalHeader()
  467. horizontal_header.setMinimumSectionSize(10)
  468. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  469. horizontal_header.resizeSection(0, 20)
  470. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  471. # self.tools_table.setSortingEnabled(True)
  472. # sort by tool diameter
  473. # self.tools_table.sortItems(1)
  474. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  475. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  476. self.ui_connect()
  477. def update_ui(self, row=None):
  478. """
  479. Will update the UI form with the data from obj.tools
  480. :param row: the row (tool) from which to extract information's used to populate the form
  481. :return:
  482. """
  483. self.ui_disconnect()
  484. if row is None:
  485. try:
  486. current_row = self.tools_table.currentRow()
  487. except:
  488. current_row = 0
  489. else:
  490. current_row = row
  491. if current_row < 0:
  492. current_row = 0
  493. # populate the form with the data from the tool associated with the row parameter
  494. try:
  495. tooluid = int(self.tools_table.item(current_row, 2).text())
  496. except Exception as e:
  497. log.debug("Tool missing. Add a tool in Tool Table. %s" % str(e))
  498. return
  499. # update the form
  500. try:
  501. # set the form with data from the newly selected tool
  502. for tooluid_key, tooluid_value in self.tooltable_tools.items():
  503. if int(tooluid_key) == tooluid:
  504. self.set_form(deepcopy(tooluid_value['data']))
  505. except Exception as e:
  506. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  507. self.ui_connect()
  508. def on_row_selection_change(self):
  509. self.update_ui()
  510. def ui_connect(self):
  511. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  512. # changes in geometry UI
  513. for i in range(self.gcode_form_layout.count()):
  514. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCComboBox):
  515. self.gcode_form_layout.itemAt(i).widget().currentIndexChanged.connect(self.read_form_to_tooldata)
  516. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCEntry):
  517. self.gcode_form_layout.itemAt(i).widget().editingFinished.connect(self.read_form_to_tooldata)
  518. self.tools_table.itemChanged.connect(self.on_tool_edit)
  519. self.tools_table.currentItemChanged.connect(self.on_row_selection_change)
  520. def ui_disconnect(self):
  521. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  522. try:
  523. for i in range(self.gcode_form_layout.count()):
  524. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCComboBox):
  525. self.gcode_form_layout.itemAt(i).widget().currentIndexChanged.disconnect()
  526. if isinstance(self.gcode_form_layout.itemAt(i).widget(), FCEntry):
  527. self.gcode_form_layout.itemAt(i).widget().editingFinished.disconnect()
  528. except:
  529. pass
  530. try:
  531. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  532. except:
  533. pass
  534. try:
  535. self.tools_table.currentItemChanged.disconnect(self.on_row_selection_change)
  536. except:
  537. pass
  538. def update_comboboxes(self, obj, status):
  539. """
  540. Modify the current text of the comboboxes to show the last object
  541. that was created.
  542. :param obj: object that was changed and called this PyQt slot
  543. :param status: what kind of change happened: 'append' or 'delete'
  544. :return:
  545. """
  546. obj_name = obj.options['name']
  547. if status == 'append':
  548. idx = self.obj_combo.findText(obj_name)
  549. if idx != -1:
  550. self.obj_combo.setCurrentIndex(idx)
  551. idx = self.geo_obj_combo.findText(obj_name)
  552. if idx != -1:
  553. self.geo_obj_combo.setCurrentIndex(idx)
  554. idx = self.cnc_obj_combo.findText(obj_name)
  555. if idx != -1:
  556. self.cnc_obj_combo.setCurrentIndex(idx)
  557. def read_form_to_options(self):
  558. """
  559. Will read all the parameters from Solder Paste Tool UI and update the self.options dictionary
  560. :return:
  561. """
  562. for key in self.form_fields:
  563. self.options[key] = self.form_fields[key].get_value()
  564. def read_form_to_tooldata(self, tooluid=None):
  565. """
  566. Will read all the items in the UI form and set the self.tools data accordingly
  567. :param tooluid: the uid of the tool to be updated in the obj.tools
  568. :return:
  569. """
  570. current_row = self.tools_table.currentRow()
  571. uid = tooluid if tooluid else int(self.tools_table.item(current_row, 2).text())
  572. for key in self.form_fields:
  573. self.tooltable_tools[uid]['data'].update({
  574. key: self.form_fields[key].get_value()
  575. })
  576. def set_form_from_defaults(self):
  577. """
  578. Will read all the parameters of Solder Paste Tool from the app self.defaults and update the UI
  579. :return:
  580. """
  581. for key in self.form_fields:
  582. if key in self.app.defaults:
  583. self.form_fields[key].set_value(self.app.defaults[key])
  584. def set_form(self, val):
  585. """
  586. Will read all the parameters of Solder Paste Tool from the provided val parameter and update the UI
  587. :param val: dictionary with values to store in the form
  588. param_type: dictionary
  589. :return:
  590. """
  591. if not isinstance(val, dict):
  592. log.debug("ToolSoderPaste.set_form() --> parameter not a dict")
  593. return
  594. for key in self.form_fields:
  595. if key in val:
  596. self.form_fields[key].set_value(val[key])
  597. def on_tool_add(self, dia=None, muted=None):
  598. """
  599. Add a Tool in the Tool Table
  600. :param dia: diameter of the tool to be added
  601. :param muted: if True will not send status bar messages about adding tools
  602. :return:
  603. """
  604. self.ui_disconnect()
  605. if dia:
  606. tool_dia = dia
  607. else:
  608. try:
  609. tool_dia = float(self.addtool_entry.get_value())
  610. except ValueError:
  611. # try to convert comma to decimal point. if it's still not working error message and return
  612. try:
  613. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  614. except ValueError:
  615. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  616. "use a number."))
  617. return
  618. if tool_dia is None:
  619. self.build_ui()
  620. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  621. return
  622. if tool_dia == 0:
  623. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  624. return
  625. # construct a list of all 'tooluid' in the self.tooltable_tools
  626. tool_uid_list = []
  627. for tooluid_key in self.tooltable_tools:
  628. tool_uid_item = int(tooluid_key)
  629. tool_uid_list.append(tool_uid_item)
  630. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  631. if not tool_uid_list:
  632. max_uid = 0
  633. else:
  634. max_uid = max(tool_uid_list)
  635. self.tooluid = int(max_uid + 1)
  636. tool_dias = []
  637. for k, v in self.tooltable_tools.items():
  638. for tool_v in v.keys():
  639. if tool_v == 'tooldia':
  640. tool_dias.append(float('%.4f' % v[tool_v]))
  641. if float('%.4f' % tool_dia) in tool_dias:
  642. if muted is None:
  643. self.app.inform.emit(_("[WARNING_NOTCL] Adding Nozzle tool cancelled. Tool already in Tool Table."))
  644. self.tools_table.itemChanged.connect(self.on_tool_edit)
  645. return
  646. else:
  647. if muted is None:
  648. self.app.inform.emit(_("[success] New Nozzle tool added to Tool Table."))
  649. self.tooltable_tools.update({
  650. int(self.tooluid): {
  651. 'tooldia': float('%.4f' % tool_dia),
  652. 'data': deepcopy(self.options),
  653. 'solid_geometry': []
  654. }
  655. })
  656. self.build_ui()
  657. def on_tool_edit(self):
  658. """
  659. Edit a tool in the Tool Table
  660. :return:
  661. """
  662. self.ui_disconnect()
  663. tool_dias = []
  664. for k, v in self.tooltable_tools.items():
  665. for tool_v in v.keys():
  666. if tool_v == 'tooldia':
  667. tool_dias.append(float('%.4f' % v[tool_v]))
  668. for row in range(self.tools_table.rowCount()):
  669. try:
  670. new_tool_dia = float(self.tools_table.item(row, 1).text())
  671. except ValueError:
  672. # try to convert comma to decimal point. if it's still not working error message and return
  673. try:
  674. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  675. except ValueError:
  676. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  677. "use a number."))
  678. return
  679. tooluid = int(self.tools_table.item(row, 2).text())
  680. # identify the tool that was edited and get it's tooluid
  681. if new_tool_dia not in tool_dias:
  682. self.tooltable_tools[tooluid]['tooldia'] = new_tool_dia
  683. self.app.inform.emit(_("[success] Nozzle tool from Tool Table was edited."))
  684. self.build_ui()
  685. return
  686. else:
  687. # identify the old tool_dia and restore the text in tool table
  688. for k, v in self.tooltable_tools.items():
  689. if k == tooluid:
  690. old_tool_dia = v['tooldia']
  691. break
  692. restore_dia_item = self.tools_table.item(row, 1)
  693. restore_dia_item.setText(str(old_tool_dia))
  694. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table."))
  695. self.build_ui()
  696. def on_tool_delete(self, rows_to_delete=None, all=None):
  697. """
  698. Will delete tool(s) in the Tool Table
  699. :param rows_to_delete: tell which row (tool) to delete
  700. :param all: to delete all tools at once
  701. :return:
  702. """
  703. self.ui_disconnect()
  704. deleted_tools_list = []
  705. if all:
  706. self.tooltable_tools.clear()
  707. self.build_ui()
  708. return
  709. if rows_to_delete:
  710. try:
  711. for row in rows_to_delete:
  712. tooluid_del = int(self.tools_table.item(row, 2).text())
  713. deleted_tools_list.append(tooluid_del)
  714. except TypeError:
  715. deleted_tools_list.append(rows_to_delete)
  716. for t in deleted_tools_list:
  717. self.tooltable_tools.pop(t, None)
  718. self.build_ui()
  719. return
  720. try:
  721. if self.tools_table.selectedItems():
  722. for row_sel in self.tools_table.selectedItems():
  723. row = row_sel.row()
  724. if row < 0:
  725. continue
  726. tooluid_del = int(self.tools_table.item(row, 2).text())
  727. deleted_tools_list.append(tooluid_del)
  728. for t in deleted_tools_list:
  729. self.tooltable_tools.pop(t, None)
  730. except AttributeError:
  731. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a Nozzle tool to delete."))
  732. return
  733. except Exception as e:
  734. log.debug(str(e))
  735. self.app.inform.emit(_("[success] Nozzle tool(s) deleted from Tool Table."))
  736. self.build_ui()
  737. def on_rmb_combo(self, pos, combo):
  738. """
  739. Will create a context menu on the combobox items
  740. :param pos: mouse click position passed by the signal that called this slot
  741. :param combo: the actual combo from where the signal was triggered
  742. :return:
  743. """
  744. view = combo.view
  745. idx = view.indexAt(pos)
  746. if not idx.isValid():
  747. return
  748. self.obj_to_be_deleted_name = combo.model().itemData(idx)[0]
  749. menu = QtWidgets.QMenu()
  750. menu.addAction(self.combo_context_del_action)
  751. menu.exec(view.mapToGlobal(pos))
  752. def on_delete_object(self):
  753. """
  754. Slot for the 'delete' action triggered in the combobox context menu.
  755. The name of the object to be deleted is collected when the combobox context menu is created.
  756. :return:
  757. """
  758. if self.obj_to_be_deleted_name != '':
  759. self.app.collection.set_active(self.obj_to_be_deleted_name)
  760. self.app.collection.delete_active(select_project=False)
  761. self.obj_to_be_deleted_name = ''
  762. def on_geo_select(self):
  763. # if self.geo_obj_combo.currentText().rpartition('_')[2] == 'solderpaste':
  764. # self.gcode_frame.setDisabled(False)
  765. # else:
  766. # self.gcode_frame.setDisabled(True)
  767. pass
  768. def on_cncjob_select(self):
  769. # if self.cnc_obj_combo.currentText().rpartition('_')[2] == 'solderpaste':
  770. # self.save_gcode_frame.setDisabled(False)
  771. # else:
  772. # self.save_gcode_frame.setDisabled(True)
  773. pass
  774. def on_create_geo_click(self, signal):
  775. """
  776. Will create a solderpaste dispensing geometry.
  777. :param signal: passed by the signal that called this slot
  778. :return:
  779. """
  780. name = self.obj_combo.currentText()
  781. if name == '':
  782. self.app.inform.emit(_("[WARNING_NOTCL] No SolderPaste mask Gerber object loaded."))
  783. return
  784. obj = self.app.collection.get_by_name(name)
  785. # update the self.options
  786. self.read_form_to_options()
  787. self.on_create_geo(name=name, work_object=obj)
  788. def on_create_geo(self, name, work_object, use_thread=True):
  789. """
  790. The actual work for creating solderpaste dispensing geometry is done here.
  791. :param name: the outname for the resulting geometry object
  792. :param work_object: the source Gerber object from which the geometry is created
  793. :return: a Geometry type object
  794. """
  795. proc = self.app.proc_container.new(_("Creating Solder Paste dispensing geometry."))
  796. obj = work_object
  797. # Sort tools in descending order
  798. sorted_tools = []
  799. for k, v in self.tooltable_tools.items():
  800. # make sure that the tools diameter is more than zero and not zero
  801. if float(v['tooldia']) > 0:
  802. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  803. sorted_tools.sort(reverse=True)
  804. if not sorted_tools:
  805. self.app.inform.emit(_("[WARNING_NOTCL] No Nozzle tools in the tool table."))
  806. return 'fail'
  807. def flatten(geometry=None, reset=True, pathonly=False):
  808. """
  809. Creates a list of non-iterable linear geometry objects.
  810. Polygons are expanded into its exterior pathonly param if specified.
  811. Results are placed in flat_geometry
  812. :param geometry: Shapely type or list or list of list of such.
  813. :param reset: Clears the contents of self.flat_geometry.
  814. :param pathonly: Expands polygons into linear elements from the exterior attribute.
  815. """
  816. if reset:
  817. self.flat_geometry = []
  818. ## If iterable, expand recursively.
  819. try:
  820. for geo in geometry:
  821. if geo is not None:
  822. flatten(geometry=geo,
  823. reset=False,
  824. pathonly=pathonly)
  825. ## Not iterable, do the actual indexing and add.
  826. except TypeError:
  827. if pathonly and type(geometry) == Polygon:
  828. self.flat_geometry.append(geometry.exterior)
  829. else:
  830. self.flat_geometry.append(geometry)
  831. return self.flat_geometry
  832. # TODO when/if the Gerber files will have solid_geometry in the self.apertures I will have to take care here
  833. flatten(geometry=obj.solid_geometry, pathonly=True)
  834. def geo_init(geo_obj, app_obj):
  835. geo_obj.options.update(self.options)
  836. geo_obj.solid_geometry = []
  837. geo_obj.tools = {}
  838. geo_obj.multigeo = True
  839. geo_obj.multitool = True
  840. geo_obj.special_group = 'solder_paste_tool'
  841. geo = LineString()
  842. work_geo = self.flat_geometry
  843. rest_geo = []
  844. tooluid = 1
  845. for tool in sorted_tools:
  846. offset = tool / 2
  847. for uid, v in self.tooltable_tools.items():
  848. if float('%.4f' % float(v['tooldia'])) == tool:
  849. tooluid = int(uid)
  850. break
  851. geo_obj.tools[tooluid] = {}
  852. geo_obj.tools[tooluid]['tooldia'] = tool
  853. geo_obj.tools[tooluid]['data'] = deepcopy(self.tooltable_tools[tooluid]['data'])
  854. geo_obj.tools[tooluid]['solid_geometry'] = []
  855. geo_obj.tools[tooluid]['offset'] = 'Path'
  856. geo_obj.tools[tooluid]['offset_value'] = 0.0
  857. geo_obj.tools[tooluid]['type'] = 'SolderPaste'
  858. geo_obj.tools[tooluid]['tool_type'] = 'DN'
  859. # self.flat_geometry is a list of LinearRings produced by flatten() from the exteriors of the Polygons
  860. # We get possible issues if we try to directly use the Polygons, due of possible the interiors,
  861. # so we do a hack: get first the exterior in a form of LinearRings and then convert back to Polygon
  862. # because intersection does not work on LinearRings
  863. for g in work_geo:
  864. # for whatever reason intersection on LinearRings does not work so we convert back to Polygons
  865. poly = Polygon(g)
  866. x_min, y_min, x_max, y_max = poly.bounds
  867. diag_1_intersect = LineString([(x_min, y_min), (x_max, y_max)]).intersection(poly)
  868. diag_2_intersect = LineString([(x_min, y_max), (x_max, y_min)]).intersection(poly)
  869. if self.units == 'MM':
  870. round_diag_1 = round(diag_1_intersect.length, 1)
  871. round_diag_2 = round(diag_2_intersect.length, 1)
  872. else:
  873. round_diag_1 = round(diag_1_intersect.length, 2)
  874. round_diag_2 = round(diag_2_intersect.length, 2)
  875. if round_diag_1 == round_diag_2:
  876. l = distance((x_min, y_min), (x_max, y_min))
  877. h = distance((x_min, y_min), (x_min, y_max))
  878. if offset >= l / 2 or offset >= h / 2:
  879. pass
  880. else:
  881. if l > h:
  882. h_half = h / 2
  883. start = [x_min, (y_min + h_half)]
  884. stop = [(x_min + l), (y_min + h_half)]
  885. geo = LineString([start, stop])
  886. else:
  887. l_half = l / 2
  888. start = [(x_min + l_half), y_min]
  889. stop = [(x_min + l_half), (y_min + h)]
  890. geo = LineString([start, stop])
  891. elif round_diag_1 > round_diag_2:
  892. geo = diag_1_intersect
  893. else:
  894. geo = diag_2_intersect
  895. offseted_poly = poly.buffer(-offset)
  896. geo = geo.intersection(offseted_poly)
  897. if not geo.is_empty:
  898. try:
  899. geo_obj.tools[tooluid]['solid_geometry'].append(geo)
  900. except Exception as e:
  901. log.debug('ToolSolderPaste.on_create_geo() --> %s' % str(e))
  902. else:
  903. rest_geo.append(g)
  904. work_geo = deepcopy(rest_geo)
  905. rest_geo[:] = []
  906. if not work_geo:
  907. a = 0
  908. for tooluid_key in geo_obj.tools:
  909. if not geo_obj.tools[tooluid_key]['solid_geometry']:
  910. a += 1
  911. if a == len(geo_obj.tools):
  912. self.app.inform.emit(_('[ERROR_NOTCL] Cancelled. Empty file, it has no geometry...'))
  913. return 'fail'
  914. app_obj.inform.emit(_("[success] Solder Paste geometry generated successfully..."))
  915. return
  916. # if we still have geometry not processed at the end of the tools then we failed
  917. # some or all the pads are not covered with solder paste
  918. if work_geo:
  919. app_obj.inform.emit(_("[WARNING_NOTCL] Some or all pads have no solder "
  920. "due of inadequate nozzle diameters..."))
  921. return 'fail'
  922. if use_thread:
  923. def job_thread(app_obj):
  924. try:
  925. app_obj.new_object("geometry", name + "_solderpaste", geo_init)
  926. except Exception as e:
  927. log.error("SolderPaste.on_create_geo() --> %s" % str(e))
  928. proc.done()
  929. return
  930. proc.done()
  931. self.app.inform.emit(_("Generating Solder Paste dispensing geometry..."))
  932. # Promise object with the new name
  933. self.app.collection.promise(name)
  934. # Background
  935. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  936. else:
  937. self.app.new_object("geometry", name + "_solderpaste", geo_init)
  938. def on_create_gcode_click(self, signal):
  939. """
  940. Will create a CNCJob object from the solderpaste dispensing geometry.
  941. :param signal: parameter passed by the signal that called this slot
  942. :return:
  943. """
  944. name = self.geo_obj_combo.currentText()
  945. obj = self.app.collection.get_by_name(name)
  946. if name == '':
  947. self.app.inform.emit(_("[WARNING_NOTCL] There is no Geometry object available."))
  948. return 'fail'
  949. if obj.special_group != 'solder_paste_tool':
  950. self.app.inform.emit(_("[WARNING_NOTCL] This Geometry can't be processed. NOT a solder_paste_tool geometry."))
  951. return 'fail'
  952. a = 0
  953. for tooluid_key in obj.tools:
  954. if obj.tools[tooluid_key]['solid_geometry'] is None:
  955. a += 1
  956. if a == len(obj.tools):
  957. self.app.inform.emit(_('[ERROR_NOTCL] Cancelled. Empty file, it has no geometry...'))
  958. return 'fail'
  959. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  960. originar_name = obj.options['name'].partition('_')[0]
  961. outname = "%s_%s" % (originar_name, 'cnc_solderpaste')
  962. self.on_create_gcode(name=outname, workobject=obj)
  963. def on_create_gcode(self, name, workobject, use_thread=True):
  964. """
  965. Creates a multi-tool CNCJob. The actual work is done here.
  966. :param name: outname for the resulting CNCJob object
  967. :param workobject: the solderpaste dispensing Geometry object that is the source
  968. :param use_thread: True if threaded execution is desired
  969. :return:
  970. """
  971. obj = workobject
  972. try:
  973. xmin = obj.options['xmin']
  974. ymin = obj.options['ymin']
  975. xmax = obj.options['xmax']
  976. ymax = obj.options['ymax']
  977. except Exception as e:
  978. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  979. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  980. msg += 'FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s' % str(e)
  981. msg += traceback.format_exc()
  982. self.app.inform.emit(msg)
  983. return
  984. # Object initialization function for app.new_object()
  985. # RUNNING ON SEPARATE THREAD!
  986. def job_init(job_obj, app_obj):
  987. assert isinstance(job_obj, FlatCAMCNCjob), \
  988. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  989. tool_cnc_dict = {}
  990. # this turn on the FlatCAMCNCJob plot for multiple tools
  991. job_obj.multitool = True
  992. job_obj.multigeo = True
  993. job_obj.cnc_tools.clear()
  994. job_obj.special_group = 'solder_paste_tool'
  995. job_obj.options['xmin'] = xmin
  996. job_obj.options['ymin'] = ymin
  997. job_obj.options['xmax'] = xmax
  998. job_obj.options['ymax'] = ymax
  999. for tooluid_key, tooluid_value in obj.tools.items():
  1000. app_obj.progress.emit(20)
  1001. # find the tool_dia associated with the tooluid_key
  1002. tool_dia = tooluid_value['tooldia']
  1003. tool_cnc_dict = deepcopy(tooluid_value)
  1004. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1005. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1006. job_obj.tool = int(tooluid_key)
  1007. # Propagate options
  1008. job_obj.options["tooldia"] = tool_dia
  1009. job_obj.options['tool_dia'] = tool_dia
  1010. ### CREATE GCODE ###
  1011. res = job_obj.generate_gcode_from_solderpaste_geo(**tooluid_value)
  1012. if res == 'fail':
  1013. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  1014. return 'fail'
  1015. else:
  1016. tool_cnc_dict['gcode'] = res
  1017. ### PARSE GCODE ###
  1018. tool_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  1019. # TODO this serve for bounding box creation only; should be optimized
  1020. tool_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in tool_cnc_dict['gcode_parsed']])
  1021. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  1022. # object is the source of gcode
  1023. job_obj.toolchange_xy_type = "geometry"
  1024. app_obj.progress.emit(80)
  1025. job_obj.cnc_tools.update({
  1026. tooluid_key: deepcopy(tool_cnc_dict)
  1027. })
  1028. tool_cnc_dict.clear()
  1029. if use_thread:
  1030. # To be run in separate thread
  1031. def job_thread(app_obj):
  1032. with self.app.proc_container.new("Generating CNC Code"):
  1033. if app_obj.new_object("cncjob", name, job_init) != 'fail':
  1034. app_obj.inform.emit(_("[success] ToolSolderPaste CNCjob created: %s") % name)
  1035. app_obj.progress.emit(100)
  1036. # Create a promise with the name
  1037. self.app.collection.promise(name)
  1038. # Send to worker
  1039. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1040. else:
  1041. self.app.new_object("cncjob", name, job_init)
  1042. def on_view_gcode(self):
  1043. """
  1044. View GCode in the Editor Tab.
  1045. :return:
  1046. """
  1047. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1048. # add the tab if it was closed
  1049. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "Code Editor")
  1050. # first clear previous text in text editor (if any)
  1051. self.app.ui.code_editor.clear()
  1052. # Switch plot_area to CNCJob tab
  1053. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  1054. name = self.cnc_obj_combo.currentText()
  1055. obj = self.app.collection.get_by_name(name)
  1056. try:
  1057. if obj.special_group != 'solder_paste_tool':
  1058. self.app.inform.emit(_("[WARNING_NOTCL] This CNCJob object can't be processed. "
  1059. "NOT a solder_paste_tool CNCJob object."))
  1060. return
  1061. except AttributeError:
  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. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1066. (str(self.app.version), str(self.app.version_date)) + '\n'
  1067. gcode += '(Name: ' + str(name) + ')\n'
  1068. gcode += '(Type: ' + "G-code from " + str(obj.options['type']) + " for Solder Paste dispenser" + ')\n'
  1069. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1070. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1071. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1072. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1073. for tool in obj.cnc_tools:
  1074. gcode += obj.cnc_tools[tool]['gcode']
  1075. # then append the text from GCode to the text editor
  1076. try:
  1077. lines = StringIO(gcode)
  1078. except:
  1079. self.app.inform.emit(_("[ERROR_NOTCL] No Gcode in the object..."))
  1080. return
  1081. try:
  1082. for line in lines:
  1083. proc_line = str(line).strip('\n')
  1084. self.app.ui.code_editor.append(proc_line)
  1085. except Exception as e:
  1086. log.debug('ToolSolderPaste.on_view_gcode() -->%s' % str(e))
  1087. self.app.inform.emit(_('[ERROR] ToolSolderPaste.on_view_gcode() -->%s') % str(e))
  1088. return
  1089. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  1090. self.app.handleTextChanged()
  1091. self.app.ui.show()
  1092. def on_save_gcode(self):
  1093. """
  1094. Save sodlerpaste dispensing GCode to a file on HDD.
  1095. :return:
  1096. """
  1097. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  1098. name = self.cnc_obj_combo.currentText()
  1099. obj = self.app.collection.get_by_name(name)
  1100. if obj.special_group != 'solder_paste_tool':
  1101. self.app.inform.emit(_("[WARNING_NOTCL] This CNCJob object can't be processed. "
  1102. "NOT a solder_paste_tool CNCJob object."))
  1103. return
  1104. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  1105. "G-Code Files (*.g-code);;All Files (*.*)"
  1106. try:
  1107. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  1108. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  1109. caption=_("Export GCode ..."),
  1110. directory=dir_file_to_save,
  1111. filter=_filter_
  1112. )
  1113. except TypeError:
  1114. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  1115. if filename == '':
  1116. self.app.inform.emit(_("[WARNING_NOTCL] Export Machine Code cancelled ..."))
  1117. return
  1118. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  1119. (str(self.app.version), str(self.app.version_date)) + '\n'
  1120. gcode += '(Name: ' + str(name) + ')\n'
  1121. gcode += '(Type: ' + "G-code from " + str(obj.options['type']) + " for Solder Paste dispenser" + ')\n'
  1122. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  1123. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  1124. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  1125. gcode += '(Created on ' + time_str + ')\n' + '\n'
  1126. for tool in obj.cnc_tools:
  1127. gcode += obj.cnc_tools[tool]['gcode']
  1128. lines = StringIO(gcode)
  1129. ## Write
  1130. if filename is not None:
  1131. try:
  1132. with open(filename, 'w') as f:
  1133. for line in lines:
  1134. f.write(line)
  1135. except FileNotFoundError:
  1136. self.app.inform.emit(_("[WARNING_NOTCL] No such file or directory"))
  1137. return
  1138. self.app.file_saved.emit("gcode", filename)
  1139. self.app.inform.emit(_("[success] Solder paste dispenser GCode file saved to: %s") % filename)
  1140. def reset_fields(self):
  1141. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1142. self.geo_obj_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  1143. self.cnc_obj_combo.setRootModelIndex(self.app.collection.index(3, 0, QtCore.QModelIndex()))