ToolNCC.py 198 KB

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