ToolNCC.py 213 KB

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