ToolPaint.py 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Modified: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from PyQt5.QtCore import Qt
  9. from appTool import AppTool
  10. from copy import deepcopy
  11. # from ObjectCollection import *
  12. from appParsers.ParseGerber import Gerber
  13. from camlib import Geometry, FlatCAMRTreeStorage, grace
  14. from appGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet, FCButton, FCComboBox
  15. from shapely.geometry import base, Polygon, MultiPolygon, LinearRing, Point
  16. from shapely.ops import cascaded_union, unary_union, linemerge
  17. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  18. import numpy as np
  19. import math
  20. from numpy import Inf
  21. import traceback
  22. import logging
  23. import gettext
  24. import appTranslation as fcTranslate
  25. import builtins
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. log = logging.getLogger('base')
  30. class ToolPaint(AppTool, Gerber):
  31. def __init__(self, app):
  32. self.app = app
  33. self.decimals = self.app.decimals
  34. AppTool.__init__(self, app)
  35. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  36. # #############################################################################
  37. # ######################### Tool GUI ##########################################
  38. # #############################################################################
  39. self.ui = PaintUI(layout=self.layout, app=self.app)
  40. self.toolName = self.ui.toolName
  41. # #############################################################################
  42. # ########################## VARIABLES ########################################
  43. # #############################################################################
  44. self.obj_name = ""
  45. self.paint_obj = None
  46. self.bound_obj_name = ""
  47. self.bound_obj = None
  48. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  49. self.tooldia_list = []
  50. self.tooldia = None
  51. self.sel_rect = None
  52. self.o_name = None
  53. self.overlap = None
  54. self.connect = None
  55. self.contour = None
  56. self.select_method = None
  57. self.units = ''
  58. self.paint_tools = {}
  59. self.tooluid = 0
  60. self.first_click = False
  61. self.cursor_pos = None
  62. self.mouse_is_dragging = False
  63. self.mm = None
  64. self.mp = None
  65. self.mr = None
  66. self.kp = None
  67. # disconnect flags
  68. self.area_sel_disconnect_flag = False
  69. self.poly_sel_disconnect_flag = False
  70. self.sel_rect = []
  71. # store here if the grid snapping is active
  72. self.grid_status_memory = False
  73. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  74. self.poly_dict = {}
  75. # store here the default data for Geometry Data
  76. self.default_data = {}
  77. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  78. self.form_fields = {
  79. "tools_paintoverlap": self.ui.paintoverlap_entry,
  80. "tools_paintoffset": self.ui.offset_entry,
  81. "tools_paintmethod": self.ui.paintmethod_combo,
  82. "tools_pathconnect": self.ui.pathconnect_cb,
  83. "tools_paintcontour": self.ui.paintcontour_cb,
  84. }
  85. self.name2option = {
  86. 'p_overlap': "tools_paintoverlap",
  87. 'p_offset': "tools_paintoffset",
  88. 'p_method': "tools_paintmethod",
  89. 'p_connect': "tools_pathconnect",
  90. 'p_contour': "tools_paintcontour",
  91. }
  92. self.old_tool_dia = None
  93. # store here the points for the "Polygon" area selection shape
  94. self.points = []
  95. # set this as True when in middle of drawing a "Polygon" area selection shape
  96. # it is made False by first click to signify that the shape is complete
  97. self.poly_drawn = False
  98. self.connect_signals_at_init()
  99. # #############################################################################
  100. # ###################### Setup CONTEXT MENU ###################################
  101. # #############################################################################
  102. self.ui.tools_table.setupContextMenu()
  103. self.ui.tools_table.addContextMenu(
  104. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  105. )
  106. self.ui.tools_table.addContextMenu(
  107. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  108. )
  109. self.ui.tools_table.addContextMenu(
  110. _("Delete"), lambda:
  111. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  112. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  113. )
  114. def on_type_obj_changed(self, val):
  115. obj_type = 0 if val == 'gerber' else 2
  116. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  117. self.ui.obj_combo.setCurrentIndex(0)
  118. self.ui.obj_combo.obj_type = {"gerber": "Gerber", "geometry": "Geometry"}[val]
  119. idx = self.ui.paintmethod_combo.findText(_("Laser_lines"))
  120. if self.ui.type_obj_radio.get_value().lower() == 'gerber':
  121. self.ui.paintmethod_combo.model().item(idx).setEnabled(True)
  122. else:
  123. self.ui.paintmethod_combo.model().item(idx).setEnabled(False)
  124. if self.ui.paintmethod_combo.get_value() == _("Laser_lines"):
  125. self.ui.paintmethod_combo.set_value(_("Lines"))
  126. def on_reference_combo_changed(self):
  127. obj_type = self.ui.reference_type_combo.currentIndex()
  128. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  129. self.ui.reference_combo.setCurrentIndex(0)
  130. self.ui.reference_combo.obj_type = {
  131. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  132. }[self.ui.reference_type_combo.get_value()]
  133. def connect_signals_at_init(self):
  134. # #############################################################################
  135. # ################################# Signals ###################################
  136. # #############################################################################
  137. self.ui.addtool_btn.clicked.connect(self.on_tool_add)
  138. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  139. self.ui.deltool_btn.clicked.connect(self.on_tool_delete)
  140. self.ui.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  141. self.ui.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  142. self.ui.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  143. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  144. self.ui.selectmethod_combo.currentIndexChanged.connect(self.on_selection)
  145. self.ui.reference_type_combo.currentIndexChanged.connect(self.on_reference_combo_changed)
  146. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  147. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  148. self.ui.addtool_from_db_btn.clicked.connect(self.on_paint_tool_add_from_db_clicked)
  149. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  150. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  151. self.app.cleanup.connect(self.set_tool_ui)
  152. def install(self, icon=None, separator=None, **kwargs):
  153. AppTool.install(self, icon, separator, shortcut='Alt+P', **kwargs)
  154. def run(self, toggle=True):
  155. self.app.defaults.report_usage("ToolPaint()")
  156. log.debug("ToolPaint().run() was launched ...")
  157. if toggle:
  158. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  159. if self.app.ui.splitter.sizes()[0] == 0:
  160. self.app.ui.splitter.setSizes([1, 1])
  161. else:
  162. try:
  163. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  164. # if tab is populated with the tool but it does not have the focus, focus on it
  165. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  166. # focus on Tool Tab
  167. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  168. else:
  169. self.app.ui.splitter.setSizes([0, 1])
  170. except AttributeError:
  171. pass
  172. else:
  173. if self.app.ui.splitter.sizes()[0] == 0:
  174. self.app.ui.splitter.setSizes([1, 1])
  175. AppTool.run(self)
  176. self.set_tool_ui()
  177. self.build_ui()
  178. # all the tools are selected by default
  179. self.ui.tools_table.selectAll()
  180. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  181. def on_toggle_all_rows(self):
  182. """
  183. will toggle the selection of all rows in Tools table
  184. :return:
  185. """
  186. sel_model = self.ui.tools_table.selectionModel()
  187. sel_indexes = sel_model.selectedIndexes()
  188. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  189. sel_rows = set()
  190. for idx in sel_indexes:
  191. sel_rows.add(idx.row())
  192. if len(sel_rows) == self.ui.tools_table.rowCount():
  193. self.ui.tools_table.clearSelection()
  194. else:
  195. self.ui.tools_table.selectAll()
  196. self.update_ui()
  197. def on_row_selection_change(self):
  198. self.update_ui()
  199. def update_ui(self):
  200. self.blockSignals(True)
  201. sel_rows = set()
  202. table_items = self.ui.tools_table.selectedItems()
  203. if table_items:
  204. for it in table_items:
  205. sel_rows.add(it.row())
  206. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  207. if not sel_rows or len(sel_rows) == 0:
  208. self.ui.generate_paint_button.setDisabled(True)
  209. self.ui.tool_data_label.setText(
  210. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  211. )
  212. self.blockSignals(False)
  213. return
  214. else:
  215. self.ui.generate_paint_button.setDisabled(False)
  216. for current_row in sel_rows:
  217. # populate the form with the data from the tool associated with the row parameter
  218. try:
  219. item = self.ui.tools_table.item(current_row, 3)
  220. if item is None:
  221. return 'fail'
  222. tooluid = int(item.text())
  223. except Exception as e:
  224. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  225. return
  226. # update the QLabel that shows for which Tool we have the parameters in the UI form
  227. if len(sel_rows) == 1:
  228. cr = self.ui.tools_table.item(current_row, 0).text()
  229. self.ui.tool_data_label.setText(
  230. "<b>%s: <font color='#0000FF'>%s %s</font></b>" % (_('Parameters for'), _("Tool"), cr)
  231. )
  232. try:
  233. # set the form with data from the newly selected tool
  234. for tooluid_key, tooluid_value in list(self.paint_tools.items()):
  235. if int(tooluid_key) == tooluid:
  236. self.storage_to_form(tooluid_value['data'])
  237. except Exception as e:
  238. log.debug("ToolPaint ---> update_ui() " + str(e))
  239. else:
  240. self.ui.tool_data_label.setText(
  241. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  242. )
  243. self.blockSignals(False)
  244. def storage_to_form(self, dict_storage):
  245. for k in self.form_fields:
  246. try:
  247. self.form_fields[k].set_value(dict_storage[k])
  248. except Exception as err:
  249. log.debug("ToolPaint.storage.form() --> %s" % str(err))
  250. def form_to_storage(self):
  251. if self.ui.tools_table.rowCount() == 0:
  252. # there is no tool in tool table so we can't save the GUI elements values to storage
  253. return
  254. self.blockSignals(True)
  255. widget_changed = self.sender()
  256. wdg_objname = widget_changed.objectName()
  257. option_changed = self.name2option[wdg_objname]
  258. # row = self.ui.tools_table.currentRow()
  259. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  260. for row in rows:
  261. if row < 0:
  262. row = 0
  263. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  264. for tooluid_key, tooluid_val in self.paint_tools.items():
  265. if int(tooluid_key) == tooluid_item:
  266. new_option_value = self.form_fields[option_changed].get_value()
  267. if option_changed in tooluid_val:
  268. tooluid_val[option_changed] = new_option_value
  269. if option_changed in tooluid_val['data']:
  270. tooluid_val['data'][option_changed] = new_option_value
  271. self.blockSignals(False)
  272. def on_apply_param_to_all_clicked(self):
  273. if self.ui.tools_table.rowCount() == 0:
  274. # there is no tool in tool table so we can't save the GUI elements values to storage
  275. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  276. return
  277. self.blockSignals(True)
  278. row = self.ui.tools_table.currentRow()
  279. if row < 0:
  280. row = 0
  281. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  282. temp_tool_data = {}
  283. for tooluid_key, tooluid_val in self.paint_tools.items():
  284. if int(tooluid_key) == tooluid_item:
  285. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  286. # the current row in the tool table
  287. temp_tool_data = tooluid_val['data']
  288. break
  289. for tooluid_key, tooluid_val in self.paint_tools.items():
  290. tooluid_val['data'] = deepcopy(temp_tool_data)
  291. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  292. self.blockSignals(False)
  293. def on_add_tool_by_key(self):
  294. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  295. text='%s:' % _('Enter a Tool Diameter'),
  296. min=0.0000, max=99.9999, decimals=4)
  297. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  298. val, ok = tool_add_popup.get_value()
  299. if ok:
  300. if float(val) == 0:
  301. self.app.inform.emit('[WARNING_NOTCL] %s' %
  302. _("Please enter a tool diameter with non-zero value, in Float format."))
  303. return
  304. self.on_tool_add(dia=float(val))
  305. else:
  306. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  307. def on_tooltable_cellwidget_change(self):
  308. cw = self.sender()
  309. assert isinstance(cw, QtWidgets.QComboBox), \
  310. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  311. cw_index = self.ui.tools_table.indexAt(cw.pos())
  312. cw_row = cw_index.row()
  313. cw_col = cw_index.column()
  314. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  315. # if the sender is in the column with index 2 then we update the tool_type key
  316. if cw_col == 2:
  317. tt = cw.currentText()
  318. typ = 'Iso' if tt == 'V' else "Rough"
  319. self.paint_tools[current_uid].update({
  320. 'type': typ,
  321. 'tool_type': tt,
  322. })
  323. def on_tool_type(self, val):
  324. if val == 'V':
  325. self.ui.addtool_entry_lbl.setDisabled(True)
  326. self.ui.addtool_entry.setDisabled(True)
  327. self.ui.tipdialabel.show()
  328. self.ui.tipdia_entry.show()
  329. self.ui.tipanglelabel.show()
  330. self.ui.tipangle_entry.show()
  331. self.on_calculate_tooldia()
  332. else:
  333. self.ui.addtool_entry_lbl.setDisabled(False)
  334. self.ui.addtool_entry.setDisabled(False)
  335. self.ui.tipdialabel.hide()
  336. self.ui.tipdia_entry.hide()
  337. self.ui.tipanglelabel.hide()
  338. self.ui.tipangle_entry.hide()
  339. self.ui.addtool_entry.set_value(self.old_tool_dia)
  340. def on_calculate_tooldia(self):
  341. if self.ui.tool_type_radio.get_value() == 'V':
  342. tip_dia = float(self.ui.tipdia_entry.get_value())
  343. tip_angle = float(self.ui.tipangle_entry.get_value()) / 2.0
  344. cut_z = float(self.ui.cutz_entry.get_value())
  345. cut_z = -cut_z if cut_z < 0 else cut_z
  346. # calculated tool diameter so the cut_z parameter is obeyed
  347. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  348. # update the default_data so it is used in the ncc_tools dict
  349. self.default_data.update({
  350. "vtipdia": tip_dia,
  351. "vtipangle": (tip_angle * 2),
  352. })
  353. self.ui.addtool_entry.set_value(tool_dia)
  354. return tool_dia
  355. else:
  356. return float(self.ui.addtool_entry.get_value())
  357. def on_selection(self):
  358. sel_combo = self.ui.selectmethod_combo.get_value()
  359. if sel_combo == _("Reference Object"):
  360. self.ui.reference_combo.show()
  361. self.ui.reference_combo_label.show()
  362. self.ui.reference_type_combo.show()
  363. self.ui.reference_type_label.show()
  364. else:
  365. self.ui.reference_combo.hide()
  366. self.ui.reference_combo_label.hide()
  367. self.ui.reference_type_combo.hide()
  368. self.ui.reference_type_label.hide()
  369. if sel_combo == _("Polygon Selection"):
  370. # disable rest-machining for single polygon painting
  371. # self.ui.rest_cb.set_value(False)
  372. # self.ui.rest_cb.setDisabled(True)
  373. pass
  374. if sel_combo == _("Area Selection"):
  375. # disable rest-machining for area painting
  376. # self.ui.rest_cb.set_value(False)
  377. # self.ui.rest_cb.setDisabled(True)
  378. self.ui.area_shape_label.show()
  379. self.ui.area_shape_radio.show()
  380. else:
  381. self.ui.addtool_entry.setDisabled(False)
  382. self.ui.addtool_btn.setDisabled(False)
  383. self.ui.deltool_btn.setDisabled(False)
  384. self.ui.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  385. self.ui.area_shape_label.hide()
  386. self.ui.area_shape_radio.hide()
  387. def on_order_changed(self, order):
  388. if order != 'no':
  389. self.build_ui()
  390. def on_rest_machining_check(self, state):
  391. if state:
  392. self.ui.order_radio.set_value('rev')
  393. self.ui.order_label.setDisabled(True)
  394. self.ui.order_radio.setDisabled(True)
  395. self.ui.offset_label.hide()
  396. self.ui.offset_entry.hide()
  397. self.ui.rest_offset_label.show()
  398. self.ui.rest_offset_entry.show()
  399. else:
  400. self.ui.order_label.setDisabled(False)
  401. self.ui.order_radio.setDisabled(False)
  402. self.ui.offset_label.show()
  403. self.ui.offset_entry.show()
  404. self.ui.rest_offset_label.hide()
  405. self.ui.rest_offset_entry.hide()
  406. def set_tool_ui(self):
  407. self.ui.tools_frame.show()
  408. self.reset_fields()
  409. self.old_tool_dia = self.app.defaults["tools_paintnewdia"]
  410. # updated units
  411. self.units = self.app.defaults['units'].upper()
  412. # set the working variables to a known state
  413. self.paint_tools.clear()
  414. self.tooluid = 0
  415. self.default_data.clear()
  416. self.default_data.update({
  417. "name": '_paint',
  418. "plot": self.app.defaults["geometry_plot"],
  419. "cutz": float(self.app.defaults["tools_paintcutz"]),
  420. "vtipdia": float(self.app.defaults["tools_painttipdia"]),
  421. "vtipangle": float(self.app.defaults["tools_painttipangle"]),
  422. "travelz": float(self.app.defaults["geometry_travelz"]),
  423. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  424. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  425. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  426. "dwell": self.app.defaults["geometry_dwell"],
  427. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  428. "multidepth": self.app.defaults["geometry_multidepth"],
  429. "ppname_g": self.app.defaults["geometry_ppname_g"],
  430. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  431. "extracut": self.app.defaults["geometry_extracut"],
  432. "extracut_length": self.app.defaults["geometry_extracut_length"],
  433. "toolchange": self.app.defaults["geometry_toolchange"],
  434. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  435. "endz": float(self.app.defaults["geometry_endz"]),
  436. "endxy": self.app.defaults["geometry_endxy"],
  437. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  438. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  439. "startz": self.app.defaults["geometry_startz"],
  440. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  441. "area_shape": self.app.defaults["geometry_area_shape"],
  442. "area_strategy": self.app.defaults["geometry_area_strategy"],
  443. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  444. "tooldia": self.app.defaults["tools_painttooldia"],
  445. "tools_paintoffset": self.app.defaults["tools_paintoffset"],
  446. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  447. "tools_selectmethod": self.app.defaults["tools_selectmethod"],
  448. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  449. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  450. "tools_paintoverlap": self.app.defaults["tools_paintoverlap"],
  451. "tools_paintrest": self.app.defaults["tools_paintrest"],
  452. })
  453. # ## Init the GUI interface
  454. self.ui.order_radio.set_value(self.app.defaults["tools_paintorder"])
  455. self.ui.offset_entry.set_value(self.app.defaults["tools_paintoffset"])
  456. self.ui.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  457. self.ui.selectmethod_combo.set_value(self.app.defaults["tools_selectmethod"])
  458. self.ui.area_shape_radio.set_value(self.app.defaults["tools_paint_area_shape"])
  459. self.ui.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  460. self.ui.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  461. self.ui.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  462. self.ui.cutz_entry.set_value(self.app.defaults["tools_paintcutz"])
  463. self.ui.tool_type_radio.set_value(self.app.defaults["tools_painttool_type"])
  464. self.ui.tipdia_entry.set_value(self.app.defaults["tools_painttipdia"])
  465. self.ui.tipangle_entry.set_value(self.app.defaults["tools_painttipangle"])
  466. self.ui.addtool_entry.set_value(self.app.defaults["tools_paintnewdia"])
  467. self.ui.rest_cb.set_value(self.app.defaults["tools_paintrest"])
  468. self.on_tool_type(val=self.ui.tool_type_radio.get_value())
  469. # # make the default object type, "Geometry"
  470. # self.type_obj_radio.set_value("geometry")
  471. # use the current selected object and make it visible in the Paint object combobox
  472. sel_list = self.app.collection.get_selected()
  473. if len(sel_list) == 1:
  474. active = self.app.collection.get_active()
  475. kind = active.kind
  476. if kind == 'gerber':
  477. self.ui.type_obj_radio.set_value(kind)
  478. else:
  479. kind = 'geometry'
  480. self.ui.type_obj_radio.set_value(kind)
  481. # run those once so the obj_type attribute is updated in the FCComboBoxes
  482. # to make sure that the last loaded object is displayed in the combobox
  483. self.on_type_obj_changed(val=kind)
  484. self.on_reference_combo_changed()
  485. self.ui.obj_combo.set_value(active.options['name'])
  486. else:
  487. kind = 'geometry'
  488. self.ui.type_obj_radio.set_value('geometry')
  489. # run those once so the obj_type attribute is updated in the FCComboBoxes
  490. # to make sure that the last loaded object is displayed in the combobox
  491. self.on_type_obj_changed(val=kind)
  492. self.on_reference_combo_changed()
  493. try:
  494. diameters = [float(self.app.defaults["tools_painttooldia"])]
  495. except (ValueError, TypeError):
  496. diameters = [eval(x) for x in self.app.defaults["tools_painttooldia"].split(",") if x != '']
  497. if not diameters:
  498. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  499. self.build_ui()
  500. # if the Paint Method is "Single" disable the tool table context menu
  501. if self.default_data["tools_selectmethod"] == "single":
  502. self.ui.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  503. return
  504. # call on self.on_tool_add() counts as an call to self.build_ui()
  505. # through this, we add a initial row / tool in the tool_table
  506. for dia in diameters:
  507. self.on_tool_add(dia, muted=True)
  508. self.on_rest_machining_check(state=self.app.defaults["tools_paintrest"])
  509. # if the Paint Method is "Single" disable the tool table context menu
  510. if self.default_data["tools_selectmethod"] == "single":
  511. self.ui.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  512. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  513. def rebuild_ui(self):
  514. # read the table tools uid
  515. current_uid_list = []
  516. for row in range(self.ui.tools_table.rowCount()):
  517. uid = int(self.ui.tools_table.item(row, 3).text())
  518. current_uid_list.append(uid)
  519. new_tools = {}
  520. new_uid = 1
  521. for current_uid in current_uid_list:
  522. new_tools[new_uid] = deepcopy(self.paint_tools[current_uid])
  523. new_uid += 1
  524. self.paint_tools = new_tools
  525. # the tools table changed therefore we need to rebuild it
  526. QtCore.QTimer.singleShot(20, self.build_ui)
  527. def build_ui(self):
  528. self.ui_disconnect()
  529. # updated units
  530. self.units = self.app.defaults['units'].upper()
  531. sorted_tools = []
  532. for k, v in self.paint_tools.items():
  533. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  534. order = self.ui.order_radio.get_value()
  535. if order == 'fwd':
  536. sorted_tools.sort(reverse=False)
  537. elif order == 'rev':
  538. sorted_tools.sort(reverse=True)
  539. else:
  540. pass
  541. n = len(sorted_tools)
  542. self.ui.tools_table.setRowCount(n)
  543. tool_id = 0
  544. for tool_sorted in sorted_tools:
  545. for tooluid_key, tooluid_value in self.paint_tools.items():
  546. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  547. tool_id += 1
  548. id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  549. id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  550. row_no = tool_id - 1
  551. self.ui.tools_table.setItem(row_no, 0, id_item) # Tool name/id
  552. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  553. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  554. self.ui.tools_table.setItem(row_no, 1, dia) # Diameter
  555. tool_type_item = FCComboBox()
  556. for item in self.tool_type_item_options:
  557. tool_type_item.addItem(item)
  558. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  559. idx = tool_type_item.findText(tooluid_value['tool_type'])
  560. tool_type_item.setCurrentIndex(idx)
  561. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  562. self.ui.tools_table.setCellWidget(row_no, 2, tool_type_item)
  563. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  564. self.ui.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  565. # make the diameter column editable
  566. for row in range(tool_id):
  567. self.ui.tools_table.item(row, 1).setFlags(
  568. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  569. # all the tools are selected by default
  570. self.ui.tools_table.selectColumn(0)
  571. #
  572. self.ui.tools_table.resizeColumnsToContents()
  573. self.ui.tools_table.resizeRowsToContents()
  574. vertical_header = self.ui.tools_table.verticalHeader()
  575. vertical_header.hide()
  576. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  577. horizontal_header = self.ui.tools_table.horizontalHeader()
  578. horizontal_header.setMinimumSectionSize(10)
  579. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  580. horizontal_header.resizeSection(0, 20)
  581. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  582. # self.ui.tools_table.setSortingEnabled(True)
  583. # sort by tool diameter
  584. # self.ui.tools_table.sortItems(1)
  585. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  586. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  587. self.ui_connect()
  588. # set the text on tool_data_label after loading the object
  589. sel_rows = set()
  590. sel_items = self.ui.tools_table.selectedItems()
  591. for it in sel_items:
  592. sel_rows.add(it.row())
  593. if len(sel_rows) > 1:
  594. self.ui.tool_data_label.setText(
  595. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  596. )
  597. def on_tool_add(self, dia=None, muted=None):
  598. self.blockSignals(True)
  599. if dia:
  600. tool_dia = dia
  601. else:
  602. tool_dia = self.on_calculate_tooldia()
  603. if tool_dia is None:
  604. self.build_ui()
  605. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  606. return
  607. # construct a list of all 'tooluid' in the self.tools
  608. tool_uid_list = []
  609. for tooluid_key in self.paint_tools:
  610. tool_uid_item = int(tooluid_key)
  611. tool_uid_list.append(tool_uid_item)
  612. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  613. if not tool_uid_list:
  614. max_uid = 0
  615. else:
  616. max_uid = max(tool_uid_list)
  617. self.tooluid = int(max_uid + 1)
  618. tool_dias = []
  619. for k, v in self.paint_tools.items():
  620. for tool_v in v.keys():
  621. if tool_v == 'tooldia':
  622. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  623. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  624. if muted is None:
  625. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  626. self.blockSignals(False)
  627. return
  628. else:
  629. if muted is None:
  630. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  631. self.paint_tools.update({
  632. int(self.tooluid): {
  633. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  634. 'offset': 'Path',
  635. 'offset_value': 0.0,
  636. 'type': 'Iso',
  637. 'tool_type': self.ui.tool_type_radio.get_value(),
  638. 'data': dict(self.default_data),
  639. 'solid_geometry': []
  640. }
  641. })
  642. self.blockSignals(False)
  643. self.build_ui()
  644. # select the tool just added
  645. for row in range(self.ui.tools_table.rowCount()):
  646. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  647. self.ui.tools_table.selectRow(row)
  648. break
  649. def on_tool_edit(self, item):
  650. self.blockSignals(True)
  651. edited_row = item.row()
  652. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  653. tool_dias = []
  654. try:
  655. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  656. except ValueError:
  657. # try to convert comma to decimal point. if it's still not working error message and return
  658. try:
  659. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  660. except ValueError:
  661. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  662. return
  663. for k, v in self.paint_tools.items():
  664. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  665. # identify the tool that was edited and get it's tooluid
  666. if new_tool_dia not in tool_dias:
  667. self.paint_tools[editeduid]['tooldia'] = new_tool_dia
  668. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  669. self.blockSignals(False)
  670. self.build_ui()
  671. return
  672. # identify the old tool_dia and restore the text in tool table
  673. for k, v in self.paint_tools.items():
  674. if k == editeduid:
  675. old_tool_dia = v['tooldia']
  676. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  677. restore_dia_item.setText(str(old_tool_dia))
  678. break
  679. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  680. self.blockSignals(False)
  681. self.build_ui()
  682. # def on_tool_copy(self, all=None):
  683. # try:
  684. # self.ui.tools_table.itemChanged.disconnect()
  685. # except:
  686. # pass
  687. #
  688. # # find the tool_uid maximum value in the self.tools
  689. # uid_list = []
  690. # for key in self.paint_tools:
  691. # uid_list.append(int(key))
  692. # try:
  693. # max_uid = max(uid_list, key=int)
  694. # except ValueError:
  695. # max_uid = 0
  696. #
  697. # if all is None:
  698. # if self.ui.tools_table.selectedItems():
  699. # for current_row in self.ui.tools_table.selectedItems():
  700. # # sometime the header get selected and it has row number -1
  701. # # we don't want to do anything with the header :)
  702. # if current_row.row() < 0:
  703. # continue
  704. # try:
  705. # tooluid_copy = int(self.ui.tools_table.item(current_row.row(), 3).text())
  706. # max_uid += 1
  707. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  708. # for td in self.paint_tools:
  709. # print("COPIED", self.paint_tools[td])
  710. # self.build_ui()
  711. # except AttributeError:
  712. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  713. # self.build_ui()
  714. # return
  715. # except Exception as e:
  716. # log.debug("on_tool_copy() --> " + str(e))
  717. # # deselect the table
  718. # # self.ui.geo_tools_table.clearSelection()
  719. # else:
  720. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  721. # self.build_ui()
  722. # return
  723. # else:
  724. # # we copy all tools in geo_tools_table
  725. # try:
  726. # temp_tools = dict(self.paint_tools)
  727. # max_uid += 1
  728. # for tooluid in temp_tools:
  729. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  730. # temp_tools.clear()
  731. # self.build_ui()
  732. # except Exception as e:
  733. # log.debug("on_tool_copy() --> " + str(e))
  734. #
  735. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  736. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  737. """
  738. Will delete a tool in the tool table
  739. :param rows_to_delete: which rows to delete; can be a list
  740. :param all_tools: delete all tools in the tool table
  741. :return:
  742. """
  743. self.blockSignals(True)
  744. deleted_tools_list = []
  745. if all_tools:
  746. self.paint_tools.clear()
  747. self.blockSignals(False)
  748. self.build_ui()
  749. return
  750. if rows_to_delete:
  751. try:
  752. for row in rows_to_delete:
  753. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  754. deleted_tools_list.append(tooluid_del)
  755. except TypeError:
  756. deleted_tools_list.append(rows_to_delete)
  757. for t in deleted_tools_list:
  758. self.paint_tools.pop(t, None)
  759. self.blockSignals(False)
  760. self.build_ui()
  761. return
  762. try:
  763. if self.ui.tools_table.selectedItems():
  764. for row_sel in self.ui.tools_table.selectedItems():
  765. row = row_sel.row()
  766. if row < 0:
  767. continue
  768. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  769. deleted_tools_list.append(tooluid_del)
  770. for t in deleted_tools_list:
  771. self.paint_tools.pop(t, None)
  772. except AttributeError:
  773. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  774. self.blockSignals(False)
  775. return
  776. except Exception as e:
  777. log.debug(str(e))
  778. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  779. self.blockSignals(False)
  780. self.build_ui()
  781. def on_paint_button_click(self):
  782. """
  783. Slot for clicking signal
  784. :return: None
  785. """
  786. self.app.defaults.report_usage("on_paint_button_click")
  787. self.first_click = False
  788. self.cursor_pos = None
  789. self.mouse_is_dragging = False
  790. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  791. if prog_plot:
  792. self.temp_shapes.clear(update=True)
  793. self.sel_rect = []
  794. obj_type = self.ui.type_obj_radio.get_value
  795. self.circle_steps = int(self.app.defaults["gerber_circle_steps"]) if obj_type == 'gerber' else \
  796. int(self.app.defaults["geometry_circle_steps"])
  797. self.obj_name = self.ui.obj_combo.currentText()
  798. # Get source object.
  799. try:
  800. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  801. except Exception as e:
  802. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  803. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object: %s"), self.obj_name))
  804. return
  805. if self.paint_obj is None:
  806. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), self.paint_obj))
  807. return
  808. # test if the Geometry Object is multigeo and return Fail if True because
  809. # for now Paint don't work on MultiGeo
  810. if self.paint_obj.kind == 'geometry' and self.paint_obj.multigeo is True:
  811. self.app.inform.emit('[ERROR_NOTCL] %s...' % _("Can't do Paint on MultiGeo geometries"))
  812. return 'Fail'
  813. self.o_name = '%s_mt_paint' % self.obj_name
  814. # use the selected tools in the tool table; get diameters
  815. self.tooldia_list = []
  816. table_items = self.ui.tools_table.selectedItems()
  817. sel_rows = {t.row() for t in table_items}
  818. if len(sel_rows) > 0:
  819. for row in sel_rows:
  820. try:
  821. self.tooldia = float(self.ui.tools_table.item(row, 1).text())
  822. except ValueError:
  823. # try to convert comma to decimal point. if it's still not working error message and return
  824. try:
  825. self.tooldia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
  826. except ValueError:
  827. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  828. continue
  829. self.tooldia_list.append(self.tooldia)
  830. else:
  831. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  832. return
  833. self.select_method = self.ui.selectmethod_combo.get_value()
  834. if self.select_method == _("All"):
  835. self.paint_poly_all(self.paint_obj, tooldia=self.tooldia_list, outname=self.o_name)
  836. elif self.select_method == _("Polygon Selection"):
  837. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  838. if self.app.ui.grid_snap_btn.isChecked():
  839. self.grid_status_memory = True
  840. self.app.ui.grid_snap_btn.trigger()
  841. else:
  842. self.grid_status_memory = False
  843. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  844. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  845. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  846. if self.app.is_legacy is False:
  847. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  848. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  849. else:
  850. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  851. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  852. # disconnect flags
  853. self.poly_sel_disconnect_flag = True
  854. elif self.select_method == _("Area Selection"):
  855. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  856. if self.app.is_legacy is False:
  857. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  858. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  859. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  860. else:
  861. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  862. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  863. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  864. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  865. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  866. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  867. # disconnect flags
  868. self.area_sel_disconnect_flag = True
  869. elif self.select_method == _("Reference Object"):
  870. self.bound_obj_name = self.reference_combo.currentText()
  871. # Get source object.
  872. try:
  873. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  874. except Exception:
  875. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  876. return "Could not retrieve object: %s" % self.obj_name
  877. self.paint_poly_ref(obj=self.paint_obj, sel_obj=self.bound_obj, tooldia=self.tooldia_list,
  878. outname=self.o_name)
  879. # To be called after clicking on the plot.
  880. def on_single_poly_mouse_release(self, event):
  881. if self.app.is_legacy is False:
  882. event_pos = event.pos
  883. right_button = 2
  884. event_is_dragging = self.app.event_is_dragging
  885. else:
  886. event_pos = (event.xdata, event.ydata)
  887. right_button = 3
  888. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  889. try:
  890. x = float(event_pos[0])
  891. y = float(event_pos[1])
  892. except TypeError:
  893. return
  894. event_pos = (x, y)
  895. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  896. # do paint single only for left mouse clicks
  897. if event.button == 1:
  898. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  899. if clicked_poly:
  900. if clicked_poly not in self.poly_dict.values():
  901. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  902. layer=0,
  903. shape=clicked_poly,
  904. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  905. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  906. visible=True)
  907. self.poly_dict[shape_id] = clicked_poly
  908. self.app.inform.emit(
  909. '%s: %d. %s' % (_("Added polygon"),
  910. int(len(self.poly_dict)),
  911. _("Click to add next polygon or right click to start painting."))
  912. )
  913. else:
  914. try:
  915. for k, v in list(self.poly_dict.items()):
  916. if v == clicked_poly:
  917. self.app.tool_shapes.remove(k)
  918. self.poly_dict.pop(k)
  919. break
  920. except TypeError:
  921. return
  922. self.app.inform.emit(
  923. '%s. %s' % (_("Removed polygon"),
  924. _("Click to add/remove next polygon or right click to start painting."))
  925. )
  926. self.app.tool_shapes.redraw()
  927. else:
  928. self.app.inform.emit(_("No polygon detected under click position."))
  929. elif event.button == right_button and event_is_dragging is False:
  930. # restore the Grid snapping if it was active before
  931. if self.grid_status_memory is True:
  932. self.app.ui.grid_snap_btn.trigger()
  933. if self.app.is_legacy is False:
  934. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  935. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  936. else:
  937. self.app.plotcanvas.graph_event_disconnect(self.mr)
  938. self.app.plotcanvas.graph_event_disconnect(self.kp)
  939. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  940. self.app.on_mouse_click_over_plot)
  941. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  942. self.app.on_mouse_click_release_over_plot)
  943. # disconnect flags
  944. self.poly_sel_disconnect_flag = False
  945. self.app.tool_shapes.clear(update=True)
  946. if self.poly_dict:
  947. poly_list = deepcopy(list(self.poly_dict.values()))
  948. self.paint_poly(self.paint_obj, inside_pt=(curr_pos[0], curr_pos[1]), poly_list=poly_list,
  949. tooldia=self.tooldia_list)
  950. self.poly_dict.clear()
  951. else:
  952. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  953. # To be called after clicking on the plot.
  954. def on_mouse_release(self, event):
  955. if self.app.is_legacy is False:
  956. event_pos = event.pos
  957. # event_is_dragging = event.is_dragging
  958. right_button = 2
  959. else:
  960. event_pos = (event.xdata, event.ydata)
  961. # event_is_dragging = self.app.plotcanvas.is_dragging
  962. right_button = 3
  963. try:
  964. x = float(event_pos[0])
  965. y = float(event_pos[1])
  966. except TypeError:
  967. return
  968. event_pos = (x, y)
  969. shape_type = self.ui.area_shape_radio.get_value()
  970. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  971. if self.app.grid_status():
  972. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  973. x1, y1 = curr_pos[0], curr_pos[1]
  974. # do paint single only for left mouse clicks
  975. if event.button == 1:
  976. if shape_type == "square":
  977. if not self.first_click:
  978. self.first_click = True
  979. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  980. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  981. if self.app.grid_status():
  982. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  983. else:
  984. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  985. self.app.delete_selection_shape()
  986. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  987. pt1 = (x0, y0)
  988. pt2 = (x1, y0)
  989. pt3 = (x1, y1)
  990. pt4 = (x0, y1)
  991. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  992. self.sel_rect.append(new_rectangle)
  993. # add a temporary shape on canvas
  994. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  995. self.first_click = False
  996. return
  997. else:
  998. self.points.append((x1, y1))
  999. if len(self.points) > 1:
  1000. self.poly_drawn = True
  1001. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1002. return ""
  1003. elif event.button == right_button and self.mouse_is_dragging is False:
  1004. shape_type = self.ui.area_shape_radio.get_value()
  1005. if shape_type == "square":
  1006. self.first_click = False
  1007. else:
  1008. # if we finish to add a polygon
  1009. if self.poly_drawn is True:
  1010. try:
  1011. # try to add the point where we last clicked if it is not already in the self.points
  1012. last_pt = (x1, y1)
  1013. if last_pt != self.points[-1]:
  1014. self.points.append(last_pt)
  1015. except IndexError:
  1016. pass
  1017. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1018. if len(self.points) > 2:
  1019. self.delete_moving_selection_shape()
  1020. pol = Polygon(self.points)
  1021. # do not add invalid polygons even if they are drawn by utility geometry
  1022. if pol.is_valid:
  1023. self.sel_rect.append(pol)
  1024. self.draw_selection_shape_polygon(points=self.points)
  1025. self.app.inform.emit(
  1026. _("Zone added. Click to start adding next zone or right click to finish."))
  1027. self.points = []
  1028. self.poly_drawn = False
  1029. return
  1030. self.delete_tool_selection_shape()
  1031. if self.app.is_legacy is False:
  1032. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1033. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1034. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1035. else:
  1036. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1037. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1038. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1039. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1040. self.app.on_mouse_click_over_plot)
  1041. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1042. self.app.on_mouse_move_over_plot)
  1043. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1044. self.app.on_mouse_click_release_over_plot)
  1045. # disconnect flags
  1046. self.area_sel_disconnect_flag = False
  1047. if len(self.sel_rect) == 0:
  1048. return
  1049. self.sel_rect = cascaded_union(self.sel_rect)
  1050. self.paint_poly_area(obj=self.paint_obj, tooldia=self.tooldia_list, sel_obj=self.sel_rect,
  1051. outname=self.o_name)
  1052. # called on mouse move
  1053. def on_mouse_move(self, event):
  1054. shape_type = self.ui.area_shape_radio.get_value()
  1055. if self.app.is_legacy is False:
  1056. event_pos = event.pos
  1057. event_is_dragging = event.is_dragging
  1058. # right_button = 2
  1059. else:
  1060. event_pos = (event.xdata, event.ydata)
  1061. event_is_dragging = self.app.plotcanvas.is_dragging
  1062. # right_button = 3
  1063. try:
  1064. x = float(event_pos[0])
  1065. y = float(event_pos[1])
  1066. except TypeError:
  1067. return
  1068. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1069. # detect mouse dragging motion
  1070. if event_is_dragging == 1:
  1071. self.mouse_is_dragging = True
  1072. else:
  1073. self.mouse_is_dragging = False
  1074. # update the cursor position
  1075. if self.app.grid_status():
  1076. # Update cursor
  1077. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1078. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1079. symbol='++', edge_color=self.app.cursor_color_3D,
  1080. edge_width=self.app.defaults["global_cursor_width"],
  1081. size=self.app.defaults["global_cursor_size"])
  1082. if self.cursor_pos is None:
  1083. self.cursor_pos = (0, 0)
  1084. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  1085. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  1086. # # update the positions on status bar
  1087. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1088. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  1089. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1090. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  1091. units = self.app.defaults["units"].lower()
  1092. self.app.plotcanvas.text_hud.text = \
  1093. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  1094. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  1095. # draw the utility geometry
  1096. if shape_type == "square":
  1097. if self.first_click:
  1098. self.app.delete_selection_shape()
  1099. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1100. coords=(curr_pos[0], curr_pos[1]))
  1101. else:
  1102. self.delete_moving_selection_shape()
  1103. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  1104. def on_key_press(self, event):
  1105. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1106. # matplotlib_key_flag = False
  1107. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1108. if type(event) is int:
  1109. key = event
  1110. # events from the GUI are of type QKeyEvent
  1111. elif type(event) == QtGui.QKeyEvent:
  1112. key = event.key()
  1113. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1114. # matplotlib_key_flag = True
  1115. key = event.key
  1116. key = QtGui.QKeySequence(key)
  1117. # check for modifiers
  1118. key_string = key.toString().lower()
  1119. if '+' in key_string:
  1120. mod, __, key_text = key_string.rpartition('+')
  1121. if mod.lower() == 'ctrl':
  1122. # modifiers = QtCore.Qt.ControlModifier
  1123. pass
  1124. elif mod.lower() == 'alt':
  1125. # modifiers = QtCore.Qt.AltModifier
  1126. pass
  1127. elif mod.lower() == 'shift':
  1128. # modifiers = QtCore.Qt.ShiftModifier
  1129. pass
  1130. else:
  1131. # modifiers = QtCore.Qt.NoModifier
  1132. pass
  1133. key = QtGui.QKeySequence(key_text)
  1134. # events from Vispy are of type KeyEvent
  1135. else:
  1136. key = event.key
  1137. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1138. if self.area_sel_disconnect_flag is True:
  1139. try:
  1140. if self.app.is_legacy is False:
  1141. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1142. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1143. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1144. else:
  1145. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1146. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1147. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1148. except Exception as e:
  1149. log.debug("ToolPaint.on_key_press() _1 --> %s" % str(e))
  1150. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1151. self.app.on_mouse_click_over_plot)
  1152. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1153. self.app.on_mouse_move_over_plot)
  1154. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1155. self.app.on_mouse_click_release_over_plot)
  1156. if self.poly_sel_disconnect_flag is False:
  1157. try:
  1158. # restore the Grid snapping if it was active before
  1159. if self.grid_status_memory is True:
  1160. self.app.ui.grid_snap_btn.trigger()
  1161. if self.app.is_legacy is False:
  1162. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1163. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1164. else:
  1165. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1166. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1167. self.app.tool_shapes.clear(update=True)
  1168. except Exception as e:
  1169. log.debug("ToolPaint.on_key_press() _2 --> %s" % str(e))
  1170. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1171. self.app.on_mouse_click_release_over_plot)
  1172. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1173. self.app.on_mouse_click_over_plot)
  1174. self.points = []
  1175. self.poly_drawn = False
  1176. self.poly_dict.clear()
  1177. self.delete_moving_selection_shape()
  1178. self.delete_tool_selection_shape()
  1179. def paint_polygon_worker(self, polyg, tooldiameter, paint_method, over, conn, cont, prog_plot, obj):
  1180. cpoly = None
  1181. if paint_method == _("Standard"):
  1182. try:
  1183. # Type(cp) == FlatCAMRTreeStorage | None
  1184. cpoly = self.clear_polygon(polyg,
  1185. tooldia=tooldiameter,
  1186. steps_per_circle=self.circle_steps,
  1187. overlap=over,
  1188. contour=cont,
  1189. connect=conn,
  1190. prog_plot=prog_plot)
  1191. except grace:
  1192. return "fail"
  1193. except Exception as ee:
  1194. log.debug("ToolPaint.paint_polygon_worker() Standard --> %s" % str(ee))
  1195. elif paint_method == _("Seed"):
  1196. try:
  1197. # Type(cp) == FlatCAMRTreeStorage | None
  1198. cpoly = self.clear_polygon2(polyg,
  1199. tooldia=tooldiameter,
  1200. steps_per_circle=self.circle_steps,
  1201. overlap=over,
  1202. contour=cont,
  1203. connect=conn,
  1204. prog_plot=prog_plot)
  1205. except grace:
  1206. return "fail"
  1207. except Exception as ee:
  1208. log.debug("ToolPaint.paint_polygon_worker() Seed --> %s" % str(ee))
  1209. elif paint_method == _("Lines"):
  1210. try:
  1211. # Type(cp) == FlatCAMRTreeStorage | None
  1212. cpoly = self.clear_polygon3(polyg,
  1213. tooldia=tooldiameter,
  1214. steps_per_circle=self.circle_steps,
  1215. overlap=over,
  1216. contour=cont,
  1217. connect=conn,
  1218. prog_plot=prog_plot)
  1219. except grace:
  1220. return "fail"
  1221. except Exception as ee:
  1222. log.debug("ToolPaint.paint_polygon_worker() Lines --> %s" % str(ee))
  1223. elif paint_method == _("Laser_lines"):
  1224. try:
  1225. # line = None
  1226. # aperture_size = None
  1227. # the key is the aperture type and the val is a list of geo elements
  1228. flash_el_dict = {}
  1229. # the key is the aperture size, the val is a list of geo elements
  1230. traces_el_dict = {}
  1231. # find the flashes and the lines that are in the selected polygon and store them separately
  1232. for apid, apval in obj.apertures.items():
  1233. for geo_el in apval['geometry']:
  1234. if apval["size"] == 0.0:
  1235. if apval["size"] in traces_el_dict:
  1236. traces_el_dict[apval["size"]].append(geo_el)
  1237. else:
  1238. traces_el_dict[apval["size"]] = [geo_el]
  1239. if 'follow' in geo_el and geo_el['follow'].within(polyg):
  1240. if isinstance(geo_el['follow'], Point):
  1241. if apval["type"] == 'C':
  1242. if 'C' in flash_el_dict:
  1243. flash_el_dict['C'].append(geo_el)
  1244. else:
  1245. flash_el_dict['C'] = [geo_el]
  1246. elif apval["type"] == 'O':
  1247. if 'O' in flash_el_dict:
  1248. flash_el_dict['O'].append(geo_el)
  1249. else:
  1250. flash_el_dict['O'] = [geo_el]
  1251. elif apval["type"] == 'R':
  1252. if 'R' in flash_el_dict:
  1253. flash_el_dict['R'].append(geo_el)
  1254. else:
  1255. flash_el_dict['R'] = [geo_el]
  1256. else:
  1257. aperture_size = apval['size']
  1258. if aperture_size in traces_el_dict:
  1259. traces_el_dict[aperture_size].append(geo_el)
  1260. else:
  1261. traces_el_dict[aperture_size] = [geo_el]
  1262. cpoly = FlatCAMRTreeStorage()
  1263. pads_lines_list = []
  1264. # process the flashes found in the selected polygon with the 'lines' method for rectangular
  1265. # flashes and with _("Seed") for oblong and circular flashes
  1266. # and pads (flahes) need the contour therefore I override the GUI settings with always True
  1267. for ap_type in flash_el_dict:
  1268. for elem in flash_el_dict[ap_type]:
  1269. if 'solid' in elem:
  1270. if ap_type == 'C':
  1271. f_o = self.clear_polygon2(elem['solid'],
  1272. tooldia=tooldiameter,
  1273. steps_per_circle=self.app.defaults[
  1274. "geometry_circle_steps"],
  1275. overlap=over,
  1276. contour=True,
  1277. connect=conn,
  1278. prog_plot=prog_plot)
  1279. pads_lines_list += [p for p in f_o.get_objects() if p]
  1280. elif ap_type == 'O':
  1281. f_o = self.clear_polygon2(elem['solid'],
  1282. tooldia=tooldiameter,
  1283. steps_per_circle=self.app.defaults[
  1284. "geometry_circle_steps"],
  1285. overlap=over,
  1286. contour=True,
  1287. connect=conn,
  1288. prog_plot=prog_plot)
  1289. pads_lines_list += [p for p in f_o.get_objects() if p]
  1290. elif ap_type == 'R':
  1291. f_o = self.clear_polygon3(elem['solid'],
  1292. tooldia=tooldiameter,
  1293. steps_per_circle=self.app.defaults[
  1294. "geometry_circle_steps"],
  1295. overlap=over,
  1296. contour=True,
  1297. connect=conn,
  1298. prog_plot=prog_plot)
  1299. pads_lines_list += [p for p in f_o.get_objects() if p]
  1300. # add the lines from pads to the storage
  1301. try:
  1302. for lin in pads_lines_list:
  1303. if lin:
  1304. cpoly.insert(lin)
  1305. except TypeError:
  1306. cpoly.insert(pads_lines_list)
  1307. copper_lines_list = []
  1308. # process the traces found in the selected polygon using the 'laser_lines' method,
  1309. # method which will follow the 'follow' line therefore use the longer path possible for the
  1310. # laser, therefore the acceleration will play a smaller factor
  1311. for aperture_size in traces_el_dict:
  1312. for elem in traces_el_dict[aperture_size]:
  1313. line = elem['follow']
  1314. if line:
  1315. t_o = self.fill_with_lines(line, aperture_size,
  1316. tooldia=tooldiameter,
  1317. steps_per_circle=self.app.defaults[
  1318. "geometry_circle_steps"],
  1319. overlap=over,
  1320. contour=cont,
  1321. connect=conn,
  1322. prog_plot=prog_plot)
  1323. copper_lines_list += [p for p in t_o.get_objects() if p]
  1324. # add the lines from copper features to storage but first try to make as few lines as possible
  1325. # by trying to fuse them
  1326. lines_union = linemerge(unary_union(copper_lines_list))
  1327. try:
  1328. for lin in lines_union:
  1329. if lin:
  1330. cpoly.insert(lin)
  1331. except TypeError:
  1332. cpoly.insert(lines_union)
  1333. # # determine the Gerber follow line
  1334. # for apid, apval in obj.apertures.items():
  1335. # for geo_el in apval['geometry']:
  1336. # if 'solid' in geo_el:
  1337. # if Point(inside_pt).within(geo_el['solid']):
  1338. # if not isinstance(geo_el['follow'], Point):
  1339. # line = geo_el['follow']
  1340. #
  1341. # if apval['type'] == 'C':
  1342. # aperture_size = apval['size']
  1343. # else:
  1344. # if apval['width'] > apval['height']:
  1345. # aperture_size = apval['height']
  1346. # else:
  1347. # aperture_size = apval['width']
  1348. #
  1349. # if line:
  1350. # cpoly = self.fill_with_lines(line, aperture_size,
  1351. # tooldia=tooldiameter,
  1352. # steps_per_circle=self.circle_steps,
  1353. # overlap=over,
  1354. # contour=cont,
  1355. # connect=conn,
  1356. # prog_plot=prog_plot)
  1357. except grace:
  1358. return "fail"
  1359. except Exception as ee:
  1360. log.debug("ToolPaint.paint_polygon_worker() Laser Lines --> %s" % str(ee))
  1361. elif paint_method == _("Combo"):
  1362. try:
  1363. self.app.inform.emit(_("Painting polygon with method: lines."))
  1364. cpoly = self.clear_polygon3(polyg,
  1365. tooldia=tooldiameter,
  1366. steps_per_circle=self.circle_steps,
  1367. overlap=over,
  1368. contour=cont,
  1369. connect=conn,
  1370. prog_plot=prog_plot)
  1371. if cpoly and cpoly.objects:
  1372. pass
  1373. else:
  1374. self.app.inform.emit(_("Failed. Painting polygon with method: seed."))
  1375. cpoly = self.clear_polygon2(polyg,
  1376. tooldia=tooldiameter,
  1377. steps_per_circle=self.circle_steps,
  1378. overlap=over,
  1379. contour=cont,
  1380. connect=conn,
  1381. prog_plot=prog_plot)
  1382. if cpoly and cpoly.objects:
  1383. pass
  1384. else:
  1385. self.app.inform.emit(_("Failed. Painting polygon with method: standard."))
  1386. cpoly = self.clear_polygon(polyg,
  1387. tooldia=tooldiameter,
  1388. steps_per_circle=self.circle_steps,
  1389. overlap=over,
  1390. contour=cont,
  1391. connect=conn,
  1392. prog_plot=prog_plot)
  1393. except grace:
  1394. return "fail"
  1395. except Exception as ee:
  1396. log.debug("ToolPaint.paint_polygon_worker() Combo --> %s" % str(ee))
  1397. if cpoly and cpoly.objects:
  1398. return cpoly
  1399. else:
  1400. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be painted completely'))
  1401. return None
  1402. def paint_geo(self, obj, geometry, tooldia=None, order=None, method=None, outname=None,
  1403. tools_storage=None, plot=True, run_threaded=True):
  1404. """
  1405. Paints a given geometry.
  1406. :param obj: painted object
  1407. :param tooldia: Diameter of the painting tool
  1408. :param order: if the tools are ordered and how
  1409. :param outname: Name of the resulting Geometry Object.
  1410. :param method: choice out of _("Seed"), 'normal', 'lines'
  1411. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1412. Usage of the different one is related to when this function is called
  1413. from a TcL command.
  1414. :param plot:
  1415. :param run_threaded:
  1416. :return: None
  1417. """
  1418. paint_method = method if method is not None else self.ui.paintmethod_combo.get_value()
  1419. # determine if to use the progressive plotting
  1420. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1421. name = outname if outname is not None else self.obj_name + "_paint"
  1422. order = order if order is not None else self.ui.order_radio.get_value()
  1423. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1424. sorted_tools = []
  1425. if tooldia is not None:
  1426. try:
  1427. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1428. except AttributeError:
  1429. if not isinstance(tooldia, list):
  1430. sorted_tools = [float(tooldia)]
  1431. else:
  1432. sorted_tools = tooldia
  1433. else:
  1434. table_items = self.ui.tools_table.selectedItems()
  1435. sel_rows = {t.row() for t in table_items}
  1436. for row in sel_rows:
  1437. try:
  1438. self.tooldia = float(self.ui.tools_table.item(row, 1).text())
  1439. except ValueError:
  1440. # try to convert comma to decimal point. if it's still not working error message and return
  1441. try:
  1442. self.tooldia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
  1443. except ValueError:
  1444. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1445. continue
  1446. sorted_tools.append(self.tooldia)
  1447. if not sorted_tools:
  1448. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1449. return 'fail'
  1450. # Initializes the new geometry object
  1451. def job_normal_clear(geo_obj, app_obj):
  1452. tool_dia = None
  1453. current_uid = None
  1454. final_solid_geometry = []
  1455. old_disp_number = 0
  1456. # sort the tools if we have an order selected in the UI
  1457. if order == 'fwd':
  1458. sorted_tools.sort(reverse=False)
  1459. elif order == 'rev':
  1460. sorted_tools.sort(reverse=True)
  1461. else:
  1462. pass
  1463. for tool_dia in sorted_tools:
  1464. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1465. msg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1466. str(tool_dia),
  1467. self.units.lower(),
  1468. _('started'))
  1469. self.app.inform.emit(msg)
  1470. self.app.proc_container.update_view_text(' %d%%' % 0)
  1471. # find the tooluid associated with the current tool_dia so we know what tool to use
  1472. for k, v in tools_storage.items():
  1473. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1474. current_uid = int(k)
  1475. if not current_uid:
  1476. return "fail"
  1477. # determine the tool parameters to use
  1478. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1479. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1480. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1481. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  1482. poly_buf = []
  1483. for pol in geometry:
  1484. buffered_pol = pol.buffer(-paint_offset)
  1485. if buffered_pol and not buffered_pol.is_empty:
  1486. poly_buf.append(buffered_pol)
  1487. if not poly_buf:
  1488. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1489. continue
  1490. # variables to display the percentage of work done
  1491. geo_len = len(poly_buf)
  1492. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1493. pol_nr = 0
  1494. # -----------------------------
  1495. # effective polygon clearing job
  1496. # -----------------------------
  1497. try:
  1498. cp = []
  1499. try:
  1500. for pp in poly_buf:
  1501. # provide the app with a way to process the GUI events when in a blocking loop
  1502. QtWidgets.QApplication.processEvents()
  1503. if self.app.abort_flag:
  1504. # graceful abort requested by the user
  1505. raise grace
  1506. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1507. cont=cont, paint_method=paint_method, obj=obj,
  1508. prog_plot=prog_plot)
  1509. if geo_res:
  1510. cp.append(geo_res)
  1511. pol_nr += 1
  1512. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1513. # log.debug("Polygons cleared: %d" % pol_nr)
  1514. if old_disp_number < disp_number <= 100:
  1515. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1516. old_disp_number = disp_number
  1517. except TypeError:
  1518. # provide the app with a way to process the GUI events when in a blocking loop
  1519. QtWidgets.QApplication.processEvents()
  1520. if self.app.abort_flag:
  1521. # graceful abort requested by the user
  1522. raise grace
  1523. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1524. cont=cont, paint_method=paint_method, obj=obj,
  1525. prog_plot=prog_plot)
  1526. if geo_res:
  1527. cp.append(geo_res)
  1528. total_geometry = []
  1529. if cp:
  1530. for x in cp:
  1531. total_geometry += list(x.get_objects())
  1532. # clean the geometry
  1533. new_geo = [g for g in total_geometry if g and not g.is_empty]
  1534. total_geometry = new_geo
  1535. final_solid_geometry += total_geometry
  1536. except grace:
  1537. return "fail"
  1538. except Exception as e:
  1539. log.debug("Could not Paint the polygons. %s" % str(e))
  1540. mssg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  1541. "Or a different strategy of paint"), str(e))
  1542. self.app.inform.emit(mssg)
  1543. continue
  1544. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1545. # dictionary and then reset the temporary list that stored that solid_geometry
  1546. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1547. tools_storage[current_uid]['data']['name'] = name
  1548. # clean the progressive plotted shapes if it was used
  1549. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1550. self.temp_shapes.clear(update=True)
  1551. # delete tools with empty geometry
  1552. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1553. for uid in list(tools_storage.keys()):
  1554. # if the solid_geometry (type=list) is empty
  1555. if not tools_storage[uid]['solid_geometry']:
  1556. tools_storage.pop(uid, None)
  1557. if not tools_storage:
  1558. return 'fail'
  1559. geo_obj.options["cnctooldia"] = str(tool_dia)
  1560. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1561. geo_obj.multigeo = True
  1562. geo_obj.multitool = True
  1563. geo_obj.tools.clear()
  1564. geo_obj.tools = dict(tools_storage)
  1565. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1566. try:
  1567. if isinstance(geo_obj.solid_geometry, list):
  1568. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1569. else:
  1570. a, b, c, d = geo_obj.solid_geometry.bounds
  1571. geo_obj.options['xmin'] = a
  1572. geo_obj.options['ymin'] = b
  1573. geo_obj.options['xmax'] = c
  1574. geo_obj.options['ymax'] = d
  1575. except Exception as ee:
  1576. log.debug("ToolPaint.paint_poly.job_init() bounds error --> %s" % str(ee))
  1577. return
  1578. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1579. has_solid_geo = 0
  1580. for tooluid in geo_obj.tools:
  1581. if geo_obj.tools[tooluid]['solid_geometry']:
  1582. has_solid_geo += 1
  1583. if has_solid_geo == 0:
  1584. app_obj.inform.emit('[ERROR] %s' %
  1585. _("There is no Painting Geometry in the file.\n"
  1586. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1587. "Change the painting parameters and try again."))
  1588. return "fail"
  1589. # Experimental...
  1590. # print("Indexing...", end=' ')
  1591. # geo_obj.make_index()
  1592. # Initializes the new geometry object
  1593. def job_rest_clear(geo_obj, app_obj):
  1594. current_uid = None
  1595. final_solid_geometry = []
  1596. old_disp_number = 0
  1597. # sort the tools reversed for the rest machining
  1598. sorted_tools.sort(reverse=True)
  1599. paint_offset = self.ui.rest_offset_entry.get_value()
  1600. poly_buf = []
  1601. for pol in geometry:
  1602. buffered_pol = pol.buffer(-paint_offset)
  1603. if buffered_pol and not buffered_pol.is_empty:
  1604. try:
  1605. for x in buffered_pol:
  1606. poly_buf.append(x)
  1607. except TypeError:
  1608. poly_buf.append(buffered_pol)
  1609. poly_buf = cascaded_union(poly_buf)
  1610. if not poly_buf:
  1611. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1612. return 'fail'
  1613. # variables to display the percentage of work done
  1614. geo_len = len(poly_buf)
  1615. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1616. for tool_dia in sorted_tools:
  1617. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1618. msg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1619. str(tool_dia),
  1620. self.units.lower(),
  1621. _('started'))
  1622. self.app.inform.emit(msg)
  1623. self.app.proc_container.update_view_text(' %d%%' % 0)
  1624. # find the tooluid associated with the current tool_dia so we know what tool to use
  1625. for k, v in tools_storage.items():
  1626. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1627. current_uid = int(k)
  1628. if not current_uid:
  1629. return "fail"
  1630. # store here the cleared geometry
  1631. cleared_geo = []
  1632. # determine the tool parameters to use
  1633. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1634. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1635. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1636. pol_nr = 0
  1637. # store here the parts of polygons that could not be cleared; actually those are parts of polygons
  1638. rest_list = []
  1639. # -----------------------------
  1640. # effective polygon clearing job
  1641. # -----------------------------
  1642. try:
  1643. cleared_geo = []
  1644. try:
  1645. for pp in poly_buf:
  1646. # provide the app with a way to process the GUI events when in a blocking loop
  1647. QtWidgets.QApplication.processEvents()
  1648. if self.app.abort_flag:
  1649. # graceful abort requested by the user
  1650. raise grace
  1651. # speedup the clearing by not trying to clear polygons that is clear they can't be
  1652. # cleared with the current tool. this tremendously reduce the clearing time
  1653. check_dist = -tool_dia / 2.0
  1654. check_buff = pp.buffer(check_dist)
  1655. if not check_buff or check_buff.is_empty:
  1656. continue
  1657. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1658. cont=cont, paint_method=paint_method, obj=obj,
  1659. prog_plot=prog_plot)
  1660. geo_elems = list(geo_res.get_objects())
  1661. # See if the polygon was completely cleared
  1662. pp_cleared = cascaded_union(geo_elems).buffer(tool_dia / 2.0)
  1663. rest = pp.difference(pp_cleared)
  1664. if rest and not rest.is_empty:
  1665. try:
  1666. for r in rest:
  1667. if r.is_valid:
  1668. rest_list.append(r)
  1669. except TypeError:
  1670. if rest.is_valid:
  1671. rest_list.append(rest)
  1672. if geo_res:
  1673. cleared_geo += geo_elems
  1674. pol_nr += 1
  1675. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1676. # log.debug("Polygons cleared: %d" % pol_nr)
  1677. if old_disp_number < disp_number <= 100:
  1678. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1679. old_disp_number = disp_number
  1680. except TypeError:
  1681. # provide the app with a way to process the GUI events when in a blocking loop
  1682. QtWidgets.QApplication.processEvents()
  1683. if self.app.abort_flag:
  1684. # graceful abort requested by the user
  1685. raise grace
  1686. # speedup the clearing by not trying to clear polygons that is clear they can't be
  1687. # cleared with the current tool. this tremendously reduce the clearing time
  1688. check_dist = -tool_dia / 2.0
  1689. check_buff = poly_buf.buffer(check_dist)
  1690. if not check_buff or check_buff.is_empty:
  1691. continue
  1692. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1693. cont=cont, paint_method=paint_method, obj=obj,
  1694. prog_plot=prog_plot)
  1695. geo_elems = list(geo_res.get_objects())
  1696. # See if the polygon was completely cleared
  1697. pp_cleared = cascaded_union(geo_elems).buffer(tool_dia / 2.0)
  1698. rest = poly_buf.difference(pp_cleared)
  1699. if rest and not rest.is_empty:
  1700. try:
  1701. for r in rest:
  1702. if r.is_valid:
  1703. rest_list.append(r)
  1704. except TypeError:
  1705. if rest.is_valid:
  1706. rest_list.append(rest)
  1707. if geo_res:
  1708. cleared_geo += geo_elems
  1709. except grace:
  1710. return "fail"
  1711. except Exception as e:
  1712. log.debug("Could not Paint the polygons. %s" % str(e))
  1713. msg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  1714. "Or a different strategy of paint"), str(e))
  1715. self.app.inform.emit(msg)
  1716. continue
  1717. if cleared_geo:
  1718. final_solid_geometry += cleared_geo
  1719. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1720. # dictionary and then reset the temporary list that stored that solid_geometry
  1721. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1722. tools_storage[current_uid]['data']['name'] = name
  1723. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1724. else:
  1725. log.debug("There are no geometries in the cleared polygon.")
  1726. # Area to clear next
  1727. log.debug("Generating rest geometry for the next tool.")
  1728. buffered_cleared = unary_union(cleared_geo)
  1729. buffered_cleared = buffered_cleared.buffer(tool_dia / 2.0)
  1730. poly_buf = poly_buf.difference(buffered_cleared)
  1731. tmp = []
  1732. try:
  1733. for p in poly_buf:
  1734. if p.is_valid:
  1735. tmp.append(p)
  1736. except TypeError:
  1737. if poly_buf.is_valid:
  1738. tmp.append(poly_buf)
  1739. tmp += rest_list
  1740. poly_buf = MultiPolygon(tmp)
  1741. if not poly_buf.is_valid:
  1742. poly_buf = cascaded_union(tmp)
  1743. if not poly_buf or poly_buf.is_empty or not poly_buf.is_valid:
  1744. log.debug("Rest geometry empty. Breaking.")
  1745. break
  1746. geo_obj.multigeo = True
  1747. geo_obj.options["cnctooldia"] = '0.0'
  1748. # clean the progressive plotted shapes if it was used
  1749. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1750. self.temp_shapes.clear(update=True)
  1751. # delete tools with empty geometry
  1752. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1753. for uid in list(tools_storage.keys()):
  1754. # if the solid_geometry (type=list) is empty
  1755. if not tools_storage[uid]['solid_geometry']:
  1756. tools_storage.pop(uid, None)
  1757. if not tools_storage:
  1758. return 'fail'
  1759. geo_obj.multitool = True
  1760. if geo_obj.tools:
  1761. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1762. has_solid_geo = 0
  1763. for tooluid in geo_obj.tools:
  1764. if geo_obj.tools[tooluid]['solid_geometry']:
  1765. has_solid_geo += 1
  1766. if has_solid_geo == 0:
  1767. app_obj.inform.emit('[ERROR] %s' %
  1768. _("There is no Painting Geometry in the file.\n"
  1769. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1770. "Change the painting parameters and try again."))
  1771. return "fail"
  1772. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1773. else:
  1774. return 'fail'
  1775. try:
  1776. if isinstance(geo_obj.solid_geometry, list):
  1777. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1778. else:
  1779. a, b, c, d = geo_obj.solid_geometry.bounds
  1780. geo_obj.options['xmin'] = a
  1781. geo_obj.options['ymin'] = b
  1782. geo_obj.options['xmax'] = c
  1783. geo_obj.options['ymax'] = d
  1784. except Exception as ee:
  1785. log.debug("ToolPaint.paint_poly.job_init() bounds error --> %s" % str(ee))
  1786. return
  1787. # Experimental...
  1788. # print("Indexing...", end=' ')
  1789. # geo_obj.make_index()
  1790. def job_thread(app_obj):
  1791. try:
  1792. if self.ui.rest_cb.get_value():
  1793. ret = app_obj.app_obj.new_object("geometry", name, job_rest_clear, plot=plot)
  1794. else:
  1795. ret = app_obj.app_obj.new_object("geometry", name, job_normal_clear, plot=plot)
  1796. except grace:
  1797. proc.done()
  1798. return
  1799. except Exception as er:
  1800. proc.done()
  1801. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_geo()', str(er)))
  1802. traceback.print_stack()
  1803. return
  1804. proc.done()
  1805. if ret == 'fail':
  1806. self.app.inform.emit('[ERROR] %s' % _("Paint failed."))
  1807. return
  1808. # focus on Selected Tab
  1809. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1810. self.app.inform.emit('[success] %s' % _("Paint Done."))
  1811. # Promise object with the new name
  1812. self.app.collection.promise(name)
  1813. proc = self.app.proc_container.new(_("Painting..."))
  1814. if run_threaded:
  1815. # Background
  1816. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1817. else:
  1818. job_thread(app_obj=self.app)
  1819. def paint_poly(self, obj, inside_pt=None, poly_list=None, tooldia=None, order=None, method=None, outname=None,
  1820. tools_storage=None, plot=True, run_threaded=True):
  1821. """
  1822. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1823. Note:
  1824. * The margin is taken directly from the form.
  1825. :param run_threaded:
  1826. :param plot:
  1827. :param poly_list:
  1828. :param obj: painted object
  1829. :param inside_pt: [x, y]
  1830. :param tooldia: Diameter of the painting tool
  1831. :param order: if the tools are ordered and how
  1832. :param outname: Name of the resulting Geometry Object.
  1833. :param method: choice out of _("Seed"), 'normal', 'lines'
  1834. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1835. Usage of the different one is related to when this function is called
  1836. from a TcL command.
  1837. :return: None
  1838. """
  1839. if obj.kind == 'gerber':
  1840. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1841. if self.app.defaults["gerber_buffering"] == 'no':
  1842. msg = '%s %s %s' % (_("Paint Tool."),
  1843. _("Normal painting polygon task started."),
  1844. _("Buffering geometry..."))
  1845. self.app.inform.emit(msg)
  1846. else:
  1847. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1848. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1849. if isinstance(obj.solid_geometry, list):
  1850. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1851. else:
  1852. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1853. else:
  1854. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1855. if inside_pt and poly_list is None:
  1856. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1857. elif (inside_pt is None and poly_list) or (inside_pt and poly_list):
  1858. polygon_list = poly_list
  1859. else:
  1860. return
  1861. # No polygon?
  1862. if polygon_list is None:
  1863. self.app.log.warning('No polygon found.')
  1864. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1865. return
  1866. self.paint_geo(obj, polygon_list, tooldia=tooldia, order=order, method=method, outname=outname,
  1867. tools_storage=tools_storage, plot=plot, run_threaded=run_threaded)
  1868. def paint_poly_all(self, obj, tooldia=None, order=None, method=None, outname=None, tools_storage=None, plot=True,
  1869. run_threaded=True):
  1870. """
  1871. Paints all polygons in this object.
  1872. :param obj: painted object
  1873. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1874. :param order: if the tools are ordered and how
  1875. :param outname: name of the resulting object
  1876. :param method: choice out of _("Seed"), 'normal', 'lines'
  1877. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1878. Usage of the different one is related to when this function is called from
  1879. a TcL command.
  1880. :param run_threaded:
  1881. :param plot:
  1882. :return:
  1883. """
  1884. # This is a recursive generator of individual Polygons.
  1885. # Note: Double check correct implementation. Might exit
  1886. # early if it finds something that is not a Polygon?
  1887. # def recurse(geo):
  1888. # try:
  1889. # for subg in geo:
  1890. # for subsubg in recurse(subg):
  1891. # yield subsubg
  1892. # except TypeError:
  1893. # if isinstance(geo, Polygon):
  1894. # yield geo
  1895. #
  1896. # raise StopIteration
  1897. def recurse(geometry, reset=True):
  1898. """
  1899. Creates a list of non-iterable linear geometry objects.
  1900. Results are placed in self.flat_geometry
  1901. :param geometry: Shapely type or list or list of list of such.
  1902. :param reset: Clears the contents of self.flat_geometry.
  1903. """
  1904. if self.app.abort_flag:
  1905. # graceful abort requested by the user
  1906. raise grace
  1907. if geometry is None:
  1908. return
  1909. if reset:
  1910. self.flat_geometry = []
  1911. # ## If iterable, expand recursively.
  1912. try:
  1913. for geo in geometry:
  1914. if geo and not geo.is_empty and geo.is_valid:
  1915. recurse(geometry=geo, reset=False)
  1916. # ## Not iterable, do the actual indexing and add.
  1917. except TypeError:
  1918. if isinstance(geometry, LinearRing):
  1919. g = Polygon(geometry)
  1920. self.flat_geometry.append(g)
  1921. else:
  1922. self.flat_geometry.append(geometry)
  1923. return self.flat_geometry
  1924. if obj.kind == 'gerber':
  1925. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1926. if self.app.defaults["gerber_buffering"] == 'no':
  1927. msg = '%s %s %s' % (_("Paint Tool."), _("Paint all polygons task started."), _("Buffering geometry..."))
  1928. self.app.inform.emit(msg)
  1929. else:
  1930. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1931. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1932. if isinstance(obj.solid_geometry, list):
  1933. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1934. else:
  1935. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1936. else:
  1937. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1938. painted_area = recurse(obj.solid_geometry)
  1939. # No polygon?
  1940. if not painted_area:
  1941. self.app.log.warning('No polygon found.')
  1942. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1943. return
  1944. self.paint_geo(obj, painted_area, tooldia=tooldia, order=order, method=method, outname=outname,
  1945. tools_storage=tools_storage, plot=plot, run_threaded=run_threaded)
  1946. def paint_poly_area(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  1947. tools_storage=None, plot=True, run_threaded=True):
  1948. """
  1949. Paints all polygons in this object that are within the sel_obj object
  1950. :param obj: painted object
  1951. :param sel_obj: paint only what is inside this object bounds
  1952. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1953. :param order: if the tools are ordered and how
  1954. :param outname: name of the resulting object
  1955. :param method: choice out of _("Seed"), 'normal', 'lines'
  1956. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1957. Usage of the different one is related to when this function is called from a TcL command.
  1958. :param run_threaded:
  1959. :param plot:
  1960. :return:
  1961. """
  1962. def recurse(geometry, reset=True):
  1963. """
  1964. Creates a list of non-iterable linear geometry objects.
  1965. Results are placed in self.flat_geometry
  1966. :param geometry: Shapely type or list or list of list of such.
  1967. :param reset: Clears the contents of self.flat_geometry.
  1968. """
  1969. if self.app.abort_flag:
  1970. # graceful abort requested by the user
  1971. raise grace
  1972. if geometry is None:
  1973. return
  1974. if reset:
  1975. self.flat_geometry = []
  1976. # ## If iterable, expand recursively.
  1977. try:
  1978. for geo in geometry:
  1979. if geo is not None:
  1980. recurse(geometry=geo, reset=False)
  1981. # ## Not iterable, do the actual indexing and add.
  1982. except TypeError:
  1983. if isinstance(geometry, LinearRing):
  1984. g = Polygon(geometry)
  1985. self.flat_geometry.append(g)
  1986. else:
  1987. self.flat_geometry.append(geometry)
  1988. return self.flat_geometry
  1989. # this is were heavy lifting is done and creating the geometry to be painted
  1990. target_geo = MultiPolygon(obj.solid_geometry)
  1991. if obj.kind == 'gerber':
  1992. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1993. if self.app.defaults["gerber_buffering"] == 'no':
  1994. msg = '%s %s %s' % (_("Paint Tool."),
  1995. _("Painting area task started."),
  1996. _("Buffering geometry..."))
  1997. self.app.inform.emit(msg)
  1998. else:
  1999. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2000. if obj.kind == 'gerber':
  2001. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2002. target_geo = target_geo.buffer(0)
  2003. else:
  2004. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2005. geo_to_paint = target_geo.intersection(sel_obj)
  2006. painted_area = recurse(geo_to_paint)
  2007. # No polygon?
  2008. if not painted_area:
  2009. self.app.log.warning('No polygon found.')
  2010. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  2011. return
  2012. self.paint_geo(obj, painted_area, tooldia=tooldia, order=order, method=method, outname=outname,
  2013. tools_storage=tools_storage, plot=plot, run_threaded=run_threaded)
  2014. def paint_poly_ref(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  2015. tools_storage=None, plot=True, run_threaded=True):
  2016. """
  2017. Paints all polygons in this object that are within the sel_obj object
  2018. :param obj: painted object
  2019. :param sel_obj: paint only what is inside this object bounds
  2020. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2021. :param order: if the tools are ordered and how
  2022. :param outname: name of the resulting object
  2023. :param method: choice out of _("Seed"), 'normal', 'lines'
  2024. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2025. Usage of the different one is related to when this function is called from a TcL command.
  2026. :param run_threaded:
  2027. :param plot:
  2028. :return:
  2029. """
  2030. geo = sel_obj.solid_geometry
  2031. try:
  2032. if isinstance(geo, MultiPolygon):
  2033. env_obj = geo.convex_hull
  2034. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2035. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2036. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2037. else:
  2038. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2039. env_obj = env_obj.convex_hull
  2040. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2041. except Exception as e:
  2042. log.debug("ToolPaint.paint_poly_ref() --> %s" % str(e))
  2043. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2044. return
  2045. self.paint_poly_area(obj=obj,
  2046. sel_obj=sel_rect,
  2047. tooldia=tooldia,
  2048. order=order,
  2049. method=method,
  2050. outname=outname,
  2051. tools_storage=tools_storage,
  2052. plot=plot,
  2053. run_threaded=run_threaded)
  2054. def ui_connect(self):
  2055. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  2056. # rows selected
  2057. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  2058. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  2059. # Table widgets
  2060. for row in range(self.ui.tools_table.rowCount()):
  2061. try:
  2062. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2063. except AttributeError:
  2064. pass
  2065. try:
  2066. self.ui.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2067. except AttributeError:
  2068. pass
  2069. # Parameters FORM UI
  2070. # first disconnect
  2071. for opt in self.form_fields:
  2072. current_widget = self.form_fields[opt]
  2073. if isinstance(current_widget, FCCheckBox):
  2074. try:
  2075. current_widget.stateChanged.disconnect()
  2076. except (TypeError, ValueError):
  2077. pass
  2078. if isinstance(current_widget, RadioSet):
  2079. try:
  2080. current_widget.activated_custom.disconnect()
  2081. except (TypeError, ValueError):
  2082. pass
  2083. elif isinstance(current_widget, FCDoubleSpinner):
  2084. try:
  2085. current_widget.returnPressed.disconnect()
  2086. except (TypeError, ValueError):
  2087. pass
  2088. # then reconnect
  2089. for opt in self.form_fields:
  2090. current_widget = self.form_fields[opt]
  2091. if isinstance(current_widget, FCCheckBox):
  2092. current_widget.stateChanged.connect(self.form_to_storage)
  2093. if isinstance(current_widget, RadioSet):
  2094. current_widget.activated_custom.connect(self.form_to_storage)
  2095. elif isinstance(current_widget, FCDoubleSpinner):
  2096. current_widget.returnPressed.connect(self.form_to_storage)
  2097. elif isinstance(current_widget, FCComboBox):
  2098. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2099. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type)
  2100. self.ui.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  2101. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  2102. def ui_disconnect(self):
  2103. try:
  2104. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2105. self.ui.tools_table.itemChanged.disconnect()
  2106. except (TypeError, AttributeError):
  2107. pass
  2108. # rows selected
  2109. try:
  2110. self.ui.tools_table.clicked.disconnect()
  2111. except (TypeError, AttributeError):
  2112. pass
  2113. try:
  2114. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  2115. except (TypeError, AttributeError):
  2116. pass
  2117. # Table widgets
  2118. for row in range(self.ui.tools_table.rowCount()):
  2119. for col in [2, 4]:
  2120. try:
  2121. self.ui.tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2122. except (TypeError, AttributeError):
  2123. pass
  2124. # Parameters FORM UI
  2125. for opt in self.form_fields:
  2126. current_widget = self.form_fields[opt]
  2127. if isinstance(current_widget, FCCheckBox):
  2128. try:
  2129. current_widget.stateChanged.disconnect(self.form_to_storage)
  2130. except (TypeError, ValueError):
  2131. pass
  2132. if isinstance(current_widget, RadioSet):
  2133. try:
  2134. current_widget.activated_custom.disconnect(self.form_to_storage)
  2135. except (TypeError, ValueError):
  2136. pass
  2137. elif isinstance(current_widget, FCDoubleSpinner):
  2138. try:
  2139. current_widget.returnPressed.disconnect(self.form_to_storage)
  2140. except (TypeError, ValueError):
  2141. pass
  2142. elif isinstance(current_widget, FCComboBox):
  2143. try:
  2144. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2145. except (TypeError, ValueError):
  2146. pass
  2147. try:
  2148. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2149. self.ui.tool_type_radio.activated_custom.disconnect()
  2150. except (TypeError, AttributeError):
  2151. pass
  2152. try:
  2153. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2154. self.ui.rest_cb.stateChanged.disconnect()
  2155. except (TypeError, AttributeError):
  2156. pass
  2157. try:
  2158. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2159. self.ui.order_radio.activated_custom[str].disconnect()
  2160. except (TypeError, AttributeError):
  2161. pass
  2162. @staticmethod
  2163. def paint_bounds(geometry):
  2164. def bounds_rec(o):
  2165. if type(o) is list:
  2166. minx = Inf
  2167. miny = Inf
  2168. maxx = -Inf
  2169. maxy = -Inf
  2170. for k in o:
  2171. try:
  2172. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2173. except Exception as e:
  2174. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2175. return
  2176. minx = min(minx, minx_)
  2177. miny = min(miny, miny_)
  2178. maxx = max(maxx, maxx_)
  2179. maxy = max(maxy, maxy_)
  2180. return minx, miny, maxx, maxy
  2181. else:
  2182. # it's a Shapely object, return it's bounds
  2183. return o.bounds
  2184. return bounds_rec(geometry)
  2185. def on_paint_tool_add_from_db_executed(self, tool):
  2186. """
  2187. Here add the tool from DB in the selected geometry object
  2188. :return:
  2189. """
  2190. tool_from_db = deepcopy(tool)
  2191. res = self.on_paint_tool_from_db_inserted(tool=tool_from_db)
  2192. for idx in range(self.app.ui.plot_tab_area.count()):
  2193. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2194. wdg = self.app.ui.plot_tab_area.widget(idx)
  2195. wdg.deleteLater()
  2196. self.app.ui.plot_tab_area.removeTab(idx)
  2197. if res == 'fail':
  2198. return
  2199. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2200. # select last tool added
  2201. toolid = res
  2202. for row in range(self.ui.tools_table.rowCount()):
  2203. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  2204. self.ui.tools_table.selectRow(row)
  2205. self.on_row_selection_change()
  2206. def on_paint_tool_from_db_inserted(self, tool):
  2207. """
  2208. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2209. :param tool: a dict with the tool data
  2210. :return: None
  2211. """
  2212. self.ui_disconnect()
  2213. self.units = self.app.defaults['units'].upper()
  2214. tooldia = float(tool['tooldia'])
  2215. # construct a list of all 'tooluid' in the self.tools
  2216. tool_uid_list = []
  2217. for tooluid_key in self.paint_tools:
  2218. tool_uid_item = int(tooluid_key)
  2219. tool_uid_list.append(tool_uid_item)
  2220. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2221. if not tool_uid_list:
  2222. max_uid = 0
  2223. else:
  2224. max_uid = max(tool_uid_list)
  2225. tooluid = max_uid + 1
  2226. tooldia = float('%.*f' % (self.decimals, tooldia))
  2227. tool_dias = []
  2228. for k, v in self.paint_tools.items():
  2229. for tool_v in v.keys():
  2230. if tool_v == 'tooldia':
  2231. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2232. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2233. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2234. self.ui_connect()
  2235. return 'fail'
  2236. self.paint_tools.update({
  2237. tooluid: {
  2238. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2239. 'offset': tool['offset'],
  2240. 'offset_value': tool['offset_value'],
  2241. 'type': tool['type'],
  2242. 'tool_type': tool['tool_type'],
  2243. 'data': deepcopy(tool['data']),
  2244. 'solid_geometry': []
  2245. }
  2246. })
  2247. self.paint_tools[tooluid]['data']['name'] = '_paint'
  2248. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2249. self.ui_connect()
  2250. self.build_ui()
  2251. # select the tool just added
  2252. for row in range(self.ui.tools_table.rowCount()):
  2253. if int(self.ui.tools_table.item(row, 3).text()) == tooluid:
  2254. self.ui.tools_table.selectRow(row)
  2255. break
  2256. return tooluid
  2257. def on_paint_tool_add_from_db_clicked(self):
  2258. """
  2259. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2260. and display the Tools Database tab in the form needed for the Tool adding
  2261. :return: None
  2262. """
  2263. # if the Tools Database is already opened focus on it
  2264. for idx in range(self.app.ui.plot_tab_area.count()):
  2265. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2266. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2267. break
  2268. self.app.on_tools_database(source='paint')
  2269. self.app.tools_db_tab.ok_to_add = True
  2270. self.app.tools_db_tab.ui.buttons_frame.hide()
  2271. self.app.tools_db_tab.ui.add_tool_from_db.show()
  2272. self.app.tools_db_tab.ui.cancel_tool_from_db.show()
  2273. def reset_fields(self):
  2274. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2275. class PaintUI:
  2276. toolName = _("Paint Tool")
  2277. def __init__(self, layout, app):
  2278. self.app = app
  2279. self.decimals = self.app.decimals
  2280. self.layout = layout
  2281. # ## Title
  2282. title_label = QtWidgets.QLabel("%s" % self.toolName)
  2283. title_label.setStyleSheet("""
  2284. QLabel
  2285. {
  2286. font-size: 16px;
  2287. font-weight: bold;
  2288. }
  2289. """)
  2290. self.layout.addWidget(title_label)
  2291. self.tools_frame = QtWidgets.QFrame()
  2292. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2293. self.layout.addWidget(self.tools_frame)
  2294. self.tools_box = QtWidgets.QVBoxLayout()
  2295. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2296. self.tools_frame.setLayout(self.tools_box)
  2297. # ## Form Layout
  2298. grid0 = QtWidgets.QGridLayout()
  2299. grid0.setColumnStretch(0, 0)
  2300. grid0.setColumnStretch(1, 1)
  2301. self.tools_box.addLayout(grid0)
  2302. # ################################################
  2303. # ##### Type of object to be painted #############
  2304. # ################################################
  2305. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  2306. self.type_obj_combo_label.setToolTip(
  2307. _("Specify the type of object to be painted.\n"
  2308. "It can be of type: Gerber or Geometry.\n"
  2309. "What is selected here will dictate the kind\n"
  2310. "of objects that will populate the 'Object' combobox.")
  2311. )
  2312. self.type_obj_combo_label.setMinimumWidth(60)
  2313. self.type_obj_radio = RadioSet([{'label': "Geometry", 'value': 'geometry'},
  2314. {'label': "Gerber", 'value': 'gerber'}])
  2315. grid0.addWidget(self.type_obj_combo_label, 1, 0)
  2316. grid0.addWidget(self.type_obj_radio, 1, 1)
  2317. # ################################################
  2318. # ##### The object to be painted #################
  2319. # ################################################
  2320. self.obj_combo = FCComboBox()
  2321. self.obj_combo.setModel(self.app.collection)
  2322. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2323. self.obj_combo.is_last = True
  2324. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  2325. self.object_label.setToolTip(_("Object to be painted."))
  2326. grid0.addWidget(self.object_label, 2, 0)
  2327. grid0.addWidget(self.obj_combo, 2, 1)
  2328. separator_line = QtWidgets.QFrame()
  2329. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2330. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2331. grid0.addWidget(separator_line, 5, 0, 1, 2)
  2332. # ### Tools ## ##
  2333. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  2334. self.tools_table_label.setToolTip(
  2335. _("Tools pool from which the algorithm\n"
  2336. "will pick the ones used for painting.")
  2337. )
  2338. self.tools_table = FCTable(drag_drop=True)
  2339. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2340. grid0.addWidget(self.tools_table_label, 6, 0, 1, 2)
  2341. grid0.addWidget(self.tools_table, 7, 0, 1, 2)
  2342. self.tools_table.setColumnCount(4)
  2343. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  2344. self.tools_table.setColumnHidden(3, True)
  2345. # self.tools_table.setSortingEnabled(False)
  2346. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2347. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2348. _("This is the Tool Number.\n"
  2349. "Painting will start with the tool with the biggest diameter,\n"
  2350. "continuing until there are no more tools.\n"
  2351. "Only tools that create painting geometry will still be present\n"
  2352. "in the resulting geometry. This is because with some tools\n"
  2353. "this function will not be able to create painting geometry.")
  2354. )
  2355. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2356. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  2357. "is the cut width into the material."))
  2358. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2359. _("The Tool Type (TT) can be:\n"
  2360. "- Circular -> it is informative only. Being circular,\n"
  2361. "the cut width in material is exactly the tool diameter.\n"
  2362. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  2363. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  2364. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  2365. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  2366. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  2367. "column of this table.\n"
  2368. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  2369. "in the resulting geometry as Isolation."))
  2370. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  2371. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2372. "'No' --> means that the used order is the one in the tool table\n"
  2373. "'Forward' --> means that the tools will be ordered from small to big\n"
  2374. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2375. "WARNING: using rest machining will automatically set the order\n"
  2376. "in reverse and disable this control."))
  2377. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2378. {'label': _('Forward'), 'value': 'fwd'},
  2379. {'label': _('Reverse'), 'value': 'rev'}])
  2380. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2381. "'No' --> means that the used order is the one in the tool table\n"
  2382. "'Forward' --> means that the tools will be ordered from small to big\n"
  2383. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2384. "WARNING: using rest machining will automatically set the order\n"
  2385. "in reverse and disable this control."))
  2386. grid0.addWidget(self.order_label, 9, 0)
  2387. grid0.addWidget(self.order_radio, 9, 1)
  2388. separator_line = QtWidgets.QFrame()
  2389. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2390. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2391. grid0.addWidget(separator_line, 10, 0, 1, 2)
  2392. self.grid3 = QtWidgets.QGridLayout()
  2393. self.tools_box.addLayout(self.grid3)
  2394. self.grid3.setColumnStretch(0, 0)
  2395. self.grid3.setColumnStretch(1, 1)
  2396. # ##############################################################################
  2397. # ###################### ADD A NEW TOOL ########################################
  2398. # ##############################################################################
  2399. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  2400. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  2401. # Tool Type Radio Button
  2402. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  2403. self.tool_type_label.setToolTip(
  2404. _("Default tool type:\n"
  2405. "- 'V-shape'\n"
  2406. "- Circular")
  2407. )
  2408. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  2409. {'label': _('Circular'), 'value': 'C1'}])
  2410. self.tool_type_radio.setToolTip(
  2411. _("Default tool type:\n"
  2412. "- 'V-shape'\n"
  2413. "- Circular")
  2414. )
  2415. self.tool_type_radio.setObjectName('p_tool_type')
  2416. self.grid3.addWidget(self.tool_type_label, 2, 0)
  2417. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  2418. # Tip Dia
  2419. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  2420. self.tipdialabel.setToolTip(
  2421. _("The tip diameter for V-Shape Tool"))
  2422. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2423. self.tipdia_entry.set_precision(self.decimals)
  2424. self.tipdia_entry.set_range(0.0000, 9999.9999)
  2425. self.tipdia_entry.setSingleStep(0.1)
  2426. self.tipdia_entry.setObjectName('p_vtip_dia')
  2427. self.grid3.addWidget(self.tipdialabel, 3, 0)
  2428. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  2429. # Tip Angle
  2430. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  2431. self.tipanglelabel.setToolTip(
  2432. _("The tip angle for V-Shape Tool.\n"
  2433. "In degree."))
  2434. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2435. self.tipangle_entry.set_precision(self.decimals)
  2436. self.tipangle_entry.set_range(0.0000, 180.0000)
  2437. self.tipangle_entry.setSingleStep(5)
  2438. self.tipangle_entry.setObjectName('p_vtip_angle')
  2439. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  2440. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  2441. # Cut Z entry
  2442. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  2443. cutzlabel.setToolTip(
  2444. _("Depth of cut into material. Negative value.\n"
  2445. "In FlatCAM units.")
  2446. )
  2447. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2448. self.cutz_entry.set_precision(self.decimals)
  2449. self.cutz_entry.set_range(-99999.9999, 0.0000)
  2450. self.cutz_entry.setObjectName('p_cutz')
  2451. self.cutz_entry.setToolTip(
  2452. _("Depth of cut into material. Negative value.\n"
  2453. "In FlatCAM units.")
  2454. )
  2455. self.grid3.addWidget(cutzlabel, 5, 0)
  2456. self.grid3.addWidget(self.cutz_entry, 5, 1)
  2457. # ### Tool Diameter ####
  2458. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  2459. self.addtool_entry_lbl.setToolTip(
  2460. _("Diameter for the new tool to add in the Tool Table.\n"
  2461. "If the tool is V-shape type then this value is automatically\n"
  2462. "calculated from the other parameters.")
  2463. )
  2464. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2465. self.addtool_entry.set_precision(self.decimals)
  2466. self.addtool_entry.set_range(0.000, 9999.9999)
  2467. self.addtool_entry.setObjectName('p_tool_dia')
  2468. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  2469. self.grid3.addWidget(self.addtool_entry, 6, 1)
  2470. hlay = QtWidgets.QHBoxLayout()
  2471. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  2472. self.addtool_btn.setToolTip(
  2473. _("Add a new tool to the Tool Table\n"
  2474. "with the diameter specified above.")
  2475. )
  2476. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  2477. self.addtool_from_db_btn.setToolTip(
  2478. _("Add a new tool to the Tool Table\n"
  2479. "from the Tool Database.\n"
  2480. "Tool database administration in Menu: Options -> Tools Database")
  2481. )
  2482. hlay.addWidget(self.addtool_btn)
  2483. hlay.addWidget(self.addtool_from_db_btn)
  2484. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  2485. separator_line = QtWidgets.QFrame()
  2486. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2487. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2488. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  2489. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  2490. self.deltool_btn.setToolTip(
  2491. _("Delete a selection of tools in the Tool Table\n"
  2492. "by first selecting a row(s) in the Tool Table.")
  2493. )
  2494. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  2495. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  2496. separator_line = QtWidgets.QFrame()
  2497. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2498. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2499. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  2500. self.tool_data_label = QtWidgets.QLabel(
  2501. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2502. self.tool_data_label.setToolTip(
  2503. _(
  2504. "The data used for creating GCode.\n"
  2505. "Each tool store it's own set of such data."
  2506. )
  2507. )
  2508. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  2509. grid4 = QtWidgets.QGridLayout()
  2510. grid4.setColumnStretch(0, 0)
  2511. grid4.setColumnStretch(1, 1)
  2512. self.tools_box.addLayout(grid4)
  2513. # Overlap
  2514. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  2515. ovlabel.setToolTip(
  2516. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  2517. "Adjust the value starting with lower values\n"
  2518. "and increasing it if areas that should be painted are still \n"
  2519. "not painted.\n"
  2520. "Lower values = faster processing, faster execution on CNC.\n"
  2521. "Higher values = slow processing and slow execution on CNC\n"
  2522. "due of too many paths.")
  2523. )
  2524. self.paintoverlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  2525. self.paintoverlap_entry.set_precision(3)
  2526. self.paintoverlap_entry.setWrapping(True)
  2527. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  2528. self.paintoverlap_entry.setSingleStep(0.1)
  2529. self.paintoverlap_entry.setObjectName('p_overlap')
  2530. grid4.addWidget(ovlabel, 1, 0)
  2531. grid4.addWidget(self.paintoverlap_entry, 1, 1)
  2532. # Offset
  2533. self.offset_label = QtWidgets.QLabel('%s:' % _('Offset'))
  2534. self.offset_label.setToolTip(
  2535. _("Distance by which to avoid\n"
  2536. "the edges of the polygon to\n"
  2537. "be painted.")
  2538. )
  2539. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2540. self.offset_entry.set_precision(self.decimals)
  2541. self.offset_entry.set_range(-9999.9999, 9999.9999)
  2542. self.offset_entry.setObjectName('p_offset')
  2543. grid4.addWidget(self.offset_label, 2, 0)
  2544. grid4.addWidget(self.offset_entry, 2, 1)
  2545. # Method
  2546. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  2547. methodlabel.setToolTip(
  2548. _("Algorithm for painting:\n"
  2549. "- Standard: Fixed step inwards.\n"
  2550. "- Seed-based: Outwards from seed.\n"
  2551. "- Line-based: Parallel lines.\n"
  2552. "- Laser-lines: Active only for Gerber objects.\n"
  2553. "Will create lines that follow the traces.\n"
  2554. "- Combo: In case of failure a new method will be picked from the above\n"
  2555. "in the order specified.")
  2556. )
  2557. # self.paintmethod_combo = RadioSet([
  2558. # {"label": _("Standard"), "value": "standard"},
  2559. # {"label": _("Seed-based"), "value": _("Seed")},
  2560. # {"label": _("Straight lines"), "value": _("Lines")},
  2561. # {"label": _("Laser lines"), "value": _("Laser_lines")},
  2562. # {"label": _("Combo"), "value": _("Combo")}
  2563. # ], orientation='vertical', stretch=False)
  2564. # for choice in self.paintmethod_combo.choices:
  2565. # if choice['value'] == _("Laser_lines"):
  2566. # choice["radio"].setEnabled(False)
  2567. self.paintmethod_combo = FCComboBox()
  2568. self.paintmethod_combo.addItems(
  2569. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  2570. )
  2571. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  2572. self.paintmethod_combo.model().item(idx).setEnabled(False)
  2573. self.paintmethod_combo.setObjectName('p_method')
  2574. grid4.addWidget(methodlabel, 7, 0)
  2575. grid4.addWidget(self.paintmethod_combo, 7, 1)
  2576. # Connect lines
  2577. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  2578. self.pathconnect_cb.setObjectName('p_connect')
  2579. self.pathconnect_cb.setToolTip(
  2580. _("Draw lines between resulting\n"
  2581. "segments to minimize tool lifts.")
  2582. )
  2583. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  2584. self.paintcontour_cb.setObjectName('p_contour')
  2585. self.paintcontour_cb.setToolTip(
  2586. _("Cut around the perimeter of the polygon\n"
  2587. "to trim rough edges.")
  2588. )
  2589. grid4.addWidget(self.pathconnect_cb, 10, 0)
  2590. grid4.addWidget(self.paintcontour_cb, 10, 1)
  2591. separator_line = QtWidgets.QFrame()
  2592. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2593. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2594. grid4.addWidget(separator_line, 11, 0, 1, 2)
  2595. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  2596. self.apply_param_to_all.setToolTip(
  2597. _("The parameters in the current form will be applied\n"
  2598. "on all the tools from the Tool Table.")
  2599. )
  2600. grid4.addWidget(self.apply_param_to_all, 12, 0, 1, 2)
  2601. separator_line = QtWidgets.QFrame()
  2602. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2603. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2604. grid4.addWidget(separator_line, 13, 0, 1, 2)
  2605. # General Parameters
  2606. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  2607. self.gen_param_label.setToolTip(
  2608. _("Parameters that are common for all tools.")
  2609. )
  2610. grid4.addWidget(self.gen_param_label, 15, 0, 1, 2)
  2611. self.rest_cb = FCCheckBox('%s' % _("Rest"))
  2612. self.rest_cb.setObjectName('p_rest_machining')
  2613. self.rest_cb.setToolTip(
  2614. _("If checked, use 'rest machining'.\n"
  2615. "Basically it will clear copper outside PCB features,\n"
  2616. "using the biggest tool and continue with the next tools,\n"
  2617. "from bigger to smaller, to clear areas of copper that\n"
  2618. "could not be cleared by previous tool, until there is\n"
  2619. "no more copper to clear or there are no more tools.\n\n"
  2620. "If not checked, use the standard algorithm.")
  2621. )
  2622. grid4.addWidget(self.rest_cb, 16, 0, 1, 2)
  2623. # Rest Offset
  2624. self.rest_offset_label = QtWidgets.QLabel('%s:' % _('Offset'))
  2625. self.rest_offset_label.setToolTip(
  2626. _("Distance by which to avoid\n"
  2627. "the edges of the polygon to\n"
  2628. "be painted.")
  2629. )
  2630. self.rest_offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2631. self.rest_offset_entry.set_precision(self.decimals)
  2632. self.rest_offset_entry.set_range(-9999.9999, 9999.9999)
  2633. grid4.addWidget(self.rest_offset_label, 17, 0)
  2634. grid4.addWidget(self.rest_offset_entry, 17, 1)
  2635. # Polygon selection
  2636. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  2637. selectlabel.setToolTip(
  2638. _("Selection of area to be processed.\n"
  2639. "- 'Polygon Selection' - left mouse click to add/remove polygons to be processed.\n"
  2640. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  2641. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  2642. "- 'All Polygons' - the process will start after click.\n"
  2643. "- 'Reference Object' - will process the area specified by another object.")
  2644. )
  2645. # grid3 = QtWidgets.QGridLayout()
  2646. # self.selectmethod_combo = RadioSet([
  2647. # {"label": _("Polygon Selection"), "value": "single"},
  2648. # {"label": _("Area Selection"), "value": "area"},
  2649. # {"label": _("All Polygons"), "value": "all"},
  2650. # {"label": _("Reference Object"), "value": "ref"}
  2651. # ], orientation='vertical', stretch=False)
  2652. # self.selectmethod_combo.setObjectName('p_selection')
  2653. # self.selectmethod_combo.setToolTip(
  2654. # _("How to select Polygons to be painted.\n"
  2655. # "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  2656. # "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  2657. # "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  2658. # "- 'All Polygons' - the Paint will start after click.\n"
  2659. # "- 'Reference Object' - will do non copper clearing within the area\n"
  2660. # "specified by another object.")
  2661. # )
  2662. self.selectmethod_combo = FCComboBox()
  2663. self.selectmethod_combo.addItems(
  2664. [_("Polygon Selection"), _("Area Selection"), _("All"), _("Reference Object")]
  2665. )
  2666. self.selectmethod_combo.setObjectName('p_selection')
  2667. grid4.addWidget(selectlabel, 18, 0)
  2668. grid4.addWidget(self.selectmethod_combo, 18, 1)
  2669. form1 = QtWidgets.QFormLayout()
  2670. grid4.addLayout(form1, 20, 0, 1, 2)
  2671. self.reference_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  2672. self.reference_type_label.setToolTip(
  2673. _("The type of FlatCAM object to be used as paint reference.\n"
  2674. "It can be Gerber, Excellon or Geometry.")
  2675. )
  2676. self.reference_type_combo = FCComboBox()
  2677. self.reference_type_combo.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  2678. form1.addRow(self.reference_type_label, self.reference_type_combo)
  2679. self.reference_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  2680. self.reference_combo_label.setToolTip(
  2681. _("The FlatCAM object to be used as non copper clearing reference.")
  2682. )
  2683. self.reference_combo = FCComboBox()
  2684. self.reference_combo.setModel(self.app.collection)
  2685. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2686. self.reference_combo.is_last = True
  2687. form1.addRow(self.reference_combo_label, self.reference_combo)
  2688. self.reference_combo.hide()
  2689. self.reference_combo_label.hide()
  2690. self.reference_type_combo.hide()
  2691. self.reference_type_label.hide()
  2692. # Area Selection shape
  2693. self.area_shape_label = QtWidgets.QLabel('%s:' % _("Shape"))
  2694. self.area_shape_label.setToolTip(
  2695. _("The kind of selection shape used for area selection.")
  2696. )
  2697. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  2698. {'label': _("Polygon"), 'value': 'polygon'}])
  2699. grid4.addWidget(self.area_shape_label, 21, 0)
  2700. grid4.addWidget(self.area_shape_radio, 21, 1)
  2701. self.area_shape_label.hide()
  2702. self.area_shape_radio.hide()
  2703. # GO Button
  2704. self.generate_paint_button = QtWidgets.QPushButton(_('Generate Geometry'))
  2705. self.generate_paint_button.setToolTip(
  2706. _("Create a Geometry Object which paints the polygons.")
  2707. )
  2708. self.generate_paint_button.setStyleSheet("""
  2709. QPushButton
  2710. {
  2711. font-weight: bold;
  2712. }
  2713. """)
  2714. self.tools_box.addWidget(self.generate_paint_button)
  2715. self.tools_box.addStretch()
  2716. # ## Reset Tool
  2717. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  2718. self.reset_button.setToolTip(
  2719. _("Will reset the tool parameters.")
  2720. )
  2721. self.reset_button.setStyleSheet("""
  2722. QPushButton
  2723. {
  2724. font-weight: bold;
  2725. }
  2726. """)
  2727. self.tools_box.addWidget(self.reset_button)
  2728. # #################################### FINSIHED GUI ###########################
  2729. # #############################################################################
  2730. def confirmation_message(self, accepted, minval, maxval):
  2731. if accepted is False:
  2732. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2733. self.decimals,
  2734. minval,
  2735. self.decimals,
  2736. maxval), False)
  2737. else:
  2738. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2739. def confirmation_message_int(self, accepted, minval, maxval):
  2740. if accepted is False:
  2741. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2742. (_("Edited value is out of range"), minval, maxval), False)
  2743. else:
  2744. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)