ToolPaint.py 167 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792
  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. # disconnect flags
  67. self.area_sel_disconnect_flag = False
  68. self.poly_sel_disconnect_flag = False
  69. self.sel_rect = []
  70. # store here if the grid snapping is active
  71. self.grid_status_memory = False
  72. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  73. self.poly_dict = {}
  74. # store here the default data for Geometry Data
  75. self.default_data = {}
  76. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  77. self.form_fields = {
  78. "tools_paintoverlap": self.ui.paintoverlap_entry,
  79. "tools_paintoffset": self.ui.offset_entry,
  80. "tools_paintmethod": self.ui.paintmethod_combo,
  81. "tools_pathconnect": self.ui.pathconnect_cb,
  82. "tools_paintcontour": self.ui.paintcontour_cb,
  83. }
  84. self.name2option = {
  85. 'p_overlap': "tools_paintoverlap",
  86. 'p_offset': "tools_paintoffset",
  87. 'p_method': "tools_paintmethod",
  88. 'p_connect': "tools_pathconnect",
  89. 'p_contour': "tools_paintcontour",
  90. }
  91. self.old_tool_dia = None
  92. # store here the points for the "Polygon" area selection shape
  93. self.points = []
  94. # set this as True when in middle of drawing a "Polygon" area selection shape
  95. # it is made False by first click to signify that the shape is complete
  96. self.poly_drawn = False
  97. self.connect_signals_at_init()
  98. # #############################################################################
  99. # ###################### Setup CONTEXT MENU ###################################
  100. # #############################################################################
  101. self.ui.tools_table.setupContextMenu()
  102. self.ui.tools_table.addContextMenu(
  103. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  104. )
  105. self.ui.tools_table.addContextMenu(
  106. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  107. )
  108. self.ui.tools_table.addContextMenu(
  109. _("Delete"), lambda:
  110. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  111. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  112. )
  113. def on_type_obj_changed(self, val):
  114. obj_type = 0 if val == 'gerber' else 2
  115. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  116. self.ui.obj_combo.setCurrentIndex(0)
  117. self.ui.obj_combo.obj_type = {"gerber": "Gerber", "geometry": "Geometry"}[val]
  118. idx = self.ui.paintmethod_combo.findText(_("Laser_lines"))
  119. if self.ui.type_obj_radio.get_value().lower() == 'gerber':
  120. self.ui.paintmethod_combo.model().item(idx).setEnabled(True)
  121. else:
  122. self.ui.paintmethod_combo.model().item(idx).setEnabled(False)
  123. if self.ui.paintmethod_combo.get_value() == _("Laser_lines"):
  124. self.ui.paintmethod_combo.set_value(_("Lines"))
  125. def on_reference_combo_changed(self):
  126. obj_type = self.ui.reference_type_combo.currentIndex()
  127. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  128. self.ui.reference_combo.setCurrentIndex(0)
  129. self.ui.reference_combo.obj_type = {
  130. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  131. }[self.ui.reference_type_combo.get_value()]
  132. def connect_signals_at_init(self):
  133. # #############################################################################
  134. # ################################# Signals ###################################
  135. # #############################################################################
  136. self.ui.addtool_btn.clicked.connect(self.on_tool_add)
  137. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  138. self.ui.deltool_btn.clicked.connect(self.on_tool_delete)
  139. self.ui.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  140. self.ui.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  141. self.ui.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  142. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  143. self.ui.selectmethod_combo.currentIndexChanged.connect(self.on_selection)
  144. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  145. self.ui.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  146. self.ui.reference_type_combo.currentIndexChanged.connect(self.on_reference_combo_changed)
  147. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  148. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  149. self.ui.addtool_from_db_btn.clicked.connect(self.on_paint_tool_add_from_db_clicked)
  150. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  151. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  152. self.app.cleanup.connect(self.set_tool_ui)
  153. def install(self, icon=None, separator=None, **kwargs):
  154. AppTool.install(self, icon, separator, shortcut='Alt+P', **kwargs)
  155. def run(self, toggle=True):
  156. self.app.defaults.report_usage("ToolPaint()")
  157. log.debug("ToolPaint().run() was launched ...")
  158. if toggle:
  159. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  160. if self.app.ui.splitter.sizes()[0] == 0:
  161. self.app.ui.splitter.setSizes([1, 1])
  162. else:
  163. try:
  164. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  165. # if tab is populated with the tool but it does not have the focus, focus on it
  166. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  167. # focus on Tool Tab
  168. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  169. else:
  170. self.app.ui.splitter.setSizes([0, 1])
  171. except AttributeError:
  172. pass
  173. else:
  174. if self.app.ui.splitter.sizes()[0] == 0:
  175. self.app.ui.splitter.setSizes([1, 1])
  176. AppTool.run(self)
  177. self.set_tool_ui()
  178. self.build_ui()
  179. # all the tools are selected by default
  180. self.ui.tools_table.selectAll()
  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_paintoffset": self.app.defaults["tools_paintoffset"],
  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.offset_entry.set_value(self.app.defaults["tools_paintoffset"])
  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. # disconnect flags
  840. self.poly_sel_disconnect_flag = True
  841. elif self.select_method == _("Area Selection"):
  842. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  843. if self.app.is_legacy is False:
  844. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  845. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  846. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  847. else:
  848. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  849. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  850. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  851. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  852. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  853. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  854. # disconnect flags
  855. self.area_sel_disconnect_flag = True
  856. elif self.select_method == _("Reference Object"):
  857. self.bound_obj_name = self.reference_combo.currentText()
  858. # Get source object.
  859. try:
  860. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  861. except Exception:
  862. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  863. return "Could not retrieve object: %s" % self.obj_name
  864. self.paint_poly_ref(obj=self.paint_obj, sel_obj=self.bound_obj, tooldia=self.tooldia_list,
  865. outname=self.o_name)
  866. # To be called after clicking on the plot.
  867. def on_single_poly_mouse_release(self, event):
  868. if self.app.is_legacy is False:
  869. event_pos = event.pos
  870. right_button = 2
  871. event_is_dragging = self.app.event_is_dragging
  872. else:
  873. event_pos = (event.xdata, event.ydata)
  874. right_button = 3
  875. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  876. try:
  877. x = float(event_pos[0])
  878. y = float(event_pos[1])
  879. except TypeError:
  880. return
  881. event_pos = (x, y)
  882. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  883. # do paint single only for left mouse clicks
  884. if event.button == 1:
  885. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  886. if clicked_poly:
  887. if clicked_poly not in self.poly_dict.values():
  888. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  889. layer=0,
  890. shape=clicked_poly,
  891. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  892. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  893. visible=True)
  894. self.poly_dict[shape_id] = clicked_poly
  895. self.app.inform.emit(
  896. '%s: %d. %s' % (_("Added polygon"),
  897. int(len(self.poly_dict)),
  898. _("Click to add next polygon or right click to start painting."))
  899. )
  900. else:
  901. try:
  902. for k, v in list(self.poly_dict.items()):
  903. if v == clicked_poly:
  904. self.app.tool_shapes.remove(k)
  905. self.poly_dict.pop(k)
  906. break
  907. except TypeError:
  908. return
  909. self.app.inform.emit(
  910. '%s. %s' % (_("Removed polygon"),
  911. _("Click to add/remove next polygon or right click to start painting."))
  912. )
  913. self.app.tool_shapes.redraw()
  914. else:
  915. self.app.inform.emit(_("No polygon detected under click position."))
  916. elif event.button == right_button and event_is_dragging is False:
  917. # restore the Grid snapping if it was active before
  918. if self.grid_status_memory is True:
  919. self.app.ui.grid_snap_btn.trigger()
  920. if self.app.is_legacy is False:
  921. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  922. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  923. else:
  924. self.app.plotcanvas.graph_event_disconnect(self.mr)
  925. self.app.plotcanvas.graph_event_disconnect(self.kp)
  926. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  927. self.app.on_mouse_click_over_plot)
  928. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  929. self.app.on_mouse_click_release_over_plot)
  930. # disconnect flags
  931. self.poly_sel_disconnect_flag = False
  932. self.app.tool_shapes.clear(update=True)
  933. if self.poly_dict:
  934. poly_list = deepcopy(list(self.poly_dict.values()))
  935. self.paint_poly(self.paint_obj, inside_pt=(curr_pos[0], curr_pos[1]), poly_list=poly_list,
  936. tooldia=self.tooldia_list)
  937. self.poly_dict.clear()
  938. else:
  939. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  940. # To be called after clicking on the plot.
  941. def on_mouse_release(self, event):
  942. if self.app.is_legacy is False:
  943. event_pos = event.pos
  944. # event_is_dragging = event.is_dragging
  945. right_button = 2
  946. else:
  947. event_pos = (event.xdata, event.ydata)
  948. # event_is_dragging = self.app.plotcanvas.is_dragging
  949. right_button = 3
  950. try:
  951. x = float(event_pos[0])
  952. y = float(event_pos[1])
  953. except TypeError:
  954. return
  955. event_pos = (x, y)
  956. shape_type = self.ui.area_shape_radio.get_value()
  957. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  958. if self.app.grid_status():
  959. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  960. x1, y1 = curr_pos[0], curr_pos[1]
  961. # do paint single only for left mouse clicks
  962. if event.button == 1:
  963. if shape_type == "square":
  964. if not self.first_click:
  965. self.first_click = True
  966. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  967. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  968. if self.app.grid_status():
  969. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  970. else:
  971. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  972. self.app.delete_selection_shape()
  973. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  974. pt1 = (x0, y0)
  975. pt2 = (x1, y0)
  976. pt3 = (x1, y1)
  977. pt4 = (x0, y1)
  978. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  979. self.sel_rect.append(new_rectangle)
  980. # add a temporary shape on canvas
  981. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  982. self.first_click = False
  983. return
  984. else:
  985. self.points.append((x1, y1))
  986. if len(self.points) > 1:
  987. self.poly_drawn = True
  988. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  989. return ""
  990. elif event.button == right_button and self.mouse_is_dragging is False:
  991. shape_type = self.area_shape_radio.get_value()
  992. if shape_type == "square":
  993. self.first_click = False
  994. else:
  995. # if we finish to add a polygon
  996. if self.poly_drawn is True:
  997. try:
  998. # try to add the point where we last clicked if it is not already in the self.points
  999. last_pt = (x1, y1)
  1000. if last_pt != self.points[-1]:
  1001. self.points.append(last_pt)
  1002. except IndexError:
  1003. pass
  1004. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1005. if len(self.points) > 2:
  1006. self.delete_moving_selection_shape()
  1007. pol = Polygon(self.points)
  1008. # do not add invalid polygons even if they are drawn by utility geometry
  1009. if pol.is_valid:
  1010. self.sel_rect.append(pol)
  1011. self.draw_selection_shape_polygon(points=self.points)
  1012. self.app.inform.emit(
  1013. _("Zone added. Click to start adding next zone or right click to finish."))
  1014. self.points = []
  1015. self.poly_drawn = False
  1016. return
  1017. self.delete_tool_selection_shape()
  1018. if self.app.is_legacy is False:
  1019. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1020. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1021. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1022. else:
  1023. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1024. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1025. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1026. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1027. self.app.on_mouse_click_over_plot)
  1028. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1029. self.app.on_mouse_move_over_plot)
  1030. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1031. self.app.on_mouse_click_release_over_plot)
  1032. # disconnect flags
  1033. self.area_sel_disconnect_flag = False
  1034. if len(self.sel_rect) == 0:
  1035. return
  1036. self.sel_rect = cascaded_union(self.sel_rect)
  1037. self.paint_poly_area(obj=self.paint_obj, tooldia=self.tooldia_list, sel_obj=self.sel_rect,
  1038. outname=self.o_name)
  1039. # called on mouse move
  1040. def on_mouse_move(self, event):
  1041. shape_type = self.ui.area_shape_radio.get_value()
  1042. if self.app.is_legacy is False:
  1043. event_pos = event.pos
  1044. event_is_dragging = event.is_dragging
  1045. # right_button = 2
  1046. else:
  1047. event_pos = (event.xdata, event.ydata)
  1048. event_is_dragging = self.app.plotcanvas.is_dragging
  1049. # right_button = 3
  1050. try:
  1051. x = float(event_pos[0])
  1052. y = float(event_pos[1])
  1053. except TypeError:
  1054. return
  1055. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1056. # detect mouse dragging motion
  1057. if event_is_dragging == 1:
  1058. self.mouse_is_dragging = True
  1059. else:
  1060. self.mouse_is_dragging = False
  1061. # update the cursor position
  1062. if self.app.grid_status():
  1063. # Update cursor
  1064. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1065. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1066. symbol='++', edge_color=self.app.cursor_color_3D,
  1067. edge_width=self.app.defaults["global_cursor_width"],
  1068. size=self.app.defaults["global_cursor_size"])
  1069. if self.cursor_pos is None:
  1070. self.cursor_pos = (0, 0)
  1071. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  1072. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  1073. # # update the positions on status bar
  1074. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1075. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  1076. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1077. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  1078. units = self.app.defaults["units"].lower()
  1079. self.app.plotcanvas.text_hud.text = \
  1080. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  1081. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  1082. # draw the utility geometry
  1083. if shape_type == "square":
  1084. if self.first_click:
  1085. self.app.delete_selection_shape()
  1086. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1087. coords=(curr_pos[0], curr_pos[1]))
  1088. else:
  1089. self.delete_moving_selection_shape()
  1090. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  1091. def on_key_press(self, event):
  1092. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1093. # matplotlib_key_flag = False
  1094. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1095. if type(event) is int:
  1096. key = event
  1097. # events from the GUI are of type QKeyEvent
  1098. elif type(event) == QtGui.QKeyEvent:
  1099. key = event.key()
  1100. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1101. # matplotlib_key_flag = True
  1102. key = event.key
  1103. key = QtGui.QKeySequence(key)
  1104. # check for modifiers
  1105. key_string = key.toString().lower()
  1106. if '+' in key_string:
  1107. mod, __, key_text = key_string.rpartition('+')
  1108. if mod.lower() == 'ctrl':
  1109. # modifiers = QtCore.Qt.ControlModifier
  1110. pass
  1111. elif mod.lower() == 'alt':
  1112. # modifiers = QtCore.Qt.AltModifier
  1113. pass
  1114. elif mod.lower() == 'shift':
  1115. # modifiers = QtCore.Qt.ShiftModifier
  1116. pass
  1117. else:
  1118. # modifiers = QtCore.Qt.NoModifier
  1119. pass
  1120. key = QtGui.QKeySequence(key_text)
  1121. # events from Vispy are of type KeyEvent
  1122. else:
  1123. key = event.key
  1124. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1125. if self.area_sel_disconnect_flag is True:
  1126. try:
  1127. if self.app.is_legacy is False:
  1128. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1129. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1130. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1131. else:
  1132. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1133. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1134. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1135. except Exception as e:
  1136. log.debug("ToolPaint.on_key_press() _1 --> %s" % str(e))
  1137. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1138. self.app.on_mouse_click_over_plot)
  1139. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1140. self.app.on_mouse_move_over_plot)
  1141. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1142. self.app.on_mouse_click_release_over_plot)
  1143. if self.poly_sel_disconnect_flag is False:
  1144. try:
  1145. # restore the Grid snapping if it was active before
  1146. if self.grid_status_memory is True:
  1147. self.app.ui.grid_snap_btn.trigger()
  1148. if self.app.is_legacy is False:
  1149. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1150. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1151. else:
  1152. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1153. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1154. self.app.tool_shapes.clear(update=True)
  1155. except Exception as e:
  1156. log.debug("ToolPaint.on_key_press() _2 --> %s" % str(e))
  1157. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1158. self.app.on_mouse_click_release_over_plot)
  1159. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1160. self.app.on_mouse_click_over_plot)
  1161. self.points = []
  1162. self.poly_drawn = False
  1163. self.poly_dict.clear()
  1164. self.delete_moving_selection_shape()
  1165. self.delete_tool_selection_shape()
  1166. def paint_polygon_worker(self, polyg, tooldiameter, paint_method, over, conn, cont, prog_plot, obj):
  1167. cpoly = None
  1168. if paint_method == _("Standard"):
  1169. try:
  1170. # Type(cp) == FlatCAMRTreeStorage | None
  1171. cpoly = self.clear_polygon(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() Standard --> %s" % str(ee))
  1182. elif paint_method == _("Seed"):
  1183. try:
  1184. # Type(cp) == FlatCAMRTreeStorage | None
  1185. cpoly = self.clear_polygon2(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() Seed --> %s" % str(ee))
  1196. elif paint_method == _("Lines"):
  1197. try:
  1198. # Type(cp) == FlatCAMRTreeStorage | None
  1199. cpoly = self.clear_polygon3(polyg,
  1200. tooldia=tooldiameter,
  1201. steps_per_circle=self.circle_steps,
  1202. overlap=over,
  1203. contour=cont,
  1204. connect=conn,
  1205. prog_plot=prog_plot)
  1206. except grace:
  1207. return "fail"
  1208. except Exception as ee:
  1209. log.debug("ToolPaint.paint_polygon_worker() Lines --> %s" % str(ee))
  1210. elif paint_method == _("Laser_lines"):
  1211. try:
  1212. # line = None
  1213. # aperture_size = None
  1214. # the key is the aperture type and the val is a list of geo elements
  1215. flash_el_dict = {}
  1216. # the key is the aperture size, the val is a list of geo elements
  1217. traces_el_dict = {}
  1218. # find the flashes and the lines that are in the selected polygon and store them separately
  1219. for apid, apval in obj.apertures.items():
  1220. for geo_el in apval['geometry']:
  1221. if apval["size"] == 0.0:
  1222. if apval["size"] in traces_el_dict:
  1223. traces_el_dict[apval["size"]].append(geo_el)
  1224. else:
  1225. traces_el_dict[apval["size"]] = [geo_el]
  1226. if 'follow' in geo_el and geo_el['follow'].within(polyg):
  1227. if isinstance(geo_el['follow'], Point):
  1228. if apval["type"] == 'C':
  1229. if 'C' in flash_el_dict:
  1230. flash_el_dict['C'].append(geo_el)
  1231. else:
  1232. flash_el_dict['C'] = [geo_el]
  1233. elif apval["type"] == 'O':
  1234. if 'O' in flash_el_dict:
  1235. flash_el_dict['O'].append(geo_el)
  1236. else:
  1237. flash_el_dict['O'] = [geo_el]
  1238. elif apval["type"] == 'R':
  1239. if 'R' in flash_el_dict:
  1240. flash_el_dict['R'].append(geo_el)
  1241. else:
  1242. flash_el_dict['R'] = [geo_el]
  1243. else:
  1244. aperture_size = apval['size']
  1245. if aperture_size in traces_el_dict:
  1246. traces_el_dict[aperture_size].append(geo_el)
  1247. else:
  1248. traces_el_dict[aperture_size] = [geo_el]
  1249. cpoly = FlatCAMRTreeStorage()
  1250. pads_lines_list = []
  1251. # process the flashes found in the selected polygon with the 'lines' method for rectangular
  1252. # flashes and with _("Seed") for oblong and circular flashes
  1253. # and pads (flahes) need the contour therefore I override the GUI settings with always True
  1254. for ap_type in flash_el_dict:
  1255. for elem in flash_el_dict[ap_type]:
  1256. if 'solid' in elem:
  1257. if ap_type == 'C':
  1258. f_o = self.clear_polygon2(elem['solid'],
  1259. tooldia=tooldiameter,
  1260. steps_per_circle=self.app.defaults[
  1261. "geometry_circle_steps"],
  1262. overlap=over,
  1263. contour=True,
  1264. connect=conn,
  1265. prog_plot=prog_plot)
  1266. pads_lines_list += [p for p in f_o.get_objects() if p]
  1267. elif ap_type == 'O':
  1268. f_o = self.clear_polygon2(elem['solid'],
  1269. tooldia=tooldiameter,
  1270. steps_per_circle=self.app.defaults[
  1271. "geometry_circle_steps"],
  1272. overlap=over,
  1273. contour=True,
  1274. connect=conn,
  1275. prog_plot=prog_plot)
  1276. pads_lines_list += [p for p in f_o.get_objects() if p]
  1277. elif ap_type == 'R':
  1278. f_o = self.clear_polygon3(elem['solid'],
  1279. tooldia=tooldiameter,
  1280. steps_per_circle=self.app.defaults[
  1281. "geometry_circle_steps"],
  1282. overlap=over,
  1283. contour=True,
  1284. connect=conn,
  1285. prog_plot=prog_plot)
  1286. pads_lines_list += [p for p in f_o.get_objects() if p]
  1287. # add the lines from pads to the storage
  1288. try:
  1289. for lin in pads_lines_list:
  1290. if lin:
  1291. cpoly.insert(lin)
  1292. except TypeError:
  1293. cpoly.insert(pads_lines_list)
  1294. copper_lines_list = []
  1295. # process the traces found in the selected polygon using the 'laser_lines' method,
  1296. # method which will follow the 'follow' line therefore use the longer path possible for the
  1297. # laser, therefore the acceleration will play a smaller factor
  1298. for aperture_size in traces_el_dict:
  1299. for elem in traces_el_dict[aperture_size]:
  1300. line = elem['follow']
  1301. if line:
  1302. t_o = self.fill_with_lines(line, aperture_size,
  1303. tooldia=tooldiameter,
  1304. steps_per_circle=self.app.defaults[
  1305. "geometry_circle_steps"],
  1306. overlap=over,
  1307. contour=cont,
  1308. connect=conn,
  1309. prog_plot=prog_plot)
  1310. copper_lines_list += [p for p in t_o.get_objects() if p]
  1311. # add the lines from copper features to storage but first try to make as few lines as possible
  1312. # by trying to fuse them
  1313. lines_union = linemerge(unary_union(copper_lines_list))
  1314. try:
  1315. for lin in lines_union:
  1316. if lin:
  1317. cpoly.insert(lin)
  1318. except TypeError:
  1319. cpoly.insert(lines_union)
  1320. # # determine the Gerber follow line
  1321. # for apid, apval in obj.apertures.items():
  1322. # for geo_el in apval['geometry']:
  1323. # if 'solid' in geo_el:
  1324. # if Point(inside_pt).within(geo_el['solid']):
  1325. # if not isinstance(geo_el['follow'], Point):
  1326. # line = geo_el['follow']
  1327. #
  1328. # if apval['type'] == 'C':
  1329. # aperture_size = apval['size']
  1330. # else:
  1331. # if apval['width'] > apval['height']:
  1332. # aperture_size = apval['height']
  1333. # else:
  1334. # aperture_size = apval['width']
  1335. #
  1336. # if line:
  1337. # cpoly = self.fill_with_lines(line, aperture_size,
  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. except grace:
  1345. return "fail"
  1346. except Exception as ee:
  1347. log.debug("ToolPaint.paint_polygon_worker() Laser Lines --> %s" % str(ee))
  1348. elif paint_method == _("Combo"):
  1349. try:
  1350. self.app.inform.emit(_("Painting polygon with method: lines."))
  1351. cpoly = self.clear_polygon3(polyg,
  1352. tooldia=tooldiameter,
  1353. steps_per_circle=self.circle_steps,
  1354. overlap=over,
  1355. contour=cont,
  1356. connect=conn,
  1357. prog_plot=prog_plot)
  1358. if cpoly and cpoly.objects:
  1359. pass
  1360. else:
  1361. self.app.inform.emit(_("Failed. Painting polygon with method: seed."))
  1362. cpoly = self.clear_polygon2(polyg,
  1363. tooldia=tooldiameter,
  1364. steps_per_circle=self.circle_steps,
  1365. overlap=over,
  1366. contour=cont,
  1367. connect=conn,
  1368. prog_plot=prog_plot)
  1369. if cpoly and cpoly.objects:
  1370. pass
  1371. else:
  1372. self.app.inform.emit(_("Failed. Painting polygon with method: standard."))
  1373. cpoly = self.clear_polygon(polyg,
  1374. tooldia=tooldiameter,
  1375. steps_per_circle=self.circle_steps,
  1376. overlap=over,
  1377. contour=cont,
  1378. connect=conn,
  1379. prog_plot=prog_plot)
  1380. except grace:
  1381. return "fail"
  1382. except Exception as ee:
  1383. log.debug("ToolPaint.paint_polygon_worker() Combo --> %s" % str(ee))
  1384. if cpoly and cpoly.objects:
  1385. return cpoly
  1386. else:
  1387. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be painted completely'))
  1388. return None
  1389. def paint_poly(self, obj, inside_pt=None, poly_list=None, tooldia=None, order=None, method=None, outname=None,
  1390. tools_storage=None, plot=True, run_threaded=True):
  1391. """
  1392. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1393. Note:
  1394. * The margin is taken directly from the form.
  1395. :param run_threaded:
  1396. :param plot:
  1397. :param poly_list:
  1398. :param obj: painted object
  1399. :param inside_pt: [x, y]
  1400. :param tooldia: Diameter of the painting tool
  1401. :param order: if the tools are ordered and how
  1402. :param outname: Name of the resulting Geometry Object.
  1403. :param method: choice out of _("Seed"), 'normal', 'lines'
  1404. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1405. Usage of the different one is related to when this function is called from a TcL command.
  1406. :return: None
  1407. """
  1408. if obj.kind == 'gerber':
  1409. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1410. if self.app.defaults["gerber_buffering"] == 'no':
  1411. msg = '%s %s %s' % (_("Paint Tool."),
  1412. _("Normal painting polygon task started."),
  1413. _("Buffering geometry..."))
  1414. self.app.inform.emit(msg)
  1415. else:
  1416. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1417. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1418. if isinstance(obj.solid_geometry, list):
  1419. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1420. else:
  1421. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1422. else:
  1423. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1424. if inside_pt and poly_list is None:
  1425. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1426. elif (inside_pt is None and poly_list) or (inside_pt and poly_list):
  1427. polygon_list = poly_list
  1428. else:
  1429. return
  1430. # No polygon?
  1431. if polygon_list is None:
  1432. self.app.log.warning('No polygon found.')
  1433. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1434. return
  1435. paint_method = method if method is not None else self.ui.paintmethod_combo.get_value()
  1436. # determine if to use the progressive plotting
  1437. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1438. name = outname if outname is not None else self.obj_name + "_paint"
  1439. order = order if order is not None else self.ui.order_radio.get_value()
  1440. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1441. sorted_tools = []
  1442. if tooldia is not None:
  1443. try:
  1444. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1445. except AttributeError:
  1446. if not isinstance(tooldia, list):
  1447. sorted_tools = [float(tooldia)]
  1448. else:
  1449. sorted_tools = tooldia
  1450. else:
  1451. for row in range(self.ui.tools_table.rowCount()):
  1452. sorted_tools.append(float(self.ui.tools_table.item(row, 1).text()))
  1453. # sort the tools if we have an order selected in the UI
  1454. if order == 'fwd':
  1455. sorted_tools.sort(reverse=False)
  1456. elif order == 'rev':
  1457. sorted_tools.sort(reverse=True)
  1458. proc = self.app.proc_container.new(_("Painting polygon..."))
  1459. tool_dia = None
  1460. current_uid = None
  1461. final_solid_geometry = []
  1462. old_disp_number = 0
  1463. for tool_dia in sorted_tools:
  1464. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1465. msg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1466. str(tool_dia),
  1467. self.units.lower(),
  1468. _('started'))
  1469. self.app.inform.emit(msg)
  1470. self.app.proc_container.update_view_text(' %d%%' % 0)
  1471. # find the tooluid associated with the current tool_dia so we know what tool to use
  1472. for k, v in tools_storage.items():
  1473. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1474. current_uid = int(k)
  1475. if not current_uid:
  1476. return "fail"
  1477. # determine the tool parameters to use
  1478. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1479. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1480. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1481. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  1482. poly_buf = []
  1483. for pol in polygon_list:
  1484. buffered_pol = pol.buffer(-paint_offset)
  1485. if buffered_pol and not buffered_pol.is_empty:
  1486. poly_buf.append(buffered_pol)
  1487. if not poly_buf:
  1488. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1489. continue
  1490. # variables to display the percentage of work done
  1491. geo_len = len(poly_buf)
  1492. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1493. pol_nr = 0
  1494. # -----------------------------
  1495. # effective polygon clearing job
  1496. # -----------------------------
  1497. try:
  1498. cp = []
  1499. try:
  1500. for pp in poly_buf:
  1501. # provide the app with a way to process the GUI events when in a blocking loop
  1502. QtWidgets.QApplication.processEvents()
  1503. if self.app.abort_flag:
  1504. # graceful abort requested by the user
  1505. raise grace
  1506. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1507. cont=cont, paint_method=paint_method, obj=obj,
  1508. prog_plot=prog_plot)
  1509. if geo_res:
  1510. cp.append(geo_res)
  1511. pol_nr += 1
  1512. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1513. # log.debug("Polygons cleared: %d" % pol_nr)
  1514. if old_disp_number < disp_number <= 100:
  1515. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1516. old_disp_number = disp_number
  1517. except TypeError:
  1518. # provide the app with a way to process the GUI events when in a blocking loop
  1519. QtWidgets.QApplication.processEvents()
  1520. if self.app.abort_flag:
  1521. # graceful abort requested by the user
  1522. raise grace
  1523. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1524. cont=cont, paint_method=paint_method, obj=obj,
  1525. prog_plot=prog_plot)
  1526. if geo_res:
  1527. cp.append(geo_res)
  1528. total_geometry = []
  1529. if cp:
  1530. for x in cp:
  1531. total_geometry += list(x.get_objects())
  1532. final_solid_geometry += total_geometry
  1533. except grace:
  1534. return "fail"
  1535. except Exception as e:
  1536. log.debug("Could not Paint the polygons. %s" % str(e))
  1537. self.app.inform.emit(
  1538. '[ERROR] %s\n%s' %
  1539. (_("Could not do Paint. Try a different combination of parameters. "
  1540. "Or a different strategy of paint"), str(e)
  1541. )
  1542. )
  1543. continue
  1544. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1545. # dictionary and then reset the temporary list that stored that solid_geometry
  1546. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1547. tools_storage[current_uid]['data']['name'] = name
  1548. # clean the progressive plotted shapes if it was used
  1549. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1550. self.temp_shapes.clear(update=True)
  1551. # delete tools with empty geometry
  1552. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1553. for uid in list(tools_storage.keys()):
  1554. # if the solid_geometry (type=list) is empty
  1555. if not tools_storage[uid]['solid_geometry']:
  1556. tools_storage.pop(uid, None)
  1557. if not tools_storage:
  1558. return 'fail'
  1559. def job_init(geo_obj, app_obj):
  1560. geo_obj.options["cnctooldia"] = str(tool_dia)
  1561. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1562. geo_obj.multigeo = True
  1563. geo_obj.multitool = True
  1564. geo_obj.tools.clear()
  1565. geo_obj.tools = dict(tools_storage)
  1566. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1567. try:
  1568. if isinstance(geo_obj.solid_geometry, list):
  1569. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1570. else:
  1571. a, b, c, d = geo_obj.solid_geometry.bounds
  1572. geo_obj.options['xmin'] = a
  1573. geo_obj.options['ymin'] = b
  1574. geo_obj.options['xmax'] = c
  1575. geo_obj.options['ymax'] = d
  1576. except Exception as ee:
  1577. log.debug("ToolPaint.paint_poly.job_init() bounds error --> %s" % str(ee))
  1578. return
  1579. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1580. has_solid_geo = 0
  1581. for tooluid in geo_obj.tools:
  1582. if geo_obj.tools[tooluid]['solid_geometry']:
  1583. has_solid_geo += 1
  1584. if has_solid_geo == 0:
  1585. app_obj.inform.emit('[ERROR] %s' %
  1586. _("There is no Painting Geometry in the file.\n"
  1587. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1588. "Change the painting parameters and try again."))
  1589. return "fail"
  1590. # Experimental...
  1591. # print("Indexing...", end=' ')
  1592. # geo_obj.make_index()
  1593. def job_thread(app_obj):
  1594. try:
  1595. ret = app_obj.app_obj.new_object("geometry", name, job_init, plot=plot)
  1596. except grace:
  1597. proc.done()
  1598. return
  1599. except Exception as er:
  1600. proc.done()
  1601. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_poly()', str(er)))
  1602. traceback.print_stack()
  1603. return
  1604. proc.done()
  1605. if ret == 'fail':
  1606. self.app.inform.emit('[ERROR] %s' % _("Paint Single failed."))
  1607. return
  1608. # focus on Selected Tab
  1609. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1610. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1611. self.app.inform.emit(_("Polygon Paint started ..."))
  1612. # Promise object with the new name
  1613. self.app.collection.promise(name)
  1614. if run_threaded:
  1615. # Background
  1616. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1617. else:
  1618. job_thread(app_obj=self.app)
  1619. def paint_poly_all(self, obj, tooldia=None, order=None, method=None, outname=None, tools_storage=None, plot=True,
  1620. run_threaded=True):
  1621. """
  1622. Paints all polygons in this object.
  1623. :param obj: painted object
  1624. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1625. :param order: if the tools are ordered and how
  1626. :param outname: name of the resulting object
  1627. :param method: choice out of _("Seed"), 'normal', 'lines'
  1628. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1629. Usage of the different one is related to when this function is called from
  1630. a TcL command.
  1631. :param run_threaded:
  1632. :param plot:
  1633. :return:
  1634. """
  1635. # This is a recursive generator of individual Polygons.
  1636. # Note: Double check correct implementation. Might exit
  1637. # early if it finds something that is not a Polygon?
  1638. # def recurse(geo):
  1639. # try:
  1640. # for subg in geo:
  1641. # for subsubg in recurse(subg):
  1642. # yield subsubg
  1643. # except TypeError:
  1644. # if isinstance(geo, Polygon):
  1645. # yield geo
  1646. #
  1647. # raise StopIteration
  1648. def recurse(geometry, reset=True):
  1649. """
  1650. Creates a list of non-iterable linear geometry objects.
  1651. Results are placed in self.flat_geometry
  1652. :param geometry: Shapely type or list or list of list of such.
  1653. :param reset: Clears the contents of self.flat_geometry.
  1654. """
  1655. if self.app.abort_flag:
  1656. # graceful abort requested by the user
  1657. raise grace
  1658. if geometry is None:
  1659. return
  1660. if reset:
  1661. self.flat_geometry = []
  1662. # ## If iterable, expand recursively.
  1663. try:
  1664. for geo in geometry:
  1665. if geo is not None:
  1666. recurse(geometry=geo, reset=False)
  1667. # ## Not iterable, do the actual indexing and add.
  1668. except TypeError:
  1669. if isinstance(geometry, LinearRing):
  1670. g = Polygon(geometry)
  1671. self.flat_geometry.append(g)
  1672. else:
  1673. self.flat_geometry.append(geometry)
  1674. return self.flat_geometry
  1675. if obj.kind == 'gerber':
  1676. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  1677. if self.app.defaults["gerber_buffering"] == 'no':
  1678. msg = '%s %s %s' % (_("Paint Tool."), _("Paint all polygons task started."), _("Buffering geometry..."))
  1679. self.app.inform.emit(msg)
  1680. else:
  1681. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1682. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1683. if isinstance(obj.solid_geometry, list):
  1684. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1685. else:
  1686. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1687. else:
  1688. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Paint all polygons task started.")))
  1689. painted_area = recurse(obj.solid_geometry)
  1690. # No polygon?
  1691. if not painted_area:
  1692. self.app.log.warning('No polygon found.')
  1693. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1694. return
  1695. paint_method = method if method is not None else self.ui.paintmethod_combo.get_value()
  1696. # determine if to use the progressive plotting
  1697. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1698. name = outname if outname is not None else self.obj_name + "_paint"
  1699. order = order if order is not None else self.ui.order_radio.get_value()
  1700. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1701. sorted_tools = []
  1702. if tooldia is not None:
  1703. try:
  1704. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1705. except AttributeError:
  1706. if not isinstance(tooldia, list):
  1707. sorted_tools = [float(tooldia)]
  1708. else:
  1709. sorted_tools = tooldia
  1710. else:
  1711. for row in range(self.ui.tools_table.rowCount()):
  1712. sorted_tools.append(float(self.ui.tools_table.item(row, 1).text()))
  1713. proc = self.app.proc_container.new(_("Painting polygons..."))
  1714. # Initializes the new geometry object
  1715. def gen_paintarea(geo_obj, app_obj):
  1716. log.debug("Paint Tool. Normal painting all task started.")
  1717. if order == 'fwd':
  1718. sorted_tools.sort(reverse=False)
  1719. elif order == 'rev':
  1720. sorted_tools.sort(reverse=True)
  1721. else:
  1722. pass
  1723. tool_dia = None
  1724. current_uid = int(1)
  1725. old_disp_number = 0
  1726. final_solid_geometry = []
  1727. for tool_dia in sorted_tools:
  1728. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1729. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1730. str(tool_dia), self.units.lower(),
  1731. _('started'))
  1732. app_obj.inform.emit(mssg)
  1733. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1734. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1735. for k, v in tools_storage.items():
  1736. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1737. current_uid = int(k)
  1738. break
  1739. if not current_uid:
  1740. return "fail"
  1741. # determine the tool parameters to use
  1742. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1743. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1744. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1745. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  1746. poly_buf = []
  1747. for pol in painted_area:
  1748. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  1749. buffered_pol = pol.buffer(-paint_offset)
  1750. if buffered_pol and not buffered_pol.is_empty:
  1751. poly_buf.append(buffered_pol)
  1752. if not poly_buf:
  1753. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1754. continue
  1755. # variables to display the percentage of work done
  1756. geo_len = len(poly_buf)
  1757. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1758. pol_nr = 0
  1759. # -----------------------------
  1760. # effective polygon clearing job
  1761. # -----------------------------
  1762. poly_processed = []
  1763. try:
  1764. cp = []
  1765. try:
  1766. for pp in poly_buf:
  1767. # provide the app with a way to process the GUI events when in a blocking loop
  1768. QtWidgets.QApplication.processEvents()
  1769. if self.app.abort_flag:
  1770. # graceful abort requested by the user
  1771. raise grace
  1772. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1773. cont=cont, paint_method=paint_method, obj=obj,
  1774. prog_plot=prog_plot)
  1775. if geo_res:
  1776. cp.append(geo_res)
  1777. poly_processed.append(True)
  1778. else:
  1779. poly_processed.append(False)
  1780. pol_nr += 1
  1781. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1782. # log.debug("Polygons cleared: %d" % pol_nr)
  1783. if old_disp_number < disp_number <= 100:
  1784. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1785. old_disp_number = disp_number
  1786. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1787. except TypeError:
  1788. # provide the app with a way to process the GUI events when in a blocking loop
  1789. QtWidgets.QApplication.processEvents()
  1790. if self.app.abort_flag:
  1791. # graceful abort requested by the user
  1792. raise grace
  1793. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1794. cont=cont, paint_method=paint_method, obj=obj,
  1795. prog_plot=prog_plot)
  1796. if geo_res:
  1797. cp.append(geo_res)
  1798. poly_processed.append(True)
  1799. else:
  1800. poly_processed.append(False)
  1801. total_geometry = []
  1802. if cp:
  1803. for x in cp:
  1804. total_geometry += list(x.get_objects())
  1805. # clean the geometry
  1806. new_geo = [g for g in total_geometry if g and not g.is_empty]
  1807. total_geometry = new_geo
  1808. final_solid_geometry += total_geometry
  1809. except Exception as err:
  1810. log.debug("Could not Paint the polygons. %s" % str(err))
  1811. self.app.inform.emit(
  1812. '[ERROR] %s\n%s' %
  1813. (_("Could not do Paint. Try a different combination of parameters. "
  1814. "Or a different strategy of paint"), str(err)
  1815. )
  1816. )
  1817. continue
  1818. p_cleared = poly_processed.count(True)
  1819. p_not_cleared = poly_processed.count(False)
  1820. if p_not_cleared:
  1821. app_obj.poly_not_cleared = True
  1822. if p_cleared == 0:
  1823. continue
  1824. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1825. # dictionary and then reset the temporary list that stored that solid_geometry
  1826. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1827. tools_storage[current_uid]['data']['name'] = name
  1828. # clean the progressive plotted shapes if it was used
  1829. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1830. self.temp_shapes.clear(update=True)
  1831. # delete tools with empty geometry
  1832. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1833. for uid in list(tools_storage.keys()):
  1834. # if the solid_geometry (type=list) is empty
  1835. if not tools_storage[uid]['solid_geometry']:
  1836. tools_storage.pop(uid, None)
  1837. if not tools_storage:
  1838. return 'fail'
  1839. geo_obj.options["cnctooldia"] = str(tool_dia)
  1840. # this turn on the FlatCAMCNCJob plot for multiple tools
  1841. geo_obj.multigeo = True
  1842. geo_obj.multitool = True
  1843. geo_obj.tools.clear()
  1844. geo_obj.tools = dict(tools_storage)
  1845. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1846. try:
  1847. # a, b, c, d = obj.bounds()
  1848. if isinstance(geo_obj.solid_geometry, list):
  1849. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1850. else:
  1851. a, b, c, d = geo_obj.solid_geometry.bounds
  1852. geo_obj.options['xmin'] = a
  1853. geo_obj.options['ymin'] = b
  1854. geo_obj.options['xmax'] = c
  1855. geo_obj.options['ymax'] = d
  1856. except Exception as e:
  1857. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1858. return
  1859. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1860. has_solid_geo = 0
  1861. for tooluid in geo_obj.tools:
  1862. if geo_obj.tools[tooluid]['solid_geometry']:
  1863. has_solid_geo += 1
  1864. if has_solid_geo == 0:
  1865. self.app.inform.emit('[ERROR] %s' %
  1866. _("There is no Painting Geometry in the file.\n"
  1867. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1868. "Change the painting parameters and try again."))
  1869. return "fail"
  1870. # Experimental...
  1871. # print("Indexing...", end=' ')
  1872. # geo_obj.make_index()
  1873. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  1874. # Initializes the new geometry object
  1875. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1876. log.debug("Paint Tool. Rest machining painting all task started.")
  1877. # when using rest machining use always the reverse order; from bigger tool to smaller one
  1878. sorted_tools.sort(reverse=True)
  1879. tool_dia = None
  1880. cleared_geo = []
  1881. current_uid = int(1)
  1882. old_disp_number = 0
  1883. final_solid_geometry = []
  1884. for tool_dia in sorted_tools:
  1885. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1886. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1887. str(tool_dia),
  1888. self.units.lower(),
  1889. _('started'))
  1890. app_obj.inform.emit(mssg)
  1891. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1892. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1893. for k, v in tools_storage.items():
  1894. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1895. current_uid = int(k)
  1896. break
  1897. if not current_uid:
  1898. return "fail"
  1899. # determine the tool parameters to use
  1900. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  1901. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  1902. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  1903. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  1904. poly_buf = []
  1905. for pol in painted_area:
  1906. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  1907. buffered_pol = pol.buffer(-paint_offset)
  1908. if buffered_pol and not buffered_pol.is_empty:
  1909. poly_buf.append(buffered_pol)
  1910. if not poly_buf:
  1911. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  1912. continue
  1913. # variables to display the percentage of work done
  1914. geo_len = len(poly_buf)
  1915. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1916. pol_nr = 0
  1917. # -----------------------------
  1918. # effective polygon clearing job
  1919. # -----------------------------
  1920. try:
  1921. cp = []
  1922. try:
  1923. for pp in poly_buf:
  1924. # provide the app with a way to process the GUI events when in a blocking loop
  1925. QtWidgets.QApplication.processEvents()
  1926. if self.app.abort_flag:
  1927. # graceful abort requested by the user
  1928. raise grace
  1929. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  1930. cont=cont, paint_method=paint_method, obj=obj,
  1931. prog_plot=prog_plot)
  1932. if geo_res:
  1933. cp.append(geo_res)
  1934. pol_nr += 1
  1935. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1936. # log.debug("Polygons cleared: %d" % pol_nr)
  1937. if old_disp_number < disp_number <= 100:
  1938. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1939. old_disp_number = disp_number
  1940. except TypeError:
  1941. # provide the app with a way to process the GUI events when in a blocking loop
  1942. QtWidgets.QApplication.processEvents()
  1943. if self.app.abort_flag:
  1944. # graceful abort requested by the user
  1945. raise grace
  1946. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  1947. cont=cont, paint_method=paint_method, obj=obj,
  1948. prog_plot=prog_plot)
  1949. if geo_res:
  1950. cp.append(geo_res)
  1951. if cp:
  1952. for x in cp:
  1953. cleared_geo += list(x.get_objects())
  1954. final_solid_geometry += cleared_geo
  1955. except grace:
  1956. return "fail"
  1957. except Exception as e:
  1958. log.debug("Could not Paint the polygons. %s" % str(e))
  1959. mssg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  1960. "Or a different strategy of paint"),
  1961. str(e))
  1962. self.app.inform.emit(mssg)
  1963. continue
  1964. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1965. # then reset the temporary list that stored that solid_geometry
  1966. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1967. tools_storage[current_uid]['data']['name'] = name
  1968. cleared_geo[:] = []
  1969. # clean the progressive plotted shapes if it was used
  1970. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1971. self.temp_shapes.clear(update=True)
  1972. # delete tools with empty geometry
  1973. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1974. for uid in list(tools_storage.keys()):
  1975. # if the solid_geometry (type=list) is empty
  1976. if not tools_storage[uid]['solid_geometry']:
  1977. tools_storage.pop(uid, None)
  1978. if not tools_storage:
  1979. return 'fail'
  1980. geo_obj.options["cnctooldia"] = str(tool_dia)
  1981. # this turn on the FlatCAMCNCJob plot for multiple tools
  1982. geo_obj.multigeo = True
  1983. geo_obj.multitool = True
  1984. geo_obj.tools.clear()
  1985. geo_obj.tools = dict(tools_storage)
  1986. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  1987. try:
  1988. # a, b, c, d = obj.bounds()
  1989. if isinstance(geo_obj.solid_geometry, list):
  1990. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1991. else:
  1992. a, b, c, d = geo_obj.solid_geometry.bounds
  1993. geo_obj.options['xmin'] = a
  1994. geo_obj.options['ymin'] = b
  1995. geo_obj.options['xmax'] = c
  1996. geo_obj.options['ymax'] = d
  1997. except Exception as e:
  1998. log.debug("ToolPaint.paint_poly.gen_paintarea_rest_machining() bounds error --> %s" % str(e))
  1999. return
  2000. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2001. has_solid_geo = 0
  2002. for tooluid in geo_obj.tools:
  2003. if geo_obj.tools[tooluid]['solid_geometry']:
  2004. has_solid_geo += 1
  2005. if has_solid_geo == 0:
  2006. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2007. _("There is no Painting Geometry in the file.\n"
  2008. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2009. "Change the painting parameters and try again."))
  2010. return 'fail'
  2011. # Experimental...
  2012. # print("Indexing...", end=' ')
  2013. # geo_obj.make_index()
  2014. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2015. def job_thread(app_obj):
  2016. try:
  2017. if self.ui.rest_cb.isChecked():
  2018. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2019. else:
  2020. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2021. except grace:
  2022. proc.done()
  2023. return
  2024. except Exception as err:
  2025. proc.done()
  2026. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_poly_all()', str(err)))
  2027. traceback.print_stack()
  2028. return
  2029. proc.done()
  2030. if ret == 'fail':
  2031. self.app.inform.emit('[ERROR] %s' % _("Paint All failed."))
  2032. return
  2033. # focus on Selected Tab
  2034. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2035. self.app.inform.emit('[success] %s' % _("Paint Poly All Done."))
  2036. self.app.inform.emit(_("Polygon Paint started ..."))
  2037. # Promise object with the new name
  2038. self.app.collection.promise(name)
  2039. if run_threaded:
  2040. # Background
  2041. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2042. else:
  2043. job_thread(app_obj=self.app)
  2044. def paint_poly_area(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  2045. tools_storage=None, plot=True, run_threaded=True):
  2046. """
  2047. Paints all polygons in this object that are within the sel_obj object
  2048. :param obj: painted object
  2049. :param sel_obj: paint only what is inside this object bounds
  2050. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2051. :param order: if the tools are ordered and how
  2052. :param outname: name of the resulting object
  2053. :param method: choice out of _("Seed"), 'normal', 'lines'
  2054. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2055. Usage of the different one is related to when this function is called from a TcL command.
  2056. :param run_threaded:
  2057. :param plot:
  2058. :return:
  2059. """
  2060. def recurse(geometry, reset=True):
  2061. """
  2062. Creates a list of non-iterable linear geometry objects.
  2063. Results are placed in self.flat_geometry
  2064. :param geometry: Shapely type or list or list of list of such.
  2065. :param reset: Clears the contents of self.flat_geometry.
  2066. """
  2067. if self.app.abort_flag:
  2068. # graceful abort requested by the user
  2069. raise grace
  2070. if geometry is None:
  2071. return
  2072. if reset:
  2073. self.flat_geometry = []
  2074. # ## If iterable, expand recursively.
  2075. try:
  2076. for geo in geometry:
  2077. if geo is not None:
  2078. recurse(geometry=geo, reset=False)
  2079. # ## Not iterable, do the actual indexing and add.
  2080. except TypeError:
  2081. if isinstance(geometry, LinearRing):
  2082. g = Polygon(geometry)
  2083. self.flat_geometry.append(g)
  2084. else:
  2085. self.flat_geometry.append(geometry)
  2086. return self.flat_geometry
  2087. # this is were heavy lifting is done and creating the geometry to be painted
  2088. target_geo = MultiPolygon(obj.solid_geometry)
  2089. if obj.kind == 'gerber':
  2090. # I don't do anything here, like buffering when the Gerber is loaded without buffering????!!!!
  2091. if self.app.defaults["gerber_buffering"] == 'no':
  2092. msg = '%s %s %s' % (_("Paint Tool."),
  2093. _("Painting area task started."),
  2094. _("Buffering geometry..."))
  2095. self.app.inform.emit(msg)
  2096. else:
  2097. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2098. if obj.kind == 'gerber':
  2099. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2100. target_geo = target_geo.buffer(0)
  2101. else:
  2102. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Painting area task started.")))
  2103. geo_to_paint = target_geo.intersection(sel_obj)
  2104. painted_area = recurse(geo_to_paint)
  2105. # No polygon?
  2106. if not painted_area:
  2107. self.app.log.warning('No polygon found.')
  2108. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  2109. return
  2110. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  2111. # determine if to use the progressive plotting
  2112. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  2113. name = outname if outname is not None else self.obj_name + "_paint"
  2114. order = order if order is not None else self.ui.order_radio.get_value()
  2115. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  2116. sorted_tools = []
  2117. if tooldia is not None:
  2118. try:
  2119. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  2120. except AttributeError:
  2121. if not isinstance(tooldia, list):
  2122. sorted_tools = [float(tooldia)]
  2123. else:
  2124. sorted_tools = tooldia
  2125. else:
  2126. for row in range(self.ui.tools_table.rowCount()):
  2127. sorted_tools.append(float(self.ui.tools_table.item(row, 1).text()))
  2128. proc = self.app.proc_container.new(_("Painting polygons..."))
  2129. # Initializes the new geometry object
  2130. def gen_paintarea(geo_obj, app_obj):
  2131. log.debug("Paint Tool. Normal painting area task started.")
  2132. if order == 'fwd':
  2133. sorted_tools.sort(reverse=False)
  2134. elif order == 'rev':
  2135. sorted_tools.sort(reverse=True)
  2136. else:
  2137. pass
  2138. tool_dia = None
  2139. current_uid = int(1)
  2140. old_disp_number = 0
  2141. final_solid_geometry = []
  2142. for tool_dia in sorted_tools:
  2143. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2144. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2145. str(tool_dia),
  2146. self.units.lower(),
  2147. _('started'))
  2148. app_obj.inform.emit(mssg)
  2149. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2150. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2151. for k, v in tools_storage.items():
  2152. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2153. current_uid = int(k)
  2154. break
  2155. if not current_uid:
  2156. return "fail"
  2157. # determine the tool parameters to use
  2158. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  2159. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  2160. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  2161. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  2162. poly_buf = []
  2163. for pol in painted_area:
  2164. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  2165. buffered_pol = pol.buffer(-paint_offset)
  2166. if buffered_pol and not buffered_pol.is_empty:
  2167. poly_buf.append(buffered_pol)
  2168. if not poly_buf:
  2169. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  2170. continue
  2171. # variables to display the percentage of work done
  2172. geo_len = len(poly_buf)
  2173. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2174. pol_nr = 0
  2175. # -----------------------------
  2176. # effective polygon clearing job
  2177. # -----------------------------
  2178. poly_processed = []
  2179. total_geometry = []
  2180. try:
  2181. try:
  2182. for pp in poly_buf:
  2183. # provide the app with a way to process the GUI events when in a blocking loop
  2184. QtWidgets.QApplication.processEvents()
  2185. if self.app.abort_flag:
  2186. # graceful abort requested by the user
  2187. raise grace
  2188. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  2189. cont=cont, paint_method=paint_method, obj=obj,
  2190. prog_plot=prog_plot)
  2191. if geo_res and geo_res.objects:
  2192. total_geometry += list(geo_res.get_objects())
  2193. poly_processed.append(True)
  2194. else:
  2195. poly_processed.append(False)
  2196. pol_nr += 1
  2197. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2198. # log.debug("Polygons cleared: %d" % pol_nr)
  2199. if old_disp_number < disp_number <= 100:
  2200. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2201. old_disp_number = disp_number
  2202. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2203. except TypeError:
  2204. # provide the app with a way to process the GUI events when in a blocking loop
  2205. QtWidgets.QApplication.processEvents()
  2206. if self.app.abort_flag:
  2207. # graceful abort requested by the user
  2208. raise grace
  2209. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  2210. cont=cont, paint_method=paint_method, obj=obj,
  2211. prog_plot=prog_plot)
  2212. if geo_res and geo_res.objects:
  2213. total_geometry += list(geo_res.get_objects())
  2214. poly_processed.append(True)
  2215. else:
  2216. poly_processed.append(False)
  2217. except Exception as err:
  2218. log.debug("Could not Paint the polygons. %s" % str(err))
  2219. self.app.inform.emit(
  2220. '[ERROR] %s\n%s' %
  2221. (_("Could not do Paint. Try a different combination of parameters. "
  2222. "Or a different strategy of paint"), str(err)
  2223. )
  2224. )
  2225. continue
  2226. p_cleared = poly_processed.count(True)
  2227. p_not_cleared = poly_processed.count(False)
  2228. if p_not_cleared:
  2229. app_obj.poly_not_cleared = True
  2230. if p_cleared == 0:
  2231. continue
  2232. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  2233. # dictionary and then reset the temporary list that stored that solid_geometry
  2234. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  2235. tools_storage[current_uid]['data']['name'] = name
  2236. total_geometry[:] = []
  2237. # clean the progressive plotted shapes if it was used
  2238. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2239. self.temp_shapes.clear(update=True)
  2240. # delete tools with empty geometry
  2241. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2242. for uid in list(tools_storage.keys()):
  2243. # if the solid_geometry (type=list) is empty
  2244. if not tools_storage[uid]['solid_geometry']:
  2245. tools_storage.pop(uid, None)
  2246. if not tools_storage:
  2247. return 'fail'
  2248. geo_obj.options["cnctooldia"] = str(tool_dia)
  2249. # this turn on the FlatCAMCNCJob plot for multiple tools
  2250. geo_obj.multigeo = True
  2251. geo_obj.multitool = True
  2252. geo_obj.tools.clear()
  2253. geo_obj.tools = dict(tools_storage)
  2254. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  2255. try:
  2256. a, b, c, d = self.paint_bounds(geo_to_paint)
  2257. geo_obj.options['xmin'] = a
  2258. geo_obj.options['ymin'] = b
  2259. geo_obj.options['xmax'] = c
  2260. geo_obj.options['ymax'] = d
  2261. except Exception as e:
  2262. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2263. return
  2264. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2265. has_solid_geo = 0
  2266. for tooluid in geo_obj.tools:
  2267. if geo_obj.tools[tooluid]['solid_geometry']:
  2268. has_solid_geo += 1
  2269. if has_solid_geo == 0:
  2270. self.app.inform.emit('[ERROR] %s' %
  2271. _("There is no Painting Geometry in the file.\n"
  2272. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2273. "Change the painting parameters and try again."))
  2274. return "fail"
  2275. # Experimental...
  2276. # print("Indexing...", end=' ')
  2277. # geo_obj.make_index()
  2278. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  2279. # Initializes the new geometry object
  2280. def gen_paintarea_rest_machining(geo_obj, app_obj):
  2281. log.debug("Paint Tool. Rest machining painting area task started.")
  2282. sorted_tools.sort(reverse=True)
  2283. cleared_geo = []
  2284. tool_dia = None
  2285. current_uid = int(1)
  2286. old_disp_number = 0
  2287. final_solid_geometry = []
  2288. for tool_dia in sorted_tools:
  2289. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2290. mssg = '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2291. str(tool_dia),
  2292. self.units.lower(),
  2293. _('started'))
  2294. app_obj.inform.emit(mssg)
  2295. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2296. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2297. for k, v in tools_storage.items():
  2298. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2299. current_uid = int(k)
  2300. break
  2301. if not current_uid:
  2302. return "fail"
  2303. # determine the tool parameters to use
  2304. over = float(tools_storage[current_uid]['data']['tools_paintoverlap']) / 100.0
  2305. conn = tools_storage[current_uid]['data']['tools_pathconnect']
  2306. cont = tools_storage[current_uid]['data']['tools_paintcontour']
  2307. paint_offset = float(tools_storage[current_uid]['data']['tools_paintoffset'])
  2308. poly_buf = []
  2309. for pol in painted_area:
  2310. pol = Polygon(pol) if not isinstance(pol, Polygon) else pol
  2311. buffered_pol = pol.buffer(-paint_offset)
  2312. if buffered_pol and not buffered_pol.is_empty:
  2313. poly_buf.append(buffered_pol)
  2314. if not poly_buf:
  2315. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Margin parameter too big. Tool is not used"))
  2316. continue
  2317. # variables to display the percentage of work done
  2318. geo_len = len(poly_buf)
  2319. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2320. pol_nr = 0
  2321. # -----------------------------
  2322. # effective polygon clearing job
  2323. # -----------------------------
  2324. poly_processed = []
  2325. try:
  2326. try:
  2327. for pp in poly_buf:
  2328. # provide the app with a way to process the GUI events when in a blocking loop
  2329. QtWidgets.QApplication.processEvents()
  2330. if self.app.abort_flag:
  2331. # graceful abort requested by the user
  2332. raise grace
  2333. geo_res = self.paint_polygon_worker(pp, tooldiameter=tool_dia, over=over, conn=conn,
  2334. cont=cont, paint_method=paint_method, obj=obj,
  2335. prog_plot=prog_plot)
  2336. if geo_res and geo_res.objects:
  2337. cleared_geo += list(geo_res.get_objects())
  2338. poly_processed.append(True)
  2339. else:
  2340. poly_processed.append(False)
  2341. pol_nr += 1
  2342. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2343. # log.debug("Polygons cleared: %d" % pol_nr)
  2344. if old_disp_number < disp_number <= 100:
  2345. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2346. old_disp_number = disp_number
  2347. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2348. except TypeError:
  2349. # provide the app with a way to process the GUI events when in a blocking loop
  2350. QtWidgets.QApplication.processEvents()
  2351. if self.app.abort_flag:
  2352. # graceful abort requested by the user
  2353. raise grace
  2354. geo_res = self.paint_polygon_worker(poly_buf, tooldiameter=tool_dia, over=over, conn=conn,
  2355. cont=cont, paint_method=paint_method, obj=obj,
  2356. prog_plot=prog_plot)
  2357. if geo_res and geo_res.objects:
  2358. cleared_geo += list(geo_res.get_objects())
  2359. poly_processed.append(True)
  2360. else:
  2361. poly_processed.append(False)
  2362. except Exception as err:
  2363. log.debug("Could not Paint the polygons. %s" % str(err))
  2364. mssg = '[ERROR] %s\n%s' % (_("Could not do Paint. Try a different combination of parameters. "
  2365. "Or a different strategy of paint"),
  2366. str(err))
  2367. self.app.inform.emit(mssg)
  2368. continue
  2369. p_cleared = poly_processed.count(True)
  2370. p_not_cleared = poly_processed.count(False)
  2371. if p_not_cleared:
  2372. app_obj.poly_not_cleared = True
  2373. if p_cleared == 0:
  2374. continue
  2375. final_solid_geometry += cleared_geo
  2376. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2377. # then reset the temporary list that stored that solid_geometry
  2378. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2379. tools_storage[current_uid]['data']['name'] = name
  2380. cleared_geo[:] = []
  2381. # clean the progressive plotted shapes if it was used
  2382. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2383. self.temp_shapes.clear(update=True)
  2384. # delete tools with empty geometry
  2385. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2386. for uid in list(tools_storage.keys()):
  2387. # if the solid_geometry (type=list) is empty
  2388. if not tools_storage[uid]['solid_geometry']:
  2389. tools_storage.pop(uid, None)
  2390. if not tools_storage:
  2391. return 'fail'
  2392. geo_obj.options["cnctooldia"] = str(tool_dia)
  2393. # this turn on the FlatCAMCNCJob plot for multiple tools
  2394. geo_obj.multigeo = True
  2395. geo_obj.multitool = True
  2396. geo_obj.tools.clear()
  2397. geo_obj.tools = dict(tools_storage)
  2398. geo_obj.solid_geometry = cascaded_union(final_solid_geometry)
  2399. try:
  2400. a, b, c, d = self.paint_bounds(geo_to_paint)
  2401. geo_obj.options['xmin'] = a
  2402. geo_obj.options['ymin'] = b
  2403. geo_obj.options['xmax'] = c
  2404. geo_obj.options['ymax'] = d
  2405. except Exception as e:
  2406. log.debug("ToolPaint.paint_poly.gen_paintarea_rest_machining() bounds error --> %s" % str(e))
  2407. return
  2408. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2409. has_solid_geo = 0
  2410. for tooluid in geo_obj.tools:
  2411. if geo_obj.tools[tooluid]['solid_geometry']:
  2412. has_solid_geo += 1
  2413. if has_solid_geo == 0:
  2414. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2415. _("There is no Painting Geometry in the file.\n"
  2416. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2417. "Change the painting parameters and try again."))
  2418. return 'fail'
  2419. # Experimental...
  2420. # print("Indexing...", end=' ')
  2421. # geo_obj.make_index()
  2422. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2423. def job_thread(app_obj):
  2424. try:
  2425. if self.ui.rest_cb.isChecked():
  2426. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2427. else:
  2428. ret = app_obj.app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2429. except grace:
  2430. proc.done()
  2431. return
  2432. except Exception as err:
  2433. proc.done()
  2434. app_obj.inform.emit('[ERROR] %s --> %s' % ('PaintTool.paint_poly_area()', str(err)))
  2435. traceback.print_stack()
  2436. return
  2437. proc.done()
  2438. if ret == 'fail':
  2439. self.app.inform.emit('[ERROR] %s' % _("Paint Area failed."))
  2440. return
  2441. # focus on Selected Tab
  2442. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2443. self.app.inform.emit('[success] %s' % _("Paint Poly Area Done."))
  2444. self.app.inform.emit(_("Polygon Paint started ..."))
  2445. # Promise object with the new name
  2446. self.app.collection.promise(name)
  2447. if run_threaded:
  2448. # Background
  2449. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2450. else:
  2451. job_thread(app_obj=self.app)
  2452. def paint_poly_ref(self, obj, sel_obj, tooldia=None, order=None, method=None, outname=None,
  2453. tools_storage=None, plot=True, run_threaded=True):
  2454. """
  2455. Paints all polygons in this object that are within the sel_obj object
  2456. :param obj: painted object
  2457. :param sel_obj: paint only what is inside this object bounds
  2458. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2459. :param order: if the tools are ordered and how
  2460. :param outname: name of the resulting object
  2461. :param method: choice out of _("Seed"), 'normal', 'lines'
  2462. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2463. Usage of the different one is related to when this function is called from a TcL command.
  2464. :param run_threaded:
  2465. :param plot:
  2466. :return:
  2467. """
  2468. geo = sel_obj.solid_geometry
  2469. try:
  2470. if isinstance(geo, MultiPolygon):
  2471. env_obj = geo.convex_hull
  2472. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2473. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2474. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2475. else:
  2476. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2477. env_obj = env_obj.convex_hull
  2478. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2479. except Exception as e:
  2480. log.debug("ToolPaint.paint_poly_ref() --> %s" % str(e))
  2481. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2482. return
  2483. self.paint_poly_area(obj=obj,
  2484. sel_obj=sel_rect,
  2485. tooldia=tooldia,
  2486. order=order,
  2487. method=method,
  2488. outname=outname,
  2489. tools_storage=tools_storage,
  2490. plot=plot,
  2491. run_threaded=run_threaded)
  2492. def ui_connect(self):
  2493. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  2494. # rows selected
  2495. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  2496. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  2497. for row in range(self.ui.tools_table.rowCount()):
  2498. try:
  2499. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2500. except AttributeError:
  2501. pass
  2502. try:
  2503. self.ui.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2504. except AttributeError:
  2505. pass
  2506. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type)
  2507. # first disconnect
  2508. for opt in self.form_fields:
  2509. current_widget = self.form_fields[opt]
  2510. if isinstance(current_widget, FCCheckBox):
  2511. try:
  2512. current_widget.stateChanged.disconnect()
  2513. except (TypeError, ValueError):
  2514. pass
  2515. if isinstance(current_widget, RadioSet):
  2516. try:
  2517. current_widget.activated_custom.disconnect()
  2518. except (TypeError, ValueError):
  2519. pass
  2520. elif isinstance(current_widget, FCDoubleSpinner):
  2521. try:
  2522. current_widget.returnPressed.disconnect()
  2523. except (TypeError, ValueError):
  2524. pass
  2525. # then reconnect
  2526. for opt in self.form_fields:
  2527. current_widget = self.form_fields[opt]
  2528. if isinstance(current_widget, FCCheckBox):
  2529. current_widget.stateChanged.connect(self.form_to_storage)
  2530. if isinstance(current_widget, RadioSet):
  2531. current_widget.activated_custom.connect(self.form_to_storage)
  2532. elif isinstance(current_widget, FCDoubleSpinner):
  2533. current_widget.returnPressed.connect(self.form_to_storage)
  2534. elif isinstance(current_widget, FCComboBox):
  2535. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2536. self.ui.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  2537. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  2538. def ui_disconnect(self):
  2539. try:
  2540. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2541. self.ui.tools_table.itemChanged.disconnect()
  2542. except (TypeError, AttributeError):
  2543. pass
  2544. try:
  2545. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect(self.on_row_selection_change)
  2546. except (TypeError, AttributeError):
  2547. pass
  2548. try:
  2549. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2550. self.ui.tool_type_radio.activated_custom.disconnect()
  2551. except (TypeError, AttributeError):
  2552. pass
  2553. for row in range(self.ui.tools_table.rowCount()):
  2554. for col in [2, 4]:
  2555. try:
  2556. self.ui.tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2557. except (TypeError, AttributeError):
  2558. pass
  2559. for opt in self.form_fields:
  2560. current_widget = self.form_fields[opt]
  2561. if isinstance(current_widget, FCCheckBox):
  2562. try:
  2563. current_widget.stateChanged.disconnect(self.form_to_storage)
  2564. except (TypeError, ValueError):
  2565. pass
  2566. if isinstance(current_widget, RadioSet):
  2567. try:
  2568. current_widget.activated_custom.disconnect(self.form_to_storage)
  2569. except (TypeError, ValueError):
  2570. pass
  2571. elif isinstance(current_widget, FCDoubleSpinner):
  2572. try:
  2573. current_widget.returnPressed.disconnect(self.form_to_storage)
  2574. except (TypeError, ValueError):
  2575. pass
  2576. elif isinstance(current_widget, FCComboBox):
  2577. try:
  2578. current_widget.currentIndexChanged.connect(self.form_to_storage)
  2579. except (TypeError, ValueError):
  2580. pass
  2581. # rows selected
  2582. try:
  2583. self.ui.tools_table.clicked.disconnect()
  2584. except (TypeError, AttributeError):
  2585. pass
  2586. try:
  2587. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  2588. except (TypeError, AttributeError):
  2589. pass
  2590. @staticmethod
  2591. def paint_bounds(geometry):
  2592. def bounds_rec(o):
  2593. if type(o) is list:
  2594. minx = Inf
  2595. miny = Inf
  2596. maxx = -Inf
  2597. maxy = -Inf
  2598. for k in o:
  2599. try:
  2600. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2601. except Exception as e:
  2602. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2603. return
  2604. minx = min(minx, minx_)
  2605. miny = min(miny, miny_)
  2606. maxx = max(maxx, maxx_)
  2607. maxy = max(maxy, maxy_)
  2608. return minx, miny, maxx, maxy
  2609. else:
  2610. # it's a Shapely object, return it's bounds
  2611. return o.bounds
  2612. return bounds_rec(geometry)
  2613. def on_paint_tool_add_from_db_executed(self, tool):
  2614. """
  2615. Here add the tool from DB in the selected geometry object
  2616. :return:
  2617. """
  2618. tool_from_db = deepcopy(tool)
  2619. res = self.on_paint_tool_from_db_inserted(tool=tool_from_db)
  2620. for idx in range(self.app.ui.plot_tab_area.count()):
  2621. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2622. wdg = self.app.ui.plot_tab_area.widget(idx)
  2623. wdg.deleteLater()
  2624. self.app.ui.plot_tab_area.removeTab(idx)
  2625. if res == 'fail':
  2626. return
  2627. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2628. # select last tool added
  2629. toolid = res
  2630. for row in range(self.ui.tools_table.rowCount()):
  2631. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  2632. self.ui.tools_table.selectRow(row)
  2633. self.on_row_selection_change()
  2634. def on_paint_tool_from_db_inserted(self, tool):
  2635. """
  2636. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2637. :param tool: a dict with the tool data
  2638. :return: None
  2639. """
  2640. self.ui_disconnect()
  2641. self.units = self.app.defaults['units'].upper()
  2642. tooldia = float(tool['tooldia'])
  2643. # construct a list of all 'tooluid' in the self.tools
  2644. tool_uid_list = []
  2645. for tooluid_key in self.paint_tools:
  2646. tool_uid_item = int(tooluid_key)
  2647. tool_uid_list.append(tool_uid_item)
  2648. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2649. if not tool_uid_list:
  2650. max_uid = 0
  2651. else:
  2652. max_uid = max(tool_uid_list)
  2653. tooluid = max_uid + 1
  2654. tooldia = float('%.*f' % (self.decimals, tooldia))
  2655. tool_dias = []
  2656. for k, v in self.paint_tools.items():
  2657. for tool_v in v.keys():
  2658. if tool_v == 'tooldia':
  2659. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2660. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2661. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2662. self.ui_connect()
  2663. return 'fail'
  2664. self.paint_tools.update({
  2665. tooluid: {
  2666. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2667. 'offset': tool['offset'],
  2668. 'offset_value': tool['offset_value'],
  2669. 'type': tool['type'],
  2670. 'tool_type': tool['tool_type'],
  2671. 'data': deepcopy(tool['data']),
  2672. 'solid_geometry': []
  2673. }
  2674. })
  2675. self.paint_tools[tooluid]['data']['name'] = '_paint'
  2676. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2677. self.ui_connect()
  2678. self.build_ui()
  2679. # select the tool just added
  2680. for row in range(self.ui.tools_table.rowCount()):
  2681. if int(self.ui.tools_table.item(row, 3).text()) == tooluid:
  2682. self.ui.tools_table.selectRow(row)
  2683. break
  2684. return tooluid
  2685. def on_paint_tool_add_from_db_clicked(self):
  2686. """
  2687. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2688. and display the Tools Database tab in the form needed for the Tool adding
  2689. :return: None
  2690. """
  2691. # if the Tools Database is already opened focus on it
  2692. for idx in range(self.app.ui.plot_tab_area.count()):
  2693. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2694. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2695. break
  2696. self.app.on_tools_database(source='paint')
  2697. self.app.tools_db_tab.ok_to_add = True
  2698. self.app.tools_db_tab.buttons_frame.hide()
  2699. self.app.tools_db_tab.add_tool_from_db.show()
  2700. self.app.tools_db_tab.cancel_tool_from_db.show()
  2701. def reset_fields(self):
  2702. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2703. class PaintUI:
  2704. toolName = _("Paint Tool")
  2705. def __init__(self, layout, app):
  2706. self.app = app
  2707. self.decimals = self.app.decimals
  2708. self.layout = layout
  2709. # ## Title
  2710. title_label = QtWidgets.QLabel("%s" % self.toolName)
  2711. title_label.setStyleSheet("""
  2712. QLabel
  2713. {
  2714. font-size: 16px;
  2715. font-weight: bold;
  2716. }
  2717. """)
  2718. self.layout.addWidget(title_label)
  2719. self.tools_frame = QtWidgets.QFrame()
  2720. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2721. self.layout.addWidget(self.tools_frame)
  2722. self.tools_box = QtWidgets.QVBoxLayout()
  2723. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2724. self.tools_frame.setLayout(self.tools_box)
  2725. # ## Form Layout
  2726. grid0 = QtWidgets.QGridLayout()
  2727. grid0.setColumnStretch(0, 0)
  2728. grid0.setColumnStretch(1, 1)
  2729. self.tools_box.addLayout(grid0)
  2730. # ################################################
  2731. # ##### Type of object to be painted #############
  2732. # ################################################
  2733. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  2734. self.type_obj_combo_label.setToolTip(
  2735. _("Specify the type of object to be painted.\n"
  2736. "It can be of type: Gerber or Geometry.\n"
  2737. "What is selected here will dictate the kind\n"
  2738. "of objects that will populate the 'Object' combobox.")
  2739. )
  2740. self.type_obj_combo_label.setMinimumWidth(60)
  2741. self.type_obj_radio = RadioSet([{'label': "Geometry", 'value': 'geometry'},
  2742. {'label': "Gerber", 'value': 'gerber'}])
  2743. grid0.addWidget(self.type_obj_combo_label, 1, 0)
  2744. grid0.addWidget(self.type_obj_radio, 1, 1)
  2745. # ################################################
  2746. # ##### The object to be painted #################
  2747. # ################################################
  2748. self.obj_combo = FCComboBox()
  2749. self.obj_combo.setModel(self.app.collection)
  2750. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2751. self.obj_combo.is_last = True
  2752. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  2753. self.object_label.setToolTip(_("Object to be painted."))
  2754. grid0.addWidget(self.object_label, 2, 0)
  2755. grid0.addWidget(self.obj_combo, 2, 1)
  2756. separator_line = QtWidgets.QFrame()
  2757. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2758. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2759. grid0.addWidget(separator_line, 5, 0, 1, 2)
  2760. # ### Tools ## ##
  2761. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  2762. self.tools_table_label.setToolTip(
  2763. _("Tools pool from which the algorithm\n"
  2764. "will pick the ones used for painting.")
  2765. )
  2766. self.tools_table = FCTable(drag_drop=True)
  2767. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2768. grid0.addWidget(self.tools_table_label, 6, 0, 1, 2)
  2769. grid0.addWidget(self.tools_table, 7, 0, 1, 2)
  2770. self.tools_table.setColumnCount(4)
  2771. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  2772. self.tools_table.setColumnHidden(3, True)
  2773. # self.tools_table.setSortingEnabled(False)
  2774. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2775. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2776. _("This is the Tool Number.\n"
  2777. "Painting will start with the tool with the biggest diameter,\n"
  2778. "continuing until there are no more tools.\n"
  2779. "Only tools that create painting geometry will still be present\n"
  2780. "in the resulting geometry. This is because with some tools\n"
  2781. "this function will not be able to create painting geometry.")
  2782. )
  2783. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2784. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  2785. "is the cut width into the material."))
  2786. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2787. _("The Tool Type (TT) can be:\n"
  2788. "- Circular -> it is informative only. Being circular,\n"
  2789. "the cut width in material is exactly the tool diameter.\n"
  2790. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  2791. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  2792. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  2793. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  2794. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  2795. "column of this table.\n"
  2796. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  2797. "in the resulting geometry as Isolation."))
  2798. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  2799. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2800. "'No' --> means that the used order is the one in the tool table\n"
  2801. "'Forward' --> means that the tools will be ordered from small to big\n"
  2802. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2803. "WARNING: using rest machining will automatically set the order\n"
  2804. "in reverse and disable this control."))
  2805. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2806. {'label': _('Forward'), 'value': 'fwd'},
  2807. {'label': _('Reverse'), 'value': 'rev'}])
  2808. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2809. "'No' --> means that the used order is the one in the tool table\n"
  2810. "'Forward' --> means that the tools will be ordered from small to big\n"
  2811. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2812. "WARNING: using rest machining will automatically set the order\n"
  2813. "in reverse and disable this control."))
  2814. grid0.addWidget(self.order_label, 9, 0)
  2815. grid0.addWidget(self.order_radio, 9, 1)
  2816. separator_line = QtWidgets.QFrame()
  2817. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2818. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2819. grid0.addWidget(separator_line, 10, 0, 1, 2)
  2820. self.grid3 = QtWidgets.QGridLayout()
  2821. self.tools_box.addLayout(self.grid3)
  2822. self.grid3.setColumnStretch(0, 0)
  2823. self.grid3.setColumnStretch(1, 1)
  2824. # ##############################################################################
  2825. # ###################### ADD A NEW TOOL ########################################
  2826. # ##############################################################################
  2827. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  2828. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  2829. # Tool Type Radio Button
  2830. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  2831. self.tool_type_label.setToolTip(
  2832. _("Default tool type:\n"
  2833. "- 'V-shape'\n"
  2834. "- Circular")
  2835. )
  2836. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  2837. {'label': _('Circular'), 'value': 'C1'}])
  2838. self.tool_type_radio.setToolTip(
  2839. _("Default tool type:\n"
  2840. "- 'V-shape'\n"
  2841. "- Circular")
  2842. )
  2843. self.tool_type_radio.setObjectName('p_tool_type')
  2844. self.grid3.addWidget(self.tool_type_label, 2, 0)
  2845. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  2846. # Tip Dia
  2847. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  2848. self.tipdialabel.setToolTip(
  2849. _("The tip diameter for V-Shape Tool"))
  2850. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2851. self.tipdia_entry.set_precision(self.decimals)
  2852. self.tipdia_entry.set_range(0.0000, 9999.9999)
  2853. self.tipdia_entry.setSingleStep(0.1)
  2854. self.tipdia_entry.setObjectName('p_vtip_dia')
  2855. self.grid3.addWidget(self.tipdialabel, 3, 0)
  2856. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  2857. # Tip Angle
  2858. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  2859. self.tipanglelabel.setToolTip(
  2860. _("The tip angle for V-Shape Tool.\n"
  2861. "In degree."))
  2862. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2863. self.tipangle_entry.set_precision(self.decimals)
  2864. self.tipangle_entry.set_range(0.0000, 180.0000)
  2865. self.tipangle_entry.setSingleStep(5)
  2866. self.tipangle_entry.setObjectName('p_vtip_angle')
  2867. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  2868. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  2869. # Cut Z entry
  2870. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  2871. cutzlabel.setToolTip(
  2872. _("Depth of cut into material. Negative value.\n"
  2873. "In FlatCAM units.")
  2874. )
  2875. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2876. self.cutz_entry.set_precision(self.decimals)
  2877. self.cutz_entry.set_range(-99999.9999, 0.0000)
  2878. self.cutz_entry.setObjectName('p_cutz')
  2879. self.cutz_entry.setToolTip(
  2880. _("Depth of cut into material. Negative value.\n"
  2881. "In FlatCAM units.")
  2882. )
  2883. self.grid3.addWidget(cutzlabel, 5, 0)
  2884. self.grid3.addWidget(self.cutz_entry, 5, 1)
  2885. # ### Tool Diameter ####
  2886. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  2887. self.addtool_entry_lbl.setToolTip(
  2888. _("Diameter for the new tool to add in the Tool Table.\n"
  2889. "If the tool is V-shape type then this value is automatically\n"
  2890. "calculated from the other parameters.")
  2891. )
  2892. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2893. self.addtool_entry.set_precision(self.decimals)
  2894. self.addtool_entry.set_range(0.000, 9999.9999)
  2895. self.addtool_entry.setObjectName('p_tool_dia')
  2896. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  2897. self.grid3.addWidget(self.addtool_entry, 6, 1)
  2898. hlay = QtWidgets.QHBoxLayout()
  2899. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  2900. self.addtool_btn.setToolTip(
  2901. _("Add a new tool to the Tool Table\n"
  2902. "with the diameter specified above.")
  2903. )
  2904. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  2905. self.addtool_from_db_btn.setToolTip(
  2906. _("Add a new tool to the Tool Table\n"
  2907. "from the Tool Database.\n"
  2908. "Tool database administration in Menu: Options -> Tools Database")
  2909. )
  2910. hlay.addWidget(self.addtool_btn)
  2911. hlay.addWidget(self.addtool_from_db_btn)
  2912. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  2913. separator_line = QtWidgets.QFrame()
  2914. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2915. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2916. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  2917. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  2918. self.deltool_btn.setToolTip(
  2919. _("Delete a selection of tools in the Tool Table\n"
  2920. "by first selecting a row(s) in the Tool Table.")
  2921. )
  2922. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  2923. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  2924. separator_line = QtWidgets.QFrame()
  2925. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2926. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2927. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  2928. self.tool_data_label = QtWidgets.QLabel(
  2929. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2930. self.tool_data_label.setToolTip(
  2931. _(
  2932. "The data used for creating GCode.\n"
  2933. "Each tool store it's own set of such data."
  2934. )
  2935. )
  2936. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  2937. grid4 = QtWidgets.QGridLayout()
  2938. grid4.setColumnStretch(0, 0)
  2939. grid4.setColumnStretch(1, 1)
  2940. self.tools_box.addLayout(grid4)
  2941. # Overlap
  2942. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  2943. ovlabel.setToolTip(
  2944. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  2945. "Adjust the value starting with lower values\n"
  2946. "and increasing it if areas that should be painted are still \n"
  2947. "not painted.\n"
  2948. "Lower values = faster processing, faster execution on CNC.\n"
  2949. "Higher values = slow processing and slow execution on CNC\n"
  2950. "due of too many paths.")
  2951. )
  2952. self.paintoverlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  2953. self.paintoverlap_entry.set_precision(3)
  2954. self.paintoverlap_entry.setWrapping(True)
  2955. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  2956. self.paintoverlap_entry.setSingleStep(0.1)
  2957. self.paintoverlap_entry.setObjectName('p_overlap')
  2958. grid4.addWidget(ovlabel, 1, 0)
  2959. grid4.addWidget(self.paintoverlap_entry, 1, 1)
  2960. # Margin
  2961. marginlabel = QtWidgets.QLabel('%s:' % _('Offset'))
  2962. marginlabel.setToolTip(
  2963. _("Distance by which to avoid\n"
  2964. "the edges of the polygon to\n"
  2965. "be painted.")
  2966. )
  2967. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2968. self.offset_entry.set_precision(self.decimals)
  2969. self.offset_entry.set_range(-9999.9999, 9999.9999)
  2970. self.offset_entry.setObjectName('p_offset')
  2971. grid4.addWidget(marginlabel, 2, 0)
  2972. grid4.addWidget(self.offset_entry, 2, 1)
  2973. # Method
  2974. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  2975. methodlabel.setToolTip(
  2976. _("Algorithm for painting:\n"
  2977. "- Standard: Fixed step inwards.\n"
  2978. "- Seed-based: Outwards from seed.\n"
  2979. "- Line-based: Parallel lines.\n"
  2980. "- Laser-lines: Active only for Gerber objects.\n"
  2981. "Will create lines that follow the traces.\n"
  2982. "- Combo: In case of failure a new method will be picked from the above\n"
  2983. "in the order specified.")
  2984. )
  2985. # self.paintmethod_combo = RadioSet([
  2986. # {"label": _("Standard"), "value": "standard"},
  2987. # {"label": _("Seed-based"), "value": _("Seed")},
  2988. # {"label": _("Straight lines"), "value": _("Lines")},
  2989. # {"label": _("Laser lines"), "value": _("Laser_lines")},
  2990. # {"label": _("Combo"), "value": _("Combo")}
  2991. # ], orientation='vertical', stretch=False)
  2992. # for choice in self.paintmethod_combo.choices:
  2993. # if choice['value'] == _("Laser_lines"):
  2994. # choice["radio"].setEnabled(False)
  2995. self.paintmethod_combo = FCComboBox()
  2996. self.paintmethod_combo.addItems(
  2997. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  2998. )
  2999. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  3000. self.paintmethod_combo.model().item(idx).setEnabled(False)
  3001. self.paintmethod_combo.setObjectName('p_method')
  3002. grid4.addWidget(methodlabel, 7, 0)
  3003. grid4.addWidget(self.paintmethod_combo, 7, 1)
  3004. # Connect lines
  3005. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  3006. self.pathconnect_cb.setObjectName('p_connect')
  3007. self.pathconnect_cb.setToolTip(
  3008. _("Draw lines between resulting\n"
  3009. "segments to minimize tool lifts.")
  3010. )
  3011. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  3012. self.paintcontour_cb.setObjectName('p_contour')
  3013. self.paintcontour_cb.setToolTip(
  3014. _("Cut around the perimeter of the polygon\n"
  3015. "to trim rough edges.")
  3016. )
  3017. grid4.addWidget(self.pathconnect_cb, 10, 0)
  3018. grid4.addWidget(self.paintcontour_cb, 10, 1)
  3019. separator_line = QtWidgets.QFrame()
  3020. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3021. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3022. grid4.addWidget(separator_line, 11, 0, 1, 2)
  3023. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  3024. self.apply_param_to_all.setToolTip(
  3025. _("The parameters in the current form will be applied\n"
  3026. "on all the tools from the Tool Table.")
  3027. )
  3028. grid4.addWidget(self.apply_param_to_all, 12, 0, 1, 2)
  3029. separator_line = QtWidgets.QFrame()
  3030. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3031. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3032. grid4.addWidget(separator_line, 13, 0, 1, 2)
  3033. # General Parameters
  3034. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  3035. self.gen_param_label.setToolTip(
  3036. _("Parameters that are common for all tools.")
  3037. )
  3038. grid4.addWidget(self.gen_param_label, 15, 0, 1, 2)
  3039. self.rest_cb = FCCheckBox('%s' % _("Rest"))
  3040. self.rest_cb.setObjectName('p_rest_machining')
  3041. self.rest_cb.setToolTip(
  3042. _("If checked, use 'rest machining'.\n"
  3043. "Basically it will clear copper outside PCB features,\n"
  3044. "using the biggest tool and continue with the next tools,\n"
  3045. "from bigger to smaller, to clear areas of copper that\n"
  3046. "could not be cleared by previous tool, until there is\n"
  3047. "no more copper to clear or there are no more tools.\n\n"
  3048. "If not checked, use the standard algorithm.")
  3049. )
  3050. grid4.addWidget(self.rest_cb, 16, 0, 1, 2)
  3051. # Polygon selection
  3052. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  3053. selectlabel.setToolTip(
  3054. _("Selection of area to be processed.\n"
  3055. "- 'Polygon Selection' - left mouse click to add/remove polygons to be processed.\n"
  3056. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  3057. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  3058. "- 'All Polygons' - the process will start after click.\n"
  3059. "- 'Reference Object' - will process the area specified by another object.")
  3060. )
  3061. # grid3 = QtWidgets.QGridLayout()
  3062. # self.selectmethod_combo = RadioSet([
  3063. # {"label": _("Polygon Selection"), "value": "single"},
  3064. # {"label": _("Area Selection"), "value": "area"},
  3065. # {"label": _("All Polygons"), "value": "all"},
  3066. # {"label": _("Reference Object"), "value": "ref"}
  3067. # ], orientation='vertical', stretch=False)
  3068. # self.selectmethod_combo.setObjectName('p_selection')
  3069. # self.selectmethod_combo.setToolTip(
  3070. # _("How to select Polygons to be painted.\n"
  3071. # "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  3072. # "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  3073. # "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  3074. # "- 'All Polygons' - the Paint will start after click.\n"
  3075. # "- 'Reference Object' - will do non copper clearing within the area\n"
  3076. # "specified by another object.")
  3077. # )
  3078. self.selectmethod_combo = FCComboBox()
  3079. self.selectmethod_combo.addItems(
  3080. [_("Polygon Selection"), _("Area Selection"), _("All"), _("Reference Object")]
  3081. )
  3082. self.selectmethod_combo.setObjectName('p_selection')
  3083. grid4.addWidget(selectlabel, 18, 0)
  3084. grid4.addWidget(self.selectmethod_combo, 18, 1)
  3085. form1 = QtWidgets.QFormLayout()
  3086. grid4.addLayout(form1, 20, 0, 1, 2)
  3087. self.reference_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  3088. self.reference_type_label.setToolTip(
  3089. _("The type of FlatCAM object to be used as paint reference.\n"
  3090. "It can be Gerber, Excellon or Geometry.")
  3091. )
  3092. self.reference_type_combo = FCComboBox()
  3093. self.reference_type_combo.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  3094. form1.addRow(self.reference_type_label, self.reference_type_combo)
  3095. self.reference_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  3096. self.reference_combo_label.setToolTip(
  3097. _("The FlatCAM object to be used as non copper clearing reference.")
  3098. )
  3099. self.reference_combo = FCComboBox()
  3100. self.reference_combo.setModel(self.app.collection)
  3101. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3102. self.reference_combo.is_last = True
  3103. form1.addRow(self.reference_combo_label, self.reference_combo)
  3104. self.reference_combo.hide()
  3105. self.reference_combo_label.hide()
  3106. self.reference_type_combo.hide()
  3107. self.reference_type_label.hide()
  3108. # Area Selection shape
  3109. self.area_shape_label = QtWidgets.QLabel('%s:' % _("Shape"))
  3110. self.area_shape_label.setToolTip(
  3111. _("The kind of selection shape used for area selection.")
  3112. )
  3113. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  3114. {'label': _("Polygon"), 'value': 'polygon'}])
  3115. grid4.addWidget(self.area_shape_label, 21, 0)
  3116. grid4.addWidget(self.area_shape_radio, 21, 1)
  3117. self.area_shape_label.hide()
  3118. self.area_shape_radio.hide()
  3119. # GO Button
  3120. self.generate_paint_button = QtWidgets.QPushButton(_('Generate Geometry'))
  3121. self.generate_paint_button.setToolTip(
  3122. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  3123. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  3124. "- 'All Polygons' - the Paint will start after click.\n"
  3125. "- 'Reference Object' - will do non copper clearing within the area\n"
  3126. "specified by another object.")
  3127. )
  3128. self.generate_paint_button.setStyleSheet("""
  3129. QPushButton
  3130. {
  3131. font-weight: bold;
  3132. }
  3133. """)
  3134. self.tools_box.addWidget(self.generate_paint_button)
  3135. self.tools_box.addStretch()
  3136. # ## Reset Tool
  3137. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  3138. self.reset_button.setToolTip(
  3139. _("Will reset the tool parameters.")
  3140. )
  3141. self.reset_button.setStyleSheet("""
  3142. QPushButton
  3143. {
  3144. font-weight: bold;
  3145. }
  3146. """)
  3147. self.tools_box.addWidget(self.reset_button)
  3148. # #################################### FINSIHED GUI ###########################
  3149. # #############################################################################
  3150. def confirmation_message(self, accepted, minval, maxval):
  3151. if accepted is False:
  3152. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  3153. self.decimals,
  3154. minval,
  3155. self.decimals,
  3156. maxval), False)
  3157. else:
  3158. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  3159. def confirmation_message_int(self, accepted, minval, maxval):
  3160. if accepted is False:
  3161. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  3162. (_("Edited value is out of range"), minval, maxval), False)
  3163. else:
  3164. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)