ToolNCC.py 202 KB

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