ToolNCC.py 199 KB

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