ToolSolderPaste.py 65 KB

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