ToolNCC.py 214 KB

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