ToolPaint.py 145 KB

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