ToolNCC.py 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125
  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.set_tool_ui)
  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. except Exception:
  424. dias = []
  425. self.tooluid = 0
  426. self.ncc_tools.clear()
  427. for tool_dia in dias:
  428. self.tooluid += 1
  429. self.ncc_tools.update({
  430. int(self.tooluid): {
  431. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  432. 'offset': 'Path',
  433. 'offset_value': 0.0,
  434. 'type': 'Iso',
  435. 'tool_type': self.app.defaults["tools_ncctool_type"],
  436. 'data': deepcopy(self.default_data),
  437. 'solid_geometry': []
  438. }
  439. })
  440. self.obj_name = ""
  441. self.ncc_obj = None
  442. self.bound_obj_name = ""
  443. self.bound_obj = None
  444. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  445. self.units = self.app.defaults['units'].upper()
  446. self.first_click = False
  447. self.cursor_pos = None
  448. self.mouse_is_dragging = False
  449. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  450. if prog_plot:
  451. self.temp_shapes.clear(update=True)
  452. self.sel_rect = []
  453. def build_ui(self):
  454. self.ui_disconnect()
  455. # updated units
  456. self.units = self.app.defaults['units'].upper()
  457. sorted_tools = []
  458. for k, v in self.ncc_tools.items():
  459. if self.units == "IN":
  460. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  461. else:
  462. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  463. order = self.ui.ncc_order_radio.get_value()
  464. if order == 'fwd':
  465. sorted_tools.sort(reverse=False)
  466. elif order == 'rev':
  467. sorted_tools.sort(reverse=True)
  468. else:
  469. pass
  470. n = len(sorted_tools)
  471. self.ui.tools_table.setRowCount(n)
  472. tool_id = 0
  473. for tool_sorted in sorted_tools:
  474. for tooluid_key, tooluid_value in self.ncc_tools.items():
  475. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  476. tool_id += 1
  477. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  478. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  479. row_no = tool_id - 1
  480. self.ui.tools_table.setItem(row_no, 0, id_) # Tool name/id
  481. # Make sure that the drill diameter when in MM is with no more than self.decimals decimals
  482. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  483. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  484. self.ui.tools_table.setItem(row_no, 1, dia) # Diameter
  485. tool_type_item = FCComboBox()
  486. tool_type_item.addItems(self.tool_type_item_options)
  487. idx = tool_type_item.findText(tooluid_value['tool_type'])
  488. tool_type_item.setCurrentIndex(idx)
  489. self.ui.tools_table.setCellWidget(row_no, 2, tool_type_item)
  490. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  491. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  492. self.ui.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  493. # make the diameter column editable
  494. for row in range(tool_id):
  495. self.ui.tools_table.item(row, 1).setFlags(
  496. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  497. # all the tools are selected by default
  498. self.ui.tools_table.selectColumn(0)
  499. #
  500. self.ui.tools_table.resizeColumnsToContents()
  501. self.ui.tools_table.resizeRowsToContents()
  502. vertical_header = self.ui.tools_table.verticalHeader()
  503. vertical_header.hide()
  504. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  505. horizontal_header = self.ui.tools_table.horizontalHeader()
  506. horizontal_header.setMinimumSectionSize(10)
  507. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  508. horizontal_header.resizeSection(0, 20)
  509. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  510. # self.ui.tools_table.setSortingEnabled(True)
  511. # sort by tool diameter
  512. # self.ui.tools_table.sortItems(1)
  513. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  514. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  515. self.ui_connect()
  516. # set the text on tool_data_label after loading the object
  517. sel_rows = []
  518. sel_items = self.ui.tools_table.selectedItems()
  519. for it in sel_items:
  520. sel_rows.append(it.row())
  521. if len(sel_rows) > 1:
  522. self.ui.tool_data_label.setText(
  523. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  524. )
  525. def ui_connect(self):
  526. self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  527. # rows selected
  528. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  529. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  530. for row in range(self.ui.tools_table.rowCount()):
  531. try:
  532. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  533. except AttributeError:
  534. pass
  535. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type)
  536. for opt in self.form_fields:
  537. current_widget = self.form_fields[opt]
  538. if isinstance(current_widget, FCCheckBox):
  539. current_widget.stateChanged.connect(self.form_to_storage)
  540. if isinstance(current_widget, RadioSet):
  541. current_widget.activated_custom.connect(self.form_to_storage)
  542. elif isinstance(current_widget, FCDoubleSpinner):
  543. current_widget.returnPressed.connect(self.form_to_storage)
  544. elif isinstance(current_widget, FCComboBox):
  545. current_widget.currentIndexChanged.connect(self.form_to_storage)
  546. self.ui.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  547. self.ui.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  548. def ui_disconnect(self):
  549. try:
  550. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  551. self.ui.tools_table.itemChanged.disconnect()
  552. except (TypeError, AttributeError):
  553. pass
  554. try:
  555. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  556. self.ui.tool_type_radio.activated_custom.disconnect()
  557. except (TypeError, AttributeError):
  558. pass
  559. for row in range(self.ui.tools_table.rowCount()):
  560. try:
  561. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  562. except (TypeError, AttributeError):
  563. pass
  564. for opt in self.form_fields:
  565. current_widget = self.form_fields[opt]
  566. if isinstance(current_widget, FCCheckBox):
  567. try:
  568. current_widget.stateChanged.disconnect(self.form_to_storage)
  569. except (TypeError, ValueError):
  570. pass
  571. if isinstance(current_widget, RadioSet):
  572. try:
  573. current_widget.activated_custom.disconnect(self.form_to_storage)
  574. except (TypeError, ValueError):
  575. pass
  576. elif isinstance(current_widget, FCDoubleSpinner):
  577. try:
  578. current_widget.returnPressed.disconnect(self.form_to_storage)
  579. except (TypeError, ValueError):
  580. pass
  581. elif isinstance(current_widget, FCComboBox):
  582. try:
  583. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  584. except (TypeError, ValueError):
  585. pass
  586. try:
  587. self.ui.ncc_rest_cb.stateChanged.disconnect()
  588. except (TypeError, ValueError):
  589. pass
  590. try:
  591. self.ui.ncc_order_radio.activated_custom[str].disconnect()
  592. except (TypeError, ValueError):
  593. pass
  594. # rows selected
  595. try:
  596. self.ui.tools_table.clicked.disconnect()
  597. except (TypeError, AttributeError):
  598. pass
  599. try:
  600. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  601. except (TypeError, AttributeError):
  602. pass
  603. def on_tooldia_updated(self):
  604. if self.ui.tool_type_radio.get_value() == 'C1':
  605. self.old_tool_dia = self.ui.addtool_entry.get_value()
  606. def on_reference_combo_changed(self):
  607. obj_type = self.ui.reference_combo_type.currentIndex()
  608. self.ui.reference_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  609. self.ui.reference_combo.setCurrentIndex(0)
  610. self.ui.reference_combo.obj_type = {
  611. _("Gerber"): "Gerber", _("Excellon"): "Excellon", _("Geometry"): "Geometry"
  612. }[self.ui.reference_combo_type.get_value()]
  613. def on_toggle_reference(self):
  614. sel_combo = self.ui.select_combo.get_value()
  615. if sel_combo == _("Itself"):
  616. self.ui.reference_combo.hide()
  617. self.ui.reference_combo_label.hide()
  618. self.ui.reference_combo_type.hide()
  619. self.ui.reference_combo_type_label.hide()
  620. self.ui.area_shape_label.hide()
  621. self.ui.area_shape_radio.hide()
  622. # disable rest-machining for area painting
  623. self.ui.ncc_rest_cb.setDisabled(False)
  624. elif sel_combo == _("Area Selection"):
  625. self.ui.reference_combo.hide()
  626. self.ui.reference_combo_label.hide()
  627. self.ui.reference_combo_type.hide()
  628. self.ui.reference_combo_type_label.hide()
  629. self.ui.area_shape_label.show()
  630. self.ui.area_shape_radio.show()
  631. # disable rest-machining for area painting
  632. self.ui.ncc_rest_cb.set_value(False)
  633. self.ui.ncc_rest_cb.setDisabled(True)
  634. else:
  635. self.ui.reference_combo.show()
  636. self.ui.reference_combo_label.show()
  637. self.ui.reference_combo_type.show()
  638. self.ui.reference_combo_type_label.show()
  639. self.ui.area_shape_label.hide()
  640. self.ui.area_shape_radio.hide()
  641. # disable rest-machining for area painting
  642. self.ui.ncc_rest_cb.setDisabled(False)
  643. def on_order_changed(self, order):
  644. if order != 'no':
  645. self.build_ui()
  646. def on_rest_machining_check(self, state):
  647. if state:
  648. self.ui.ncc_order_radio.set_value('rev')
  649. self.ui.ncc_order_label.setDisabled(True)
  650. self.ui.ncc_order_radio.setDisabled(True)
  651. else:
  652. self.ui.ncc_order_label.setDisabled(False)
  653. self.ui.ncc_order_radio.setDisabled(False)
  654. def on_tooltable_cellwidget_change(self):
  655. cw = self.sender()
  656. assert isinstance(cw, QtWidgets.QComboBox),\
  657. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  658. cw_index = self.ui.tools_table.indexAt(cw.pos())
  659. cw_row = cw_index.row()
  660. cw_col = cw_index.column()
  661. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  662. # if the sender is in the column with index 2 then we update the tool_type key
  663. if cw_col == 2:
  664. tt = cw.currentText()
  665. typ = 'Iso' if tt == 'V' else "Rough"
  666. self.ncc_tools[current_uid].update({
  667. 'type': typ,
  668. 'tool_type': tt,
  669. })
  670. def on_tool_type(self, val):
  671. if val == 'V':
  672. self.ui.addtool_entry_lbl.setDisabled(True)
  673. self.ui.addtool_entry.setDisabled(True)
  674. self.ui.tipdialabel.show()
  675. self.ui.tipdia_entry.show()
  676. self.ui.tipanglelabel.show()
  677. self.ui.tipangle_entry.show()
  678. self.on_calculate_tooldia()
  679. else:
  680. self.ui.addtool_entry_lbl.setDisabled(False)
  681. self.ui.addtool_entry.setDisabled(False)
  682. self.ui.tipdialabel.hide()
  683. self.ui.tipdia_entry.hide()
  684. self.ui.tipanglelabel.hide()
  685. self.ui.tipangle_entry.hide()
  686. self.ui.addtool_entry.set_value(self.old_tool_dia)
  687. def on_calculate_tooldia(self):
  688. if self.ui.tool_type_radio.get_value() == 'V':
  689. tip_dia = float(self.ui.tipdia_entry.get_value())
  690. tip_angle = float(self.ui.tipangle_entry.get_value()) / 2.0
  691. cut_z = float(self.ui.cutz_entry.get_value())
  692. cut_z = -cut_z if cut_z < 0 else cut_z
  693. # calculated tool diameter so the cut_z parameter is obeyed
  694. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  695. # update the default_data so it is used in the ncc_tools dict
  696. self.default_data.update({
  697. "vtipdia": tip_dia,
  698. "vtipangle": (tip_angle * 2),
  699. })
  700. self.ui.addtool_entry.set_value(tool_dia)
  701. return tool_dia
  702. else:
  703. return float(self.ui.addtool_entry.get_value())
  704. def on_tool_add(self, dia=None, muted=None):
  705. self.blockSignals(True)
  706. self.units = self.app.defaults['units'].upper()
  707. if dia:
  708. tool_dia = dia
  709. else:
  710. tool_dia = self.on_calculate_tooldia()
  711. if tool_dia is None:
  712. self.build_ui()
  713. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  714. return
  715. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  716. if tool_dia == 0:
  717. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  718. "in Float format."))
  719. return
  720. # construct a list of all 'tooluid' in the self.tools
  721. tool_uid_list = []
  722. for tooluid_key in self.ncc_tools:
  723. tool_uid_item = int(tooluid_key)
  724. tool_uid_list.append(tool_uid_item)
  725. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  726. if not tool_uid_list:
  727. max_uid = 0
  728. else:
  729. max_uid = max(tool_uid_list)
  730. self.tooluid = int(max_uid + 1)
  731. tool_dias = []
  732. for k, v in self.ncc_tools.items():
  733. for tool_v in v.keys():
  734. if tool_v == 'tooldia':
  735. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  736. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  737. if muted is None:
  738. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  739. # self.ui.tools_table.itemChanged.connect(self.on_tool_edit)
  740. self.blockSignals(False)
  741. return
  742. else:
  743. if muted is None:
  744. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  745. self.ncc_tools.update({
  746. int(self.tooluid): {
  747. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  748. 'offset': 'Path',
  749. 'offset_value': 0.0,
  750. 'type': 'Iso',
  751. 'tool_type': self.app.defaults["tools_ncctool_type"],
  752. 'data': deepcopy(self.default_data),
  753. 'solid_geometry': []
  754. }
  755. })
  756. self.blockSignals(False)
  757. self.build_ui()
  758. def on_tool_edit(self, item):
  759. self.blockSignals(True)
  760. edited_row = item.row()
  761. editeduid = int(self.ui.tools_table.item(edited_row, 3).text())
  762. tool_dias = []
  763. try:
  764. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text())
  765. except ValueError:
  766. # try to convert comma to decimal point. if it's still not working error message and return
  767. try:
  768. new_tool_dia = float(self.ui.tools_table.item(edited_row, 1).text().replace(',', '.'))
  769. except ValueError:
  770. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  771. self.blockSignals(False)
  772. return
  773. for v in self.ncc_tools.values():
  774. tool_dias = [float('%.*f' % (self.decimals, v[tool_v])) for tool_v in v.keys() if tool_v == 'tooldia']
  775. # identify the tool that was edited and get it's tooluid
  776. if new_tool_dia not in tool_dias:
  777. self.ncc_tools[editeduid]['tooldia'] = deepcopy(float('%.*f' % (self.decimals, new_tool_dia)))
  778. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  779. self.blockSignals(False)
  780. self.build_ui()
  781. return
  782. # identify the old tool_dia and restore the text in tool table
  783. for k, v in self.ncc_tools.items():
  784. if k == editeduid:
  785. old_tool_dia = v['tooldia']
  786. restore_dia_item = self.ui.tools_table.item(edited_row, 1)
  787. restore_dia_item.setText(str(old_tool_dia))
  788. break
  789. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. New diameter value is already in the Tool Table."))
  790. self.blockSignals(False)
  791. self.build_ui()
  792. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  793. """
  794. Will delete a tool in the tool table
  795. :param rows_to_delete: which rows to delete; can be a list
  796. :param all_tools: delete all tools in the tool table
  797. :return:
  798. """
  799. self.blockSignals(True)
  800. deleted_tools_list = []
  801. if all_tools:
  802. self.ncc_tools.clear()
  803. self.blockSignals(False)
  804. self.build_ui()
  805. return
  806. if rows_to_delete:
  807. try:
  808. for row in rows_to_delete:
  809. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  810. deleted_tools_list.append(tooluid_del)
  811. except TypeError:
  812. tooluid_del = int(self.ui.tools_table.item(rows_to_delete, 3).text())
  813. deleted_tools_list.append(tooluid_del)
  814. for t in deleted_tools_list:
  815. self.ncc_tools.pop(t, None)
  816. self.blockSignals(False)
  817. self.build_ui()
  818. return
  819. try:
  820. if self.ui.tools_table.selectedItems():
  821. for row_sel in self.ui.tools_table.selectedItems():
  822. row = row_sel.row()
  823. if row < 0:
  824. continue
  825. tooluid_del = int(self.ui.tools_table.item(row, 3).text())
  826. deleted_tools_list.append(tooluid_del)
  827. for t in deleted_tools_list:
  828. self.ncc_tools.pop(t, None)
  829. except AttributeError:
  830. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  831. self.blockSignals(False)
  832. return
  833. except Exception as e:
  834. log.debug(str(e))
  835. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  836. self.blockSignals(False)
  837. self.build_ui()
  838. def on_ncc_click(self):
  839. """
  840. Slot for clicking signal of the self.generate.ncc_button
  841. :return: None
  842. """
  843. self.app.defaults.report_usage("on_ncc_click")
  844. self.first_click = False
  845. self.cursor_pos = None
  846. self.mouse_is_dragging = False
  847. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  848. if prog_plot:
  849. self.temp_shapes.clear(update=True)
  850. self.sel_rect = []
  851. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  852. self.obj_name = self.ui.object_combo.currentText()
  853. # Get source object.
  854. try:
  855. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  856. except Exception as e:
  857. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  858. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  859. if self.ncc_obj is None:
  860. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  861. return
  862. # use the selected tools in the tool table; get diameters for isolation
  863. self.iso_dia_list = []
  864. # use the selected tools in the tool table; get diameters for non-copper clear
  865. self.ncc_dia_list = []
  866. if self.ui.tools_table.selectedItems():
  867. for x in self.ui.tools_table.selectedItems():
  868. try:
  869. self.tooldia = float(self.ui.tools_table.item(x.row(), 1).text())
  870. except ValueError:
  871. # try to convert comma to decimal point. if it's still not working error message and return
  872. try:
  873. self.tooldia = float(self.ui.tools_table.item(x.row(), 1).text().replace(',', '.'))
  874. except ValueError:
  875. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong Tool Dia value format entered, "
  876. "use a number."))
  877. continue
  878. # find out which tools is for isolation and which are for copper clearing
  879. for uid_k, uid_v in self.ncc_tools.items():
  880. if round(uid_v['tooldia'], self.decimals) == round(self.tooldia, self.decimals):
  881. if uid_v['data']['tools_nccoperation'] == "iso":
  882. self.iso_dia_list.append(self.tooldia)
  883. else:
  884. self.ncc_dia_list.append(self.tooldia)
  885. else:
  886. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  887. return
  888. self.o_name = '%s_ncc' % self.obj_name
  889. self.select_method = self.ui.select_combo.get_value()
  890. if self.select_method == _('Itself'):
  891. self.bound_obj_name = self.ui.object_combo.currentText()
  892. # Get source object.
  893. try:
  894. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  895. except Exception as e:
  896. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  897. return "Could not retrieve object: %s with error: %s" % (self.bound_obj_name, str(e))
  898. self.clear_copper(ncc_obj=self.ncc_obj,
  899. ncctooldia=self.ncc_dia_list,
  900. isotooldia=self.iso_dia_list,
  901. outname=self.o_name,
  902. tools_storage=self.ncc_tools)
  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: only this area is kept
  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' or empty.is_empty:
  1256. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1257. self.app.inform.emit(msg)
  1258. return 'fail'
  1259. elif ncc_obj.kind == 'gerber' and isotooldia:
  1260. isolated_geo = []
  1261. # unfortunately for this function to work time efficient,
  1262. # if the Gerber was loaded without buffering then it require the buffering now.
  1263. # TODO 'buffering status' should be a property of the object not the project property
  1264. if self.app.defaults['gerber_buffering'] == 'no':
  1265. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1266. else:
  1267. self.solid_geometry = ncc_obj.solid_geometry
  1268. # if milling type is climb then the move is counter-clockwise around features
  1269. milling_type = self.ui.milling_type_radio.get_value()
  1270. for tool_iso in isotooldia:
  1271. new_geometry = []
  1272. if milling_type == 'cl':
  1273. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1274. else:
  1275. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1276. if isolated_geo == 'fail' or isolated_geo.is_empty:
  1277. self.app.inform.emit('[ERROR_NOTCL] %s %s' %
  1278. (_("Isolation geometry could not be generated."), str(tool_iso)))
  1279. continue
  1280. if ncc_margin < tool_iso:
  1281. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1282. "than isolation tool diameter."))
  1283. try:
  1284. for geo_elem in isolated_geo:
  1285. # provide the app with a way to process the GUI events when in a blocking loop
  1286. QtWidgets.QApplication.processEvents()
  1287. if self.app.abort_flag:
  1288. # graceful abort requested by the user
  1289. raise grace
  1290. if isinstance(geo_elem, Polygon):
  1291. for ring in self.poly2rings(geo_elem):
  1292. new_geo = ring.intersection(bounding_box)
  1293. if new_geo and not new_geo.is_empty:
  1294. new_geometry.append(new_geo)
  1295. elif isinstance(geo_elem, MultiPolygon):
  1296. for poly in geo_elem:
  1297. for ring in self.poly2rings(poly):
  1298. new_geo = ring.intersection(bounding_box)
  1299. if new_geo and not new_geo.is_empty:
  1300. new_geometry.append(new_geo)
  1301. elif isinstance(geo_elem, LineString):
  1302. new_geo = geo_elem.intersection(bounding_box)
  1303. if new_geo:
  1304. if not new_geo.is_empty:
  1305. new_geometry.append(new_geo)
  1306. elif isinstance(geo_elem, MultiLineString):
  1307. for line_elem in geo_elem:
  1308. new_geo = line_elem.intersection(bounding_box)
  1309. if new_geo and not new_geo.is_empty:
  1310. new_geometry.append(new_geo)
  1311. except TypeError:
  1312. if isinstance(isolated_geo, Polygon):
  1313. for ring in self.poly2rings(isolated_geo):
  1314. new_geo = ring.intersection(bounding_box)
  1315. if new_geo:
  1316. if not new_geo.is_empty:
  1317. new_geometry.append(new_geo)
  1318. elif isinstance(isolated_geo, LineString):
  1319. new_geo = isolated_geo.intersection(bounding_box)
  1320. if new_geo and not new_geo.is_empty:
  1321. new_geometry.append(new_geo)
  1322. elif isinstance(isolated_geo, MultiLineString):
  1323. for line_elem in isolated_geo:
  1324. new_geo = line_elem.intersection(bounding_box)
  1325. if new_geo and not new_geo.is_empty:
  1326. new_geometry.append(new_geo)
  1327. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1328. for geo_e in new_geometry:
  1329. if type(geo_e) == MultiLineString:
  1330. warning_flag += 1
  1331. break
  1332. for k, v in tools_storage.items():
  1333. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1334. tool_iso)):
  1335. current_uid = int(k)
  1336. # add the solid_geometry to the current too in self.paint_tools dictionary
  1337. # and then reset the temporary list that stored that solid_geometry
  1338. v['solid_geometry'] = deepcopy(new_geometry)
  1339. v['data']['name'] = name
  1340. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1341. break
  1342. sol_geo = cascaded_union(isolated_geo)
  1343. if has_offset is True:
  1344. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1345. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1346. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1347. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1348. if empty == 'fail' or empty.is_empty:
  1349. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1350. self.app.inform.emit(msg)
  1351. return 'fail'
  1352. elif ncc_obj.kind == 'geometry':
  1353. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1354. if has_offset is True:
  1355. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1356. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1357. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1358. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1359. if empty == 'fail' or empty.is_empty:
  1360. msg = '[ERROR_NOTCL] %s' % _("Could not get the extent of the area to be non copper cleared.")
  1361. self.app.inform.emit(msg)
  1362. return 'fail'
  1363. else:
  1364. self.app.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  1365. return 'fail'
  1366. if type(empty) is Polygon:
  1367. empty = MultiPolygon([empty])
  1368. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1369. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1370. return empty, warning_flag
  1371. def clear_polygon_worker(self, pol, tooldia, ncc_method, ncc_overlap, ncc_connect, ncc_contour, prog_plot):
  1372. cp = None
  1373. if ncc_method == _("Standard"):
  1374. try:
  1375. cp = self.clear_polygon(pol, tooldia,
  1376. steps_per_circle=self.grb_circle_steps,
  1377. overlap=ncc_overlap, contour=ncc_contour,
  1378. connect=ncc_connect,
  1379. prog_plot=prog_plot)
  1380. except grace:
  1381. return "fail"
  1382. except Exception as ee:
  1383. log.debug("NonCopperClear.clear_polygon_worker() Standard --> %s" % str(ee))
  1384. elif ncc_method == _("Seed"):
  1385. try:
  1386. cp = self.clear_polygon2(pol, tooldia,
  1387. steps_per_circle=self.grb_circle_steps,
  1388. overlap=ncc_overlap, contour=ncc_contour,
  1389. connect=ncc_connect,
  1390. prog_plot=prog_plot)
  1391. except grace:
  1392. return "fail"
  1393. except Exception as ee:
  1394. log.debug("NonCopperClear.clear_polygon_worker() Seed --> %s" % str(ee))
  1395. elif ncc_method == _("Lines"):
  1396. try:
  1397. cp = self.clear_polygon3(pol, tooldia,
  1398. steps_per_circle=self.grb_circle_steps,
  1399. overlap=ncc_overlap, contour=ncc_contour,
  1400. connect=ncc_connect,
  1401. prog_plot=prog_plot)
  1402. except grace:
  1403. return "fail"
  1404. except Exception as ee:
  1405. log.debug("NonCopperClear.clear_polygon_worker() Lines --> %s" % str(ee))
  1406. elif ncc_method == _("Combo"):
  1407. try:
  1408. self.app.inform.emit(_("Clearing the polygon with the method: lines."))
  1409. cp = self.clear_polygon3(pol, tooldia,
  1410. steps_per_circle=self.grb_circle_steps,
  1411. overlap=ncc_overlap, contour=ncc_contour,
  1412. connect=ncc_connect,
  1413. prog_plot=prog_plot)
  1414. if cp and cp.objects:
  1415. pass
  1416. else:
  1417. self.app.inform.emit(_("Failed. Clearing the polygon with the method: seed."))
  1418. cp = self.clear_polygon2(pol, tooldia,
  1419. steps_per_circle=self.grb_circle_steps,
  1420. overlap=ncc_overlap, contour=ncc_contour,
  1421. connect=ncc_connect,
  1422. prog_plot=prog_plot)
  1423. if cp and cp.objects:
  1424. pass
  1425. else:
  1426. self.app.inform.emit(_("Failed. Clearing the polygon with the method: standard."))
  1427. cp = self.clear_polygon(pol, tooldia,
  1428. steps_per_circle=self.grb_circle_steps,
  1429. overlap=ncc_overlap, contour=ncc_contour,
  1430. connect=ncc_connect,
  1431. prog_plot=prog_plot)
  1432. except grace:
  1433. return "fail"
  1434. except Exception as ee:
  1435. log.debug("NonCopperClear.clear_polygon_worker() Combo --> %s" % str(ee))
  1436. if cp and cp.objects:
  1437. return list(cp.get_objects())
  1438. else:
  1439. self.app.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be cleared completely'))
  1440. return None
  1441. def clear_copper(self, ncc_obj, ncctooldia, isotooldia, sel_obj=None, outname=None, order=None,
  1442. tools_storage=None, run_threaded=True):
  1443. """
  1444. Clear the excess copper from the entire object.
  1445. :param ncc_obj: ncc cleared object
  1446. :type ncc_obj: appObjects.FlatCAMGerber.GerberObject
  1447. :param ncctooldia: a list of diameters of the tools to be used to ncc clear
  1448. :type ncctooldia: list
  1449. :param isotooldia: a list of diameters of the tools to be used for isolation
  1450. :type isotooldia: list
  1451. :param sel_obj:
  1452. :type sel_obj:
  1453. :param outname: name of the resulting object
  1454. :type outname: str
  1455. :param order: Tools order
  1456. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1457. Usage of the different one is related to when this function is called
  1458. from a TcL command.
  1459. :type tools_storage: dict
  1460. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False
  1461. it will run non-threaded for TclShell usage
  1462. :type run_threaded: bool
  1463. :return:
  1464. """
  1465. log.debug("Executing the handler ...")
  1466. if run_threaded:
  1467. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1468. else:
  1469. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1470. QtWidgets.QApplication.processEvents()
  1471. # ######################################################################################################
  1472. # ######################### Read the parameters ########################################################
  1473. # ######################################################################################################
  1474. units = self.app.defaults['units']
  1475. order = order if order else self.ui.ncc_order_radio.get_value()
  1476. ncc_select = self.ui.select_combo.get_value()
  1477. rest_machining_choice = self.ui.ncc_rest_cb.get_value()
  1478. # determine if to use the progressive plotting
  1479. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  1480. tools_storage = tools_storage if tools_storage is not None else self.ncc_tools
  1481. sorted_clear_tools = ncctooldia
  1482. if not sorted_clear_tools:
  1483. self.app.inform.emit('[ERROR_NOTCL] %s' % _("There is no copper clearing tool in the selection "
  1484. "and at least one is needed."))
  1485. return 'fail'
  1486. # ########################################################################################################
  1487. # set the name for the future Geometry object
  1488. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1489. # ########################################################################################################
  1490. name = outname if outname is not None else self.obj_name + "_ncc"
  1491. # ########################################################################################################
  1492. # ######### #####Initializes the new geometry object #####################################################
  1493. # ########################################################################################################
  1494. def gen_clear_area(geo_obj, app_obj):
  1495. log.debug("NCC Tool. Normal copper clearing task started.")
  1496. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1497. # provide the app with a way to process the GUI events when in a blocking loop
  1498. if not run_threaded:
  1499. QtWidgets.QApplication.processEvents()
  1500. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1501. # will store the number of tools for which the isolation is broken
  1502. warning_flag = 0
  1503. tool = None
  1504. if order == 'fwd':
  1505. sorted_clear_tools.sort(reverse=False)
  1506. elif order == 'rev':
  1507. sorted_clear_tools.sort(reverse=True)
  1508. else:
  1509. pass
  1510. app_obj.poly_not_cleared = False # flag for polygons not cleared
  1511. if ncc_select == _("Reference Object"):
  1512. bbox_geo, bbox_kind = self.calculate_bounding_box(
  1513. ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1514. else:
  1515. bbox_geo, bbox_kind = self.calculate_bounding_box(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1516. if bbox_geo is None and bbox_kind is None:
  1517. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1518. return "fail"
  1519. # COPPER CLEARING with tools marked for CLEAR#
  1520. for tool in sorted_clear_tools:
  1521. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1522. if self.app.abort_flag:
  1523. # graceful abort requested by the user
  1524. raise grace
  1525. # provide the app with a way to process the GUI events when in a blocking loop
  1526. if not run_threaded:
  1527. QtWidgets.QApplication.processEvents()
  1528. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1529. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1530. )
  1531. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1532. # store here the geometry generated by clear operation
  1533. cleared_geo = []
  1534. tool_uid = 0 # find the current tool_uid
  1535. for k, v in self.ncc_tools.items():
  1536. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1537. tool_uid = int(k)
  1538. break
  1539. # parameters that are particular to the current tool
  1540. ncc_overlap = float(self.ncc_tools[tool_uid]["data"]["tools_nccoverlap"]) / 100.0
  1541. ncc_margin = float(self.ncc_tools[tool_uid]["data"]["tools_nccmargin"])
  1542. ncc_method = self.ncc_tools[tool_uid]["data"]["tools_nccmethod"]
  1543. ncc_connect = self.ncc_tools[tool_uid]["data"]["tools_nccconnect"]
  1544. ncc_contour = self.ncc_tools[tool_uid]["data"]["tools_ncccontour"]
  1545. has_offset = self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_choice"]
  1546. ncc_offset = float(self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_value"])
  1547. # Bounding box for current tool
  1548. bbox = self.apply_margin_to_bounding_box(bbox=bbox_geo, box_kind=bbox_kind,
  1549. ncc_select=ncc_select, ncc_margin=ncc_margin)
  1550. # Area to clear
  1551. area, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1552. isotooldia=isotooldia, ncc_margin=ncc_margin,
  1553. has_offset=has_offset, ncc_offset=ncc_offset,
  1554. tools_storage=tools_storage, bounding_box=bbox)
  1555. # Transform area to MultiPolygon
  1556. if isinstance(area, Polygon):
  1557. area = MultiPolygon([area])
  1558. # variables to display the percentage of work done
  1559. geo_len = len(area.geoms)
  1560. old_disp_number = 0
  1561. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1562. if area.geoms:
  1563. if len(area.geoms) > 0:
  1564. pol_nr = 0
  1565. for p in area.geoms:
  1566. # provide the app with a way to process the GUI events when in a blocking loop
  1567. if not run_threaded:
  1568. QtWidgets.QApplication.processEvents()
  1569. if self.app.abort_flag:
  1570. # graceful abort requested by the user
  1571. raise grace
  1572. # clean the polygon
  1573. p = p.buffer(0)
  1574. if p is not None and p.is_valid:
  1575. poly_failed = 0
  1576. try:
  1577. for pol in p:
  1578. if pol is not None and isinstance(pol, Polygon):
  1579. res = self.clear_polygon_worker(pol=pol, tooldia=tool,
  1580. ncc_method=ncc_method,
  1581. ncc_overlap=ncc_overlap,
  1582. ncc_connect=ncc_connect,
  1583. ncc_contour=ncc_contour,
  1584. prog_plot=prog_plot)
  1585. if res is not None:
  1586. cleared_geo += res
  1587. else:
  1588. poly_failed += 1
  1589. else:
  1590. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(pol)))
  1591. except TypeError:
  1592. if isinstance(p, Polygon):
  1593. res = self.clear_polygon_worker(pol=p, tooldia=tool,
  1594. ncc_method=ncc_method,
  1595. ncc_overlap=ncc_overlap,
  1596. ncc_connect=ncc_connect,
  1597. ncc_contour=ncc_contour,
  1598. prog_plot=prog_plot)
  1599. if res is not None:
  1600. cleared_geo += res
  1601. else:
  1602. poly_failed += 1
  1603. else:
  1604. log.warning("Expected geo is a Polygon. Instead got a %s" % str(type(p)))
  1605. if poly_failed > 0:
  1606. app_obj.poly_not_cleared = True
  1607. pol_nr += 1
  1608. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1609. # log.debug("Polygons cleared: %d" % pol_nr)
  1610. if old_disp_number < disp_number <= 100:
  1611. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1612. old_disp_number = disp_number
  1613. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1614. # check if there is a geometry at all in the cleared geometry
  1615. if cleared_geo:
  1616. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1617. # solid_geometry
  1618. for k, v in tools_storage.items():
  1619. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1620. tool)):
  1621. current_uid = int(k)
  1622. # add the solid_geometry to the current too in self.paint_tools dictionary
  1623. # and then reset the temporary list that stored that solid_geometry
  1624. v['solid_geometry'] = deepcopy(cleared_geo)
  1625. v['data']['name'] = name
  1626. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1627. break
  1628. else:
  1629. log.debug("There are no geometries in the cleared polygon.")
  1630. # clean the progressive plotted shapes if it was used
  1631. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1632. self.temp_shapes.clear(update=True)
  1633. # delete tools with empty geometry
  1634. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1635. for uid, uid_val in list(tools_storage.items()):
  1636. try:
  1637. # if the solid_geometry (type=list) is empty
  1638. if not uid_val['solid_geometry']:
  1639. msg = '%s %s: %s %s: %s' % (
  1640. _("Could not use the tool for copper clear."),
  1641. _("Tool"),
  1642. str(uid),
  1643. _("with diameter"),
  1644. str(uid_val['tooldia']))
  1645. self.app.inform.emit(msg)
  1646. log.debug("Empty geometry for tool: %s with diameter: %s" % (str(uid), str(uid_val['tooldia'])))
  1647. tools_storage.pop(uid, None)
  1648. except KeyError:
  1649. tools_storage.pop(uid, None)
  1650. geo_obj.options["cnctooldia"] = str(tool)
  1651. geo_obj.multigeo = True
  1652. geo_obj.tools = dict(tools_storage)
  1653. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1654. has_solid_geo = 0
  1655. for tid in geo_obj.tools:
  1656. if geo_obj.tools[tid]['solid_geometry']:
  1657. has_solid_geo += 1
  1658. if has_solid_geo == 0:
  1659. msg = '[ERROR] %s' % _("There is no NCC Geometry in the file.\n"
  1660. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1661. "Change the painting parameters and try again.")
  1662. app_obj.inform.emit(msg)
  1663. return 'fail'
  1664. # check to see if geo_obj.tools is empty
  1665. # it will be updated only if there is a solid_geometry for tools
  1666. if geo_obj.tools:
  1667. if warning_flag == 0:
  1668. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1669. else:
  1670. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1671. _("NCC Tool clear all done but the copper features isolation is broken for"),
  1672. str(warning_flag),
  1673. _("tools")))
  1674. return
  1675. # create the solid_geometry
  1676. geo_obj.solid_geometry = []
  1677. for tool_id in geo_obj.tools:
  1678. if geo_obj.tools[tool_id]['solid_geometry']:
  1679. try:
  1680. for geo in geo_obj.tools[tool_id]['solid_geometry']:
  1681. geo_obj.solid_geometry.append(geo)
  1682. except TypeError:
  1683. geo_obj.solid_geometry.append(geo_obj.tools[tool_id]['solid_geometry'])
  1684. else:
  1685. # I will use this variable for this purpose although it was meant for something else
  1686. # signal that we have no geo in the object therefore don't create it
  1687. app_obj.poly_not_cleared = False
  1688. return "fail"
  1689. # # Experimental...
  1690. # # print("Indexing...", end=' ')
  1691. # # geo_obj.make_index()
  1692. # ###########################################################################################
  1693. # Initializes the new geometry object for the case of the rest-machining ####################
  1694. # ###########################################################################################
  1695. def gen_clear_area_rest(geo_obj, app_obj):
  1696. assert geo_obj.kind == 'geometry', \
  1697. "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  1698. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1699. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1700. # provide the app with a way to process the GUI events when in a blocking loop
  1701. if not run_threaded:
  1702. QtWidgets.QApplication.processEvents()
  1703. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1704. # will store the number of tools for which the isolation is broken
  1705. warning_flag = 0
  1706. sorted_clear_tools.sort(reverse=True)
  1707. cleared_geo = []
  1708. cleared_by_last_tool = []
  1709. rest_geo = []
  1710. current_uid = 1
  1711. try:
  1712. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1713. except TypeError:
  1714. tool = eval(self.app.defaults["tools_ncctools"])
  1715. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1716. app_obj.poly_not_cleared = True
  1717. if ncc_select == _("Reference Object"):
  1718. env_obj, box_obj_kind = self.calculate_bounding_box(
  1719. ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1720. else:
  1721. env_obj, box_obj_kind = self.calculate_bounding_box(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1722. if env_obj is None and box_obj_kind is None:
  1723. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1724. return "fail"
  1725. log.debug("NCC Tool. Calculate 'empty' area.")
  1726. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1727. # Generate area for each tool
  1728. while sorted_clear_tools:
  1729. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1730. if self.app.abort_flag:
  1731. # graceful abort requested by the user
  1732. raise grace
  1733. # provide the app with a way to process the GUI events when in a blocking loop
  1734. QtWidgets.QApplication.processEvents()
  1735. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1736. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1737. )
  1738. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1739. tool = sorted_clear_tools.pop(0)
  1740. tool_uid = 0
  1741. for k, v in self.ncc_tools.items():
  1742. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1743. tool_uid = int(k)
  1744. break
  1745. ncc_overlap = float(self.ncc_tools[tool_uid]["data"]["tools_nccoverlap"]) / 100.0
  1746. ncc_margin = float(self.ncc_tools[tool_uid]["data"]["tools_nccmargin"])
  1747. ncc_method = self.ncc_tools[tool_uid]["data"]["tools_nccmethod"]
  1748. ncc_connect = self.ncc_tools[tool_uid]["data"]["tools_nccconnect"]
  1749. ncc_contour = self.ncc_tools[tool_uid]["data"]["tools_ncccontour"]
  1750. has_offset = self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_choice"]
  1751. ncc_offset = float(self.ncc_tools[tool_uid]["data"]["tools_ncc_offset_value"])
  1752. tool_used = tool - 1e-12
  1753. cleared_geo[:] = []
  1754. # Bounding box for current tool
  1755. bbox = self.apply_margin_to_bounding_box(bbox=env_obj, box_kind=box_obj_kind,
  1756. ncc_select=ncc_select, ncc_margin=ncc_margin)
  1757. # Area to clear
  1758. empty, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1759. isotooldia=isotooldia,
  1760. has_offset=has_offset, ncc_offset=ncc_offset,
  1761. ncc_margin=ncc_margin, tools_storage=tools_storage,
  1762. bounding_box=bbox)
  1763. area = empty.buffer(0)
  1764. # Area to clear
  1765. for poly in cleared_by_last_tool:
  1766. # provide the app with a way to process the GUI events when in a blocking loop
  1767. QtWidgets.QApplication.processEvents()
  1768. if self.app.abort_flag:
  1769. # graceful abort requested by the user
  1770. raise grace
  1771. try:
  1772. area = area.difference(poly)
  1773. except Exception:
  1774. pass
  1775. cleared_by_last_tool[:] = []
  1776. # Transform area to MultiPolygon
  1777. if type(area) is Polygon:
  1778. area = MultiPolygon([area])
  1779. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1780. # and rest_geo it's a list
  1781. allparts = [p.buffer(0) for p in area.geoms]
  1782. allparts += deepcopy(rest_geo)
  1783. rest_geo[:] = []
  1784. area = MultiPolygon(deepcopy(allparts))
  1785. allparts[:] = []
  1786. # variables to display the percentage of work done
  1787. geo_len = len(area.geoms)
  1788. old_disp_number = 0
  1789. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1790. if area.geoms:
  1791. if len(area.geoms) > 0:
  1792. pol_nr = 0
  1793. for p in area.geoms:
  1794. if self.app.abort_flag:
  1795. # graceful abort requested by the user
  1796. raise grace
  1797. # clean the polygon
  1798. p = p.buffer(0)
  1799. if p is not None and p.is_valid:
  1800. # provide the app with a way to process the GUI events when in a blocking loop
  1801. QtWidgets.QApplication.processEvents()
  1802. if isinstance(p, Polygon):
  1803. try:
  1804. if ncc_method == _("Standard"):
  1805. cp = self.clear_polygon(p, tool_used,
  1806. self.grb_circle_steps,
  1807. overlap=ncc_overlap, contour=ncc_contour,
  1808. connect=ncc_connect,
  1809. prog_plot=prog_plot)
  1810. elif ncc_method == _("Seed"):
  1811. cp = self.clear_polygon2(p, tool_used,
  1812. self.grb_circle_steps,
  1813. overlap=ncc_overlap, contour=ncc_contour,
  1814. connect=ncc_connect,
  1815. prog_plot=prog_plot)
  1816. else:
  1817. cp = self.clear_polygon3(p, tool_used,
  1818. self.grb_circle_steps,
  1819. overlap=ncc_overlap, contour=ncc_contour,
  1820. connect=ncc_connect,
  1821. prog_plot=prog_plot)
  1822. cleared_geo.append(list(cp.get_objects()))
  1823. except Exception as e:
  1824. log.warning("Polygon can't be cleared. %s" % str(e))
  1825. # this polygon should be added to a list and then try clear it with
  1826. # a smaller tool
  1827. rest_geo.append(p)
  1828. elif isinstance(p, MultiPolygon):
  1829. for poly in p:
  1830. if poly is not None:
  1831. # provide the app with a way to process the GUI events when
  1832. # in a blocking loop
  1833. QtWidgets.QApplication.processEvents()
  1834. try:
  1835. if ncc_method == _("Standard"):
  1836. cp = self.clear_polygon(poly, tool_used,
  1837. self.grb_circle_steps,
  1838. overlap=ncc_overlap, contour=ncc_contour,
  1839. connect=ncc_connect,
  1840. prog_plot=prog_plot)
  1841. elif ncc_method == _("Seed"):
  1842. cp = self.clear_polygon2(poly, tool_used,
  1843. self.grb_circle_steps,
  1844. overlap=ncc_overlap, contour=ncc_contour,
  1845. connect=ncc_connect,
  1846. prog_plot=prog_plot)
  1847. else:
  1848. cp = self.clear_polygon3(poly, tool_used,
  1849. self.grb_circle_steps,
  1850. overlap=ncc_overlap, contour=ncc_contour,
  1851. connect=ncc_connect,
  1852. prog_plot=prog_plot)
  1853. cleared_geo.append(list(cp.get_objects()))
  1854. except Exception as e:
  1855. log.warning("Polygon can't be cleared. %s" % str(e))
  1856. # this polygon should be added to a list and then try clear it with
  1857. # a smaller tool
  1858. rest_geo.append(poly)
  1859. pol_nr += 1
  1860. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1861. # log.debug("Polygons cleared: %d" % pol_nr)
  1862. if old_disp_number < disp_number <= 100:
  1863. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1864. old_disp_number = disp_number
  1865. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1866. if self.app.abort_flag:
  1867. # graceful abort requested by the user
  1868. raise grace
  1869. # check if there is a geometry at all in the cleared geometry
  1870. if cleared_geo:
  1871. # Overall cleared area
  1872. cleared_area = list(self.flatten_list(cleared_geo))
  1873. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1874. # for p in cleared_area])
  1875. # here we store the poly's already processed in the original geometry by the current tool
  1876. # into cleared_by_last_tool list
  1877. # this will be sutracted from the original geometry_to_be_cleared and make data for
  1878. # the next tool
  1879. buffer_value = tool_used / 2
  1880. for p in cleared_area:
  1881. if self.app.abort_flag:
  1882. # graceful abort requested by the user
  1883. raise grace
  1884. poly = p.buffer(buffer_value)
  1885. cleared_by_last_tool.append(poly)
  1886. # find the tool uid associated with the current tool_dia so we know
  1887. # where to add the tool solid_geometry
  1888. for k, v in tools_storage.items():
  1889. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1890. tool)):
  1891. current_uid = int(k)
  1892. # add the solid_geometry to the current too in self.paint_tools dictionary
  1893. # and then reset the temporary list that stored that solid_geometry
  1894. v['solid_geometry'] = deepcopy(cleared_area)
  1895. v['data']['name'] = name
  1896. cleared_area[:] = []
  1897. break
  1898. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1899. else:
  1900. log.debug("There are no geometries in the cleared polygon.")
  1901. geo_obj.multigeo = True
  1902. geo_obj.options["cnctooldia"] = str(tool)
  1903. # clean the progressive plotted shapes if it was used
  1904. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1905. self.temp_shapes.clear(update=True)
  1906. # check to see if geo_obj.tools is empty
  1907. # it will be updated only if there is a solid_geometry for tools
  1908. if geo_obj.tools:
  1909. if warning_flag == 0:
  1910. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  1911. else:
  1912. self.app.inform.emit(
  1913. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  1914. "isolation is broken for"), str(warning_flag), _("tools")))
  1915. return
  1916. # create the solid_geometry
  1917. geo_obj.solid_geometry = []
  1918. for tool_uid in geo_obj.tools:
  1919. if geo_obj.tools[tool_uid]['solid_geometry']:
  1920. try:
  1921. for geo in geo_obj.tools[tool_uid]['solid_geometry']:
  1922. geo_obj.solid_geometry.append(geo)
  1923. except TypeError:
  1924. geo_obj.solid_geometry.append(geo_obj.tools[tool_uid]['solid_geometry'])
  1925. else:
  1926. # I will use this variable for this purpose although it was meant for something else
  1927. # signal that we have no geo in the object therefore don't create it
  1928. app_obj.poly_not_cleared = False
  1929. return "fail"
  1930. # ###########################################################################################
  1931. # Create the Job function and send it to the worker to be processed in another thread #######
  1932. # ###########################################################################################
  1933. def job_thread(a_obj):
  1934. try:
  1935. if rest_machining_choice is True:
  1936. a_obj.app_obj.new_object("geometry", name, gen_clear_area_rest)
  1937. else:
  1938. a_obj.app_obj.new_object("geometry", name, gen_clear_area)
  1939. except grace:
  1940. if run_threaded:
  1941. proc.done()
  1942. return
  1943. except Exception:
  1944. if run_threaded:
  1945. proc.done()
  1946. traceback.print_stack()
  1947. return
  1948. if run_threaded:
  1949. proc.done()
  1950. else:
  1951. a_obj.proc_container.view.set_idle()
  1952. # focus on Selected Tab
  1953. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1954. if run_threaded:
  1955. # Promise object with the new name
  1956. self.app.collection.promise(name)
  1957. # Background
  1958. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1959. else:
  1960. job_thread(app_obj=self.app)
  1961. def clear_copper_tcl(self, ncc_obj, sel_obj=None, ncctooldia=None, isotooldia=None, margin=None, has_offset=None,
  1962. offset=None, select_method=None, outname=None, overlap=None, connect=None, contour=None,
  1963. order=None, method=None, rest=None, tools_storage=None, plot=True, run_threaded=False):
  1964. """
  1965. Clear the excess copper from the entire object. To be used only in a TCL command.
  1966. :param ncc_obj: ncc cleared object
  1967. :param sel_obj:
  1968. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1969. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1970. :param overlap: value by which the paths will overlap
  1971. :param order: if the tools are ordered and how
  1972. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  1973. another object
  1974. :param has_offset: True if an offset is needed
  1975. :param offset: distance from the copper features where the copper clearing is stopping
  1976. :param margin: a border around cleared area
  1977. :param outname: name of the resulting object
  1978. :param connect: Connect lines to avoid tool lifts.
  1979. :param contour: Clear around the edges.
  1980. :param method: choice out of 'seed', 'normal', 'lines'
  1981. :param rest: True if to use rest-machining
  1982. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1983. Usage of the different one is related to when this function is called from a
  1984. TcL command.
  1985. :param plot: if True after the job is finished the result will be plotted, else it will not.
  1986. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage;
  1987. if False it will run non-threaded for TclShell usage
  1988. :return:
  1989. """
  1990. if run_threaded:
  1991. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1992. else:
  1993. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1994. QtWidgets.QApplication.processEvents()
  1995. # #####################################################################
  1996. # ####### Read the parameters #########################################
  1997. # #####################################################################
  1998. units = self.app.defaults['units']
  1999. log.debug("NCC Tool started. Reading parameters.")
  2000. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  2001. ncc_method = method
  2002. ncc_margin = margin
  2003. ncc_select = select_method
  2004. overlap = overlap
  2005. connect = connect
  2006. contour = contour
  2007. order = order
  2008. if tools_storage is not None:
  2009. tools_storage = tools_storage
  2010. else:
  2011. tools_storage = self.ncc_tools
  2012. ncc_offset = 0.0
  2013. if has_offset is True:
  2014. ncc_offset = offset
  2015. # ######################################################################################################
  2016. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  2017. # ######################################################################################################
  2018. sorted_tools = []
  2019. try:
  2020. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  2021. except AttributeError:
  2022. if not isinstance(ncctooldia, list):
  2023. sorted_tools = [float(ncctooldia)]
  2024. else:
  2025. sorted_tools = ncctooldia
  2026. if not sorted_tools:
  2027. return 'fail'
  2028. # ##############################################################################################################
  2029. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  2030. # ##############################################################################################################
  2031. log.debug("NCC Tool. Preparing non-copper polygons.")
  2032. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  2033. try:
  2034. if sel_obj is None or sel_obj == _('Itself'):
  2035. ncc_sel_obj = ncc_obj
  2036. else:
  2037. ncc_sel_obj = sel_obj
  2038. except Exception as e:
  2039. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  2040. return 'fail'
  2041. bounding_box = None
  2042. if ncc_select == _('Itself'):
  2043. geo_n = ncc_sel_obj.solid_geometry
  2044. try:
  2045. if isinstance(geo_n, MultiPolygon):
  2046. env_obj = geo_n.convex_hull
  2047. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  2048. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  2049. env_obj = cascaded_union(geo_n)
  2050. else:
  2051. env_obj = cascaded_union(geo_n)
  2052. env_obj = env_obj.convex_hull
  2053. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2054. except Exception as e:
  2055. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  2056. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2057. return 'fail'
  2058. elif ncc_select == 'area':
  2059. geo_n = cascaded_union(self.sel_rect)
  2060. try:
  2061. __ = iter(geo_n)
  2062. except Exception as e:
  2063. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  2064. geo_n = [geo_n]
  2065. geo_buff_list = []
  2066. for poly in geo_n:
  2067. if self.app.abort_flag:
  2068. # graceful abort requested by the user
  2069. raise grace
  2070. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2071. bounding_box = cascaded_union(geo_buff_list)
  2072. elif ncc_select == _("Reference Object"):
  2073. geo_n = ncc_sel_obj.solid_geometry
  2074. if ncc_sel_obj.kind == 'geometry':
  2075. try:
  2076. __ = iter(geo_n)
  2077. except Exception as e:
  2078. log.debug("NonCopperClear.clear_copper() 'Reference Object' --> %s" % str(e))
  2079. geo_n = [geo_n]
  2080. geo_buff_list = []
  2081. for poly in geo_n:
  2082. if self.app.abort_flag:
  2083. # graceful abort requested by the user
  2084. raise grace
  2085. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2086. bounding_box = cascaded_union(geo_buff_list)
  2087. elif ncc_sel_obj.kind == 'gerber':
  2088. geo_n = cascaded_union(geo_n).convex_hull
  2089. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  2090. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2091. else:
  2092. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  2093. return 'fail'
  2094. log.debug("NCC Tool. Finished non-copper polygons.")
  2095. # ########################################################################################################
  2096. # set the name for the future Geometry object
  2097. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  2098. # ########################################################################################################
  2099. rest_machining_choice = rest
  2100. if rest_machining_choice is True:
  2101. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2102. else:
  2103. name = outname if outname is not None else self.obj_name + "_ncc"
  2104. # ##########################################################################################
  2105. # Initializes the new geometry object ######################################################
  2106. # ##########################################################################################
  2107. def gen_clear_area(geo_obj, app_obj):
  2108. assert geo_obj.kind == 'geometry', \
  2109. "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  2110. # provide the app with a way to process the GUI events when in a blocking loop
  2111. if not run_threaded:
  2112. QtWidgets.QApplication.processEvents()
  2113. log.debug("NCC Tool. Normal copper clearing task started.")
  2114. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  2115. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2116. # will store the number of tools for which the isolation is broken
  2117. warning_flag = 0
  2118. if order == 'fwd':
  2119. sorted_tools.sort(reverse=False)
  2120. elif order == 'rev':
  2121. sorted_tools.sort(reverse=True)
  2122. else:
  2123. pass
  2124. cleared_geo = []
  2125. # Already cleared area
  2126. cleared = MultiPolygon()
  2127. # flag for polygons not cleared
  2128. app_obj.poly_not_cleared = False
  2129. # Generate area for each tool
  2130. offset_a = sum(sorted_tools)
  2131. current_uid = int(1)
  2132. try:
  2133. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2134. except TypeError:
  2135. tool = eval(self.app.defaults["tools_ncctools"])
  2136. # ###################################################################################################
  2137. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2138. # ###################################################################################################
  2139. log.debug("NCC Tool. Calculate 'empty' area.")
  2140. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  2141. if ncc_obj.kind == 'gerber' and not isotooldia:
  2142. # unfortunately for this function to work time efficient,
  2143. # if the Gerber was loaded without buffering then it require the buffering now.
  2144. if self.app.defaults['gerber_buffering'] == 'no':
  2145. sol_geo = ncc_obj.solid_geometry.buffer(0)
  2146. else:
  2147. sol_geo = ncc_obj.solid_geometry
  2148. if has_offset is True:
  2149. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2150. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2151. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2152. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2153. if empty == 'fail':
  2154. return 'fail'
  2155. if empty.is_empty:
  2156. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2157. _("Could not get the extent of the area to be non copper cleared."))
  2158. return 'fail'
  2159. elif ncc_obj.kind == 'gerber' and isotooldia:
  2160. isolated_geo = []
  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. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  2165. else:
  2166. self.solid_geometry = ncc_obj.solid_geometry
  2167. # if milling type is climb then the move is counter-clockwise around features
  2168. milling_type = self.app.defaults["tools_nccmilling_type"]
  2169. for tool_iso in isotooldia:
  2170. new_geometry = []
  2171. if milling_type == 'cl':
  2172. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  2173. else:
  2174. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  2175. if isolated_geo == 'fail':
  2176. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2177. else:
  2178. if ncc_margin < tool_iso:
  2179. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2180. "than isolation tool diameter."))
  2181. try:
  2182. for geo_elem in isolated_geo:
  2183. # provide the app with a way to process the GUI events when in a blocking loop
  2184. QtWidgets.QApplication.processEvents()
  2185. if self.app.abort_flag:
  2186. # graceful abort requested by the user
  2187. raise grace
  2188. if isinstance(geo_elem, Polygon):
  2189. for ring in self.poly2rings(geo_elem):
  2190. new_geo = ring.intersection(bounding_box)
  2191. if new_geo and not new_geo.is_empty:
  2192. new_geometry.append(new_geo)
  2193. elif isinstance(geo_elem, MultiPolygon):
  2194. for a_poly in geo_elem:
  2195. for ring in self.poly2rings(a_poly):
  2196. new_geo = ring.intersection(bounding_box)
  2197. if new_geo and not new_geo.is_empty:
  2198. new_geometry.append(new_geo)
  2199. elif isinstance(geo_elem, LineString):
  2200. new_geo = geo_elem.intersection(bounding_box)
  2201. if new_geo:
  2202. if not new_geo.is_empty:
  2203. new_geometry.append(new_geo)
  2204. elif isinstance(geo_elem, MultiLineString):
  2205. for line_elem in geo_elem:
  2206. new_geo = line_elem.intersection(bounding_box)
  2207. if new_geo and not new_geo.is_empty:
  2208. new_geometry.append(new_geo)
  2209. except TypeError:
  2210. if isinstance(isolated_geo, Polygon):
  2211. for ring in self.poly2rings(isolated_geo):
  2212. new_geo = ring.intersection(bounding_box)
  2213. if new_geo:
  2214. if not new_geo.is_empty:
  2215. new_geometry.append(new_geo)
  2216. elif isinstance(isolated_geo, LineString):
  2217. new_geo = isolated_geo.intersection(bounding_box)
  2218. if new_geo and not new_geo.is_empty:
  2219. new_geometry.append(new_geo)
  2220. elif isinstance(isolated_geo, MultiLineString):
  2221. for line_elem in isolated_geo:
  2222. new_geo = line_elem.intersection(bounding_box)
  2223. if new_geo and not new_geo.is_empty:
  2224. new_geometry.append(new_geo)
  2225. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2226. for geo_e in new_geometry:
  2227. if type(geo_e) == MultiLineString:
  2228. warning_flag += 1
  2229. break
  2230. for k, v in tools_storage.items():
  2231. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2232. tool_iso)):
  2233. current_uid = int(k)
  2234. # add the solid_geometry to the current too in self.paint_tools dictionary
  2235. # and then reset the temporary list that stored that solid_geometry
  2236. v['solid_geometry'] = deepcopy(new_geometry)
  2237. v['data']['name'] = name
  2238. break
  2239. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2240. sol_geo = cascaded_union(isolated_geo)
  2241. if has_offset is True:
  2242. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2243. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2244. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2245. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2246. if empty == 'fail':
  2247. return 'fail'
  2248. if empty.is_empty:
  2249. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2250. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2251. return 'fail'
  2252. elif ncc_obj.kind == 'geometry':
  2253. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2254. if has_offset is True:
  2255. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2256. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2257. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2258. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2259. if empty == 'fail':
  2260. return 'fail'
  2261. if empty.is_empty:
  2262. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2263. _("Could not get the extent of the area to be non copper cleared."))
  2264. return 'fail'
  2265. else:
  2266. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2267. return 'fail'
  2268. if type(empty) is Polygon:
  2269. empty = MultiPolygon([empty])
  2270. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2271. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  2272. # COPPER CLEARING #
  2273. for tool in sorted_tools:
  2274. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2275. if self.app.abort_flag:
  2276. # graceful abort requested by the user
  2277. raise grace
  2278. # provide the app with a way to process the GUI events when in a blocking loop
  2279. QtWidgets.QApplication.processEvents()
  2280. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2281. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2282. )
  2283. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2284. cleared_geo[:] = []
  2285. # Get remaining tools offset
  2286. offset_a -= (tool - 1e-12)
  2287. # Area to clear
  2288. area = empty.buffer(-offset_a)
  2289. try:
  2290. area = area.difference(cleared)
  2291. except Exception:
  2292. continue
  2293. # Transform area to MultiPolygon
  2294. if type(area) is Polygon:
  2295. area = MultiPolygon([area])
  2296. # variables to display the percentage of work done
  2297. geo_len = len(area.geoms)
  2298. old_disp_number = 0
  2299. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2300. if area.geoms:
  2301. if len(area.geoms) > 0:
  2302. pol_nr = 0
  2303. for p in area.geoms:
  2304. # provide the app with a way to process the GUI events when in a blocking loop
  2305. QtWidgets.QApplication.processEvents()
  2306. if self.app.abort_flag:
  2307. # graceful abort requested by the user
  2308. raise grace
  2309. # clean the polygon
  2310. p = p.buffer(0)
  2311. if p is not None and p.is_valid:
  2312. poly_processed = []
  2313. try:
  2314. for pol in p:
  2315. if pol is not None and isinstance(pol, Polygon):
  2316. if ncc_method == 'standard':
  2317. cp = self.clear_polygon(pol, tool,
  2318. self.grb_circle_steps,
  2319. overlap=overlap, contour=contour,
  2320. connect=connect,
  2321. prog_plot=False)
  2322. elif ncc_method == 'seed':
  2323. cp = self.clear_polygon2(pol, tool,
  2324. self.grb_circle_steps,
  2325. overlap=overlap, contour=contour,
  2326. connect=connect,
  2327. prog_plot=False)
  2328. else:
  2329. cp = self.clear_polygon3(pol, tool,
  2330. self.grb_circle_steps,
  2331. overlap=overlap, contour=contour,
  2332. connect=connect,
  2333. prog_plot=False)
  2334. if cp:
  2335. cleared_geo += list(cp.get_objects())
  2336. poly_processed.append(True)
  2337. else:
  2338. poly_processed.append(False)
  2339. log.warning("Polygon in MultiPolygon can not be cleared.")
  2340. else:
  2341. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2342. "It is: %s" % str(type(pol)))
  2343. except TypeError:
  2344. if isinstance(p, Polygon):
  2345. if ncc_method == 'standard':
  2346. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  2347. overlap=overlap, contour=contour, connect=connect,
  2348. prog_plot=False)
  2349. elif ncc_method == 'seed':
  2350. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  2351. overlap=overlap, contour=contour, connect=connect,
  2352. prog_plot=False)
  2353. else:
  2354. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  2355. overlap=overlap, contour=contour, connect=connect,
  2356. prog_plot=False)
  2357. if cp:
  2358. cleared_geo += list(cp.get_objects())
  2359. poly_processed.append(True)
  2360. else:
  2361. poly_processed.append(False)
  2362. log.warning("Polygon can not be cleared.")
  2363. else:
  2364. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  2365. p_cleared = poly_processed.count(True)
  2366. p_not_cleared = poly_processed.count(False)
  2367. if p_not_cleared:
  2368. app_obj.poly_not_cleared = True
  2369. if p_cleared == 0:
  2370. continue
  2371. pol_nr += 1
  2372. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2373. # log.debug("Polygons cleared: %d" % pol_nr)
  2374. if old_disp_number < disp_number <= 100:
  2375. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2376. old_disp_number = disp_number
  2377. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2378. # check if there is a geometry at all in the cleared geometry
  2379. if cleared_geo:
  2380. # Overall cleared area
  2381. cleared = empty.buffer(-offset_a * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  2382. tool / 1.999999)
  2383. # clean-up cleared geo
  2384. cleared = cleared.buffer(0)
  2385. # find the tooluid associated with the current tool_dia so we know where to add the tool
  2386. # solid_geometry
  2387. for k, v in tools_storage.items():
  2388. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2389. tool)):
  2390. current_uid = int(k)
  2391. # add the solid_geometry to the current too in self.paint_tools dictionary
  2392. # and then reset the temporary list that stored that solid_geometry
  2393. v['solid_geometry'] = deepcopy(cleared_geo)
  2394. v['data']['name'] = name
  2395. break
  2396. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2397. else:
  2398. log.debug("There are no geometries in the cleared polygon.")
  2399. # delete tools with empty geometry
  2400. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2401. for uid, uid_val in list(tools_storage.items()):
  2402. try:
  2403. # if the solid_geometry (type=list) is empty
  2404. if not uid_val['solid_geometry']:
  2405. tools_storage.pop(uid, None)
  2406. except KeyError:
  2407. tools_storage.pop(uid, None)
  2408. geo_obj.options["cnctooldia"] = str(tool)
  2409. geo_obj.multigeo = True
  2410. geo_obj.tools.clear()
  2411. geo_obj.tools = dict(tools_storage)
  2412. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2413. has_solid_geo = 0
  2414. for tooluid in geo_obj.tools:
  2415. if geo_obj.tools[tooluid]['solid_geometry']:
  2416. has_solid_geo += 1
  2417. if has_solid_geo == 0:
  2418. app_obj.inform.emit('[ERROR] %s' %
  2419. _("There is no NCC Geometry in the file.\n"
  2420. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2421. "Change the painting parameters and try again."))
  2422. return 'fail'
  2423. # check to see if geo_obj.tools is empty
  2424. # it will be updated only if there is a solid_geometry for tools
  2425. if geo_obj.tools:
  2426. if warning_flag == 0:
  2427. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  2428. else:
  2429. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  2430. _("NCC Tool clear all done but the copper features isolation is broken for"),
  2431. str(warning_flag),
  2432. _("tools")))
  2433. return
  2434. # create the solid_geometry
  2435. geo_obj.solid_geometry = []
  2436. for tooluid in geo_obj.tools:
  2437. if geo_obj.tools[tooluid]['solid_geometry']:
  2438. try:
  2439. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2440. geo_obj.solid_geometry.append(geo)
  2441. except TypeError:
  2442. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2443. else:
  2444. # I will use this variable for this purpose although it was meant for something else
  2445. # signal that we have no geo in the object therefore don't create it
  2446. app_obj.poly_not_cleared = False
  2447. return "fail"
  2448. # ###########################################################################################
  2449. # Initializes the new geometry object for the case of the rest-machining ####################
  2450. # ###########################################################################################
  2451. def gen_clear_area_rest(geo_obj, app_obj):
  2452. assert geo_obj.kind == 'geometry', \
  2453. "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  2454. log.debug("NCC Tool. Rest machining copper clearing task started.")
  2455. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  2456. # provide the app with a way to process the GUI events when in a blocking loop
  2457. if not run_threaded:
  2458. QtWidgets.QApplication.processEvents()
  2459. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2460. # will store the number of tools for which the isolation is broken
  2461. warning_flag = 0
  2462. sorted_tools.sort(reverse=True)
  2463. cleared_geo = []
  2464. cleared_by_last_tool = []
  2465. rest_geo = []
  2466. current_uid = 1
  2467. try:
  2468. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2469. except TypeError:
  2470. tool = eval(self.app.defaults["tools_ncctools"])
  2471. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2472. app_obj.poly_not_cleared = True
  2473. log.debug("NCC Tool. Calculate 'empty' area.")
  2474. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  2475. # ###################################################################################################
  2476. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2477. # ###################################################################################################
  2478. if ncc_obj.kind == 'gerber' and not isotooldia:
  2479. sol_geo = ncc_obj.solid_geometry
  2480. if has_offset is True:
  2481. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2482. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2483. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2484. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2485. if empty == 'fail':
  2486. return 'fail'
  2487. if empty.is_empty:
  2488. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2489. _("Could not get the extent of the area to be non copper cleared."))
  2490. return 'fail'
  2491. elif ncc_obj.kind == 'gerber' and isotooldia:
  2492. isolated_geo = []
  2493. self.solid_geometry = ncc_obj.solid_geometry
  2494. # if milling type is climb then the move is counter-clockwise around features
  2495. milling_type = self.app.defaults["tools_nccmilling_type"]
  2496. for tool_iso in isotooldia:
  2497. new_geometry = []
  2498. if milling_type == 'cl':
  2499. isolated_geo = self.generate_envelope(tool_iso, 1)
  2500. else:
  2501. isolated_geo = self.generate_envelope(tool_iso, 0)
  2502. if isolated_geo == 'fail':
  2503. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2504. else:
  2505. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2506. "than isolation tool diameter."))
  2507. try:
  2508. for geo_elem in isolated_geo:
  2509. # provide the app with a way to process the GUI events when in a blocking loop
  2510. QtWidgets.QApplication.processEvents()
  2511. if self.app.abort_flag:
  2512. # graceful abort requested by the user
  2513. raise grace
  2514. if isinstance(geo_elem, Polygon):
  2515. for ring in self.poly2rings(geo_elem):
  2516. new_geo = ring.intersection(bounding_box)
  2517. if new_geo and not new_geo.is_empty:
  2518. new_geometry.append(new_geo)
  2519. elif isinstance(geo_elem, MultiPolygon):
  2520. for poly_g in geo_elem:
  2521. for ring in self.poly2rings(poly_g):
  2522. new_geo = ring.intersection(bounding_box)
  2523. if new_geo and not new_geo.is_empty:
  2524. new_geometry.append(new_geo)
  2525. elif isinstance(geo_elem, LineString):
  2526. new_geo = geo_elem.intersection(bounding_box)
  2527. if new_geo:
  2528. if not new_geo.is_empty:
  2529. new_geometry.append(new_geo)
  2530. elif isinstance(geo_elem, MultiLineString):
  2531. for line_elem in geo_elem:
  2532. new_geo = line_elem.intersection(bounding_box)
  2533. if new_geo and not new_geo.is_empty:
  2534. new_geometry.append(new_geo)
  2535. except TypeError:
  2536. try:
  2537. if isinstance(isolated_geo, Polygon):
  2538. for ring in self.poly2rings(isolated_geo):
  2539. new_geo = ring.intersection(bounding_box)
  2540. if new_geo:
  2541. if not new_geo.is_empty:
  2542. new_geometry.append(new_geo)
  2543. elif isinstance(isolated_geo, LineString):
  2544. new_geo = isolated_geo.intersection(bounding_box)
  2545. if new_geo and not new_geo.is_empty:
  2546. new_geometry.append(new_geo)
  2547. elif isinstance(isolated_geo, MultiLineString):
  2548. for line_elem in isolated_geo:
  2549. new_geo = line_elem.intersection(bounding_box)
  2550. if new_geo and not new_geo.is_empty:
  2551. new_geometry.append(new_geo)
  2552. except Exception:
  2553. pass
  2554. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2555. for geo_e in new_geometry:
  2556. if type(geo_e) == MultiLineString:
  2557. warning_flag += 1
  2558. break
  2559. for k, v in tools_storage.items():
  2560. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2561. tool_iso)):
  2562. current_uid = int(k)
  2563. # add the solid_geometry to the current too in self.paint_tools dictionary
  2564. # and then reset the temporary list that stored that solid_geometry
  2565. v['solid_geometry'] = deepcopy(new_geometry)
  2566. v['data']['name'] = name
  2567. break
  2568. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2569. sol_geo = cascaded_union(isolated_geo)
  2570. if has_offset is True:
  2571. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2572. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2573. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2574. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2575. if empty == 'fail':
  2576. return 'fail'
  2577. if empty.is_empty:
  2578. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2579. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2580. return 'fail'
  2581. elif ncc_obj.kind == 'geometry':
  2582. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2583. if has_offset is True:
  2584. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2585. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2586. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2587. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2588. if empty == 'fail':
  2589. return 'fail'
  2590. if empty.is_empty:
  2591. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2592. _("Could not get the extent of the area to be non copper cleared."))
  2593. return 'fail'
  2594. else:
  2595. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2596. return
  2597. if self.app.abort_flag:
  2598. # graceful abort requested by the user
  2599. raise grace
  2600. if type(empty) is Polygon:
  2601. empty = MultiPolygon([empty])
  2602. area = empty.buffer(0)
  2603. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2604. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2605. # Generate area for each tool
  2606. while sorted_tools:
  2607. if self.app.abort_flag:
  2608. # graceful abort requested by the user
  2609. raise grace
  2610. tool = sorted_tools.pop(0)
  2611. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2612. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2613. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2614. )
  2615. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2616. tool_used = tool - 1e-12
  2617. cleared_geo[:] = []
  2618. # Area to clear
  2619. for poly_r in cleared_by_last_tool:
  2620. # provide the app with a way to process the GUI events when in a blocking loop
  2621. QtWidgets.QApplication.processEvents()
  2622. if self.app.abort_flag:
  2623. # graceful abort requested by the user
  2624. raise grace
  2625. try:
  2626. area = area.difference(poly_r)
  2627. except Exception:
  2628. pass
  2629. cleared_by_last_tool[:] = []
  2630. # Transform area to MultiPolygon
  2631. if type(area) is Polygon:
  2632. area = MultiPolygon([area])
  2633. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2634. # and rest_geo it's a list
  2635. allparts = [p.buffer(0) for p in area.geoms]
  2636. allparts += deepcopy(rest_geo)
  2637. rest_geo[:] = []
  2638. area = MultiPolygon(deepcopy(allparts))
  2639. allparts[:] = []
  2640. # variables to display the percentage of work done
  2641. geo_len = len(area.geoms)
  2642. old_disp_number = 0
  2643. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2644. if area.geoms:
  2645. if len(area.geoms) > 0:
  2646. pol_nr = 0
  2647. for p in area.geoms:
  2648. if self.app.abort_flag:
  2649. # graceful abort requested by the user
  2650. raise grace
  2651. # clean the polygon
  2652. p = p.buffer(0)
  2653. if p is not None and p.is_valid:
  2654. # provide the app with a way to process the GUI events when in a blocking loop
  2655. QtWidgets.QApplication.processEvents()
  2656. if isinstance(p, Polygon):
  2657. try:
  2658. if ncc_method == 'standard':
  2659. cp = self.clear_polygon(p, tool_used,
  2660. self.grb_circle_steps,
  2661. overlap=overlap, contour=contour, connect=connect,
  2662. prog_plot=False)
  2663. elif ncc_method == 'seed':
  2664. cp = self.clear_polygon2(p, tool_used,
  2665. self.grb_circle_steps,
  2666. overlap=overlap, contour=contour, connect=connect,
  2667. prog_plot=False)
  2668. else:
  2669. cp = self.clear_polygon3(p, tool_used,
  2670. self.grb_circle_steps,
  2671. overlap=overlap, contour=contour, connect=connect,
  2672. prog_plot=False)
  2673. cleared_geo.append(list(cp.get_objects()))
  2674. except Exception as ee:
  2675. log.warning("Polygon can't be cleared. %s" % str(ee))
  2676. # this polygon should be added to a list and then try clear it with
  2677. # a smaller tool
  2678. rest_geo.append(p)
  2679. elif isinstance(p, MultiPolygon):
  2680. for poly_p in p:
  2681. if poly_p is not None:
  2682. # provide the app with a way to process the GUI events when
  2683. # in a blocking loop
  2684. QtWidgets.QApplication.processEvents()
  2685. try:
  2686. if ncc_method == 'standard':
  2687. cp = self.clear_polygon(poly_p, tool_used,
  2688. self.grb_circle_steps,
  2689. overlap=overlap, contour=contour,
  2690. connect=connect,
  2691. prog_plot=False)
  2692. elif ncc_method == 'seed':
  2693. cp = self.clear_polygon2(poly_p, tool_used,
  2694. self.grb_circle_steps,
  2695. overlap=overlap, contour=contour,
  2696. connect=connect,
  2697. prog_plot=False)
  2698. else:
  2699. cp = self.clear_polygon3(poly_p, tool_used,
  2700. self.grb_circle_steps,
  2701. overlap=overlap, contour=contour,
  2702. connect=connect,
  2703. prog_plot=False)
  2704. cleared_geo.append(list(cp.get_objects()))
  2705. except Exception as eee:
  2706. log.warning("Polygon can't be cleared. %s" % str(eee))
  2707. # this polygon should be added to a list and then try clear it with
  2708. # a smaller tool
  2709. rest_geo.append(poly_p)
  2710. pol_nr += 1
  2711. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2712. # log.debug("Polygons cleared: %d" % pol_nr)
  2713. if old_disp_number < disp_number <= 100:
  2714. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2715. old_disp_number = disp_number
  2716. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2717. if self.app.abort_flag:
  2718. # graceful abort requested by the user
  2719. raise grace
  2720. # check if there is a geometry at all in the cleared geometry
  2721. if cleared_geo:
  2722. # Overall cleared area
  2723. cleared_area = list(self.flatten_list(cleared_geo))
  2724. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2725. # for p in cleared_area])
  2726. # here we store the poly's already processed in the original geometry by the current tool
  2727. # into cleared_by_last_tool list
  2728. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2729. # the next tool
  2730. buffer_value = tool_used / 2
  2731. for p in cleared_area:
  2732. if self.app.abort_flag:
  2733. # graceful abort requested by the user
  2734. raise grace
  2735. r_poly = p.buffer(buffer_value)
  2736. cleared_by_last_tool.append(r_poly)
  2737. # find the tooluid associated with the current tool_dia so we know
  2738. # where to add the tool solid_geometry
  2739. for k, v in tools_storage.items():
  2740. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2741. tool)):
  2742. current_uid = int(k)
  2743. # add the solid_geometry to the current too in self.paint_tools dictionary
  2744. # and then reset the temporary list that stored that solid_geometry
  2745. v['solid_geometry'] = deepcopy(cleared_area)
  2746. v['data']['name'] = name
  2747. cleared_area[:] = []
  2748. break
  2749. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2750. else:
  2751. log.debug("There are no geometries in the cleared polygon.")
  2752. geo_obj.multigeo = True
  2753. geo_obj.options["cnctooldia"] = str(tool)
  2754. # check to see if geo_obj.tools is empty
  2755. # it will be updated only if there is a solid_geometry for tools
  2756. if geo_obj.tools:
  2757. if warning_flag == 0:
  2758. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2759. else:
  2760. self.app.inform.emit(
  2761. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2762. "isolation is broken for"), str(warning_flag), _("tools")))
  2763. return
  2764. # create the solid_geometry
  2765. geo_obj.solid_geometry = []
  2766. for tooluid in geo_obj.tools:
  2767. if geo_obj.tools[tooluid]['solid_geometry']:
  2768. try:
  2769. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2770. geo_obj.solid_geometry.append(geo)
  2771. except TypeError:
  2772. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2773. else:
  2774. # I will use this variable for this purpose although it was meant for something else
  2775. # signal that we have no geo in the object therefore don't create it
  2776. app_obj.poly_not_cleared = False
  2777. return "fail"
  2778. # ###########################################################################################
  2779. # Create the Job function and send it to the worker to be processed in another thread #######
  2780. # ###########################################################################################
  2781. def job_thread(app_obj):
  2782. try:
  2783. if rest_machining_choice is True:
  2784. app_obj.app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  2785. else:
  2786. app_obj.app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  2787. except grace:
  2788. if run_threaded:
  2789. proc.done()
  2790. return
  2791. except Exception:
  2792. if run_threaded:
  2793. proc.done()
  2794. traceback.print_stack()
  2795. return
  2796. if run_threaded:
  2797. proc.done()
  2798. else:
  2799. app_obj.proc_container.view.set_idle()
  2800. # focus on Selected Tab
  2801. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2802. if run_threaded:
  2803. # Promise object with the new name
  2804. self.app.collection.promise(name)
  2805. # Background
  2806. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2807. else:
  2808. job_thread(app_obj=self.app)
  2809. def get_ncc_empty_area(self, target, boundary=None):
  2810. """
  2811. Returns the complement of target geometry within
  2812. the given boundary polygon. If not specified, it defaults to
  2813. the rectangular bounding box of target geometry.
  2814. :param target: The geometry that is to be 'inverted'
  2815. :param boundary: A polygon that surrounds the entire solid geometry and from which we subtract in order to
  2816. create a "negative" geometry (geometry to be emptied of copper)
  2817. :return:
  2818. """
  2819. if isinstance(target, Polygon):
  2820. geo_len = 1
  2821. else:
  2822. geo_len = len(target)
  2823. pol_nr = 0
  2824. old_disp_number = 0
  2825. if boundary is None:
  2826. boundary = target.envelope
  2827. else:
  2828. boundary = boundary
  2829. try:
  2830. ret_val = boundary.difference(target)
  2831. except Exception:
  2832. try:
  2833. for el in target:
  2834. # provide the app with a way to process the GUI events when in a blocking loop
  2835. QtWidgets.QApplication.processEvents()
  2836. if self.app.abort_flag:
  2837. # graceful abort requested by the user
  2838. raise grace
  2839. boundary = boundary.difference(el)
  2840. pol_nr += 1
  2841. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2842. if old_disp_number < disp_number <= 100:
  2843. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2844. old_disp_number = disp_number
  2845. return boundary
  2846. except Exception:
  2847. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2848. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  2849. "Reload the Gerber file after this change."))
  2850. return 'fail'
  2851. return ret_val
  2852. @staticmethod
  2853. def poly2rings(poly):
  2854. return [poly.exterior] + [interior for interior in poly.interiors]
  2855. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  2856. # isolation_geometry produces an envelope that is going on the left of the geometry
  2857. # (the copper features). To leave the least amount of burrs on the features
  2858. # the tool needs to travel on the right side of the features (this is called conventional milling)
  2859. # the first pass is the one cutting all of the features, so it needs to be reversed
  2860. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  2861. # to cut on the right side of the left over copper i.e on the left side of the features.
  2862. try:
  2863. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  2864. except Exception as e:
  2865. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  2866. return 'fail'
  2867. if invert:
  2868. try:
  2869. try:
  2870. pl = []
  2871. for p in geom:
  2872. if p is not None:
  2873. if isinstance(p, Polygon):
  2874. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2875. elif isinstance(p, LinearRing):
  2876. pl.append(Polygon(p.coords[::-1]))
  2877. geom = MultiPolygon(pl)
  2878. except TypeError:
  2879. if isinstance(geom, Polygon) and geom is not None:
  2880. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2881. elif isinstance(geom, LinearRing) and geom is not None:
  2882. geom = Polygon(geom.coords[::-1])
  2883. else:
  2884. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  2885. type(geom))
  2886. except Exception as e:
  2887. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  2888. return 'fail'
  2889. return geom
  2890. def on_ncc_tool_add_from_db_executed(self, tool):
  2891. """
  2892. Here add the tool from DB in the selected geometry object
  2893. :return:
  2894. """
  2895. tool_from_db = deepcopy(tool)
  2896. res = self.on_ncc_tool_from_db_inserted(tool=tool_from_db)
  2897. for idx in range(self.app.ui.plot_tab_area.count()):
  2898. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2899. wdg = self.app.ui.plot_tab_area.widget(idx)
  2900. wdg.deleteLater()
  2901. self.app.ui.plot_tab_area.removeTab(idx)
  2902. if res == 'fail':
  2903. return
  2904. self.app.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  2905. # select last tool added
  2906. toolid = res
  2907. for row in range(self.ui.tools_table.rowCount()):
  2908. if int(self.ui.tools_table.item(row, 3).text()) == toolid:
  2909. self.ui.tools_table.selectRow(row)
  2910. self.on_row_selection_change()
  2911. def on_ncc_tool_from_db_inserted(self, tool):
  2912. """
  2913. Called from the Tools DB object through a App method when adding a tool from Tools Database
  2914. :param tool: a dict with the tool data
  2915. :return: None
  2916. """
  2917. self.ui_disconnect()
  2918. self.units = self.app.defaults['units'].upper()
  2919. tooldia = float(tool['tooldia'])
  2920. # construct a list of all 'tooluid' in the self.tools
  2921. tool_uid_list = []
  2922. for tooluid_key in self.ncc_tools:
  2923. tool_uid_item = int(tooluid_key)
  2924. tool_uid_list.append(tool_uid_item)
  2925. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2926. if not tool_uid_list:
  2927. max_uid = 0
  2928. else:
  2929. max_uid = max(tool_uid_list)
  2930. tooluid = max_uid + 1
  2931. tooldia = float('%.*f' % (self.decimals, tooldia))
  2932. tool_dias = []
  2933. for k, v in self.ncc_tools.items():
  2934. for tool_v in v.keys():
  2935. if tool_v == 'tooldia':
  2936. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  2937. if float('%.*f' % (self.decimals, tooldia)) in tool_dias:
  2938. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. Tool already in Tool Table."))
  2939. self.ui_connect()
  2940. return 'fail'
  2941. self.ncc_tools.update({
  2942. tooluid: {
  2943. 'tooldia': float('%.*f' % (self.decimals, tooldia)),
  2944. 'offset': tool['offset'],
  2945. 'offset_value': tool['offset_value'],
  2946. 'type': tool['type'],
  2947. 'tool_type': tool['tool_type'],
  2948. 'data': deepcopy(tool['data']),
  2949. 'solid_geometry': []
  2950. }
  2951. })
  2952. self.ncc_tools[tooluid]['data']['name'] = '_ncc'
  2953. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  2954. self.ui_connect()
  2955. self.build_ui()
  2956. # if self.ui.tools_table.rowCount() != 0:
  2957. # self.param_frame.setDisabled(False)
  2958. def on_ncc_tool_add_from_db_clicked(self):
  2959. """
  2960. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  2961. and display the Tools Database tab in the form needed for the Tool adding
  2962. :return: None
  2963. """
  2964. # if the Tools Database is already opened focus on it
  2965. for idx in range(self.app.ui.plot_tab_area.count()):
  2966. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  2967. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  2968. break
  2969. self.app.on_tools_database(source='ncc')
  2970. self.app.tools_db_tab.ok_to_add = True
  2971. self.app.tools_db_tab.buttons_frame.hide()
  2972. self.app.tools_db_tab.add_tool_from_db.show()
  2973. self.app.tools_db_tab.cancel_tool_from_db.show()
  2974. def reset_fields(self):
  2975. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2976. class NccUI:
  2977. toolName = _("Non-Copper Clearing")
  2978. def __init__(self, layout, app):
  2979. self.app = app
  2980. self.decimals = self.app.decimals
  2981. self.layout = layout
  2982. self.tools_frame = QtWidgets.QFrame()
  2983. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2984. self.layout.addWidget(self.tools_frame)
  2985. self.tools_box = QtWidgets.QVBoxLayout()
  2986. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2987. self.tools_frame.setLayout(self.tools_box)
  2988. # ## Title
  2989. title_label = QtWidgets.QLabel("%s" % self.toolName)
  2990. title_label.setStyleSheet("""
  2991. QLabel
  2992. {
  2993. font-size: 16px;
  2994. font-weight: bold;
  2995. }
  2996. """)
  2997. self.tools_box.addWidget(title_label)
  2998. # ## Form Layout
  2999. form_layout = QtWidgets.QFormLayout()
  3000. self.tools_box.addLayout(form_layout)
  3001. # ################################################
  3002. # ##### Type of object to be copper cleaned ######
  3003. # ################################################
  3004. # self.type_obj_radio = FCComboBox()
  3005. # self.type_obj_radio.addItem("Gerber")
  3006. # self.type_obj_radio.addItem("Excellon")
  3007. # self.type_obj_radio.addItem("Geometry")
  3008. #
  3009. # # we get rid of item1 ("Excellon") as it is not suitable
  3010. # self.type_obj_radio.view().setRowHidden(1, True)
  3011. # self.type_obj_radio.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  3012. # self.type_obj_radio.setItemIcon(2, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  3013. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  3014. self.type_obj_combo_label.setToolTip(
  3015. _("Specify the type of object to be cleared of excess copper.\n"
  3016. "It can be of type: Gerber or Geometry.\n"
  3017. "What is selected here will dictate the kind\n"
  3018. "of objects that will populate the 'Object' combobox.")
  3019. )
  3020. self.type_obj_combo_label.setMinimumWidth(60)
  3021. self.type_obj_radio = RadioSet([{'label': _("Geometry"), 'value': 'geometry'},
  3022. {'label': _("Gerber"), 'value': 'gerber'}])
  3023. form_layout.addRow(self.type_obj_combo_label, self.type_obj_radio)
  3024. # ################################################
  3025. # ##### The object to be copper cleaned ##########
  3026. # ################################################
  3027. self.object_combo = FCComboBox()
  3028. self.object_combo.setModel(self.app.collection)
  3029. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3030. # self.object_combo.setCurrentIndex(1)
  3031. self.object_combo.is_last = True
  3032. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  3033. self.object_label.setToolTip(_("Object to be cleared of excess copper."))
  3034. form_layout.addRow(self.object_label, self.object_combo)
  3035. separator_line = QtWidgets.QFrame()
  3036. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3037. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3038. self.tools_box.addWidget(separator_line)
  3039. # ### Tools ## ##
  3040. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  3041. self.tools_table_label.setToolTip(
  3042. _("Tools pool from which the algorithm\n"
  3043. "will pick the ones used for copper clearing.")
  3044. )
  3045. self.tools_box.addWidget(self.tools_table_label)
  3046. self.tools_table = FCTable()
  3047. self.tools_box.addWidget(self.tools_table)
  3048. self.tools_table.setColumnCount(4)
  3049. # 3rd column is reserved (and hidden) for the tool ID
  3050. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  3051. self.tools_table.setColumnHidden(3, True)
  3052. self.tools_table.setSortingEnabled(False)
  3053. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  3054. self.tools_table.horizontalHeaderItem(0).setToolTip(
  3055. _("This is the Tool Number.\n"
  3056. "Non copper clearing will start with the tool with the biggest \n"
  3057. "diameter, continuing until there are no more tools.\n"
  3058. "Only tools that create NCC clearing geometry will still be present\n"
  3059. "in the resulting geometry. This is because with some tools\n"
  3060. "this function will not be able to create painting geometry.")
  3061. )
  3062. self.tools_table.horizontalHeaderItem(1).setToolTip(
  3063. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  3064. "is the cut width into the material."))
  3065. self.tools_table.horizontalHeaderItem(2).setToolTip(
  3066. _("The Tool Type (TT) can be:\n"
  3067. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  3068. "the cut width in material is exactly the tool diameter.\n"
  3069. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  3070. "- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
  3071. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  3072. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  3073. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  3074. "column of this table.\n"
  3075. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  3076. "in the resulting geometry as Isolation."))
  3077. # self.tools_table.horizontalHeaderItem(4).setToolTip(
  3078. # _("The 'Operation' can be:\n"
  3079. # "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  3080. # "If it's not successful then the non-copper clearing will fail, too.\n"
  3081. # "- Clear -> the regular non-copper clearing."))
  3082. grid1 = QtWidgets.QGridLayout()
  3083. self.tools_box.addLayout(grid1)
  3084. grid1.setColumnStretch(0, 0)
  3085. grid1.setColumnStretch(1, 1)
  3086. # Tool order
  3087. self.ncc_order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  3088. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  3089. "'No' --> means that the used order is the one in the tool table\n"
  3090. "'Forward' --> means that the tools will be ordered from small to big\n"
  3091. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  3092. "WARNING: using rest machining will automatically set the order\n"
  3093. "in reverse and disable this control."))
  3094. self.ncc_order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  3095. {'label': _('Forward'), 'value': 'fwd'},
  3096. {'label': _('Reverse'), 'value': 'rev'}])
  3097. self.ncc_order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  3098. "'No' --> means that the used order is the one in the tool table\n"
  3099. "'Forward' --> means that the tools will be ordered from small to big\n"
  3100. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  3101. "WARNING: using rest machining will automatically set the order\n"
  3102. "in reverse and disable this control."))
  3103. grid1.addWidget(self.ncc_order_label, 1, 0)
  3104. grid1.addWidget(self.ncc_order_radio, 1, 1)
  3105. separator_line = QtWidgets.QFrame()
  3106. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3107. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3108. grid1.addWidget(separator_line, 2, 0, 1, 2)
  3109. # #############################################################
  3110. # ############### Tool selection ##############################
  3111. # #############################################################
  3112. self.grid3 = QtWidgets.QGridLayout()
  3113. self.tools_box.addLayout(self.grid3)
  3114. self.grid3.setColumnStretch(0, 0)
  3115. self.grid3.setColumnStretch(1, 1)
  3116. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  3117. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  3118. # Tool Type Radio Button
  3119. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  3120. self.tool_type_label.setToolTip(
  3121. _("Default tool type:\n"
  3122. "- 'V-shape'\n"
  3123. "- Circular")
  3124. )
  3125. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  3126. {'label': _('Circular'), 'value': 'C1'}])
  3127. self.tool_type_radio.setToolTip(
  3128. _("Default tool type:\n"
  3129. "- 'V-shape'\n"
  3130. "- Circular")
  3131. )
  3132. self.tool_type_radio.setObjectName(_("Tool Type"))
  3133. self.grid3.addWidget(self.tool_type_label, 2, 0)
  3134. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  3135. # Tip Dia
  3136. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  3137. self.tipdialabel.setToolTip(
  3138. _("The tip diameter for V-Shape Tool"))
  3139. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3140. self.tipdia_entry.set_precision(self.decimals)
  3141. self.tipdia_entry.set_range(0.0000, 9999.9999)
  3142. self.tipdia_entry.setSingleStep(0.1)
  3143. self.tipdia_entry.setObjectName(_("V-Tip Dia"))
  3144. self.grid3.addWidget(self.tipdialabel, 3, 0)
  3145. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  3146. # Tip Angle
  3147. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  3148. self.tipanglelabel.setToolTip(
  3149. _("The tip angle for V-Shape Tool.\n"
  3150. "In degree."))
  3151. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3152. self.tipangle_entry.set_precision(self.decimals)
  3153. self.tipangle_entry.set_range(0.0000, 180.0000)
  3154. self.tipangle_entry.setSingleStep(5)
  3155. self.tipangle_entry.setObjectName(_("V-Tip Angle"))
  3156. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  3157. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  3158. # Cut Z entry
  3159. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  3160. cutzlabel.setToolTip(
  3161. _("Depth of cut into material. Negative value.\n"
  3162. "In FlatCAM units.")
  3163. )
  3164. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3165. self.cutz_entry.set_precision(self.decimals)
  3166. self.cutz_entry.set_range(-99999.9999, 0.0000)
  3167. self.cutz_entry.setObjectName(_("Cut Z"))
  3168. self.cutz_entry.setToolTip(
  3169. _("Depth of cut into material. Negative value.\n"
  3170. "In FlatCAM units.")
  3171. )
  3172. self.grid3.addWidget(cutzlabel, 5, 0)
  3173. self.grid3.addWidget(self.cutz_entry, 5, 1)
  3174. # ### Tool Diameter ####
  3175. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  3176. self.addtool_entry_lbl.setToolTip(
  3177. _("Diameter for the new tool to add in the Tool Table.\n"
  3178. "If the tool is V-shape type then this value is automatically\n"
  3179. "calculated from the other parameters.")
  3180. )
  3181. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3182. self.addtool_entry.set_precision(self.decimals)
  3183. self.addtool_entry.set_range(0.000, 9999.9999)
  3184. self.addtool_entry.setObjectName(_("Tool Dia"))
  3185. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  3186. self.grid3.addWidget(self.addtool_entry, 6, 1)
  3187. hlay = QtWidgets.QHBoxLayout()
  3188. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  3189. self.addtool_btn.setToolTip(
  3190. _("Add a new tool to the Tool Table\n"
  3191. "with the diameter specified above.")
  3192. )
  3193. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  3194. self.addtool_from_db_btn.setToolTip(
  3195. _("Add a new tool to the Tool Table\n"
  3196. "from the Tool DataBase.")
  3197. )
  3198. hlay.addWidget(self.addtool_btn)
  3199. hlay.addWidget(self.addtool_from_db_btn)
  3200. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  3201. separator_line = QtWidgets.QFrame()
  3202. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3203. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3204. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  3205. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  3206. self.deltool_btn.setToolTip(
  3207. _("Delete a selection of tools in the Tool Table\n"
  3208. "by first selecting a row(s) in the Tool Table.")
  3209. )
  3210. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  3211. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  3212. separator_line = QtWidgets.QFrame()
  3213. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3214. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3215. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  3216. self.tool_data_label = QtWidgets.QLabel(
  3217. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  3218. self.tool_data_label.setToolTip(
  3219. _(
  3220. "The data used for creating GCode.\n"
  3221. "Each tool store it's own set of such data."
  3222. )
  3223. )
  3224. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  3225. # Operation
  3226. op_label = QtWidgets.QLabel('%s:' % _('Operation'))
  3227. op_label.setToolTip(
  3228. _("The 'Operation' can be:\n"
  3229. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  3230. "If it's not successful then the non-copper clearing will fail, too.\n"
  3231. "- Clear -> the regular non-copper clearing.")
  3232. )
  3233. self.op_radio = RadioSet([
  3234. {"label": _("Clear"), "value": "clear"},
  3235. {"label": _("Isolation"), "value": "iso"}
  3236. ], orientation='horizontal', stretch=False)
  3237. self.op_radio.setObjectName("n_operation")
  3238. self.grid3.addWidget(op_label, 13, 0)
  3239. self.grid3.addWidget(self.op_radio, 13, 1)
  3240. # Milling Type Radio Button
  3241. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  3242. self.milling_type_label.setToolTip(
  3243. _("Milling type when the selected tool is of type: 'iso_op':\n"
  3244. "- climb / best for precision milling and to reduce tool usage\n"
  3245. "- conventional / useful when there is no backlash compensation")
  3246. )
  3247. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  3248. {'label': _('Conventional'), 'value': 'cv'}])
  3249. self.milling_type_radio.setToolTip(
  3250. _("Milling type when the selected tool is of type: 'iso_op':\n"
  3251. "- climb / best for precision milling and to reduce tool usage\n"
  3252. "- conventional / useful when there is no backlash compensation")
  3253. )
  3254. self.milling_type_radio.setObjectName("n_milling_type")
  3255. self.milling_type_label.setEnabled(False)
  3256. self.milling_type_radio.setEnabled(False)
  3257. self.grid3.addWidget(self.milling_type_label, 14, 0)
  3258. self.grid3.addWidget(self.milling_type_radio, 14, 1)
  3259. # Overlap Entry
  3260. nccoverlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  3261. nccoverlabel.setToolTip(
  3262. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  3263. "Adjust the value starting with lower values\n"
  3264. "and increasing it if areas that should be cleared are still \n"
  3265. "not cleared.\n"
  3266. "Lower values = faster processing, faster execution on CNC.\n"
  3267. "Higher values = slow processing and slow execution on CNC\n"
  3268. "due of too many paths.")
  3269. )
  3270. self.ncc_overlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  3271. self.ncc_overlap_entry.set_precision(self.decimals)
  3272. self.ncc_overlap_entry.setWrapping(True)
  3273. self.ncc_overlap_entry.setRange(0.000, 99.9999)
  3274. self.ncc_overlap_entry.setSingleStep(0.1)
  3275. self.ncc_overlap_entry.setObjectName("n_overlap")
  3276. self.grid3.addWidget(nccoverlabel, 15, 0)
  3277. self.grid3.addWidget(self.ncc_overlap_entry, 15, 1)
  3278. # Margin
  3279. nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  3280. nccmarginlabel.setToolTip(
  3281. _("Bounding box margin.")
  3282. )
  3283. self.ncc_margin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  3284. self.ncc_margin_entry.set_precision(self.decimals)
  3285. self.ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  3286. self.ncc_margin_entry.setObjectName("n_margin")
  3287. self.grid3.addWidget(nccmarginlabel, 16, 0)
  3288. self.grid3.addWidget(self.ncc_margin_entry, 16, 1)
  3289. # Method
  3290. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  3291. methodlabel.setToolTip(
  3292. _("Algorithm for copper clearing:\n"
  3293. "- Standard: Fixed step inwards.\n"
  3294. "- Seed-based: Outwards from seed.\n"
  3295. "- Line-based: Parallel lines.")
  3296. )
  3297. # self.ncc_method_radio = RadioSet([
  3298. # {"label": _("Standard"), "value": "standard"},
  3299. # {"label": _("Seed-based"), "value": "seed"},
  3300. # {"label": _("Straight lines"), "value": "lines"}
  3301. # ], orientation='vertical', stretch=False)
  3302. self.ncc_method_combo = FCComboBox()
  3303. self.ncc_method_combo.addItems(
  3304. [_("Standard"), _("Seed"), _("Lines"), _("Combo")]
  3305. )
  3306. self.ncc_method_combo.setObjectName("n_method")
  3307. self.grid3.addWidget(methodlabel, 17, 0)
  3308. self.grid3.addWidget(self.ncc_method_combo, 17, 1)
  3309. # Connect lines
  3310. self.ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  3311. self.ncc_connect_cb.setObjectName("n_connect")
  3312. self.ncc_connect_cb.setToolTip(
  3313. _("Draw lines between resulting\n"
  3314. "segments to minimize tool lifts.")
  3315. )
  3316. self.grid3.addWidget(self.ncc_connect_cb, 18, 0)
  3317. # Contour
  3318. self.ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  3319. self.ncc_contour_cb.setObjectName("n_contour")
  3320. self.ncc_contour_cb.setToolTip(
  3321. _("Cut around the perimeter of the polygon\n"
  3322. "to trim rough edges.")
  3323. )
  3324. self.grid3.addWidget(self.ncc_contour_cb, 18, 1)
  3325. # ## NCC Offset choice
  3326. self.ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  3327. self.ncc_choice_offset_cb.setObjectName("n_offset")
  3328. self.ncc_choice_offset_cb.setToolTip(
  3329. _("If used, it will add an offset to the copper features.\n"
  3330. "The copper clearing will finish to a distance\n"
  3331. "from the copper features.\n"
  3332. "The value can be between 0 and 10 FlatCAM units.")
  3333. )
  3334. self.grid3.addWidget(self.ncc_choice_offset_cb, 19, 0)
  3335. # ## NCC Offset Entry
  3336. self.ncc_offset_spinner = FCDoubleSpinner(callback=self.confirmation_message)
  3337. self.ncc_offset_spinner.set_range(0.00, 10.00)
  3338. self.ncc_offset_spinner.set_precision(4)
  3339. self.ncc_offset_spinner.setWrapping(True)
  3340. self.ncc_offset_spinner.setObjectName("n_offset_value")
  3341. units = self.app.defaults['units'].upper()
  3342. if units == 'MM':
  3343. self.ncc_offset_spinner.setSingleStep(0.1)
  3344. else:
  3345. self.ncc_offset_spinner.setSingleStep(0.01)
  3346. self.grid3.addWidget(self.ncc_offset_spinner, 19, 1)
  3347. self.ois_ncc_offset = OptionalInputSection(self.ncc_choice_offset_cb, [self.ncc_offset_spinner])
  3348. separator_line = QtWidgets.QFrame()
  3349. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3350. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3351. self.grid3.addWidget(separator_line, 21, 0, 1, 2)
  3352. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  3353. self.apply_param_to_all.setToolTip(
  3354. _("The parameters in the current form will be applied\n"
  3355. "on all the tools from the Tool Table.")
  3356. )
  3357. self.grid3.addWidget(self.apply_param_to_all, 22, 0, 1, 2)
  3358. separator_line = QtWidgets.QFrame()
  3359. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3360. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3361. self.grid3.addWidget(separator_line, 23, 0, 1, 2)
  3362. # General Parameters
  3363. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  3364. self.gen_param_label.setToolTip(
  3365. _("Parameters that are common for all tools.")
  3366. )
  3367. self.grid3.addWidget(self.gen_param_label, 24, 0, 1, 2)
  3368. # Rest Machining
  3369. self.ncc_rest_cb = FCCheckBox('%s' % _("Rest"))
  3370. self.ncc_rest_cb.setObjectName("n_rest_machining")
  3371. self.ncc_rest_cb.setToolTip(
  3372. _("If checked, use 'rest machining'.\n"
  3373. "Basically it will clear copper outside PCB features,\n"
  3374. "using the biggest tool and continue with the next tools,\n"
  3375. "from bigger to smaller, to clear areas of copper that\n"
  3376. "could not be cleared by previous tool, until there is\n"
  3377. "no more copper to clear or there are no more tools.\n"
  3378. "If not checked, use the standard algorithm.")
  3379. )
  3380. self.grid3.addWidget(self.ncc_rest_cb, 25, 0, 1, 2)
  3381. # ## Reference
  3382. # self.select_radio = RadioSet([
  3383. # {'label': _('Itself'), 'value': 'itself'},
  3384. # {"label": _("Area Selection"), "value": "area"},
  3385. # {'label': _("Reference Object"), 'value': 'box'}
  3386. # ], orientation='vertical', stretch=False)
  3387. self.select_combo = FCComboBox()
  3388. self.select_combo.addItems(
  3389. [_("Itself"), _("Area Selection"), _("Reference Object")]
  3390. )
  3391. self.select_combo.setObjectName("n_selection")
  3392. self.select_label = QtWidgets.QLabel('%s:' % _("Selection"))
  3393. self.select_label.setToolTip(
  3394. _("Selection of area to be processed.\n"
  3395. "- 'Itself' - the processing extent is based on the object that is processed.\n "
  3396. "- 'Area Selection' - left mouse click to start selection of the area to be processed.\n"
  3397. "- 'Reference Object' - will process the area specified by another object.")
  3398. )
  3399. self.grid3.addWidget(self.select_label, 26, 0, )
  3400. self.grid3.addWidget(self.select_combo, 26, 1)
  3401. form1 = QtWidgets.QFormLayout()
  3402. self.grid3.addLayout(form1, 28, 0, 1, 2)
  3403. self.reference_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  3404. self.reference_combo_type_label.setToolTip(
  3405. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  3406. "It can be Gerber, Excellon or Geometry.")
  3407. )
  3408. self.reference_combo_type = FCComboBox()
  3409. self.reference_combo_type.addItems([_("Gerber"), _("Excellon"), _("Geometry")])
  3410. form1.addRow(self.reference_combo_type_label, self.reference_combo_type)
  3411. self.reference_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  3412. self.reference_combo_label.setToolTip(
  3413. _("The FlatCAM object to be used as non copper clearing reference.")
  3414. )
  3415. self.reference_combo = FCComboBox()
  3416. self.reference_combo.setModel(self.app.collection)
  3417. self.reference_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3418. self.reference_combo.is_last = True
  3419. form1.addRow(self.reference_combo_label, self.reference_combo)
  3420. self.reference_combo.hide()
  3421. self.reference_combo_label.hide()
  3422. self.reference_combo_type.hide()
  3423. self.reference_combo_type_label.hide()
  3424. # Area Selection shape
  3425. self.area_shape_label = QtWidgets.QLabel('%s:' % _("Shape"))
  3426. self.area_shape_label.setToolTip(
  3427. _("The kind of selection shape used for area selection.")
  3428. )
  3429. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  3430. {'label': _("Polygon"), 'value': 'polygon'}])
  3431. self.grid3.addWidget(self.area_shape_label, 29, 0)
  3432. self.grid3.addWidget(self.area_shape_radio, 29, 1)
  3433. self.area_shape_label.hide()
  3434. self.area_shape_radio.hide()
  3435. separator_line = QtWidgets.QFrame()
  3436. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  3437. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  3438. self.grid3.addWidget(separator_line, 30, 0, 1, 2)
  3439. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  3440. self.generate_ncc_button.setToolTip(
  3441. _("Create the Geometry Object\n"
  3442. "for non-copper routing.")
  3443. )
  3444. self.generate_ncc_button.setStyleSheet("""
  3445. QPushButton
  3446. {
  3447. font-weight: bold;
  3448. }
  3449. """)
  3450. self.tools_box.addWidget(self.generate_ncc_button)
  3451. self.tools_box.addStretch()
  3452. # ## Reset Tool
  3453. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  3454. self.reset_button.setToolTip(
  3455. _("Will reset the tool parameters.")
  3456. )
  3457. self.reset_button.setStyleSheet("""
  3458. QPushButton
  3459. {
  3460. font-weight: bold;
  3461. }
  3462. """)
  3463. self.tools_box.addWidget(self.reset_button)
  3464. # ############################ FINSIHED GUI ###################################
  3465. # #############################################################################
  3466. def confirmation_message(self, accepted, minval, maxval):
  3467. if accepted is False:
  3468. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  3469. self.decimals,
  3470. minval,
  3471. self.decimals,
  3472. maxval), False)
  3473. else:
  3474. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  3475. def confirmation_message_int(self, accepted, minval, maxval):
  3476. if accepted is False:
  3477. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  3478. (_("Edited value is out of range"), minval, maxval), False)
  3479. else:
  3480. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)