ToolNCC.py 206 KB

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