ToolNCC.py 213 KB

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