ToolPaint.py 166 KB

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