ToolPaint.py 145 KB

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