ToolPaint.py 145 KB

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