ToolNCC.py 209 KB

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