ToolPaint.py 145 KB

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