ToolPaint.py 145 KB

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