ToolNCC.py 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Modified by: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCCheckBox, FCDoubleSpinner, RadioSet, FCTable, FCInputDialog, FCButton,\
  10. FCComboBox, OptionalInputSection, FCLabel
  11. from appParsers.ParseGerber import Gerber
  12. from camlib import grace
  13. from copy import deepcopy
  14. import numpy as np
  15. from shapely.geometry import base
  16. from shapely.ops import unary_union, nearest_points
  17. from shapely.geometry import MultiPolygon, Polygon, MultiLineString, LineString, LinearRing
  18. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  19. import logging
  20. import traceback
  21. import sys
  22. import gettext
  23. import simplejson as json
  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 NonCopperClear(AppTool, Gerber):
  31. optimal_found_sig = QtCore.pyqtSignal(float)
  32. def __init__(self, app):
  33. self.app = app
  34. self.decimals = self.app.decimals
  35. AppTool.__init__(self, app)
  36. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  37. # #############################################################################
  38. # ######################### Tool GUI ##########################################
  39. # #############################################################################
  40. self.ui = NccUI(layout=self.layout, app=self.app)
  41. self.toolName = self.ui.toolName
  42. # #############################################################################
  43. # ###################### Setup CONTEXT MENU ###################################
  44. # #############################################################################
  45. self.ui.tools_table.setupContextMenu()
  46. self.ui.tools_table.addContextMenu(
  47. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  48. )
  49. self.ui.tools_table.addContextMenu(
  50. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  51. )
  52. self.ui.tools_table.addContextMenu(
  53. _("Delete"), lambda:
  54. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  55. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  56. )
  57. # #############################################################################
  58. # ########################## VARIABLES ########################################
  59. # #############################################################################
  60. self.units = ''
  61. self.ncc_tools = {}
  62. self.tooluid = 0
  63. # store here the default data for Geometry Data
  64. self.default_data = {}
  65. self.obj_name = ""
  66. self.ncc_obj = None
  67. self.sel_rect = []
  68. self.bound_obj_name = ""
  69. self.bound_obj = None
  70. self.ncc_dia_list = []
  71. self.iso_dia_list = []
  72. self.has_offset = None
  73. self.o_name = None
  74. self.overlap = None
  75. self.connect = None
  76. self.contour = None
  77. self.rest = None
  78. # store here the tool diameter that is guaranteed to isolate the object
  79. self.safe_tooldia = None
  80. self.first_click = False
  81. self.cursor_pos = None
  82. self.mouse_is_dragging = False
  83. # store here the points for the "Polygon" area selection shape
  84. self.points = []
  85. # set this as True when in middle of drawing a "Polygon" area selection shape
  86. # it is made False by first click to signify that the shape is complete
  87. self.poly_drawn = False
  88. self.mm = None
  89. self.mr = None
  90. self.kp = None
  91. # disconnect flags
  92. self.area_sel_disconnect_flag = False
  93. # store here solid_geometry when there are tool with isolation job
  94. self.solid_geometry = []
  95. self.select_method = None
  96. self.tool_type_item_options = []
  97. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  98. self.tooldia = None
  99. self.form_fields = {
  100. "tools_ncc_operation": self.ui.op_radio,
  101. "tools_ncc_overlap": self.ui.ncc_overlap_entry,
  102. "tools_ncc_margin": self.ui.ncc_margin_entry,
  103. "tools_ncc_method": self.ui.ncc_method_combo,
  104. "tools_ncc_connect": self.ui.ncc_connect_cb,
  105. "tools_ncc_contour": self.ui.ncc_contour_cb,
  106. "tools_ncc_offset_choice": self.ui.ncc_choice_offset_cb,
  107. "tools_ncc_offset_value": self.ui.ncc_offset_spinner,
  108. "tools_ncc_milling_type": self.ui.milling_type_radio,
  109. "tools_ncc_check_valid": self.ui.valid_cb
  110. }
  111. self.name2option = {
  112. "n_operation": "tools_ncc_operation",
  113. "n_overlap": "tools_ncc_overlap",
  114. "n_margin": "tools_ncc_margin",
  115. "n_method": "tools_ncc_method",
  116. "n_connect": "tools_ncc_connect",
  117. "n_contour": "tools_ncc_contour",
  118. "n_offset": "tools_ncc_offset_choice",
  119. "n_offset_value": "tools_ncc_offset_value",
  120. "n_milling_type": "tools_ncc_milling_type",
  121. "n_check": "tools_ncc_check_valid",
  122. }
  123. self.old_tool_dia = None
  124. self.connect_signals_at_init()
  125. def install(self, icon=None, separator=None, **kwargs):
  126. AppTool.install(self, icon, separator, shortcut='Alt+N', **kwargs)
  127. def run(self, toggle=True):
  128. self.app.defaults.report_usage("ToolNonCopperClear()")
  129. log.debug("ToolNCC().run() was launched ...")
  130. if toggle:
  131. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  132. if self.app.ui.splitter.sizes()[0] == 0:
  133. self.app.ui.splitter.setSizes([1, 1])
  134. else:
  135. try:
  136. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  137. # if tab is populated with the tool but it does not have the focus, focus on it
  138. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  139. # focus on Tool Tab
  140. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  141. else:
  142. self.app.ui.splitter.setSizes([0, 1])
  143. except AttributeError:
  144. pass
  145. else:
  146. if self.app.ui.splitter.sizes()[0] == 0:
  147. self.app.ui.splitter.setSizes([1, 1])
  148. AppTool.run(self)
  149. self.set_tool_ui()
  150. # reset those objects on a new run
  151. self.ncc_obj = None
  152. self.bound_obj = None
  153. self.obj_name = ''
  154. self.bound_obj_name = ''
  155. self.build_ui()
  156. # all the tools are selected by default
  157. # self.ui.tools_table.selectColumn(0)
  158. self.ui.tools_table.selectAll()
  159. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  160. def connect_signals_at_init(self):
  161. # #############################################################################
  162. # ############################ SIGNALS ########################################
  163. # #############################################################################
  164. self.ui.find_optimal_button.clicked.connect(self.on_find_optimal_tooldia)
  165. # Custom Signal
  166. self.optimal_found_sig.connect(lambda val: self.ui.new_tooldia_entry.set_value(float(val)))
  167. self.ui.deltool_btn.clicked.connect(self.on_tool_delete)
  168. self.ui.generate_ncc_button.clicked.connect(self.on_ncc_click)
  169. self.ui.op_radio.activated_custom.connect(self.on_operation_change)
  170. self.ui.reference_combo_type.currentIndexChanged.connect(self.on_reference_combo_changed)
  171. self.ui.select_combo.currentIndexChanged.connect(self.ui.on_toggle_reference)
  172. self.ui.ncc_rest_cb.stateChanged.connect(self.ui.on_rest_machining_check)
  173. self.ui.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  174. self.ui.type_obj_radio.activated_custom.connect(self.on_type_obj_index_changed)
  175. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  176. # add a new tool Signals
  177. self.ui.add_newtool_button.clicked.connect(lambda: self.on_tool_add())
  178. self.ui.addtool_from_db_btn.clicked.connect(self.on_ncc_tool_add_from_db_clicked)
  179. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  180. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  181. self.app.cleanup.connect(self.set_tool_ui)
  182. def on_type_obj_index_changed(self, val):
  183. obj_type = 0 if val == 'gerber' else 2
  184. self.ui.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  185. self.ui.object_combo.setCurrentIndex(0)
  186. self.ui.object_combo.obj_type = {
  187. "gerber": "Gerber", "geometry": "Geometry"
  188. }[self.ui.type_obj_radio.get_value()]
  189. def on_operation_change(self, val):
  190. self.ui.parameters_ui(val=val)
  191. current_row = self.ui.tools_table.currentRow()
  192. try:
  193. current_uid = int(self.ui.tools_table.item(current_row, 3).text())
  194. self.ncc_tools[current_uid]['data']['tools_ncc_operation'] = val
  195. # TODO got a crash here, a KeyError exception; need to see it again and find out the why
  196. except AttributeError:
  197. return
  198. def on_toggle_all_rows(self):
  199. """
  200. will toggle the selection of all rows in Tools table
  201. :return:
  202. """
  203. sel_model = self.ui.tools_table.selectionModel()
  204. sel_indexes = sel_model.selectedIndexes()
  205. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  206. sel_rows = set()
  207. for idx in sel_indexes:
  208. sel_rows.add(idx.row())
  209. if len(sel_rows) == self.ui.tools_table.rowCount():
  210. self.ui.tools_table.clearSelection()
  211. self.ui.tool_data_label.setText(
  212. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  213. )
  214. else:
  215. self.ui.tools_table.selectAll()
  216. self.ui.tool_data_label.setText(
  217. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  218. )
  219. def on_row_selection_change(self):
  220. sel_model = self.ui.tools_table.selectionModel()
  221. sel_indexes = sel_model.selectedIndexes()
  222. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  223. sel_rows = set()
  224. for idx in sel_indexes:
  225. sel_rows.add(idx.row())
  226. # update UI only if only one row is selected otherwise having multiple rows selected will deform information
  227. # for the rows other that the current one (first selected)
  228. if len(sel_rows) == 1:
  229. self.update_ui()
  230. def update_ui(self):
  231. self.blockSignals(True)
  232. sel_rows = set()
  233. table_items = self.ui.tools_table.selectedItems()
  234. if table_items:
  235. for it in table_items:
  236. sel_rows.add(it.row())
  237. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  238. if not sel_rows or len(sel_rows) == 0:
  239. self.ui.generate_ncc_button.setDisabled(True)
  240. self.ui.tool_data_label.setText(
  241. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  242. )
  243. self.blockSignals(False)
  244. return
  245. else:
  246. self.ui.generate_ncc_button.setDisabled(False)
  247. for current_row in sel_rows:
  248. # populate the form with the data from the tool associated with the row parameter
  249. try:
  250. item = self.ui.tools_table.item(current_row, 3)
  251. if item is not None:
  252. tooluid = int(item.text())
  253. else:
  254. return
  255. except Exception as e:
  256. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  257. return
  258. # update the QLabel that shows for which Tool we have the parameters in the UI form
  259. if len(sel_rows) == 1:
  260. cr = current_row + 1
  261. self.ui.tool_data_label.setText(
  262. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), cr)
  263. )
  264. try:
  265. # set the form with data from the newly selected tool
  266. for tooluid_key, tooluid_value in list(self.ncc_tools.items()):
  267. if int(tooluid_key) == tooluid:
  268. for key, value in tooluid_value.items():
  269. if key == 'data':
  270. self.storage_to_form(tooluid_value['data'])
  271. except Exception as e:
  272. log.debug("NonCopperClear ---> update_ui() " + str(e))
  273. else:
  274. self.ui.tool_data_label.setText(
  275. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  276. )
  277. self.blockSignals(False)
  278. def storage_to_form(self, dict_storage):
  279. for form_key in self.form_fields:
  280. for storage_key in dict_storage:
  281. if form_key == storage_key:
  282. try:
  283. self.form_fields[form_key].set_value(dict_storage[form_key])
  284. except Exception as e:
  285. log.debug("NonCopperClear.storage_to_form() --> %s" % str(e))
  286. pass
  287. def form_to_storage(self):
  288. if self.ui.tools_table.rowCount() == 0:
  289. # there is no tool in tool table so we can't save the GUI elements values to storage
  290. return
  291. self.blockSignals(True)
  292. widget_changed = self.sender()
  293. wdg_objname = widget_changed.objectName()
  294. option_changed = self.name2option[wdg_objname]
  295. # row = self.ui.tools_table.currentRow()
  296. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  297. for row in rows:
  298. if row < 0:
  299. row = 0
  300. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  301. for tooluid_key, tooluid_val in self.ncc_tools.items():
  302. if int(tooluid_key) == tooluid_item:
  303. new_option_value = self.form_fields[option_changed].get_value()
  304. if option_changed in tooluid_val:
  305. tooluid_val[option_changed] = new_option_value
  306. if option_changed in tooluid_val['data']:
  307. tooluid_val['data'][option_changed] = new_option_value
  308. self.blockSignals(False)
  309. def on_apply_param_to_all_clicked(self):
  310. if self.ui.tools_table.rowCount() == 0:
  311. # there is no tool in tool table so we can't save the GUI elements values to storage
  312. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  313. return
  314. self.blockSignals(True)
  315. row = self.ui.tools_table.currentRow()
  316. if row < 0:
  317. row = 0
  318. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  319. temp_tool_data = {}
  320. for tooluid_key, tooluid_val in self.ncc_tools.items():
  321. if int(tooluid_key) == tooluid_item:
  322. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  323. # the current row in the tool table
  324. temp_tool_data = tooluid_val['data']
  325. break
  326. for tooluid_key, tooluid_val in self.ncc_tools.items():
  327. tooluid_val['data'] = deepcopy(temp_tool_data)
  328. # store all the data associated with the row parameter to the self.tools storage
  329. # tooldia_item = float(self.ui.tools_table.item(row, 1).text())
  330. # type_item = self.ui.tools_table.cellWidget(row, 2).currentText()
  331. # operation_type_item = self.ui.tools_table.cellWidget(row, 4).currentText()
  332. #
  333. # nccoffset_item = self.ncc_choice_offset_cb.get_value()
  334. # nccoffset_value_item = float(self.ncc_offset_spinner.get_value())
  335. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  336. # temp_tools = {}
  337. # temp_dia = {}
  338. # temp_data = {}
  339. #
  340. # for tooluid_key, tooluid_value in self.ncc_tools.items():
  341. # for key, value in tooluid_value.items():
  342. # if key == 'data':
  343. # # update the 'data' section
  344. # for data_key in tooluid_value[key].keys():
  345. # for form_key, form_value in self.form_fields.items():
  346. # if form_key == data_key:
  347. # temp_data[data_key] = form_value.get_value()
  348. # # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  349. # # updated from self.app.defaults
  350. # if data_key not in self.form_fields:
  351. # temp_data[data_key] = value[data_key]
  352. # temp_dia[key] = deepcopy(temp_data)
  353. # temp_data.clear()
  354. #
  355. # elif key == 'solid_geometry':
  356. # temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  357. # else:
  358. # temp_dia[key] = deepcopy(value)
  359. #
  360. # temp_tools[tooluid_key] = deepcopy(temp_dia)
  361. #
  362. # self.ncc_tools.clear()
  363. # self.ncc_tools = deepcopy(temp_tools)
  364. # temp_tools.clear()
  365. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  366. self.blockSignals(False)
  367. def on_add_tool_by_key(self):
  368. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  369. text='%s:' % _('Enter a Tool Diameter'),
  370. min=0.0001, max=9999.9999, decimals=self.decimals)
  371. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  372. val, ok = tool_add_popup.get_value()
  373. if ok:
  374. if float(val) == 0:
  375. self.app.inform.emit('[WARNING_NOTCL] %s' %
  376. _("Please enter a tool diameter with non-zero value, in Float format."))
  377. return
  378. self.on_tool_add(custom_dia=float(val))
  379. else:
  380. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  381. def set_tool_ui(self):
  382. self.units = self.app.defaults['units'].upper()
  383. self.old_tool_dia = self.app.defaults["tools_ncc_newdia"]
  384. # reset the value to prepare for another isolation
  385. self.safe_tooldia = None
  386. self.ui.tools_frame.show()
  387. # use the current selected object and make it visible in the NCC object combobox
  388. sel_list = self.app.collection.get_selected()
  389. if len(sel_list) == 1:
  390. active = self.app.collection.get_active()
  391. kind = active.kind
  392. if kind == 'gerber':
  393. self.ui.type_obj_radio.set_value('gerber')
  394. else:
  395. self.ui.type_obj_radio.set_value('geometry')
  396. # run those once so the obj_type attribute is updated for the FCComboboxes
  397. # so the last loaded object is displayed
  398. self.on_type_obj_index_changed(val=kind)
  399. self.on_reference_combo_changed()
  400. self.ui.object_combo.set_value(active.options['name'])
  401. else:
  402. kind = 'gerber'
  403. self.ui.type_obj_radio.set_value('gerber')
  404. # run those once so the obj_type attribute is updated for the FCComboboxes
  405. # so the last loaded object is displayed
  406. self.on_type_obj_index_changed(val=kind)
  407. self.on_reference_combo_changed()
  408. self.ui.op_radio.set_value(self.app.defaults["tools_ncc_operation"])
  409. self.ui.ncc_order_radio.set_value(self.app.defaults["tools_ncc_order"])
  410. self.ui.ncc_overlap_entry.set_value(self.app.defaults["tools_ncc_overlap"])
  411. self.ui.ncc_margin_entry.set_value(self.app.defaults["tools_ncc_margin"])
  412. self.ui.ncc_method_combo.set_value(self.app.defaults["tools_ncc_method"])
  413. self.ui.ncc_connect_cb.set_value(self.app.defaults["tools_ncc_connect"])
  414. self.ui.ncc_contour_cb.set_value(self.app.defaults["tools_ncc_contour"])
  415. self.ui.ncc_choice_offset_cb.set_value(self.app.defaults["tools_ncc_offset_choice"])
  416. self.ui.ncc_offset_spinner.set_value(self.app.defaults["tools_ncc_offset_value"])
  417. self.ui.ncc_rest_cb.set_value(self.app.defaults["tools_ncc_rest"])
  418. self.ui.on_rest_machining_check(state=self.app.defaults["tools_ncc_rest"])
  419. self.ui.rest_ncc_margin_entry.set_value(self.app.defaults["tools_ncc_margin"])
  420. self.ui.rest_ncc_connect_cb.set_value(self.app.defaults["tools_ncc_connect"])
  421. self.ui.rest_ncc_contour_cb.set_value(self.app.defaults["tools_ncc_contour"])
  422. self.ui.rest_ncc_choice_offset_cb.set_value(self.app.defaults["tools_ncc_offset_choice"])
  423. self.ui.rest_ncc_offset_spinner.set_value(self.app.defaults["tools_ncc_offset_value"])
  424. self.ui.select_combo.set_value(self.app.defaults["tools_ncc_ref"])
  425. self.ui.area_shape_radio.set_value(self.app.defaults["tools_ncc_area_shape"])
  426. self.ui.valid_cb.set_value(self.app.defaults["tools_ncc_check_valid"])
  427. self.ui.milling_type_radio.set_value(self.app.defaults["tools_ncc_milling_type"])
  428. self.ui.new_tooldia_entry.set_value(self.app.defaults["tools_ncc_newdia"])
  429. # init the working variables
  430. self.default_data.clear()
  431. self.default_data = {
  432. "name": '_ncc',
  433. "plot": self.app.defaults["geometry_plot"],
  434. "cutz": float(self.app.defaults["geometry_cutz"]),
  435. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  436. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  437. "travelz": self.app.defaults["geometry_travelz"],
  438. "feedrate": self.app.defaults["geometry_feedrate"],
  439. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  440. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  441. "dwell": self.app.defaults["geometry_dwell"],
  442. "dwelltime": self.app.defaults["geometry_dwelltime"],
  443. "multidepth": self.app.defaults["geometry_multidepth"],
  444. "ppname_g": self.app.defaults["geometry_ppname_g"],
  445. "depthperpass": self.app.defaults["geometry_depthperpass"],
  446. "extracut": self.app.defaults["geometry_extracut"],
  447. "extracut_length": self.app.defaults["geometry_extracut_length"],
  448. "toolchange": self.app.defaults["geometry_toolchange"],
  449. "toolchangez": self.app.defaults["geometry_toolchangez"],
  450. "endz": self.app.defaults["geometry_endz"],
  451. "endxy": self.app.defaults["geometry_endxy"],
  452. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  453. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  454. "startz": self.app.defaults["geometry_startz"],
  455. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  456. "area_shape": self.app.defaults["geometry_area_shape"],
  457. "area_strategy": self.app.defaults["geometry_area_strategy"],
  458. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  459. "optimization_type": self.app.defaults["geometry_optimization_type"],
  460. "tools_ncc_operation": self.app.defaults["tools_ncc_operation"],
  461. "tools_ncc_margin": self.app.defaults["tools_ncc_margin"],
  462. "tools_ncc_method": self.app.defaults["tools_ncc_method"],
  463. "tools_ncc_connect": self.app.defaults["tools_ncc_connect"],
  464. "tools_ncc_contour": self.app.defaults["tools_ncc_contour"],
  465. "tools_ncc_overlap": self.app.defaults["tools_ncc_overlap"],
  466. "tools_ncc_rest": self.app.defaults["tools_ncc_rest"],
  467. "tools_ncc_ref": self.app.defaults["tools_ncc_ref"],
  468. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  469. "tools_ncc_offset_value": self.app.defaults["tools_ncc_offset_value"],
  470. "tools_ncc_milling_type": self.app.defaults["tools_ncc_milling_type"],
  471. "tools_ncc_check_valid": self.app.defaults["tools_ncc_check_valid"],
  472. }
  473. try:
  474. dias = [float(self.app.defaults["tools_ncc_tools"])]
  475. except (ValueError, TypeError):
  476. try:
  477. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncc_tools"].split(",") if dia != '']
  478. except AttributeError:
  479. dias = self.app.defaults["tools_ncc_tools"]
  480. except Exception:
  481. dias = []
  482. self.tooluid = 0
  483. self.ncc_tools.clear()
  484. for tool_dia in dias:
  485. self.on_tool_add(custom_dia=tool_dia)
  486. self.obj_name = ""
  487. self.ncc_obj = None
  488. self.bound_obj_name = ""
  489. self.bound_obj = None
  490. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  491. self.units = self.app.defaults['units'].upper()
  492. self.first_click = False
  493. self.cursor_pos = None
  494. self.mouse_is_dragging = False
  495. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  496. if prog_plot:
  497. self.temp_shapes.clear(update=True)
  498. self.sel_rect = []
  499. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  500. def rebuild_ui(self):
  501. # read the table tools uid
  502. current_uid_list = []
  503. for row in range(self.ui.tools_table.rowCount()):
  504. uid = int(self.ui.tools_table.item(row,3).text())
  505. current_uid_list.append(uid)
  506. new_tools = {}
  507. new_uid = 1
  508. for current_uid in current_uid_list:
  509. new_tools[new_uid] = deepcopy(self.ncc_tools[current_uid])
  510. new_uid += 1
  511. self.ncc_tools = new_tools
  512. # the tools table changed therefore we need to rebuild it
  513. QtCore.QTimer.singleShot(20, self.build_ui)
  514. def build_ui(self):
  515. self.ui_disconnect()
  516. # updated units
  517. self.units = self.app.defaults['units'].upper()
  518. sorted_tools = []
  519. for k, v in self.ncc_tools.items():
  520. if self.units == "IN":
  521. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  522. else:
  523. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  524. order = self.ui.ncc_order_radio.get_value()
  525. if order == 'fwd':
  526. sorted_tools.sort(reverse=False)
  527. elif order == 'rev':
  528. sorted_tools.sort(reverse=True)
  529. else:
  530. pass
  531. n = len(sorted_tools)
  532. self.ui.tools_table.setRowCount(n)
  533. tool_id = 0
  534. for tool_sorted in sorted_tools:
  535. for tooluid_key, tooluid_value in self.ncc_tools.items():
  536. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  537. tool_id += 1
  538. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  539. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  540. row_no = tool_id - 1
  541. self.ui.tools_table.setItem(row_no, 0, id_) # Tool name/id
  542. # Make sure that the drill diameter when in MM is with no more than self.decimals decimals
  543. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  544. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  545. self.ui.tools_table.setItem(row_no, 1, dia) # Diameter
  546. tool_type_item = FCComboBox()
  547. tool_type_item.addItems(self.tool_type_item_options)
  548. idx = tool_type_item.findText(tooluid_value['tool_type'])
  549. tool_type_item.setCurrentIndex(idx)
  550. self.ui.tools_table.setCellWidget(row_no, 2, tool_type_item)
  551. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  552. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  553. self.ui.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  554. # make the diameter column editable
  555. for row in range(tool_id):
  556. self.ui.tools_table.item(row, 1).setFlags(
  557. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  558. self.ui.tools_table.resizeColumnsToContents()
  559. self.ui.tools_table.resizeRowsToContents()
  560. vertical_header = self.ui.tools_table.verticalHeader()
  561. vertical_header.hide()
  562. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  563. horizontal_header = self.ui.tools_table.horizontalHeader()
  564. horizontal_header.setMinimumSectionSize(10)
  565. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  566. horizontal_header.resizeSection(0, 20)
  567. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  568. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  569. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  570. self.ui_connect()
  571. # set the text on tool_data_label after loading the object
  572. sel_rows = set()
  573. sel_items = self.ui.tools_table.selectedItems()
  574. for it in sel_items:
  575. sel_rows.add(it.row())
  576. if len(sel_rows) > 1:
  577. self.ui.tool_data_label.setText(
  578. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  579. )
  580. def ui_connect(self):
  581. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  582. # rows selected
  583. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  584. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  585. for row in range(self.ui.tools_table.rowCount()):
  586. try:
  587. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  588. except AttributeError:
  589. pass
  590. for opt in self.form_fields:
  591. current_widget = self.form_fields[opt]
  592. if isinstance(current_widget, FCCheckBox):
  593. current_widget.stateChanged.connect(self.form_to_storage)
  594. if isinstance(current_widget, RadioSet):
  595. current_widget.activated_custom.connect(self.form_to_storage)
  596. elif isinstance(current_widget, FCDoubleSpinner):
  597. current_widget.returnPressed.connect(self.form_to_storage)
  598. elif isinstance(current_widget, FCComboBox):
  599. current_widget.currentIndexChanged.connect(self.form_to_storage)
  600. self.ui.ncc_rest_cb.stateChanged.connect(self.ui.on_rest_machining_check)
  601. self.ui.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  602. def ui_disconnect(self):
  603. try:
  604. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  605. self.ui.tools_table.itemChanged.disconnect()
  606. except (TypeError, AttributeError):
  607. pass
  608. for row in range(self.ui.tools_table.rowCount()):
  609. try:
  610. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  611. except (TypeError, AttributeError):
  612. pass
  613. for opt in self.form_fields:
  614. current_widget = self.form_fields[opt]
  615. if isinstance(current_widget, FCCheckBox):
  616. try:
  617. current_widget.stateChanged.disconnect(self.form_to_storage)
  618. except (TypeError, ValueError):
  619. pass
  620. if isinstance(current_widget, RadioSet):
  621. try:
  622. current_widget.activated_custom.disconnect(self.form_to_storage)
  623. except (TypeError, ValueError):
  624. pass
  625. elif isinstance(current_widget, FCDoubleSpinner):
  626. try:
  627. current_widget.returnPressed.disconnect(self.form_to_storage)
  628. except (TypeError, ValueError):
  629. pass
  630. elif isinstance(current_widget, FCComboBox):
  631. try:
  632. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  633. except (TypeError, ValueError):
  634. pass
  635. try:
  636. self.ui.ncc_rest_cb.stateChanged.disconnect(self.ui.on_rest_machining_check)
  637. except (TypeError, ValueError):
  638. pass
  639. try:
  640. self.ui.ncc_order_radio.activated_custom[str].disconnect(self.on_order_changed)
  641. except (TypeError, ValueError):
  642. pass
  643. # rows selected
  644. try:
  645. self.ui.tools_table.clicked.disconnect()
  646. except (TypeError, AttributeError):
  647. pass
  648. try:
  649. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  650. except (TypeError, AttributeError):
  651. pass
  652. def on_reference_combo_changed(self):
  653. obj_type = self.ui.reference_combo_type.currentIndex()
  654. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  655. self.ui.reference_combo.setCurrentIndex(0)
  656. self.ui.reference_combo.obj_type = {
  657. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  658. }[self.ui.reference_combo_type.get_value()]
  659. def on_order_changed(self, order):
  660. if order != 'no':
  661. self.build_ui()
  662. def on_tooltable_cellwidget_change(self):
  663. cw = self.sender()
  664. assert isinstance(cw, QtWidgets.QComboBox),\
  665. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  666. cw_index = self.ui.tools_table.indexAt(cw.pos())
  667. cw_row = cw_index.row()
  668. cw_col = cw_index.column()
  669. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  670. # if the sender is in the column with index 2 then we update the tool_type key
  671. if cw_col == 2:
  672. tt = cw.currentText()
  673. typ = 'Iso' if tt == 'V' else "Rough"
  674. self.ncc_tools[current_uid].update({
  675. 'type': typ,
  676. 'tool_type': tt,
  677. })
  678. def on_find_optimal_tooldia(self):
  679. self.find_safe_tooldia_worker(is_displayed=True)
  680. def find_safe_tooldia_worker(self, is_displayed):
  681. self.app.inform.emit(_("NCC Tool. Checking tools for validity."))
  682. self.units = self.app.defaults['units'].upper()
  683. obj_name = self.ui.object_combo.currentText()
  684. # Get source object.
  685. try:
  686. fcobj = self.app.collection.get_by_name(obj_name)
  687. except Exception:
  688. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  689. return
  690. if fcobj is None:
  691. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  692. return
  693. proc = self.app.proc_container.new(_("Working..."))
  694. def job_thread(app_obj, is_display):
  695. try:
  696. old_disp_number = 0
  697. pol_nr = 0
  698. app_obj.proc_container.update_view_text(' %d%%' % 0)
  699. total_geo = []
  700. for ap in list(fcobj.apertures.keys()):
  701. if 'geometry' in fcobj.apertures[ap]:
  702. for geo_el in fcobj.apertures[ap]['geometry']:
  703. if self.app.abort_flag:
  704. # graceful abort requested by the user
  705. raise grace
  706. if 'solid' in geo_el and geo_el['solid'] is not None and geo_el['solid'].is_valid:
  707. total_geo.append(geo_el['solid'])
  708. total_geo = MultiPolygon(total_geo)
  709. total_geo = total_geo.buffer(0)
  710. try:
  711. __ = iter(total_geo)
  712. geo_len = len(total_geo)
  713. geo_len = (geo_len * (geo_len - 1)) / 2
  714. except TypeError:
  715. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  716. _("The Gerber object has one Polygon as geometry.\n"
  717. "There are no distances between geometry elements to be found."))
  718. return 'fail'
  719. min_dict = {}
  720. idx = 1
  721. for geo in total_geo:
  722. for s_geo in total_geo[idx:]:
  723. if self.app.abort_flag:
  724. # graceful abort requested by the user
  725. raise grace
  726. # minimize the number of distances by not taking into considerations those that are too small
  727. dist = geo.distance(s_geo)
  728. dist = float('%.*f' % (self.decimals, dist))
  729. loc_1, loc_2 = nearest_points(geo, s_geo)
  730. proc_loc = (
  731. (float('%.*f' % (self.decimals, loc_1.x)), float('%.*f' % (self.decimals, loc_1.y))),
  732. (float('%.*f' % (self.decimals, loc_2.x)), float('%.*f' % (self.decimals, loc_2.y)))
  733. )
  734. if dist in min_dict:
  735. min_dict[dist].append(proc_loc)
  736. else:
  737. min_dict[dist] = [proc_loc]
  738. pol_nr += 1
  739. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  740. if old_disp_number < disp_number <= 100:
  741. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  742. old_disp_number = disp_number
  743. idx += 1
  744. min_list = list(min_dict.keys())
  745. min_dist = min(min_list)
  746. min_dist_truncated = self.app.dec_format(float(min_dist), self.decimals)
  747. self.safe_tooldia = min_dist_truncated
  748. if is_display:
  749. self.optimal_found_sig.emit(min_dist_truncated)
  750. app_obj.inform.emit('[success] %s: %s %s' %
  751. (_("Optimal tool diameter found"), str(min_dist_truncated),
  752. self.units.lower()))
  753. else:
  754. # find the selected tool ID's
  755. sorted_tools = []
  756. table_items = self.ui.tools_table.selectedItems()
  757. sel_rows = {t.row() for t in table_items}
  758. for row in sel_rows:
  759. tid = int(self.ui.tools_table.item(row, 3).text())
  760. sorted_tools.append(tid)
  761. if not sorted_tools:
  762. msg = _("There are no tools selected in the Tool Table.")
  763. self.app.inform.emit('[ERROR_NOTCL] %s' % msg)
  764. return 'fail'
  765. # check if the tools diameters are less then the safe tool diameter
  766. suitable_tools = []
  767. for tool in sorted_tools:
  768. tool_dia = float(self.ncc_tools[tool]['tooldia'])
  769. if tool_dia <= self.safe_tooldia:
  770. suitable_tools.append(tool_dia)
  771. if not suitable_tools:
  772. msg = _("Incomplete isolation. None of the selected tools could do a complete isolation.")
  773. self.app.inform.emit('[WARNING] %s' % msg)
  774. else:
  775. msg = _("At least one of the selected tools can do a complete isolation.")
  776. self.app.inform.emit('[success] %s' % msg)
  777. # reset the value to prepare for another isolation
  778. self.safe_tooldia = None
  779. except Exception as ee:
  780. log.debug(str(ee))
  781. return
  782. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app, is_displayed]})
  783. def on_tool_add(self, custom_dia=None):
  784. self.blockSignals(True)
  785. filename = self.app.data_path + '\\tools_db.FlatDB'
  786. new_tools_dict = deepcopy(self.default_data)
  787. updated_tooldia = None
  788. # construct a list of all 'tooluid' in the self.iso_tools
  789. tool_uid_list = [int(tooluid_key) for tooluid_key in self.ncc_tools]
  790. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  791. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  792. tooluid = int(max_uid + 1)
  793. tool_dias = []
  794. for k, v in self.ncc_tools.items():
  795. for tool_v in v.keys():
  796. if tool_v == 'tooldia':
  797. tool_dias.append(self.app.dec_format(v[tool_v], self.decimals))
  798. # determine the new tool diameter
  799. if custom_dia is None:
  800. tool_dia = self.ui.new_tooldia_entry.get_value()
  801. else:
  802. tool_dia = custom_dia
  803. if tool_dia is None or tool_dia == 0:
  804. self.build_ui()
  805. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  806. "in Float format."))
  807. self.blockSignals(False)
  808. return
  809. truncated_tooldia = self.app.dec_format(tool_dia, self.decimals)
  810. # if new tool diameter already in the Tool List then abort
  811. if truncated_tooldia in tool_dias:
  812. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  813. self.blockSignals(False)
  814. return
  815. # load the database tools from the file
  816. try:
  817. with open(filename) as f:
  818. tools = f.read()
  819. except IOError:
  820. self.app.log.error("Could not load tools DB file.")
  821. self.app.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  822. self.blockSignals(False)
  823. self.on_tool_default_add(dia=tool_dia)
  824. return
  825. try:
  826. # store here the tools from Tools Database when searching in Tools Database
  827. tools_db_dict = json.loads(tools)
  828. except Exception:
  829. e = sys.exc_info()[0]
  830. self.app.log.error(str(e))
  831. self.app.inform.emit('[ERROR] %s' % _("Failed to parse Tools DB file."))
  832. self.blockSignals(False)
  833. self.on_tool_default_add(dia=tool_dia)
  834. return
  835. tool_found = 0
  836. offset = 'Path'
  837. offset_val = 0.0
  838. typ = "Rough"
  839. tool_type = 'V'
  840. # look in database tools
  841. for db_tool, db_tool_val in tools_db_dict.items():
  842. offset = db_tool_val['offset']
  843. offset_val = db_tool_val['offset_value']
  844. typ = db_tool_val['type']
  845. tool_type = db_tool_val['tool_type']
  846. db_tooldia = db_tool_val['tooldia']
  847. low_limit = float(db_tool_val['data']['tol_min'])
  848. high_limit = float(db_tool_val['data']['tol_max'])
  849. # we need only tool marked for Isolation Tool
  850. if db_tool_val['data']['tool_target'] != _('NCC'):
  851. continue
  852. # if we find a tool with the same diameter in the Tools DB just update it's data
  853. if truncated_tooldia == db_tooldia:
  854. tool_found += 1
  855. for d in db_tool_val['data']:
  856. if d.find('tools_iso') == 0:
  857. new_tools_dict[d] = db_tool_val['data'][d]
  858. elif d.find('tools_') == 0:
  859. # don't need data for other App Tools; this tests after 'tools_drill_'
  860. continue
  861. else:
  862. new_tools_dict[d] = db_tool_val['data'][d]
  863. # search for a tool that has a tolerance that the tool fits in
  864. elif high_limit >= truncated_tooldia >= low_limit:
  865. tool_found += 1
  866. updated_tooldia = db_tooldia
  867. for d in db_tool_val['data']:
  868. if d.find('tools_iso') == 0:
  869. new_tools_dict[d] = db_tool_val['data'][d]
  870. elif d.find('tools_') == 0:
  871. # don't need data for other App Tools; this tests after 'tools_drill_'
  872. continue
  873. else:
  874. new_tools_dict[d] = db_tool_val['data'][d]
  875. # test we found a suitable tool in Tools Database or if multiple ones
  876. if tool_found == 0:
  877. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Tool not in Tools Database. Adding a default tool."))
  878. self.on_tool_default_add(dia=tool_dia)
  879. self.blockSignals(False)
  880. return
  881. if tool_found > 1:
  882. self.app.inform.emit(
  883. '[WARNING_NOTCL] %s' % _("Cancelled.\n"
  884. "Multiple tools for one tool diameter found in Tools Database."))
  885. self.blockSignals(False)
  886. return
  887. # if new tool diameter found in Tools Database already in the Tool List then abort
  888. if updated_tooldia is not None and updated_tooldia in tool_dias:
  889. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  890. self.blockSignals(False)
  891. return
  892. new_tdia = deepcopy(updated_tooldia) if updated_tooldia is not None else deepcopy(truncated_tooldia)
  893. self.ncc_tools.update({
  894. tooluid: {
  895. 'tooldia': new_tdia,
  896. 'offset': deepcopy(offset),
  897. 'offset_value': deepcopy(offset_val),
  898. 'type': deepcopy(typ),
  899. 'tool_type': deepcopy(tool_type),
  900. 'data': deepcopy(new_tools_dict),
  901. 'solid_geometry': []
  902. }
  903. })
  904. self.blockSignals(False)
  905. self.build_ui()
  906. # select the tool just added
  907. for row in range(self.ui.tools_table.rowCount()):
  908. if int(self.ui.tools_table.item(row, 3).text()) == tooluid:
  909. self.ui.tools_table.selectRow(row)
  910. break
  911. # update the UI form
  912. self.update_ui()
  913. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table from Tools Database."))
  914. def on_tool_default_add(self, dia=None, muted=None):
  915. self.blockSignals(True)
  916. self.units = self.app.defaults['units'].upper()
  917. if dia:
  918. tool_dia = dia
  919. else:
  920. tool_dia = self.ui.new_tooldia_entry.get_value()
  921. if tool_dia is None or tool_dia == 0:
  922. self.build_ui()
  923. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  924. "in Float format."))
  925. self.blockSignals(False)
  926. return
  927. # construct a list of all 'tooluid' in the self.tools
  928. tool_uid_list = [int(tooluid_key) for tooluid_key in self.ncc_tools]
  929. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  930. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  931. self.tooluid = int(max_uid + 1)
  932. tool_dias = []
  933. for k, v in self.ncc_tools.items():
  934. for tool_v in v.keys():
  935. if tool_v == 'tooldia':
  936. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  937. truncated_tooldia = self.app.dec_format(tool_dia, self.decimals)
  938. if truncated_tooldia in tool_dias:
  939. if muted is None:
  940. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  941. # self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  942. self.blockSignals(False)
  943. return
  944. self.ncc_tools.update({
  945. int(self.tooluid): {
  946. 'tooldia': truncated_tooldia,
  947. 'offset': 'Path',
  948. 'offset_value': 0.0,
  949. 'type': 'Iso',
  950. 'tool_type': deepcopy(self.app.defaults["tools_ncc_tool_type"]),
  951. 'data': deepcopy(self.default_data),
  952. 'solid_geometry': []
  953. }
  954. })
  955. self.blockSignals(False)
  956. self.build_ui()
  957. # select the tool just added
  958. for row in range(self.ui.tools_table.rowCount()):
  959. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  960. self.ui.tools_table.selectRow(row)
  961. break
  962. # update the UI form
  963. self.update_ui()
  964. if muted is None:
  965. self.app.inform.emit('[success] %s' % _("Default tool added to Tool Table."))
  966. def on_tool_edit(self, item):
  967. self.blockSignals(True)
  968. edited_row = item.row()
  969. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  970. tool_dias = []
  971. try:
  972. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  973. except ValueError:
  974. # try to convert comma to decimal point. if it's still not working error message and return
  975. try:
  976. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  977. except ValueError:
  978. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  979. self.blockSignals(False)
  980. return
  981. for v in self.ncc_tools.values():
  982. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  983. # identify the tool that was edited and get it's tooluid
  984. if new_tool_dia not in tool_dias:
  985. self.ncc_tools[editeduid]['tooldia'] = deepcopy(float('%.*f' % (self.decimals, new_tool_dia)))
  986. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  987. self.blockSignals(False)
  988. self.build_ui()
  989. return
  990. # identify the old tool_dia and restore the text in tool table
  991. for k, v in self.ncc_tools.items():
  992. if k == editeduid:
  993. old_tool_dia = v['tooldia']
  994. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  995. restore_dia_item.setText(str(old_tool_dia))
  996. break
  997. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  998. self.blockSignals(False)
  999. self.build_ui()
  1000. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1001. """
  1002. Will delete a tool in the tool table
  1003. :param rows_to_delete: which rows to delete; can be a list
  1004. :param all_tools: delete all tools in the tool table
  1005. :return:
  1006. """
  1007. self.blockSignals(True)
  1008. deleted_tools_list = []
  1009. if all_tools:
  1010. self.ncc_tools.clear()
  1011. self.blockSignals(False)
  1012. self.build_ui()
  1013. return
  1014. if rows_to_delete:
  1015. try:
  1016. for row in rows_to_delete:
  1017. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  1018. deleted_tools_list.append(tooluid_del)
  1019. except TypeError:
  1020. tooluid_del = int(self.ui.tools_table.item(rows_to_delete, 3).text())
  1021. deleted_tools_list.append(tooluid_del)
  1022. for t in deleted_tools_list:
  1023. self.ncc_tools.pop(t, None)
  1024. self.blockSignals(False)
  1025. self.build_ui()
  1026. return
  1027. try:
  1028. if self.ui.tools_table.selectedItems():
  1029. for row_sel in self.ui.tools_table.selectedItems():
  1030. row = row_sel.row()
  1031. if row < 0:
  1032. continue
  1033. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  1034. deleted_tools_list.append(tooluid_del)
  1035. for t in deleted_tools_list:
  1036. self.ncc_tools.pop(t, None)
  1037. except AttributeError:
  1038. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1039. self.blockSignals(False)
  1040. return
  1041. except Exception as e:
  1042. log.debug(str(e))
  1043. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1044. self.blockSignals(False)
  1045. self.build_ui()
  1046. def on_ncc_click(self):
  1047. """
  1048. Slot for clicking signal
  1049. :return: None
  1050. """
  1051. self.app.defaults.report_usage("on_ncc_click")
  1052. self.first_click = False
  1053. self.cursor_pos = None
  1054. self.mouse_is_dragging = False
  1055. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  1056. if prog_plot:
  1057. self.temp_shapes.clear(update=True)
  1058. self.sel_rect = []
  1059. obj_type = self.ui.type_obj_radio.get_value
  1060. self.circle_steps = int(self.app.defaults["gerber_circle_steps"]) if obj_type == 'gerber' else \
  1061. int(self.app.defaults["geometry_circle_steps"])
  1062. self.obj_name = self.ui.object_combo.currentText()
  1063. # Get source object.
  1064. try:
  1065. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  1066. except Exception as e:
  1067. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1068. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1069. if self.ncc_obj is None:
  1070. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1071. return
  1072. if self.ui.valid_cb.get_value() is True:
  1073. self.find_safe_tooldia_worker(is_displayed=False)
  1074. # use the selected tools in the tool table; get diameters for isolation
  1075. self.iso_dia_list = []
  1076. # use the selected tools in the tool table; get diameters for non-copper clear
  1077. self.ncc_dia_list = []
  1078. table_items = self.ui.tools_table.selectedItems()
  1079. sel_rows = {t.row() for t in table_items}
  1080. if len(sel_rows) > 0:
  1081. for row in sel_rows:
  1082. try:
  1083. self.tooldia = float(self.ui.tools_table.item(row, 1).text())
  1084. except ValueError:
  1085. # try to convert comma to decimal point. if it's still not working error message and return
  1086. try:
  1087. self.tooldia = float(self.ui.tools_table.item(row, 1).text().replace(',', '.'))
  1088. except ValueError:
  1089. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1090. continue
  1091. # find out which tools is for isolation and which are for copper clearing
  1092. for uid_k, uid_v in self.ncc_tools.items():
  1093. if round(uid_v['tooldia'], self.decimals) == round(self.tooldia, self.decimals):
  1094. if uid_v['data']['tools_ncc_operation'] == "iso":
  1095. self.iso_dia_list.append(self.tooldia)
  1096. else:
  1097. self.ncc_dia_list.append(self.tooldia)
  1098. else:
  1099. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There are no tools selected in the Tool Table."))
  1100. return
  1101. self.o_name = '%s_ncc' % self.obj_name
  1102. self.select_method = self.ui.select_combo.get_value()
  1103. if self.select_method == _('Itself'):
  1104. self.bound_obj_name = self.ui.object_combo.currentText()
  1105. # Get source object.
  1106. try:
  1107. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1108. except Exception as e:
  1109. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1110. return "Could not retrieve object: %s with error: %s" % (self.bound_obj_name, str(e))
  1111. self.clear_copper(ncc_obj=self.ncc_obj,
  1112. ncctooldia=self.ncc_dia_list,
  1113. isotooldia=self.iso_dia_list,
  1114. outname=self.o_name,
  1115. tools_storage=self.ncc_tools)
  1116. elif self.select_method == _("Area Selection"):
  1117. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1118. if self.app.is_legacy is False:
  1119. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1120. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1121. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1122. else:
  1123. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1124. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1125. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1126. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1127. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1128. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  1129. # disconnect flags
  1130. self.area_sel_disconnect_flag = True
  1131. elif self.select_method == _("Reference Object"):
  1132. self.bound_obj_name = self.ui.reference_combo.currentText()
  1133. # Get source object.
  1134. try:
  1135. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1136. except Exception as e:
  1137. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1138. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1139. self.clear_copper(ncc_obj=self.ncc_obj,
  1140. sel_obj=self.bound_obj,
  1141. ncctooldia=self.ncc_dia_list,
  1142. isotooldia=self.iso_dia_list,
  1143. outname=self.o_name)
  1144. # To be called after clicking on the plot.
  1145. def on_mouse_release(self, event):
  1146. if self.app.is_legacy is False:
  1147. event_pos = event.pos
  1148. # event_is_dragging = event.is_dragging
  1149. right_button = 2
  1150. else:
  1151. event_pos = (event.xdata, event.ydata)
  1152. # event_is_dragging = self.app.plotcanvas.is_dragging
  1153. right_button = 3
  1154. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1155. if self.app.grid_status():
  1156. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1157. else:
  1158. curr_pos = (event_pos[0], event_pos[1])
  1159. x1, y1 = curr_pos[0], curr_pos[1]
  1160. shape_type = self.ui.area_shape_radio.get_value()
  1161. # do clear area only for left mouse clicks
  1162. if event.button == 1:
  1163. if shape_type == "square":
  1164. if self.first_click is False:
  1165. self.first_click = True
  1166. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  1167. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1168. if self.app.grid_status():
  1169. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1170. else:
  1171. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1172. self.app.delete_selection_shape()
  1173. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1174. pt1 = (x0, y0)
  1175. pt2 = (x1, y0)
  1176. pt3 = (x1, y1)
  1177. pt4 = (x0, y1)
  1178. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1179. self.sel_rect.append(new_rectangle)
  1180. # add a temporary shape on canvas
  1181. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1182. self.first_click = False
  1183. return
  1184. else:
  1185. self.points.append((x1, y1))
  1186. if len(self.points) > 1:
  1187. self.poly_drawn = True
  1188. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1189. return ""
  1190. elif event.button == right_button and self.mouse_is_dragging is False:
  1191. shape_type = self.ui.area_shape_radio.get_value()
  1192. if shape_type == "square":
  1193. self.first_click = False
  1194. else:
  1195. # if we finish to add a polygon
  1196. if self.poly_drawn is True:
  1197. try:
  1198. # try to add the point where we last clicked if it is not already in the self.points
  1199. last_pt = (x1, y1)
  1200. if last_pt != self.points[-1]:
  1201. self.points.append(last_pt)
  1202. except IndexError:
  1203. pass
  1204. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  1205. if len(self.points) > 2:
  1206. self.delete_moving_selection_shape()
  1207. pol = Polygon(self.points)
  1208. # do not add invalid polygons even if they are drawn by utility geometry
  1209. if pol.is_valid:
  1210. self.sel_rect.append(pol)
  1211. self.draw_selection_shape_polygon(points=self.points)
  1212. self.app.inform.emit(
  1213. _("Zone added. Click to start adding next zone or right click to finish."))
  1214. self.points = []
  1215. self.poly_drawn = False
  1216. return
  1217. self.delete_tool_selection_shape()
  1218. if self.app.is_legacy is False:
  1219. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1220. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1221. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1222. else:
  1223. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1224. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1225. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1226. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1227. self.app.on_mouse_click_over_plot)
  1228. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1229. self.app.on_mouse_move_over_plot)
  1230. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1231. self.app.on_mouse_click_release_over_plot)
  1232. # disconnect flags
  1233. self.area_sel_disconnect_flag = False
  1234. if len(self.sel_rect) == 0:
  1235. return
  1236. self.sel_rect = unary_union(self.sel_rect)
  1237. self.clear_copper(ncc_obj=self.ncc_obj, sel_obj=self.bound_obj, ncctooldia=self.ncc_dia_list,
  1238. isotooldia=self.iso_dia_list, outname=self.o_name)
  1239. # called on mouse move
  1240. def on_mouse_move(self, event):
  1241. shape_type = self.ui.area_shape_radio.get_value()
  1242. if self.app.is_legacy is False:
  1243. event_pos = event.pos
  1244. event_is_dragging = event.is_dragging
  1245. # right_button = 2
  1246. else:
  1247. event_pos = (event.xdata, event.ydata)
  1248. event_is_dragging = self.app.plotcanvas.is_dragging
  1249. # right_button = 3
  1250. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1251. # detect mouse dragging motion
  1252. if event_is_dragging is True:
  1253. self.mouse_is_dragging = True
  1254. else:
  1255. self.mouse_is_dragging = False
  1256. # update the cursor position
  1257. if self.app.grid_status():
  1258. # Update cursor
  1259. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1260. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1261. symbol='++', edge_color=self.app.cursor_color_3D,
  1262. edge_width=self.app.defaults["global_cursor_width"],
  1263. size=self.app.defaults["global_cursor_size"])
  1264. if self.cursor_pos is None:
  1265. self.cursor_pos = (0, 0)
  1266. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  1267. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  1268. # # update the positions on status bar
  1269. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1270. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  1271. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1272. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  1273. units = self.app.defaults["units"].lower()
  1274. self.app.plotcanvas.text_hud.text = \
  1275. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  1276. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  1277. # draw the utility geometry
  1278. if shape_type == "square":
  1279. if self.first_click:
  1280. self.app.delete_selection_shape()
  1281. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1282. coords=(curr_pos[0], curr_pos[1]))
  1283. else:
  1284. self.delete_moving_selection_shape()
  1285. self.draw_moving_selection_shape_poly(points=self.points, data=(curr_pos[0], curr_pos[1]))
  1286. def on_key_press(self, event):
  1287. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  1288. # matplotlib_key_flag = False
  1289. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1290. if type(event) is int:
  1291. key = event
  1292. # events from the GUI are of type QKeyEvent
  1293. elif type(event) == QtGui.QKeyEvent:
  1294. key = event.key()
  1295. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1296. # matplotlib_key_flag = True
  1297. key = event.key
  1298. key = QtGui.QKeySequence(key)
  1299. # check for modifiers
  1300. key_string = key.toString().lower()
  1301. if '+' in key_string:
  1302. mod, __, key_text = key_string.rpartition('+')
  1303. if mod.lower() == 'ctrl':
  1304. # modifiers = QtCore.Qt.ControlModifier
  1305. pass
  1306. elif mod.lower() == 'alt':
  1307. # modifiers = QtCore.Qt.AltModifier
  1308. pass
  1309. elif mod.lower() == 'shift':
  1310. # modifiers = QtCore.Qt.ShiftModifier
  1311. pass
  1312. else:
  1313. # modifiers = QtCore.Qt.NoModifier
  1314. pass
  1315. key = QtGui.QKeySequence(key_text)
  1316. # events from Vispy are of type KeyEvent
  1317. else:
  1318. key = event.key
  1319. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1320. if self.area_sel_disconnect_flag is True:
  1321. if self.app.is_legacy is False:
  1322. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1323. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1324. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1325. else:
  1326. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1327. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1328. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1329. try:
  1330. # restore the Grid snapping if it was active before
  1331. if self.grid_status_memory is True:
  1332. self.app.ui.grid_snap_btn.trigger()
  1333. if self.app.is_legacy is False:
  1334. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1335. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1336. else:
  1337. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1338. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1339. self.app.tool_shapes.clear(update=True)
  1340. except Exception as e:
  1341. log.debug("ToolPaint.on_key_press() _2 --> %s" % str(e))
  1342. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1343. self.app.on_mouse_click_over_plot)
  1344. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1345. self.app.on_mouse_move_over_plot)
  1346. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1347. self.app.on_mouse_click_release_over_plot)
  1348. self.points = []
  1349. self.poly_drawn = False
  1350. self.delete_moving_selection_shape()
  1351. self.delete_tool_selection_shape()
  1352. def calculate_bounding_box(self, ncc_obj, ncc_select, box_obj=None):
  1353. """
  1354. Will return a geometry that dictate the total extent of the area to be copper cleared
  1355. :param ncc_obj: The object to be copper cleared
  1356. :param box_obj: The object whose geometry will be used as delimitation for copper clearing - if selected
  1357. :param ncc_select: String that choose what kind of reference to be used for copper clearing extent
  1358. :return: The geometry that surrounds the area to be cleared and the kind of object from which the
  1359. geometry originated (string: "gerber", "geometry" or None)
  1360. """
  1361. box_kind = box_obj.kind if box_obj is not None else None
  1362. env_obj = None
  1363. if ncc_select == _('Itself'):
  1364. geo_n = ncc_obj.solid_geometry
  1365. try:
  1366. if isinstance(geo_n, MultiPolygon):
  1367. env_obj = geo_n.convex_hull
  1368. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1369. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1370. env_obj = unary_union(geo_n)
  1371. else:
  1372. env_obj = unary_union(geo_n)
  1373. env_obj = env_obj.convex_hull
  1374. except Exception as e:
  1375. log.debug("NonCopperClear.calculate_bounding_box() 'itself' --> %s" % str(e))
  1376. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1377. return None
  1378. elif ncc_select == _("Area Selection"):
  1379. env_obj = unary_union(self.sel_rect)
  1380. try:
  1381. __ = iter(env_obj)
  1382. except Exception:
  1383. env_obj = [env_obj]
  1384. elif ncc_select == _("Reference Object"):
  1385. if box_obj is None:
  1386. return None, None
  1387. box_geo = box_obj.solid_geometry
  1388. if box_kind == 'geometry':
  1389. try:
  1390. __ = iter(box_geo)
  1391. env_obj = box_geo
  1392. except Exception:
  1393. env_obj = [box_geo]
  1394. elif box_kind == 'gerber':
  1395. box_geo = unary_union(box_obj.solid_geometry).convex_hull
  1396. ncc_geo = unary_union(ncc_obj.solid_geometry).convex_hull
  1397. env_obj = ncc_geo.intersection(box_geo)
  1398. else:
  1399. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1400. return 'fail'
  1401. return env_obj, box_kind
  1402. def apply_margin_to_bounding_box(self, bbox, box_kind, ncc_select, ncc_margin):
  1403. """
  1404. Prepare non-copper polygons.
  1405. Apply a margin to the bounding box area from which the copper features will be subtracted
  1406. :param bbox: the Geometry to be used as bounding box after applying the ncc_margin
  1407. :param box_kind: "geometry" or "gerber"
  1408. :param ncc_select: the kind of area to be copper cleared
  1409. :param ncc_margin: the margin around the area to be copper cleared
  1410. :return: an geometric element (Polygon or MultiPolygon) that specify the area to be copper cleared
  1411. """
  1412. log.debug("NCC Tool. Preparing non-copper polygons.")
  1413. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1414. if bbox is None:
  1415. log.debug("NonCopperClear.apply_margin_to_bounding_box() --> The object is None")
  1416. return 'fail'
  1417. new_bounding_box = None
  1418. if ncc_select == _('Itself'):
  1419. try:
  1420. new_bounding_box = bbox.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1421. except Exception as e:
  1422. log.debug("NonCopperClear.apply_margin_to_bounding_box() 'itself' --> %s" % str(e))
  1423. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1424. return 'fail'
  1425. elif ncc_select == _("Area Selection"):
  1426. geo_buff_list = []
  1427. for poly in bbox:
  1428. if self.app.abort_flag:
  1429. # graceful abort requested by the user
  1430. raise grace
  1431. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1432. new_bounding_box = unary_union(geo_buff_list)
  1433. elif ncc_select == _("Reference Object"):
  1434. if box_kind == 'geometry':
  1435. geo_buff_list = []
  1436. for poly in bbox:
  1437. if self.app.abort_flag:
  1438. # graceful abort requested by the user
  1439. raise grace
  1440. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1441. new_bounding_box = unary_union(geo_buff_list)
  1442. elif box_kind == 'gerber':
  1443. new_bounding_box = bbox.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1444. else:
  1445. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1446. return 'fail'
  1447. log.debug("NCC Tool. Finished non-copper polygons.")
  1448. return new_bounding_box
  1449. def get_tool_empty_area(self, name, ncc_obj, geo_obj, isotooldia, has_offset, ncc_offset, ncc_margin,
  1450. bounding_box, tools_storage, work_geo=None):
  1451. """
  1452. Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry.
  1453. :param name:
  1454. :param ncc_obj:
  1455. :param geo_obj:
  1456. :param isotooldia:
  1457. :param has_offset:
  1458. :param ncc_offset:
  1459. :param ncc_margin:
  1460. :param bounding_box: only this area is kept
  1461. :param tools_storage:
  1462. :param work_geo: if provided use this geometry to generate the empty area
  1463. :return:
  1464. """
  1465. log.debug("NCC Tool. Calculate 'empty' area.")
  1466. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1467. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1468. # will store the number of tools for which the isolation is broken
  1469. warning_flag = 0
  1470. if work_geo:
  1471. sol_geo = work_geo
  1472. if has_offset is True:
  1473. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1474. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1475. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1476. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1477. if empty == 'fail' or empty.is_empty:
  1478. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1479. self.app.inform.emit(msg)
  1480. return 'fail'
  1481. if type(empty) is Polygon:
  1482. empty = MultiPolygon([empty])
  1483. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1484. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1485. return empty, warning_flag
  1486. if ncc_obj.kind == 'gerber' and not isotooldia:
  1487. # unfortunately for this function to work time efficient,
  1488. # if the Gerber was loaded without buffering then it require the buffering now.
  1489. if self.app.defaults['gerber_buffering'] == 'no':
  1490. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1491. else:
  1492. sol_geo = ncc_obj.solid_geometry
  1493. if has_offset is True:
  1494. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1495. if isinstance(sol_geo, list):
  1496. sol_geo = MultiPolygon(sol_geo)
  1497. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1498. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1499. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1500. if empty == 'fail' or empty.is_empty:
  1501. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1502. self.app.inform.emit(msg)
  1503. return 'fail'
  1504. elif ncc_obj.kind == 'gerber' and isotooldia:
  1505. isolated_geo = []
  1506. # unfortunately for this function to work time efficient,
  1507. # if the Gerber was loaded without buffering then it require the buffering now.
  1508. # TODO 'buffering status' should be a property of the object not the project property
  1509. if self.app.defaults['gerber_buffering'] == 'no':
  1510. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1511. else:
  1512. self.solid_geometry = ncc_obj.solid_geometry
  1513. # if milling type is climb then the move is counter-clockwise around features
  1514. milling_type = self.ui.milling_type_radio.get_value()
  1515. for tool_iso in isotooldia:
  1516. new_geometry = []
  1517. if milling_type == 'cl':
  1518. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1519. else:
  1520. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1521. if isolated_geo == 'fail' or isolated_geo.is_empty:
  1522. self.app.inform.emit('[ERROR_NOTCL] %s %s' %
  1523. (_("Isolation geometry could not be generated."), str(tool_iso)))
  1524. continue
  1525. if ncc_margin < tool_iso:
  1526. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1527. "than isolation tool diameter."))
  1528. try:
  1529. for geo_elem in isolated_geo:
  1530. # provide the app with a way to process the GUI events when in a blocking loop
  1531. QtWidgets.QApplication.processEvents()
  1532. if self.app.abort_flag:
  1533. # graceful abort requested by the user
  1534. raise grace
  1535. if isinstance(geo_elem, Polygon):
  1536. for ring in self.poly2rings(geo_elem):
  1537. new_geo = ring.intersection(bounding_box)
  1538. if new_geo and not new_geo.is_empty:
  1539. new_geometry.append(new_geo)
  1540. elif isinstance(geo_elem, MultiPolygon):
  1541. for poly in geo_elem:
  1542. for ring in self.poly2rings(poly):
  1543. new_geo = ring.intersection(bounding_box)
  1544. if new_geo and not new_geo.is_empty:
  1545. new_geometry.append(new_geo)
  1546. elif isinstance(geo_elem, LineString):
  1547. new_geo = geo_elem.intersection(bounding_box)
  1548. if new_geo:
  1549. if not new_geo.is_empty:
  1550. new_geometry.append(new_geo)
  1551. elif isinstance(geo_elem, MultiLineString):
  1552. for line_elem in geo_elem:
  1553. new_geo = line_elem.intersection(bounding_box)
  1554. if new_geo and not new_geo.is_empty:
  1555. new_geometry.append(new_geo)
  1556. except TypeError:
  1557. if isinstance(isolated_geo, Polygon):
  1558. for ring in self.poly2rings(isolated_geo):
  1559. new_geo = ring.intersection(bounding_box)
  1560. if new_geo:
  1561. if not new_geo.is_empty:
  1562. new_geometry.append(new_geo)
  1563. elif isinstance(isolated_geo, LineString):
  1564. new_geo = isolated_geo.intersection(bounding_box)
  1565. if new_geo and not new_geo.is_empty:
  1566. new_geometry.append(new_geo)
  1567. elif isinstance(isolated_geo, MultiLineString):
  1568. for line_elem in isolated_geo:
  1569. new_geo = line_elem.intersection(bounding_box)
  1570. if new_geo and not new_geo.is_empty:
  1571. new_geometry.append(new_geo)
  1572. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1573. for geo_e in new_geometry:
  1574. if type(geo_e) == MultiLineString:
  1575. warning_flag += 1
  1576. break
  1577. for k, v in tools_storage.items():
  1578. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1579. tool_iso)):
  1580. current_uid = int(k)
  1581. # add the solid_geometry to the current too in self.paint_tools dictionary
  1582. # and then reset the temporary list that stored that solid_geometry
  1583. v['solid_geometry'] = deepcopy(new_geometry)
  1584. v['data']['name'] = name
  1585. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1586. break
  1587. sol_geo = unary_union(isolated_geo)
  1588. if has_offset is True:
  1589. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1590. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1591. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1592. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1593. if empty == 'fail' or empty.is_empty:
  1594. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1595. self.app.inform.emit(msg)
  1596. return 'fail'
  1597. elif ncc_obj.kind == 'geometry':
  1598. sol_geo = unary_union(ncc_obj.solid_geometry)
  1599. if has_offset is True:
  1600. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1601. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1602. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1603. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1604. if empty == 'fail' or empty.is_empty:
  1605. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1606. self.app.inform.emit(msg)
  1607. return 'fail'
  1608. else:
  1609. self.app.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  1610. return 'fail'
  1611. if type(empty) is Polygon:
  1612. empty = MultiPolygon([empty])
  1613. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1614. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1615. return empty, warning_flag
  1616. def clear_polygon_worker(self, pol, tooldia, ncc_method, ncc_overlap, ncc_connect, ncc_contour, prog_plot):
  1617. cp = None
  1618. if ncc_method == _("Standard"):
  1619. try:
  1620. cp = self.clear_polygon(pol, tooldia,
  1621. steps_per_circle=self.circle_steps,
  1622. overlap=ncc_overlap, contour=ncc_contour,
  1623. connect=ncc_connect,
  1624. prog_plot=prog_plot)
  1625. except grace:
  1626. return "fail"
  1627. except Exception as ee:
  1628. log.debug("NonCopperClear.clear_polygon_worker() Standard --> %s" % str(ee))
  1629. elif ncc_method == _("Seed"):
  1630. try:
  1631. cp = self.clear_polygon2(pol, tooldia,
  1632. steps_per_circle=self.circle_steps,
  1633. overlap=ncc_overlap, contour=ncc_contour,
  1634. connect=ncc_connect,
  1635. prog_plot=prog_plot)
  1636. except grace:
  1637. return "fail"
  1638. except Exception as ee:
  1639. log.debug("NonCopperClear.clear_polygon_worker() Seed --> %s" % str(ee))
  1640. elif ncc_method == _("Lines"):
  1641. try:
  1642. cp = self.clear_polygon3(pol, tooldia,
  1643. steps_per_circle=self.circle_steps,
  1644. overlap=ncc_overlap, contour=ncc_contour,
  1645. connect=ncc_connect,
  1646. prog_plot=prog_plot)
  1647. except grace:
  1648. return "fail"
  1649. except Exception as ee:
  1650. log.debug("NonCopperClear.clear_polygon_worker() Lines --> %s" % str(ee))
  1651. elif ncc_method == _("Combo"):
  1652. try:
  1653. self.app.inform.emit(_("Clearing the polygon with the method: lines."))
  1654. cp = self.clear_polygon3(pol, tooldia,
  1655. steps_per_circle=self.circle_steps,
  1656. overlap=ncc_overlap, contour=ncc_contour,
  1657. connect=ncc_connect,
  1658. prog_plot=prog_plot)
  1659. if cp and cp.objects:
  1660. pass
  1661. else:
  1662. self.app.inform.emit(_("Failed. Clearing the polygon with the method: seed."))
  1663. cp = self.clear_polygon2(pol, tooldia,
  1664. steps_per_circle=self.circle_steps,
  1665. overlap=ncc_overlap, contour=ncc_contour,
  1666. connect=ncc_connect,
  1667. prog_plot=prog_plot)
  1668. if cp and cp.objects:
  1669. pass
  1670. else:
  1671. self.app.inform.emit(_("Failed. Clearing the polygon with the method: standard."))
  1672. cp = self.clear_polygon(pol, tooldia,
  1673. steps_per_circle=self.circle_steps,
  1674. overlap=ncc_overlap, contour=ncc_contour,
  1675. connect=ncc_connect,
  1676. prog_plot=prog_plot)
  1677. except grace:
  1678. return "fail"
  1679. except Exception as ee:
  1680. log.debug("NonCopperClear.clear_polygon_worker() Combo --> %s" % str(ee))
  1681. if cp and cp.objects:
  1682. return list(cp.get_objects())
  1683. else:
  1684. pt = pol.representative_point()
  1685. coords = (pt.x, pt.y)
  1686. self.app.inform_shell.emit('%s %s' % (_('Polygon could not be cleared. Location:'), str(coords)))
  1687. return None
  1688. def clear_copper(self, ncc_obj, ncctooldia, isotooldia, sel_obj=None, outname=None, order=None,
  1689. tools_storage=None, run_threaded=True):
  1690. """
  1691. Clear the excess copper from the entire object.
  1692. :param ncc_obj: ncc cleared object
  1693. :type ncc_obj: appObjects.FlatCAMGerber.GerberObject
  1694. :param ncctooldia: a list of diameters of the tools to be used to ncc clear
  1695. :type ncctooldia: list
  1696. :param isotooldia: a list of diameters of the tools to be used for isolation
  1697. :type isotooldia: list
  1698. :param sel_obj:
  1699. :type sel_obj:
  1700. :param outname: name of the resulting object
  1701. :type outname: str
  1702. :param order: Tools order
  1703. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1704. Usage of the different one is related to when this function is called
  1705. from a TcL command.
  1706. :type tools_storage: dict
  1707. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False
  1708. it will run non-threaded for TclShell usage
  1709. :type run_threaded: bool
  1710. :return:
  1711. """
  1712. log.debug("Executing the handler ...")
  1713. if run_threaded:
  1714. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1715. else:
  1716. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1717. QtWidgets.QApplication.processEvents()
  1718. # ######################################################################################################
  1719. # ######################### Read the parameters ########################################################
  1720. # ######################################################################################################
  1721. units = self.app.defaults['units']
  1722. order = order if order else self.ui.ncc_order_radio.get_value()
  1723. ncc_select = self.ui.select_combo.get_value()
  1724. rest_machining_choice = self.ui.ncc_rest_cb.get_value()
  1725. # determine if to use the progressive plotting
  1726. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  1727. tools_storage = tools_storage if tools_storage is not None else self.ncc_tools
  1728. sorted_clear_tools = ncctooldia
  1729. if not sorted_clear_tools:
  1730. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There is no copper clearing tool in the selection "
  1731. "and at least one is needed."))
  1732. return 'fail'
  1733. # ########################################################################################################
  1734. # set the name for the future Geometry object
  1735. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1736. # ########################################################################################################
  1737. name = outname if outname is not None else self.obj_name + "_ncc"
  1738. # ########################################################################################################
  1739. # ######### #####Initializes the new geometry object #####################################################
  1740. # ########################################################################################################
  1741. def gen_clear_area(geo_obj, app_obj):
  1742. log.debug("NCC Tool. Normal copper clearing task started.")
  1743. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1744. # provide the app with a way to process the GUI events when in a blocking loop
  1745. if not run_threaded:
  1746. QtWidgets.QApplication.processEvents()
  1747. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1748. # will store the number of tools for which the isolation is broken
  1749. warning_flag = 0
  1750. tool = None
  1751. if order == 'fwd':
  1752. sorted_clear_tools.sort(reverse=False)
  1753. elif order == 'rev':
  1754. sorted_clear_tools.sort(reverse=True)
  1755. else:
  1756. pass
  1757. app_obj.poly_not_cleared = False # flag for polygons not cleared
  1758. if ncc_select == _("Reference Object"):
  1759. bbox_geo, bbox_kind = self.calculate_bounding_box(
  1760. ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1761. else:
  1762. bbox_geo, bbox_kind = self.calculate_bounding_box(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1763. if bbox_geo is None and bbox_kind is None:
  1764. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1765. return "fail"
  1766. # Bounding box for current tool
  1767. ncc_margin = self.ui.ncc_margin_entry.get_value()
  1768. bbox = self.apply_margin_to_bounding_box(bbox=bbox_geo, box_kind=bbox_kind,
  1769. ncc_select=ncc_select, ncc_margin=ncc_margin)
  1770. # COPPER CLEARING with tools marked for CLEAR#
  1771. for tool in sorted_clear_tools:
  1772. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1773. if self.app.abort_flag:
  1774. # graceful abort requested by the user
  1775. raise grace
  1776. # provide the app with a way to process the GUI events when in a blocking loop
  1777. if not run_threaded:
  1778. QtWidgets.QApplication.processEvents()
  1779. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1780. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1781. )
  1782. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1783. # store here the geometry generated by clear operation
  1784. cleared_geo = []
  1785. tool_uid = 0 # find the current tool_uid
  1786. for k, v in self.ncc_tools.items():
  1787. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1788. tool_uid = int(k)
  1789. break
  1790. # parameters that are particular to the current tool
  1791. ncc_overlap = float(self.ncc_tools[tool_uid]["data"]["tools_ncc_overlap"]) / 100.0
  1792. ncc_method = self.ncc_tools[tool_uid]["data"]["tools_ncc_method"]
  1793. ncc_connect = self.ncc_tools[tool_uid]["data"]["tools_ncc_connect"]
  1794. ncc_contour = self.ncc_tools[tool_uid]["data"]["tools_ncc_contour"]
  1795. has_offset = self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_choice"]
  1796. ncc_offset = float(self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_value"])
  1797. # Area to clear
  1798. area, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1799. isotooldia=isotooldia, ncc_margin=ncc_margin,
  1800. has_offset=has_offset, ncc_offset=ncc_offset,
  1801. tools_storage=tools_storage, bounding_box=bbox)
  1802. # Transform area to MultiPolygon
  1803. if isinstance(area, Polygon):
  1804. area = MultiPolygon([area])
  1805. # variables to display the percentage of work done
  1806. geo_len = len(area.geoms)
  1807. old_disp_number = 0
  1808. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1809. if area.geoms:
  1810. if len(area.geoms) > 0:
  1811. pol_nr = 0
  1812. for p in area.geoms:
  1813. # provide the app with a way to process the GUI events when in a blocking loop
  1814. if not run_threaded:
  1815. QtWidgets.QApplication.processEvents()
  1816. if self.app.abort_flag:
  1817. # graceful abort requested by the user
  1818. raise grace
  1819. # clean the polygon
  1820. p = p.buffer(0)
  1821. if p is not None and p.is_valid:
  1822. poly_failed = 0
  1823. try:
  1824. for pol in p:
  1825. # provide the app with a way to process the GUI events when in a blocking loop
  1826. QtWidgets.QApplication.processEvents()
  1827. if pol is not None and isinstance(pol, Polygon):
  1828. res = self.clear_polygon_worker(pol=pol, tooldia=tool,
  1829. ncc_method=ncc_method,
  1830. ncc_overlap=ncc_overlap,
  1831. ncc_connect=ncc_connect,
  1832. ncc_contour=ncc_contour,
  1833. prog_plot=prog_plot)
  1834. if res is not None:
  1835. cleared_geo += res
  1836. else:
  1837. poly_failed += 1
  1838. else:
  1839. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(pol)))
  1840. except TypeError:
  1841. if isinstance(p, Polygon):
  1842. res = self.clear_polygon_worker(pol=p, tooldia=tool,
  1843. ncc_method=ncc_method,
  1844. ncc_overlap=ncc_overlap,
  1845. ncc_connect=ncc_connect,
  1846. ncc_contour=ncc_contour,
  1847. prog_plot=prog_plot)
  1848. if res is not None:
  1849. cleared_geo += res
  1850. else:
  1851. poly_failed += 1
  1852. else:
  1853. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(p)))
  1854. if poly_failed > 0:
  1855. app_obj.poly_not_cleared = True
  1856. pol_nr += 1
  1857. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1858. # log.debug("Polygons cleared: %d" % pol_nr)
  1859. if old_disp_number < disp_number <= 100:
  1860. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1861. old_disp_number = disp_number
  1862. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1863. # check if there is a geometry at all in the cleared geometry
  1864. if cleared_geo:
  1865. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1866. # solid_geometry
  1867. for k, v in tools_storage.items():
  1868. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1869. tool)):
  1870. current_uid = int(k)
  1871. # add the solid_geometry to the current too in self.paint_tools dictionary
  1872. # and then reset the temporary list that stored that solid_geometry
  1873. v['solid_geometry'] = deepcopy(cleared_geo)
  1874. v['data']['name'] = name
  1875. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1876. break
  1877. else:
  1878. log.debug("There are no geometries in the cleared polygon.")
  1879. # clean the progressive plotted shapes if it was used
  1880. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1881. self.temp_shapes.clear(update=True)
  1882. # delete tools with empty geometry
  1883. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1884. for uid, uid_val in list(tools_storage.items()):
  1885. try:
  1886. # if the solid_geometry (type=list) is empty
  1887. if not uid_val['solid_geometry']:
  1888. msg = '%s %s: %s %s: %s' % (
  1889. _("Could not use the tool for copper clear."),
  1890. _("Tool"),
  1891. str(uid),
  1892. _("with diameter"),
  1893. str(uid_val['tooldia']))
  1894. self.app.inform.emit(msg)
  1895. log.debug("Empty geometry for tool: %s with diameter: %s" % (str(uid), str(uid_val['tooldia'])))
  1896. tools_storage.pop(uid, None)
  1897. except KeyError:
  1898. tools_storage.pop(uid, None)
  1899. geo_obj.options["cnctooldia"] = str(tool)
  1900. geo_obj.multigeo = True
  1901. geo_obj.tools = dict(tools_storage)
  1902. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1903. has_solid_geo = 0
  1904. for tid in geo_obj.tools:
  1905. if geo_obj.tools[tid]['solid_geometry']:
  1906. has_solid_geo += 1
  1907. if has_solid_geo == 0:
  1908. msg = '[ERROR] %s' % _("There is no NCC Geometry in the file.\n"
  1909. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1910. "Change the painting parameters and try again.")
  1911. app_obj.inform.emit(msg)
  1912. return 'fail'
  1913. # check to see if geo_obj.tools is empty
  1914. # it will be updated only if there is a solid_geometry for tools
  1915. if geo_obj.tools:
  1916. if warning_flag == 0:
  1917. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1918. else:
  1919. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1920. _("NCC Tool clear all done but the copper features isolation is broken for"),
  1921. str(warning_flag),
  1922. _("tools")))
  1923. return
  1924. # create the solid_geometry
  1925. geo_obj.solid_geometry = []
  1926. for tool_id in geo_obj.tools:
  1927. if geo_obj.tools[tool_id]['solid_geometry']:
  1928. try:
  1929. for geo in geo_obj.tools[tool_id]['solid_geometry']:
  1930. geo_obj.solid_geometry.append(geo)
  1931. except TypeError:
  1932. geo_obj.solid_geometry.append(geo_obj.tools[tool_id]['solid_geometry'])
  1933. else:
  1934. # I will use this variable for this purpose although it was meant for something else
  1935. # signal that we have no geo in the object therefore don't create it
  1936. app_obj.poly_not_cleared = False
  1937. return "fail"
  1938. # # Experimental...
  1939. # # print("Indexing...", end=' ')
  1940. # # geo_obj.make_index()
  1941. # ###########################################################################################
  1942. # Initializes the new geometry object for the case of the rest-machining ####################
  1943. # ###########################################################################################
  1944. def gen_clear_area_rest(geo_obj, app_obj):
  1945. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1946. app_obj.inform.emit(_("NCC Tool. Rest machining copper clearing task started."))
  1947. # provide the app with a way to process the GUI events when in a blocking loop
  1948. if not run_threaded:
  1949. QtWidgets.QApplication.processEvents()
  1950. sorted_clear_tools.sort(reverse=True)
  1951. cleared_by_last_tool = []
  1952. rest_geo = []
  1953. current_uid = 1
  1954. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1955. app_obj.poly_not_cleared = True
  1956. if ncc_select == _("Reference Object"):
  1957. env_obj, box_obj_kind = self.calculate_bounding_box(
  1958. ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1959. else:
  1960. env_obj, box_obj_kind = self.calculate_bounding_box(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1961. if env_obj is None and box_obj_kind is None:
  1962. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1963. return "fail"
  1964. # log.debug("NCC Tool. Calculate 'empty' area.")
  1965. # app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1966. # Bounding box for current tool
  1967. ncc_margin = self.ui.ncc_margin_entry.get_value()
  1968. bbox = self.apply_margin_to_bounding_box(bbox=env_obj, box_kind=box_obj_kind,
  1969. ncc_select=ncc_select, ncc_margin=ncc_margin)
  1970. ncc_connect = self.ui.rest_ncc_connect_cb.get_value()
  1971. ncc_contour = self.ui.rest_ncc_contour_cb.get_value()
  1972. has_offset = self.ui.rest_ncc_choice_offset_cb.get_value()
  1973. ncc_offset = self.ui.rest_ncc_offset_spinner.get_value()
  1974. # Area to clear
  1975. area, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1976. isotooldia=isotooldia,
  1977. has_offset=has_offset, ncc_offset=ncc_offset,
  1978. ncc_margin=ncc_margin, tools_storage=tools_storage,
  1979. bounding_box=bbox)
  1980. # for testing purposes ----------------------------------
  1981. # for po in area.geoms:
  1982. # self.app.tool_shapes.add(po, color=self.app.defaults['global_sel_line'],
  1983. # face_color=self.app.defaults['global_sel_line'],
  1984. # update=True, layer=0, tolerance=None)
  1985. # -------------------------------------------------------
  1986. # Generate area for each tool
  1987. while sorted_clear_tools:
  1988. tool = sorted_clear_tools.pop(0)
  1989. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1990. if self.app.abort_flag:
  1991. # graceful abort requested by the user
  1992. raise grace
  1993. # provide the app with a way to process the GUI events when in a blocking loop
  1994. QtWidgets.QApplication.processEvents()
  1995. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1996. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1997. )
  1998. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1999. tool_uid = 0 # find the current tool_uid
  2000. for k, v in self.ncc_tools.items():
  2001. if self.app.dec_format(v['tooldia'], self.decimals) == self.app.dec_format(tool, self.decimals):
  2002. tool_uid = int(k)
  2003. break
  2004. tool_data_dict = self.ncc_tools[tool_uid]["data"]
  2005. # parameters that are particular to the current tool
  2006. ncc_overlap = float(tool_data_dict["tools_ncc_overlap"]) / 100.0
  2007. ncc_method = tool_data_dict["tools_ncc_method"]
  2008. # variables to display the percentage of work done
  2009. geo_len = len(area.geoms)
  2010. old_disp_number = 0
  2011. log.warning("Total number of polygons to be cleared: %s" % str(geo_len))
  2012. # def random_color():
  2013. # r_color = np.random.rand(4)
  2014. # r_color[3] = 0.5
  2015. # return r_color
  2016. # store here the geometry generated by clear operation
  2017. cleared_geo = []
  2018. poly_failed = 0
  2019. if area.geoms and len(area.geoms) > 0:
  2020. pol_nr = 0
  2021. for p in area.geoms:
  2022. if self.app.abort_flag:
  2023. # graceful abort requested by the user
  2024. raise grace
  2025. if p is not None and p.is_valid and not p.is_empty:
  2026. # provide the app with a way to process the GUI events when in a blocking loop
  2027. QtWidgets.QApplication.processEvents()
  2028. # speedup the clearing by not trying to clear polygons that is clear they can't be
  2029. # cleared with the current tool. this tremendously reduce the clearing time
  2030. check_dist = -tool / 2
  2031. check_buff = p.buffer(check_dist, self.circle_steps)
  2032. if not check_buff or check_buff.is_empty:
  2033. continue
  2034. # if self.app.dec_format(float(tool), self.decimals) == 0.15:
  2035. # # for testing purposes ----------------------------------
  2036. # self.app.tool_shapes.add(p, color=self.app.defaults['global_sel_line'],
  2037. # face_color=random_color(),
  2038. # update=True, layer=0, tolerance=None)
  2039. # self.app.tool_shapes.add(check_buff, color=self.app.defaults['global_sel_line'],
  2040. # face_color='#FFFFFFFF',
  2041. # update=True, layer=0, tolerance=None)
  2042. # # -------------------------------------------------------
  2043. # actual copper clearing is done here
  2044. if isinstance(p, Polygon):
  2045. res = self.clear_polygon_worker(pol=p, tooldia=tool,
  2046. ncc_method=ncc_method,
  2047. ncc_overlap=ncc_overlap,
  2048. ncc_connect=ncc_connect,
  2049. ncc_contour=ncc_contour,
  2050. prog_plot=prog_plot)
  2051. if res is not None:
  2052. cleared_geo += res
  2053. else:
  2054. poly_failed += 1
  2055. else:
  2056. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(p)))
  2057. if poly_failed > 0:
  2058. app_obj.poly_not_cleared = True
  2059. pol_nr += 1
  2060. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2061. # log.debug("Polygons cleared: %d" % pol_nr)
  2062. if old_disp_number < disp_number <= 100:
  2063. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2064. old_disp_number = disp_number
  2065. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2066. if self.app.abort_flag:
  2067. raise grace # graceful abort requested by the user
  2068. # check if there is a geometry at all in the cleared geometry
  2069. if cleared_geo:
  2070. tools_storage[tool_uid]["solid_geometry"] = deepcopy(cleared_geo)
  2071. tools_storage[tool_uid]["data"]["name"] = name + '_' + str(tool)
  2072. geo_obj.tools[tool_uid] = dict(tools_storage[tool_uid])
  2073. else:
  2074. log.debug("There are no geometries in the cleared polygon.")
  2075. log.warning("Total number of polygons failed to be cleared: %s" % str(poly_failed))
  2076. else:
  2077. log.warning("The area to be cleared has no polygons.")
  2078. # # Area to clear next
  2079. # try:
  2080. # # buffered_cleared = unary_union(cleared_geo).buffer(tool / 2.0)
  2081. # # area = area.difference(buffered_cleared)
  2082. # area = area.difference(unary_union(cleared_geo))
  2083. # except Exception as e:
  2084. # log.debug("Creating new area failed due of: %s" % str(e))
  2085. new_area = MultiPolygon([line.buffer(tool / 1.9999999) for line in cleared_geo])
  2086. new_area = new_area.buffer(0.0000001)
  2087. area = area.difference(new_area)
  2088. new_area = [pol for pol in area if pol.is_valid and not pol.is_empty]
  2089. area = MultiPolygon(new_area)
  2090. # speedup the clearing by not trying to clear polygons that is clear they can't be
  2091. # cleared with any tool. this tremendously reduce the clearing time
  2092. # found_poly_to_clear = False
  2093. # for t in sorted_clear_tools:
  2094. # check_dist = -t / 2.000000001
  2095. # for pl in area:
  2096. # check_buff = pl.buffer(check_dist)
  2097. # if not check_buff or check_buff.is_empty or not check_buff.is_valid:
  2098. # continue
  2099. # else:
  2100. # found_poly_to_clear = True
  2101. # break
  2102. # if found_poly_to_clear is True:
  2103. # break
  2104. #
  2105. # if found_poly_to_clear is False:
  2106. # log.warning("The area to be cleared no longer has polygons. Finishing.")
  2107. # break
  2108. if not area or area.is_empty:
  2109. break
  2110. # # try to clear the polygons
  2111. # buff_distance = 0.0
  2112. # try:
  2113. # new_area = [p.buffer(buff_distance) for p in area if not p.is_empty]
  2114. # except TypeError:
  2115. # new_area = [area.buffer(tool * ncc_overlap)]
  2116. # area = unary_union(area)
  2117. geo_obj.multigeo = True
  2118. geo_obj.options["cnctooldia"] = '0.0'
  2119. # clean the progressive plotted shapes if it was used
  2120. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  2121. self.temp_shapes.clear(update=True)
  2122. # check to see if geo_obj.tools is empty
  2123. # it will be updated only if there is a solid_geometry for tools
  2124. if geo_obj.tools:
  2125. if warning_flag == 0:
  2126. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2127. else:
  2128. self.app.inform.emit(
  2129. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2130. "isolation is broken for"), str(warning_flag), _("tools")))
  2131. return
  2132. # create the solid_geometry
  2133. geo_obj.solid_geometry = []
  2134. for tool_uid in geo_obj.tools:
  2135. if geo_obj.tools[tool_uid]['solid_geometry']:
  2136. try:
  2137. for geo in geo_obj.tools[tool_uid]['solid_geometry']:
  2138. geo_obj.solid_geometry.append(geo)
  2139. except TypeError:
  2140. geo_obj.solid_geometry.append(geo_obj.tools[tool_uid]['solid_geometry'])
  2141. else:
  2142. # I will use this variable for this purpose although it was meant for something else
  2143. # signal that we have no geo in the object therefore don't create it
  2144. app_obj.poly_not_cleared = False
  2145. return "fail"
  2146. # ###########################################################################################
  2147. # Create the Job function and send it to the worker to be processed in another thread #######
  2148. # ###########################################################################################
  2149. def job_thread(a_obj):
  2150. try:
  2151. if rest_machining_choice is True:
  2152. a_obj.app_obj.new_object("geometry", name, gen_clear_area_rest)
  2153. else:
  2154. a_obj.app_obj.new_object("geometry", name, gen_clear_area)
  2155. except grace:
  2156. if run_threaded:
  2157. proc.done()
  2158. return
  2159. except Exception:
  2160. if run_threaded:
  2161. proc.done()
  2162. traceback.print_stack()
  2163. return
  2164. if run_threaded:
  2165. proc.done()
  2166. else:
  2167. a_obj.proc_container.view.set_idle()
  2168. # focus on Properties Tab
  2169. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  2170. if run_threaded:
  2171. # Promise object with the new name
  2172. self.app.collection.promise(name)
  2173. # Background
  2174. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2175. else:
  2176. job_thread(app_obj=self.app)
  2177. def clear_copper_tcl(self, ncc_obj, sel_obj=None, ncctooldia=None, isotooldia=None, margin=None, has_offset=None,
  2178. offset=None, select_method=None, outname=None, overlap=None, connect=None, contour=None,
  2179. order=None, method=None, rest=None, tools_storage=None, plot=True, run_threaded=False):
  2180. """
  2181. Clear the excess copper from the entire object. To be used only in a TCL command.
  2182. :param ncc_obj: ncc cleared object
  2183. :param sel_obj:
  2184. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  2185. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  2186. :param overlap: value by which the paths will overlap
  2187. :param order: if the tools are ordered and how
  2188. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  2189. another object
  2190. :param has_offset: True if an offset is needed
  2191. :param offset: distance from the copper features where the copper clearing is stopping
  2192. :param margin: a border around cleared area
  2193. :param outname: name of the resulting object
  2194. :param connect: Connect lines to avoid tool lifts.
  2195. :param contour: Clear around the edges.
  2196. :param method: choice out of 'seed', 'normal', 'lines'
  2197. :param rest: True if to use rest-machining
  2198. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  2199. Usage of the different one is related to when this function is called from a
  2200. TcL command.
  2201. :param plot: if True after the job is finished the result will be plotted, else it will not.
  2202. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage;
  2203. if False it will run non-threaded for TclShell usage
  2204. :return:
  2205. """
  2206. if run_threaded:
  2207. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  2208. else:
  2209. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  2210. QtWidgets.QApplication.processEvents()
  2211. # #####################################################################
  2212. # ####### Read the parameters #########################################
  2213. # #####################################################################
  2214. units = self.app.defaults['units']
  2215. log.debug("NCC Tool started. Reading parameters.")
  2216. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  2217. ncc_method = method
  2218. ncc_margin = margin
  2219. ncc_select = select_method
  2220. overlap = overlap
  2221. connect = connect
  2222. contour = contour
  2223. order = order
  2224. if tools_storage is not None:
  2225. tools_storage = tools_storage
  2226. else:
  2227. tools_storage = self.ncc_tools
  2228. ncc_offset = 0.0
  2229. if has_offset is True:
  2230. ncc_offset = offset
  2231. # ######################################################################################################
  2232. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  2233. # ######################################################################################################
  2234. sorted_tools = []
  2235. try:
  2236. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  2237. except AttributeError:
  2238. if not isinstance(ncctooldia, list):
  2239. sorted_tools = [float(ncctooldia)]
  2240. else:
  2241. sorted_tools = ncctooldia
  2242. if not sorted_tools:
  2243. return 'fail'
  2244. # ##############################################################################################################
  2245. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  2246. # ##############################################################################################################
  2247. log.debug("NCC Tool. Preparing non-copper polygons.")
  2248. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  2249. try:
  2250. if sel_obj is None or sel_obj == _('Itself'):
  2251. ncc_sel_obj = ncc_obj
  2252. else:
  2253. ncc_sel_obj = sel_obj
  2254. except Exception as e:
  2255. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  2256. return 'fail'
  2257. bounding_box = None
  2258. if ncc_select == _('Itself'):
  2259. geo_n = ncc_sel_obj.solid_geometry
  2260. try:
  2261. if isinstance(geo_n, MultiPolygon):
  2262. env_obj = geo_n.convex_hull
  2263. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  2264. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  2265. env_obj = unary_union(geo_n)
  2266. else:
  2267. env_obj = unary_union(geo_n)
  2268. env_obj = env_obj.convex_hull
  2269. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2270. except Exception as e:
  2271. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  2272. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2273. return 'fail'
  2274. elif ncc_select == 'area':
  2275. geo_n = unary_union(self.sel_rect)
  2276. try:
  2277. __ = iter(geo_n)
  2278. except Exception as e:
  2279. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  2280. geo_n = [geo_n]
  2281. geo_buff_list = []
  2282. for poly in geo_n:
  2283. if self.app.abort_flag:
  2284. # graceful abort requested by the user
  2285. raise grace
  2286. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2287. bounding_box = unary_union(geo_buff_list)
  2288. elif ncc_select == _("Reference Object"):
  2289. geo_n = ncc_sel_obj.solid_geometry
  2290. if ncc_sel_obj.kind == 'geometry':
  2291. try:
  2292. __ = iter(geo_n)
  2293. except Exception as e:
  2294. log.debug("NonCopperClear.clear_copper() 'Reference Object' --> %s" % str(e))
  2295. geo_n = [geo_n]
  2296. geo_buff_list = []
  2297. for poly in geo_n:
  2298. if self.app.abort_flag:
  2299. # graceful abort requested by the user
  2300. raise grace
  2301. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2302. bounding_box = unary_union(geo_buff_list)
  2303. elif ncc_sel_obj.kind == 'gerber':
  2304. geo_n = unary_union(geo_n).convex_hull
  2305. bounding_box = unary_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  2306. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2307. else:
  2308. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  2309. return 'fail'
  2310. log.debug("NCC Tool. Finished non-copper polygons.")
  2311. # ########################################################################################################
  2312. # set the name for the future Geometry object
  2313. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  2314. # ########################################################################################################
  2315. rest_machining_choice = rest
  2316. if rest_machining_choice is True:
  2317. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2318. else:
  2319. name = outname if outname is not None else self.obj_name + "_ncc"
  2320. # ##########################################################################################
  2321. # Initializes the new geometry object ######################################################
  2322. # ##########################################################################################
  2323. def gen_clear_area(geo_obj, app_obj):
  2324. assert geo_obj.kind == 'geometry', \
  2325. "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  2326. # provide the app with a way to process the GUI events when in a blocking loop
  2327. if not run_threaded:
  2328. QtWidgets.QApplication.processEvents()
  2329. log.debug("NCC Tool. Normal copper clearing task started.")
  2330. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  2331. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2332. # will store the number of tools for which the isolation is broken
  2333. warning_flag = 0
  2334. if order == 'fwd':
  2335. sorted_tools.sort(reverse=False)
  2336. elif order == 'rev':
  2337. sorted_tools.sort(reverse=True)
  2338. else:
  2339. pass
  2340. cleared_geo = []
  2341. # Already cleared area
  2342. cleared = MultiPolygon()
  2343. # flag for polygons not cleared
  2344. app_obj.poly_not_cleared = False
  2345. # Generate area for each tool
  2346. offset_a = sum(sorted_tools)
  2347. current_uid = int(1)
  2348. try:
  2349. tool = eval(self.app.defaults["tools_ncc_tools"])[0]
  2350. except TypeError:
  2351. tool = eval(self.app.defaults["tools_ncc_tools"])
  2352. # ###################################################################################################
  2353. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2354. # ###################################################################################################
  2355. log.debug("NCC Tool. Calculate 'empty' area.")
  2356. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  2357. if ncc_obj.kind == 'gerber' and not isotooldia:
  2358. # unfortunately for this function to work time efficient,
  2359. # if the Gerber was loaded without buffering then it require the buffering now.
  2360. if self.app.defaults['gerber_buffering'] == 'no':
  2361. sol_geo = ncc_obj.solid_geometry.buffer(0)
  2362. else:
  2363. sol_geo = ncc_obj.solid_geometry
  2364. if has_offset is True:
  2365. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2366. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2367. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2368. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2369. if empty == 'fail':
  2370. return 'fail'
  2371. if empty.is_empty:
  2372. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2373. _("Could not get the extent of the area to be non copper cleared."))
  2374. return 'fail'
  2375. elif ncc_obj.kind == 'gerber' and isotooldia:
  2376. isolated_geo = []
  2377. # unfortunately for this function to work time efficient,
  2378. # if the Gerber was loaded without buffering then it require the buffering now.
  2379. if self.app.defaults['gerber_buffering'] == 'no':
  2380. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  2381. else:
  2382. self.solid_geometry = ncc_obj.solid_geometry
  2383. # if milling type is climb then the move is counter-clockwise around features
  2384. milling_type = self.app.defaults["tools_ncc_milling_type"]
  2385. for tool_iso in isotooldia:
  2386. new_geometry = []
  2387. if milling_type == 'cl':
  2388. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  2389. else:
  2390. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  2391. if isolated_geo == 'fail':
  2392. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2393. else:
  2394. if ncc_margin < tool_iso:
  2395. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2396. "than isolation tool diameter."))
  2397. try:
  2398. for geo_elem in isolated_geo:
  2399. # provide the app with a way to process the GUI events when in a blocking loop
  2400. QtWidgets.QApplication.processEvents()
  2401. if self.app.abort_flag:
  2402. # graceful abort requested by the user
  2403. raise grace
  2404. if isinstance(geo_elem, Polygon):
  2405. for ring in self.poly2rings(geo_elem):
  2406. new_geo = ring.intersection(bounding_box)
  2407. if new_geo and not new_geo.is_empty:
  2408. new_geometry.append(new_geo)
  2409. elif isinstance(geo_elem, MultiPolygon):
  2410. for a_poly in geo_elem:
  2411. for ring in self.poly2rings(a_poly):
  2412. new_geo = ring.intersection(bounding_box)
  2413. if new_geo and not new_geo.is_empty:
  2414. new_geometry.append(new_geo)
  2415. elif isinstance(geo_elem, LineString):
  2416. new_geo = geo_elem.intersection(bounding_box)
  2417. if new_geo:
  2418. if not new_geo.is_empty:
  2419. new_geometry.append(new_geo)
  2420. elif isinstance(geo_elem, MultiLineString):
  2421. for line_elem in geo_elem:
  2422. new_geo = line_elem.intersection(bounding_box)
  2423. if new_geo and not new_geo.is_empty:
  2424. new_geometry.append(new_geo)
  2425. except TypeError:
  2426. if isinstance(isolated_geo, Polygon):
  2427. for ring in self.poly2rings(isolated_geo):
  2428. new_geo = ring.intersection(bounding_box)
  2429. if new_geo:
  2430. if not new_geo.is_empty:
  2431. new_geometry.append(new_geo)
  2432. elif isinstance(isolated_geo, LineString):
  2433. new_geo = isolated_geo.intersection(bounding_box)
  2434. if new_geo and not new_geo.is_empty:
  2435. new_geometry.append(new_geo)
  2436. elif isinstance(isolated_geo, MultiLineString):
  2437. for line_elem in isolated_geo:
  2438. new_geo = line_elem.intersection(bounding_box)
  2439. if new_geo and not new_geo.is_empty:
  2440. new_geometry.append(new_geo)
  2441. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2442. for geo_e in new_geometry:
  2443. if type(geo_e) == MultiLineString:
  2444. warning_flag += 1
  2445. break
  2446. for k, v in tools_storage.items():
  2447. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2448. tool_iso)):
  2449. current_uid = int(k)
  2450. # add the solid_geometry to the current too in self.paint_tools dictionary
  2451. # and then reset the temporary list that stored that solid_geometry
  2452. v['solid_geometry'] = deepcopy(new_geometry)
  2453. v['data']['name'] = name
  2454. break
  2455. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2456. sol_geo = unary_union(isolated_geo)
  2457. if has_offset is True:
  2458. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2459. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2460. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2461. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2462. if empty == 'fail':
  2463. return 'fail'
  2464. if empty.is_empty:
  2465. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2466. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2467. return 'fail'
  2468. elif ncc_obj.kind == 'geometry':
  2469. sol_geo = unary_union(ncc_obj.solid_geometry)
  2470. if has_offset is True:
  2471. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2472. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2473. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2474. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2475. if empty == 'fail':
  2476. return 'fail'
  2477. if empty.is_empty:
  2478. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2479. _("Could not get the extent of the area to be non copper cleared."))
  2480. return 'fail'
  2481. else:
  2482. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2483. return 'fail'
  2484. if type(empty) is Polygon:
  2485. empty = MultiPolygon([empty])
  2486. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2487. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  2488. # COPPER CLEARING #
  2489. for tool in sorted_tools:
  2490. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2491. if self.app.abort_flag:
  2492. # graceful abort requested by the user
  2493. raise grace
  2494. # provide the app with a way to process the GUI events when in a blocking loop
  2495. QtWidgets.QApplication.processEvents()
  2496. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2497. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2498. )
  2499. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2500. cleared_geo[:] = []
  2501. # Get remaining tools offset
  2502. offset_a -= (tool - 1e-12)
  2503. # Area to clear
  2504. area = empty.buffer(-offset_a)
  2505. try:
  2506. area = area.difference(cleared)
  2507. except Exception:
  2508. continue
  2509. # Transform area to MultiPolygon
  2510. if type(area) is Polygon:
  2511. area = MultiPolygon([area])
  2512. # variables to display the percentage of work done
  2513. geo_len = len(area.geoms)
  2514. old_disp_number = 0
  2515. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2516. if area.geoms:
  2517. if len(area.geoms) > 0:
  2518. pol_nr = 0
  2519. for p in area.geoms:
  2520. # provide the app with a way to process the GUI events when in a blocking loop
  2521. QtWidgets.QApplication.processEvents()
  2522. if self.app.abort_flag:
  2523. # graceful abort requested by the user
  2524. raise grace
  2525. # clean the polygon
  2526. p = p.buffer(0)
  2527. if p is not None and p.is_valid:
  2528. poly_processed = []
  2529. try:
  2530. for pol in p:
  2531. if pol is not None and isinstance(pol, Polygon):
  2532. if ncc_method == 'standard':
  2533. cp = self.clear_polygon(pol, tool,
  2534. self.circle_steps,
  2535. overlap=overlap, contour=contour,
  2536. connect=connect,
  2537. prog_plot=False)
  2538. elif ncc_method == 'seed':
  2539. cp = self.clear_polygon2(pol, tool,
  2540. self.circle_steps,
  2541. overlap=overlap, contour=contour,
  2542. connect=connect,
  2543. prog_plot=False)
  2544. else:
  2545. cp = self.clear_polygon3(pol, tool,
  2546. self.circle_steps,
  2547. overlap=overlap, contour=contour,
  2548. connect=connect,
  2549. prog_plot=False)
  2550. if cp:
  2551. cleared_geo += list(cp.get_objects())
  2552. poly_processed.append(True)
  2553. else:
  2554. poly_processed.append(False)
  2555. log.warning("Polygon in MultiPolygon can not be cleared.")
  2556. else:
  2557. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2558. "It is: %s" % str(type(pol)))
  2559. except TypeError:
  2560. if isinstance(p, Polygon):
  2561. if ncc_method == 'standard':
  2562. cp = self.clear_polygon(p, tool, self.circle_steps,
  2563. overlap=overlap, contour=contour, connect=connect,
  2564. prog_plot=False)
  2565. elif ncc_method == 'seed':
  2566. cp = self.clear_polygon2(p, tool, self.circle_steps,
  2567. overlap=overlap, contour=contour, connect=connect,
  2568. prog_plot=False)
  2569. else:
  2570. cp = self.clear_polygon3(p, tool, self.circle_steps,
  2571. overlap=overlap, contour=contour, connect=connect,
  2572. prog_plot=False)
  2573. if cp:
  2574. cleared_geo += list(cp.get_objects())
  2575. poly_processed.append(True)
  2576. else:
  2577. poly_processed.append(False)
  2578. log.warning("Polygon can not be cleared.")
  2579. else:
  2580. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  2581. p_cleared = poly_processed.count(True)
  2582. p_not_cleared = poly_processed.count(False)
  2583. if p_not_cleared:
  2584. app_obj.poly_not_cleared = True
  2585. if p_cleared == 0:
  2586. continue
  2587. pol_nr += 1
  2588. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2589. # log.debug("Polygons cleared: %d" % pol_nr)
  2590. if old_disp_number < disp_number <= 100:
  2591. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2592. old_disp_number = disp_number
  2593. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2594. # check if there is a geometry at all in the cleared geometry
  2595. if cleared_geo:
  2596. # Overall cleared area
  2597. cleared = empty.buffer(-offset_a * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  2598. tool / 1.999999)
  2599. # clean-up cleared geo
  2600. cleared = cleared.buffer(0)
  2601. # find the tooluid associated with the current tool_dia so we know where to add the tool
  2602. # solid_geometry
  2603. for k, v in tools_storage.items():
  2604. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2605. tool)):
  2606. current_uid = int(k)
  2607. # add the solid_geometry to the current too in self.paint_tools dictionary
  2608. # and then reset the temporary list that stored that solid_geometry
  2609. v['solid_geometry'] = deepcopy(cleared_geo)
  2610. v['data']['name'] = name
  2611. break
  2612. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2613. else:
  2614. log.debug("There are no geometries in the cleared polygon.")
  2615. # delete tools with empty geometry
  2616. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2617. for uid, uid_val in list(tools_storage.items()):
  2618. try:
  2619. # if the solid_geometry (type=list) is empty
  2620. if not uid_val['solid_geometry']:
  2621. tools_storage.pop(uid, None)
  2622. except KeyError:
  2623. tools_storage.pop(uid, None)
  2624. geo_obj.options["cnctooldia"] = str(tool)
  2625. geo_obj.multigeo = True
  2626. geo_obj.tools.clear()
  2627. geo_obj.tools = dict(tools_storage)
  2628. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2629. has_solid_geo = 0
  2630. for tooluid in geo_obj.tools:
  2631. if geo_obj.tools[tooluid]['solid_geometry']:
  2632. has_solid_geo += 1
  2633. if has_solid_geo == 0:
  2634. app_obj.inform.emit('[ERROR] %s' %
  2635. _("There is no NCC Geometry in the file.\n"
  2636. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2637. "Change the painting parameters and try again."))
  2638. return 'fail'
  2639. # check to see if geo_obj.tools is empty
  2640. # it will be updated only if there is a solid_geometry for tools
  2641. if geo_obj.tools:
  2642. if warning_flag == 0:
  2643. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  2644. else:
  2645. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  2646. _("NCC Tool clear all done but the copper features isolation is broken for"),
  2647. str(warning_flag),
  2648. _("tools")))
  2649. return
  2650. # create the solid_geometry
  2651. geo_obj.solid_geometry = []
  2652. for tooluid in geo_obj.tools:
  2653. if geo_obj.tools[tooluid]['solid_geometry']:
  2654. try:
  2655. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2656. geo_obj.solid_geometry.append(geo)
  2657. except TypeError:
  2658. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2659. else:
  2660. # I will use this variable for this purpose although it was meant for something else
  2661. # signal that we have no geo in the object therefore don't create it
  2662. app_obj.poly_not_cleared = False
  2663. return "fail"
  2664. # ###########################################################################################
  2665. # Initializes the new geometry object for the case of the rest-machining ####################
  2666. # ###########################################################################################
  2667. def gen_clear_area_rest(geo_obj, app_obj):
  2668. assert geo_obj.kind == 'geometry', \
  2669. "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  2670. log.debug("NCC Tool. Rest machining copper clearing task started.")
  2671. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  2672. # provide the app with a way to process the GUI events when in a blocking loop
  2673. if not run_threaded:
  2674. QtWidgets.QApplication.processEvents()
  2675. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2676. # will store the number of tools for which the isolation is broken
  2677. warning_flag = 0
  2678. sorted_tools.sort(reverse=True)
  2679. cleared_geo = []
  2680. cleared_by_last_tool = []
  2681. rest_geo = []
  2682. current_uid = 1
  2683. try:
  2684. tool = eval(self.app.defaults["tools_ncc_tools"])[0]
  2685. except TypeError:
  2686. tool = eval(self.app.defaults["tools_ncc_tools"])
  2687. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2688. app_obj.poly_not_cleared = True
  2689. log.debug("NCC Tool. Calculate 'empty' area.")
  2690. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  2691. # ###################################################################################################
  2692. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2693. # ###################################################################################################
  2694. if ncc_obj.kind == 'gerber' and not isotooldia:
  2695. sol_geo = ncc_obj.solid_geometry
  2696. if has_offset is True:
  2697. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2698. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2699. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2700. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2701. if empty == 'fail':
  2702. return 'fail'
  2703. if empty.is_empty:
  2704. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2705. _("Could not get the extent of the area to be non copper cleared."))
  2706. return 'fail'
  2707. elif ncc_obj.kind == 'gerber' and isotooldia:
  2708. isolated_geo = []
  2709. self.solid_geometry = ncc_obj.solid_geometry
  2710. # if milling type is climb then the move is counter-clockwise around features
  2711. milling_type = self.app.defaults["tools_ncc_milling_type"]
  2712. for tool_iso in isotooldia:
  2713. new_geometry = []
  2714. if milling_type == 'cl':
  2715. isolated_geo = self.generate_envelope(tool_iso, 1)
  2716. else:
  2717. isolated_geo = self.generate_envelope(tool_iso, 0)
  2718. if isolated_geo == 'fail':
  2719. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2720. else:
  2721. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2722. "than isolation tool diameter."))
  2723. try:
  2724. for geo_elem in isolated_geo:
  2725. # provide the app with a way to process the GUI events when in a blocking loop
  2726. QtWidgets.QApplication.processEvents()
  2727. if self.app.abort_flag:
  2728. # graceful abort requested by the user
  2729. raise grace
  2730. if isinstance(geo_elem, Polygon):
  2731. for ring in self.poly2rings(geo_elem):
  2732. new_geo = ring.intersection(bounding_box)
  2733. if new_geo and not new_geo.is_empty:
  2734. new_geometry.append(new_geo)
  2735. elif isinstance(geo_elem, MultiPolygon):
  2736. for poly_g in geo_elem:
  2737. for ring in self.poly2rings(poly_g):
  2738. new_geo = ring.intersection(bounding_box)
  2739. if new_geo and not new_geo.is_empty:
  2740. new_geometry.append(new_geo)
  2741. elif isinstance(geo_elem, LineString):
  2742. new_geo = geo_elem.intersection(bounding_box)
  2743. if new_geo:
  2744. if not new_geo.is_empty:
  2745. new_geometry.append(new_geo)
  2746. elif isinstance(geo_elem, MultiLineString):
  2747. for line_elem in geo_elem:
  2748. new_geo = line_elem.intersection(bounding_box)
  2749. if new_geo and not new_geo.is_empty:
  2750. new_geometry.append(new_geo)
  2751. except TypeError:
  2752. try:
  2753. if isinstance(isolated_geo, Polygon):
  2754. for ring in self.poly2rings(isolated_geo):
  2755. new_geo = ring.intersection(bounding_box)
  2756. if new_geo:
  2757. if not new_geo.is_empty:
  2758. new_geometry.append(new_geo)
  2759. elif isinstance(isolated_geo, LineString):
  2760. new_geo = isolated_geo.intersection(bounding_box)
  2761. if new_geo and not new_geo.is_empty:
  2762. new_geometry.append(new_geo)
  2763. elif isinstance(isolated_geo, MultiLineString):
  2764. for line_elem in isolated_geo:
  2765. new_geo = line_elem.intersection(bounding_box)
  2766. if new_geo and not new_geo.is_empty:
  2767. new_geometry.append(new_geo)
  2768. except Exception:
  2769. pass
  2770. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2771. for geo_e in new_geometry:
  2772. if type(geo_e) == MultiLineString:
  2773. warning_flag += 1
  2774. break
  2775. for k, v in tools_storage.items():
  2776. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2777. tool_iso)):
  2778. current_uid = int(k)
  2779. # add the solid_geometry to the current too in self.paint_tools dictionary
  2780. # and then reset the temporary list that stored that solid_geometry
  2781. v['solid_geometry'] = deepcopy(new_geometry)
  2782. v['data']['name'] = name
  2783. break
  2784. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2785. sol_geo = unary_union(isolated_geo)
  2786. if has_offset is True:
  2787. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2788. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2789. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2790. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2791. if empty == 'fail':
  2792. return 'fail'
  2793. if empty.is_empty:
  2794. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2795. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2796. return 'fail'
  2797. elif ncc_obj.kind == 'geometry':
  2798. sol_geo = unary_union(ncc_obj.solid_geometry)
  2799. if has_offset is True:
  2800. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2801. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2802. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2803. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2804. if empty == 'fail':
  2805. return 'fail'
  2806. if empty.is_empty:
  2807. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2808. _("Could not get the extent of the area to be non copper cleared."))
  2809. return 'fail'
  2810. else:
  2811. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2812. return
  2813. if self.app.abort_flag:
  2814. # graceful abort requested by the user
  2815. raise grace
  2816. if type(empty) is Polygon:
  2817. empty = MultiPolygon([empty])
  2818. area = empty.buffer(0)
  2819. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2820. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2821. # Generate area for each tool
  2822. while sorted_tools:
  2823. if self.app.abort_flag:
  2824. # graceful abort requested by the user
  2825. raise grace
  2826. tool = sorted_tools.pop(0)
  2827. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2828. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2829. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2830. )
  2831. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2832. tool_used = tool - 1e-12
  2833. cleared_geo[:] = []
  2834. # Area to clear
  2835. for poly_r in cleared_by_last_tool:
  2836. # provide the app with a way to process the GUI events when in a blocking loop
  2837. QtWidgets.QApplication.processEvents()
  2838. if self.app.abort_flag:
  2839. # graceful abort requested by the user
  2840. raise grace
  2841. try:
  2842. area = area.difference(poly_r)
  2843. except Exception:
  2844. pass
  2845. cleared_by_last_tool[:] = []
  2846. # Transform area to MultiPolygon
  2847. if type(area) is Polygon:
  2848. area = MultiPolygon([area])
  2849. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2850. # and rest_geo it's a list
  2851. allparts = [p.buffer(0) for p in area.geoms]
  2852. allparts += deepcopy(rest_geo)
  2853. rest_geo[:] = []
  2854. area = MultiPolygon(deepcopy(allparts))
  2855. allparts[:] = []
  2856. # variables to display the percentage of work done
  2857. geo_len = len(area.geoms)
  2858. old_disp_number = 0
  2859. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2860. if area.geoms:
  2861. if len(area.geoms) > 0:
  2862. pol_nr = 0
  2863. for p in area.geoms:
  2864. if self.app.abort_flag:
  2865. # graceful abort requested by the user
  2866. raise grace
  2867. # clean the polygon
  2868. p = p.buffer(0)
  2869. if p is not None and p.is_valid:
  2870. # provide the app with a way to process the GUI events when in a blocking loop
  2871. QtWidgets.QApplication.processEvents()
  2872. if isinstance(p, Polygon):
  2873. try:
  2874. if ncc_method == 'standard':
  2875. cp = self.clear_polygon(p, tool_used,
  2876. self.circle_steps,
  2877. overlap=overlap, contour=contour, connect=connect,
  2878. prog_plot=False)
  2879. elif ncc_method == 'seed':
  2880. cp = self.clear_polygon2(p, tool_used,
  2881. self.circle_steps,
  2882. overlap=overlap, contour=contour, connect=connect,
  2883. prog_plot=False)
  2884. else:
  2885. cp = self.clear_polygon3(p, tool_used,
  2886. self.circle_steps,
  2887. overlap=overlap, contour=contour, connect=connect,
  2888. prog_plot=False)
  2889. cleared_geo.append(list(cp.get_objects()))
  2890. except Exception as ee:
  2891. log.warning("Polygon can't be cleared. %s" % str(ee))
  2892. # this polygon should be added to a list and then try clear it with
  2893. # a smaller tool
  2894. rest_geo.append(p)
  2895. elif isinstance(p, MultiPolygon):
  2896. for poly_p in p:
  2897. if poly_p is not None:
  2898. # provide the app with a way to process the GUI events when
  2899. # in a blocking loop
  2900. QtWidgets.QApplication.processEvents()
  2901. try:
  2902. if ncc_method == 'standard':
  2903. cp = self.clear_polygon(poly_p, tool_used,
  2904. self.circle_steps,
  2905. overlap=overlap, contour=contour,
  2906. connect=connect,
  2907. prog_plot=False)
  2908. elif ncc_method == 'seed':
  2909. cp = self.clear_polygon2(poly_p, tool_used,
  2910. self.circle_steps,
  2911. overlap=overlap, contour=contour,
  2912. connect=connect,
  2913. prog_plot=False)
  2914. else:
  2915. cp = self.clear_polygon3(poly_p, tool_used,
  2916. self.circle_steps,
  2917. overlap=overlap, contour=contour,
  2918. connect=connect,
  2919. prog_plot=False)
  2920. cleared_geo.append(list(cp.get_objects()))
  2921. except Exception as eee:
  2922. log.warning("Polygon can't be cleared. %s" % str(eee))
  2923. # this polygon should be added to a list and then try clear it with
  2924. # a smaller tool
  2925. rest_geo.append(poly_p)
  2926. pol_nr += 1
  2927. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2928. # log.debug("Polygons cleared: %d" % pol_nr)
  2929. if old_disp_number < disp_number <= 100:
  2930. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2931. old_disp_number = disp_number
  2932. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2933. if self.app.abort_flag:
  2934. # graceful abort requested by the user
  2935. raise grace
  2936. # check if there is a geometry at all in the cleared geometry
  2937. if cleared_geo:
  2938. # Overall cleared area
  2939. cleared_area = list(self.flatten_list(cleared_geo))
  2940. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2941. # for p in cleared_area])
  2942. # here we store the poly's already processed in the original geometry by the current tool
  2943. # into cleared_by_last_tool list
  2944. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2945. # the next tool
  2946. buffer_value = tool_used / 2
  2947. for p in cleared_area:
  2948. if self.app.abort_flag:
  2949. # graceful abort requested by the user
  2950. raise grace
  2951. r_poly = p.buffer(buffer_value)
  2952. cleared_by_last_tool.append(r_poly)
  2953. # find the tooluid associated with the current tool_dia so we know
  2954. # where to add the tool solid_geometry
  2955. for k, v in tools_storage.items():
  2956. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2957. tool)):
  2958. current_uid = int(k)
  2959. # add the solid_geometry to the current too in self.paint_tools dictionary
  2960. # and then reset the temporary list that stored that solid_geometry
  2961. v['solid_geometry'] = deepcopy(cleared_area)
  2962. v['data']['name'] = name
  2963. cleared_area[:] = []
  2964. break
  2965. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2966. else:
  2967. log.debug("There are no geometries in the cleared polygon.")
  2968. geo_obj.multigeo = True
  2969. geo_obj.options["cnctooldia"] = str(tool)
  2970. # check to see if geo_obj.tools is empty
  2971. # it will be updated only if there is a solid_geometry for tools
  2972. if geo_obj.tools:
  2973. if warning_flag == 0:
  2974. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2975. else:
  2976. self.app.inform.emit(
  2977. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2978. "isolation is broken for"), str(warning_flag), _("tools")))
  2979. return
  2980. # create the solid_geometry
  2981. geo_obj.solid_geometry = []
  2982. for tooluid in geo_obj.tools:
  2983. if geo_obj.tools[tooluid]['solid_geometry']:
  2984. try:
  2985. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2986. geo_obj.solid_geometry.append(geo)
  2987. except TypeError:
  2988. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2989. else:
  2990. # I will use this variable for this purpose although it was meant for something else
  2991. # signal that we have no geo in the object therefore don't create it
  2992. app_obj.poly_not_cleared = False
  2993. return "fail"
  2994. # ###########################################################################################
  2995. # Create the Job function and send it to the worker to be processed in another thread #######
  2996. # ###########################################################################################
  2997. def job_thread(app_obj):
  2998. try:
  2999. if rest_machining_choice is True:
  3000. app_obj.app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  3001. else:
  3002. app_obj.app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  3003. except grace:
  3004. if run_threaded:
  3005. proc.done()
  3006. return
  3007. except Exception:
  3008. if run_threaded:
  3009. proc.done()
  3010. traceback.print_stack()
  3011. return
  3012. if run_threaded:
  3013. proc.done()
  3014. else:
  3015. app_obj.proc_container.view.set_idle()
  3016. # focus on Properties Tab
  3017. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  3018. if run_threaded:
  3019. # Promise object with the new name
  3020. self.app.collection.promise(name)
  3021. # Background
  3022. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3023. else:
  3024. job_thread(app_obj=self.app)
  3025. def get_ncc_empty_area(self, target, boundary=None):
  3026. """
  3027. Returns the complement of target geometry within
  3028. the given boundary polygon. If not specified, it defaults to
  3029. the rectangular bounding box of target geometry.
  3030. :param target: The geometry that is to be 'inverted'
  3031. :param boundary: A polygon that surrounds the entire solid geometry and from which we subtract in order to
  3032. create a "negative" geometry (geometry to be emptied of copper)
  3033. :return:
  3034. """
  3035. if isinstance(target, Polygon):
  3036. geo_len = 1
  3037. else:
  3038. geo_len = len(target)
  3039. pol_nr = 0
  3040. old_disp_number = 0
  3041. if boundary is None:
  3042. boundary = target.envelope
  3043. else:
  3044. boundary = boundary
  3045. try:
  3046. ret_val = boundary.difference(target)
  3047. except Exception:
  3048. try:
  3049. for el in target:
  3050. # provide the app with a way to process the GUI events when in a blocking loop
  3051. QtWidgets.QApplication.processEvents()
  3052. if self.app.abort_flag:
  3053. # graceful abort requested by the user
  3054. raise grace
  3055. boundary = boundary.difference(el)
  3056. pol_nr += 1
  3057. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3058. if old_disp_number < disp_number <= 100:
  3059. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3060. old_disp_number = disp_number
  3061. return boundary
  3062. except Exception:
  3063. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3064. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  3065. "Reload the Gerber file after this change."))
  3066. return 'fail'
  3067. return ret_val
  3068. @staticmethod
  3069. def poly2rings(poly):
  3070. return [poly.exterior] + [interior for interior in poly.interiors]
  3071. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  3072. # isolation_geometry produces an envelope that is going on the left of the geometry
  3073. # (the copper features). To leave the least amount of burrs on the features
  3074. # the tool needs to travel on the right side of the features (this is called conventional milling)
  3075. # the first pass is the one cutting all of the features, so it needs to be reversed
  3076. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  3077. # to cut on the right side of the left over copper i.e on the left side of the features.
  3078. try:
  3079. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  3080. except Exception as e:
  3081. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  3082. return 'fail'
  3083. if invert:
  3084. try:
  3085. try:
  3086. pl = []
  3087. for p in geom:
  3088. if p is not None:
  3089. if isinstance(p, Polygon):
  3090. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3091. elif isinstance(p, LinearRing):
  3092. pl.append(Polygon(p.coords[::-1]))
  3093. geom = MultiPolygon(pl)
  3094. except TypeError:
  3095. if isinstance(geom, Polygon) and geom is not None:
  3096. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3097. elif isinstance(geom, LinearRing) and geom is not None:
  3098. geom = Polygon(geom.coords[::-1])
  3099. else:
  3100. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  3101. type(geom))
  3102. except Exception as e:
  3103. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  3104. return 'fail'
  3105. return geom
  3106. def on_ncc_tool_add_from_db_executed(self, tool):
  3107. """
  3108. Here add the tool from DB in the selected geometry object
  3109. :return:
  3110. """
  3111. tool_from_db = deepcopy(tool)
  3112. if tool['data']['tool_target'] != _("NCC"):
  3113. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  3114. return
  3115. res = self.on_ncc_tool_from_db_inserted(tool=tool_from_db)
  3116. for idx in range(self.app.ui.plot_tab_area.count()):
  3117. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3118. wdg = self.app.ui.plot_tab_area.widget(idx)
  3119. wdg.deleteLater()
  3120. self.app.ui.plot_tab_area.removeTab(idx)
  3121. if res == 'fail':
  3122. return
  3123. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  3124. # select last tool added
  3125. toolid = res
  3126. for row in range(self.ui.tools_table.rowCount()):
  3127. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  3128. self.ui.tools_table.selectRow(row)
  3129. self.on_row_selection_change()
  3130. def on_ncc_tool_from_db_inserted(self, tool):
  3131. """
  3132. Called from the Tools DB object through a App method when adding a tool from Tools Database
  3133. :param tool: a dict with the tool data
  3134. :return: None
  3135. """
  3136. self.ui_disconnect()
  3137. self.units = self.app.defaults['units'].upper()
  3138. tooldia = float(tool['tooldia'])
  3139. # construct a list of all 'tooluid' in the self.tools
  3140. tool_uid_list = [int(tooluid_key) for tooluid_key in self.ncc_tools]
  3141. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3142. max_uid = 0 if not tool_uid_list else max(tool_uid_list)
  3143. tooluid = max_uid + 1
  3144. tool_dias = []
  3145. for k, v in self.ncc_tools.items():
  3146. for tool_v in v.keys():
  3147. if tool_v == 'tooldia':
  3148. tool_dias.append(self.app.dec_format(v[tool_v], self.decimals))
  3149. truncated_tooldia = self.app.dec_format(tooldia, self.decimals)
  3150. if truncated_tooldia in tool_dias:
  3151. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  3152. self.ui_connect()
  3153. return 'fail'
  3154. self.ncc_tools.update({
  3155. tooluid: {
  3156. 'tooldia': truncated_tooldia,
  3157. 'offset': deepcopy(tool['offset']),
  3158. 'offset_value': deepcopy(tool['offset_value']),
  3159. 'type': deepcopy(tool['type']),
  3160. 'tool_type': deepcopy(tool['tool_type']),
  3161. 'data': deepcopy(tool['data']),
  3162. 'solid_geometry': []
  3163. }
  3164. })
  3165. self.ncc_tools[tooluid]['data']['name'] = '_ncc'
  3166. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  3167. self.ui_connect()
  3168. self.build_ui()
  3169. # select the tool just added
  3170. for row in range(self.ui.tools_table.rowCount()):
  3171. if int(self.ui.tools_table.item(row, 3).text()) == self.tooluid:
  3172. self.ui.tools_table.selectRow(row)
  3173. break
  3174. def on_ncc_tool_add_from_db_clicked(self):
  3175. """
  3176. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  3177. and display the Tools Database tab in the form needed for the Tool adding
  3178. :return: None
  3179. """
  3180. # if the Tools Database is already opened focus on it
  3181. for idx in range(self.app.ui.plot_tab_area.count()):
  3182. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3183. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  3184. break
  3185. self.app.on_tools_database(source='ncc')
  3186. self.app.tools_db_tab.ok_to_add = True
  3187. self.app.tools_db_tab.ui.buttons_frame.hide()
  3188. self.app.tools_db_tab.ui.add_tool_from_db.show()
  3189. self.app.tools_db_tab.ui.cancel_tool_from_db.show()
  3190. def reset_fields(self):
  3191. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3192. class NccUI:
  3193. toolName = _("Non-Copper Clearing")
  3194. def __init__(self, layout, app):
  3195. self.app = app
  3196. self.decimals = self.app.decimals
  3197. self.layout = layout
  3198. self.tools_frame = QtWidgets.QFrame()
  3199. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  3200. self.layout.addWidget(self.tools_frame)
  3201. self.tools_box = QtWidgets.QVBoxLayout()
  3202. self.tools_box.setContentsMargins(0, 0, 0, 0)
  3203. self.tools_frame.setLayout(self.tools_box)
  3204. # ## Title
  3205. title_label = FCLabel("%s" % self.toolName)
  3206. title_label.setStyleSheet("""
  3207. QLabel
  3208. {
  3209. font-size: 16px;
  3210. font-weight: bold;
  3211. }
  3212. """)
  3213. self.tools_box.addWidget(title_label)
  3214. # ## Form Layout
  3215. form_layout = QtWidgets.QFormLayout()
  3216. self.tools_box.addLayout(form_layout)
  3217. self.type_obj_combo_label = FCLabel('%s:' % _("Obj Type"))
  3218. self.type_obj_combo_label.setToolTip(
  3219. _("Specify the type of object to be cleared of excess copper.\n"
  3220. "It can be of type: Gerber or Geometry.\n"
  3221. "What is selected here will dictate the kind\n"
  3222. "of objects that will populate the 'Object' combobox.")
  3223. )
  3224. self.type_obj_combo_label.setMinimumWidth(60)
  3225. self.type_obj_radio = RadioSet([{'label': _("Geometry"), 'value': 'geometry'},
  3226. {'label': _("Gerber"), 'value': 'gerber'}])
  3227. form_layout.addRow(self.type_obj_combo_label, self.type_obj_radio)
  3228. # ################################################
  3229. # ##### The object to be copper cleaned ##########
  3230. # ################################################
  3231. self.object_combo = FCComboBox()
  3232. self.object_combo.setModel(self.app.collection)
  3233. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3234. # self.object_combo.setCurrentIndex(1)
  3235. self.object_combo.is_last = True
  3236. self.object_label = FCLabel('%s:' % _("Object"))
  3237. self.object_label.setToolTip(_("Object to be cleared of excess copper."))
  3238. form_layout.addRow(self.object_label, self.object_combo)
  3239. separator_line = QtWidgets.QFrame()
  3240. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3241. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3242. self.tools_box.addWidget(separator_line)
  3243. # ### Tools ## ##
  3244. self.tools_table_label = FCLabel('<b>%s</b>' % _('Tools Table'))
  3245. self.tools_table_label.setToolTip(
  3246. _("Tools pool from which the algorithm\n"
  3247. "will pick the ones used for copper clearing.")
  3248. )
  3249. self.tools_box.addWidget(self.tools_table_label)
  3250. self.tools_table = FCTable(drag_drop=True)
  3251. self.tools_box.addWidget(self.tools_table)
  3252. self.tools_table.setColumnCount(4)
  3253. # 3rd column is reserved (and hidden) for the tool ID
  3254. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  3255. self.tools_table.setColumnHidden(3, True)
  3256. self.tools_table.setSortingEnabled(False)
  3257. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  3258. self.tools_table.horizontalHeaderItem(0).setToolTip(
  3259. _("This is the Tool Number.\n"
  3260. "Non copper clearing will start with the tool with the biggest \n"
  3261. "diameter, continuing until there are no more tools.\n"
  3262. "Only tools that create NCC clearing geometry will still be present\n"
  3263. "in the resulting geometry. This is because with some tools\n"
  3264. "this function will not be able to create painting geometry.")
  3265. )
  3266. self.tools_table.horizontalHeaderItem(1).setToolTip(
  3267. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  3268. "is the cut width into the material."))
  3269. self.tools_table.horizontalHeaderItem(2).setToolTip(
  3270. _("The Tool Type (TT) can be:\n"
  3271. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  3272. "the cut width in material is exactly the tool diameter.\n"
  3273. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  3274. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  3275. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  3276. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  3277. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  3278. "column of this table.\n"
  3279. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  3280. "in the resulting geometry as Isolation."))
  3281. # self.tools_table.horizontalHeaderItem(4).setToolTip(
  3282. # _("The 'Operation' can be:\n"
  3283. # "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  3284. # "If it's not successful then the non-copper clearing will fail, too.\n"
  3285. # "- Clear -> the regular non-copper clearing."))
  3286. grid1 = QtWidgets.QGridLayout()
  3287. self.tools_box.addLayout(grid1)
  3288. grid1.setColumnStretch(0, 0)
  3289. grid1.setColumnStretch(1, 1)
  3290. # Tool order
  3291. self.ncc_order_label = FCLabel('%s:' % _('Tool order'))
  3292. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  3293. "'No' --> means that the used order is the one in the tool table\n"
  3294. "'Forward' --> means that the tools will be ordered from small to big\n"
  3295. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  3296. "WARNING: using rest machining will automatically set the order\n"
  3297. "in reverse and disable this control."))
  3298. self.ncc_order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  3299. {'label': _('Forward'), 'value': 'fwd'},
  3300. {'label': _('Reverse'), 'value': 'rev'}])
  3301. self.ncc_order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  3302. "'No' --> means that the used order is the one in the tool table\n"
  3303. "'Forward' --> means that the tools will be ordered from small to big\n"
  3304. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  3305. "WARNING: using rest machining will automatically set the order\n"
  3306. "in reverse and disable this control."))
  3307. grid1.addWidget(self.ncc_order_label, 1, 0)
  3308. grid1.addWidget(self.ncc_order_radio, 1, 1)
  3309. separator_line = QtWidgets.QFrame()
  3310. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3311. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3312. grid1.addWidget(separator_line, 2, 0, 1, 2)
  3313. # #############################################################
  3314. # ############### Tool selection ##############################
  3315. # #############################################################
  3316. self.grid3 = QtWidgets.QGridLayout()
  3317. self.tools_box.addLayout(self.grid3)
  3318. self.grid3.setColumnStretch(0, 0)
  3319. self.grid3.setColumnStretch(1, 1)
  3320. self.tool_sel_label = FCLabel('<b>%s</b>' % _('Add from DB'))
  3321. self.grid3.addWidget(self.tool_sel_label, 0, 0, 1, 2)
  3322. # ### Tool Diameter ####
  3323. self.new_tooldia_lbl = FCLabel('%s:' % _('Tool Dia'))
  3324. self.new_tooldia_lbl.setToolTip(
  3325. _("Diameter for the new tool")
  3326. )
  3327. self.grid3.addWidget(self.new_tooldia_lbl, 2, 0)
  3328. new_tool_lay = QtWidgets.QHBoxLayout()
  3329. self.new_tooldia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3330. self.new_tooldia_entry.set_precision(self.decimals)
  3331. self.new_tooldia_entry.set_range(0.000, 9999.9999)
  3332. self.new_tooldia_entry.setObjectName(_("Tool Dia"))
  3333. new_tool_lay.addWidget(self.new_tooldia_entry)
  3334. # Find Optimal Tooldia
  3335. self.find_optimal_button = QtWidgets.QToolButton()
  3336. self.find_optimal_button.setText(_('Optimal'))
  3337. self.find_optimal_button.setIcon(QtGui.QIcon(self.app.resource_location + '/open_excellon32.png'))
  3338. self.find_optimal_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
  3339. self.find_optimal_button.setToolTip(
  3340. _("Find a tool diameter that is guaranteed\n"
  3341. "to do a complete isolation.")
  3342. )
  3343. new_tool_lay.addWidget(self.find_optimal_button)
  3344. self.grid3.addLayout(new_tool_lay, 2, 1)
  3345. hlay = QtWidgets.QHBoxLayout()
  3346. self.add_newtool_button = FCButton(_('Search and Add'))
  3347. self.add_newtool_button.setIcon(QtGui.QIcon(self.app.resource_location + '/plus16.png'))
  3348. self.add_newtool_button.setToolTip(
  3349. _("Add a new tool to the Tool Table\n"
  3350. "with the diameter specified above.\n"
  3351. "This is done by a background search\n"
  3352. "in the Tools Database. If nothing is found\n"
  3353. "in the Tools DB then a default tool is added.")
  3354. )
  3355. hlay.addWidget(self.add_newtool_button)
  3356. self.addtool_from_db_btn = FCButton(_('Pick from DB'))
  3357. self.addtool_from_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/search_db32.png'))
  3358. self.addtool_from_db_btn.setToolTip(
  3359. _("Add a new tool to the Tool Table\n"
  3360. "from the Tools Database.\n"
  3361. "Tools database administration in in:\n"
  3362. "Menu: Options -> Tools Database")
  3363. )
  3364. hlay.addWidget(self.addtool_from_db_btn)
  3365. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  3366. separator_line = QtWidgets.QFrame()
  3367. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3368. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3369. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  3370. self.deltool_btn = FCButton(_('Delete'))
  3371. self.deltool_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/trash16.png'))
  3372. self.deltool_btn.setToolTip(
  3373. _("Delete a selection of tools in the Tool Table\n"
  3374. "by first selecting a row(s) in the Tool Table.")
  3375. )
  3376. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  3377. # self.grid3.addWidget(FCLabel(''), 10, 0, 1, 2)
  3378. separator_line = QtWidgets.QFrame()
  3379. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3380. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3381. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  3382. self.tool_data_label = FCLabel(
  3383. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  3384. self.tool_data_label.setToolTip(
  3385. _(
  3386. "The data used for creating GCode.\n"
  3387. "Each tool store it's own set of such data."
  3388. )
  3389. )
  3390. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  3391. # Operation
  3392. op_label = FCLabel('%s:' % _('Operation'))
  3393. op_label.setToolTip(
  3394. _("The 'Operation' can be:\n"
  3395. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  3396. "If it's not successful then the non-copper clearing will fail, too.\n"
  3397. "- Clear -> the regular non-copper clearing.")
  3398. )
  3399. self.op_radio = RadioSet([
  3400. {"label": _("Clear"), "value": "clear"},
  3401. {"label": _("Isolation"), "value": "iso"}
  3402. ], orientation='horizontal', stretch=False)
  3403. self.op_radio.setObjectName("n_operation")
  3404. self.grid3.addWidget(op_label, 13, 0)
  3405. self.grid3.addWidget(self.op_radio, 13, 1)
  3406. # Milling Type Radio Button
  3407. self.milling_type_label = FCLabel('%s:' % _('Milling Type'))
  3408. self.milling_type_label.setToolTip(
  3409. _("Milling type when the selected tool is of type: 'iso_op':\n"
  3410. "- climb / best for precision milling and to reduce tool usage\n"
  3411. "- conventional / useful when there is no backlash compensation")
  3412. )
  3413. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  3414. {'label': _('Conventional'), 'value': 'cv'}])
  3415. self.milling_type_radio.setToolTip(
  3416. _("Milling type when the selected tool is of type: 'iso_op':\n"
  3417. "- climb / best for precision milling and to reduce tool usage\n"
  3418. "- conventional / useful when there is no backlash compensation")
  3419. )
  3420. self.milling_type_radio.setObjectName("n_milling_type")
  3421. self.milling_type_label.setEnabled(False)
  3422. self.milling_type_radio.setEnabled(False)
  3423. self.grid3.addWidget(self.milling_type_label, 14, 0)
  3424. self.grid3.addWidget(self.milling_type_radio, 14, 1)
  3425. # Overlap Entry
  3426. self.nccoverlabel = FCLabel('%s:' % _('Overlap'))
  3427. self.nccoverlabel.setToolTip(
  3428. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  3429. "Adjust the value starting with lower values\n"
  3430. "and increasing it if areas that should be cleared are still \n"
  3431. "not cleared.\n"
  3432. "Lower values = faster processing, faster execution on CNC.\n"
  3433. "Higher values = slow processing and slow execution on CNC\n"
  3434. "due of too many paths.")
  3435. )
  3436. self.ncc_overlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  3437. self.ncc_overlap_entry.set_precision(self.decimals)
  3438. self.ncc_overlap_entry.setWrapping(True)
  3439. self.ncc_overlap_entry.setRange(0.000, 99.9999)
  3440. self.ncc_overlap_entry.setSingleStep(0.1)
  3441. self.ncc_overlap_entry.setObjectName("n_overlap")
  3442. self.grid3.addWidget(self.nccoverlabel, 15, 0)
  3443. self.grid3.addWidget(self.ncc_overlap_entry, 15, 1)
  3444. # Method
  3445. self.methodlabel = FCLabel('%s:' % _('Method'))
  3446. self.methodlabel.setToolTip(
  3447. _("Algorithm for copper clearing:\n"
  3448. "- Standard: Fixed step inwards.\n"
  3449. "- Seed-based: Outwards from seed.\n"
  3450. "- Line-based: Parallel lines.")
  3451. )
  3452. # self.ncc_method_radio = RadioSet([
  3453. # {"label": _("Standard"), "value": "standard"},
  3454. # {"label": _("Seed-based"), "value": "seed"},
  3455. # {"label": _("Straight lines"), "value": "lines"}
  3456. # ], orientation='vertical', stretch=False)
  3457. self.ncc_method_combo = FCComboBox()
  3458. self.ncc_method_combo.addItems(
  3459. [_("Standard"), _("Seed"), _("Lines"), _("Combo")]
  3460. )
  3461. self.ncc_method_combo.setObjectName("n_method")
  3462. self.grid3.addWidget(self.methodlabel, 16, 0)
  3463. self.grid3.addWidget(self.ncc_method_combo, 16, 1)
  3464. # Margin
  3465. self.nccmarginlabel = FCLabel('%s:' % _('Margin'))
  3466. self.nccmarginlabel.setToolTip(
  3467. _("Bounding box margin.")
  3468. )
  3469. self.ncc_margin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3470. self.ncc_margin_entry.set_precision(self.decimals)
  3471. self.ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  3472. self.ncc_margin_entry.setObjectName("n_margin")
  3473. self.grid3.addWidget(self.nccmarginlabel, 17, 0)
  3474. self.grid3.addWidget(self.ncc_margin_entry, 17, 1)
  3475. # Connect lines
  3476. self.ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  3477. self.ncc_connect_cb.setObjectName("n_connect")
  3478. self.ncc_connect_cb.setToolTip(
  3479. _("Draw lines between resulting\n"
  3480. "segments to minimize tool lifts.")
  3481. )
  3482. self.grid3.addWidget(self.ncc_connect_cb, 18, 0)
  3483. # Contour
  3484. self.ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  3485. self.ncc_contour_cb.setObjectName("n_contour")
  3486. self.ncc_contour_cb.setToolTip(
  3487. _("Cut around the perimeter of the polygon\n"
  3488. "to trim rough edges.")
  3489. )
  3490. self.grid3.addWidget(self.ncc_contour_cb, 18, 1)
  3491. # ## NCC Offset choice
  3492. self.ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  3493. self.ncc_choice_offset_cb.setObjectName("n_offset")
  3494. self.ncc_choice_offset_cb.setToolTip(
  3495. _("If used, it will add an offset to the copper features.\n"
  3496. "The copper clearing will finish to a distance\n"
  3497. "from the copper features.\n"
  3498. "The value can be between 0 and 10 FlatCAM units.")
  3499. )
  3500. self.grid3.addWidget(self.ncc_choice_offset_cb, 19, 0)
  3501. # ## NCC Offset Entry
  3502. self.ncc_offset_spinner = FCDoubleSpinner(callback=self.confirmation_message)
  3503. self.ncc_offset_spinner.set_range(0.00, 10.00)
  3504. self.ncc_offset_spinner.set_precision(4)
  3505. self.ncc_offset_spinner.setWrapping(True)
  3506. self.ncc_offset_spinner.setObjectName("n_offset_value")
  3507. units = self.app.defaults['units'].upper()
  3508. if units == 'MM':
  3509. self.ncc_offset_spinner.setSingleStep(0.1)
  3510. else:
  3511. self.ncc_offset_spinner.setSingleStep(0.01)
  3512. self.grid3.addWidget(self.ncc_offset_spinner, 19, 1)
  3513. self.ois_ncc_offset = OptionalInputSection(self.ncc_choice_offset_cb, [self.ncc_offset_spinner])
  3514. separator_line = QtWidgets.QFrame()
  3515. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3516. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3517. self.grid3.addWidget(separator_line, 21, 0, 1, 2)
  3518. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  3519. self.apply_param_to_all.setIcon(QtGui.QIcon(self.app.resource_location + '/param_all32.png'))
  3520. self.apply_param_to_all.setToolTip(
  3521. _("The parameters in the current form will be applied\n"
  3522. "on all the tools from the Tool Table.")
  3523. )
  3524. self.grid3.addWidget(self.apply_param_to_all, 22, 0, 1, 2)
  3525. separator_line = QtWidgets.QFrame()
  3526. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3527. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3528. self.grid3.addWidget(separator_line, 23, 0, 1, 2)
  3529. # General Parameters
  3530. self.gen_param_label = FCLabel('<b>%s</b>' % _("Common Parameters"))
  3531. self.gen_param_label.setToolTip(
  3532. _("Parameters that are common for all tools.")
  3533. )
  3534. self.grid3.addWidget(self.gen_param_label, 24, 0, 1, 2)
  3535. # Rest Machining
  3536. self.ncc_rest_cb = FCCheckBox('%s' % _("Rest"))
  3537. self.ncc_rest_cb.setObjectName("n_rest_machining")
  3538. self.ncc_rest_cb.setToolTip(
  3539. _("If checked, use 'rest machining'.\n"
  3540. "Basically it will clear copper outside PCB features,\n"
  3541. "using the biggest tool and continue with the next tools,\n"
  3542. "from bigger to smaller, to clear areas of copper that\n"
  3543. "could not be cleared by previous tool, until there is\n"
  3544. "no more copper to clear or there are no more tools.\n"
  3545. "If not checked, use the standard algorithm.")
  3546. )
  3547. self.grid3.addWidget(self.ncc_rest_cb, 25, 0, 1, 2)
  3548. # Rest Margin
  3549. self.rest_nccmarginlabel = FCLabel('%s:' % _('Margin'))
  3550. self.rest_nccmarginlabel.setToolTip(
  3551. _("Bounding box margin.")
  3552. )
  3553. self.rest_ncc_margin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3554. self.rest_ncc_margin_entry.set_precision(self.decimals)
  3555. self.rest_ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  3556. self.rest_ncc_margin_entry.setObjectName("n_margin")
  3557. self.grid3.addWidget(self.rest_nccmarginlabel, 26, 0)
  3558. self.grid3.addWidget(self.rest_ncc_margin_entry, 26, 1)
  3559. # Rest Connect lines
  3560. self.rest_ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  3561. self.rest_ncc_connect_cb.setToolTip(
  3562. _("Draw lines between resulting\n"
  3563. "segments to minimize tool lifts.")
  3564. )
  3565. self.grid3.addWidget(self.rest_ncc_connect_cb, 27, 0)
  3566. # Rest Contour
  3567. self.rest_ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  3568. self.rest_ncc_contour_cb.setToolTip(
  3569. _("Cut around the perimeter of the polygon\n"
  3570. "to trim rough edges.")
  3571. )
  3572. self.grid3.addWidget(self.rest_ncc_contour_cb, 27, 1)
  3573. # ## Rest NCC Offset choice
  3574. self.rest_ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  3575. self.rest_ncc_choice_offset_cb.setToolTip(
  3576. _("If used, it will add an offset to the copper features.\n"
  3577. "The copper clearing will finish to a distance\n"
  3578. "from the copper features.\n"
  3579. "The value can be between 0 and 10 FlatCAM units.")
  3580. )
  3581. self.grid3.addWidget(self.rest_ncc_choice_offset_cb, 28, 0)
  3582. # ## Rest NCC Offset Entry
  3583. self.rest_ncc_offset_spinner = FCDoubleSpinner(callback=self.confirmation_message)
  3584. self.rest_ncc_offset_spinner.set_range(0.00, 10.00)
  3585. self.rest_ncc_offset_spinner.set_precision(4)
  3586. self.rest_ncc_offset_spinner.setWrapping(True)
  3587. units = self.app.defaults['units'].upper()
  3588. if units == 'MM':
  3589. self.rest_ncc_offset_spinner.setSingleStep(0.1)
  3590. else:
  3591. self.rest_ncc_offset_spinner.setSingleStep(0.01)
  3592. self.grid3.addWidget(self.rest_ncc_offset_spinner, 28, 1)
  3593. self.rest_ois_ncc_offset = OptionalInputSection(self.rest_ncc_choice_offset_cb, [self.rest_ncc_offset_spinner])
  3594. # ## Reference
  3595. # self.select_radio = RadioSet([
  3596. # {'label': _('Itself'), 'value': 'itself'},
  3597. # {"label": _("Area Selection"), "value": "area"},
  3598. # {'label': _("Reference Object"), 'value': 'box'}
  3599. # ], orientation='vertical', stretch=False)
  3600. self.select_combo = FCComboBox()
  3601. self.select_combo.addItems(
  3602. [_("Itself"), _("Area Selection"), _("Reference Object")]
  3603. )
  3604. self.select_combo.setObjectName("n_selection")
  3605. self.select_label = FCLabel('%s:' % _("Selection"))
  3606. self.select_label.setToolTip(
  3607. _("Selection of area to be processed.\n"
  3608. "- 'Itself' - the processing extent is based on the object that is processed.\n "
  3609. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  3610. "- 'Reference Object' - will process the area specified by another object.")
  3611. )
  3612. self.grid3.addWidget(self.select_label, 29, 0, )
  3613. self.grid3.addWidget(self.select_combo, 29, 1)
  3614. form1 = QtWidgets.QFormLayout()
  3615. self.grid3.addLayout(form1, 30, 0, 1, 2)
  3616. self.reference_combo_type_label = FCLabel('%s:' % _("Ref. Type"))
  3617. self.reference_combo_type_label.setToolTip(
  3618. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  3619. "It can be Gerber, Excellon or Geometry.")
  3620. )
  3621. self.reference_combo_type = FCComboBox()
  3622. self.reference_combo_type.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  3623. form1.addRow(self.reference_combo_type_label, self.reference_combo_type)
  3624. self.reference_combo_label = FCLabel('%s:' % _("Ref. Object"))
  3625. self.reference_combo_label.setToolTip(
  3626. _("The FlatCAM object to be used as non copper clearing reference.")
  3627. )
  3628. self.reference_combo = FCComboBox()
  3629. self.reference_combo.setModel(self.app.collection)
  3630. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3631. self.reference_combo.is_last = True
  3632. form1.addRow(self.reference_combo_label, self.reference_combo)
  3633. self.reference_combo.hide()
  3634. self.reference_combo_label.hide()
  3635. self.reference_combo_type.hide()
  3636. self.reference_combo_type_label.hide()
  3637. # Area Selection shape
  3638. self.area_shape_label = FCLabel('%s:' % _("Shape"))
  3639. self.area_shape_label.setToolTip(
  3640. _("The kind of selection shape used for area selection.")
  3641. )
  3642. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  3643. {'label': _("Polygon"), 'value': 'polygon'}])
  3644. self.grid3.addWidget(self.area_shape_label, 31, 0)
  3645. self.grid3.addWidget(self.area_shape_radio, 31, 1)
  3646. self.area_shape_label.hide()
  3647. self.area_shape_radio.hide()
  3648. # Check Tool validity
  3649. self.valid_cb = FCCheckBox(label=_('Check validity'))
  3650. self.valid_cb.setToolTip(
  3651. _("If checked then the tools diameters are verified\n"
  3652. "if they will provide a complete isolation.")
  3653. )
  3654. self.valid_cb.setObjectName("n_check")
  3655. self.grid3.addWidget(self.valid_cb, 33, 0, 1, 2)
  3656. separator_line = QtWidgets.QFrame()
  3657. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3658. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3659. self.grid3.addWidget(separator_line, 35, 0, 1, 2)
  3660. self.generate_ncc_button = FCButton(_('Generate Geometry'))
  3661. self.generate_ncc_button.setIcon(QtGui.QIcon(self.app.resource_location + '/geometry32.png'))
  3662. self.generate_ncc_button.setToolTip(
  3663. _("Create the Geometry Object\n"
  3664. "for non-copper routing.")
  3665. )
  3666. self.generate_ncc_button.setStyleSheet("""
  3667. QPushButton
  3668. {
  3669. font-weight: bold;
  3670. }
  3671. """)
  3672. self.tools_box.addWidget(self.generate_ncc_button)
  3673. self.tools_box.addStretch()
  3674. # ## Reset Tool
  3675. self.reset_button = FCButton(_("Reset Tool"))
  3676. self.reset_button.setIcon(QtGui.QIcon(self.app.resource_location + '/reset32.png'))
  3677. self.reset_button.setToolTip(
  3678. _("Will reset the tool parameters.")
  3679. )
  3680. self.reset_button.setStyleSheet("""
  3681. QPushButton
  3682. {
  3683. font-weight: bold;
  3684. }
  3685. """)
  3686. self.tools_box.addWidget(self.reset_button)
  3687. # ############################ FINSIHED GUI ###################################
  3688. # #############################################################################
  3689. def parameters_ui(self, val):
  3690. if val == 'iso':
  3691. self.milling_type_label.setEnabled(True)
  3692. self.milling_type_radio.setEnabled(True)
  3693. self.nccoverlabel.setEnabled(False)
  3694. self.ncc_overlap_entry.setEnabled(False)
  3695. self.methodlabel.setEnabled(False)
  3696. self.ncc_method_combo.setEnabled(False)
  3697. self.nccmarginlabel.setEnabled(False)
  3698. self.ncc_margin_entry.setEnabled(False)
  3699. self.ncc_connect_cb.setEnabled(False)
  3700. self.ncc_contour_cb.setEnabled(False)
  3701. self.ncc_choice_offset_cb.setEnabled(False)
  3702. self.ncc_offset_spinner.setEnabled(False)
  3703. else:
  3704. self.milling_type_label.setEnabled(False)
  3705. self.milling_type_radio.setEnabled(False)
  3706. self.nccoverlabel.setEnabled(True)
  3707. self.ncc_overlap_entry.setEnabled(True)
  3708. self.methodlabel.setEnabled(True)
  3709. self.ncc_method_combo.setEnabled(True)
  3710. self.nccmarginlabel.setEnabled(True)
  3711. self.ncc_margin_entry.setEnabled(True)
  3712. self.ncc_connect_cb.setEnabled(True)
  3713. self.ncc_contour_cb.setEnabled(True)
  3714. self.ncc_choice_offset_cb.setEnabled(True)
  3715. self.ncc_offset_spinner.setEnabled(True)
  3716. def on_toggle_reference(self):
  3717. sel_combo = self.select_combo.get_value()
  3718. if sel_combo == _("Itself"):
  3719. self.reference_combo.hide()
  3720. self.reference_combo_label.hide()
  3721. self.reference_combo_type.hide()
  3722. self.reference_combo_type_label.hide()
  3723. self.area_shape_label.hide()
  3724. self.area_shape_radio.hide()
  3725. # disable rest-machining for area painting
  3726. self.ncc_rest_cb.setDisabled(False)
  3727. elif sel_combo == _("Area Selection"):
  3728. self.reference_combo.hide()
  3729. self.reference_combo_label.hide()
  3730. self.reference_combo_type.hide()
  3731. self.reference_combo_type_label.hide()
  3732. self.area_shape_label.show()
  3733. self.area_shape_radio.show()
  3734. # disable rest-machining for area painting
  3735. # self.ncc_rest_cb.set_value(False)
  3736. # self.ncc_rest_cb.setDisabled(True)
  3737. else:
  3738. self.reference_combo.show()
  3739. self.reference_combo_label.show()
  3740. self.reference_combo_type.show()
  3741. self.reference_combo_type_label.show()
  3742. self.area_shape_label.hide()
  3743. self.area_shape_radio.hide()
  3744. # disable rest-machining for area painting
  3745. self.ncc_rest_cb.setDisabled(False)
  3746. def on_rest_machining_check(self, state):
  3747. if state:
  3748. self.ncc_order_radio.set_value('rev')
  3749. self.ncc_order_label.setDisabled(True)
  3750. self.ncc_order_radio.setDisabled(True)
  3751. self.nccmarginlabel.hide()
  3752. self.ncc_margin_entry.hide()
  3753. self.ncc_connect_cb.hide()
  3754. self.ncc_contour_cb.hide()
  3755. self.ncc_choice_offset_cb.hide()
  3756. self.ncc_offset_spinner.hide()
  3757. self.rest_nccmarginlabel.show()
  3758. self.rest_ncc_margin_entry.show()
  3759. self.rest_ncc_connect_cb.show()
  3760. self.rest_ncc_contour_cb.show()
  3761. self.rest_ncc_choice_offset_cb.show()
  3762. self.rest_ncc_offset_spinner.show()
  3763. else:
  3764. self.ncc_order_label.setDisabled(False)
  3765. self.ncc_order_radio.setDisabled(False)
  3766. self.nccmarginlabel.show()
  3767. self.ncc_margin_entry.show()
  3768. self.ncc_connect_cb.show()
  3769. self.ncc_contour_cb.show()
  3770. self.ncc_choice_offset_cb.show()
  3771. self.ncc_offset_spinner.show()
  3772. self.rest_nccmarginlabel.hide()
  3773. self.rest_ncc_margin_entry.hide()
  3774. self.rest_ncc_connect_cb.hide()
  3775. self.rest_ncc_contour_cb.hide()
  3776. self.rest_ncc_choice_offset_cb.hide()
  3777. self.rest_ncc_offset_spinner.hide()
  3778. def confirmation_message(self, accepted, minval, maxval):
  3779. if accepted is False:
  3780. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  3781. self.decimals,
  3782. minval,
  3783. self.decimals,
  3784. maxval), False)
  3785. else:
  3786. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  3787. def confirmation_message_int(self, accepted, minval, maxval):
  3788. if accepted is False:
  3789. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  3790. (_("Edited value is out of range"), minval, maxval), False)
  3791. else:
  3792. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)