ToolNCC.py 216 KB

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