AppGerberEditor.py 265 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 8/17/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtGui, QtCore, QtWidgets
  8. from PyQt5.QtCore import Qt
  9. from shapely.geometry import LineString, LinearRing, MultiLineString, Point, Polygon, MultiPolygon, box
  10. from shapely.ops import unary_union
  11. import shapely.affinity as affinity
  12. from vispy.geometry import Rect
  13. from copy import copy, deepcopy
  14. import logging
  15. from camlib import distance, arc, three_point_circle
  16. from appGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, FCSpinner, RadioSet, \
  17. EvalEntry2, FCInputDialog, FCButton, OptionalInputSection, FCCheckBox, NumericalEvalTupleEntry, FCComboBox2
  18. from appTool import AppTool
  19. import numpy as np
  20. from numpy.linalg import norm as numpy_norm
  21. import math
  22. # from vispy.io import read_png
  23. # import pngcanvas
  24. import traceback
  25. import gettext
  26. import appTranslation as fcTranslate
  27. import builtins
  28. fcTranslate.apply_language('strings')
  29. if '_' not in builtins.__dict__:
  30. _ = gettext.gettext
  31. log = logging.getLogger('base')
  32. class DrawToolShape(object):
  33. """
  34. Encapsulates "shapes" under a common class.
  35. """
  36. tolerance = None
  37. @staticmethod
  38. def get_pts(o):
  39. """
  40. Returns a list of all points in the object, where
  41. the object can be a Polygon, Not a polygon, or a list
  42. of such. Search is done recursively.
  43. :param: geometric object
  44. :return: List of points
  45. :rtype: list
  46. """
  47. pts = []
  48. # ## Iterable: descend into each item.
  49. try:
  50. for sub_o in o:
  51. pts += DrawToolShape.get_pts(sub_o)
  52. # Non-iterable
  53. except TypeError:
  54. if o is not None:
  55. # DrawToolShape: descend into .geo.
  56. if isinstance(o, DrawToolShape):
  57. pts += DrawToolShape.get_pts(o.geo)
  58. # ## Descend into .exerior and .interiors
  59. elif type(o) == Polygon:
  60. pts += DrawToolShape.get_pts(o.exterior)
  61. for i in o.interiors:
  62. pts += DrawToolShape.get_pts(i)
  63. elif type(o) == MultiLineString:
  64. for line in o:
  65. pts += DrawToolShape.get_pts(line)
  66. # ## Has .coords: list them.
  67. else:
  68. if DrawToolShape.tolerance is not None:
  69. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  70. else:
  71. pts += list(o.coords)
  72. else:
  73. return
  74. return pts
  75. def __init__(self, geo=None):
  76. # Shapely type or list of such
  77. self.geo = geo
  78. self.utility = False
  79. class DrawToolUtilityShape(DrawToolShape):
  80. """
  81. Utility shapes are temporary geometry in the editor
  82. to assist in the creation of shapes. For example it
  83. will show the outline of a rectangle from the first
  84. point to the current mouse pointer before the second
  85. point is clicked and the final geometry is created.
  86. """
  87. def __init__(self, geo=None):
  88. super(DrawToolUtilityShape, self).__init__(geo=geo)
  89. self.utility = True
  90. class DrawTool(object):
  91. """
  92. Abstract Class representing a tool in the drawing
  93. program. Can generate geometry, including temporary
  94. utility geometry that is updated on user clicks
  95. and mouse motion.
  96. """
  97. def __init__(self, draw_app):
  98. self.draw_app = draw_app
  99. self.complete = False
  100. self.points = []
  101. self.geometry = None # DrawToolShape or None
  102. def click(self, point):
  103. """
  104. :param point: [x, y] Coordinate pair.
  105. """
  106. return ""
  107. def click_release(self, point):
  108. """
  109. :param point: [x, y] Coordinate pair.
  110. """
  111. return ""
  112. def on_key(self, key):
  113. # Jump to coords
  114. if key == QtCore.Qt.Key_J or key == 'J':
  115. self.draw_app.app.on_jump_to()
  116. def utility_geometry(self, data=None):
  117. return None
  118. @staticmethod
  119. def bounds(obj):
  120. def bounds_rec(o):
  121. if type(o) is list:
  122. minx = np.Inf
  123. miny = np.Inf
  124. maxx = -np.Inf
  125. maxy = -np.Inf
  126. for k in o:
  127. try:
  128. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  129. except Exception as e:
  130. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  131. return
  132. minx = min(minx, minx_)
  133. miny = min(miny, miny_)
  134. maxx = max(maxx, maxx_)
  135. maxy = max(maxy, maxy_)
  136. return minx, miny, maxx, maxy
  137. else:
  138. # it's a Shapely object, return it's bounds
  139. if 'solid' in o.geo:
  140. return o.geo['solid'].bounds
  141. return bounds_rec(obj)
  142. class FCShapeTool(DrawTool):
  143. """
  144. Abstract class for tools that create a shape.
  145. """
  146. def __init__(self, draw_app):
  147. DrawTool.__init__(self, draw_app)
  148. self.name = None
  149. def make(self):
  150. pass
  151. class FCPad(FCShapeTool):
  152. """
  153. Resulting type: Polygon
  154. """
  155. def __init__(self, draw_app):
  156. DrawTool.__init__(self, draw_app)
  157. self.name = 'pad'
  158. self.draw_app = draw_app
  159. self.dont_execute = False
  160. try:
  161. QtGui.QGuiApplication.restoreOverrideCursor()
  162. except Exception:
  163. pass
  164. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_circle.png'))
  165. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  166. try:
  167. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  168. except KeyError:
  169. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  170. _("You need to preselect a aperture in the Aperture Table that has a size."))
  171. try:
  172. QtGui.QGuiApplication.restoreOverrideCursor()
  173. except Exception:
  174. pass
  175. self.dont_execute = True
  176. self.draw_app.in_action = False
  177. self.complete = True
  178. self.draw_app.select_tool('select')
  179. return
  180. if self.radius == 0:
  181. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' %
  182. _("Aperture size is zero. It needs to be greater than zero."))
  183. self.dont_execute = True
  184. return
  185. else:
  186. self.dont_execute = False
  187. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry']
  188. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  189. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  190. try:
  191. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  192. except KeyError:
  193. pass
  194. try:
  195. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  196. except KeyError:
  197. pass
  198. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  199. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  200. self.draw_app.draw_utility_geometry(geo=geo)
  201. self.draw_app.app.inform.emit(_("Click to place ..."))
  202. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  203. # Switch notebook to Properties page
  204. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.properties_tab)
  205. self.start_msg = _("Click to place ...")
  206. def click(self, point):
  207. self.make()
  208. return "Done."
  209. def utility_geometry(self, data=None):
  210. if self.dont_execute is True:
  211. self.draw_app.select_tool('select')
  212. return
  213. self.points = data
  214. geo_data = self.util_shape(data)
  215. if geo_data:
  216. return DrawToolUtilityShape(geo_data)
  217. else:
  218. return None
  219. def util_shape(self, point):
  220. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  221. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry']
  222. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  223. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  224. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  225. try:
  226. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  227. except KeyError:
  228. pass
  229. try:
  230. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  231. except KeyError:
  232. pass
  233. if point[0] is None and point[1] is None:
  234. point_x = self.draw_app.x
  235. point_y = self.draw_app.y
  236. else:
  237. point_x = point[0]
  238. point_y = point[1]
  239. ap_type = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['type']
  240. if ap_type == 'C':
  241. new_geo_el = {}
  242. center = Point([point_x, point_y])
  243. new_geo_el['solid'] = center.buffer(self.radius)
  244. new_geo_el['follow'] = center
  245. return new_geo_el
  246. elif ap_type == 'R':
  247. new_geo_el = {}
  248. p1 = (point_x - self.half_width, point_y - self.half_height)
  249. p2 = (point_x + self.half_width, point_y - self.half_height)
  250. p3 = (point_x + self.half_width, point_y + self.half_height)
  251. p4 = (point_x - self.half_width, point_y + self.half_height)
  252. center = Point([point_x, point_y])
  253. new_geo_el['solid'] = Polygon([p1, p2, p3, p4, p1])
  254. new_geo_el['follow'] = center
  255. return new_geo_el
  256. elif ap_type == 'O':
  257. geo = []
  258. new_geo_el = {}
  259. if self.half_height > self.half_width:
  260. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  261. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  262. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  263. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  264. down_center = [point_x, point_y - self.half_height + self.half_width]
  265. d_start_angle = np.pi
  266. d_stop_angle = 0.0
  267. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  268. up_center = [point_x, point_y + self.half_height - self.half_width]
  269. u_start_angle = 0.0
  270. u_stop_angle = np.pi
  271. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  272. geo.append(p1)
  273. for pt in down_arc:
  274. geo.append(pt)
  275. geo.append(p2)
  276. geo.append(p3)
  277. for pt in up_arc:
  278. geo.append(pt)
  279. geo.append(p4)
  280. new_geo_el['solid'] = Polygon(geo)
  281. center = Point([point_x, point_y])
  282. new_geo_el['follow'] = center
  283. return new_geo_el
  284. else:
  285. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  286. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  287. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  288. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  289. left_center = [point_x - self.half_width + self.half_height, point_y]
  290. d_start_angle = np.pi / 2
  291. d_stop_angle = 1.5 * np.pi
  292. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  293. right_center = [point_x + self.half_width - self.half_height, point_y]
  294. u_start_angle = 1.5 * np.pi
  295. u_stop_angle = np.pi / 2
  296. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  297. geo.append(p1)
  298. geo.append(p2)
  299. for pt in right_arc:
  300. geo.append(pt)
  301. geo.append(p3)
  302. geo.append(p4)
  303. for pt in left_arc:
  304. geo.append(pt)
  305. new_geo_el['solid'] = Polygon(geo)
  306. center = Point([point_x, point_y])
  307. new_geo_el['follow'] = center
  308. return new_geo_el
  309. else:
  310. self.draw_app.app.inform.emit(_(
  311. "Incompatible aperture type. Select an aperture with type 'C', 'R' or 'O'."))
  312. return None
  313. def make(self):
  314. self.draw_app.current_storage = self.storage_obj
  315. try:
  316. self.geometry = DrawToolShape(self.util_shape(self.points))
  317. except Exception as e:
  318. log.debug("FCPad.make() --> %s" % str(e))
  319. self.draw_app.in_action = False
  320. self.complete = True
  321. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  322. self.draw_app.app.jump_signal.disconnect()
  323. def clean_up(self):
  324. self.draw_app.selected = []
  325. self.draw_app.ui.apertures_table.clearSelection()
  326. self.draw_app.plot_all()
  327. try:
  328. self.draw_app.app.jump_signal.disconnect()
  329. except (TypeError, AttributeError):
  330. pass
  331. class FCPadArray(FCShapeTool):
  332. """
  333. Resulting type: MultiPolygon
  334. """
  335. def __init__(self, draw_app):
  336. DrawTool.__init__(self, draw_app)
  337. self.name = 'array'
  338. self.draw_app = draw_app
  339. self.dont_execute = False
  340. try:
  341. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  342. except KeyError:
  343. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  344. _("You need to preselect a aperture in the Aperture Table that has a size."))
  345. self.complete = True
  346. self.dont_execute = True
  347. self.draw_app.in_action = False
  348. self.draw_app.ui.array_frame.hide()
  349. self.draw_app.select_tool('select')
  350. return
  351. if self.radius == 0:
  352. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' %
  353. _("Aperture size is zero. It needs to be greater than zero."))
  354. self.dont_execute = True
  355. return
  356. else:
  357. self.dont_execute = False
  358. try:
  359. QtGui.QGuiApplication.restoreOverrideCursor()
  360. except Exception:
  361. pass
  362. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_array.png'))
  363. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  364. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry']
  365. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  366. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  367. try:
  368. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  369. except KeyError:
  370. pass
  371. try:
  372. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  373. except KeyError:
  374. pass
  375. self.draw_app.ui.array_frame.show()
  376. self.selected_size = None
  377. self.pad_axis = 'X'
  378. self.pad_array = 0 # 'linear'
  379. self.pad_array_size = None
  380. self.pad_pitch = None
  381. self.pad_linear_angle = None
  382. self.pad_angle = None
  383. self.pad_direction = None
  384. self.pad_radius = None
  385. self.origin = None
  386. self.destination = None
  387. self.flag_for_circ_array = None
  388. self.last_dx = 0
  389. self.last_dy = 0
  390. self.pt = []
  391. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  392. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  393. self.draw_app.draw_utility_geometry(geo=geo)
  394. self.draw_app.app.inform.emit(_("Click on target location ..."))
  395. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  396. # Switch notebook to Properties page
  397. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.properties_tab)
  398. def click(self, point):
  399. if self.draw_app.ui.array_type_combo.get_value() == 0: # 'Linear'
  400. self.make()
  401. return
  402. else:
  403. if self.flag_for_circ_array is None:
  404. self.draw_app.in_action = True
  405. self.pt.append(point)
  406. self.flag_for_circ_array = True
  407. self.set_origin(point)
  408. self.draw_app.app.inform.emit(_("Click on the Pad Circular Array Start position"))
  409. else:
  410. self.destination = point
  411. self.make()
  412. self.flag_for_circ_array = None
  413. return
  414. def set_origin(self, origin):
  415. self.origin = origin
  416. def utility_geometry(self, data=None, static=None):
  417. if self.dont_execute is True:
  418. self.draw_app.select_tool('select')
  419. return
  420. self.pad_axis = self.draw_app.ui.pad_axis_radio.get_value()
  421. self.pad_direction = self.draw_app.ui.pad_direction_radio.get_value()
  422. self.pad_array = self.draw_app.ui.array_type_combo.get_value()
  423. try:
  424. self.pad_array_size = int(self.draw_app.ui.pad_array_size_entry.get_value())
  425. try:
  426. self.pad_pitch = float(self.draw_app.ui.pad_pitch_entry.get_value())
  427. self.pad_linear_angle = float(self.draw_app.ui.linear_angle_spinner.get_value())
  428. self.pad_angle = float(self.draw_app.ui.pad_angle_entry.get_value())
  429. except TypeError:
  430. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  431. _("The value is not Float. Check for comma instead of dot separator."))
  432. return
  433. except Exception:
  434. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' % _("The value is mistyped. Check the value."))
  435. return
  436. if self.pad_array == 0: # 'Linear'
  437. if data[0] is None and data[1] is None:
  438. dx = self.draw_app.x
  439. dy = self.draw_app.y
  440. else:
  441. dx = data[0]
  442. dy = data[1]
  443. geo_el_list = []
  444. geo_el = []
  445. self.points = [dx, dy]
  446. for item in range(self.pad_array_size):
  447. if self.pad_axis == 'X':
  448. geo_el = self.util_shape(((dx + (self.pad_pitch * item)), dy))
  449. if self.pad_axis == 'Y':
  450. geo_el = self.util_shape((dx, (dy + (self.pad_pitch * item))))
  451. if self.pad_axis == 'A':
  452. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  453. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  454. geo_el = self.util_shape(
  455. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  456. )
  457. if static is None or static is False:
  458. new_geo_el = {}
  459. if 'solid' in geo_el:
  460. new_geo_el['solid'] = affinity.translate(
  461. geo_el['solid'], xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)
  462. )
  463. if 'follow' in geo_el:
  464. new_geo_el['follow'] = affinity.translate(
  465. geo_el['follow'], xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)
  466. )
  467. geo_el_list.append(new_geo_el)
  468. else:
  469. geo_el_list.append(geo_el)
  470. # self.origin = data
  471. self.last_dx = dx
  472. self.last_dy = dy
  473. return DrawToolUtilityShape(geo_el_list)
  474. else: # 'Circular'
  475. if data[0] is None and data[1] is None:
  476. cdx = self.draw_app.x
  477. cdy = self.draw_app.y
  478. else:
  479. cdx = data[0]
  480. cdy = data[1]
  481. if len(self.pt) > 0:
  482. temp_points = [x for x in self.pt]
  483. temp_points.append([cdx, cdy])
  484. return DrawToolUtilityShape(LineString(temp_points))
  485. def util_shape(self, point):
  486. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  487. self.storage_obj = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry']
  488. self.radius = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size']) / 2
  489. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  490. # if those cause KeyError exception it means that the aperture type is not 'R'. Only 'R' type has those keys
  491. try:
  492. self.half_width = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['width']) / 2
  493. except KeyError:
  494. pass
  495. try:
  496. self.half_height = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['height']) / 2
  497. except KeyError:
  498. pass
  499. if point[0] is None and point[1] is None:
  500. point_x = self.draw_app.x
  501. point_y = self.draw_app.y
  502. else:
  503. point_x = point[0]
  504. point_y = point[1]
  505. ap_type = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['type']
  506. if ap_type == 'C':
  507. new_geo_el = {}
  508. center = Point([point_x, point_y])
  509. new_geo_el['solid'] = center.buffer(self.radius)
  510. new_geo_el['follow'] = center
  511. return new_geo_el
  512. elif ap_type == 'R':
  513. new_geo_el = {}
  514. p1 = (point_x - self.half_width, point_y - self.half_height)
  515. p2 = (point_x + self.half_width, point_y - self.half_height)
  516. p3 = (point_x + self.half_width, point_y + self.half_height)
  517. p4 = (point_x - self.half_width, point_y + self.half_height)
  518. new_geo_el['solid'] = Polygon([p1, p2, p3, p4, p1])
  519. new_geo_el['follow'] = Point([point_x, point_y])
  520. return new_geo_el
  521. elif ap_type == 'O':
  522. geo = []
  523. new_geo_el = {}
  524. if self.half_height > self.half_width:
  525. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  526. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  527. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  528. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  529. down_center = [point_x, point_y - self.half_height + self.half_width]
  530. d_start_angle = np.pi
  531. d_stop_angle = 0.0
  532. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  533. up_center = [point_x, point_y + self.half_height - self.half_width]
  534. u_start_angle = 0.0
  535. u_stop_angle = np.pi
  536. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  537. geo.append(p1)
  538. for pt in down_arc:
  539. geo.append(pt)
  540. geo.append(p2)
  541. geo.append(p3)
  542. for pt in up_arc:
  543. geo.append(pt)
  544. geo.append(p4)
  545. new_geo_el['solid'] = Polygon(geo)
  546. center = Point([point_x, point_y])
  547. new_geo_el['follow'] = center
  548. return new_geo_el
  549. else:
  550. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  551. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  552. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  553. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  554. left_center = [point_x - self.half_width + self.half_height, point_y]
  555. d_start_angle = np.pi / 2
  556. d_stop_angle = 1.5 * np.pi
  557. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  558. right_center = [point_x + self.half_width - self.half_height, point_y]
  559. u_start_angle = 1.5 * np.pi
  560. u_stop_angle = np.pi / 2
  561. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  562. geo.append(p1)
  563. geo.append(p2)
  564. for pt in right_arc:
  565. geo.append(pt)
  566. geo.append(p3)
  567. geo.append(p4)
  568. for pt in left_arc:
  569. geo.append(pt)
  570. new_geo_el['solid'] = Polygon(geo)
  571. center = Point([point_x, point_y])
  572. new_geo_el['follow'] = center
  573. return new_geo_el
  574. else:
  575. self.draw_app.app.inform.emit(_(
  576. "Incompatible aperture type. Select an aperture with type 'C', 'R' or 'O'."))
  577. return None
  578. def make(self):
  579. self.geometry = []
  580. geo = None
  581. self.draw_app.current_storage = self.storage_obj
  582. if self.pad_array == 0: # 'Linear'
  583. for item in range(self.pad_array_size):
  584. if self.pad_axis == 'X':
  585. geo = self.util_shape(((self.points[0] + (self.pad_pitch * item)), self.points[1]))
  586. if self.pad_axis == 'Y':
  587. geo = self.util_shape((self.points[0], (self.points[1] + (self.pad_pitch * item))))
  588. if self.pad_axis == 'A':
  589. x_adj = self.pad_pitch * math.cos(math.radians(self.pad_linear_angle))
  590. y_adj = self.pad_pitch * math.sin(math.radians(self.pad_linear_angle))
  591. geo = self.util_shape(
  592. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  593. )
  594. self.geometry.append(DrawToolShape(geo))
  595. else: # 'Circular'
  596. if (self.pad_angle * self.pad_array_size) > 360:
  597. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' %
  598. _("Too many items for the selected spacing angle."))
  599. return
  600. radius = distance(self.destination, self.origin)
  601. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  602. for i in range(self.pad_array_size):
  603. angle_radians = math.radians(self.pad_angle * i)
  604. if self.pad_direction == 'CW':
  605. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  606. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  607. else:
  608. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  609. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  610. geo = self.util_shape((x, y))
  611. if self.pad_direction == 'CW':
  612. geo = affinity.rotate(geo, angle=(math.pi - angle_radians), use_radians=True)
  613. else:
  614. geo = affinity.rotate(geo, angle=(angle_radians - math.pi), use_radians=True)
  615. self.geometry.append(DrawToolShape(geo))
  616. self.complete = True
  617. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  618. self.draw_app.in_action = False
  619. self.draw_app.ui.array_frame.hide()
  620. self.draw_app.app.jump_signal.disconnect()
  621. def clean_up(self):
  622. self.draw_app.selected = []
  623. self.draw_app.ui.apertures_table.clearSelection()
  624. self.draw_app.plot_all()
  625. try:
  626. self.draw_app.app.jump_signal.disconnect()
  627. except (TypeError, AttributeError):
  628. pass
  629. class FCPoligonize(FCShapeTool):
  630. """
  631. Resulting type: Polygon
  632. """
  633. def __init__(self, draw_app):
  634. DrawTool.__init__(self, draw_app)
  635. self.name = 'poligonize'
  636. self.draw_app = draw_app
  637. self.draw_app.app.inform.emit(_("Select shape(s) and then click ..."))
  638. self.draw_app.in_action = True
  639. self.make()
  640. def click(self, point):
  641. return ""
  642. def make(self):
  643. if not self.draw_app.selected:
  644. self.draw_app.in_action = False
  645. self.complete = True
  646. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  647. _("Failed. Nothing selected."))
  648. self.draw_app.select_tool("select")
  649. return
  650. apcode_set = set()
  651. for elem in self.draw_app.selected:
  652. for apcode in self.draw_app.storage_dict:
  653. if 'geometry' in self.draw_app.storage_dict[apcode]:
  654. if elem in self.draw_app.storage_dict[apcode]['geometry']:
  655. apcode_set.add(apcode)
  656. break
  657. if len(apcode_set) > 1:
  658. self.draw_app.in_action = False
  659. self.complete = True
  660. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s' %
  661. _("Failed. Poligonize works only on geometries belonging "
  662. "to the same aperture."))
  663. self.draw_app.select_tool("select")
  664. return
  665. # exterior_geo = [Polygon(sh.geo.exterior) for sh in self.draw_app.selected]
  666. exterior_geo = []
  667. for geo_shape in self.draw_app.selected:
  668. geometric_data = geo_shape.geo
  669. if 'solid' in geometric_data:
  670. exterior_geo.append(Polygon(geometric_data['solid'].exterior))
  671. fused_geo = MultiPolygon(exterior_geo)
  672. fused_geo = fused_geo.buffer(0.0000001)
  673. current_storage = self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry']
  674. if isinstance(fused_geo, MultiPolygon):
  675. for geo in fused_geo:
  676. # clean-up the geo
  677. geo = geo.buffer(0)
  678. if len(geo.interiors) == 0:
  679. try:
  680. current_storage = self.draw_app.storage_dict['0']['geometry']
  681. except KeyError:
  682. self.draw_app.on_aperture_add(apcode='0')
  683. current_storage = self.draw_app.storage_dict['0']['geometry']
  684. new_el = {'solid': geo, 'follow': geo.exterior}
  685. self.draw_app.on_grb_shape_complete(current_storage, specific_shape=DrawToolShape(deepcopy(new_el)))
  686. else:
  687. # clean-up the geo
  688. fused_geo = fused_geo.buffer(0)
  689. if len(fused_geo.interiors) == 0 and len(exterior_geo) == 1:
  690. try:
  691. current_storage = self.draw_app.storage_dict['0']['geometry']
  692. except KeyError:
  693. self.draw_app.on_aperture_add(apcode='0')
  694. current_storage = self.draw_app.storage_dict['0']['geometry']
  695. new_el = {'solid': fused_geo, 'follow': fused_geo.exterior}
  696. self.draw_app.on_grb_shape_complete(current_storage, specific_shape=DrawToolShape(deepcopy(new_el)))
  697. self.draw_app.delete_selected()
  698. self.draw_app.plot_all()
  699. self.draw_app.in_action = False
  700. self.complete = True
  701. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  702. # MS: always return to the Select Tool if modifier key is not pressed
  703. # else return to the current tool
  704. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  705. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  706. modifier_to_use = Qt.ControlModifier
  707. else:
  708. modifier_to_use = Qt.ShiftModifier
  709. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  710. # in the selected list, we removed it. Therefore first click selects, second deselects.
  711. if key_modifier == modifier_to_use:
  712. self.draw_app.select_tool(self.draw_app.active_tool.name)
  713. else:
  714. self.draw_app.select_tool("select")
  715. return
  716. def clean_up(self):
  717. self.draw_app.selected = []
  718. self.draw_app.ui.apertures_table.clearSelection()
  719. self.draw_app.plot_all()
  720. class FCRegion(FCShapeTool):
  721. """
  722. Resulting type: Polygon
  723. """
  724. def __init__(self, draw_app):
  725. DrawTool.__init__(self, draw_app)
  726. self.name = 'region'
  727. self.draw_app = draw_app
  728. self.dont_execute = False
  729. self.steps_per_circle = self.draw_app.app.defaults["gerber_circle_steps"]
  730. try:
  731. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  732. except KeyError:
  733. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  734. _("You need to preselect a aperture in the Aperture Table that has a size."))
  735. try:
  736. QtGui.QGuiApplication.restoreOverrideCursor()
  737. except Exception:
  738. pass
  739. self.dont_execute = True
  740. self.draw_app.in_action = False
  741. self.complete = True
  742. self.draw_app.select_tool('select')
  743. return
  744. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  745. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  746. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  747. self.temp_points = []
  748. # this will store the inflexion point in the geometry
  749. self.inter_point = None
  750. try:
  751. QtGui.QGuiApplication.restoreOverrideCursor()
  752. except Exception as e:
  753. log.debug("AppGerberEditor.FCRegion --> %s" % str(e))
  754. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero.png'))
  755. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  756. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  757. self.draw_app.app.inform.emit(_('Corner Mode 1: 45 degrees ...'))
  758. self.start_msg = _("Click on 1st point ...")
  759. def click(self, point):
  760. self.draw_app.in_action = True
  761. if self.inter_point is not None:
  762. self.points.append(self.inter_point)
  763. self.points.append(point)
  764. if len(self.points) > 0:
  765. self.draw_app.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  766. return "Click on next point or hit ENTER to complete ..."
  767. return ""
  768. def update_grid_info(self):
  769. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  770. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  771. def utility_geometry(self, data=None):
  772. if self.dont_execute is True:
  773. self.draw_app.select_tool('select')
  774. return
  775. new_geo_el = {}
  776. x = data[0]
  777. y = data[1]
  778. if len(self.points) == 0:
  779. new_geo_el['solid'] = Point(data).buffer(self.buf_val, resolution=int(self.steps_per_circle / 4))
  780. return DrawToolUtilityShape(new_geo_el)
  781. if len(self.points) == 1:
  782. self.temp_points = [x for x in self.points]
  783. old_x = self.points[0][0]
  784. old_y = self.points[0][1]
  785. mx = abs(round((x - old_x) / self.gridx_size))
  786. my = abs(round((y - old_y) / self.gridy_size))
  787. if mx and my:
  788. if self.draw_app.app.ui.grid_snap_btn.isChecked():
  789. if self.draw_app.bend_mode != 5:
  790. if self.draw_app.bend_mode == 1:
  791. if x > old_x:
  792. if mx > my:
  793. self.inter_point = (old_x + self.gridx_size * (mx - my), old_y)
  794. if mx < my:
  795. if y < old_y:
  796. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  797. else:
  798. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  799. if x < old_x:
  800. if mx > my:
  801. self.inter_point = (old_x - self.gridx_size * (mx - my), old_y)
  802. if mx < my:
  803. if y < old_y:
  804. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  805. else:
  806. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  807. elif self.draw_app.bend_mode == 2:
  808. if x > old_x:
  809. if mx > my:
  810. self.inter_point = (old_x + self.gridx_size * my, y)
  811. if mx < my:
  812. if y < old_y:
  813. self.inter_point = (x, old_y - self.gridy_size * mx)
  814. else:
  815. self.inter_point = (x, old_y + self.gridy_size * mx)
  816. if x < old_x:
  817. if mx > my:
  818. self.inter_point = (old_x - self.gridx_size * my, y)
  819. if mx < my:
  820. if y < old_y:
  821. self.inter_point = (x, old_y - self.gridy_size * mx)
  822. else:
  823. self.inter_point = (x, old_y + self.gridy_size * mx)
  824. elif self.draw_app.bend_mode == 3:
  825. self.inter_point = (x, old_y)
  826. elif self.draw_app.bend_mode == 4:
  827. self.inter_point = (old_x, y)
  828. if self.inter_point is not None:
  829. self.temp_points.append(self.inter_point)
  830. else:
  831. self.inter_point = data
  832. else:
  833. self.inter_point = data
  834. self.temp_points.append(data)
  835. new_geo_el = {}
  836. if len(self.temp_points) > 1:
  837. try:
  838. new_geo_el['solid'] = LineString(self.temp_points).buffer(self.buf_val,
  839. resolution=int(self.steps_per_circle / 4),
  840. join_style=1)
  841. return DrawToolUtilityShape(new_geo_el)
  842. except Exception as e:
  843. log.debug("AppGerberEditor.FCRegion.utility_geometry() --> %s" % str(e))
  844. else:
  845. new_geo_el['solid'] = Point(self.temp_points).buffer(self.buf_val,
  846. resolution=int(self.steps_per_circle / 4))
  847. return DrawToolUtilityShape(new_geo_el)
  848. if len(self.points) > 2:
  849. self.temp_points = [x for x in self.points]
  850. old_x = self.points[-1][0]
  851. old_y = self.points[-1][1]
  852. mx = abs(round((x - old_x) / self.gridx_size))
  853. my = abs(round((y - old_y) / self.gridy_size))
  854. if mx and my:
  855. if self.draw_app.app.ui.grid_snap_btn.isChecked():
  856. if self.draw_app.bend_mode != 5:
  857. if self.draw_app.bend_mode == 1:
  858. if x > old_x:
  859. if mx > my:
  860. self.inter_point = (old_x + self.gridx_size * (mx - my), old_y)
  861. if mx < my:
  862. if y < old_y:
  863. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  864. else:
  865. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  866. if x < old_x:
  867. if mx > my:
  868. self.inter_point = (old_x - self.gridx_size * (mx - my), old_y)
  869. if mx < my:
  870. if y < old_y:
  871. self.inter_point = (old_x, old_y - self.gridy_size * (my - mx))
  872. else:
  873. self.inter_point = (old_x, old_y - self.gridy_size * (mx - my))
  874. elif self.draw_app.bend_mode == 2:
  875. if x > old_x:
  876. if mx > my:
  877. self.inter_point = (old_x + self.gridx_size * my, y)
  878. if mx < my:
  879. if y < old_y:
  880. self.inter_point = (x, old_y - self.gridy_size * mx)
  881. else:
  882. self.inter_point = (x, old_y + self.gridy_size * mx)
  883. if x < old_x:
  884. if mx > my:
  885. self.inter_point = (old_x - self.gridx_size * my, y)
  886. if mx < my:
  887. if y < old_y:
  888. self.inter_point = (x, old_y - self.gridy_size * mx)
  889. else:
  890. self.inter_point = (x, old_y + self.gridy_size * mx)
  891. elif self.draw_app.bend_mode == 3:
  892. self.inter_point = (x, old_y)
  893. elif self.draw_app.bend_mode == 4:
  894. self.inter_point = (old_x, y)
  895. self.temp_points.append(self.inter_point)
  896. self.temp_points.append(data)
  897. new_geo_el = {
  898. 'solid': LinearRing(self.temp_points).buffer(self.buf_val,
  899. resolution=int(self.steps_per_circle / 4),
  900. join_style=1),
  901. 'follow': LinearRing(self.temp_points)}
  902. return DrawToolUtilityShape(new_geo_el)
  903. return None
  904. def make(self):
  905. # self.geometry = LinearRing(self.points)
  906. if len(self.points) > 2:
  907. # regions are added always in the '0' aperture
  908. if '0' not in self.draw_app.storage_dict:
  909. self.draw_app.on_aperture_add(apcode='0')
  910. else:
  911. self.draw_app.last_aperture_selected = '0'
  912. new_geo_el = {
  913. 'solid': Polygon(self.points).buffer(self.buf_val,
  914. resolution=int(self.steps_per_circle / 4),
  915. join_style=2), 'follow': Polygon(self.points).exterior
  916. }
  917. self.geometry = DrawToolShape(new_geo_el)
  918. self.draw_app.in_action = False
  919. self.complete = True
  920. self.draw_app.app.jump_signal.disconnect()
  921. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  922. def on_key(self, key):
  923. # Jump to coords
  924. if key == QtCore.Qt.Key_J or key == 'J':
  925. self.draw_app.app.on_jump_to()
  926. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  927. if len(self.points) > 0:
  928. if self.draw_app.bend_mode == 5:
  929. self.points = self.points[0:-1]
  930. else:
  931. self.points = self.points[0:-2]
  932. # Remove any previous utility shape
  933. self.draw_app.tool_shape.clear(update=False)
  934. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  935. self.draw_app.draw_utility_geometry(geo=geo)
  936. return _("Backtracked one point ...")
  937. if key == 'T' or key == QtCore.Qt.Key_T:
  938. if self.draw_app.bend_mode == 1:
  939. self.draw_app.bend_mode = 2
  940. msg = _('Corner Mode 2: Reverse 45 degrees ...')
  941. elif self.draw_app.bend_mode == 2:
  942. self.draw_app.bend_mode = 3
  943. msg = _('Corner Mode 3: 90 degrees ...')
  944. elif self.draw_app.bend_mode == 3:
  945. self.draw_app.bend_mode = 4
  946. msg = _('Corner Mode 4: Reverse 90 degrees ...')
  947. elif self.draw_app.bend_mode == 4:
  948. self.draw_app.bend_mode = 5
  949. msg = _('Corner Mode 5: Free angle ...')
  950. else:
  951. self.draw_app.bend_mode = 1
  952. msg = _('Corner Mode 1: 45 degrees ...')
  953. # Remove any previous utility shape
  954. self.draw_app.tool_shape.clear(update=False)
  955. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  956. self.draw_app.draw_utility_geometry(geo=geo)
  957. return msg
  958. if key == 'R' or key == QtCore.Qt.Key_R:
  959. if self.draw_app.bend_mode == 1:
  960. self.draw_app.bend_mode = 5
  961. msg = _('Corner Mode 5: Free angle ...')
  962. elif self.draw_app.bend_mode == 5:
  963. self.draw_app.bend_mode = 4
  964. msg = _('Corner Mode 4: Reverse 90 degrees ...')
  965. elif self.draw_app.bend_mode == 4:
  966. self.draw_app.bend_mode = 3
  967. msg = _('Corner Mode 3: 90 degrees ...')
  968. elif self.draw_app.bend_mode == 3:
  969. self.draw_app.bend_mode = 2
  970. msg = _('Corner Mode 2: Reverse 45 degrees ...')
  971. else:
  972. self.draw_app.bend_mode = 1
  973. msg = _('Corner Mode 1: 45 degrees ...')
  974. # Remove any previous utility shape
  975. self.draw_app.tool_shape.clear(update=False)
  976. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  977. self.draw_app.draw_utility_geometry(geo=geo)
  978. return msg
  979. def clean_up(self):
  980. self.draw_app.selected = []
  981. self.draw_app.ui.apertures_table.clearSelection()
  982. self.draw_app.plot_all()
  983. try:
  984. self.draw_app.app.jump_signal.disconnect()
  985. except (TypeError, AttributeError):
  986. pass
  987. class FCTrack(FCShapeTool):
  988. """
  989. Resulting type: Polygon
  990. """
  991. def __init__(self, draw_app):
  992. DrawTool.__init__(self, draw_app)
  993. self.name = 'track'
  994. self.draw_app = draw_app
  995. self.dont_execute = False
  996. self.steps_per_circle = self.draw_app.app.defaults["gerber_circle_steps"]
  997. try:
  998. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  999. except KeyError:
  1000. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  1001. _("You need to preselect a aperture in the Aperture Table that has a size."))
  1002. try:
  1003. QtGui.QGuiApplication.restoreOverrideCursor()
  1004. except Exception:
  1005. pass
  1006. self.dont_execute = True
  1007. self.draw_app.in_action = False
  1008. self.complete = True
  1009. self.draw_app.select_tool('select')
  1010. return
  1011. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  1012. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  1013. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  1014. self.temp_points = []
  1015. self.final_click = False
  1016. try:
  1017. QtGui.QGuiApplication.restoreOverrideCursor()
  1018. except Exception as e:
  1019. log.debug("AppGerberEditor.FCTrack.__init__() --> %s" % str(e))
  1020. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location +
  1021. '/aero_path%s.png' % self.draw_app.bend_mode))
  1022. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1023. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1024. self.draw_app.app.inform.emit(_('Track Mode 1: 45 degrees ...'))
  1025. def click(self, point):
  1026. self.draw_app.in_action = True
  1027. if not self.points:
  1028. self.points.append(point)
  1029. elif point != self.points[-1]:
  1030. self.points.append(point)
  1031. else:
  1032. return
  1033. new_geo_el = {}
  1034. if len(self.temp_points) == 1:
  1035. new_geo_el['solid'] = Point(self.temp_points).buffer(self.buf_val, int(self.steps_per_circle))
  1036. new_geo_el['follow'] = Point(self.temp_points)
  1037. else:
  1038. new_geo_el['solid'] = LineString(self.temp_points).buffer(self.buf_val, int(self.steps_per_circle))
  1039. new_geo_el['follow'] = LineString(self.temp_points)
  1040. self.draw_app.add_gerber_shape(DrawToolShape(new_geo_el),
  1041. self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['geometry'])
  1042. self.draw_app.plot_all()
  1043. if len(self.points) > 0:
  1044. self.draw_app.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  1045. return "Click on next point or hit ENTER to complete ..."
  1046. return ""
  1047. def update_grid_info(self):
  1048. self.gridx_size = float(self.draw_app.app.ui.grid_gap_x_entry.get_value())
  1049. self.gridy_size = float(self.draw_app.app.ui.grid_gap_y_entry.get_value())
  1050. def utility_geometry(self, data=None):
  1051. if self.dont_execute is True:
  1052. self.draw_app.select_tool('select')
  1053. return
  1054. self.update_grid_info()
  1055. new_geo_el = {}
  1056. if not self.points:
  1057. new_geo_el['solid'] = Point(data).buffer(self.buf_val, int(self.steps_per_circle))
  1058. return DrawToolUtilityShape(new_geo_el)
  1059. else:
  1060. old_x = self.points[-1][0]
  1061. old_y = self.points[-1][1]
  1062. x = data[0]
  1063. y = data[1]
  1064. self.temp_points = [self.points[-1]]
  1065. mx = abs(round((x - old_x) / self.gridx_size))
  1066. my = abs(round((y - old_y) / self.gridy_size))
  1067. if self.draw_app.app.ui.grid_snap_btn.isChecked():
  1068. if self.draw_app.bend_mode == 1:
  1069. if x > old_x:
  1070. if mx > my:
  1071. self.temp_points.append((old_x + self.gridx_size*(mx-my), old_y))
  1072. if mx < my:
  1073. if y < old_y:
  1074. self.temp_points.append((old_x, old_y - self.gridy_size * (my-mx)))
  1075. else:
  1076. self.temp_points.append((old_x, old_y - self.gridy_size * (mx-my)))
  1077. if x < old_x:
  1078. if mx > my:
  1079. self.temp_points.append((old_x - self.gridx_size*(mx-my), old_y))
  1080. if mx < my:
  1081. if y < old_y:
  1082. self.temp_points.append((old_x, old_y - self.gridy_size * (my-mx)))
  1083. else:
  1084. self.temp_points.append((old_x, old_y - self.gridy_size * (mx-my)))
  1085. elif self.draw_app.bend_mode == 2:
  1086. if x > old_x:
  1087. if mx > my:
  1088. self.temp_points.append((old_x + self.gridx_size*my, y))
  1089. if mx < my:
  1090. if y < old_y:
  1091. self.temp_points.append((x, old_y - self.gridy_size * mx))
  1092. else:
  1093. self.temp_points.append((x, old_y + self.gridy_size * mx))
  1094. if x < old_x:
  1095. if mx > my:
  1096. self.temp_points.append((old_x - self.gridx_size * my, y))
  1097. if mx < my:
  1098. if y < old_y:
  1099. self.temp_points.append((x, old_y - self.gridy_size * mx))
  1100. else:
  1101. self.temp_points.append((x, old_y + self.gridy_size * mx))
  1102. elif self.draw_app.bend_mode == 3:
  1103. self.temp_points.append((x, old_y))
  1104. elif self.draw_app.bend_mode == 4:
  1105. self.temp_points.append((old_x, y))
  1106. else:
  1107. pass
  1108. self.temp_points.append(data)
  1109. if len(self.temp_points) == 1:
  1110. new_geo_el['solid'] = Point(self.temp_points).buffer(self.buf_val, int(self.steps_per_circle))
  1111. return DrawToolUtilityShape(new_geo_el)
  1112. new_geo_el['solid'] = LineString(self.temp_points).buffer(self.buf_val, int(self.steps_per_circle))
  1113. return DrawToolUtilityShape(new_geo_el)
  1114. def make(self):
  1115. new_geo_el = {}
  1116. if len(self.temp_points) == 1:
  1117. new_geo_el['solid'] = Point(self.temp_points).buffer(self.buf_val, int(self.steps_per_circle))
  1118. new_geo_el['follow'] = Point(self.temp_points)
  1119. else:
  1120. new_geo_el['solid'] = LineString(self.temp_points).buffer(self.buf_val, int(self.steps_per_circle))
  1121. new_geo_el['solid'] = new_geo_el['solid'].buffer(0) # try to clean the geometry
  1122. new_geo_el['follow'] = LineString(self.temp_points)
  1123. self.geometry = DrawToolShape(new_geo_el)
  1124. self.draw_app.in_action = False
  1125. self.complete = True
  1126. self.draw_app.app.jump_signal.disconnect()
  1127. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  1128. def on_key(self, key):
  1129. if key == 'Backspace' or key == QtCore.Qt.Key_Backspace:
  1130. if len(self.points) > 0:
  1131. self.temp_points = self.points[0:-1]
  1132. # Remove any previous utility shape
  1133. self.draw_app.tool_shape.clear(update=False)
  1134. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1135. self.draw_app.draw_utility_geometry(geo=geo)
  1136. return _("Backtracked one point ...")
  1137. # Jump to coords
  1138. if key == QtCore.Qt.Key_J or key == 'J':
  1139. self.draw_app.app.on_jump_to()
  1140. if key == 'T' or key == QtCore.Qt.Key_T:
  1141. try:
  1142. QtGui.QGuiApplication.restoreOverrideCursor()
  1143. except Exception as e:
  1144. log.debug("AppGerberEditor.FCTrack.on_key() --> %s" % str(e))
  1145. if self.draw_app.bend_mode == 1:
  1146. self.draw_app.bend_mode = 2
  1147. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path2.png'))
  1148. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1149. msg = _('Track Mode 2: Reverse 45 degrees ...')
  1150. elif self.draw_app.bend_mode == 2:
  1151. self.draw_app.bend_mode = 3
  1152. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path3.png'))
  1153. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1154. msg = _('Track Mode 3: 90 degrees ...')
  1155. elif self.draw_app.bend_mode == 3:
  1156. self.draw_app.bend_mode = 4
  1157. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path4.png'))
  1158. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1159. msg = _('Track Mode 4: Reverse 90 degrees ...')
  1160. elif self.draw_app.bend_mode == 4:
  1161. self.draw_app.bend_mode = 5
  1162. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path5.png'))
  1163. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1164. msg = _('Track Mode 5: Free angle ...')
  1165. else:
  1166. self.draw_app.bend_mode = 1
  1167. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path1.png'))
  1168. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1169. msg = _('Track Mode 1: 45 degrees ...')
  1170. # Remove any previous utility shape
  1171. self.draw_app.tool_shape.clear(update=False)
  1172. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1173. self.draw_app.draw_utility_geometry(geo=geo)
  1174. return msg
  1175. if key == 'R' or key == QtCore.Qt.Key_R:
  1176. try:
  1177. QtGui.QGuiApplication.restoreOverrideCursor()
  1178. except Exception as e:
  1179. log.debug("AppGerberEditor.FCTrack.on_key() --> %s" % str(e))
  1180. if self.draw_app.bend_mode == 1:
  1181. self.draw_app.bend_mode = 5
  1182. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path5.png'))
  1183. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1184. msg = _('Track Mode 5: Free angle ...')
  1185. elif self.draw_app.bend_mode == 5:
  1186. self.draw_app.bend_mode = 4
  1187. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path4.png'))
  1188. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1189. msg = _('Track Mode 4: Reverse 90 degrees ...')
  1190. elif self.draw_app.bend_mode == 4:
  1191. self.draw_app.bend_mode = 3
  1192. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path3.png'))
  1193. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1194. msg = _('Track Mode 3: 90 degrees ...')
  1195. elif self.draw_app.bend_mode == 3:
  1196. self.draw_app.bend_mode = 2
  1197. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path2.png'))
  1198. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1199. msg = _('Track Mode 2: Reverse 45 degrees ...')
  1200. else:
  1201. self.draw_app.bend_mode = 1
  1202. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_path1.png'))
  1203. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1204. msg = _('Track Mode 1: 45 degrees ...')
  1205. # Remove any previous utility shape
  1206. self.draw_app.tool_shape.clear(update=False)
  1207. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  1208. self.draw_app.draw_utility_geometry(geo=geo)
  1209. return msg
  1210. def clean_up(self):
  1211. self.draw_app.selected = []
  1212. self.draw_app.ui.apertures_table.clearSelection()
  1213. self.draw_app.plot_all()
  1214. try:
  1215. self.draw_app.app.jump_signal.disconnect()
  1216. except (TypeError, AttributeError):
  1217. pass
  1218. class FCDisc(FCShapeTool):
  1219. """
  1220. Resulting type: Polygon
  1221. """
  1222. def __init__(self, draw_app):
  1223. DrawTool.__init__(self, draw_app)
  1224. self.name = 'disc'
  1225. self.dont_execute = False
  1226. try:
  1227. QtGui.QGuiApplication.restoreOverrideCursor()
  1228. except Exception:
  1229. pass
  1230. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_disc.png'))
  1231. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1232. try:
  1233. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  1234. except KeyError:
  1235. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  1236. _("You need to preselect a aperture in the Aperture Table that has a size."))
  1237. try:
  1238. QtGui.QGuiApplication.restoreOverrideCursor()
  1239. except Exception:
  1240. pass
  1241. self.dont_execute = True
  1242. self.draw_app.in_action = False
  1243. self.complete = True
  1244. self.draw_app.select_tool('select')
  1245. return
  1246. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  1247. if '0' in self.draw_app.storage_dict:
  1248. self.storage_obj = self.draw_app.storage_dict['0']['geometry']
  1249. else:
  1250. self.draw_app.storage_dict['0'] = {
  1251. 'type': 'C',
  1252. 'size': 0.0,
  1253. 'geometry': []
  1254. }
  1255. self.storage_obj = self.draw_app.storage_dict['0']['geometry']
  1256. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1257. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1258. self.steps_per_circ = self.draw_app.app.defaults["gerber_circle_steps"]
  1259. def click(self, point):
  1260. self.points.append(point)
  1261. if len(self.points) == 1:
  1262. self.draw_app.app.inform.emit(_("Click on Perimeter point to complete ..."))
  1263. return "Click on Perimeter to complete ..."
  1264. if len(self.points) == 2:
  1265. self.make()
  1266. return "Done."
  1267. return ""
  1268. def utility_geometry(self, data=None):
  1269. if self.dont_execute is True:
  1270. self.draw_app.select_tool('select')
  1271. return
  1272. new_geo_el = {}
  1273. if len(self.points) == 1:
  1274. p1 = self.points[0]
  1275. p2 = data
  1276. radius = math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1277. new_geo_el['solid'] = Point(p1).buffer((radius + self.buf_val / 2), int(self.steps_per_circ / 4))
  1278. return DrawToolUtilityShape(new_geo_el)
  1279. return None
  1280. def make(self):
  1281. new_geo_el = {}
  1282. try:
  1283. QtGui.QGuiApplication.restoreOverrideCursor()
  1284. except Exception as e:
  1285. log.debug("AppGerberEditor.FCDisc --> %s" % str(e))
  1286. self.draw_app.current_storage = self.storage_obj
  1287. p1 = self.points[0]
  1288. p2 = self.points[1]
  1289. radius = distance(p1, p2)
  1290. new_geo_el['solid'] = Point(p1).buffer((radius + self.buf_val / 2), int(self.steps_per_circ / 4))
  1291. new_geo_el['follow'] = Point(p1).buffer((radius + self.buf_val / 2), int(self.steps_per_circ / 4)).exterior
  1292. self.geometry = DrawToolShape(new_geo_el)
  1293. self.draw_app.in_action = False
  1294. self.complete = True
  1295. self.draw_app.app.jump_signal.disconnect()
  1296. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  1297. def clean_up(self):
  1298. self.draw_app.selected = []
  1299. self.draw_app.ui.apertures_table.clearSelection()
  1300. self.draw_app.plot_all()
  1301. try:
  1302. self.draw_app.app.jump_signal.disconnect()
  1303. except (TypeError, AttributeError):
  1304. pass
  1305. class FCSemiDisc(FCShapeTool):
  1306. def __init__(self, draw_app):
  1307. DrawTool.__init__(self, draw_app)
  1308. self.name = 'semidisc'
  1309. self.dont_execute = False
  1310. try:
  1311. QtGui.QGuiApplication.restoreOverrideCursor()
  1312. except Exception as e:
  1313. log.debug("AppGerberEditor.FCSemiDisc --> %s" % str(e))
  1314. self.cursor = QtGui.QCursor(QtGui.QPixmap(self.draw_app.app.resource_location + '/aero_semidisc.png'))
  1315. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  1316. self.draw_app.app.inform.emit(_("Click on Center point ..."))
  1317. # Direction of rotation between point 1 and 2.
  1318. # 'cw' or 'ccw'. Switch direction by hitting the
  1319. # 'o' key.
  1320. self.direction = "cw"
  1321. # Mode
  1322. # C12 = Center, p1, p2
  1323. # 12C = p1, p2, Center
  1324. # 132 = p1, p3, p2
  1325. self.mode = "c12" # Center, p1, p2
  1326. try:
  1327. size_ap = float(self.draw_app.storage_dict[self.draw_app.last_aperture_selected]['size'])
  1328. except KeyError:
  1329. self.draw_app.app.inform.emit('[ERROR_NOTCL] %s' %
  1330. _("You need to preselect a aperture in the Aperture Table that has a size."))
  1331. try:
  1332. QtGui.QGuiApplication.restoreOverrideCursor()
  1333. except Exception:
  1334. pass
  1335. self.dont_execute = True
  1336. self.draw_app.in_action = False
  1337. self.complete = True
  1338. self.draw_app.select_tool('select')
  1339. return
  1340. self.buf_val = (size_ap / 2) if size_ap > 0 else 0.0000001
  1341. if '0' in self.draw_app.storage_dict:
  1342. self.storage_obj = self.draw_app.storage_dict['0']['geometry']
  1343. else:
  1344. self.draw_app.storage_dict['0'] = {
  1345. 'type': 'C',
  1346. 'size': 0.0,
  1347. 'geometry': []
  1348. }
  1349. self.storage_obj = self.draw_app.storage_dict['0']['geometry']
  1350. self.steps_per_circ = self.draw_app.app.defaults["gerber_circle_steps"]
  1351. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1352. def click(self, point):
  1353. self.points.append(point)
  1354. if len(self.points) == 1:
  1355. if self.mode == 'c12':
  1356. self.draw_app.app.inform.emit(_("Click on Start point ..."))
  1357. elif self.mode == '132':
  1358. self.draw_app.app.inform.emit(_("Click on Point3 ..."))
  1359. else:
  1360. self.draw_app.app.inform.emit(_("Click on Stop point ..."))
  1361. return "Click on 1st point ..."
  1362. if len(self.points) == 2:
  1363. if self.mode == 'c12':
  1364. self.draw_app.app.inform.emit(_("Click on Stop point to complete ..."))
  1365. elif self.mode == '132':
  1366. self.draw_app.app.inform.emit(_("Click on Point2 to complete ..."))
  1367. else:
  1368. self.draw_app.app.inform.emit(_("Click on Center point to complete ..."))
  1369. return "Click on 2nd point to complete ..."
  1370. if len(self.points) == 3:
  1371. self.make()
  1372. return "Done."
  1373. return ""
  1374. def on_key(self, key):
  1375. if key == 'D' or key == QtCore.Qt.Key_D:
  1376. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1377. return '%s: %s' % (_('Direction'), self.direction.upper())
  1378. # Jump to coords
  1379. if key == QtCore.Qt.Key_J or key == 'J':
  1380. self.draw_app.app.on_jump_to()
  1381. if key == 'M' or key == QtCore.Qt.Key_M:
  1382. # delete the possible points made before this action; we want to start anew
  1383. self.points = []
  1384. # and delete the utility geometry made up until this point
  1385. self.draw_app.delete_utility_geometry()
  1386. if self.mode == 'c12':
  1387. self.mode = '12c'
  1388. return _('Mode: Start -> Stop -> Center. Click on Start point ...')
  1389. elif self.mode == '12c':
  1390. self.mode = '132'
  1391. return _('Mode: Point1 -> Point3 -> Point2. Click on Point1 ...')
  1392. else:
  1393. self.mode = 'c12'
  1394. return _('Mode: Center -> Start -> Stop. Click on Center point ...')
  1395. def utility_geometry(self, data=None):
  1396. if self.dont_execute is True:
  1397. self.draw_app.select_tool('select')
  1398. return
  1399. new_geo_el = {}
  1400. new_geo_el_pt1 = {}
  1401. new_geo_el_pt2 = {}
  1402. new_geo_el_pt3 = {}
  1403. if len(self.points) == 1: # Show the radius
  1404. center = self.points[0]
  1405. p1 = data
  1406. new_geo_el['solid'] = LineString([center, p1])
  1407. return DrawToolUtilityShape(new_geo_el)
  1408. if len(self.points) == 2: # Show the arc
  1409. if self.mode == 'c12':
  1410. center = self.points[0]
  1411. p1 = self.points[1]
  1412. p2 = data
  1413. radius = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2) + (self.buf_val / 2)
  1414. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1415. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1416. new_geo_el['solid'] = LineString(
  1417. arc(center, radius, startangle, stopangle, self.direction, self.steps_per_circ))
  1418. new_geo_el_pt1['solid'] = Point(center)
  1419. return DrawToolUtilityShape([new_geo_el, new_geo_el_pt1])
  1420. elif self.mode == '132':
  1421. p1 = np.array(self.points[0])
  1422. p3 = np.array(self.points[1])
  1423. p2 = np.array(data)
  1424. try:
  1425. center, radius, t = three_point_circle(p1, p2, p3)
  1426. except TypeError:
  1427. return
  1428. direction = 'cw' if np.sign(t) > 0 else 'ccw'
  1429. radius += (self.buf_val / 2)
  1430. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1431. stopangle = np.arctan2(p3[1] - center[1], p3[0] - center[0])
  1432. new_geo_el['solid'] = LineString(
  1433. arc(center, radius, startangle, stopangle, direction, self.steps_per_circ))
  1434. new_geo_el_pt2['solid'] = Point(center)
  1435. new_geo_el_pt1['solid'] = Point(p1)
  1436. new_geo_el_pt3['solid'] = Point(p3)
  1437. return DrawToolUtilityShape([new_geo_el, new_geo_el_pt2, new_geo_el_pt1, new_geo_el_pt3])
  1438. else: # '12c'
  1439. p1 = np.array(self.points[0])
  1440. p2 = np.array(self.points[1])
  1441. # Midpoint
  1442. a = (p1 + p2) / 2.0
  1443. # Parallel vector
  1444. c = p2 - p1
  1445. # Perpendicular vector
  1446. b = np.dot(c, np.array([[0, -1], [1, 0]], dtype=np.float32))
  1447. b /= numpy_norm(b)
  1448. # Distance
  1449. t = distance(data, a)
  1450. # Which side? Cross product with c.
  1451. # cross(M-A, B-A), where line is AB and M is test point.
  1452. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1453. t *= np.sign(side)
  1454. # Center = a + bt
  1455. center = a + b * t
  1456. radius = numpy_norm(center - p1) + (self.buf_val / 2)
  1457. startangle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1458. stopangle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1459. new_geo_el['solid'] = LineString(
  1460. arc(center, radius, startangle, stopangle, self.direction, self.steps_per_circ))
  1461. new_geo_el_pt2['solid'] = Point(center)
  1462. return DrawToolUtilityShape([new_geo_el, new_geo_el_pt2])
  1463. return None
  1464. def make(self):
  1465. self.draw_app.current_storage = self.storage_obj
  1466. new_geo_el = {}
  1467. if self.mode == 'c12':
  1468. center = self.points[0]
  1469. p1 = self.points[1]
  1470. p2 = self.points[2]
  1471. radius = distance(center, p1) + (self.buf_val / 2)
  1472. start_angle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1473. stop_angle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1474. new_geo_el['solid'] = Polygon(
  1475. arc(center, radius, start_angle, stop_angle, self.direction, self.steps_per_circ))
  1476. new_geo_el['follow'] = Polygon(
  1477. arc(center, radius, start_angle, stop_angle, self.direction, self.steps_per_circ)).exterior
  1478. self.geometry = DrawToolShape(new_geo_el)
  1479. elif self.mode == '132':
  1480. p1 = np.array(self.points[0])
  1481. p3 = np.array(self.points[1])
  1482. p2 = np.array(self.points[2])
  1483. center, radius, t = three_point_circle(p1, p2, p3)
  1484. direction = 'cw' if np.sign(t) > 0 else 'ccw'
  1485. radius += (self.buf_val / 2)
  1486. start_angle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1487. stop_angle = np.arctan2(p3[1] - center[1], p3[0] - center[0])
  1488. new_geo_el['solid'] = Polygon(arc(center, radius, start_angle, stop_angle, direction, self.steps_per_circ))
  1489. new_geo_el['follow'] = Polygon(
  1490. arc(center, radius, start_angle, stop_angle, direction, self.steps_per_circ)).exterior
  1491. self.geometry = DrawToolShape(new_geo_el)
  1492. else: # self.mode == '12c'
  1493. p1 = np.array(self.points[0])
  1494. p2 = np.array(self.points[1])
  1495. pc = np.array(self.points[2])
  1496. # Midpoint
  1497. a = (p1 + p2) / 2.0
  1498. # Parallel vector
  1499. c = p2 - p1
  1500. # Perpendicular vector
  1501. b = np.dot(c, np.array([[0, -1], [1, 0]], dtype=np.float32))
  1502. b /= numpy_norm(b)
  1503. # Distance
  1504. t = distance(pc, a)
  1505. # Which side? Cross product with c.
  1506. # cross(M-A, B-A), where line is AB and M is test point.
  1507. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1508. t *= np.sign(side)
  1509. # Center = a + bt
  1510. center = a + b * t
  1511. radius = numpy_norm(center - p1) + (self.buf_val / 2)
  1512. start_angle = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  1513. stop_angle = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  1514. new_geo_el['solid'] = Polygon(
  1515. arc(center, radius, start_angle, stop_angle, self.direction, self.steps_per_circ))
  1516. new_geo_el['follow'] = Polygon(
  1517. arc(center, radius, start_angle, stop_angle, self.direction, self.steps_per_circ)).exterior
  1518. self.geometry = DrawToolShape(new_geo_el)
  1519. self.draw_app.in_action = False
  1520. self.complete = True
  1521. self.draw_app.app.jump_signal.disconnect()
  1522. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  1523. def clean_up(self):
  1524. self.draw_app.selected = []
  1525. self.draw_app.ui.apertures_table.clearSelection()
  1526. self.draw_app.plot_all()
  1527. try:
  1528. self.draw_app.app.jump_signal.disconnect()
  1529. except (TypeError, AttributeError):
  1530. pass
  1531. class FCScale(FCShapeTool):
  1532. def __init__(self, draw_app):
  1533. FCShapeTool.__init__(self, draw_app)
  1534. self.name = 'scale'
  1535. # self.shape_buffer = self.draw_app.shape_buffer
  1536. self.draw_app = draw_app
  1537. self.app = draw_app.app
  1538. self.draw_app.app.inform.emit(_("Scale the selected Gerber apertures ..."))
  1539. self.origin = (0, 0)
  1540. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  1541. self.draw_app.app.ui.splitter.setSizes([1, 1])
  1542. self.activate_scale()
  1543. def activate_scale(self):
  1544. self.draw_app.hide_tool('all')
  1545. self.draw_app.ui.scale_tool_frame.show()
  1546. try:
  1547. self.draw_app.ui.scale_button.clicked.disconnect()
  1548. except (TypeError, AttributeError):
  1549. pass
  1550. self.draw_app.ui.scale_button.clicked.connect(self.on_scale_click)
  1551. def deactivate_scale(self):
  1552. self.draw_app.ui.scale_button.clicked.disconnect()
  1553. self.complete = True
  1554. self.draw_app.select_tool("select")
  1555. self.draw_app.hide_tool(self.name)
  1556. def on_scale_click(self):
  1557. self.draw_app.on_scale()
  1558. self.deactivate_scale()
  1559. def clean_up(self):
  1560. self.draw_app.selected = []
  1561. self.draw_app.ui.apertures_table.clearSelection()
  1562. self.draw_app.plot_all()
  1563. class FCBuffer(FCShapeTool):
  1564. def __init__(self, draw_app):
  1565. FCShapeTool.__init__(self, draw_app)
  1566. self.name = 'buffer'
  1567. # self.shape_buffer = self.draw_app.shape_buffer
  1568. self.draw_app = draw_app
  1569. self.app = draw_app.app
  1570. self.draw_app.app.inform.emit(_("Buffer the selected apertures ..."))
  1571. self.origin = (0, 0)
  1572. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  1573. self.draw_app.app.ui.splitter.setSizes([1, 1])
  1574. self.activate_buffer()
  1575. def activate_buffer(self):
  1576. self.draw_app.hide_tool('all')
  1577. self.draw_app.ui.buffer_tool_frame.show()
  1578. try:
  1579. self.draw_app.ui.buffer_button.clicked.disconnect()
  1580. except (TypeError, AttributeError):
  1581. pass
  1582. self.draw_app.ui.buffer_button.clicked.connect(self.on_buffer_click)
  1583. def deactivate_buffer(self):
  1584. self.draw_app.ui.buffer_button.clicked.disconnect()
  1585. self.complete = True
  1586. self.draw_app.select_tool("select")
  1587. self.draw_app.hide_tool(self.name)
  1588. def on_buffer_click(self):
  1589. self.draw_app.on_buffer()
  1590. self.deactivate_buffer()
  1591. def clean_up(self):
  1592. self.draw_app.selected = []
  1593. self.draw_app.ui.apertures_table.clearSelection()
  1594. self.draw_app.plot_all()
  1595. class FCMarkArea(FCShapeTool):
  1596. def __init__(self, draw_app):
  1597. FCShapeTool.__init__(self, draw_app)
  1598. self.name = 'markarea'
  1599. # self.shape_buffer = self.draw_app.shape_buffer
  1600. self.draw_app = draw_app
  1601. self.app = draw_app.app
  1602. self.draw_app.app.inform.emit(_("Mark polygon areas in the edited Gerber ..."))
  1603. self.origin = (0, 0)
  1604. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  1605. self.draw_app.app.ui.splitter.setSizes([1, 1])
  1606. self.activate_markarea()
  1607. def activate_markarea(self):
  1608. self.draw_app.ui.ma_tool_frame.show()
  1609. # clear previous marking
  1610. self.draw_app.ui.ma_annotation.clear(update=True)
  1611. try:
  1612. self.draw_app.ui.ma_threshold_button.clicked.disconnect()
  1613. except (TypeError, AttributeError):
  1614. pass
  1615. self.draw_app.ui.ma_threshold_button.clicked.connect(self.on_markarea_click)
  1616. try:
  1617. self.draw_app.ui.ma_delete_button.clicked.disconnect()
  1618. except TypeError:
  1619. pass
  1620. self.draw_app.ui.ma_delete_button.clicked.connect(self.on_markarea_delete)
  1621. try:
  1622. self.draw_app.ui.ma_clear_button.clicked.disconnect()
  1623. except TypeError:
  1624. pass
  1625. self.draw_app.ui.ma_clear_button.clicked.connect(self.on_markarea_clear)
  1626. def deactivate_markarea(self):
  1627. self.draw_app.ui.ma_threshold_button.clicked.disconnect()
  1628. self.complete = True
  1629. self.draw_app.select_tool("select")
  1630. self.draw_app.hide_tool(self.name)
  1631. def on_markarea_click(self):
  1632. self.draw_app.on_markarea()
  1633. def on_markarea_clear(self):
  1634. self.draw_app.ma_annotation.clear(update=True)
  1635. self.deactivate_markarea()
  1636. def on_markarea_delete(self):
  1637. self.draw_app.delete_marked_polygons()
  1638. self.on_markarea_clear()
  1639. def clean_up(self):
  1640. self.draw_app.selected = []
  1641. self.draw_app.ui.apertures_table.clearSelection()
  1642. self.draw_app.plot_all()
  1643. class FCApertureMove(FCShapeTool):
  1644. def __init__(self, draw_app):
  1645. DrawTool.__init__(self, draw_app)
  1646. self.name = 'move'
  1647. # self.shape_buffer = self.draw_app.shape_buffer
  1648. self.origin = None
  1649. self.destination = None
  1650. self.selected_apertures = []
  1651. if len(self.draw_app.get_selected()) == 0:
  1652. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s...' %
  1653. _("Nothing selected to move"))
  1654. self.complete = True
  1655. self.draw_app.select_tool("select")
  1656. return
  1657. if self.draw_app.launched_from_shortcuts is True:
  1658. self.draw_app.launched_from_shortcuts = False
  1659. self.draw_app.app.inform.emit(_("Click on target location ..."))
  1660. else:
  1661. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  1662. self.current_storage = None
  1663. self.geometry = []
  1664. for index in self.draw_app.ui.apertures_table.selectedIndexes():
  1665. row = index.row()
  1666. # on column 1 in tool tables we hold the aperture codes, and we retrieve them as strings
  1667. aperture_on_row = self.draw_app.ui.apertures_table.item(row, 1).text()
  1668. self.selected_apertures.append(aperture_on_row)
  1669. # Switch notebook to Properties page
  1670. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.properties_tab)
  1671. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1672. self.sel_limit = self.draw_app.app.defaults["gerber_editor_sel_limit"]
  1673. self.selection_shape = self.selection_bbox()
  1674. def set_origin(self, origin):
  1675. self.origin = origin
  1676. def click(self, point):
  1677. if len(self.draw_app.get_selected()) == 0:
  1678. return "Nothing to move."
  1679. if self.origin is None:
  1680. self.set_origin(point)
  1681. self.draw_app.app.inform.emit(_("Click on target location ..."))
  1682. return
  1683. else:
  1684. self.destination = point
  1685. self.make()
  1686. # MS: always return to the Select Tool
  1687. self.draw_app.select_tool("select")
  1688. return
  1689. # def create_png(self):
  1690. # """
  1691. # Create a PNG file out of a list of Shapely polygons
  1692. # :return:
  1693. # """
  1694. # if len(self.draw_app.get_selected()) == 0:
  1695. # return None
  1696. #
  1697. # geo_list = [geoms.geo for geoms in self.draw_app.get_selected()]
  1698. # xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  1699. #
  1700. # iwidth = (xmax - xmin)
  1701. # iwidth = int(round(iwidth))
  1702. # iheight = (ymax - ymin)
  1703. # iheight = int(round(iheight))
  1704. # c = pngcanvas.PNGCanvas(iwidth, iheight)
  1705. #
  1706. # pixels = []
  1707. # for geom in self.draw_app.get_selected():
  1708. # m = mapping(geom.geo.exterior)
  1709. # pixels += [[coord[0], coord[1]] for coord in m['coordinates']]
  1710. # for g in geom.geo.interiors:
  1711. # m = mapping(g)
  1712. # pixels += [[coord[0], coord[1]] for coord in m['coordinates']]
  1713. # c.polyline(pixels)
  1714. # pixels = []
  1715. #
  1716. # f = open("%s.png" % 'D:\\shapely_image', "wb")
  1717. # f.write(c.dump())
  1718. # f.close()
  1719. def selection_bbox(self):
  1720. geo_list = []
  1721. for select_shape in self.draw_app.get_selected():
  1722. geometric_data = select_shape.geo
  1723. geo_list.append(geometric_data['solid'])
  1724. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  1725. pt1 = (xmin, ymin)
  1726. pt2 = (xmax, ymin)
  1727. pt3 = (xmax, ymax)
  1728. pt4 = (xmin, ymax)
  1729. return Polygon([pt1, pt2, pt3, pt4])
  1730. def make(self):
  1731. # Create new geometry
  1732. dx = self.destination[0] - self.origin[0]
  1733. dy = self.destination[1] - self.origin[1]
  1734. sel_shapes_to_be_deleted = []
  1735. for sel_dia in self.selected_apertures:
  1736. self.current_storage = self.draw_app.storage_dict[sel_dia]['geometry']
  1737. for select_shape in self.draw_app.get_selected():
  1738. if select_shape in self.current_storage:
  1739. geometric_data = select_shape.geo
  1740. new_geo_el = {}
  1741. if 'solid' in geometric_data:
  1742. new_geo_el['solid'] = affinity.translate(geometric_data['solid'], xoff=dx, yoff=dy)
  1743. if 'follow' in geometric_data:
  1744. new_geo_el['follow'] = affinity.translate(geometric_data['follow'], xoff=dx, yoff=dy)
  1745. if 'clear' in geometric_data:
  1746. new_geo_el['clear'] = affinity.translate(geometric_data['clear'], xoff=dx, yoff=dy)
  1747. self.geometry.append(DrawToolShape(new_geo_el))
  1748. self.current_storage.remove(select_shape)
  1749. sel_shapes_to_be_deleted.append(select_shape)
  1750. self.draw_app.on_grb_shape_complete(self.current_storage, no_plot=True)
  1751. self.geometry = []
  1752. for shp in sel_shapes_to_be_deleted:
  1753. self.draw_app.selected.remove(shp)
  1754. sel_shapes_to_be_deleted = []
  1755. self.draw_app.plot_all()
  1756. self.draw_app.build_ui()
  1757. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  1758. self.draw_app.app.jump_signal.disconnect()
  1759. def clean_up(self):
  1760. self.draw_app.selected = []
  1761. self.draw_app.ui.apertures_table.clearSelection()
  1762. self.draw_app.plot_all()
  1763. try:
  1764. self.draw_app.app.jump_signal.disconnect()
  1765. except (TypeError, AttributeError):
  1766. pass
  1767. def utility_geometry(self, data=None):
  1768. """
  1769. Temporary geometry on screen while using this tool.
  1770. :param data:
  1771. :return:
  1772. """
  1773. geo_list = []
  1774. if self.origin is None:
  1775. return None
  1776. if len(self.draw_app.get_selected()) == 0:
  1777. return None
  1778. dx = data[0] - self.origin[0]
  1779. dy = data[1] - self.origin[1]
  1780. if len(self.draw_app.get_selected()) <= self.sel_limit:
  1781. for geom in self.draw_app.get_selected():
  1782. new_geo_el = {}
  1783. if 'solid' in geom.geo:
  1784. new_geo_el['solid'] = affinity.translate(geom.geo['solid'], xoff=dx, yoff=dy)
  1785. if 'follow' in geom.geo:
  1786. new_geo_el['follow'] = affinity.translate(geom.geo['follow'], xoff=dx, yoff=dy)
  1787. if 'clear' in geom.geo:
  1788. new_geo_el['clear'] = affinity.translate(geom.geo['clear'], xoff=dx, yoff=dy)
  1789. geo_list.append(deepcopy(new_geo_el))
  1790. return DrawToolUtilityShape(geo_list)
  1791. else:
  1792. ss_el = {'solid': affinity.translate(self.selection_shape, xoff=dx, yoff=dy)}
  1793. return DrawToolUtilityShape(ss_el)
  1794. class FCApertureCopy(FCApertureMove):
  1795. def __init__(self, draw_app):
  1796. FCApertureMove.__init__(self, draw_app)
  1797. self.name = 'copy'
  1798. def make(self):
  1799. # Create new geometry
  1800. dx = self.destination[0] - self.origin[0]
  1801. dy = self.destination[1] - self.origin[1]
  1802. sel_shapes_to_be_deleted = []
  1803. for sel_dia in self.selected_apertures:
  1804. self.current_storage = self.draw_app.storage_dict[sel_dia]['geometry']
  1805. for select_shape in self.draw_app.get_selected():
  1806. if select_shape in self.current_storage:
  1807. geometric_data = select_shape.geo
  1808. new_geo_el = {}
  1809. if 'solid' in geometric_data:
  1810. new_geo_el['solid'] = affinity.translate(geometric_data['solid'], xoff=dx, yoff=dy)
  1811. if 'follow' in geometric_data:
  1812. new_geo_el['follow'] = affinity.translate(geometric_data['follow'], xoff=dx, yoff=dy)
  1813. if 'clear' in geometric_data:
  1814. new_geo_el['clear'] = affinity.translate(geometric_data['clear'], xoff=dx, yoff=dy)
  1815. self.geometry.append(DrawToolShape(new_geo_el))
  1816. sel_shapes_to_be_deleted.append(select_shape)
  1817. self.draw_app.on_grb_shape_complete(self.current_storage)
  1818. self.geometry = []
  1819. for shp in sel_shapes_to_be_deleted:
  1820. self.draw_app.selected.remove(shp)
  1821. sel_shapes_to_be_deleted = []
  1822. self.draw_app.build_ui()
  1823. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  1824. self.draw_app.app.jump_signal.disconnect()
  1825. class FCEraser(FCShapeTool):
  1826. def __init__(self, draw_app):
  1827. DrawTool.__init__(self, draw_app)
  1828. self.name = 'eraser'
  1829. self.origin = None
  1830. self.destination = None
  1831. self.selected_apertures = []
  1832. if len(self.draw_app.get_selected()) == 0:
  1833. if self.draw_app.launched_from_shortcuts is True:
  1834. self.draw_app.launched_from_shortcuts = False
  1835. self.draw_app.app.inform.emit(_("Select a shape to act as deletion area ..."))
  1836. else:
  1837. self.draw_app.app.inform.emit(_("Click to pick-up the erase shape..."))
  1838. self.current_storage = None
  1839. self.geometry = []
  1840. for index in self.draw_app.ui.apertures_table.selectedIndexes():
  1841. row = index.row()
  1842. # on column 1 in tool tables we hold the aperture codes, and we retrieve them as strings
  1843. aperture_on_row = self.draw_app.ui.apertures_table.item(row, 1).text()
  1844. self.selected_apertures.append(aperture_on_row)
  1845. # Switch notebook to Properties page
  1846. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.properties_tab)
  1847. self.draw_app.app.jump_signal.connect(lambda x: self.draw_app.update_utility_geometry(data=x))
  1848. self.sel_limit = self.draw_app.app.defaults["gerber_editor_sel_limit"]
  1849. def set_origin(self, origin):
  1850. self.origin = origin
  1851. def click(self, point):
  1852. if len(self.draw_app.get_selected()) == 0:
  1853. self.draw_app.ui.apertures_table.clearSelection()
  1854. sel_aperture = set()
  1855. for storage in self.draw_app.storage_dict:
  1856. try:
  1857. for geo_el in self.draw_app.storage_dict[storage]['geometry']:
  1858. if 'solid' in geo_el.geo:
  1859. geometric_data = geo_el.geo['solid']
  1860. if Point(point).within(geometric_data):
  1861. self.draw_app.selected = []
  1862. self.draw_app.selected.append(geo_el)
  1863. sel_aperture.add(storage)
  1864. except KeyError:
  1865. pass
  1866. # select the aperture in the Apertures Table that is associated with the selected shape
  1867. try:
  1868. self.draw_app.ui.apertures_table.cellPressed.disconnect()
  1869. except Exception as e:
  1870. log.debug("AppGerberEditor.FCEraser.click_release() --> %s" % str(e))
  1871. self.draw_app.ui.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  1872. for aper in sel_aperture:
  1873. for row in range(self.draw_app.ui.apertures_table.rowCount()):
  1874. if str(aper) == self.draw_app.ui.apertures_table.item(row, 1).text():
  1875. self.draw_app.ui.apertures_table.selectRow(row)
  1876. self.draw_app.last_aperture_selected = aper
  1877. self.draw_app.ui.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1878. self.draw_app.ui.apertures_table.cellPressed.connect(self.draw_app.on_row_selected)
  1879. if len(self.draw_app.get_selected()) == 0:
  1880. return "Nothing to ersase."
  1881. if self.origin is None:
  1882. self.set_origin(point)
  1883. self.draw_app.app.inform.emit(_("Click to erase ..."))
  1884. return
  1885. else:
  1886. self.destination = point
  1887. self.make()
  1888. # self.draw_app.select_tool("select")
  1889. return
  1890. def make(self):
  1891. eraser_sel_shapes = []
  1892. # create the eraser shape from selection
  1893. for eraser_shape in self.utility_geometry(data=self.destination).geo:
  1894. temp_shape = eraser_shape['solid'].buffer(0.0000001)
  1895. temp_shape = Polygon(temp_shape.exterior)
  1896. eraser_sel_shapes.append(temp_shape)
  1897. eraser_sel_shapes = unary_union(eraser_sel_shapes)
  1898. for storage in self.draw_app.storage_dict:
  1899. try:
  1900. for geo_el in self.draw_app.storage_dict[storage]['geometry']:
  1901. if 'solid' in geo_el.geo:
  1902. geometric_data = geo_el.geo['solid']
  1903. if eraser_sel_shapes.within(geometric_data) or eraser_sel_shapes.intersects(geometric_data):
  1904. geos = geometric_data.difference(eraser_sel_shapes)
  1905. geos = geos.buffer(0)
  1906. geo_el.geo['solid'] = deepcopy(geos)
  1907. except KeyError:
  1908. pass
  1909. self.draw_app.delete_utility_geometry()
  1910. self.draw_app.plot_all()
  1911. self.draw_app.app.inform.emit('[success] %s' % _("Done."))
  1912. self.draw_app.app.jump_signal.disconnect()
  1913. def clean_up(self):
  1914. self.draw_app.selected = []
  1915. self.draw_app.ui.apertures_table.clearSelection()
  1916. self.draw_app.plot_all()
  1917. try:
  1918. self.draw_app.app.jump_signal.disconnect()
  1919. except (TypeError, AttributeError):
  1920. pass
  1921. def utility_geometry(self, data=None):
  1922. """
  1923. Temporary geometry on screen while using this tool.
  1924. :param data:
  1925. :return:
  1926. """
  1927. geo_list = []
  1928. if self.origin is None:
  1929. return None
  1930. if len(self.draw_app.get_selected()) == 0:
  1931. return None
  1932. dx = data[0] - self.origin[0]
  1933. dy = data[1] - self.origin[1]
  1934. for geom in self.draw_app.get_selected():
  1935. new_geo_el = {}
  1936. if 'solid' in geom.geo:
  1937. new_geo_el['solid'] = affinity.translate(geom.geo['solid'], xoff=dx, yoff=dy)
  1938. if 'follow' in geom.geo:
  1939. new_geo_el['follow'] = affinity.translate(geom.geo['follow'], xoff=dx, yoff=dy)
  1940. if 'clear' in geom.geo:
  1941. new_geo_el['clear'] = affinity.translate(geom.geo['clear'], xoff=dx, yoff=dy)
  1942. geo_list.append(deepcopy(new_geo_el))
  1943. return DrawToolUtilityShape(geo_list)
  1944. class FCApertureSelect(DrawTool):
  1945. def __init__(self, draw_app):
  1946. DrawTool.__init__(self, draw_app)
  1947. self.name = 'select'
  1948. self.origin = None
  1949. self.draw_app = draw_app
  1950. self.storage = self.draw_app.storage_dict
  1951. # self.selected = self.draw_app.selected
  1952. # here we store all shapes that were selected
  1953. self.sel_storage = []
  1954. # since FCApertureSelect tool is activated whenever a tool is exited I place here the reinitialization of the
  1955. # bending modes using in FCRegion and FCTrack
  1956. self.draw_app.bend_mode = 1
  1957. # here store the selected apertures
  1958. self.sel_aperture = []
  1959. try:
  1960. self.draw_app.ui.apertures_table.clearSelection()
  1961. except Exception as e:
  1962. log.error("FlatCAMGerbEditor.FCApertureSelect.__init__() --> %s" % str(e))
  1963. self.draw_app.hide_tool('all')
  1964. self.draw_app.hide_tool('select')
  1965. self.draw_app.ui.array_frame.hide()
  1966. try:
  1967. QtGui.QGuiApplication.restoreOverrideCursor()
  1968. except Exception as e:
  1969. log.debug("AppGerberEditor.FCApertureSelect --> %s" % str(e))
  1970. try:
  1971. self.draw_app.selection_triggered.disconnect()
  1972. except (TypeError, AttributeError):
  1973. pass
  1974. self.draw_app.selection_triggered.connect(self.selection_worker)
  1975. try:
  1976. self.draw_app.plot_object.disconnect()
  1977. except (TypeError, AttributeError):
  1978. pass
  1979. self.draw_app.plot_object.connect(self.clean_up)
  1980. def set_origin(self, origin):
  1981. self.origin = origin
  1982. def click(self, point):
  1983. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1984. if key_modifier == QtCore.Qt.ShiftModifier:
  1985. mod_key = 'Shift'
  1986. elif key_modifier == QtCore.Qt.ControlModifier:
  1987. mod_key = 'Control'
  1988. else:
  1989. mod_key = None
  1990. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  1991. pass
  1992. else:
  1993. self.draw_app.selected = []
  1994. def click_release(self, point):
  1995. self.draw_app.ui.apertures_table.clearSelection()
  1996. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1997. if key_modifier == QtCore.Qt.ShiftModifier:
  1998. mod_key = 'Shift'
  1999. elif key_modifier == QtCore.Qt.ControlModifier:
  2000. mod_key = 'Control'
  2001. else:
  2002. mod_key = None
  2003. if mod_key != self.draw_app.app.defaults["global_mselect_key"]:
  2004. self.draw_app.selected.clear()
  2005. self.sel_aperture.clear()
  2006. self.draw_app.selection_triggered.emit(point)
  2007. def selection_worker(self, point):
  2008. def job_thread(editor_obj):
  2009. with editor_obj.app.proc_container.new('%s' % _("Working ...")):
  2010. brake_flag = False
  2011. for storage_key, storage_val in editor_obj.storage_dict.items():
  2012. for shape_stored in storage_val['geometry']:
  2013. if 'solid' in shape_stored.geo:
  2014. geometric_data = shape_stored.geo['solid']
  2015. if Point(point).intersects(geometric_data):
  2016. if shape_stored in editor_obj.selected:
  2017. editor_obj.selected.remove(shape_stored)
  2018. else:
  2019. # add the object to the selected shapes
  2020. editor_obj.selected.append(shape_stored)
  2021. brake_flag = True
  2022. break
  2023. if brake_flag is True:
  2024. break
  2025. # ######################################################################################################
  2026. # select the aperture in the Apertures Table that is associated with the selected shape
  2027. # ######################################################################################################
  2028. self.sel_aperture.clear()
  2029. editor_obj.ui.apertures_table.clearSelection()
  2030. # disconnect signal when clicking in the table
  2031. try:
  2032. editor_obj.ui.apertures_table.cellPressed.disconnect()
  2033. except Exception as e:
  2034. log.debug("AppGerberEditor.FCApertureSelect.click_release() --> %s" % str(e))
  2035. brake_flag = False
  2036. for shape_s in editor_obj.selected:
  2037. for storage in editor_obj.storage_dict:
  2038. if shape_s in editor_obj.storage_dict[storage]['geometry']:
  2039. self.sel_aperture.append(storage)
  2040. brake_flag = True
  2041. break
  2042. if brake_flag is True:
  2043. break
  2044. # actual row selection is done here
  2045. for aper in self.sel_aperture:
  2046. for row in range(editor_obj.ui.apertures_table.rowCount()):
  2047. if str(aper) == editor_obj.ui.apertures_table.item(row, 1).text():
  2048. if not editor_obj.ui.apertures_table.item(row, 0).isSelected():
  2049. editor_obj.ui.apertures_table.selectRow(row)
  2050. editor_obj.last_aperture_selected = aper
  2051. # reconnect signal when clicking in the table
  2052. editor_obj.ui.apertures_table.cellPressed.connect(editor_obj.on_row_selected)
  2053. editor_obj.plot_object.emit(None)
  2054. self.draw_app.app.worker_task.emit({'fcn': job_thread, 'params': [self.draw_app]})
  2055. def clean_up(self):
  2056. self.draw_app.plot_all()
  2057. class FCTransform(FCShapeTool):
  2058. def __init__(self, draw_app):
  2059. FCShapeTool.__init__(self, draw_app)
  2060. self.name = 'transformation'
  2061. # self.shape_buffer = self.draw_app.shape_buffer
  2062. self.draw_app = draw_app
  2063. self.app = draw_app.app
  2064. self.start_msg = _("Shape transformations ...")
  2065. self.origin = (0, 0)
  2066. self.draw_app.transform_tool.run()
  2067. def clean_up(self):
  2068. self.draw_app.selected = []
  2069. self.draw_app.apertures_table.clearSelection()
  2070. self.draw_app.plot_all()
  2071. class AppGerberEditor(QtCore.QObject):
  2072. draw_shape_idx = -1
  2073. # plot_finished = QtCore.pyqtSignal()
  2074. mp_finished = QtCore.pyqtSignal(list)
  2075. selection_triggered = QtCore.pyqtSignal(object)
  2076. plot_object = QtCore.pyqtSignal(object)
  2077. def __init__(self, app):
  2078. # assert isinstance(app, FlatCAMApp.App), \
  2079. # "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2080. super(AppGerberEditor, self).__init__()
  2081. self.app = app
  2082. self.canvas = self.app.plotcanvas
  2083. self.decimals = self.app.decimals
  2084. # Current application units in Upper Case
  2085. self.units = self.app.defaults['units'].upper()
  2086. self.ui = AppGerberEditorUI(self.app)
  2087. # Toolbar events and properties
  2088. self.tools_gerber = {}
  2089. # # ## Data
  2090. self.active_tool = None
  2091. self.storage_dict = {}
  2092. self.current_storage = []
  2093. self.sorted_apcode = []
  2094. self.new_apertures = {}
  2095. self.new_aperture_macros = {}
  2096. # store here the plot promises, if empty the delayed plot will be activated
  2097. self.grb_plot_promises = []
  2098. # dictionary to store the tool_row and aperture codes in Tool_table
  2099. # it will be updated everytime self.build_ui() is called
  2100. self.oldapcode_newapcode = {}
  2101. self.tid2apcode = {}
  2102. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  2103. # is cleared but as a side effect also the selected tool is cleared
  2104. self.last_aperture_selected = None
  2105. self.utility = []
  2106. # this will store the polygons marked by mark are to be perhaps deleted
  2107. self.geo_to_delete = []
  2108. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2109. self.launched_from_shortcuts = False
  2110. # this var will store the state of the toolbar before starting the editor
  2111. self.toolbar_old_state = False
  2112. # #############################################################################################################
  2113. # ######################### Init appGUI #######################################################################
  2114. # #############################################################################################################
  2115. self.ui.apdim_lbl.hide()
  2116. self.ui.apdim_entry.hide()
  2117. self.gerber_obj = None
  2118. self.gerber_obj_options = {}
  2119. # VisPy Visuals
  2120. if self.app.is_legacy is False:
  2121. self.shapes = self.canvas.new_shape_collection(layers=1)
  2122. self.tool_shape = self.canvas.new_shape_collection(layers=1)
  2123. self.ma_annotation = self.canvas.new_text_group()
  2124. else:
  2125. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2126. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='shapes_grb_editor')
  2127. self.tool_shape = ShapeCollectionLegacy(obj=self, app=self.app, name='tool_shapes_grb_editor')
  2128. self.ma_annotation = ShapeCollectionLegacy(
  2129. obj=self,
  2130. app=self.app,
  2131. name='ma_anno_grb_editor',
  2132. annotation_job=True)
  2133. # Event signals disconnect id holders
  2134. self.mp = None
  2135. self.mm = None
  2136. self.mr = None
  2137. # Remove from scene
  2138. self.shapes.enabled = False
  2139. self.tool_shape.enabled = False
  2140. # List of selected geometric elements.
  2141. self.selected = []
  2142. self.key = None # Currently pressed key
  2143. self.modifiers = None
  2144. self.x = None # Current mouse cursor pos
  2145. self.y = None
  2146. # Current snapped mouse pos
  2147. self.snap_x = None
  2148. self.snap_y = None
  2149. self.pos = None
  2150. # used in FCRegion and FCTrack. Will store the bending mode
  2151. self.bend_mode = 1
  2152. # signal that there is an action active like polygon or path
  2153. self.in_action = False
  2154. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2155. self.launched_from_shortcuts = False
  2156. def_tol_val = float(self.app.defaults["global_tolerance"])
  2157. self.tolerance = def_tol_val if self.units == 'MM'else def_tol_val / 20
  2158. # options of this widget (AppGerberEditor class is a widget)
  2159. self.options = {
  2160. "global_gridx": 0.1,
  2161. "global_gridy": 0.1,
  2162. "snap_max": 0.05,
  2163. "grid_snap": True,
  2164. "corner_snap": False,
  2165. "grid_gap_link": True
  2166. }
  2167. # fill it with the application options (application preferences)
  2168. self.options.update(self.app.options)
  2169. for option in self.options:
  2170. if option in self.app.options:
  2171. self.options[option] = self.app.options[option]
  2172. # flag to show if the object was modified
  2173. self.is_modified = False
  2174. self.edited_obj_name = ""
  2175. self.tool_row = 0
  2176. # Multiprocessing pool
  2177. self.pool = self.app.pool
  2178. # Multiprocessing results
  2179. self.results = []
  2180. # A QTimer
  2181. self.plot_thread = None
  2182. # a QThread for the edit process
  2183. self.thread = QtCore.QThread()
  2184. # def entry2option(option, entry):
  2185. # self.options[option] = float(entry.text())
  2186. self.transform_tool = TransformEditorTool(self.app, self)
  2187. # #############################################################################################################
  2188. # ######################### Gerber Editor Signals #############################################################
  2189. # #############################################################################################################
  2190. self.app.pool_recreated.connect(self.pool_recreated)
  2191. self.mp_finished.connect(self.on_multiprocessing_finished)
  2192. # connect the toolbar signals
  2193. self.connect_grb_toolbar_signals()
  2194. self.app.ui.grb_add_pad_menuitem.triggered.connect(self.on_pad_add)
  2195. self.app.ui.grb_add_pad_array_menuitem.triggered.connect(self.on_pad_add_array)
  2196. self.app.ui.grb_add_track_menuitem.triggered.connect(self.on_track_add)
  2197. self.app.ui.grb_add_region_menuitem.triggered.connect(self.on_region_add)
  2198. self.app.ui.grb_convert_poly_menuitem.triggered.connect(self.on_poligonize)
  2199. self.app.ui.grb_add_semidisc_menuitem.triggered.connect(self.on_add_semidisc)
  2200. self.app.ui.grb_add_disc_menuitem.triggered.connect(self.on_disc_add)
  2201. self.app.ui.grb_add_buffer_menuitem.triggered.connect(self.on_buffer)
  2202. self.app.ui.grb_add_scale_menuitem.triggered.connect(self.on_scale)
  2203. self.app.ui.grb_add_eraser_menuitem.triggered.connect(self.on_eraser)
  2204. self.app.ui.grb_add_markarea_menuitem.triggered.connect(self.on_markarea)
  2205. self.app.ui.grb_transform_menuitem.triggered.connect(self.transform_tool.run)
  2206. self.app.ui.grb_copy_menuitem.triggered.connect(self.on_copy_button)
  2207. self.app.ui.grb_delete_menuitem.triggered.connect(self.on_delete_btn)
  2208. self.app.ui.grb_move_menuitem.triggered.connect(self.on_move_button)
  2209. self.ui.buffer_button.clicked.connect(self.on_buffer)
  2210. self.ui.scale_button.clicked.connect(self.on_scale)
  2211. self.app.ui.aperture_delete_btn.triggered.connect(self.on_delete_btn)
  2212. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  2213. self.ui.aptype_cb.currentIndexChanged[str].connect(self.on_aptype_changed)
  2214. self.ui.addaperture_btn.clicked.connect(self.on_aperture_add)
  2215. self.ui.apsize_entry.returnPressed.connect(self.on_aperture_add)
  2216. self.ui.apdim_entry.returnPressed.connect(self.on_aperture_add)
  2217. self.ui.delaperture_btn.clicked.connect(self.on_aperture_delete)
  2218. self.ui.apertures_table.cellPressed.connect(self.on_row_selected)
  2219. self.ui.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  2220. self.ui.pad_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  2221. self.ui.exit_editor_button.clicked.connect(lambda: self.app.editor2object())
  2222. self.conversion_factor = 1
  2223. self.apertures_row = 0
  2224. self.complete = True
  2225. self.set_ui()
  2226. log.debug("Initialization of the Gerber Editor is finished ...")
  2227. def make_callback(self, the_tool):
  2228. def f():
  2229. self.on_tool_select(the_tool)
  2230. return f
  2231. def connect_grb_toolbar_signals(self):
  2232. self.tools_gerber.update({
  2233. "select": {"button": self.app.ui.grb_select_btn, "constructor": FCApertureSelect},
  2234. "pad": {"button": self.app.ui.grb_add_pad_btn, "constructor": FCPad},
  2235. "array": {"button": self.app.ui.add_pad_ar_btn, "constructor": FCPadArray},
  2236. "track": {"button": self.app.ui.grb_add_track_btn, "constructor": FCTrack},
  2237. "region": {"button": self.app.ui.grb_add_region_btn, "constructor": FCRegion},
  2238. "poligonize": {"button": self.app.ui.grb_convert_poly_btn, "constructor": FCPoligonize},
  2239. "semidisc": {"button": self.app.ui.grb_add_semidisc_btn, "constructor": FCSemiDisc},
  2240. "disc": {"button": self.app.ui.grb_add_disc_btn, "constructor": FCDisc},
  2241. "buffer": {"button": self.app.ui.aperture_buffer_btn, "constructor": FCBuffer},
  2242. "scale": {"button": self.app.ui.aperture_scale_btn, "constructor": FCScale},
  2243. "markarea": {"button": self.app.ui.aperture_markarea_btn, "constructor": FCMarkArea},
  2244. "eraser": {"button": self.app.ui.aperture_eraser_btn, "constructor": FCEraser},
  2245. "copy": {"button": self.app.ui.aperture_copy_btn, "constructor": FCApertureCopy},
  2246. "transform": {"button": self.app.ui.grb_transform_btn, "constructor": FCTransform},
  2247. "move": {"button": self.app.ui.aperture_move_btn, "constructor": FCApertureMove},
  2248. })
  2249. for tool in self.tools_gerber:
  2250. self.tools_gerber[tool]["button"].triggered.connect(self.make_callback(tool)) # Events
  2251. self.tools_gerber[tool]["button"].setCheckable(True)
  2252. def pool_recreated(self, pool):
  2253. self.shapes.pool = pool
  2254. self.tool_shape.pool = pool
  2255. self.pool = pool
  2256. def set_ui(self):
  2257. # updated units
  2258. self.units = self.app.defaults['units'].upper()
  2259. self.decimals = self.app.decimals
  2260. self.oldapcode_newapcode.clear()
  2261. self.tid2apcode.clear()
  2262. # update the oldapcode_newapcode dict to make sure we have an updated state of the tool_table
  2263. for key in self.storage_dict:
  2264. self.oldapcode_newapcode[key] = key
  2265. sort_temp = []
  2266. for aperture in self.oldapcode_newapcode:
  2267. sort_temp.append(int(aperture))
  2268. self.sorted_apcode = sorted(sort_temp)
  2269. # populate self.intial_table_rows dict with the tool number as keys and aperture codes as values
  2270. for i in range(len(self.sorted_apcode)):
  2271. tt_aperture = self.sorted_apcode[i]
  2272. self.tid2apcode[i + 1] = tt_aperture
  2273. # #############################################################################################################
  2274. # Init appGUI
  2275. # #############################################################################################################
  2276. self.ui.buffer_distance_entry.set_value(self.app.defaults["gerber_editor_buff_f"])
  2277. self.ui.scale_factor_entry.set_value(self.app.defaults["gerber_editor_scale_f"])
  2278. self.ui.ma_upper_threshold_entry.set_value(self.app.defaults["gerber_editor_ma_high"])
  2279. self.ui.ma_lower_threshold_entry.set_value(self.app.defaults["gerber_editor_ma_low"])
  2280. self.ui.apsize_entry.set_value(self.app.defaults["gerber_editor_newsize"])
  2281. self.ui.aptype_cb.set_value(self.app.defaults["gerber_editor_newtype"])
  2282. self.ui.apdim_entry.set_value(self.app.defaults["gerber_editor_newdim"])
  2283. self.ui.pad_array_size_entry.set_value(int(self.app.defaults["gerber_editor_array_size"]))
  2284. # linear array
  2285. self.ui.pad_axis_radio.set_value(self.app.defaults["gerber_editor_lin_axis"])
  2286. self.ui.pad_pitch_entry.set_value(float(self.app.defaults["gerber_editor_lin_pitch"]))
  2287. self.ui.linear_angle_spinner.set_value(self.app.defaults["gerber_editor_lin_angle"])
  2288. # circular array
  2289. self.ui.pad_direction_radio.set_value(self.app.defaults["gerber_editor_circ_dir"])
  2290. self.ui.pad_angle_entry.set_value(float(self.app.defaults["gerber_editor_circ_angle"]))
  2291. def build_ui(self, first_run=None):
  2292. try:
  2293. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2294. self.ui.apertures_table.itemChanged.disconnect()
  2295. except (TypeError, AttributeError):
  2296. pass
  2297. try:
  2298. self.ui.apertures_table.cellPressed.disconnect()
  2299. except (TypeError, AttributeError):
  2300. pass
  2301. # updated units
  2302. self.units = self.app.defaults['units'].upper()
  2303. # make a new name for the new Excellon object (the one with edited content)
  2304. self.edited_obj_name = self.gerber_obj.options['name']
  2305. self.ui.name_entry.set_value(self.edited_obj_name)
  2306. self.apertures_row = 0
  2307. # aper_no = self.apertures_row + 1
  2308. sort = []
  2309. for k, v in list(self.storage_dict.items()):
  2310. sort.append(int(k))
  2311. sorted_apertures = sorted(sort)
  2312. # sort = []
  2313. # for k, v in list(self.gerber_obj.aperture_macros.items()):
  2314. # sort.append(k)
  2315. # sorted_macros = sorted(sort)
  2316. # n = len(sorted_apertures) + len(sorted_macros)
  2317. n = len(sorted_apertures)
  2318. self.ui.apertures_table.setRowCount(n)
  2319. for ap_code in sorted_apertures:
  2320. ap_code = str(ap_code)
  2321. ap_code_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  2322. ap_code_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2323. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_code_item) # Tool name/id
  2324. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  2325. ap_code_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2326. ap_type_item = QtWidgets.QTableWidgetItem(str(self.storage_dict[ap_code]['type']))
  2327. ap_type_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2328. if str(self.storage_dict[ap_code]['type']) == 'R' or str(self.storage_dict[ap_code]['type']) == 'O':
  2329. ap_dim_item = QtWidgets.QTableWidgetItem(
  2330. '%.*f, %.*f' % (self.decimals, self.storage_dict[ap_code]['width'],
  2331. self.decimals, self.storage_dict[ap_code]['height']
  2332. )
  2333. )
  2334. ap_dim_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
  2335. elif str(self.storage_dict[ap_code]['type']) == 'P':
  2336. ap_dim_item = QtWidgets.QTableWidgetItem(
  2337. '%.*f, %.*f' % (self.decimals, self.storage_dict[ap_code]['diam'],
  2338. self.decimals, self.storage_dict[ap_code]['nVertices'])
  2339. )
  2340. ap_dim_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
  2341. else:
  2342. ap_dim_item = QtWidgets.QTableWidgetItem('')
  2343. ap_dim_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2344. try:
  2345. if self.storage_dict[ap_code]['size'] is not None:
  2346. ap_size_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals,
  2347. float(self.storage_dict[ap_code]['size'])))
  2348. else:
  2349. ap_size_item = QtWidgets.QTableWidgetItem('')
  2350. except KeyError:
  2351. ap_size_item = QtWidgets.QTableWidgetItem('')
  2352. if str(self.storage_dict[ap_code]['type']) == 'C':
  2353. ap_size_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
  2354. else:
  2355. ap_size_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2356. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  2357. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  2358. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Size
  2359. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  2360. self.apertures_row += 1
  2361. if first_run is True:
  2362. # set now the last aperture selected
  2363. self.last_aperture_selected = ap_code
  2364. # for ap_code in sorted_macros:
  2365. # ap_code = str(ap_code)
  2366. #
  2367. # ap_code_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  2368. # ap_code_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2369. # self.ui.apertures_table.setItem(self.apertures_row, 0, ap_code_item) # Tool name/id
  2370. #
  2371. # ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  2372. #
  2373. # ap_type_item = QtWidgets.QTableWidgetItem('AM')
  2374. # ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2375. #
  2376. # self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  2377. # self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  2378. #
  2379. # self.apertures_row += 1
  2380. # if first_run is True:
  2381. # # set now the last aperture selected
  2382. # self.last_aperture_selected = ap_code
  2383. self.ui.apertures_table.selectColumn(0)
  2384. self.ui.apertures_table.resizeColumnsToContents()
  2385. self.ui.apertures_table.resizeRowsToContents()
  2386. vertical_header = self.ui.apertures_table.verticalHeader()
  2387. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2388. vertical_header.hide()
  2389. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2390. horizontal_header = self.ui.apertures_table.horizontalHeader()
  2391. horizontal_header.setMinimumSectionSize(10)
  2392. horizontal_header.setDefaultSectionSize(70)
  2393. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2394. horizontal_header.resizeSection(0, 27)
  2395. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  2396. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  2397. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2398. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  2399. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2400. self.ui.apertures_table.setSortingEnabled(False)
  2401. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  2402. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  2403. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  2404. self.ui.apertures_table.clearSelection()
  2405. # Remove anything else in the GUI Properties Tab
  2406. self.app.ui.properties_scroll_area.takeWidget()
  2407. # Put ourselves in the GUI Properties Tab
  2408. self.app.ui.properties_scroll_area.setWidget(self.ui.grb_edit_widget)
  2409. # Switch notebook to Properties page
  2410. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  2411. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  2412. self.ui.apertures_table.itemChanged.connect(self.on_tool_edit)
  2413. self.ui.apertures_table.cellPressed.connect(self.on_row_selected)
  2414. # for convenience set the next aperture code in the apcode field
  2415. try:
  2416. self.ui.apcode_entry.set_value(max(self.tid2apcode.values()) + 1)
  2417. except ValueError:
  2418. # this means that the edited object has no apertures so we start with 10 (Gerber specifications)
  2419. self.ui.apcode_entry.set_value(self.app.defaults["gerber_editor_newcode"])
  2420. def on_aperture_add(self, apcode=None):
  2421. self.is_modified = True
  2422. if apcode:
  2423. ap_code = apcode
  2424. else:
  2425. try:
  2426. ap_code = str(self.ui.apcode_entry.get_value())
  2427. except ValueError:
  2428. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2429. _("Aperture code value is missing or wrong format. Add it and retry."))
  2430. return
  2431. if ap_code == '':
  2432. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2433. _("Aperture code value is missing or wrong format. Add it and retry."))
  2434. return
  2435. if ap_code == '0':
  2436. if ap_code not in self.tid2apcode:
  2437. self.storage_dict[ap_code] = {}
  2438. self.storage_dict[ap_code]['type'] = 'REG'
  2439. size_val = 0
  2440. self.ui.apsize_entry.set_value(size_val)
  2441. self.storage_dict[ap_code]['size'] = size_val
  2442. self.storage_dict[ap_code]['geometry'] = []
  2443. # self.oldapcode_newapcode dict keeps the evidence on current aperture codes as keys and
  2444. # gets updated on values each time a aperture code is edited or added
  2445. self.oldapcode_newapcode[ap_code] = ap_code
  2446. else:
  2447. if ap_code not in self.oldapcode_newapcode:
  2448. self.storage_dict[ap_code] = {}
  2449. type_val = self.ui.aptype_cb.currentText()
  2450. self.storage_dict[ap_code]['type'] = type_val
  2451. if type_val == 'R' or type_val == 'O':
  2452. try:
  2453. dims = self.ui.apdim_entry.get_value()
  2454. self.storage_dict[ap_code]['width'] = dims[0]
  2455. self.storage_dict[ap_code]['height'] = dims[1]
  2456. size_val = np.sqrt((dims[0] ** 2) + (dims[1] ** 2))
  2457. self.ui.apsize_entry.set_value(size_val)
  2458. except Exception as e:
  2459. log.error("AppGerberEditor.on_aperture_add() --> the R or O aperture dims has to be in a "
  2460. "tuple format (x,y)\nError: %s" % str(e))
  2461. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2462. _("Aperture dimensions value is missing or wrong format. "
  2463. "Add it in format (width, height) and retry."))
  2464. return
  2465. else:
  2466. try:
  2467. size_val = float(self.ui.apsize_entry.get_value())
  2468. except ValueError:
  2469. # try to convert comma to decimal point. if it's still not working error message and return
  2470. try:
  2471. size_val = float(self.ui.apsize_entry.get_value().replace(',', '.'))
  2472. self.ui.apsize_entry.set_value(size_val)
  2473. except ValueError:
  2474. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2475. _("Aperture size value is missing or wrong format. Add it and retry."))
  2476. return
  2477. self.storage_dict[ap_code]['size'] = size_val
  2478. self.storage_dict[ap_code]['geometry'] = []
  2479. # self.oldapcode_newapcode dict keeps the evidence on current aperture codes as keys and gets updated on
  2480. # values each time a aperture code is edited or added
  2481. self.oldapcode_newapcode[ap_code] = ap_code
  2482. else:
  2483. self.app.inform.emit('[WARNING_NOTCL] %s' %
  2484. _("Aperture already in the aperture table."))
  2485. return
  2486. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  2487. # we add a new entry in the tid2apcode dict
  2488. self.tid2apcode[len(self.oldapcode_newapcode)] = int(ap_code)
  2489. self.app.inform.emit('[success] %s: %s' % (_("Added new aperture with code"), str(ap_code)))
  2490. self.build_ui()
  2491. self.last_aperture_selected = ap_code
  2492. # make a quick sort through the tid2apcode dict so we find which row to select
  2493. row_to_be_selected = None
  2494. for key in sorted(self.tid2apcode):
  2495. if self.tid2apcode[key] == int(ap_code):
  2496. row_to_be_selected = int(key) - 1
  2497. break
  2498. self.ui.apertures_table.selectRow(row_to_be_selected)
  2499. def on_aperture_delete(self, ap_code=None):
  2500. """
  2501. Called for aperture deletion.
  2502. :param ap_code: An Aperture code; String
  2503. :return:
  2504. """
  2505. self.is_modified = True
  2506. try:
  2507. if ap_code:
  2508. try:
  2509. deleted_apcode_list = [dd for dd in ap_code]
  2510. except TypeError:
  2511. deleted_apcode_list = [ap_code]
  2512. else:
  2513. # deleted_tool_dia = float(self.ui.apertures_table.item(self.ui.apertures_table.currentRow(), 1).text())
  2514. if len(self.ui.apertures_table.selectionModel().selectedRows()) == 0:
  2515. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Select an aperture in Aperture Table"))
  2516. return
  2517. deleted_apcode_list = []
  2518. for index in self.ui.apertures_table.selectionModel().selectedRows():
  2519. row = index.row()
  2520. deleted_apcode_list.append(self.ui.apertures_table.item(row, 1).text())
  2521. except Exception as exc:
  2522. self.app.inform.emit('[WARNING_NOTCL] %s %s' % (_("Select an aperture in Aperture Table -->", str(exc))))
  2523. return
  2524. if deleted_apcode_list:
  2525. for deleted_aperture in deleted_apcode_list:
  2526. # delete the storage used for that tool
  2527. self.storage_dict.pop(deleted_aperture, None)
  2528. for deleted_tool in list(self.tid2apcode.keys()):
  2529. if self.tid2apcode[deleted_tool] == deleted_aperture:
  2530. # delete the tool
  2531. self.tid2apcode.pop(deleted_tool, None)
  2532. self.oldapcode_newapcode.pop(deleted_aperture, None)
  2533. self.app.inform.emit('[success] %s: %s' % (_("Deleted aperture with code"), str(deleted_aperture)))
  2534. self.plot_all()
  2535. self.build_ui()
  2536. # if last aperture selected was in the apertures deleted than make sure to select a
  2537. # 'new' last aperture selected because there are tools who depend on it.
  2538. # if there is no aperture left, then add a default one :)
  2539. if self.last_aperture_selected in deleted_apcode_list:
  2540. if self.ui.apertures_table.rowCount() == 0:
  2541. self.on_aperture_add('10')
  2542. self.last_aperture_selected = '10'
  2543. else:
  2544. self.last_aperture_selected = self.ui.apertures_table.item(0, 1).text()
  2545. def on_tool_edit(self):
  2546. if self.ui.apertures_table.currentItem() is None:
  2547. return
  2548. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2549. self.ui.apertures_table.itemChanged.disconnect()
  2550. # self.ui.apertures_table.cellPressed.disconnect()
  2551. self.is_modified = True
  2552. val_edited = None
  2553. row_of_item_changed = self.ui.apertures_table.currentRow()
  2554. col_of_item_changed = self.ui.apertures_table.currentColumn()
  2555. # rows start with 0, tools start with 1 so we adjust the value by 1
  2556. key_in_tid2apcode = row_of_item_changed + 1
  2557. ap_code_old = str(self.tid2apcode[key_in_tid2apcode])
  2558. ap_code_new = self.ui.apertures_table.item(row_of_item_changed, 1).text()
  2559. if col_of_item_changed == 1:
  2560. # we edited the Aperture Code column (int)
  2561. try:
  2562. val_edited = int(self.ui.apertures_table.currentItem().text())
  2563. except ValueError as e:
  2564. log.debug("AppGerberEditor.on_tool_edit() --> %s" % str(e))
  2565. # self.ui.apertures_table.setCurrentItem(None)
  2566. # we reactivate the signals after the after the tool editing
  2567. self.ui.apertures_table.itemChanged.connect(self.on_tool_edit)
  2568. return
  2569. elif col_of_item_changed == 3:
  2570. # we edited the Size column (float)
  2571. try:
  2572. val_edited = float(self.ui.apertures_table.currentItem().text())
  2573. except ValueError as e:
  2574. log.debug("AppGerberEditor.on_tool_edit() --> %s" % str(e))
  2575. # self.ui.apertures_table.setCurrentItem(None)
  2576. # we reactivate the signals after the after the tool editing
  2577. self.ui.apertures_table.itemChanged.connect(self.on_tool_edit)
  2578. return
  2579. elif col_of_item_changed == 4:
  2580. # we edit the Dimensions column (tuple)
  2581. try:
  2582. val_edited = [
  2583. float(x.strip()) for x in self.ui.apertures_table.currentItem().text().split(",") if x != ''
  2584. ]
  2585. except ValueError as e:
  2586. log.debug("AppGerberEditor.on_tool_edit() --> %s" % str(e))
  2587. # we reactivate the signals after the after the tool editing
  2588. self.ui.apertures_table.itemChanged.connect(self.on_tool_edit)
  2589. return
  2590. if len(val_edited) != 2:
  2591. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Dimensions need two float values separated by comma."))
  2592. old_dims_txt = '%s, %s' % (str(self.storage_dict[ap_code_new]['width']),
  2593. str(self.storage_dict[ap_code_new]['height']))
  2594. self.ui.apertures_table.currentItem().setText(old_dims_txt)
  2595. # we reactivate the signals after the after the tool editing
  2596. self.ui.apertures_table.itemChanged.connect(self.on_tool_edit)
  2597. return
  2598. else:
  2599. self.app.inform.emit("[success] %s" % _("Dimensions edited."))
  2600. # In case we edited the Aperture Code therefore the val_edited holds a new Aperture Code
  2601. # TODO Edit of the Aperture Code is not active yet
  2602. if col_of_item_changed == 1:
  2603. # aperture code is not used so we create a new Aperture with the desired Aperture Code
  2604. if val_edited not in self.oldapcode_newapcode.values():
  2605. # update the dict that holds as keys old Aperture Codes and as values the new Aperture Codes
  2606. self.oldapcode_newapcode[ap_code_old] = val_edited
  2607. # update the dict that holds tool_no as key and tool_dia as value
  2608. self.tid2apcode[key_in_tid2apcode] = val_edited
  2609. old_aperture_val = self.storage_dict.pop(ap_code_old)
  2610. self.storage_dict[val_edited] = old_aperture_val
  2611. else:
  2612. # aperture code is already in use so we move the pads from the prior tool to the new tool
  2613. # but only if they are of the same type
  2614. if self.storage_dict[ap_code_old]['type'] == self.storage_dict[ap_code_new]['type']:
  2615. # TODO I have to work here; if type == 'R' or 'O' have t otake care of all attributes ...
  2616. factor = val_edited / float(ap_code_old)
  2617. geometry = []
  2618. for geo_el in self.storage_dict[ap_code_old]:
  2619. geometric_data = geo_el.geo
  2620. new_geo_el = {}
  2621. if 'solid' in geometric_data:
  2622. new_geo_el['solid'] = deepcopy(affinity.scale(geometric_data['solid'],
  2623. xfact=factor, yfact=factor))
  2624. if 'follow' in geometric_data:
  2625. new_geo_el['follow'] = deepcopy(affinity.scale(geometric_data['follow'],
  2626. xfact=factor, yfact=factor))
  2627. if 'clear' in geometric_data:
  2628. new_geo_el['clear'] = deepcopy(affinity.scale(geometric_data['clear'],
  2629. xfact=factor, yfact=factor))
  2630. geometry.append(new_geo_el)
  2631. self.add_gerber_shape(geometry, self.storage_dict[val_edited])
  2632. self.on_aperture_delete(apcode=ap_code_old)
  2633. # In case we edited the Size of the Aperture therefore the val_edited holds the new Aperture Size
  2634. # It will happen only for the Aperture Type == 'C' - I make sure of that in the self.build_ui()
  2635. elif col_of_item_changed == 3:
  2636. old_size = float(self.storage_dict[ap_code_old]['size'])
  2637. new_size = float(val_edited)
  2638. adjust_size = (new_size - old_size) / 2
  2639. geometry = []
  2640. for geo_el in self.storage_dict[ap_code_old]['geometry']:
  2641. g_data = geo_el.geo
  2642. new_geo_el = {}
  2643. if 'solid' in g_data:
  2644. if 'follow' in g_data:
  2645. if isinstance(g_data['follow'], Point):
  2646. new_geo_el['solid'] = deepcopy(g_data['solid'].buffer(adjust_size))
  2647. else:
  2648. new_geo_el['solid'] = deepcopy(g_data['solid'].buffer(adjust_size, join_style=2))
  2649. if 'follow' in g_data:
  2650. new_geo_el['follow'] = deepcopy(g_data['follow'])
  2651. if 'clear' in g_data:
  2652. new_geo_el['clear'] = deepcopy(g_data['clear'].buffer(adjust_size, join_style=2))
  2653. geometry.append(DrawToolShape(new_geo_el))
  2654. self.storage_dict[ap_code_old]['geometry'].clear()
  2655. self.add_gerber_shape(geometry, self.storage_dict[ap_code_old]['geometry'])
  2656. # self.storage_dict[ap_code_old]['geometry'] = geometry
  2657. # In case we edited the Dims of the Aperture therefore the val_edited holds a list with the dimensions
  2658. # in the format [width, height]
  2659. # It will happen only for the Aperture Type in ['R', 'O'] - I make sure of that in the self.build_ui()
  2660. # and below
  2661. elif col_of_item_changed == 4:
  2662. if str(self.storage_dict[ap_code_old]['type']) == 'R' or str(self.storage_dict[ap_code_old]['type']) == 'O':
  2663. # use the biggest from them
  2664. buff_val_lines = max(val_edited)
  2665. new_width = val_edited[0]
  2666. new_height = val_edited[1]
  2667. geometry = []
  2668. for geo_el in self.storage_dict[ap_code_old]['geometry']:
  2669. g_data = geo_el.geo
  2670. new_geo_el = {}
  2671. if 'solid' in g_data:
  2672. if 'follow' in g_data:
  2673. if isinstance(g_data['follow'], Point):
  2674. x = g_data['follow'].x
  2675. y = g_data['follow'].y
  2676. minx = x - (new_width / 2)
  2677. miny = y - (new_height / 2)
  2678. maxx = x + (new_width / 2)
  2679. maxy = y + (new_height / 2)
  2680. geo = box(minx=minx, miny=miny, maxx=maxx, maxy=maxy)
  2681. new_geo_el['solid'] = deepcopy(geo)
  2682. else:
  2683. new_geo_el['solid'] = deepcopy(g_data['solid'].buffer(buff_val_lines))
  2684. if 'follow' in g_data:
  2685. new_geo_el['follow'] = deepcopy(g_data['follow'])
  2686. if 'clear' in g_data:
  2687. if 'follow' in g_data:
  2688. if isinstance(g_data['follow'], Point):
  2689. x = g_data['follow'].x
  2690. y = g_data['follow'].y
  2691. minx = x - (new_width / 2)
  2692. miny = y - (new_height / 2)
  2693. maxx = x + (new_width / 2)
  2694. maxy = y + (new_height / 2)
  2695. geo = box(minx=minx, miny=miny, maxx=maxx, maxy=maxy)
  2696. new_geo_el['clear'] = deepcopy(geo)
  2697. else:
  2698. new_geo_el['clear'] = deepcopy(g_data['clear'].buffer(buff_val_lines, join_style=2))
  2699. geometry.append(DrawToolShape(new_geo_el))
  2700. self.storage_dict[ap_code_old]['geometry'].clear()
  2701. self.add_gerber_shape(geometry, self.storage_dict[ap_code_old]['geometry'])
  2702. self.plot_all()
  2703. # we reactivate the signals after the after the tool editing
  2704. self.ui.apertures_table.itemChanged.connect(self.on_tool_edit)
  2705. # self.ui.apertures_table.cellPressed.connect(self.on_row_selected)
  2706. def on_name_activate(self):
  2707. self.edited_obj_name = self.ui.name_entry.get_value()
  2708. def on_aptype_changed(self, current_text):
  2709. # 'O' is letter O not zero.
  2710. if current_text == 'R' or current_text == 'O':
  2711. self.ui.apdim_lbl.show()
  2712. self.ui.apdim_entry.show()
  2713. self.ui.apsize_entry.setDisabled(True)
  2714. else:
  2715. self.ui.apdim_lbl.hide()
  2716. self.ui.apdim_entry.hide()
  2717. self.ui.apsize_entry.setDisabled(False)
  2718. def activate_grb_editor(self):
  2719. # adjust the status of the menu entries related to the editor
  2720. self.app.ui.menueditedit.setDisabled(True)
  2721. self.app.ui.menueditok.setDisabled(False)
  2722. # adjust the visibility of some of the canvas context menu
  2723. self.app.ui.popmenu_edit.setVisible(False)
  2724. self.app.ui.popmenu_save.setVisible(True)
  2725. self.connect_canvas_event_handlers()
  2726. # init working objects
  2727. self.storage_dict = {}
  2728. self.current_storage = []
  2729. self.sorted_apcode = []
  2730. self.new_apertures = {}
  2731. self.new_aperture_macros = {}
  2732. self.grb_plot_promises = []
  2733. self.oldapcode_newapcode = {}
  2734. self.tid2apcode = {}
  2735. self.shapes.enabled = True
  2736. self.tool_shape.enabled = True
  2737. self.app.ui.corner_snap_btn.setVisible(True)
  2738. self.app.ui.snap_magnet.setVisible(True)
  2739. self.app.ui.grb_editor_menu.setDisabled(False)
  2740. self.app.ui.grb_editor_menu.menuAction().setVisible(True)
  2741. self.app.ui.update_obj_btn.setEnabled(True)
  2742. self.app.ui.grb_editor_cmenu.setEnabled(True)
  2743. self.app.ui.grb_edit_toolbar.setDisabled(False)
  2744. self.app.ui.grb_edit_toolbar.setVisible(True)
  2745. # self.app.ui.grid_toolbar.setDisabled(False)
  2746. # start with GRID toolbar activated
  2747. if self.app.ui.grid_snap_btn.isChecked() is False:
  2748. self.app.ui.grid_snap_btn.trigger()
  2749. # adjust the visibility of some of the canvas context menu
  2750. self.app.ui.popmenu_edit.setVisible(False)
  2751. self.app.ui.popmenu_save.setVisible(True)
  2752. self.app.ui.popmenu_disable.setVisible(False)
  2753. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  2754. self.app.ui.popmenu_properties.setVisible(False)
  2755. self.app.ui.grb_editor_cmenu.menuAction().setVisible(True)
  2756. def deactivate_grb_editor(self):
  2757. try:
  2758. QtGui.QGuiApplication.restoreOverrideCursor()
  2759. except Exception as e:
  2760. log.debug("AppGerberEditor.deactivate_grb_editor() --> %s" % str(e))
  2761. self.clear()
  2762. # adjust the status of the menu entries related to the editor
  2763. self.app.ui.menueditedit.setDisabled(False)
  2764. self.app.ui.menueditok.setDisabled(True)
  2765. # adjust the visibility of some of the canvas context menu
  2766. self.app.ui.popmenu_edit.setVisible(True)
  2767. self.app.ui.popmenu_save.setVisible(False)
  2768. self.disconnect_canvas_event_handlers()
  2769. self.app.ui.grb_edit_toolbar.setDisabled(True)
  2770. self.app.ui.corner_snap_btn.setVisible(False)
  2771. self.app.ui.snap_magnet.setVisible(False)
  2772. # set the Editor Toolbar visibility to what was before entering in the Editor
  2773. self.app.ui.grb_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2774. else self.app.ui.grb_edit_toolbar.setVisible(True)
  2775. # Disable visuals
  2776. self.shapes.enabled = False
  2777. self.tool_shape.enabled = False
  2778. # self.app.app_cursor.enabled = False
  2779. self.app.ui.grb_editor_menu.setDisabled(True)
  2780. self.app.ui.grb_editor_menu.menuAction().setVisible(False)
  2781. self.app.ui.update_obj_btn.setEnabled(False)
  2782. # adjust the visibility of some of the canvas context menu
  2783. self.app.ui.popmenu_edit.setVisible(True)
  2784. self.app.ui.popmenu_save.setVisible(False)
  2785. self.app.ui.popmenu_disable.setVisible(True)
  2786. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2787. self.app.ui.popmenu_properties.setVisible(True)
  2788. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2789. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2790. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2791. # Show original geometry
  2792. if self.gerber_obj:
  2793. self.gerber_obj.visible = True
  2794. def connect_canvas_event_handlers(self):
  2795. # Canvas events
  2796. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2797. # but those from AppGeoEditor
  2798. # first connect to new, then disconnect the old handlers
  2799. # don't ask why but if there is nothing connected I've seen issues
  2800. self.mp = self.canvas.graph_event_connect('mouse_press', self.on_canvas_click)
  2801. self.mm = self.canvas.graph_event_connect('mouse_move', self.on_canvas_move)
  2802. self.mr = self.canvas.graph_event_connect('mouse_release', self.on_grb_click_release)
  2803. if self.app.is_legacy is False:
  2804. self.canvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2805. self.canvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2806. self.canvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2807. self.canvas.graph_event_disconnect('mouse_double_click', self.app.on_mouse_double_click_over_plot)
  2808. else:
  2809. self.canvas.graph_event_disconnect(self.app.mp)
  2810. self.canvas.graph_event_disconnect(self.app.mm)
  2811. self.canvas.graph_event_disconnect(self.app.mr)
  2812. self.canvas.graph_event_disconnect(self.app.mdc)
  2813. self.app.collection.view.clicked.disconnect()
  2814. self.app.ui.popmenu_copy.triggered.disconnect()
  2815. self.app.ui.popmenu_delete.triggered.disconnect()
  2816. self.app.ui.popmenu_move.triggered.disconnect()
  2817. self.app.ui.popmenu_copy.triggered.connect(self.on_copy_button)
  2818. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2819. self.app.ui.popmenu_move.triggered.connect(self.on_move_button)
  2820. # Gerber Editor
  2821. self.app.ui.grb_draw_pad.triggered.connect(self.on_pad_add)
  2822. self.app.ui.grb_draw_pad_array.triggered.connect(self.on_pad_add_array)
  2823. self.app.ui.grb_draw_track.triggered.connect(self.on_track_add)
  2824. self.app.ui.grb_draw_region.triggered.connect(self.on_region_add)
  2825. self.app.ui.grb_draw_poligonize.triggered.connect(self.on_poligonize)
  2826. self.app.ui.grb_draw_semidisc.triggered.connect(self.on_add_semidisc)
  2827. self.app.ui.grb_draw_disc.triggered.connect(self.on_disc_add)
  2828. self.app.ui.grb_draw_buffer.triggered.connect(lambda: self.select_tool("buffer"))
  2829. self.app.ui.grb_draw_scale.triggered.connect(lambda: self.select_tool("scale"))
  2830. self.app.ui.grb_draw_markarea.triggered.connect(lambda: self.select_tool("markarea"))
  2831. self.app.ui.grb_draw_eraser.triggered.connect(self.on_eraser)
  2832. self.app.ui.grb_draw_transformations.triggered.connect(self.on_transform)
  2833. def disconnect_canvas_event_handlers(self):
  2834. # we restore the key and mouse control to FlatCAMApp method
  2835. # first connect to new, then disconnect the old handlers
  2836. # don't ask why but if there is nothing connected I've seen issues
  2837. self.app.mp = self.canvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2838. self.app.mm = self.canvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2839. self.app.mr = self.canvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2840. self.app.mdc = self.canvas.graph_event_connect('mouse_double_click', self.app.on_mouse_double_click_over_plot)
  2841. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2842. if self.app.is_legacy is False:
  2843. self.canvas.graph_event_disconnect('mouse_press', self.on_canvas_click)
  2844. self.canvas.graph_event_disconnect('mouse_move', self.on_canvas_move)
  2845. self.canvas.graph_event_disconnect('mouse_release', self.on_grb_click_release)
  2846. else:
  2847. self.canvas.graph_event_disconnect(self.mp)
  2848. self.canvas.graph_event_disconnect(self.mm)
  2849. self.canvas.graph_event_disconnect(self.mr)
  2850. try:
  2851. self.app.ui.popmenu_copy.triggered.disconnect(self.on_copy_button)
  2852. except (TypeError, AttributeError):
  2853. pass
  2854. try:
  2855. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2856. except (TypeError, AttributeError):
  2857. pass
  2858. try:
  2859. self.app.ui.popmenu_move.triggered.disconnect(self.on_move_button)
  2860. except (TypeError, AttributeError):
  2861. pass
  2862. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_command)
  2863. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2864. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2865. # Gerber Editor
  2866. try:
  2867. self.app.ui.grb_draw_pad.triggered.disconnect(self.on_pad_add)
  2868. except (TypeError, AttributeError):
  2869. pass
  2870. try:
  2871. self.app.ui.grb_draw_pad_array.triggered.disconnect(self.on_pad_add_array)
  2872. except (TypeError, AttributeError):
  2873. pass
  2874. try:
  2875. self.app.ui.grb_draw_track.triggered.disconnect(self.on_track_add)
  2876. except (TypeError, AttributeError):
  2877. pass
  2878. try:
  2879. self.app.ui.grb_draw_region.triggered.disconnect(self.on_region_add)
  2880. except (TypeError, AttributeError):
  2881. pass
  2882. try:
  2883. self.app.ui.grb_draw_poligonize.triggered.disconnect(self.on_poligonize)
  2884. except (TypeError, AttributeError):
  2885. pass
  2886. try:
  2887. self.app.ui.grb_draw_semidisc.triggered.diconnect(self.on_add_semidisc)
  2888. except (TypeError, AttributeError):
  2889. pass
  2890. try:
  2891. self.app.ui.grb_draw_disc.triggered.disconnect(self.on_disc_add)
  2892. except (TypeError, AttributeError):
  2893. pass
  2894. try:
  2895. self.app.ui.grb_draw_buffer.triggered.disconnect()
  2896. except (TypeError, AttributeError):
  2897. pass
  2898. try:
  2899. self.app.ui.grb_draw_scale.triggered.disconnect()
  2900. except (TypeError, AttributeError):
  2901. pass
  2902. try:
  2903. self.app.ui.grb_draw_markarea.triggered.disconnect()
  2904. except (TypeError, AttributeError):
  2905. pass
  2906. try:
  2907. self.app.ui.grb_draw_eraser.triggered.disconnect(self.on_eraser)
  2908. except (TypeError, AttributeError):
  2909. pass
  2910. try:
  2911. self.app.ui.grb_draw_transformations.triggered.disconnect(self.on_transform)
  2912. except (TypeError, AttributeError):
  2913. pass
  2914. try:
  2915. self.app.jump_signal.disconnect()
  2916. except (TypeError, AttributeError):
  2917. pass
  2918. def clear(self):
  2919. self.thread.quit()
  2920. self.active_tool = None
  2921. self.selected = []
  2922. self.storage_dict.clear()
  2923. self.results.clear()
  2924. self.shapes.clear(update=True)
  2925. self.tool_shape.clear(update=True)
  2926. self.ma_annotation.clear(update=True)
  2927. def edit_fcgerber(self, orig_grb_obj):
  2928. """
  2929. Imports the geometry found in self.apertures from the given FlatCAM Gerber object
  2930. into the editor.
  2931. :param orig_grb_obj: ExcellonObject
  2932. :return: None
  2933. """
  2934. self.deactivate_grb_editor()
  2935. self.activate_grb_editor()
  2936. # reset the tool table
  2937. self.ui.apertures_table.clear()
  2938. self.ui.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  2939. self.last_aperture_selected = None
  2940. # create a reference to the source object
  2941. self.gerber_obj = orig_grb_obj
  2942. self.gerber_obj_options = orig_grb_obj.options
  2943. file_units = self.gerber_obj.units if self.gerber_obj.units else 'IN'
  2944. app_units = self.app.defaults['units']
  2945. # self.conversion_factor = 25.4 if file_units == 'IN' else (1 / 25.4) if file_units != app_units else 1
  2946. if file_units == app_units:
  2947. self.conversion_factor = 1
  2948. else:
  2949. if file_units == 'IN':
  2950. self.conversion_factor = 25.4
  2951. else:
  2952. self.conversion_factor = 0.0393700787401575
  2953. # Hide original geometry
  2954. orig_grb_obj.visible = False
  2955. # Set selection tolerance
  2956. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2957. self.select_tool("select")
  2958. try:
  2959. # we activate this after the initial build as we don't need to see the tool been populated
  2960. self.ui.apertures_table.itemChanged.connect(self.on_tool_edit)
  2961. except Exception as e:
  2962. log.debug("AppGerberEditor.edit_fcgerber() --> %s" % str(e))
  2963. # apply the conversion factor on the obj.apertures
  2964. conv_apertures = deepcopy(self.gerber_obj.apertures)
  2965. for apcode in self.gerber_obj.apertures:
  2966. for key in self.gerber_obj.apertures[apcode]:
  2967. if key == 'width':
  2968. conv_apertures[apcode]['width'] = self.gerber_obj.apertures[apcode]['width'] * \
  2969. self.conversion_factor
  2970. elif key == 'height':
  2971. conv_apertures[apcode]['height'] = self.gerber_obj.apertures[apcode]['height'] * \
  2972. self.conversion_factor
  2973. elif key == 'diam':
  2974. conv_apertures[apcode]['diam'] = self.gerber_obj.apertures[apcode]['diam'] * self.conversion_factor
  2975. elif key == 'size':
  2976. conv_apertures[apcode]['size'] = self.gerber_obj.apertures[apcode]['size'] * self.conversion_factor
  2977. else:
  2978. conv_apertures[apcode][key] = self.gerber_obj.apertures[apcode][key]
  2979. self.gerber_obj.apertures = conv_apertures
  2980. self.gerber_obj.units = app_units
  2981. # # and then add it to the storage elements (each storage elements is a member of a list
  2982. # def job_thread(aperture_id):
  2983. # with self.app.proc_container.new('%s: %s ...' %
  2984. # (_("Adding geometry for aperture"), str(aperture_id))):
  2985. # storage_elem = []
  2986. # self.storage_dict[aperture_id] = {}
  2987. #
  2988. # # add the Gerber geometry to editor storage
  2989. # for k, v in self.gerber_obj.apertures[aperture_id].items():
  2990. # try:
  2991. # if k == 'geometry':
  2992. # for geo_el in v:
  2993. # if geo_el:
  2994. # self.add_gerber_shape(DrawToolShape(geo_el), storage_elem)
  2995. # self.storage_dict[aperture_id][k] = storage_elem
  2996. # else:
  2997. # self.storage_dict[aperture_id][k] = self.gerber_obj.apertures[aperture_id][k]
  2998. # except Exception as e:
  2999. # log.debug("AppGerberEditor.edit_fcgerber().job_thread() --> %s" % str(e))
  3000. #
  3001. # # Check promises and clear if exists
  3002. # while True:
  3003. # try:
  3004. # self.grb_plot_promises.remove(aperture_id)
  3005. # time.sleep(0.5)
  3006. # except ValueError:
  3007. # break
  3008. #
  3009. # # we create a job work each aperture, job that work in a threaded way to store the geometry in local storage
  3010. # # as DrawToolShapes
  3011. # for ap_code in self.gerber_obj.apertures:
  3012. # self.grb_plot_promises.append(ap_code)
  3013. # self.app.worker_task.emit({'fcn': job_thread, 'params': [ap_code]})
  3014. #
  3015. # self.set_ui()
  3016. #
  3017. # # do the delayed plot only if there is something to plot (the gerber is not empty)
  3018. # try:
  3019. # if bool(self.gerber_obj.apertures):
  3020. # self.start_delayed_plot(check_period=1000)
  3021. # else:
  3022. # raise AttributeError
  3023. # except AttributeError:
  3024. # # now that we have data (empty data actually), create the GUI interface and add it to the Tool Tab
  3025. # self.build_ui(first_run=True)
  3026. # # and add the first aperture to have something to play with
  3027. # self.on_aperture_add('10')
  3028. # self.app.worker_task.emit({'fcn': worker_job, 'params': [self]})
  3029. class Execute_Edit(QtCore.QObject):
  3030. start = QtCore.pyqtSignal(str)
  3031. def __init__(self, app):
  3032. super(Execute_Edit, self).__init__()
  3033. self.app = app
  3034. self.start.connect(self.run)
  3035. @staticmethod
  3036. def worker_job(app_obj):
  3037. with app_obj.app.proc_container.new('%s ...' % _("Loading")):
  3038. # ###############################################################
  3039. # APPLY CLEAR_GEOMETRY on the SOLID_GEOMETRY
  3040. # ###############################################################
  3041. # list of clear geos that are to be applied to the entire file
  3042. global_clear_geo = []
  3043. # create one big geometry made out of all 'negative' (clear) polygons
  3044. for aper_id in app_obj.gerber_obj.apertures:
  3045. # first check if we have any clear_geometry (LPC) and if yes added it to the global_clear_geo
  3046. if 'geometry' in app_obj.gerber_obj.apertures[aper_id]:
  3047. for elem in app_obj.gerber_obj.apertures[aper_id]['geometry']:
  3048. if 'clear' in elem:
  3049. global_clear_geo.append(elem['clear'])
  3050. log.warning("Found %d clear polygons." % len(global_clear_geo))
  3051. if global_clear_geo:
  3052. global_clear_geo = unary_union(global_clear_geo)
  3053. if isinstance(global_clear_geo, Polygon):
  3054. global_clear_geo = [global_clear_geo]
  3055. # we subtract the big "negative" (clear) geometry from each solid polygon but only the part of
  3056. # clear geometry that fits inside the solid. otherwise we may loose the solid
  3057. for ap_code in app_obj.gerber_obj.apertures:
  3058. temp_solid_geometry = []
  3059. if 'geometry' in app_obj.gerber_obj.apertures[ap_code]:
  3060. # for elem in self.gerber_obj.apertures[apcode]['geometry']:
  3061. # if 'solid' in elem:
  3062. # solid_geo = elem['solid']
  3063. # for clear_geo in global_clear_geo:
  3064. # # Make sure that the clear_geo is within the solid_geo otherwise we loose
  3065. # # the solid_geometry. We want for clear_geometry just to cut
  3066. # # into solid_geometry not to delete it
  3067. # if clear_geo.within(solid_geo):
  3068. # solid_geo = solid_geo.difference(clear_geo)
  3069. # try:
  3070. # for poly in solid_geo:
  3071. # new_elem = {}
  3072. #
  3073. # new_elem['solid'] = poly
  3074. # if 'clear' in elem:
  3075. # new_elem['clear'] = poly
  3076. # if 'follow' in elem:
  3077. # new_elem['follow'] = poly
  3078. # temp_elem.append(deepcopy(new_elem))
  3079. # except TypeError:
  3080. # new_elem = {}
  3081. # new_elem['solid'] = solid_geo
  3082. # if 'clear' in elem:
  3083. # new_elem['clear'] = solid_geo
  3084. # if 'follow' in elem:
  3085. # new_elem['follow'] = solid_geo
  3086. # temp_elem.append(deepcopy(new_elem))
  3087. for elem in app_obj.gerber_obj.apertures[ap_code]['geometry']:
  3088. new_elem = {}
  3089. if 'solid' in elem:
  3090. solid_geo = elem['solid']
  3091. if not global_clear_geo or global_clear_geo.is_empty:
  3092. pass
  3093. else:
  3094. for clear_geo in global_clear_geo:
  3095. # Make sure that the clear_geo is within the solid_geo otherwise we loose
  3096. # the solid_geometry. We want for clear_geometry just to cut into
  3097. # solid_geometry not to delete it
  3098. if clear_geo.within(solid_geo):
  3099. solid_geo = solid_geo.difference(clear_geo)
  3100. new_elem['solid'] = solid_geo
  3101. if 'clear' in elem:
  3102. new_elem['clear'] = elem['clear']
  3103. if 'follow' in elem:
  3104. new_elem['follow'] = elem['follow']
  3105. temp_solid_geometry.append(deepcopy(new_elem))
  3106. app_obj.gerber_obj.apertures[ap_code]['geometry'] = deepcopy(temp_solid_geometry)
  3107. log.warning("Polygon difference done for %d apertures." % len(app_obj.gerber_obj.apertures))
  3108. try:
  3109. # Loading the Geometry into Editor Storage
  3110. for ap_code, ap_dict in app_obj.gerber_obj.apertures.items():
  3111. app_obj.results.append(
  3112. app_obj.pool.apply_async(app_obj.add_apertures, args=(ap_code, ap_dict))
  3113. )
  3114. except Exception as ee:
  3115. log.debug(
  3116. "AppGerberEditor.edit_fcgerber.worker_job() Adding processes to pool --> %s" % str(ee))
  3117. traceback.print_exc()
  3118. output = []
  3119. for p in app_obj.results:
  3120. output.append(p.get())
  3121. for elem in output:
  3122. app_obj.storage_dict[elem[0]] = deepcopy(elem[1])
  3123. app_obj.mp_finished.emit(output)
  3124. def run(self):
  3125. self.worker_job(self.app)
  3126. # self.thread.start(QtCore.QThread.NormalPriority)
  3127. executable_edit = Execute_Edit(app=self)
  3128. # executable_edit.moveToThread(self.thread)
  3129. # executable_edit.start.emit("Started")
  3130. self.app.worker_task.emit({'fcn': executable_edit.run, 'params': []})
  3131. @staticmethod
  3132. def add_apertures(aperture_id, aperture_dict):
  3133. storage_elem = []
  3134. storage_dict = {}
  3135. for k, v in list(aperture_dict.items()):
  3136. try:
  3137. if k == 'geometry':
  3138. for geo_el in v:
  3139. if geo_el:
  3140. storage_elem.append(DrawToolShape(geo_el))
  3141. storage_dict[k] = storage_elem
  3142. else:
  3143. storage_dict[k] = aperture_dict[k]
  3144. except Exception as e:
  3145. log.debug("AppGerberEditor.edit_fcgerber().job_thread() --> %s" % str(e))
  3146. return [aperture_id, storage_dict]
  3147. def on_multiprocessing_finished(self):
  3148. self.app.proc_container.update_view_text(' %s' % _("Setting up the UI"))
  3149. self.app.inform.emit('[success] %s.' % _("Adding geometry finished. Preparing the GUI"))
  3150. self.set_ui()
  3151. self.build_ui(first_run=True)
  3152. self.plot_all()
  3153. # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  3154. # - perhaps is a bug in VisPy implementation
  3155. self.app.app_cursor.enabled = False
  3156. self.app.app_cursor.enabled = True
  3157. self.app.inform.emit('[success] %s' % _("Finished loading the Gerber object into the editor."))
  3158. def update_fcgerber(self):
  3159. """
  3160. Create a new Gerber object that contain the edited content of the source Gerber object
  3161. :return: None
  3162. """
  3163. new_grb_name = self.edited_obj_name
  3164. # if the 'delayed plot' malfunctioned stop the QTimer
  3165. try:
  3166. self.plot_thread.stop()
  3167. except Exception as e:
  3168. log.debug("AppGerberEditor.update_fcgerber() --> %s" % str(e))
  3169. if "_edit" in self.edited_obj_name:
  3170. try:
  3171. _id = int(self.edited_obj_name[-1]) + 1
  3172. new_grb_name = self.edited_obj_name[:-1] + str(_id)
  3173. except ValueError:
  3174. new_grb_name += "_1"
  3175. else:
  3176. new_grb_name = self.edited_obj_name + "_edit"
  3177. self.app.worker_task.emit({'fcn': self.new_edited_gerber, 'params': [new_grb_name, self.storage_dict]})
  3178. # self.new_edited_gerber(new_grb_name, self.storage_dict)
  3179. @staticmethod
  3180. def update_options(obj):
  3181. try:
  3182. if not obj.options:
  3183. obj.options = {'xmin': 0, 'ymin': 0, 'xmax': 0, 'ymax': 0}
  3184. return True
  3185. else:
  3186. return False
  3187. except AttributeError:
  3188. obj.options = {}
  3189. return True
  3190. def new_edited_gerber(self, outname, aperture_storage):
  3191. """
  3192. Creates a new Gerber object for the edited Gerber. Thread-safe.
  3193. :param outname: Name of the resulting object. None causes the name to be that of the file.
  3194. :type outname: str
  3195. :param aperture_storage: a dictionary that holds all the objects geometry
  3196. :type aperture_storage: dict
  3197. :return: None
  3198. """
  3199. self.app.log.debug("Update the Gerber object with edited content. Source is: %s" %
  3200. self.gerber_obj.options['name'].upper())
  3201. out_name = outname
  3202. storage_dict = aperture_storage
  3203. local_storage_dict = {}
  3204. for aperture in storage_dict:
  3205. if 'geometry' in storage_dict[aperture]:
  3206. # add aperture only if it has geometry
  3207. if len(storage_dict[aperture]['geometry']) > 0:
  3208. local_storage_dict[aperture] = deepcopy(storage_dict[aperture])
  3209. # How the object should be initialized
  3210. def obj_init(grb_obj, app_obj):
  3211. poly_buffer = []
  3212. follow_buffer = []
  3213. for storage_apcode, storage_val in local_storage_dict.items():
  3214. grb_obj.apertures[storage_apcode] = {}
  3215. for k, val in storage_val.items():
  3216. if k == 'geometry':
  3217. grb_obj.apertures[storage_apcode][k] = []
  3218. for geo_el in val:
  3219. geometric_data = geo_el.geo
  3220. new_geo_el = {}
  3221. if 'solid' in geometric_data:
  3222. new_geo_el['solid'] = geometric_data['solid']
  3223. poly_buffer.append(deepcopy(new_geo_el['solid']))
  3224. if 'follow' in geometric_data:
  3225. # if isinstance(geometric_data['follow'], Polygon):
  3226. # buff_val = -(int(storage_val['size']) / 2)
  3227. # geo_f = (geometric_data['follow'].buffer(buff_val)).exterior
  3228. # new_geo_el['follow'] = geo_f
  3229. # else:
  3230. # new_geo_el['follow'] = geometric_data['follow']
  3231. new_geo_el['follow'] = geometric_data['follow']
  3232. follow_buffer.append(deepcopy(new_geo_el['follow']))
  3233. else:
  3234. if 'solid' in geometric_data:
  3235. geo_f = geometric_data['solid'].exterior
  3236. new_geo_el['follow'] = geo_f
  3237. follow_buffer.append(deepcopy(new_geo_el['follow']))
  3238. if 'clear' in geometric_data:
  3239. new_geo_el['clear'] = geometric_data['clear']
  3240. if new_geo_el:
  3241. grb_obj.apertures[storage_apcode][k].append(deepcopy(new_geo_el))
  3242. else:
  3243. grb_obj.apertures[storage_apcode][k] = val
  3244. grb_obj.aperture_macros = deepcopy(self.gerber_obj.aperture_macros)
  3245. new_poly = MultiPolygon(poly_buffer)
  3246. new_poly = new_poly.buffer(0.00000001)
  3247. new_poly = new_poly.buffer(-0.00000001)
  3248. # for ad in grb_obj.apertures:
  3249. # print(ad, grb_obj.apertures[ad])
  3250. try:
  3251. __ = iter(new_poly)
  3252. except TypeError:
  3253. new_poly = [new_poly]
  3254. grb_obj.solid_geometry = deepcopy(new_poly)
  3255. grb_obj.follow_geometry = deepcopy(follow_buffer)
  3256. for k, v in self.gerber_obj_options.items():
  3257. if k == 'name':
  3258. grb_obj.options[k] = out_name
  3259. else:
  3260. grb_obj.options[k] = deepcopy(v)
  3261. grb_obj.multigeo = False
  3262. grb_obj.follow = False
  3263. grb_obj.units = app_obj.defaults['units']
  3264. try:
  3265. grb_obj.create_geometry()
  3266. except KeyError:
  3267. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3268. _("There are no Aperture definitions in the file. Aborting Gerber creation."))
  3269. except Exception:
  3270. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  3271. msg += traceback.format_exc()
  3272. app_obj.inform.emit(msg)
  3273. raise
  3274. grb_obj.source_file = self.app.f_handlers.export_gerber(obj_name=out_name, filename=None,
  3275. local_use=grb_obj, use_thread=False)
  3276. with self.app.proc_container.new(_("Working ...")):
  3277. try:
  3278. self.app.app_obj.new_object("gerber", outname, obj_init)
  3279. except Exception as e:
  3280. log.error("Error on Edited object creation: %s" % str(e))
  3281. # make sure to clean the previous results
  3282. self.results = []
  3283. return
  3284. # make sure to clean the previous results
  3285. self.results = []
  3286. self.deactivate_grb_editor()
  3287. self.app.inform.emit('[success] %s' % _("Done."))
  3288. def on_tool_select(self, tool):
  3289. """
  3290. Behavior of the toolbar. Tool initialization.
  3291. :rtype : None
  3292. """
  3293. current_tool = tool
  3294. self.app.log.debug("on_tool_select('%s')" % tool)
  3295. if self.last_aperture_selected is None and current_tool != 'select':
  3296. # self.draw_app.select_tool('select')
  3297. self.complete = True
  3298. current_tool = 'select'
  3299. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled. No aperture is selected"))
  3300. # This is to make the group behave as radio group
  3301. if current_tool in self.tools_gerber:
  3302. if self.tools_gerber[current_tool]["button"].isChecked():
  3303. self.app.log.debug("%s is checked." % current_tool)
  3304. for t in self.tools_gerber:
  3305. if t != current_tool:
  3306. self.tools_gerber[t]["button"].setChecked(False)
  3307. # this is where the Editor toolbar classes (button's) are instantiated
  3308. self.active_tool = self.tools_gerber[current_tool]["constructor"](self)
  3309. # self.app.inform.emit(self.active_tool.start_msg)
  3310. else:
  3311. self.app.log.debug("%s is NOT checked." % current_tool)
  3312. for t in self.tools_gerber:
  3313. self.tools_gerber[t]["button"].setChecked(False)
  3314. self.select_tool('select')
  3315. self.active_tool = FCApertureSelect(self)
  3316. def on_row_selected(self, row, col):
  3317. # if col == 0:
  3318. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3319. if self.app.defaults["global_mselect_key"] == 'Control':
  3320. modifier_to_use = Qt.ControlModifier
  3321. else:
  3322. modifier_to_use = Qt.ShiftModifier
  3323. if key_modifier == modifier_to_use:
  3324. pass
  3325. else:
  3326. self.selected = []
  3327. try:
  3328. selected_ap_code = self.ui.apertures_table.item(row, 1).text()
  3329. self.last_aperture_selected = copy(selected_ap_code)
  3330. for obj in self.storage_dict[selected_ap_code]['geometry']:
  3331. self.selected.append(obj)
  3332. except Exception as e:
  3333. self.app.log.debug(str(e))
  3334. self.plot_all()
  3335. # def toolbar_tool_toggle(self, key):
  3336. # """
  3337. #
  3338. # :param key: key to update in self.options dictionary
  3339. # :return:
  3340. # """
  3341. # self.options[key] = self.sender().isChecked()
  3342. # return self.options[key]
  3343. def on_grb_shape_complete(self, storage=None, specific_shape=None, no_plot=False):
  3344. """
  3345. :param storage: where to store the shape
  3346. :param specific_shape: optional, the shape to be stored
  3347. :param no_plot: use this if you want the added shape not plotted
  3348. :return:
  3349. """
  3350. self.app.log.debug("on_grb_shape_complete()")
  3351. if specific_shape:
  3352. geo = specific_shape
  3353. else:
  3354. geo = deepcopy(self.active_tool.geometry)
  3355. if geo is None:
  3356. return
  3357. if storage is not None:
  3358. # Add shape
  3359. self.add_gerber_shape(geo, storage)
  3360. else:
  3361. stora = self.storage_dict[self.last_aperture_selected]['geometry']
  3362. self.add_gerber_shape(geo, storage=stora)
  3363. # Remove any utility shapes
  3364. self.delete_utility_geometry()
  3365. self.tool_shape.clear(update=True)
  3366. if no_plot is False:
  3367. # Re-plot and reset tool.
  3368. self.plot_all()
  3369. def add_gerber_shape(self, shape_element, storage):
  3370. """
  3371. Adds a shape to the shape storage.
  3372. :param shape_element: Shape to be added.
  3373. :type shape_element: DrawToolShape or DrawToolUtilityShape Geometry is stored as a dict with keys: solid,
  3374. follow, clear, each value being a list of Shapely objects. The dict can have at least one of the mentioned keys
  3375. :param storage: Where to store the shape
  3376. :return: None
  3377. """
  3378. # List of DrawToolShape?
  3379. if isinstance(shape_element, list):
  3380. for subshape in shape_element:
  3381. self.add_gerber_shape(subshape, storage)
  3382. return
  3383. assert isinstance(shape_element, DrawToolShape), \
  3384. "Expected a DrawToolShape, got %s" % str(type(shape_element))
  3385. assert shape_element.geo is not None, \
  3386. "Shape object has empty geometry (None)"
  3387. assert(isinstance(shape_element.geo, list) and len(shape_element.geo) > 0) or not \
  3388. isinstance(shape_element.geo, list), "Shape objects has empty geometry ([])"
  3389. if isinstance(shape_element, DrawToolUtilityShape):
  3390. self.utility.append(shape_element)
  3391. else:
  3392. storage.append(shape_element)
  3393. def on_canvas_click(self, event):
  3394. """
  3395. event.x and .y have canvas coordinates
  3396. event.xdata and .ydata have plot coordinates
  3397. :param event: Event object dispatched by VisPy
  3398. :return: None
  3399. """
  3400. if self.app.is_legacy is False:
  3401. event_pos = event.pos
  3402. # event_is_dragging = event.is_dragging
  3403. # right_button = 2
  3404. else:
  3405. event_pos = (event.xdata, event.ydata)
  3406. # event_is_dragging = self.app.plotcanvas.is_dragging
  3407. # right_button = 3
  3408. self.pos = self.canvas.translate_coords(event_pos)
  3409. if self.app.grid_status():
  3410. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  3411. else:
  3412. self.pos = (self.pos[0], self.pos[1])
  3413. if event.button == 1:
  3414. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3415. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3416. # Selection with left mouse button
  3417. if self.active_tool is not None:
  3418. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3419. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3420. if modifiers == QtCore.Qt.ShiftModifier:
  3421. self.app.clipboard.setText(
  3422. self.app.defaults["global_point_clipboard_format"] %
  3423. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  3424. )
  3425. self.app.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  3426. return
  3427. # Dispatch event to active_tool
  3428. self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  3429. # If it is a shape generating tool
  3430. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3431. if self.current_storage is not None:
  3432. self.on_grb_shape_complete(self.current_storage)
  3433. self.build_ui()
  3434. # MS: always return to the Select Tool if modifier key is not pressed
  3435. # else return to the current tool
  3436. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3437. if self.app.defaults["global_mselect_key"] == 'Control':
  3438. modifier_to_use = Qt.ControlModifier
  3439. else:
  3440. modifier_to_use = Qt.ShiftModifier
  3441. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  3442. # in the selected list, we removed it. Therefore first click selects, second deselects.
  3443. if key_modifier == modifier_to_use:
  3444. self.select_tool(self.active_tool.name)
  3445. else:
  3446. # return to Select tool but not for FCPad
  3447. if isinstance(self.active_tool, FCPad):
  3448. self.select_tool(self.active_tool.name)
  3449. else:
  3450. self.select_tool("select")
  3451. return
  3452. # if isinstance(self.active_tool, FCApertureSelect):
  3453. # self.plot_all()
  3454. else:
  3455. self.app.log.debug("No active tool to respond to click!")
  3456. def on_grb_click_release(self, event):
  3457. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  3458. if self.app.is_legacy is False:
  3459. event_pos = event.pos
  3460. # event_is_dragging = event.is_dragging
  3461. right_button = 2
  3462. else:
  3463. event_pos = (event.xdata, event.ydata)
  3464. # event_is_dragging = self.app.plotcanvas.is_dragging
  3465. right_button = 3
  3466. pos_canvas = self.canvas.translate_coords(event_pos)
  3467. if self.app.grid_status():
  3468. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3469. else:
  3470. pos = (pos_canvas[0], pos_canvas[1])
  3471. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3472. # canvas menu
  3473. try:
  3474. if event.button == right_button: # right click
  3475. if self.app.ui.popMenu.mouse_is_panning is False:
  3476. if self.in_action is False:
  3477. try:
  3478. QtGui.QGuiApplication.restoreOverrideCursor()
  3479. except Exception as e:
  3480. log.debug("AppGerberEditor.on_grb_click_release() --> %s" % str(e))
  3481. if self.active_tool.complete is False and not isinstance(self.active_tool, FCApertureSelect):
  3482. self.active_tool.complete = True
  3483. self.in_action = False
  3484. self.delete_utility_geometry()
  3485. self.app.inform.emit('[success] %s' %
  3486. _("Done."))
  3487. self.select_tool('select')
  3488. else:
  3489. self.app.cursor = QtGui.QCursor()
  3490. self.app.populate_cmenu_grids()
  3491. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3492. else:
  3493. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3494. # right mouse click will finish the action
  3495. if isinstance(self.active_tool, FCShapeTool):
  3496. if isinstance(self.active_tool, FCTrack):
  3497. self.active_tool.make()
  3498. else:
  3499. self.active_tool.click(self.app.geo_editor.snap(self.x, self.y))
  3500. self.active_tool.make()
  3501. if self.active_tool.complete:
  3502. self.on_grb_shape_complete()
  3503. self.app.inform.emit('[success] %s' % _("Done."))
  3504. # MS: always return to the Select Tool if modifier key is not pressed
  3505. # else return to the current tool but not for FCTrack
  3506. if isinstance(self.active_tool, FCTrack):
  3507. self.select_tool(self.active_tool.name)
  3508. else:
  3509. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3510. if (self.app.defaults["global_mselect_key"] == 'Control' and
  3511. key_modifier == Qt.ControlModifier) or \
  3512. (self.app.defaults["global_mselect_key"] == 'Shift' and
  3513. key_modifier == Qt.ShiftModifier):
  3514. self.select_tool(self.active_tool.name)
  3515. else:
  3516. self.select_tool("select")
  3517. except Exception as e:
  3518. log.warning("AppGerberEditor.on_grb_click_release() RMB click --> Error: %s" % str(e))
  3519. raise
  3520. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3521. # selection and then select a type of selection ("enclosing" or "touching")
  3522. try:
  3523. if event.button == 1: # left click
  3524. if self.app.selection_type is not None:
  3525. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3526. self.app.selection_type = None
  3527. elif isinstance(self.active_tool, FCApertureSelect):
  3528. self.active_tool.click_release((self.pos[0], self.pos[1]))
  3529. # # if there are selected objects then plot them
  3530. # if self.selected:
  3531. # self.plot_all()
  3532. except Exception as e:
  3533. log.warning("AppGerberEditor.on_grb_click_release() LMB click --> Error: %s" % str(e))
  3534. raise
  3535. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3536. """
  3537. :param start_pos: mouse position when the selection LMB click was done
  3538. :param end_pos: mouse position when the left mouse button is released
  3539. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3540. :return:
  3541. """
  3542. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3543. sel_aperture = set()
  3544. self.ui.apertures_table.clearSelection()
  3545. self.app.delete_selection_shape()
  3546. for storage in self.storage_dict:
  3547. for obj in self.storage_dict[storage]['geometry']:
  3548. if 'solid' in obj.geo:
  3549. geometric_data = obj.geo['solid']
  3550. if (sel_type is True and poly_selection.contains(geometric_data)) or \
  3551. (sel_type is False and poly_selection.intersects(geometric_data)):
  3552. if self.key == self.app.defaults["global_mselect_key"]:
  3553. if obj in self.selected:
  3554. self.selected.remove(obj)
  3555. else:
  3556. # add the object to the selected shapes
  3557. self.selected.append(obj)
  3558. sel_aperture.add(storage)
  3559. else:
  3560. self.selected.append(obj)
  3561. sel_aperture.add(storage)
  3562. try:
  3563. self.ui.apertures_table.cellPressed.disconnect()
  3564. except Exception as e:
  3565. log.debug("AppGerberEditor.draw_selection_Area_handler() --> %s" % str(e))
  3566. # select the aperture code of the selected geometry, in the tool table
  3567. self.ui.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  3568. for aper in sel_aperture:
  3569. for row_to_sel in range(self.ui.apertures_table.rowCount()):
  3570. if str(aper) == self.ui.apertures_table.item(row_to_sel, 1).text():
  3571. if row_to_sel not in set(index.row() for index in self.ui.apertures_table.selectedIndexes()):
  3572. self.ui.apertures_table.selectRow(row_to_sel)
  3573. self.last_aperture_selected = aper
  3574. self.ui.apertures_table.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  3575. self.ui.apertures_table.cellPressed.connect(self.on_row_selected)
  3576. self.plot_all()
  3577. def on_canvas_move(self, event):
  3578. """
  3579. Called on 'mouse_move' event
  3580. event.pos have canvas screen coordinates
  3581. :param event: Event object dispatched by VisPy SceneCavas
  3582. :return: None
  3583. """
  3584. if self.app.is_legacy is False:
  3585. event_pos = event.pos
  3586. event_is_dragging = event.is_dragging
  3587. right_button = 2
  3588. else:
  3589. event_pos = (event.xdata, event.ydata)
  3590. event_is_dragging = self.app.plotcanvas.is_dragging
  3591. right_button = 3
  3592. pos_canvas = self.canvas.translate_coords(event_pos)
  3593. event.xdata, event.ydata = pos_canvas[0], pos_canvas[1]
  3594. self.x = event.xdata
  3595. self.y = event.ydata
  3596. self.app.ui.popMenu.mouse_is_panning = False
  3597. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3598. if event.button == right_button and event_is_dragging == 1:
  3599. self.app.ui.popMenu.mouse_is_panning = True
  3600. return
  3601. try:
  3602. x = float(event.xdata)
  3603. y = float(event.ydata)
  3604. except TypeError:
  3605. return
  3606. if self.active_tool is None:
  3607. return
  3608. # # ## Snap coordinates
  3609. if self.app.grid_status():
  3610. x, y = self.app.geo_editor.snap(x, y)
  3611. # Update cursor
  3612. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color=self.app.cursor_color_3D,
  3613. edge_width=self.app.defaults["global_cursor_width"],
  3614. size=self.app.defaults["global_cursor_size"])
  3615. self.snap_x = x
  3616. self.snap_y = y
  3617. self.app.mouse = [x, y]
  3618. if self.pos is None:
  3619. self.pos = (0, 0)
  3620. self.app.dx = x - self.pos[0]
  3621. self.app.dy = y - self.pos[1]
  3622. # # update the position label in the infobar since the APP mouse event handlers are disconnected
  3623. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3624. "<b>Y</b>: %.4f&nbsp;" % (x, y))
  3625. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3626. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3627. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  3628. units = self.app.defaults["units"].lower()
  3629. self.app.plotcanvas.text_hud.text = \
  3630. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3631. self.app.dx, units, self.app.dy, units, x, units, y, units)
  3632. self.update_utility_geometry(data=(x, y))
  3633. # # ## Selection area on canvas section # ##
  3634. if event_is_dragging == 1 and event.button == 1:
  3635. # I make an exception for FCRegion and FCTrack because clicking and dragging while making regions can
  3636. # create strange issues like missing a point in a track/region
  3637. if isinstance(self.active_tool, FCRegion) or isinstance(self.active_tool, FCTrack):
  3638. pass
  3639. else:
  3640. dx = pos_canvas[0] - self.pos[0]
  3641. self.app.delete_selection_shape()
  3642. if dx < 0:
  3643. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3644. color=self.app.defaults["global_alt_sel_line"],
  3645. face_color=self.app.defaults['global_alt_sel_fill'])
  3646. self.app.selection_type = False
  3647. else:
  3648. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3649. self.app.selection_type = True
  3650. else:
  3651. self.app.selection_type = None
  3652. def update_utility_geometry(self, data):
  3653. # # ## Utility geometry (animated)
  3654. geo = self.active_tool.utility_geometry(data=data)
  3655. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3656. # Remove any previous utility shape
  3657. self.tool_shape.clear(update=True)
  3658. self.draw_utility_geometry(geo=geo)
  3659. def draw_utility_geometry(self, geo):
  3660. if type(geo.geo) == list:
  3661. for el in geo.geo:
  3662. geometric_data = el['solid']
  3663. # Add the new utility shape
  3664. self.tool_shape.add(
  3665. shape=geometric_data, color=(self.app.defaults["global_draw_color"] + '80'),
  3666. # face_color=self.app.defaults['global_alt_sel_fill'],
  3667. update=False, layer=0, tolerance=None
  3668. )
  3669. else:
  3670. geometric_data = geo.geo['solid']
  3671. # Add the new utility shape
  3672. self.tool_shape.add(
  3673. shape=geometric_data,
  3674. color=(self.app.defaults["global_draw_color"] + '80'),
  3675. # face_color=self.app.defaults['global_alt_sel_fill'],
  3676. update=False, layer=0, tolerance=None
  3677. )
  3678. self.tool_shape.redraw()
  3679. def plot_all(self):
  3680. """
  3681. Plots all shapes in the editor.
  3682. :return: None
  3683. :rtype: None
  3684. """
  3685. with self.app.proc_container.new('%s ...' % _("Plotting")):
  3686. self.shapes.clear(update=True)
  3687. for storage in self.storage_dict:
  3688. # fix for apertures with no geometry inside
  3689. if 'geometry' in self.storage_dict[storage]:
  3690. for elem in self.storage_dict[storage]['geometry']:
  3691. if 'solid' in elem.geo:
  3692. geometric_data = elem.geo['solid']
  3693. if geometric_data is None:
  3694. continue
  3695. if elem in self.selected:
  3696. self.plot_shape(geometry=geometric_data,
  3697. color=self.app.defaults['global_sel_draw_color'] + 'FF',
  3698. linewidth=2)
  3699. else:
  3700. self.plot_shape(geometry=geometric_data,
  3701. color=self.app.defaults['global_draw_color'] + 'FF')
  3702. if self.utility:
  3703. for elem in self.utility:
  3704. geometric_data = elem.geo['solid']
  3705. self.plot_shape(geometry=geometric_data, linewidth=1)
  3706. continue
  3707. self.shapes.redraw()
  3708. def plot_shape(self, geometry=None, color='#000000FF', linewidth=1):
  3709. """
  3710. Plots a geometric object or list of objects without rendering. Plotted objects
  3711. are returned as a list. This allows for efficient/animated rendering.
  3712. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3713. :param color: Shape color
  3714. :param linewidth: Width of lines in # of pixels.
  3715. :return: List of plotted elements.
  3716. """
  3717. if geometry is None:
  3718. geometry = self.active_tool.geometry
  3719. try:
  3720. self.shapes.add(shape=geometry.geo, color=color, face_color=color, layer=0, tolerance=self.tolerance)
  3721. except AttributeError:
  3722. if type(geometry) == Point:
  3723. return
  3724. if len(color) == 9:
  3725. color = color[:7] + 'AF'
  3726. self.shapes.add(shape=geometry, color=color, face_color=color, layer=0, tolerance=self.tolerance)
  3727. # def start_delayed_plot(self, check_period):
  3728. # """
  3729. # This function starts an QTImer and it will periodically check if all the workers finish the plotting functions
  3730. #
  3731. # :param check_period: time at which to check periodically if all plots finished to be plotted
  3732. # :return:
  3733. # """
  3734. #
  3735. # # self.plot_thread = threading.Thread(target=lambda: self.check_plot_finished(check_period))
  3736. # # self.plot_thread.start()
  3737. # log.debug("AppGerberEditor --> Delayed Plot started.")
  3738. # self.plot_thread = QtCore.QTimer()
  3739. # self.plot_thread.setInterval(check_period)
  3740. # self.plot_finished.connect(self.setup_ui_after_delayed_plot)
  3741. # self.plot_thread.timeout.connect(self.check_plot_finished)
  3742. # self.plot_thread.start()
  3743. #
  3744. # def check_plot_finished(self):
  3745. # """
  3746. # If all the promises made are finished then all the shapes are in shapes_storage and can be plotted safely and
  3747. # then the UI is rebuilt accordingly.
  3748. # :return:
  3749. # """
  3750. #
  3751. # try:
  3752. # if not self.grb_plot_promises:
  3753. # self.plot_thread.stop()
  3754. # self.plot_finished.emit()
  3755. # log.debug("AppGerberEditor --> delayed_plot finished")
  3756. # except Exception as e:
  3757. # traceback.print_exc()
  3758. #
  3759. # def setup_ui_after_delayed_plot(self):
  3760. # self.plot_finished.disconnect()
  3761. #
  3762. # # now that we have data, create the GUI interface and add it to the Tool Tab
  3763. # self.build_ui(first_run=True)
  3764. # self.plot_all()
  3765. #
  3766. # # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  3767. # # - perhaps is a bug in VisPy implementation
  3768. # self.app.app_cursor.enabled = False
  3769. # self.app.app_cursor.enabled = True
  3770. def on_zoom_fit(self):
  3771. """
  3772. Callback for zoom-fit request in Gerber Editor
  3773. :return: None
  3774. """
  3775. log.debug("AppGerberEditor.on_zoom_fit()")
  3776. # calculate all the geometry in the edited Gerber object
  3777. edit_geo = []
  3778. for ap_code in self.storage_dict:
  3779. for geo_el in self.storage_dict[ap_code]['geometry']:
  3780. actual_geo = geo_el.geo
  3781. if 'solid' in actual_geo:
  3782. edit_geo.append(actual_geo['solid'])
  3783. all_geo = unary_union(edit_geo)
  3784. # calculate the bounds values for the edited Gerber object
  3785. xmin, ymin, xmax, ymax = all_geo.bounds
  3786. if self.app.is_legacy is False:
  3787. new_rect = Rect(xmin, ymin, xmax, ymax)
  3788. self.app.plotcanvas.fit_view(rect=new_rect)
  3789. else:
  3790. width = xmax - xmin
  3791. height = ymax - ymin
  3792. xmin -= 0.05 * width
  3793. xmax += 0.05 * width
  3794. ymin -= 0.05 * height
  3795. ymax += 0.05 * height
  3796. self.app.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  3797. def get_selected(self):
  3798. """
  3799. Returns list of shapes that are selected in the editor.
  3800. :return: List of shapes.
  3801. """
  3802. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3803. return self.selected
  3804. def delete_selected(self):
  3805. temp_ref = [s for s in self.selected]
  3806. if len(temp_ref) == 0:
  3807. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3808. _("Failed. No aperture geometry is selected."))
  3809. return
  3810. for shape_sel in temp_ref:
  3811. self.delete_shape(shape_sel)
  3812. self.selected = []
  3813. self.build_ui()
  3814. self.app.inform.emit('[success] %s' % _("Done."))
  3815. def delete_shape(self, geo_el):
  3816. self.is_modified = True
  3817. if geo_el in self.utility:
  3818. self.utility.remove(geo_el)
  3819. return
  3820. for storage in self.storage_dict:
  3821. try:
  3822. if geo_el in self.storage_dict[storage]['geometry']:
  3823. self.storage_dict[storage]['geometry'].remove(geo_el)
  3824. except KeyError:
  3825. pass
  3826. if geo_el in self.selected:
  3827. self.selected.remove(geo_el) # TODO: Check performance
  3828. def delete_utility_geometry(self):
  3829. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  3830. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  3831. for_deletion = [geo_el for geo_el in self.utility]
  3832. for geo_el in for_deletion:
  3833. self.delete_shape(geo_el)
  3834. self.tool_shape.clear(update=True)
  3835. self.tool_shape.redraw()
  3836. def on_delete_btn(self):
  3837. self.delete_selected()
  3838. self.plot_all()
  3839. def select_tool(self, toolname):
  3840. """
  3841. Selects a drawing tool. Impacts the object and appGUI.
  3842. :param toolname: Name of the tool.
  3843. :return: None
  3844. """
  3845. self.tools_gerber[toolname]["button"].setChecked(True)
  3846. self.on_tool_select(toolname)
  3847. def set_selected(self, geo_el):
  3848. # Remove and add to the end.
  3849. if geo_el in self.selected:
  3850. self.selected.remove(geo_el)
  3851. self.selected.append(geo_el)
  3852. def set_unselected(self, geo_el):
  3853. if geo_el in self.selected:
  3854. self.selected.remove(geo_el)
  3855. def on_array_type_combo(self):
  3856. if self.ui.array_type_combo.currentIndex() == 0:
  3857. self.ui.array_circular_frame.hide()
  3858. self.ui.array_linear_frame.show()
  3859. else:
  3860. self.delete_utility_geometry()
  3861. self.ui.array_circular_frame.show()
  3862. self.ui.array_linear_frame.hide()
  3863. self.app.inform.emit(_("Click on the circular array Center position"))
  3864. def on_linear_angle_radio(self):
  3865. val = self.ui.pad_axis_radio.get_value()
  3866. if val == 'A':
  3867. self.ui.linear_angle_spinner.show()
  3868. self.ui.linear_angle_label.show()
  3869. else:
  3870. self.ui.linear_angle_spinner.hide()
  3871. self.ui.linear_angle_label.hide()
  3872. def on_copy_button(self):
  3873. self.select_tool('copy')
  3874. return
  3875. def on_move_button(self):
  3876. self.select_tool('move')
  3877. return
  3878. def on_pad_add(self):
  3879. self.select_tool('pad')
  3880. def on_pad_add_array(self):
  3881. self.select_tool('array')
  3882. def on_track_add(self):
  3883. self.select_tool('track')
  3884. def on_region_add(self):
  3885. self.select_tool('region')
  3886. def on_poligonize(self):
  3887. self.select_tool('poligonize')
  3888. def on_disc_add(self):
  3889. self.select_tool('disc')
  3890. def on_add_semidisc(self):
  3891. self.select_tool('semidisc')
  3892. def on_buffer(self):
  3893. buff_value = 0.01
  3894. log.debug("AppGerberEditor.on_buffer()")
  3895. try:
  3896. buff_value = float(self.ui.buffer_distance_entry.get_value())
  3897. except ValueError:
  3898. # try to convert comma to decimal point. if it's still not working error message and return
  3899. try:
  3900. buff_value = float(self.ui.buffer_distance_entry.get_value().replace(',', '.'))
  3901. self.ui.buffer_distance_entry.set_value(buff_value)
  3902. except ValueError:
  3903. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3904. _("Buffer distance value is missing or wrong format. Add it and retry."))
  3905. return
  3906. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  3907. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  3908. join_style = self.ui.buffer_corner_cb.currentIndex() + 1
  3909. def buffer_recursion(geom_el, selection):
  3910. if type(geom_el) == list:
  3911. geoms = []
  3912. for local_geom in geom_el:
  3913. geoms.append(buffer_recursion(local_geom, selection=selection))
  3914. return geoms
  3915. else:
  3916. if geom_el in selection:
  3917. geometric_data = geom_el.geo
  3918. buffered_geom_el = {}
  3919. if 'solid' in geometric_data:
  3920. buffered_geom_el['solid'] = geometric_data['solid'].buffer(buff_value, join_style=join_style)
  3921. if 'follow' in geometric_data:
  3922. buffered_geom_el['follow'] = geometric_data['follow'].buffer(buff_value, join_style=join_style)
  3923. if 'clear' in geometric_data:
  3924. buffered_geom_el['clear'] = geometric_data['clear'].buffer(buff_value, join_style=join_style)
  3925. return DrawToolShape(buffered_geom_el)
  3926. else:
  3927. return geom_el
  3928. if not self.ui.apertures_table.selectedItems():
  3929. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3930. _("No aperture to buffer. Select at least one aperture and try again."))
  3931. return
  3932. for x in self.ui.apertures_table.selectedItems():
  3933. try:
  3934. apcode = self.ui.apertures_table.item(x.row(), 1).text()
  3935. temp_storage = deepcopy(buffer_recursion(self.storage_dict[apcode]['geometry'], self.selected))
  3936. self.storage_dict[apcode]['geometry'] = []
  3937. self.storage_dict[apcode]['geometry'] = temp_storage
  3938. except Exception as e:
  3939. log.debug("AppGerberEditor.buffer() --> %s" % str(e))
  3940. self.app.inform.emit('[ERROR_NOTCL] %s\n%s' % (_("Failed."), str(traceback.print_exc())))
  3941. return
  3942. self.plot_all()
  3943. self.app.inform.emit('[success] %s' % _("Done."))
  3944. def on_scale(self):
  3945. scale_factor = 1.0
  3946. log.debug("AppGerberEditor.on_scale()")
  3947. try:
  3948. scale_factor = float(self.ui.scale_factor_entry.get_value())
  3949. except ValueError:
  3950. # try to convert comma to decimal point. if it's still not working error message and return
  3951. try:
  3952. scale_factor = float(self.ui.scale_factor_entry.get_value().replace(',', '.'))
  3953. self.ui.scale_factor_entry.set_value(scale_factor)
  3954. except ValueError:
  3955. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3956. _("Scale factor value is missing or wrong format. Add it and retry."))
  3957. return
  3958. def scale_recursion(geom_el, selection):
  3959. if type(geom_el) == list:
  3960. geoms = []
  3961. for local_geom in geom_el:
  3962. geoms.append(scale_recursion(local_geom, selection=selection))
  3963. return geoms
  3964. else:
  3965. if geom_el in selection:
  3966. geometric_data = geom_el.geo
  3967. scaled_geom_el = {}
  3968. if 'solid' in geometric_data:
  3969. scaled_geom_el['solid'] = affinity.scale(
  3970. geometric_data['solid'], scale_factor, scale_factor, origin='center'
  3971. )
  3972. if 'follow' in geometric_data:
  3973. scaled_geom_el['follow'] = affinity.scale(
  3974. geometric_data['follow'], scale_factor, scale_factor, origin='center'
  3975. )
  3976. if 'clear' in geometric_data:
  3977. scaled_geom_el['clear'] = affinity.scale(
  3978. geometric_data['clear'], scale_factor, scale_factor, origin='center'
  3979. )
  3980. return DrawToolShape(scaled_geom_el)
  3981. else:
  3982. return geom_el
  3983. if not self.ui.apertures_table.selectedItems():
  3984. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3985. _("No aperture to scale. Select at least one aperture and try again."))
  3986. return
  3987. for x in self.ui.apertures_table.selectedItems():
  3988. try:
  3989. apcode = self.ui.apertures_table.item(x.row(), 1).text()
  3990. temp_storage = deepcopy(scale_recursion(self.storage_dict[apcode]['geometry'], self.selected))
  3991. self.storage_dict[apcode]['geometry'] = []
  3992. self.storage_dict[apcode]['geometry'] = temp_storage
  3993. except Exception as e:
  3994. log.debug("AppGerberEditor.on_scale() --> %s" % str(e))
  3995. self.plot_all()
  3996. self.app.inform.emit('[success] %s' % _("Done."))
  3997. def on_markarea(self):
  3998. # clear previous marking
  3999. self.ma_annotation.clear(update=True)
  4000. self.units = self.app.defaults['units'].upper()
  4001. text = []
  4002. position = []
  4003. for apcode in self.storage_dict:
  4004. if 'geometry' in self.storage_dict[apcode]:
  4005. for geo_el in self.storage_dict[apcode]['geometry']:
  4006. if 'solid' in geo_el.geo:
  4007. area = geo_el.geo['solid'].area
  4008. try:
  4009. upper_threshold_val = self.ui.ma_upper_threshold_entry.get_value()
  4010. except Exception:
  4011. return
  4012. try:
  4013. lower_threshold_val = self.ui.ma_lower_threshold_entry.get_value()
  4014. except Exception:
  4015. lower_threshold_val = 0.0
  4016. if float(upper_threshold_val) > area > float(lower_threshold_val):
  4017. current_pos = geo_el.geo['solid'].exterior.coords[-1]
  4018. text_elem = '%.*f' % (self.decimals, area)
  4019. text.append(text_elem)
  4020. position.append(current_pos)
  4021. self.geo_to_delete.append(geo_el)
  4022. if text:
  4023. self.ma_annotation.set(text=text, pos=position, visible=True,
  4024. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4025. color='#000000FF')
  4026. self.app.inform.emit('[success] %s' %
  4027. _("Polygons marked."))
  4028. else:
  4029. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4030. _("No polygons were marked. None fit within the limits."))
  4031. def delete_marked_polygons(self):
  4032. for shape_sel in self.geo_to_delete:
  4033. self.delete_shape(shape_sel)
  4034. self.build_ui()
  4035. self.plot_all()
  4036. self.app.inform.emit('[success] %s' % _("Done."))
  4037. def on_eraser(self):
  4038. self.select_tool('eraser')
  4039. def on_transform(self):
  4040. if type(self.active_tool) == FCTransform:
  4041. self.select_tool('select')
  4042. else:
  4043. self.select_tool('transform')
  4044. def hide_tool(self, tool_name):
  4045. # self.app.ui.notebook.setTabText(2, _("Tools"))
  4046. try:
  4047. if tool_name == 'all':
  4048. self.ui.apertures_frame.hide()
  4049. if tool_name == 'select':
  4050. self.ui.apertures_frame.show()
  4051. if tool_name == 'buffer' or tool_name == 'all':
  4052. self.ui.buffer_tool_frame.hide()
  4053. if tool_name == 'scale' or tool_name == 'all':
  4054. self.ui.scale_tool_frame.hide()
  4055. if tool_name == 'markarea' or tool_name == 'all':
  4056. self.ui.ma_tool_frame.hide()
  4057. except Exception as e:
  4058. log.debug("AppGerberEditor.hide_tool() --> %s" % str(e))
  4059. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  4060. class AppGerberEditorUI:
  4061. def __init__(self, app):
  4062. self.app = app
  4063. # Number of decimals used by tools in this class
  4064. self.decimals = self.app.decimals
  4065. # ## Current application units in Upper Case
  4066. self.units = self.app.defaults['units'].upper()
  4067. self.grb_edit_widget = QtWidgets.QWidget()
  4068. layout = QtWidgets.QVBoxLayout()
  4069. self.grb_edit_widget.setLayout(layout)
  4070. # Page Title box (spacing between children)
  4071. self.title_box = QtWidgets.QHBoxLayout()
  4072. layout.addLayout(self.title_box)
  4073. # Page Title icon
  4074. pixmap = QtGui.QPixmap(self.app.resource_location + '/flatcam_icon32.png')
  4075. self.icon = QtWidgets.QLabel()
  4076. self.icon.setPixmap(pixmap)
  4077. self.title_box.addWidget(self.icon, stretch=0)
  4078. # Title label
  4079. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Gerber Editor'))
  4080. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  4081. self.title_box.addWidget(self.title_label, stretch=1)
  4082. # Object name
  4083. self.name_box = QtWidgets.QHBoxLayout()
  4084. layout.addLayout(self.name_box)
  4085. name_label = QtWidgets.QLabel(_("Name:"))
  4086. self.name_box.addWidget(name_label)
  4087. self.name_entry = FCEntry()
  4088. self.name_box.addWidget(self.name_entry)
  4089. # Box for custom widgets
  4090. # This gets populated in offspring implementations.
  4091. self.custom_box = QtWidgets.QVBoxLayout()
  4092. layout.addLayout(self.custom_box)
  4093. # #########################
  4094. # ### Gerber Apertures ####
  4095. # #########################
  4096. self.apertures_table_label = QtWidgets.QLabel('<b>%s:</b>' % _('Apertures'))
  4097. self.apertures_table_label.setToolTip(
  4098. _("Apertures Table for the Gerber Object.")
  4099. )
  4100. self.custom_box.addWidget(self.apertures_table_label)
  4101. self.apertures_table = FCTable()
  4102. # delegate = SpinBoxDelegate(units=self.units)
  4103. # self.apertures_table.setItemDelegateForColumn(1, delegate)
  4104. self.custom_box.addWidget(self.apertures_table)
  4105. self.apertures_table.setColumnCount(5)
  4106. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  4107. self.apertures_table.setSortingEnabled(False)
  4108. self.apertures_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  4109. self.apertures_table.horizontalHeaderItem(0).setToolTip(
  4110. _("Index"))
  4111. self.apertures_table.horizontalHeaderItem(1).setToolTip(
  4112. _("Aperture Code"))
  4113. self.apertures_table.horizontalHeaderItem(2).setToolTip(
  4114. _("Type of aperture: circular, rectangle, macros etc"))
  4115. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  4116. _("Aperture Size:"))
  4117. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  4118. _("Aperture Dimensions:\n"
  4119. " - (width, height) for R, O type.\n"
  4120. " - (dia, nVertices) for P type"))
  4121. self.empty_label = QtWidgets.QLabel('')
  4122. self.custom_box.addWidget(self.empty_label)
  4123. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Apertures widgets
  4124. # this way I can hide/show the frame
  4125. self.apertures_frame = QtWidgets.QFrame()
  4126. self.apertures_frame.setContentsMargins(0, 0, 0, 0)
  4127. self.custom_box.addWidget(self.apertures_frame)
  4128. self.apertures_box = QtWidgets.QVBoxLayout()
  4129. self.apertures_box.setContentsMargins(0, 0, 0, 0)
  4130. self.apertures_frame.setLayout(self.apertures_box)
  4131. # # ## Add/Delete an new Aperture ## ##
  4132. grid1 = QtWidgets.QGridLayout()
  4133. self.apertures_box.addLayout(grid1)
  4134. grid1.setColumnStretch(0, 0)
  4135. grid1.setColumnStretch(1, 1)
  4136. apcode_lbl = QtWidgets.QLabel('%s:' % _('Aperture Code'))
  4137. apcode_lbl.setToolTip(_("Code for the new aperture"))
  4138. grid1.addWidget(apcode_lbl, 1, 0)
  4139. self.apcode_entry = FCSpinner()
  4140. self.apcode_entry.set_range(0, 999)
  4141. self.apcode_entry.setWrapping(True)
  4142. grid1.addWidget(self.apcode_entry, 1, 1)
  4143. apsize_lbl = QtWidgets.QLabel('%s' % _('Aperture Size:'))
  4144. apsize_lbl.setToolTip(
  4145. _("Size for the new aperture.\n"
  4146. "If aperture type is 'R' or 'O' then\n"
  4147. "this value is automatically\n"
  4148. "calculated as:\n"
  4149. "sqrt(width**2 + height**2)")
  4150. )
  4151. grid1.addWidget(apsize_lbl, 2, 0)
  4152. self.apsize_entry = FCDoubleSpinner()
  4153. self.apsize_entry.set_precision(self.decimals)
  4154. self.apsize_entry.set_range(0.0, 9999)
  4155. grid1.addWidget(self.apsize_entry, 2, 1)
  4156. aptype_lbl = QtWidgets.QLabel('%s:' % _('Aperture Type'))
  4157. aptype_lbl.setToolTip(
  4158. _("Select the type of new aperture. Can be:\n"
  4159. "C = circular\n"
  4160. "R = rectangular\n"
  4161. "O = oblong")
  4162. )
  4163. grid1.addWidget(aptype_lbl, 3, 0)
  4164. self.aptype_cb = FCComboBox()
  4165. self.aptype_cb.addItems(['C', 'R', 'O'])
  4166. grid1.addWidget(self.aptype_cb, 3, 1)
  4167. self.apdim_lbl = QtWidgets.QLabel('%s:' % _('Aperture Dim'))
  4168. self.apdim_lbl.setToolTip(
  4169. _("Dimensions for the new aperture.\n"
  4170. "Active only for rectangular apertures (type R).\n"
  4171. "The format is (width, height)")
  4172. )
  4173. grid1.addWidget(self.apdim_lbl, 4, 0)
  4174. self.apdim_entry = EvalEntry2()
  4175. grid1.addWidget(self.apdim_entry, 4, 1)
  4176. apadd_del_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Add/Delete Aperture'))
  4177. apadd_del_lbl.setToolTip(
  4178. _("Add/Delete an aperture in the aperture table")
  4179. )
  4180. self.apertures_box.addWidget(apadd_del_lbl)
  4181. hlay_ad = QtWidgets.QHBoxLayout()
  4182. self.apertures_box.addLayout(hlay_ad)
  4183. self.addaperture_btn = QtWidgets.QPushButton(_('Add'))
  4184. self.addaperture_btn.setToolTip(
  4185. _("Add a new aperture to the aperture list.")
  4186. )
  4187. self.delaperture_btn = QtWidgets.QPushButton(_('Delete'))
  4188. self.delaperture_btn.setToolTip(
  4189. _("Delete a aperture in the aperture list")
  4190. )
  4191. hlay_ad.addWidget(self.addaperture_btn)
  4192. hlay_ad.addWidget(self.delaperture_btn)
  4193. # ###################
  4194. # ### BUFFER TOOL ###
  4195. # ###################
  4196. self.buffer_tool_frame = QtWidgets.QFrame()
  4197. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  4198. self.custom_box.addWidget(self.buffer_tool_frame)
  4199. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  4200. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  4201. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  4202. self.buffer_tool_frame.hide()
  4203. # Title
  4204. buf_title_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Buffer Aperture'))
  4205. buf_title_lbl.setToolTip(
  4206. _("Buffer a aperture in the aperture list")
  4207. )
  4208. self.buffer_tools_box.addWidget(buf_title_lbl)
  4209. # Form Layout
  4210. buf_form_layout = QtWidgets.QFormLayout()
  4211. self.buffer_tools_box.addLayout(buf_form_layout)
  4212. # Buffer distance
  4213. self.buffer_distance_entry = FCDoubleSpinner()
  4214. self.buffer_distance_entry.set_precision(self.decimals)
  4215. self.buffer_distance_entry.set_range(-10000.0000, 10000.0000)
  4216. buf_form_layout.addRow('%s:' % _("Buffer distance"), self.buffer_distance_entry)
  4217. self.buffer_corner_lbl = QtWidgets.QLabel('%s:' % _("Buffer corner"))
  4218. self.buffer_corner_lbl.setToolTip(
  4219. _("There are 3 types of corners:\n"
  4220. " - 'Round': the corner is rounded.\n"
  4221. " - 'Square': the corner is met in a sharp angle.\n"
  4222. " - 'Beveled': the corner is a line that directly connects the features meeting in the corner")
  4223. )
  4224. self.buffer_corner_cb = FCComboBox()
  4225. self.buffer_corner_cb.addItem(_("Round"))
  4226. self.buffer_corner_cb.addItem(_("Square"))
  4227. self.buffer_corner_cb.addItem(_("Beveled"))
  4228. buf_form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  4229. # Buttons
  4230. hlay_buf = QtWidgets.QHBoxLayout()
  4231. self.buffer_tools_box.addLayout(hlay_buf)
  4232. self.buffer_button = QtWidgets.QPushButton(_("Buffer"))
  4233. hlay_buf.addWidget(self.buffer_button)
  4234. # ##################
  4235. # ### SCALE TOOL ###
  4236. # ##################
  4237. self.scale_tool_frame = QtWidgets.QFrame()
  4238. self.scale_tool_frame.setContentsMargins(0, 0, 0, 0)
  4239. self.custom_box.addWidget(self.scale_tool_frame)
  4240. self.scale_tools_box = QtWidgets.QVBoxLayout()
  4241. self.scale_tools_box.setContentsMargins(0, 0, 0, 0)
  4242. self.scale_tool_frame.setLayout(self.scale_tools_box)
  4243. self.scale_tool_frame.hide()
  4244. # Title
  4245. scale_title_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Scale Aperture'))
  4246. scale_title_lbl.setToolTip(
  4247. _("Scale a aperture in the aperture list")
  4248. )
  4249. self.scale_tools_box.addWidget(scale_title_lbl)
  4250. # Form Layout
  4251. scale_form_layout = QtWidgets.QFormLayout()
  4252. self.scale_tools_box.addLayout(scale_form_layout)
  4253. self.scale_factor_lbl = QtWidgets.QLabel('%s:' % _("Scale factor"))
  4254. self.scale_factor_lbl.setToolTip(
  4255. _("The factor by which to scale the selected aperture.\n"
  4256. "Values can be between 0.0000 and 999.9999")
  4257. )
  4258. self.scale_factor_entry = FCDoubleSpinner()
  4259. self.scale_factor_entry.set_precision(self.decimals)
  4260. self.scale_factor_entry.set_range(0.0000, 10000.0000)
  4261. scale_form_layout.addRow(self.scale_factor_lbl, self.scale_factor_entry)
  4262. # Buttons
  4263. hlay_scale = QtWidgets.QHBoxLayout()
  4264. self.scale_tools_box.addLayout(hlay_scale)
  4265. self.scale_button = QtWidgets.QPushButton(_("Scale"))
  4266. hlay_scale.addWidget(self.scale_button)
  4267. # ######################
  4268. # ### Mark Area TOOL ###
  4269. # ######################
  4270. self.ma_tool_frame = QtWidgets.QFrame()
  4271. self.ma_tool_frame.setContentsMargins(0, 0, 0, 0)
  4272. self.custom_box.addWidget(self.ma_tool_frame)
  4273. self.ma_tools_box = QtWidgets.QVBoxLayout()
  4274. self.ma_tools_box.setContentsMargins(0, 0, 0, 0)
  4275. self.ma_tool_frame.setLayout(self.ma_tools_box)
  4276. self.ma_tool_frame.hide()
  4277. # Title
  4278. ma_title_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Mark polygons'))
  4279. ma_title_lbl.setToolTip(
  4280. _("Mark the polygon areas.")
  4281. )
  4282. self.ma_tools_box.addWidget(ma_title_lbl)
  4283. # Form Layout
  4284. ma_form_layout = QtWidgets.QFormLayout()
  4285. self.ma_tools_box.addLayout(ma_form_layout)
  4286. self.ma_upper_threshold_lbl = QtWidgets.QLabel('%s:' % _("Area UPPER threshold"))
  4287. self.ma_upper_threshold_lbl.setToolTip(
  4288. _("The threshold value, all areas less than this are marked.\n"
  4289. "Can have a value between 0.0000 and 10000.0000")
  4290. )
  4291. self.ma_upper_threshold_entry = FCDoubleSpinner()
  4292. self.ma_upper_threshold_entry.set_precision(self.decimals)
  4293. self.ma_upper_threshold_entry.set_range(0, 10000)
  4294. self.ma_lower_threshold_lbl = QtWidgets.QLabel('%s:' % _("Area LOWER threshold"))
  4295. self.ma_lower_threshold_lbl.setToolTip(
  4296. _("The threshold value, all areas more than this are marked.\n"
  4297. "Can have a value between 0.0000 and 10000.0000")
  4298. )
  4299. self.ma_lower_threshold_entry = FCDoubleSpinner()
  4300. self.ma_lower_threshold_entry.set_precision(self.decimals)
  4301. self.ma_lower_threshold_entry.set_range(0, 10000)
  4302. ma_form_layout.addRow(self.ma_lower_threshold_lbl, self.ma_lower_threshold_entry)
  4303. ma_form_layout.addRow(self.ma_upper_threshold_lbl, self.ma_upper_threshold_entry)
  4304. # Buttons
  4305. hlay_ma = QtWidgets.QHBoxLayout()
  4306. self.ma_tools_box.addLayout(hlay_ma)
  4307. self.ma_threshold_button = QtWidgets.QPushButton(_("Mark"))
  4308. self.ma_threshold_button.setToolTip(
  4309. _("Mark the polygons that fit within limits.")
  4310. )
  4311. hlay_ma.addWidget(self.ma_threshold_button)
  4312. self.ma_delete_button = QtWidgets.QPushButton(_("Delete"))
  4313. self.ma_delete_button.setToolTip(
  4314. _("Delete all the marked polygons.")
  4315. )
  4316. hlay_ma.addWidget(self.ma_delete_button)
  4317. self.ma_clear_button = QtWidgets.QPushButton(_("Clear"))
  4318. self.ma_clear_button.setToolTip(
  4319. _("Clear all the markings.")
  4320. )
  4321. hlay_ma.addWidget(self.ma_clear_button)
  4322. # ######################
  4323. # ### Add Pad Array ####
  4324. # ######################
  4325. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  4326. # all the add Pad array widgets
  4327. # this way I can hide/show the frame
  4328. self.array_frame = QtWidgets.QFrame()
  4329. self.array_frame.setContentsMargins(0, 0, 0, 0)
  4330. self.custom_box.addWidget(self.array_frame)
  4331. self.array_box = QtWidgets.QVBoxLayout()
  4332. self.array_box.setContentsMargins(0, 0, 0, 0)
  4333. self.array_frame.setLayout(self.array_box)
  4334. self.emptyarray_label = QtWidgets.QLabel('')
  4335. self.array_box.addWidget(self.emptyarray_label)
  4336. self.padarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Pad Array"))
  4337. self.padarray_label.setToolTip(
  4338. _("Add an array of pads (linear or circular array)")
  4339. )
  4340. self.array_box.addWidget(self.padarray_label)
  4341. self.array_type_combo = FCComboBox2()
  4342. self.array_type_combo.setToolTip(
  4343. _("Select the type of pads array to create.\n"
  4344. "It can be Linear X(Y) or Circular")
  4345. )
  4346. self.array_type_combo.addItem(_("Linear"))
  4347. self.array_type_combo.addItem(_("Circular"))
  4348. self.array_box.addWidget(self.array_type_combo)
  4349. self.array_form = QtWidgets.QFormLayout()
  4350. self.array_box.addLayout(self.array_form)
  4351. self.pad_array_size_label = QtWidgets.QLabel('%s:' % _('Nr of pads'))
  4352. self.pad_array_size_label.setToolTip(
  4353. _("Specify how many pads to be in the array.")
  4354. )
  4355. self.pad_array_size_label.setMinimumWidth(100)
  4356. self.pad_array_size_entry = FCSpinner()
  4357. self.pad_array_size_entry.set_range(1, 9999)
  4358. self.array_form.addRow(self.pad_array_size_label, self.pad_array_size_entry)
  4359. self.array_linear_frame = QtWidgets.QFrame()
  4360. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  4361. self.array_box.addWidget(self.array_linear_frame)
  4362. self.linear_box = QtWidgets.QVBoxLayout()
  4363. self.linear_box.setContentsMargins(0, 0, 0, 0)
  4364. self.array_linear_frame.setLayout(self.linear_box)
  4365. self.linear_form = QtWidgets.QFormLayout()
  4366. self.linear_box.addLayout(self.linear_form)
  4367. self.pad_axis_label = QtWidgets.QLabel('%s:' % _('Direction'))
  4368. self.pad_axis_label.setToolTip(
  4369. _("Direction on which the linear array is oriented:\n"
  4370. "- 'X' - horizontal axis \n"
  4371. "- 'Y' - vertical axis or \n"
  4372. "- 'Angle' - a custom angle for the array inclination")
  4373. )
  4374. self.pad_axis_label.setMinimumWidth(100)
  4375. self.pad_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  4376. {'label': _('Y'), 'value': 'Y'},
  4377. {'label': _('Angle'), 'value': 'A'}])
  4378. self.pad_axis_radio.set_value('X')
  4379. self.linear_form.addRow(self.pad_axis_label, self.pad_axis_radio)
  4380. self.pad_pitch_label = QtWidgets.QLabel('%s:' % _('Pitch'))
  4381. self.pad_pitch_label.setToolTip(
  4382. _("Pitch = Distance between elements of the array.")
  4383. )
  4384. self.pad_pitch_label.setMinimumWidth(100)
  4385. self.pad_pitch_entry = FCDoubleSpinner()
  4386. self.pad_pitch_entry.set_precision(self.decimals)
  4387. self.pad_pitch_entry.set_range(0.0000, 10000.0000)
  4388. self.pad_pitch_entry.setSingleStep(0.1)
  4389. self.linear_form.addRow(self.pad_pitch_label, self.pad_pitch_entry)
  4390. self.linear_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  4391. self.linear_angle_label.setToolTip(
  4392. _("Angle at which the linear array is placed.\n"
  4393. "The precision is of max 2 decimals.\n"
  4394. "Min value is: -360.00 degrees.\n"
  4395. "Max value is: 360.00 degrees.")
  4396. )
  4397. self.linear_angle_label.setMinimumWidth(100)
  4398. self.linear_angle_spinner = FCDoubleSpinner()
  4399. self.linear_angle_spinner.set_precision(self.decimals)
  4400. self.linear_angle_spinner.setRange(-360.00, 360.00)
  4401. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  4402. self.array_circular_frame = QtWidgets.QFrame()
  4403. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  4404. self.array_box.addWidget(self.array_circular_frame)
  4405. self.circular_box = QtWidgets.QVBoxLayout()
  4406. self.circular_box.setContentsMargins(0, 0, 0, 0)
  4407. self.array_circular_frame.setLayout(self.circular_box)
  4408. self.pad_direction_label = QtWidgets.QLabel('%s:' % _('Direction'))
  4409. self.pad_direction_label.setToolTip(
  4410. _("Direction for circular array.\n"
  4411. "Can be CW = clockwise or CCW = counter clockwise.")
  4412. )
  4413. self.pad_direction_label.setMinimumWidth(100)
  4414. self.circular_form = QtWidgets.QFormLayout()
  4415. self.circular_box.addLayout(self.circular_form)
  4416. self.pad_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  4417. {'label': _('CCW'), 'value': 'CCW'}])
  4418. self.pad_direction_radio.set_value('CW')
  4419. self.circular_form.addRow(self.pad_direction_label, self.pad_direction_radio)
  4420. self.pad_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  4421. self.pad_angle_label.setToolTip(
  4422. _("Angle at which each element in circular array is placed.")
  4423. )
  4424. self.pad_angle_label.setMinimumWidth(100)
  4425. self.pad_angle_entry = FCDoubleSpinner()
  4426. self.pad_angle_entry.set_precision(self.decimals)
  4427. self.pad_angle_entry.set_range(-360.00, 360.00)
  4428. self.pad_angle_entry.setSingleStep(0.1)
  4429. self.circular_form.addRow(self.pad_angle_label, self.pad_angle_entry)
  4430. self.array_circular_frame.hide()
  4431. self.linear_angle_spinner.hide()
  4432. self.linear_angle_label.hide()
  4433. self.array_frame.hide()
  4434. self.custom_box.addStretch()
  4435. layout.addStretch()
  4436. # Editor
  4437. self.exit_editor_button = QtWidgets.QPushButton(_('Exit Editor'))
  4438. self.exit_editor_button.setIcon(QtGui.QIcon(self.app.resource_location + '/power16.png'))
  4439. self.exit_editor_button.setToolTip(
  4440. _("Exit from Editor.")
  4441. )
  4442. self.exit_editor_button.setStyleSheet("""
  4443. QPushButton
  4444. {
  4445. font-weight: bold;
  4446. }
  4447. """)
  4448. layout.addWidget(self.exit_editor_button)
  4449. class TransformEditorTool(AppTool):
  4450. """
  4451. Inputs to specify how to paint the selected polygons.
  4452. """
  4453. toolName = _("Transform Tool")
  4454. rotateName = _("Rotate")
  4455. skewName = _("Skew/Shear")
  4456. scaleName = _("Scale")
  4457. flipName = _("Mirror (Flip)")
  4458. offsetName = _("Offset")
  4459. bufferName = _("Buffer")
  4460. def __init__(self, app, draw_app):
  4461. AppTool.__init__(self, app)
  4462. self.app = app
  4463. self.draw_app = draw_app
  4464. self.decimals = self.app.decimals
  4465. # ## Title
  4466. title_label = QtWidgets.QLabel("%s" % self.toolName)
  4467. title_label.setStyleSheet("""
  4468. QLabel
  4469. {
  4470. font-size: 16px;
  4471. font-weight: bold;
  4472. }
  4473. """)
  4474. self.layout.addWidget(title_label)
  4475. self.layout.addWidget(QtWidgets.QLabel(''))
  4476. # ## Layout
  4477. grid0 = QtWidgets.QGridLayout()
  4478. self.layout.addLayout(grid0)
  4479. grid0.setColumnStretch(0, 0)
  4480. grid0.setColumnStretch(1, 1)
  4481. grid0.setColumnStretch(2, 0)
  4482. grid0.addWidget(QtWidgets.QLabel(''))
  4483. # Reference
  4484. ref_label = QtWidgets.QLabel('%s:' % _("Reference"))
  4485. ref_label.setToolTip(
  4486. _("The reference point for Rotate, Skew, Scale, Mirror.\n"
  4487. "Can be:\n"
  4488. "- Origin -> it is the 0, 0 point\n"
  4489. "- Selection -> the center of the bounding box of the selected objects\n"
  4490. "- Point -> a custom point defined by X,Y coordinates\n"
  4491. "- Min Selection -> the point (minx, miny) of the bounding box of the selection")
  4492. )
  4493. self.ref_combo = FCComboBox()
  4494. self.ref_items = [_("Origin"), _("Selection"), _("Point"), _("Minimum")]
  4495. self.ref_combo.addItems(self.ref_items)
  4496. grid0.addWidget(ref_label, 0, 0)
  4497. grid0.addWidget(self.ref_combo, 0, 1, 1, 2)
  4498. self.point_label = QtWidgets.QLabel('%s:' % _("Value"))
  4499. self.point_label.setToolTip(
  4500. _("A point of reference in format X,Y.")
  4501. )
  4502. self.point_entry = NumericalEvalTupleEntry()
  4503. grid0.addWidget(self.point_label, 1, 0)
  4504. grid0.addWidget(self.point_entry, 1, 1, 1, 2)
  4505. self.point_button = FCButton(_("Add"))
  4506. self.point_button.setToolTip(
  4507. _("Add point coordinates from clipboard.")
  4508. )
  4509. grid0.addWidget(self.point_button, 2, 0, 1, 3)
  4510. separator_line = QtWidgets.QFrame()
  4511. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4512. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4513. grid0.addWidget(separator_line, 5, 0, 1, 3)
  4514. # ## Rotate Title
  4515. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  4516. grid0.addWidget(rotate_title_label, 6, 0, 1, 3)
  4517. self.rotate_label = QtWidgets.QLabel('%s:' % _("Angle"))
  4518. self.rotate_label.setToolTip(
  4519. _("Angle, in degrees.\n"
  4520. "Float number between -360 and 359.\n"
  4521. "Positive numbers for CW motion.\n"
  4522. "Negative numbers for CCW motion.")
  4523. )
  4524. self.rotate_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4525. self.rotate_entry.set_precision(self.decimals)
  4526. self.rotate_entry.setSingleStep(45)
  4527. self.rotate_entry.setWrapping(True)
  4528. self.rotate_entry.set_range(-360, 360)
  4529. # self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4530. self.rotate_button = FCButton(_("Rotate"))
  4531. self.rotate_button.setToolTip(
  4532. _("Rotate the selected object(s).\n"
  4533. "The point of reference is the middle of\n"
  4534. "the bounding box for all selected objects.")
  4535. )
  4536. self.rotate_button.setMinimumWidth(90)
  4537. grid0.addWidget(self.rotate_label, 7, 0)
  4538. grid0.addWidget(self.rotate_entry, 7, 1)
  4539. grid0.addWidget(self.rotate_button, 7, 2)
  4540. separator_line = QtWidgets.QFrame()
  4541. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4542. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4543. grid0.addWidget(separator_line, 8, 0, 1, 3)
  4544. # ## Skew Title
  4545. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  4546. grid0.addWidget(skew_title_label, 9, 0, 1, 2)
  4547. self.skew_link_cb = FCCheckBox()
  4548. self.skew_link_cb.setText(_("Link"))
  4549. self.skew_link_cb.setToolTip(
  4550. _("Link the Y entry to X entry and copy its content.")
  4551. )
  4552. grid0.addWidget(self.skew_link_cb, 9, 2)
  4553. self.skewx_label = QtWidgets.QLabel('%s:' % _("X angle"))
  4554. self.skewx_label.setToolTip(
  4555. _("Angle for Skew action, in degrees.\n"
  4556. "Float number between -360 and 360.")
  4557. )
  4558. self.skewx_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4559. # self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4560. self.skewx_entry.set_precision(self.decimals)
  4561. self.skewx_entry.set_range(-360, 360)
  4562. self.skewx_button = FCButton(_("Skew X"))
  4563. self.skewx_button.setToolTip(
  4564. _("Skew/shear the selected object(s).\n"
  4565. "The point of reference is the middle of\n"
  4566. "the bounding box for all selected objects."))
  4567. self.skewx_button.setMinimumWidth(90)
  4568. grid0.addWidget(self.skewx_label, 10, 0)
  4569. grid0.addWidget(self.skewx_entry, 10, 1)
  4570. grid0.addWidget(self.skewx_button, 10, 2)
  4571. self.skewy_label = QtWidgets.QLabel('%s:' % _("Y angle"))
  4572. self.skewy_label.setToolTip(
  4573. _("Angle for Skew action, in degrees.\n"
  4574. "Float number between -360 and 360.")
  4575. )
  4576. self.skewy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4577. # self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4578. self.skewy_entry.set_precision(self.decimals)
  4579. self.skewy_entry.set_range(-360, 360)
  4580. self.skewy_button = FCButton(_("Skew Y"))
  4581. self.skewy_button.setToolTip(
  4582. _("Skew/shear the selected object(s).\n"
  4583. "The point of reference is the middle of\n"
  4584. "the bounding box for all selected objects."))
  4585. self.skewy_button.setMinimumWidth(90)
  4586. grid0.addWidget(self.skewy_label, 12, 0)
  4587. grid0.addWidget(self.skewy_entry, 12, 1)
  4588. grid0.addWidget(self.skewy_button, 12, 2)
  4589. self.ois_sk = OptionalInputSection(self.skew_link_cb, [self.skewy_label, self.skewy_entry, self.skewy_button],
  4590. logic=False)
  4591. separator_line = QtWidgets.QFrame()
  4592. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4593. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4594. grid0.addWidget(separator_line, 14, 0, 1, 3)
  4595. # ## Scale Title
  4596. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  4597. grid0.addWidget(scale_title_label, 15, 0, 1, 2)
  4598. self.scale_link_cb = FCCheckBox()
  4599. self.scale_link_cb.setText(_("Link"))
  4600. self.scale_link_cb.setToolTip(
  4601. _("Link the Y entry to X entry and copy its content.")
  4602. )
  4603. grid0.addWidget(self.scale_link_cb, 15, 2)
  4604. self.scalex_label = QtWidgets.QLabel('%s:' % _("X factor"))
  4605. self.scalex_label.setToolTip(
  4606. _("Factor for scaling on X axis.")
  4607. )
  4608. self.scalex_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4609. # self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4610. self.scalex_entry.set_precision(self.decimals)
  4611. self.scalex_entry.setMinimum(-1e6)
  4612. self.scalex_button = FCButton(_("Scale X"))
  4613. self.scalex_button.setToolTip(
  4614. _("Scale the selected object(s).\n"
  4615. "The point of reference depends on \n"
  4616. "the Scale reference checkbox state."))
  4617. self.scalex_button.setMinimumWidth(90)
  4618. grid0.addWidget(self.scalex_label, 17, 0)
  4619. grid0.addWidget(self.scalex_entry, 17, 1)
  4620. grid0.addWidget(self.scalex_button, 17, 2)
  4621. self.scaley_label = QtWidgets.QLabel('%s:' % _("Y factor"))
  4622. self.scaley_label.setToolTip(
  4623. _("Factor for scaling on Y axis.")
  4624. )
  4625. self.scaley_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4626. # self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4627. self.scaley_entry.set_precision(self.decimals)
  4628. self.scaley_entry.setMinimum(-1e6)
  4629. self.scaley_button = FCButton(_("Scale Y"))
  4630. self.scaley_button.setToolTip(
  4631. _("Scale the selected object(s).\n"
  4632. "The point of reference depends on \n"
  4633. "the Scale reference checkbox state."))
  4634. self.scaley_button.setMinimumWidth(90)
  4635. grid0.addWidget(self.scaley_label, 19, 0)
  4636. grid0.addWidget(self.scaley_entry, 19, 1)
  4637. grid0.addWidget(self.scaley_button, 19, 2)
  4638. self.ois_s = OptionalInputSection(self.scale_link_cb,
  4639. [
  4640. self.scaley_label,
  4641. self.scaley_entry,
  4642. self.scaley_button
  4643. ], logic=False)
  4644. separator_line = QtWidgets.QFrame()
  4645. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4646. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4647. grid0.addWidget(separator_line, 21, 0, 1, 3)
  4648. # ## Flip Title
  4649. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  4650. grid0.addWidget(flip_title_label, 23, 0, 1, 3)
  4651. self.flipx_button = FCButton(_("Flip on X"))
  4652. self.flipx_button.setToolTip(
  4653. _("Flip the selected object(s) over the X axis.")
  4654. )
  4655. self.flipy_button = FCButton(_("Flip on Y"))
  4656. self.flipy_button.setToolTip(
  4657. _("Flip the selected object(s) over the X axis.")
  4658. )
  4659. hlay0 = QtWidgets.QHBoxLayout()
  4660. grid0.addLayout(hlay0, 25, 0, 1, 3)
  4661. hlay0.addWidget(self.flipx_button)
  4662. hlay0.addWidget(self.flipy_button)
  4663. separator_line = QtWidgets.QFrame()
  4664. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4665. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4666. grid0.addWidget(separator_line, 27, 0, 1, 3)
  4667. # ## Offset Title
  4668. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  4669. grid0.addWidget(offset_title_label, 29, 0, 1, 3)
  4670. self.offx_label = QtWidgets.QLabel('%s:' % _("X val"))
  4671. self.offx_label.setToolTip(
  4672. _("Distance to offset on X axis. In current units.")
  4673. )
  4674. self.offx_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4675. # self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4676. self.offx_entry.set_precision(self.decimals)
  4677. self.offx_entry.setMinimum(-1e6)
  4678. self.offx_button = FCButton(_("Offset X"))
  4679. self.offx_button.setToolTip(
  4680. _("Offset the selected object(s).\n"
  4681. "The point of reference is the middle of\n"
  4682. "the bounding box for all selected objects.\n"))
  4683. self.offx_button.setMinimumWidth(90)
  4684. grid0.addWidget(self.offx_label, 31, 0)
  4685. grid0.addWidget(self.offx_entry, 31, 1)
  4686. grid0.addWidget(self.offx_button, 31, 2)
  4687. self.offy_label = QtWidgets.QLabel('%s:' % _("Y val"))
  4688. self.offy_label.setToolTip(
  4689. _("Distance to offset on Y axis. In current units.")
  4690. )
  4691. self.offy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4692. # self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4693. self.offy_entry.set_precision(self.decimals)
  4694. self.offy_entry.setMinimum(-1e6)
  4695. self.offy_button = FCButton(_("Offset Y"))
  4696. self.offy_button.setToolTip(
  4697. _("Offset the selected object(s).\n"
  4698. "The point of reference is the middle of\n"
  4699. "the bounding box for all selected objects.\n"))
  4700. self.offy_button.setMinimumWidth(90)
  4701. grid0.addWidget(self.offy_label, 32, 0)
  4702. grid0.addWidget(self.offy_entry, 32, 1)
  4703. grid0.addWidget(self.offy_button, 32, 2)
  4704. separator_line = QtWidgets.QFrame()
  4705. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4706. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4707. grid0.addWidget(separator_line, 34, 0, 1, 3)
  4708. # ## Buffer Title
  4709. buffer_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.bufferName)
  4710. grid0.addWidget(buffer_title_label, 35, 0, 1, 2)
  4711. self.buffer_rounded_cb = FCCheckBox('%s' % _("Rounded"))
  4712. self.buffer_rounded_cb.setToolTip(
  4713. _("If checked then the buffer will surround the buffered shape,\n"
  4714. "every corner will be rounded.\n"
  4715. "If not checked then the buffer will follow the exact geometry\n"
  4716. "of the buffered shape.")
  4717. )
  4718. grid0.addWidget(self.buffer_rounded_cb, 35, 2)
  4719. self.buffer_label = QtWidgets.QLabel('%s:' % _("Distance"))
  4720. self.buffer_label.setToolTip(
  4721. _("A positive value will create the effect of dilation,\n"
  4722. "while a negative value will create the effect of erosion.\n"
  4723. "Each geometry element of the object will be increased\n"
  4724. "or decreased with the 'distance'.")
  4725. )
  4726. self.buffer_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4727. self.buffer_entry.set_precision(self.decimals)
  4728. self.buffer_entry.setSingleStep(0.1)
  4729. self.buffer_entry.setWrapping(True)
  4730. self.buffer_entry.set_range(-10000.0000, 10000.0000)
  4731. self.buffer_button = FCButton(_("Buffer D"))
  4732. self.buffer_button.setToolTip(
  4733. _("Create the buffer effect on each geometry,\n"
  4734. "element from the selected object, using the distance.")
  4735. )
  4736. self.buffer_button.setMinimumWidth(90)
  4737. grid0.addWidget(self.buffer_label, 37, 0)
  4738. grid0.addWidget(self.buffer_entry, 37, 1)
  4739. grid0.addWidget(self.buffer_button, 37, 2)
  4740. self.buffer_factor_label = QtWidgets.QLabel('%s:' % _("Value"))
  4741. self.buffer_factor_label.setToolTip(
  4742. _("A positive value will create the effect of dilation,\n"
  4743. "while a negative value will create the effect of erosion.\n"
  4744. "Each geometry element of the object will be increased\n"
  4745. "or decreased to fit the 'Value'. Value is a percentage\n"
  4746. "of the initial dimension.")
  4747. )
  4748. self.buffer_factor_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  4749. self.buffer_factor_entry.set_range(-100.0000, 1000.0000)
  4750. self.buffer_factor_entry.set_precision(self.decimals)
  4751. self.buffer_factor_entry.setWrapping(True)
  4752. self.buffer_factor_entry.setSingleStep(1)
  4753. self.buffer_factor_button = FCButton(_("Buffer F"))
  4754. self.buffer_factor_button.setToolTip(
  4755. _("Create the buffer effect on each geometry,\n"
  4756. "element from the selected object, using the factor.")
  4757. )
  4758. self.buffer_factor_button.setMinimumWidth(90)
  4759. grid0.addWidget(self.buffer_factor_label, 38, 0)
  4760. grid0.addWidget(self.buffer_factor_entry, 38, 1)
  4761. grid0.addWidget(self.buffer_factor_button, 38, 2)
  4762. grid0.addWidget(QtWidgets.QLabel(''), 42, 0, 1, 3)
  4763. self.layout.addStretch()
  4764. # Signals
  4765. self.ref_combo.currentIndexChanged.connect(self.on_reference_changed)
  4766. self.point_button.clicked.connect(self.on_add_coords)
  4767. self.rotate_button.clicked.connect(self.on_rotate)
  4768. self.skewx_button.clicked.connect(self.on_skewx)
  4769. self.skewy_button.clicked.connect(self.on_skewy)
  4770. self.scalex_button.clicked.connect(self.on_scalex)
  4771. self.scaley_button.clicked.connect(self.on_scaley)
  4772. self.offx_button.clicked.connect(self.on_offx)
  4773. self.offy_button.clicked.connect(self.on_offy)
  4774. self.flipx_button.clicked.connect(self.on_flipx)
  4775. self.flipy_button.clicked.connect(self.on_flipy)
  4776. self.buffer_button.clicked.connect(self.on_buffer_by_distance)
  4777. self.buffer_factor_button.clicked.connect(self.on_buffer_by_factor)
  4778. # self.rotate_entry.editingFinished.connect(self.on_rotate)
  4779. # self.skewx_entry.editingFinished.connect(self.on_skewx)
  4780. # self.skewy_entry.editingFinished.connect(self.on_skewy)
  4781. # self.scalex_entry.editingFinished.connect(self.on_scalex)
  4782. # self.scaley_entry.editingFinished.connect(self.on_scaley)
  4783. # self.offx_entry.editingFinished.connect(self.on_offx)
  4784. # self.offy_entry.editingFinished.connect(self.on_offy)
  4785. self.set_tool_ui()
  4786. def run(self, toggle=True):
  4787. self.app.defaults.report_usage("Gerber Editor Transform Tool()")
  4788. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4789. if self.app.ui.splitter.sizes()[0] == 0:
  4790. self.app.ui.splitter.setSizes([1, 1])
  4791. if toggle:
  4792. try:
  4793. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  4794. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  4795. else:
  4796. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  4797. except AttributeError:
  4798. pass
  4799. AppTool.run(self)
  4800. self.set_tool_ui()
  4801. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  4802. def install(self, icon=None, separator=None, **kwargs):
  4803. AppTool.install(self, icon, separator, shortcut='Alt+T', **kwargs)
  4804. def set_tool_ui(self):
  4805. # Initialize form
  4806. ref_val = self.app.defaults["tools_transform_reference"]
  4807. if ref_val == _("Object"):
  4808. ref_val = _("Selection")
  4809. self.ref_combo.set_value(ref_val)
  4810. self.point_entry.set_value(self.app.defaults["tools_transform_ref_point"])
  4811. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  4812. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  4813. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  4814. self.skew_link_cb.set_value(self.app.defaults["tools_transform_skew_link"])
  4815. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  4816. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  4817. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  4818. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  4819. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  4820. self.buffer_entry.set_value(self.app.defaults["tools_transform_buffer_dis"])
  4821. self.buffer_factor_entry.set_value(self.app.defaults["tools_transform_buffer_factor"])
  4822. self.buffer_rounded_cb.set_value(self.app.defaults["tools_transform_buffer_corner"])
  4823. # initial state is hidden
  4824. self.point_label.hide()
  4825. self.point_entry.hide()
  4826. self.point_button.hide()
  4827. def template(self):
  4828. if not self.draw_app.selected:
  4829. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s %s' % (_("Cancelled."), _("No shape selected.")))
  4830. return
  4831. self.draw_app.select_tool("select")
  4832. self.app.ui.notebook.setTabText(2, "Tools")
  4833. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  4834. self.app.ui.splitter.setSizes([0, 1])
  4835. def on_reference_changed(self, index):
  4836. if index == 0 or index == 1: # "Origin" or "Selection" reference
  4837. self.point_label.hide()
  4838. self.point_entry.hide()
  4839. self.point_button.hide()
  4840. elif index == 2: # "Point" reference
  4841. self.point_label.show()
  4842. self.point_entry.show()
  4843. self.point_button.show()
  4844. def on_calculate_reference(self, ref_index=None):
  4845. if ref_index:
  4846. ref_val = ref_index
  4847. else:
  4848. ref_val = self.ref_combo.currentIndex()
  4849. if ref_val == 0: # "Origin" reference
  4850. return 0, 0
  4851. elif ref_val == 1: # "Selection" reference
  4852. sel_list = self.draw_app.selected
  4853. if sel_list:
  4854. xmin, ymin, xmax, ymax = self.alt_bounds(sel_list)
  4855. px = (xmax + xmin) * 0.5
  4856. py = (ymax + ymin) * 0.5
  4857. return px, py
  4858. else:
  4859. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No shape selected."))
  4860. return "fail"
  4861. elif ref_val == 2: # "Point" reference
  4862. point_val = self.point_entry.get_value()
  4863. try:
  4864. px, py = eval('{}'.format(point_val))
  4865. return px, py
  4866. except Exception:
  4867. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Incorrect format for Point value. Needs format X,Y"))
  4868. return "fail"
  4869. else:
  4870. sel_list = self.draw_app.selected
  4871. if sel_list:
  4872. xmin, ymin, xmax, ymax = self.alt_bounds(sel_list)
  4873. if ref_val == 3:
  4874. return xmin, ymin # lower left corner
  4875. elif ref_val == 4:
  4876. return xmax, ymin # lower right corner
  4877. elif ref_val == 5:
  4878. return xmax, ymax # upper right corner
  4879. else:
  4880. return xmin, ymax # upper left corner
  4881. else:
  4882. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No shape selected."))
  4883. return "fail"
  4884. def on_add_coords(self):
  4885. val = self.app.clipboard.text()
  4886. self.point_entry.set_value(val)
  4887. def on_rotate(self, sig=None, val=None, ref=None):
  4888. value = float(self.rotate_entry.get_value()) if val is None else val
  4889. if value == 0:
  4890. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Rotate transformation can not be done for a value of 0."))
  4891. return
  4892. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4893. if point == 'fail':
  4894. return
  4895. self.app.worker_task.emit({'fcn': self.on_rotate_action, 'params': [value, point]})
  4896. def on_flipx(self, signal=None, ref=None):
  4897. axis = 'Y'
  4898. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4899. if point == 'fail':
  4900. return
  4901. self.app.worker_task.emit({'fcn': self.on_flip, 'params': [axis, point]})
  4902. def on_flipy(self, signal=None, ref=None):
  4903. axis = 'X'
  4904. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4905. if point == 'fail':
  4906. return
  4907. self.app.worker_task.emit({'fcn': self.on_flip, 'params': [axis, point]})
  4908. def on_skewx(self, signal=None, val=None, ref=None):
  4909. xvalue = float(self.skewx_entry.get_value()) if val is None else val
  4910. if xvalue == 0:
  4911. return
  4912. if self.skew_link_cb.get_value():
  4913. yvalue = xvalue
  4914. else:
  4915. yvalue = 0
  4916. axis = 'X'
  4917. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4918. if point == 'fail':
  4919. return
  4920. self.app.worker_task.emit({'fcn': self.on_skew, 'params': [axis, xvalue, yvalue, point]})
  4921. def on_skewy(self, signal=None, val=None, ref=None):
  4922. xvalue = 0
  4923. yvalue = float(self.skewy_entry.get_value()) if val is None else val
  4924. if yvalue == 0:
  4925. return
  4926. axis = 'Y'
  4927. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4928. if point == 'fail':
  4929. return
  4930. self.app.worker_task.emit({'fcn': self.on_skew, 'params': [axis, xvalue, yvalue, point]})
  4931. def on_scalex(self, signal=None, val=None, ref=None):
  4932. xvalue = float(self.scalex_entry.get_value()) if val is None else val
  4933. if xvalue == 0 or xvalue == 1:
  4934. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4935. _("Scale transformation can not be done for a factor of 0 or 1."))
  4936. return
  4937. if self.scale_link_cb.get_value():
  4938. yvalue = xvalue
  4939. else:
  4940. yvalue = 1
  4941. axis = 'X'
  4942. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4943. if point == 'fail':
  4944. return
  4945. self.app.worker_task.emit({'fcn': self.on_scale, 'params': [axis, xvalue, yvalue, point]})
  4946. def on_scaley(self, signal=None, val=None, ref=None):
  4947. xvalue = 1
  4948. yvalue = float(self.scaley_entry.get_value()) if val is None else val
  4949. if yvalue == 0 or yvalue == 1:
  4950. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4951. _("Scale transformation can not be done for a factor of 0 or 1."))
  4952. return
  4953. axis = 'Y'
  4954. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4955. if point == 'fail':
  4956. return
  4957. self.app.worker_task.emit({'fcn': self.on_scale, 'params': [axis, xvalue, yvalue, point]})
  4958. def on_offx(self, signal=None, val=None):
  4959. value = float(self.offx_entry.get_value()) if val is None else val
  4960. if value == 0:
  4961. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Offset transformation can not be done for a value of 0."))
  4962. return
  4963. axis = 'X'
  4964. self.app.worker_task.emit({'fcn': self.on_offset, 'params': [axis, value]})
  4965. def on_offy(self, signal=None, val=None):
  4966. value = float(self.offy_entry.get_value()) if val is None else val
  4967. if value == 0:
  4968. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Offset transformation can not be done for a value of 0."))
  4969. return
  4970. axis = 'Y'
  4971. self.app.worker_task.emit({'fcn': self.on_offset, 'params': [axis, value]})
  4972. def on_buffer_by_distance(self):
  4973. value = self.buffer_entry.get_value()
  4974. join = 1 if self.buffer_rounded_cb.get_value() else 2
  4975. self.app.worker_task.emit({'fcn': self.on_buffer_action, 'params': [value, join]})
  4976. def on_buffer_by_factor(self):
  4977. value = 1 + (self.buffer_factor_entry.get_value() / 100.0)
  4978. join = 1 if self.buffer_rounded_cb.get_value() else 2
  4979. # tell the buffer method to use the factor
  4980. factor = True
  4981. self.app.worker_task.emit({'fcn': self.on_buffer_action, 'params': [value, join, factor]})
  4982. def on_rotate_action(self, val, point):
  4983. """
  4984. Rotate geometry
  4985. :param val: Rotate with a known angle value, val
  4986. :param point: Reference point for rotation: tuple
  4987. :return:
  4988. """
  4989. elem_list = self.draw_app.selected
  4990. px, py = point
  4991. if not elem_list:
  4992. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  4993. return
  4994. with self.app.proc_container.new(_("Appying Rotate")):
  4995. try:
  4996. for sel_el_shape in elem_list:
  4997. sel_el = sel_el_shape.geo
  4998. if 'solid' in sel_el:
  4999. sel_el['solid'] = affinity.rotate(sel_el['solid'], angle=-val, origin=(px, py))
  5000. if 'follow' in sel_el:
  5001. sel_el['follow'] = affinity.rotate(sel_el['follow'], angle=-val, origin=(px, py))
  5002. if 'clear' in sel_el:
  5003. sel_el['clear'] = affinity.rotate(sel_el['clear'], angle=-val, origin=(px, py))
  5004. self.draw_app.plot_all()
  5005. self.app.inform.emit('[success] %s' % _("Done."))
  5006. except Exception as e:
  5007. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5008. return
  5009. def on_flip(self, axis, point):
  5010. """
  5011. Mirror (flip) geometry
  5012. :param axis: Mirror on a known axis given by the axis parameter
  5013. :param point: Mirror reference point
  5014. :return:
  5015. """
  5016. elem_list = self.draw_app.selected
  5017. px, py = point
  5018. if not elem_list:
  5019. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5020. return
  5021. with self.app.proc_container.new(_("Applying Flip")):
  5022. try:
  5023. # execute mirroring
  5024. for sel_el_shape in elem_list:
  5025. sel_el = sel_el_shape.geo
  5026. if axis == 'X':
  5027. if 'solid' in sel_el:
  5028. sel_el['solid'] = affinity.scale(sel_el['solid'], xfact=1, yfact=-1, origin=(px, py))
  5029. if 'follow' in sel_el:
  5030. sel_el['follow'] = affinity.scale(sel_el['follow'], xfact=1, yfact=-1, origin=(px, py))
  5031. if 'clear' in sel_el:
  5032. sel_el['clear'] = affinity.scale(sel_el['clear'], xfact=1, yfact=-1, origin=(px, py))
  5033. self.app.inform.emit('[success] %s...' % _('Flip on Y axis done'))
  5034. elif axis == 'Y':
  5035. if 'solid' in sel_el:
  5036. sel_el['solid'] = affinity.scale(sel_el['solid'], xfact=-1, yfact=1, origin=(px, py))
  5037. if 'follow' in sel_el:
  5038. sel_el['follow'] = affinity.scale(sel_el['follow'], xfact=-1, yfact=1, origin=(px, py))
  5039. if 'clear' in sel_el:
  5040. sel_el['clear'] = affinity.scale(sel_el['clear'], xfact=-1, yfact=1, origin=(px, py))
  5041. self.app.inform.emit('[success] %s...' % _('Flip on X axis done'))
  5042. self.draw_app.plot_all()
  5043. except Exception as e:
  5044. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5045. return
  5046. def on_skew(self, axis, xval, yval, point):
  5047. """
  5048. Skew geometry
  5049. :param axis: Axis on which to deform, skew
  5050. :param xval: Skew value on X axis
  5051. :param yval: Skew value on Y axis
  5052. :param point: Point of reference for deformation: tuple
  5053. :return:
  5054. """
  5055. elem_list = self.draw_app.selected
  5056. px, py = point
  5057. if not elem_list:
  5058. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5059. return
  5060. with self.app.proc_container.new(_("Applying Skew")):
  5061. try:
  5062. for sel_el_shape in elem_list:
  5063. sel_el = sel_el_shape.geo
  5064. if 'solid' in sel_el:
  5065. sel_el['solid'] = affinity.skew(sel_el['solid'], xval, yval, origin=(px, py))
  5066. if 'follow' in sel_el:
  5067. sel_el['follow'] = affinity.skew(sel_el['follow'], xval, yval, origin=(px, py))
  5068. if 'clear' in sel_el:
  5069. sel_el['clear'] = affinity.skew(sel_el['clear'], xval, yval, origin=(px, py))
  5070. self.draw_app.plot_all()
  5071. if str(axis) == 'X':
  5072. self.app.inform.emit('[success] %s...' % _('Skew on the X axis done'))
  5073. else:
  5074. self.app.inform.emit('[success] %s...' % _('Skew on the Y axis done'))
  5075. except Exception as e:
  5076. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5077. return
  5078. def on_scale(self, axis, xfactor, yfactor, point=None):
  5079. """
  5080. Scale geometry
  5081. :param axis: Axis on which to scale
  5082. :param xfactor: Factor for scaling on X axis
  5083. :param yfactor: Factor for scaling on Y axis
  5084. :param point: Point of origin for scaling
  5085. :return:
  5086. """
  5087. elem_list = self.draw_app.selected
  5088. px, py = point
  5089. if not elem_list:
  5090. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5091. return
  5092. else:
  5093. with self.app.proc_container.new(_("Applying Scale")):
  5094. try:
  5095. for sel_el_shape in elem_list:
  5096. sel_el = sel_el_shape.geo
  5097. if 'solid' in sel_el:
  5098. sel_el['solid'] = affinity.scale(sel_el['solid'], xfactor, yfactor, origin=(px, py))
  5099. if 'follow' in sel_el:
  5100. sel_el['follow'] = affinity.scale(sel_el['follow'], xfactor, yfactor, origin=(px, py))
  5101. if 'clear' in sel_el:
  5102. sel_el['clear'] = affinity.scale(sel_el['clear'], xfactor, yfactor, origin=(px, py))
  5103. self.draw_app.plot_all()
  5104. if str(axis) == 'X':
  5105. self.app.inform.emit('[success] %s...' % _('Scale on the X axis done'))
  5106. else:
  5107. self.app.inform.emit('[success] %s...' % _('Scale on the Y axis done'))
  5108. except Exception as e:
  5109. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5110. return
  5111. def on_offset(self, axis, num):
  5112. """
  5113. Offset geometry
  5114. :param axis: Axis on which to apply offset
  5115. :param num: The translation factor
  5116. :return:
  5117. """
  5118. elem_list = self.draw_app.selected
  5119. if not elem_list:
  5120. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5121. return
  5122. with self.app.proc_container.new(_("Applying Offset")):
  5123. try:
  5124. for sel_el_shape in elem_list:
  5125. sel_el = sel_el_shape.geo
  5126. if axis == 'X':
  5127. if 'solid' in sel_el:
  5128. sel_el['solid'] = affinity.translate(sel_el['solid'], num, 0)
  5129. if 'follow' in sel_el:
  5130. sel_el['follow'] = affinity.translate(sel_el['follow'], num, 0)
  5131. if 'clear' in sel_el:
  5132. sel_el['clear'] = affinity.translate(sel_el['clear'], num, 0)
  5133. elif axis == 'Y':
  5134. if 'solid' in sel_el:
  5135. sel_el['solid'] = affinity.translate(sel_el['solid'], 0, num)
  5136. if 'follow' in sel_el:
  5137. sel_el['follow'] = affinity.translate(sel_el['follow'], 0, num)
  5138. if 'clear' in sel_el:
  5139. sel_el['clear'] = affinity.translate(sel_el['clear'], 0, num)
  5140. self.draw_app.plot_all()
  5141. if str(axis) == 'X':
  5142. self.app.inform.emit('[success] %s...' % _('Offset on the X axis done'))
  5143. else:
  5144. self.app.inform.emit('[success] %s...' % _('Offset on the Y axis done'))
  5145. except Exception as e:
  5146. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5147. return
  5148. def on_buffer_action(self, value, join, factor=None):
  5149. elem_list = self.draw_app.selected
  5150. if not elem_list:
  5151. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5152. return
  5153. with self.app.proc_container.new(_("Applying Buffer")):
  5154. try:
  5155. for sel_el_shape in elem_list:
  5156. sel_el = sel_el_shape.geo
  5157. if factor:
  5158. if 'solid' in sel_el:
  5159. sel_el['solid'] = affinity.scale(sel_el['solid'], value, value, origin='center')
  5160. if 'follow' in sel_el:
  5161. sel_el['follow'] = affinity.scale(sel_el['solid'], value, value, origin='center')
  5162. if 'clear' in sel_el:
  5163. sel_el['clear'] = affinity.scale(sel_el['solid'], value, value, origin='center')
  5164. else:
  5165. if 'solid' in sel_el:
  5166. sel_el['solid'] = sel_el['solid'].buffer(
  5167. value, resolution=self.app.defaults["gerber_circle_steps"], join_style=join)
  5168. if 'clear' in sel_el:
  5169. sel_el['clear'] = sel_el['clear'].buffer(
  5170. value, resolution=self.app.defaults["gerber_circle_steps"], join_style=join)
  5171. self.draw_app.plot_all()
  5172. self.app.inform.emit('[success] %s...' % _('Buffer done'))
  5173. except Exception as e:
  5174. self.app.log.debug("TransformEditorTool.on_buffer_action() --> %s" % str(e))
  5175. self.app.inform.emit('[ERROR_NOTCL] %s: %s.' % (_("Action was not executed"), str(e)))
  5176. return
  5177. def on_rotate_key(self):
  5178. val_box = FCInputDialog(title=_("Rotate ..."),
  5179. text='%s:' % _('Enter an Angle Value (degrees)'),
  5180. min=-359.9999, max=360.0000, decimals=self.decimals,
  5181. init_val=float(self.app.defaults['tools_transform_rotate']),
  5182. parent=self.app.ui)
  5183. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/rotate.png'))
  5184. val, ok = val_box.get_value()
  5185. if ok:
  5186. self.on_rotate(val=val, ref=1)
  5187. self.app.inform.emit('[success] %s...' % _("Rotate done"))
  5188. return
  5189. else:
  5190. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Rotate cancelled"))
  5191. def on_offx_key(self):
  5192. units = self.app.defaults['units'].lower()
  5193. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  5194. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  5195. min=-10000.0000, max=10000.0000, decimals=self.decimals,
  5196. init_val=float(self.app.defaults['tools_transform_offset_x']),
  5197. parent=self.app.ui)
  5198. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsetx32.png'))
  5199. val, ok = val_box.get_value()
  5200. if ok:
  5201. self.on_offx(val=val)
  5202. self.app.inform.emit('[success] %s...' % _("Offset on the X axis done"))
  5203. return
  5204. else:
  5205. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Offset X cancelled"))
  5206. def on_offy_key(self):
  5207. units = self.app.defaults['units'].lower()
  5208. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  5209. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  5210. min=-10000.0000, max=10000.0000, decimals=self.decimals,
  5211. init_val=float(self.app.defaults['tools_transform_offset_y']),
  5212. parent=self.app.ui)
  5213. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsety32.png'))
  5214. val, ok = val_box.get_value()
  5215. if ok:
  5216. self.on_offx(val=val)
  5217. self.app.inform.emit('[success] %s...' % _("Offset on Y axis done"))
  5218. return
  5219. else:
  5220. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Offset Y cancelled"))
  5221. def on_skewx_key(self):
  5222. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  5223. text='%s:' % _('Enter an Angle Value (degrees)'),
  5224. min=-359.9999, max=360.0000, decimals=self.decimals,
  5225. init_val=float(self.app.defaults['tools_transform_skew_x']),
  5226. parent=self.app.ui)
  5227. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewX.png'))
  5228. val, ok = val_box.get_value()
  5229. if ok:
  5230. self.on_skewx(val=val, ref=3)
  5231. self.app.inform.emit('[success] %s...' % _("Skew on X axis done"))
  5232. return
  5233. else:
  5234. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Skew X cancelled"))
  5235. def on_skewy_key(self):
  5236. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  5237. text='%s:' % _('Enter an Angle Value (degrees)'),
  5238. min=-359.9999, max=360.0000, decimals=self.decimals,
  5239. init_val=float(self.app.defaults['tools_transform_skew_y']),
  5240. parent=self.app.ui)
  5241. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewY.png'))
  5242. val, ok = val_box.get_value()
  5243. if ok:
  5244. self.on_skewx(val=val, ref=3)
  5245. self.app.inform.emit('[success] %s...' % _("Skew on Y axis done"))
  5246. return
  5247. else:
  5248. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Skew Y cancelled"))
  5249. @staticmethod
  5250. def alt_bounds(shapelist):
  5251. """
  5252. Returns coordinates of rectangular bounds of a selection of shapes
  5253. """
  5254. def bounds_rec(lst):
  5255. minx = np.Inf
  5256. miny = np.Inf
  5257. maxx = -np.Inf
  5258. maxy = -np.Inf
  5259. try:
  5260. for shape in lst:
  5261. el = shape.geo
  5262. if 'solid' in el:
  5263. minx_, miny_, maxx_, maxy_ = bounds_rec(el['solid'])
  5264. minx = min(minx, minx_)
  5265. miny = min(miny, miny_)
  5266. maxx = max(maxx, maxx_)
  5267. maxy = max(maxy, maxy_)
  5268. return minx, miny, maxx, maxy
  5269. except TypeError:
  5270. # it's an object, return it's bounds
  5271. return lst.bounds
  5272. return bounds_rec(shapelist)
  5273. def get_shapely_list_bounds(geometry_list):
  5274. xmin = np.Inf
  5275. ymin = np.Inf
  5276. xmax = -np.Inf
  5277. ymax = -np.Inf
  5278. for gs in geometry_list:
  5279. try:
  5280. gxmin, gymin, gxmax, gymax = gs.bounds
  5281. xmin = min([xmin, gxmin])
  5282. ymin = min([ymin, gymin])
  5283. xmax = max([xmax, gxmax])
  5284. ymax = max([ymax, gymax])
  5285. except Exception as e:
  5286. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  5287. return [xmin, ymin, xmax, ymax]