AppGerberEditor.py 266 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446
  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 not self.app.plotcanvas.native.hasFocus():
  3585. self.app.plotcanvas.native.setFocus()
  3586. if self.app.is_legacy is False:
  3587. event_pos = event.pos
  3588. event_is_dragging = event.is_dragging
  3589. right_button = 2
  3590. else:
  3591. event_pos = (event.xdata, event.ydata)
  3592. event_is_dragging = self.app.plotcanvas.is_dragging
  3593. right_button = 3
  3594. pos_canvas = self.canvas.translate_coords(event_pos)
  3595. event.xdata, event.ydata = pos_canvas[0], pos_canvas[1]
  3596. self.x = event.xdata
  3597. self.y = event.ydata
  3598. self.app.ui.popMenu.mouse_is_panning = False
  3599. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3600. if event.button == right_button and event_is_dragging == 1:
  3601. self.app.ui.popMenu.mouse_is_panning = True
  3602. return
  3603. try:
  3604. x = float(event.xdata)
  3605. y = float(event.ydata)
  3606. except TypeError:
  3607. return
  3608. if self.active_tool is None:
  3609. return
  3610. # # ## Snap coordinates
  3611. if self.app.grid_status():
  3612. x, y = self.app.geo_editor.snap(x, y)
  3613. # Update cursor
  3614. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color=self.app.cursor_color_3D,
  3615. edge_width=self.app.defaults["global_cursor_width"],
  3616. size=self.app.defaults["global_cursor_size"])
  3617. self.snap_x = x
  3618. self.snap_y = y
  3619. self.app.mouse = [x, y]
  3620. if self.pos is None:
  3621. self.pos = (0, 0)
  3622. self.app.dx = x - self.pos[0]
  3623. self.app.dy = y - self.pos[1]
  3624. # # update the position label in the infobar since the APP mouse event handlers are disconnected
  3625. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3626. "<b>Y</b>: %.4f&nbsp;" % (x, y))
  3627. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3628. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3629. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  3630. units = self.app.defaults["units"].lower()
  3631. self.app.plotcanvas.text_hud.text = \
  3632. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3633. self.app.dx, units, self.app.dy, units, x, units, y, units)
  3634. self.update_utility_geometry(data=(x, y))
  3635. # # ## Selection area on canvas section # ##
  3636. if event_is_dragging == 1 and event.button == 1:
  3637. # I make an exception for FCRegion and FCTrack because clicking and dragging while making regions can
  3638. # create strange issues like missing a point in a track/region
  3639. if isinstance(self.active_tool, FCRegion) or isinstance(self.active_tool, FCTrack):
  3640. pass
  3641. else:
  3642. dx = pos_canvas[0] - self.pos[0]
  3643. self.app.delete_selection_shape()
  3644. if dx < 0:
  3645. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  3646. color=self.app.defaults["global_alt_sel_line"],
  3647. face_color=self.app.defaults['global_alt_sel_fill'])
  3648. self.app.selection_type = False
  3649. else:
  3650. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  3651. self.app.selection_type = True
  3652. else:
  3653. self.app.selection_type = None
  3654. def update_utility_geometry(self, data):
  3655. # # ## Utility geometry (animated)
  3656. geo = self.active_tool.utility_geometry(data=data)
  3657. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3658. # Remove any previous utility shape
  3659. self.tool_shape.clear(update=True)
  3660. self.draw_utility_geometry(geo=geo)
  3661. def draw_utility_geometry(self, geo):
  3662. if type(geo.geo) == list:
  3663. for el in geo.geo:
  3664. geometric_data = el['solid']
  3665. # Add the new utility shape
  3666. self.tool_shape.add(
  3667. shape=geometric_data, color=(self.app.defaults["global_draw_color"] + '80'),
  3668. # face_color=self.app.defaults['global_alt_sel_fill'],
  3669. update=False, layer=0, tolerance=None
  3670. )
  3671. else:
  3672. geometric_data = geo.geo['solid']
  3673. # Add the new utility shape
  3674. self.tool_shape.add(
  3675. shape=geometric_data,
  3676. color=(self.app.defaults["global_draw_color"] + '80'),
  3677. # face_color=self.app.defaults['global_alt_sel_fill'],
  3678. update=False, layer=0, tolerance=None
  3679. )
  3680. self.tool_shape.redraw()
  3681. def plot_all(self):
  3682. """
  3683. Plots all shapes in the editor.
  3684. :return: None
  3685. :rtype: None
  3686. """
  3687. with self.app.proc_container.new('%s ...' % _("Plotting")):
  3688. self.shapes.clear(update=True)
  3689. for storage in self.storage_dict:
  3690. # fix for apertures with no geometry inside
  3691. if 'geometry' in self.storage_dict[storage]:
  3692. for elem in self.storage_dict[storage]['geometry']:
  3693. if 'solid' in elem.geo:
  3694. geometric_data = elem.geo['solid']
  3695. if geometric_data is None:
  3696. continue
  3697. if elem in self.selected:
  3698. self.plot_shape(geometry=geometric_data,
  3699. color=self.app.defaults['global_sel_draw_color'] + 'FF',
  3700. linewidth=2)
  3701. else:
  3702. self.plot_shape(geometry=geometric_data,
  3703. color=self.app.defaults['global_draw_color'] + 'FF')
  3704. if self.utility:
  3705. for elem in self.utility:
  3706. geometric_data = elem.geo['solid']
  3707. self.plot_shape(geometry=geometric_data, linewidth=1)
  3708. continue
  3709. self.shapes.redraw()
  3710. def plot_shape(self, geometry=None, color='#000000FF', linewidth=1):
  3711. """
  3712. Plots a geometric object or list of objects without rendering. Plotted objects
  3713. are returned as a list. This allows for efficient/animated rendering.
  3714. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3715. :param color: Shape color
  3716. :param linewidth: Width of lines in # of pixels.
  3717. :return: List of plotted elements.
  3718. """
  3719. if geometry is None:
  3720. geometry = self.active_tool.geometry
  3721. try:
  3722. self.shapes.add(shape=geometry.geo, color=color, face_color=color, layer=0, tolerance=self.tolerance)
  3723. except AttributeError:
  3724. if type(geometry) == Point:
  3725. return
  3726. if len(color) == 9:
  3727. color = color[:7] + 'AF'
  3728. self.shapes.add(shape=geometry, color=color, face_color=color, layer=0, tolerance=self.tolerance)
  3729. # def start_delayed_plot(self, check_period):
  3730. # """
  3731. # This function starts an QTImer and it will periodically check if all the workers finish the plotting functions
  3732. #
  3733. # :param check_period: time at which to check periodically if all plots finished to be plotted
  3734. # :return:
  3735. # """
  3736. #
  3737. # # self.plot_thread = threading.Thread(target=lambda: self.check_plot_finished(check_period))
  3738. # # self.plot_thread.start()
  3739. # log.debug("AppGerberEditor --> Delayed Plot started.")
  3740. # self.plot_thread = QtCore.QTimer()
  3741. # self.plot_thread.setInterval(check_period)
  3742. # self.plot_finished.connect(self.setup_ui_after_delayed_plot)
  3743. # self.plot_thread.timeout.connect(self.check_plot_finished)
  3744. # self.plot_thread.start()
  3745. #
  3746. # def check_plot_finished(self):
  3747. # """
  3748. # If all the promises made are finished then all the shapes are in shapes_storage and can be plotted safely and
  3749. # then the UI is rebuilt accordingly.
  3750. # :return:
  3751. # """
  3752. #
  3753. # try:
  3754. # if not self.grb_plot_promises:
  3755. # self.plot_thread.stop()
  3756. # self.plot_finished.emit()
  3757. # log.debug("AppGerberEditor --> delayed_plot finished")
  3758. # except Exception as e:
  3759. # traceback.print_exc()
  3760. #
  3761. # def setup_ui_after_delayed_plot(self):
  3762. # self.plot_finished.disconnect()
  3763. #
  3764. # # now that we have data, create the GUI interface and add it to the Tool Tab
  3765. # self.build_ui(first_run=True)
  3766. # self.plot_all()
  3767. #
  3768. # # HACK: enabling/disabling the cursor seams to somehow update the shapes making them more 'solid'
  3769. # # - perhaps is a bug in VisPy implementation
  3770. # self.app.app_cursor.enabled = False
  3771. # self.app.app_cursor.enabled = True
  3772. def on_zoom_fit(self):
  3773. """
  3774. Callback for zoom-fit request in Gerber Editor
  3775. :return: None
  3776. """
  3777. log.debug("AppGerberEditor.on_zoom_fit()")
  3778. # calculate all the geometry in the edited Gerber object
  3779. edit_geo = []
  3780. for ap_code in self.storage_dict:
  3781. for geo_el in self.storage_dict[ap_code]['geometry']:
  3782. actual_geo = geo_el.geo
  3783. if 'solid' in actual_geo:
  3784. edit_geo.append(actual_geo['solid'])
  3785. all_geo = unary_union(edit_geo)
  3786. # calculate the bounds values for the edited Gerber object
  3787. xmin, ymin, xmax, ymax = all_geo.bounds
  3788. if self.app.is_legacy is False:
  3789. new_rect = Rect(xmin, ymin, xmax, ymax)
  3790. self.app.plotcanvas.fit_view(rect=new_rect)
  3791. else:
  3792. width = xmax - xmin
  3793. height = ymax - ymin
  3794. xmin -= 0.05 * width
  3795. xmax += 0.05 * width
  3796. ymin -= 0.05 * height
  3797. ymax += 0.05 * height
  3798. self.app.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  3799. def get_selected(self):
  3800. """
  3801. Returns list of shapes that are selected in the editor.
  3802. :return: List of shapes.
  3803. """
  3804. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3805. return self.selected
  3806. def delete_selected(self):
  3807. temp_ref = [s for s in self.selected]
  3808. if len(temp_ref) == 0:
  3809. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3810. _("Failed. No aperture geometry is selected."))
  3811. return
  3812. for shape_sel in temp_ref:
  3813. self.delete_shape(shape_sel)
  3814. self.selected = []
  3815. self.build_ui()
  3816. self.app.inform.emit('[success] %s' % _("Done."))
  3817. def delete_shape(self, geo_el):
  3818. self.is_modified = True
  3819. if geo_el in self.utility:
  3820. self.utility.remove(geo_el)
  3821. return
  3822. for storage in self.storage_dict:
  3823. try:
  3824. if geo_el in self.storage_dict[storage]['geometry']:
  3825. self.storage_dict[storage]['geometry'].remove(geo_el)
  3826. except KeyError:
  3827. pass
  3828. if geo_el in self.selected:
  3829. self.selected.remove(geo_el) # TODO: Check performance
  3830. def delete_utility_geometry(self):
  3831. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  3832. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  3833. for_deletion = [geo_el for geo_el in self.utility]
  3834. for geo_el in for_deletion:
  3835. self.delete_shape(geo_el)
  3836. self.tool_shape.clear(update=True)
  3837. self.tool_shape.redraw()
  3838. def on_delete_btn(self):
  3839. self.delete_selected()
  3840. self.plot_all()
  3841. def select_tool(self, toolname):
  3842. """
  3843. Selects a drawing tool. Impacts the object and appGUI.
  3844. :param toolname: Name of the tool.
  3845. :return: None
  3846. """
  3847. self.tools_gerber[toolname]["button"].setChecked(True)
  3848. self.on_tool_select(toolname)
  3849. def set_selected(self, geo_el):
  3850. # Remove and add to the end.
  3851. if geo_el in self.selected:
  3852. self.selected.remove(geo_el)
  3853. self.selected.append(geo_el)
  3854. def set_unselected(self, geo_el):
  3855. if geo_el in self.selected:
  3856. self.selected.remove(geo_el)
  3857. def on_array_type_combo(self):
  3858. if self.ui.array_type_combo.currentIndex() == 0:
  3859. self.ui.array_circular_frame.hide()
  3860. self.ui.array_linear_frame.show()
  3861. else:
  3862. self.delete_utility_geometry()
  3863. self.ui.array_circular_frame.show()
  3864. self.ui.array_linear_frame.hide()
  3865. self.app.inform.emit(_("Click on the circular array Center position"))
  3866. def on_linear_angle_radio(self):
  3867. val = self.ui.pad_axis_radio.get_value()
  3868. if val == 'A':
  3869. self.ui.linear_angle_spinner.show()
  3870. self.ui.linear_angle_label.show()
  3871. else:
  3872. self.ui.linear_angle_spinner.hide()
  3873. self.ui.linear_angle_label.hide()
  3874. def on_copy_button(self):
  3875. self.select_tool('copy')
  3876. return
  3877. def on_move_button(self):
  3878. self.select_tool('move')
  3879. return
  3880. def on_pad_add(self):
  3881. self.select_tool('pad')
  3882. def on_pad_add_array(self):
  3883. self.select_tool('array')
  3884. def on_track_add(self):
  3885. self.select_tool('track')
  3886. def on_region_add(self):
  3887. self.select_tool('region')
  3888. def on_poligonize(self):
  3889. self.select_tool('poligonize')
  3890. def on_disc_add(self):
  3891. self.select_tool('disc')
  3892. def on_add_semidisc(self):
  3893. self.select_tool('semidisc')
  3894. def on_buffer(self):
  3895. buff_value = 0.01
  3896. log.debug("AppGerberEditor.on_buffer()")
  3897. try:
  3898. buff_value = float(self.ui.buffer_distance_entry.get_value())
  3899. except ValueError:
  3900. # try to convert comma to decimal point. if it's still not working error message and return
  3901. try:
  3902. buff_value = float(self.ui.buffer_distance_entry.get_value().replace(',', '.'))
  3903. self.ui.buffer_distance_entry.set_value(buff_value)
  3904. except ValueError:
  3905. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3906. _("Buffer distance value is missing or wrong format. Add it and retry."))
  3907. return
  3908. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  3909. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  3910. join_style = self.ui.buffer_corner_cb.currentIndex() + 1
  3911. def buffer_recursion(geom_el, selection):
  3912. if type(geom_el) == list:
  3913. geoms = []
  3914. for local_geom in geom_el:
  3915. geoms.append(buffer_recursion(local_geom, selection=selection))
  3916. return geoms
  3917. else:
  3918. if geom_el in selection:
  3919. geometric_data = geom_el.geo
  3920. buffered_geom_el = {}
  3921. if 'solid' in geometric_data:
  3922. buffered_geom_el['solid'] = geometric_data['solid'].buffer(buff_value, join_style=join_style)
  3923. if 'follow' in geometric_data:
  3924. buffered_geom_el['follow'] = geometric_data['follow'].buffer(buff_value, join_style=join_style)
  3925. if 'clear' in geometric_data:
  3926. buffered_geom_el['clear'] = geometric_data['clear'].buffer(buff_value, join_style=join_style)
  3927. return DrawToolShape(buffered_geom_el)
  3928. else:
  3929. return geom_el
  3930. if not self.ui.apertures_table.selectedItems():
  3931. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3932. _("No aperture to buffer. Select at least one aperture and try again."))
  3933. return
  3934. for x in self.ui.apertures_table.selectedItems():
  3935. try:
  3936. apcode = self.ui.apertures_table.item(x.row(), 1).text()
  3937. temp_storage = deepcopy(buffer_recursion(self.storage_dict[apcode]['geometry'], self.selected))
  3938. self.storage_dict[apcode]['geometry'] = []
  3939. self.storage_dict[apcode]['geometry'] = temp_storage
  3940. except Exception as e:
  3941. log.debug("AppGerberEditor.buffer() --> %s" % str(e))
  3942. self.app.inform.emit('[ERROR_NOTCL] %s\n%s' % (_("Failed."), str(traceback.print_exc())))
  3943. return
  3944. self.plot_all()
  3945. self.app.inform.emit('[success] %s' % _("Done."))
  3946. def on_scale(self):
  3947. scale_factor = 1.0
  3948. log.debug("AppGerberEditor.on_scale()")
  3949. try:
  3950. scale_factor = float(self.ui.scale_factor_entry.get_value())
  3951. except ValueError:
  3952. # try to convert comma to decimal point. if it's still not working error message and return
  3953. try:
  3954. scale_factor = float(self.ui.scale_factor_entry.get_value().replace(',', '.'))
  3955. self.ui.scale_factor_entry.set_value(scale_factor)
  3956. except ValueError:
  3957. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3958. _("Scale factor value is missing or wrong format. Add it and retry."))
  3959. return
  3960. def scale_recursion(geom_el, selection):
  3961. if type(geom_el) == list:
  3962. geoms = []
  3963. for local_geom in geom_el:
  3964. geoms.append(scale_recursion(local_geom, selection=selection))
  3965. return geoms
  3966. else:
  3967. if geom_el in selection:
  3968. geometric_data = geom_el.geo
  3969. scaled_geom_el = {}
  3970. if 'solid' in geometric_data:
  3971. scaled_geom_el['solid'] = affinity.scale(
  3972. geometric_data['solid'], scale_factor, scale_factor, origin='center'
  3973. )
  3974. if 'follow' in geometric_data:
  3975. scaled_geom_el['follow'] = affinity.scale(
  3976. geometric_data['follow'], scale_factor, scale_factor, origin='center'
  3977. )
  3978. if 'clear' in geometric_data:
  3979. scaled_geom_el['clear'] = affinity.scale(
  3980. geometric_data['clear'], scale_factor, scale_factor, origin='center'
  3981. )
  3982. return DrawToolShape(scaled_geom_el)
  3983. else:
  3984. return geom_el
  3985. if not self.ui.apertures_table.selectedItems():
  3986. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3987. _("No aperture to scale. Select at least one aperture and try again."))
  3988. return
  3989. for x in self.ui.apertures_table.selectedItems():
  3990. try:
  3991. apcode = self.ui.apertures_table.item(x.row(), 1).text()
  3992. temp_storage = deepcopy(scale_recursion(self.storage_dict[apcode]['geometry'], self.selected))
  3993. self.storage_dict[apcode]['geometry'] = []
  3994. self.storage_dict[apcode]['geometry'] = temp_storage
  3995. except Exception as e:
  3996. log.debug("AppGerberEditor.on_scale() --> %s" % str(e))
  3997. self.plot_all()
  3998. self.app.inform.emit('[success] %s' % _("Done."))
  3999. def on_markarea(self):
  4000. # clear previous marking
  4001. self.ma_annotation.clear(update=True)
  4002. self.units = self.app.defaults['units'].upper()
  4003. text = []
  4004. position = []
  4005. for apcode in self.storage_dict:
  4006. if 'geometry' in self.storage_dict[apcode]:
  4007. for geo_el in self.storage_dict[apcode]['geometry']:
  4008. if 'solid' in geo_el.geo:
  4009. area = geo_el.geo['solid'].area
  4010. try:
  4011. upper_threshold_val = self.ui.ma_upper_threshold_entry.get_value()
  4012. except Exception:
  4013. return
  4014. try:
  4015. lower_threshold_val = self.ui.ma_lower_threshold_entry.get_value()
  4016. except Exception:
  4017. lower_threshold_val = 0.0
  4018. if float(upper_threshold_val) > area > float(lower_threshold_val):
  4019. current_pos = geo_el.geo['solid'].exterior.coords[-1]
  4020. text_elem = '%.*f' % (self.decimals, area)
  4021. text.append(text_elem)
  4022. position.append(current_pos)
  4023. self.geo_to_delete.append(geo_el)
  4024. if text:
  4025. self.ma_annotation.set(text=text, pos=position, visible=True,
  4026. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4027. color='#000000FF')
  4028. self.app.inform.emit('[success] %s' %
  4029. _("Polygons marked."))
  4030. else:
  4031. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4032. _("No polygons were marked. None fit within the limits."))
  4033. def delete_marked_polygons(self):
  4034. for shape_sel in self.geo_to_delete:
  4035. self.delete_shape(shape_sel)
  4036. self.build_ui()
  4037. self.plot_all()
  4038. self.app.inform.emit('[success] %s' % _("Done."))
  4039. def on_eraser(self):
  4040. self.select_tool('eraser')
  4041. def on_transform(self):
  4042. if type(self.active_tool) == FCTransform:
  4043. self.select_tool('select')
  4044. else:
  4045. self.select_tool('transform')
  4046. def hide_tool(self, tool_name):
  4047. # self.app.ui.notebook.setTabText(2, _("Tools"))
  4048. try:
  4049. if tool_name == 'all':
  4050. self.ui.apertures_frame.hide()
  4051. if tool_name == 'select':
  4052. self.ui.apertures_frame.show()
  4053. if tool_name == 'buffer' or tool_name == 'all':
  4054. self.ui.buffer_tool_frame.hide()
  4055. if tool_name == 'scale' or tool_name == 'all':
  4056. self.ui.scale_tool_frame.hide()
  4057. if tool_name == 'markarea' or tool_name == 'all':
  4058. self.ui.ma_tool_frame.hide()
  4059. except Exception as e:
  4060. log.debug("AppGerberEditor.hide_tool() --> %s" % str(e))
  4061. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  4062. class AppGerberEditorUI:
  4063. def __init__(self, app):
  4064. self.app = app
  4065. # Number of decimals used by tools in this class
  4066. self.decimals = self.app.decimals
  4067. # ## Current application units in Upper Case
  4068. self.units = self.app.defaults['units'].upper()
  4069. self.grb_edit_widget = QtWidgets.QWidget()
  4070. layout = QtWidgets.QVBoxLayout()
  4071. self.grb_edit_widget.setLayout(layout)
  4072. # Page Title box (spacing between children)
  4073. self.title_box = QtWidgets.QHBoxLayout()
  4074. layout.addLayout(self.title_box)
  4075. # Page Title icon
  4076. pixmap = QtGui.QPixmap(self.app.resource_location + '/flatcam_icon32.png')
  4077. self.icon = QtWidgets.QLabel()
  4078. self.icon.setPixmap(pixmap)
  4079. self.title_box.addWidget(self.icon, stretch=0)
  4080. # Title label
  4081. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Gerber Editor'))
  4082. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  4083. self.title_box.addWidget(self.title_label, stretch=1)
  4084. # Object name
  4085. self.name_box = QtWidgets.QHBoxLayout()
  4086. layout.addLayout(self.name_box)
  4087. name_label = QtWidgets.QLabel(_("Name:"))
  4088. self.name_box.addWidget(name_label)
  4089. self.name_entry = FCEntry()
  4090. self.name_box.addWidget(self.name_entry)
  4091. # Box for custom widgets
  4092. # This gets populated in offspring implementations.
  4093. self.custom_box = QtWidgets.QVBoxLayout()
  4094. layout.addLayout(self.custom_box)
  4095. # #########################
  4096. # ### Gerber Apertures ####
  4097. # #########################
  4098. self.apertures_table_label = QtWidgets.QLabel('<b>%s:</b>' % _('Apertures'))
  4099. self.apertures_table_label.setToolTip(
  4100. _("Apertures Table for the Gerber Object.")
  4101. )
  4102. self.custom_box.addWidget(self.apertures_table_label)
  4103. self.apertures_table = FCTable()
  4104. # delegate = SpinBoxDelegate(units=self.units)
  4105. # self.apertures_table.setItemDelegateForColumn(1, delegate)
  4106. self.custom_box.addWidget(self.apertures_table)
  4107. self.apertures_table.setColumnCount(5)
  4108. self.apertures_table.setHorizontalHeaderLabels(['#', _('Code'), _('Type'), _('Size'), _('Dim')])
  4109. self.apertures_table.setSortingEnabled(False)
  4110. self.apertures_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  4111. self.apertures_table.horizontalHeaderItem(0).setToolTip(
  4112. _("Index"))
  4113. self.apertures_table.horizontalHeaderItem(1).setToolTip(
  4114. _("Aperture Code"))
  4115. self.apertures_table.horizontalHeaderItem(2).setToolTip(
  4116. _("Type of aperture: circular, rectangle, macros etc"))
  4117. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  4118. _("Aperture Size:"))
  4119. self.apertures_table.horizontalHeaderItem(4).setToolTip(
  4120. _("Aperture Dimensions:\n"
  4121. " - (width, height) for R, O type.\n"
  4122. " - (dia, nVertices) for P type"))
  4123. self.empty_label = QtWidgets.QLabel('')
  4124. self.custom_box.addWidget(self.empty_label)
  4125. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Apertures widgets
  4126. # this way I can hide/show the frame
  4127. self.apertures_frame = QtWidgets.QFrame()
  4128. self.apertures_frame.setContentsMargins(0, 0, 0, 0)
  4129. self.custom_box.addWidget(self.apertures_frame)
  4130. self.apertures_box = QtWidgets.QVBoxLayout()
  4131. self.apertures_box.setContentsMargins(0, 0, 0, 0)
  4132. self.apertures_frame.setLayout(self.apertures_box)
  4133. # # ## Add/Delete an new Aperture ## ##
  4134. grid1 = QtWidgets.QGridLayout()
  4135. self.apertures_box.addLayout(grid1)
  4136. grid1.setColumnStretch(0, 0)
  4137. grid1.setColumnStretch(1, 1)
  4138. apcode_lbl = QtWidgets.QLabel('%s:' % _('Aperture Code'))
  4139. apcode_lbl.setToolTip(_("Code for the new aperture"))
  4140. grid1.addWidget(apcode_lbl, 1, 0)
  4141. self.apcode_entry = FCSpinner()
  4142. self.apcode_entry.set_range(0, 999)
  4143. self.apcode_entry.setWrapping(True)
  4144. grid1.addWidget(self.apcode_entry, 1, 1)
  4145. apsize_lbl = QtWidgets.QLabel('%s' % _('Aperture Size:'))
  4146. apsize_lbl.setToolTip(
  4147. _("Size for the new aperture.\n"
  4148. "If aperture type is 'R' or 'O' then\n"
  4149. "this value is automatically\n"
  4150. "calculated as:\n"
  4151. "sqrt(width**2 + height**2)")
  4152. )
  4153. grid1.addWidget(apsize_lbl, 2, 0)
  4154. self.apsize_entry = FCDoubleSpinner()
  4155. self.apsize_entry.set_precision(self.decimals)
  4156. self.apsize_entry.set_range(0.0, 9999)
  4157. grid1.addWidget(self.apsize_entry, 2, 1)
  4158. aptype_lbl = QtWidgets.QLabel('%s:' % _('Aperture Type'))
  4159. aptype_lbl.setToolTip(
  4160. _("Select the type of new aperture. Can be:\n"
  4161. "C = circular\n"
  4162. "R = rectangular\n"
  4163. "O = oblong")
  4164. )
  4165. grid1.addWidget(aptype_lbl, 3, 0)
  4166. self.aptype_cb = FCComboBox()
  4167. self.aptype_cb.addItems(['C', 'R', 'O'])
  4168. grid1.addWidget(self.aptype_cb, 3, 1)
  4169. self.apdim_lbl = QtWidgets.QLabel('%s:' % _('Aperture Dim'))
  4170. self.apdim_lbl.setToolTip(
  4171. _("Dimensions for the new aperture.\n"
  4172. "Active only for rectangular apertures (type R).\n"
  4173. "The format is (width, height)")
  4174. )
  4175. grid1.addWidget(self.apdim_lbl, 4, 0)
  4176. self.apdim_entry = EvalEntry2()
  4177. grid1.addWidget(self.apdim_entry, 4, 1)
  4178. apadd_del_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Add/Delete Aperture'))
  4179. apadd_del_lbl.setToolTip(
  4180. _("Add/Delete an aperture in the aperture table")
  4181. )
  4182. self.apertures_box.addWidget(apadd_del_lbl)
  4183. hlay_ad = QtWidgets.QHBoxLayout()
  4184. self.apertures_box.addLayout(hlay_ad)
  4185. self.addaperture_btn = QtWidgets.QPushButton(_('Add'))
  4186. self.addaperture_btn.setToolTip(
  4187. _("Add a new aperture to the aperture list.")
  4188. )
  4189. self.delaperture_btn = QtWidgets.QPushButton(_('Delete'))
  4190. self.delaperture_btn.setToolTip(
  4191. _("Delete a aperture in the aperture list")
  4192. )
  4193. hlay_ad.addWidget(self.addaperture_btn)
  4194. hlay_ad.addWidget(self.delaperture_btn)
  4195. # ###################
  4196. # ### BUFFER TOOL ###
  4197. # ###################
  4198. self.buffer_tool_frame = QtWidgets.QFrame()
  4199. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  4200. self.custom_box.addWidget(self.buffer_tool_frame)
  4201. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  4202. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  4203. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  4204. self.buffer_tool_frame.hide()
  4205. # Title
  4206. buf_title_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Buffer Aperture'))
  4207. buf_title_lbl.setToolTip(
  4208. _("Buffer a aperture in the aperture list")
  4209. )
  4210. self.buffer_tools_box.addWidget(buf_title_lbl)
  4211. # Form Layout
  4212. buf_form_layout = QtWidgets.QFormLayout()
  4213. self.buffer_tools_box.addLayout(buf_form_layout)
  4214. # Buffer distance
  4215. self.buffer_distance_entry = FCDoubleSpinner()
  4216. self.buffer_distance_entry.set_precision(self.decimals)
  4217. self.buffer_distance_entry.set_range(-10000.0000, 10000.0000)
  4218. buf_form_layout.addRow('%s:' % _("Buffer distance"), self.buffer_distance_entry)
  4219. self.buffer_corner_lbl = QtWidgets.QLabel('%s:' % _("Buffer corner"))
  4220. self.buffer_corner_lbl.setToolTip(
  4221. _("There are 3 types of corners:\n"
  4222. " - 'Round': the corner is rounded.\n"
  4223. " - 'Square': the corner is met in a sharp angle.\n"
  4224. " - 'Beveled': the corner is a line that directly connects the features meeting in the corner")
  4225. )
  4226. self.buffer_corner_cb = FCComboBox()
  4227. self.buffer_corner_cb.addItem(_("Round"))
  4228. self.buffer_corner_cb.addItem(_("Square"))
  4229. self.buffer_corner_cb.addItem(_("Beveled"))
  4230. buf_form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  4231. # Buttons
  4232. hlay_buf = QtWidgets.QHBoxLayout()
  4233. self.buffer_tools_box.addLayout(hlay_buf)
  4234. self.buffer_button = QtWidgets.QPushButton(_("Buffer"))
  4235. hlay_buf.addWidget(self.buffer_button)
  4236. # ##################
  4237. # ### SCALE TOOL ###
  4238. # ##################
  4239. self.scale_tool_frame = QtWidgets.QFrame()
  4240. self.scale_tool_frame.setContentsMargins(0, 0, 0, 0)
  4241. self.custom_box.addWidget(self.scale_tool_frame)
  4242. self.scale_tools_box = QtWidgets.QVBoxLayout()
  4243. self.scale_tools_box.setContentsMargins(0, 0, 0, 0)
  4244. self.scale_tool_frame.setLayout(self.scale_tools_box)
  4245. self.scale_tool_frame.hide()
  4246. # Title
  4247. scale_title_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Scale Aperture'))
  4248. scale_title_lbl.setToolTip(
  4249. _("Scale a aperture in the aperture list")
  4250. )
  4251. self.scale_tools_box.addWidget(scale_title_lbl)
  4252. # Form Layout
  4253. scale_form_layout = QtWidgets.QFormLayout()
  4254. self.scale_tools_box.addLayout(scale_form_layout)
  4255. self.scale_factor_lbl = QtWidgets.QLabel('%s:' % _("Scale factor"))
  4256. self.scale_factor_lbl.setToolTip(
  4257. _("The factor by which to scale the selected aperture.\n"
  4258. "Values can be between 0.0000 and 999.9999")
  4259. )
  4260. self.scale_factor_entry = FCDoubleSpinner()
  4261. self.scale_factor_entry.set_precision(self.decimals)
  4262. self.scale_factor_entry.set_range(0.0000, 10000.0000)
  4263. scale_form_layout.addRow(self.scale_factor_lbl, self.scale_factor_entry)
  4264. # Buttons
  4265. hlay_scale = QtWidgets.QHBoxLayout()
  4266. self.scale_tools_box.addLayout(hlay_scale)
  4267. self.scale_button = QtWidgets.QPushButton(_("Scale"))
  4268. hlay_scale.addWidget(self.scale_button)
  4269. # ######################
  4270. # ### Mark Area TOOL ###
  4271. # ######################
  4272. self.ma_tool_frame = QtWidgets.QFrame()
  4273. self.ma_tool_frame.setContentsMargins(0, 0, 0, 0)
  4274. self.custom_box.addWidget(self.ma_tool_frame)
  4275. self.ma_tools_box = QtWidgets.QVBoxLayout()
  4276. self.ma_tools_box.setContentsMargins(0, 0, 0, 0)
  4277. self.ma_tool_frame.setLayout(self.ma_tools_box)
  4278. self.ma_tool_frame.hide()
  4279. # Title
  4280. ma_title_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Mark polygons'))
  4281. ma_title_lbl.setToolTip(
  4282. _("Mark the polygon areas.")
  4283. )
  4284. self.ma_tools_box.addWidget(ma_title_lbl)
  4285. # Form Layout
  4286. ma_form_layout = QtWidgets.QFormLayout()
  4287. self.ma_tools_box.addLayout(ma_form_layout)
  4288. self.ma_upper_threshold_lbl = QtWidgets.QLabel('%s:' % _("Area UPPER threshold"))
  4289. self.ma_upper_threshold_lbl.setToolTip(
  4290. _("The threshold value, all areas less than this are marked.\n"
  4291. "Can have a value between 0.0000 and 10000.0000")
  4292. )
  4293. self.ma_upper_threshold_entry = FCDoubleSpinner()
  4294. self.ma_upper_threshold_entry.set_precision(self.decimals)
  4295. self.ma_upper_threshold_entry.set_range(0, 10000)
  4296. self.ma_lower_threshold_lbl = QtWidgets.QLabel('%s:' % _("Area LOWER threshold"))
  4297. self.ma_lower_threshold_lbl.setToolTip(
  4298. _("The threshold value, all areas more than this are marked.\n"
  4299. "Can have a value between 0.0000 and 10000.0000")
  4300. )
  4301. self.ma_lower_threshold_entry = FCDoubleSpinner()
  4302. self.ma_lower_threshold_entry.set_precision(self.decimals)
  4303. self.ma_lower_threshold_entry.set_range(0, 10000)
  4304. ma_form_layout.addRow(self.ma_lower_threshold_lbl, self.ma_lower_threshold_entry)
  4305. ma_form_layout.addRow(self.ma_upper_threshold_lbl, self.ma_upper_threshold_entry)
  4306. # Buttons
  4307. hlay_ma = QtWidgets.QHBoxLayout()
  4308. self.ma_tools_box.addLayout(hlay_ma)
  4309. self.ma_threshold_button = QtWidgets.QPushButton(_("Mark"))
  4310. self.ma_threshold_button.setToolTip(
  4311. _("Mark the polygons that fit within limits.")
  4312. )
  4313. hlay_ma.addWidget(self.ma_threshold_button)
  4314. self.ma_delete_button = QtWidgets.QPushButton(_("Delete"))
  4315. self.ma_delete_button.setToolTip(
  4316. _("Delete all the marked polygons.")
  4317. )
  4318. hlay_ma.addWidget(self.ma_delete_button)
  4319. self.ma_clear_button = QtWidgets.QPushButton(_("Clear"))
  4320. self.ma_clear_button.setToolTip(
  4321. _("Clear all the markings.")
  4322. )
  4323. hlay_ma.addWidget(self.ma_clear_button)
  4324. # ######################
  4325. # ### Add Pad Array ####
  4326. # ######################
  4327. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  4328. # all the add Pad array widgets
  4329. # this way I can hide/show the frame
  4330. self.array_frame = QtWidgets.QFrame()
  4331. self.array_frame.setContentsMargins(0, 0, 0, 0)
  4332. self.custom_box.addWidget(self.array_frame)
  4333. self.array_box = QtWidgets.QVBoxLayout()
  4334. self.array_box.setContentsMargins(0, 0, 0, 0)
  4335. self.array_frame.setLayout(self.array_box)
  4336. self.emptyarray_label = QtWidgets.QLabel('')
  4337. self.array_box.addWidget(self.emptyarray_label)
  4338. self.padarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Pad Array"))
  4339. self.padarray_label.setToolTip(
  4340. _("Add an array of pads (linear or circular array)")
  4341. )
  4342. self.array_box.addWidget(self.padarray_label)
  4343. self.array_type_combo = FCComboBox2()
  4344. self.array_type_combo.setToolTip(
  4345. _("Select the type of pads array to create.\n"
  4346. "It can be Linear X(Y) or Circular")
  4347. )
  4348. self.array_type_combo.addItem(_("Linear"))
  4349. self.array_type_combo.addItem(_("Circular"))
  4350. self.array_box.addWidget(self.array_type_combo)
  4351. self.array_form = QtWidgets.QFormLayout()
  4352. self.array_box.addLayout(self.array_form)
  4353. self.pad_array_size_label = QtWidgets.QLabel('%s:' % _('Nr of pads'))
  4354. self.pad_array_size_label.setToolTip(
  4355. _("Specify how many pads to be in the array.")
  4356. )
  4357. self.pad_array_size_label.setMinimumWidth(100)
  4358. self.pad_array_size_entry = FCSpinner()
  4359. self.pad_array_size_entry.set_range(1, 9999)
  4360. self.array_form.addRow(self.pad_array_size_label, self.pad_array_size_entry)
  4361. self.array_linear_frame = QtWidgets.QFrame()
  4362. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  4363. self.array_box.addWidget(self.array_linear_frame)
  4364. self.linear_box = QtWidgets.QVBoxLayout()
  4365. self.linear_box.setContentsMargins(0, 0, 0, 0)
  4366. self.array_linear_frame.setLayout(self.linear_box)
  4367. self.linear_form = QtWidgets.QFormLayout()
  4368. self.linear_box.addLayout(self.linear_form)
  4369. self.pad_axis_label = QtWidgets.QLabel('%s:' % _('Direction'))
  4370. self.pad_axis_label.setToolTip(
  4371. _("Direction on which the linear array is oriented:\n"
  4372. "- 'X' - horizontal axis \n"
  4373. "- 'Y' - vertical axis or \n"
  4374. "- 'Angle' - a custom angle for the array inclination")
  4375. )
  4376. self.pad_axis_label.setMinimumWidth(100)
  4377. self.pad_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  4378. {'label': _('Y'), 'value': 'Y'},
  4379. {'label': _('Angle'), 'value': 'A'}])
  4380. self.pad_axis_radio.set_value('X')
  4381. self.linear_form.addRow(self.pad_axis_label, self.pad_axis_radio)
  4382. self.pad_pitch_label = QtWidgets.QLabel('%s:' % _('Pitch'))
  4383. self.pad_pitch_label.setToolTip(
  4384. _("Pitch = Distance between elements of the array.")
  4385. )
  4386. self.pad_pitch_label.setMinimumWidth(100)
  4387. self.pad_pitch_entry = FCDoubleSpinner()
  4388. self.pad_pitch_entry.set_precision(self.decimals)
  4389. self.pad_pitch_entry.set_range(0.0000, 10000.0000)
  4390. self.pad_pitch_entry.setSingleStep(0.1)
  4391. self.linear_form.addRow(self.pad_pitch_label, self.pad_pitch_entry)
  4392. self.linear_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  4393. self.linear_angle_label.setToolTip(
  4394. _("Angle at which the linear array is placed.\n"
  4395. "The precision is of max 2 decimals.\n"
  4396. "Min value is: -360.00 degrees.\n"
  4397. "Max value is: 360.00 degrees.")
  4398. )
  4399. self.linear_angle_label.setMinimumWidth(100)
  4400. self.linear_angle_spinner = FCDoubleSpinner()
  4401. self.linear_angle_spinner.set_precision(self.decimals)
  4402. self.linear_angle_spinner.setRange(-360.00, 360.00)
  4403. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  4404. self.array_circular_frame = QtWidgets.QFrame()
  4405. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  4406. self.array_box.addWidget(self.array_circular_frame)
  4407. self.circular_box = QtWidgets.QVBoxLayout()
  4408. self.circular_box.setContentsMargins(0, 0, 0, 0)
  4409. self.array_circular_frame.setLayout(self.circular_box)
  4410. self.pad_direction_label = QtWidgets.QLabel('%s:' % _('Direction'))
  4411. self.pad_direction_label.setToolTip(
  4412. _("Direction for circular array.\n"
  4413. "Can be CW = clockwise or CCW = counter clockwise.")
  4414. )
  4415. self.pad_direction_label.setMinimumWidth(100)
  4416. self.circular_form = QtWidgets.QFormLayout()
  4417. self.circular_box.addLayout(self.circular_form)
  4418. self.pad_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  4419. {'label': _('CCW'), 'value': 'CCW'}])
  4420. self.pad_direction_radio.set_value('CW')
  4421. self.circular_form.addRow(self.pad_direction_label, self.pad_direction_radio)
  4422. self.pad_angle_label = QtWidgets.QLabel('%s:' % _('Angle'))
  4423. self.pad_angle_label.setToolTip(
  4424. _("Angle at which each element in circular array is placed.")
  4425. )
  4426. self.pad_angle_label.setMinimumWidth(100)
  4427. self.pad_angle_entry = FCDoubleSpinner()
  4428. self.pad_angle_entry.set_precision(self.decimals)
  4429. self.pad_angle_entry.set_range(-360.00, 360.00)
  4430. self.pad_angle_entry.setSingleStep(0.1)
  4431. self.circular_form.addRow(self.pad_angle_label, self.pad_angle_entry)
  4432. self.array_circular_frame.hide()
  4433. self.linear_angle_spinner.hide()
  4434. self.linear_angle_label.hide()
  4435. self.array_frame.hide()
  4436. self.custom_box.addStretch()
  4437. layout.addStretch()
  4438. # Editor
  4439. self.exit_editor_button = QtWidgets.QPushButton(_('Exit Editor'))
  4440. self.exit_editor_button.setIcon(QtGui.QIcon(self.app.resource_location + '/power16.png'))
  4441. self.exit_editor_button.setToolTip(
  4442. _("Exit from Editor.")
  4443. )
  4444. self.exit_editor_button.setStyleSheet("""
  4445. QPushButton
  4446. {
  4447. font-weight: bold;
  4448. }
  4449. """)
  4450. layout.addWidget(self.exit_editor_button)
  4451. class TransformEditorTool(AppTool):
  4452. """
  4453. Inputs to specify how to paint the selected polygons.
  4454. """
  4455. toolName = _("Transform Tool")
  4456. rotateName = _("Rotate")
  4457. skewName = _("Skew/Shear")
  4458. scaleName = _("Scale")
  4459. flipName = _("Mirror (Flip)")
  4460. offsetName = _("Offset")
  4461. bufferName = _("Buffer")
  4462. def __init__(self, app, draw_app):
  4463. AppTool.__init__(self, app)
  4464. self.app = app
  4465. self.draw_app = draw_app
  4466. self.decimals = self.app.decimals
  4467. # ## Title
  4468. title_label = QtWidgets.QLabel("%s" % self.toolName)
  4469. title_label.setStyleSheet("""
  4470. QLabel
  4471. {
  4472. font-size: 16px;
  4473. font-weight: bold;
  4474. }
  4475. """)
  4476. self.layout.addWidget(title_label)
  4477. self.layout.addWidget(QtWidgets.QLabel(''))
  4478. # ## Layout
  4479. grid0 = QtWidgets.QGridLayout()
  4480. self.layout.addLayout(grid0)
  4481. grid0.setColumnStretch(0, 0)
  4482. grid0.setColumnStretch(1, 1)
  4483. grid0.setColumnStretch(2, 0)
  4484. grid0.addWidget(QtWidgets.QLabel(''))
  4485. # Reference
  4486. ref_label = QtWidgets.QLabel('%s:' % _("Reference"))
  4487. ref_label.setToolTip(
  4488. _("The reference point for Rotate, Skew, Scale, Mirror.\n"
  4489. "Can be:\n"
  4490. "- Origin -> it is the 0, 0 point\n"
  4491. "- Selection -> the center of the bounding box of the selected objects\n"
  4492. "- Point -> a custom point defined by X,Y coordinates\n"
  4493. "- Min Selection -> the point (minx, miny) of the bounding box of the selection")
  4494. )
  4495. self.ref_combo = FCComboBox()
  4496. self.ref_items = [_("Origin"), _("Selection"), _("Point"), _("Minimum")]
  4497. self.ref_combo.addItems(self.ref_items)
  4498. grid0.addWidget(ref_label, 0, 0)
  4499. grid0.addWidget(self.ref_combo, 0, 1, 1, 2)
  4500. self.point_label = QtWidgets.QLabel('%s:' % _("Value"))
  4501. self.point_label.setToolTip(
  4502. _("A point of reference in format X,Y.")
  4503. )
  4504. self.point_entry = NumericalEvalTupleEntry()
  4505. grid0.addWidget(self.point_label, 1, 0)
  4506. grid0.addWidget(self.point_entry, 1, 1, 1, 2)
  4507. self.point_button = FCButton(_("Add"))
  4508. self.point_button.setToolTip(
  4509. _("Add point coordinates from clipboard.")
  4510. )
  4511. grid0.addWidget(self.point_button, 2, 0, 1, 3)
  4512. separator_line = QtWidgets.QFrame()
  4513. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4514. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4515. grid0.addWidget(separator_line, 5, 0, 1, 3)
  4516. # ## Rotate Title
  4517. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  4518. grid0.addWidget(rotate_title_label, 6, 0, 1, 3)
  4519. self.rotate_label = QtWidgets.QLabel('%s:' % _("Angle"))
  4520. self.rotate_label.setToolTip(
  4521. _("Angle, in degrees.\n"
  4522. "Float number between -360 and 359.\n"
  4523. "Positive numbers for CW motion.\n"
  4524. "Negative numbers for CCW motion.")
  4525. )
  4526. self.rotate_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4527. self.rotate_entry.set_precision(self.decimals)
  4528. self.rotate_entry.setSingleStep(45)
  4529. self.rotate_entry.setWrapping(True)
  4530. self.rotate_entry.set_range(-360, 360)
  4531. # self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4532. self.rotate_button = FCButton(_("Rotate"))
  4533. self.rotate_button.setToolTip(
  4534. _("Rotate the selected object(s).\n"
  4535. "The point of reference is the middle of\n"
  4536. "the bounding box for all selected objects.")
  4537. )
  4538. self.rotate_button.setMinimumWidth(90)
  4539. grid0.addWidget(self.rotate_label, 7, 0)
  4540. grid0.addWidget(self.rotate_entry, 7, 1)
  4541. grid0.addWidget(self.rotate_button, 7, 2)
  4542. separator_line = QtWidgets.QFrame()
  4543. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4544. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4545. grid0.addWidget(separator_line, 8, 0, 1, 3)
  4546. # ## Skew Title
  4547. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  4548. grid0.addWidget(skew_title_label, 9, 0, 1, 2)
  4549. self.skew_link_cb = FCCheckBox()
  4550. self.skew_link_cb.setText(_("Link"))
  4551. self.skew_link_cb.setToolTip(
  4552. _("Link the Y entry to X entry and copy its content.")
  4553. )
  4554. grid0.addWidget(self.skew_link_cb, 9, 2)
  4555. self.skewx_label = QtWidgets.QLabel('%s:' % _("X angle"))
  4556. self.skewx_label.setToolTip(
  4557. _("Angle for Skew action, in degrees.\n"
  4558. "Float number between -360 and 360.")
  4559. )
  4560. self.skewx_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4561. # self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4562. self.skewx_entry.set_precision(self.decimals)
  4563. self.skewx_entry.set_range(-360, 360)
  4564. self.skewx_button = FCButton(_("Skew X"))
  4565. self.skewx_button.setToolTip(
  4566. _("Skew/shear the selected object(s).\n"
  4567. "The point of reference is the middle of\n"
  4568. "the bounding box for all selected objects."))
  4569. self.skewx_button.setMinimumWidth(90)
  4570. grid0.addWidget(self.skewx_label, 10, 0)
  4571. grid0.addWidget(self.skewx_entry, 10, 1)
  4572. grid0.addWidget(self.skewx_button, 10, 2)
  4573. self.skewy_label = QtWidgets.QLabel('%s:' % _("Y angle"))
  4574. self.skewy_label.setToolTip(
  4575. _("Angle for Skew action, in degrees.\n"
  4576. "Float number between -360 and 360.")
  4577. )
  4578. self.skewy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4579. # self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4580. self.skewy_entry.set_precision(self.decimals)
  4581. self.skewy_entry.set_range(-360, 360)
  4582. self.skewy_button = FCButton(_("Skew Y"))
  4583. self.skewy_button.setToolTip(
  4584. _("Skew/shear the selected object(s).\n"
  4585. "The point of reference is the middle of\n"
  4586. "the bounding box for all selected objects."))
  4587. self.skewy_button.setMinimumWidth(90)
  4588. grid0.addWidget(self.skewy_label, 12, 0)
  4589. grid0.addWidget(self.skewy_entry, 12, 1)
  4590. grid0.addWidget(self.skewy_button, 12, 2)
  4591. self.ois_sk = OptionalInputSection(self.skew_link_cb, [self.skewy_label, self.skewy_entry, self.skewy_button],
  4592. logic=False)
  4593. separator_line = QtWidgets.QFrame()
  4594. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4595. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4596. grid0.addWidget(separator_line, 14, 0, 1, 3)
  4597. # ## Scale Title
  4598. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  4599. grid0.addWidget(scale_title_label, 15, 0, 1, 2)
  4600. self.scale_link_cb = FCCheckBox()
  4601. self.scale_link_cb.setText(_("Link"))
  4602. self.scale_link_cb.setToolTip(
  4603. _("Link the Y entry to X entry and copy its content.")
  4604. )
  4605. grid0.addWidget(self.scale_link_cb, 15, 2)
  4606. self.scalex_label = QtWidgets.QLabel('%s:' % _("X factor"))
  4607. self.scalex_label.setToolTip(
  4608. _("Factor for scaling on X axis.")
  4609. )
  4610. self.scalex_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4611. # self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4612. self.scalex_entry.set_precision(self.decimals)
  4613. self.scalex_entry.setMinimum(-1e6)
  4614. self.scalex_button = FCButton(_("Scale X"))
  4615. self.scalex_button.setToolTip(
  4616. _("Scale the selected object(s).\n"
  4617. "The point of reference depends on \n"
  4618. "the Scale reference checkbox state."))
  4619. self.scalex_button.setMinimumWidth(90)
  4620. grid0.addWidget(self.scalex_label, 17, 0)
  4621. grid0.addWidget(self.scalex_entry, 17, 1)
  4622. grid0.addWidget(self.scalex_button, 17, 2)
  4623. self.scaley_label = QtWidgets.QLabel('%s:' % _("Y factor"))
  4624. self.scaley_label.setToolTip(
  4625. _("Factor for scaling on Y axis.")
  4626. )
  4627. self.scaley_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4628. # self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4629. self.scaley_entry.set_precision(self.decimals)
  4630. self.scaley_entry.setMinimum(-1e6)
  4631. self.scaley_button = FCButton(_("Scale Y"))
  4632. self.scaley_button.setToolTip(
  4633. _("Scale the selected object(s).\n"
  4634. "The point of reference depends on \n"
  4635. "the Scale reference checkbox state."))
  4636. self.scaley_button.setMinimumWidth(90)
  4637. grid0.addWidget(self.scaley_label, 19, 0)
  4638. grid0.addWidget(self.scaley_entry, 19, 1)
  4639. grid0.addWidget(self.scaley_button, 19, 2)
  4640. self.ois_s = OptionalInputSection(self.scale_link_cb,
  4641. [
  4642. self.scaley_label,
  4643. self.scaley_entry,
  4644. self.scaley_button
  4645. ], logic=False)
  4646. separator_line = QtWidgets.QFrame()
  4647. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4648. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4649. grid0.addWidget(separator_line, 21, 0, 1, 3)
  4650. # ## Flip Title
  4651. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  4652. grid0.addWidget(flip_title_label, 23, 0, 1, 3)
  4653. self.flipx_button = FCButton(_("Flip on X"))
  4654. self.flipx_button.setToolTip(
  4655. _("Flip the selected object(s) over the X axis.")
  4656. )
  4657. self.flipy_button = FCButton(_("Flip on Y"))
  4658. self.flipy_button.setToolTip(
  4659. _("Flip the selected object(s) over the X axis.")
  4660. )
  4661. hlay0 = QtWidgets.QHBoxLayout()
  4662. grid0.addLayout(hlay0, 25, 0, 1, 3)
  4663. hlay0.addWidget(self.flipx_button)
  4664. hlay0.addWidget(self.flipy_button)
  4665. separator_line = QtWidgets.QFrame()
  4666. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4667. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4668. grid0.addWidget(separator_line, 27, 0, 1, 3)
  4669. # ## Offset Title
  4670. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  4671. grid0.addWidget(offset_title_label, 29, 0, 1, 3)
  4672. self.offx_label = QtWidgets.QLabel('%s:' % _("X val"))
  4673. self.offx_label.setToolTip(
  4674. _("Distance to offset on X axis. In current units.")
  4675. )
  4676. self.offx_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4677. # self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4678. self.offx_entry.set_precision(self.decimals)
  4679. self.offx_entry.setMinimum(-1e6)
  4680. self.offx_button = FCButton(_("Offset X"))
  4681. self.offx_button.setToolTip(
  4682. _("Offset the selected object(s).\n"
  4683. "The point of reference is the middle of\n"
  4684. "the bounding box for all selected objects.\n"))
  4685. self.offx_button.setMinimumWidth(90)
  4686. grid0.addWidget(self.offx_label, 31, 0)
  4687. grid0.addWidget(self.offx_entry, 31, 1)
  4688. grid0.addWidget(self.offx_button, 31, 2)
  4689. self.offy_label = QtWidgets.QLabel('%s:' % _("Y val"))
  4690. self.offy_label.setToolTip(
  4691. _("Distance to offset on Y axis. In current units.")
  4692. )
  4693. self.offy_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4694. # self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  4695. self.offy_entry.set_precision(self.decimals)
  4696. self.offy_entry.setMinimum(-1e6)
  4697. self.offy_button = FCButton(_("Offset Y"))
  4698. self.offy_button.setToolTip(
  4699. _("Offset the selected object(s).\n"
  4700. "The point of reference is the middle of\n"
  4701. "the bounding box for all selected objects.\n"))
  4702. self.offy_button.setMinimumWidth(90)
  4703. grid0.addWidget(self.offy_label, 32, 0)
  4704. grid0.addWidget(self.offy_entry, 32, 1)
  4705. grid0.addWidget(self.offy_button, 32, 2)
  4706. separator_line = QtWidgets.QFrame()
  4707. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  4708. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  4709. grid0.addWidget(separator_line, 34, 0, 1, 3)
  4710. # ## Buffer Title
  4711. buffer_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.bufferName)
  4712. grid0.addWidget(buffer_title_label, 35, 0, 1, 2)
  4713. self.buffer_rounded_cb = FCCheckBox('%s' % _("Rounded"))
  4714. self.buffer_rounded_cb.setToolTip(
  4715. _("If checked then the buffer will surround the buffered shape,\n"
  4716. "every corner will be rounded.\n"
  4717. "If not checked then the buffer will follow the exact geometry\n"
  4718. "of the buffered shape.")
  4719. )
  4720. grid0.addWidget(self.buffer_rounded_cb, 35, 2)
  4721. self.buffer_label = QtWidgets.QLabel('%s:' % _("Distance"))
  4722. self.buffer_label.setToolTip(
  4723. _("A positive value will create the effect of dilation,\n"
  4724. "while a negative value will create the effect of erosion.\n"
  4725. "Each geometry element of the object will be increased\n"
  4726. "or decreased with the 'distance'.")
  4727. )
  4728. self.buffer_entry = FCDoubleSpinner(callback=self.confirmation_message)
  4729. self.buffer_entry.set_precision(self.decimals)
  4730. self.buffer_entry.setSingleStep(0.1)
  4731. self.buffer_entry.setWrapping(True)
  4732. self.buffer_entry.set_range(-10000.0000, 10000.0000)
  4733. self.buffer_button = FCButton(_("Buffer D"))
  4734. self.buffer_button.setToolTip(
  4735. _("Create the buffer effect on each geometry,\n"
  4736. "element from the selected object, using the distance.")
  4737. )
  4738. self.buffer_button.setMinimumWidth(90)
  4739. grid0.addWidget(self.buffer_label, 37, 0)
  4740. grid0.addWidget(self.buffer_entry, 37, 1)
  4741. grid0.addWidget(self.buffer_button, 37, 2)
  4742. self.buffer_factor_label = QtWidgets.QLabel('%s:' % _("Value"))
  4743. self.buffer_factor_label.setToolTip(
  4744. _("A positive value will create the effect of dilation,\n"
  4745. "while a negative value will create the effect of erosion.\n"
  4746. "Each geometry element of the object will be increased\n"
  4747. "or decreased to fit the 'Value'. Value is a percentage\n"
  4748. "of the initial dimension.")
  4749. )
  4750. self.buffer_factor_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  4751. self.buffer_factor_entry.set_range(-100.0000, 1000.0000)
  4752. self.buffer_factor_entry.set_precision(self.decimals)
  4753. self.buffer_factor_entry.setWrapping(True)
  4754. self.buffer_factor_entry.setSingleStep(1)
  4755. self.buffer_factor_button = FCButton(_("Buffer F"))
  4756. self.buffer_factor_button.setToolTip(
  4757. _("Create the buffer effect on each geometry,\n"
  4758. "element from the selected object, using the factor.")
  4759. )
  4760. self.buffer_factor_button.setMinimumWidth(90)
  4761. grid0.addWidget(self.buffer_factor_label, 38, 0)
  4762. grid0.addWidget(self.buffer_factor_entry, 38, 1)
  4763. grid0.addWidget(self.buffer_factor_button, 38, 2)
  4764. grid0.addWidget(QtWidgets.QLabel(''), 42, 0, 1, 3)
  4765. self.layout.addStretch()
  4766. # Signals
  4767. self.ref_combo.currentIndexChanged.connect(self.on_reference_changed)
  4768. self.point_button.clicked.connect(self.on_add_coords)
  4769. self.rotate_button.clicked.connect(self.on_rotate)
  4770. self.skewx_button.clicked.connect(self.on_skewx)
  4771. self.skewy_button.clicked.connect(self.on_skewy)
  4772. self.scalex_button.clicked.connect(self.on_scalex)
  4773. self.scaley_button.clicked.connect(self.on_scaley)
  4774. self.offx_button.clicked.connect(self.on_offx)
  4775. self.offy_button.clicked.connect(self.on_offy)
  4776. self.flipx_button.clicked.connect(self.on_flipx)
  4777. self.flipy_button.clicked.connect(self.on_flipy)
  4778. self.buffer_button.clicked.connect(self.on_buffer_by_distance)
  4779. self.buffer_factor_button.clicked.connect(self.on_buffer_by_factor)
  4780. # self.rotate_entry.editingFinished.connect(self.on_rotate)
  4781. # self.skewx_entry.editingFinished.connect(self.on_skewx)
  4782. # self.skewy_entry.editingFinished.connect(self.on_skewy)
  4783. # self.scalex_entry.editingFinished.connect(self.on_scalex)
  4784. # self.scaley_entry.editingFinished.connect(self.on_scaley)
  4785. # self.offx_entry.editingFinished.connect(self.on_offx)
  4786. # self.offy_entry.editingFinished.connect(self.on_offy)
  4787. self.set_tool_ui()
  4788. def run(self, toggle=True):
  4789. self.app.defaults.report_usage("Gerber Editor Transform Tool()")
  4790. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4791. if self.app.ui.splitter.sizes()[0] == 0:
  4792. self.app.ui.splitter.setSizes([1, 1])
  4793. if toggle:
  4794. try:
  4795. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  4796. self.app.ui.notebook.setCurrentWidget(self.app.ui.properties_tab)
  4797. else:
  4798. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  4799. except AttributeError:
  4800. pass
  4801. AppTool.run(self)
  4802. self.set_tool_ui()
  4803. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  4804. def install(self, icon=None, separator=None, **kwargs):
  4805. AppTool.install(self, icon, separator, shortcut='Alt+T', **kwargs)
  4806. def set_tool_ui(self):
  4807. # Initialize form
  4808. ref_val = self.app.defaults["tools_transform_reference"]
  4809. if ref_val == _("Object"):
  4810. ref_val = _("Selection")
  4811. self.ref_combo.set_value(ref_val)
  4812. self.point_entry.set_value(self.app.defaults["tools_transform_ref_point"])
  4813. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  4814. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  4815. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  4816. self.skew_link_cb.set_value(self.app.defaults["tools_transform_skew_link"])
  4817. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  4818. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  4819. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  4820. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  4821. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  4822. self.buffer_entry.set_value(self.app.defaults["tools_transform_buffer_dis"])
  4823. self.buffer_factor_entry.set_value(self.app.defaults["tools_transform_buffer_factor"])
  4824. self.buffer_rounded_cb.set_value(self.app.defaults["tools_transform_buffer_corner"])
  4825. # initial state is hidden
  4826. self.point_label.hide()
  4827. self.point_entry.hide()
  4828. self.point_button.hide()
  4829. def template(self):
  4830. if not self.draw_app.selected:
  4831. self.draw_app.app.inform.emit('[WARNING_NOTCL] %s %s' % (_("Cancelled."), _("No shape selected.")))
  4832. return
  4833. self.draw_app.select_tool("select")
  4834. self.app.ui.notebook.setTabText(2, "Tools")
  4835. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  4836. self.app.ui.splitter.setSizes([0, 1])
  4837. def on_reference_changed(self, index):
  4838. if index == 0 or index == 1: # "Origin" or "Selection" reference
  4839. self.point_label.hide()
  4840. self.point_entry.hide()
  4841. self.point_button.hide()
  4842. elif index == 2: # "Point" reference
  4843. self.point_label.show()
  4844. self.point_entry.show()
  4845. self.point_button.show()
  4846. def on_calculate_reference(self, ref_index=None):
  4847. if ref_index:
  4848. ref_val = ref_index
  4849. else:
  4850. ref_val = self.ref_combo.currentIndex()
  4851. if ref_val == 0: # "Origin" reference
  4852. return 0, 0
  4853. elif ref_val == 1: # "Selection" reference
  4854. sel_list = self.draw_app.selected
  4855. if sel_list:
  4856. xmin, ymin, xmax, ymax = self.alt_bounds(sel_list)
  4857. px = (xmax + xmin) * 0.5
  4858. py = (ymax + ymin) * 0.5
  4859. return px, py
  4860. else:
  4861. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No shape selected."))
  4862. return "fail"
  4863. elif ref_val == 2: # "Point" reference
  4864. point_val = self.point_entry.get_value()
  4865. try:
  4866. px, py = eval('{}'.format(point_val))
  4867. return px, py
  4868. except Exception:
  4869. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Incorrect format for Point value. Needs format X,Y"))
  4870. return "fail"
  4871. else:
  4872. sel_list = self.draw_app.selected
  4873. if sel_list:
  4874. xmin, ymin, xmax, ymax = self.alt_bounds(sel_list)
  4875. if ref_val == 3:
  4876. return xmin, ymin # lower left corner
  4877. elif ref_val == 4:
  4878. return xmax, ymin # lower right corner
  4879. elif ref_val == 5:
  4880. return xmax, ymax # upper right corner
  4881. else:
  4882. return xmin, ymax # upper left corner
  4883. else:
  4884. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No shape selected."))
  4885. return "fail"
  4886. def on_add_coords(self):
  4887. val = self.app.clipboard.text()
  4888. self.point_entry.set_value(val)
  4889. def on_rotate(self, sig=None, val=None, ref=None):
  4890. value = float(self.rotate_entry.get_value()) if val is None else val
  4891. if value == 0:
  4892. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Rotate transformation can not be done for a value of 0."))
  4893. return
  4894. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4895. if point == 'fail':
  4896. return
  4897. self.app.worker_task.emit({'fcn': self.on_rotate_action, 'params': [value, point]})
  4898. def on_flipx(self, signal=None, ref=None):
  4899. axis = 'Y'
  4900. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4901. if point == 'fail':
  4902. return
  4903. self.app.worker_task.emit({'fcn': self.on_flip, 'params': [axis, point]})
  4904. def on_flipy(self, signal=None, ref=None):
  4905. axis = 'X'
  4906. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4907. if point == 'fail':
  4908. return
  4909. self.app.worker_task.emit({'fcn': self.on_flip, 'params': [axis, point]})
  4910. def on_skewx(self, signal=None, val=None, ref=None):
  4911. xvalue = float(self.skewx_entry.get_value()) if val is None else val
  4912. if xvalue == 0:
  4913. return
  4914. if self.skew_link_cb.get_value():
  4915. yvalue = xvalue
  4916. else:
  4917. yvalue = 0
  4918. axis = 'X'
  4919. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4920. if point == 'fail':
  4921. return
  4922. self.app.worker_task.emit({'fcn': self.on_skew, 'params': [axis, xvalue, yvalue, point]})
  4923. def on_skewy(self, signal=None, val=None, ref=None):
  4924. xvalue = 0
  4925. yvalue = float(self.skewy_entry.get_value()) if val is None else val
  4926. if yvalue == 0:
  4927. return
  4928. axis = 'Y'
  4929. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4930. if point == 'fail':
  4931. return
  4932. self.app.worker_task.emit({'fcn': self.on_skew, 'params': [axis, xvalue, yvalue, point]})
  4933. def on_scalex(self, signal=None, val=None, ref=None):
  4934. xvalue = float(self.scalex_entry.get_value()) if val is None else val
  4935. if xvalue == 0 or xvalue == 1:
  4936. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4937. _("Scale transformation can not be done for a factor of 0 or 1."))
  4938. return
  4939. if self.scale_link_cb.get_value():
  4940. yvalue = xvalue
  4941. else:
  4942. yvalue = 1
  4943. axis = 'X'
  4944. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4945. if point == 'fail':
  4946. return
  4947. self.app.worker_task.emit({'fcn': self.on_scale, 'params': [axis, xvalue, yvalue, point]})
  4948. def on_scaley(self, signal=None, val=None, ref=None):
  4949. xvalue = 1
  4950. yvalue = float(self.scaley_entry.get_value()) if val is None else val
  4951. if yvalue == 0 or yvalue == 1:
  4952. self.app.inform.emit('[WARNING_NOTCL] %s' %
  4953. _("Scale transformation can not be done for a factor of 0 or 1."))
  4954. return
  4955. axis = 'Y'
  4956. point = self.on_calculate_reference() if ref is None else self.on_calculate_reference(ref_index=ref)
  4957. if point == 'fail':
  4958. return
  4959. self.app.worker_task.emit({'fcn': self.on_scale, 'params': [axis, xvalue, yvalue, point]})
  4960. def on_offx(self, signal=None, val=None):
  4961. value = float(self.offx_entry.get_value()) if val is None else val
  4962. if value == 0:
  4963. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Offset transformation can not be done for a value of 0."))
  4964. return
  4965. axis = 'X'
  4966. self.app.worker_task.emit({'fcn': self.on_offset, 'params': [axis, value]})
  4967. def on_offy(self, signal=None, val=None):
  4968. value = float(self.offy_entry.get_value()) if val is None else val
  4969. if value == 0:
  4970. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Offset transformation can not be done for a value of 0."))
  4971. return
  4972. axis = 'Y'
  4973. self.app.worker_task.emit({'fcn': self.on_offset, 'params': [axis, value]})
  4974. def on_buffer_by_distance(self):
  4975. value = self.buffer_entry.get_value()
  4976. join = 1 if self.buffer_rounded_cb.get_value() else 2
  4977. self.app.worker_task.emit({'fcn': self.on_buffer_action, 'params': [value, join]})
  4978. def on_buffer_by_factor(self):
  4979. value = 1 + (self.buffer_factor_entry.get_value() / 100.0)
  4980. join = 1 if self.buffer_rounded_cb.get_value() else 2
  4981. # tell the buffer method to use the factor
  4982. factor = True
  4983. self.app.worker_task.emit({'fcn': self.on_buffer_action, 'params': [value, join, factor]})
  4984. def on_rotate_action(self, val, point):
  4985. """
  4986. Rotate geometry
  4987. :param val: Rotate with a known angle value, val
  4988. :param point: Reference point for rotation: tuple
  4989. :return:
  4990. """
  4991. elem_list = self.draw_app.selected
  4992. px, py = point
  4993. if not elem_list:
  4994. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  4995. return
  4996. with self.app.proc_container.new(_("Appying Rotate")):
  4997. try:
  4998. for sel_el_shape in elem_list:
  4999. sel_el = sel_el_shape.geo
  5000. if 'solid' in sel_el:
  5001. sel_el['solid'] = affinity.rotate(sel_el['solid'], angle=-val, origin=(px, py))
  5002. if 'follow' in sel_el:
  5003. sel_el['follow'] = affinity.rotate(sel_el['follow'], angle=-val, origin=(px, py))
  5004. if 'clear' in sel_el:
  5005. sel_el['clear'] = affinity.rotate(sel_el['clear'], angle=-val, origin=(px, py))
  5006. self.draw_app.plot_all()
  5007. self.app.inform.emit('[success] %s' % _("Done."))
  5008. except Exception as e:
  5009. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5010. return
  5011. def on_flip(self, axis, point):
  5012. """
  5013. Mirror (flip) geometry
  5014. :param axis: Mirror on a known axis given by the axis parameter
  5015. :param point: Mirror reference point
  5016. :return:
  5017. """
  5018. elem_list = self.draw_app.selected
  5019. px, py = point
  5020. if not elem_list:
  5021. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5022. return
  5023. with self.app.proc_container.new(_("Applying Flip")):
  5024. try:
  5025. # execute mirroring
  5026. for sel_el_shape in elem_list:
  5027. sel_el = sel_el_shape.geo
  5028. if axis == 'X':
  5029. if 'solid' in sel_el:
  5030. sel_el['solid'] = affinity.scale(sel_el['solid'], xfact=1, yfact=-1, origin=(px, py))
  5031. if 'follow' in sel_el:
  5032. sel_el['follow'] = affinity.scale(sel_el['follow'], xfact=1, yfact=-1, origin=(px, py))
  5033. if 'clear' in sel_el:
  5034. sel_el['clear'] = affinity.scale(sel_el['clear'], xfact=1, yfact=-1, origin=(px, py))
  5035. self.app.inform.emit('[success] %s...' % _('Flip on Y axis done'))
  5036. elif axis == 'Y':
  5037. if 'solid' in sel_el:
  5038. sel_el['solid'] = affinity.scale(sel_el['solid'], xfact=-1, yfact=1, origin=(px, py))
  5039. if 'follow' in sel_el:
  5040. sel_el['follow'] = affinity.scale(sel_el['follow'], xfact=-1, yfact=1, origin=(px, py))
  5041. if 'clear' in sel_el:
  5042. sel_el['clear'] = affinity.scale(sel_el['clear'], xfact=-1, yfact=1, origin=(px, py))
  5043. self.app.inform.emit('[success] %s...' % _('Flip on X axis done'))
  5044. self.draw_app.plot_all()
  5045. except Exception as e:
  5046. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5047. return
  5048. def on_skew(self, axis, xval, yval, point):
  5049. """
  5050. Skew geometry
  5051. :param axis: Axis on which to deform, skew
  5052. :param xval: Skew value on X axis
  5053. :param yval: Skew value on Y axis
  5054. :param point: Point of reference for deformation: tuple
  5055. :return:
  5056. """
  5057. elem_list = self.draw_app.selected
  5058. px, py = point
  5059. if not elem_list:
  5060. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5061. return
  5062. with self.app.proc_container.new(_("Applying Skew")):
  5063. try:
  5064. for sel_el_shape in elem_list:
  5065. sel_el = sel_el_shape.geo
  5066. if 'solid' in sel_el:
  5067. sel_el['solid'] = affinity.skew(sel_el['solid'], xval, yval, origin=(px, py))
  5068. if 'follow' in sel_el:
  5069. sel_el['follow'] = affinity.skew(sel_el['follow'], xval, yval, origin=(px, py))
  5070. if 'clear' in sel_el:
  5071. sel_el['clear'] = affinity.skew(sel_el['clear'], xval, yval, origin=(px, py))
  5072. self.draw_app.plot_all()
  5073. if str(axis) == 'X':
  5074. self.app.inform.emit('[success] %s...' % _('Skew on the X axis done'))
  5075. else:
  5076. self.app.inform.emit('[success] %s...' % _('Skew on the Y axis done'))
  5077. except Exception as e:
  5078. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5079. return
  5080. def on_scale(self, axis, xfactor, yfactor, point=None):
  5081. """
  5082. Scale geometry
  5083. :param axis: Axis on which to scale
  5084. :param xfactor: Factor for scaling on X axis
  5085. :param yfactor: Factor for scaling on Y axis
  5086. :param point: Point of origin for scaling
  5087. :return:
  5088. """
  5089. elem_list = self.draw_app.selected
  5090. px, py = point
  5091. if not elem_list:
  5092. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5093. return
  5094. else:
  5095. with self.app.proc_container.new(_("Applying Scale")):
  5096. try:
  5097. for sel_el_shape in elem_list:
  5098. sel_el = sel_el_shape.geo
  5099. if 'solid' in sel_el:
  5100. sel_el['solid'] = affinity.scale(sel_el['solid'], xfactor, yfactor, origin=(px, py))
  5101. if 'follow' in sel_el:
  5102. sel_el['follow'] = affinity.scale(sel_el['follow'], xfactor, yfactor, origin=(px, py))
  5103. if 'clear' in sel_el:
  5104. sel_el['clear'] = affinity.scale(sel_el['clear'], xfactor, yfactor, origin=(px, py))
  5105. self.draw_app.plot_all()
  5106. if str(axis) == 'X':
  5107. self.app.inform.emit('[success] %s...' % _('Scale on the X axis done'))
  5108. else:
  5109. self.app.inform.emit('[success] %s...' % _('Scale on the Y axis done'))
  5110. except Exception as e:
  5111. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5112. return
  5113. def on_offset(self, axis, num):
  5114. """
  5115. Offset geometry
  5116. :param axis: Axis on which to apply offset
  5117. :param num: The translation factor
  5118. :return:
  5119. """
  5120. elem_list = self.draw_app.selected
  5121. if not elem_list:
  5122. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5123. return
  5124. with self.app.proc_container.new(_("Applying Offset")):
  5125. try:
  5126. for sel_el_shape in elem_list:
  5127. sel_el = sel_el_shape.geo
  5128. if axis == 'X':
  5129. if 'solid' in sel_el:
  5130. sel_el['solid'] = affinity.translate(sel_el['solid'], num, 0)
  5131. if 'follow' in sel_el:
  5132. sel_el['follow'] = affinity.translate(sel_el['follow'], num, 0)
  5133. if 'clear' in sel_el:
  5134. sel_el['clear'] = affinity.translate(sel_el['clear'], num, 0)
  5135. elif axis == 'Y':
  5136. if 'solid' in sel_el:
  5137. sel_el['solid'] = affinity.translate(sel_el['solid'], 0, num)
  5138. if 'follow' in sel_el:
  5139. sel_el['follow'] = affinity.translate(sel_el['follow'], 0, num)
  5140. if 'clear' in sel_el:
  5141. sel_el['clear'] = affinity.translate(sel_el['clear'], 0, num)
  5142. self.draw_app.plot_all()
  5143. if str(axis) == 'X':
  5144. self.app.inform.emit('[success] %s...' % _('Offset on the X axis done'))
  5145. else:
  5146. self.app.inform.emit('[success] %s...' % _('Offset on the Y axis done'))
  5147. except Exception as e:
  5148. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Action was not executed"), str(e)))
  5149. return
  5150. def on_buffer_action(self, value, join, factor=None):
  5151. elem_list = self.draw_app.selected
  5152. if not elem_list:
  5153. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No shape selected."))
  5154. return
  5155. with self.app.proc_container.new(_("Applying Buffer")):
  5156. try:
  5157. for sel_el_shape in elem_list:
  5158. sel_el = sel_el_shape.geo
  5159. if factor:
  5160. if 'solid' in sel_el:
  5161. sel_el['solid'] = affinity.scale(sel_el['solid'], value, value, origin='center')
  5162. if 'follow' in sel_el:
  5163. sel_el['follow'] = affinity.scale(sel_el['solid'], value, value, origin='center')
  5164. if 'clear' in sel_el:
  5165. sel_el['clear'] = affinity.scale(sel_el['solid'], value, value, origin='center')
  5166. else:
  5167. if 'solid' in sel_el:
  5168. sel_el['solid'] = sel_el['solid'].buffer(
  5169. value, resolution=self.app.defaults["gerber_circle_steps"], join_style=join)
  5170. if 'clear' in sel_el:
  5171. sel_el['clear'] = sel_el['clear'].buffer(
  5172. value, resolution=self.app.defaults["gerber_circle_steps"], join_style=join)
  5173. self.draw_app.plot_all()
  5174. self.app.inform.emit('[success] %s...' % _('Buffer done'))
  5175. except Exception as e:
  5176. self.app.log.debug("TransformEditorTool.on_buffer_action() --> %s" % str(e))
  5177. self.app.inform.emit('[ERROR_NOTCL] %s: %s.' % (_("Action was not executed"), str(e)))
  5178. return
  5179. def on_rotate_key(self):
  5180. val_box = FCInputDialog(title=_("Rotate ..."),
  5181. text='%s:' % _('Enter an Angle Value (degrees)'),
  5182. min=-359.9999, max=360.0000, decimals=self.decimals,
  5183. init_val=float(self.app.defaults['tools_transform_rotate']),
  5184. parent=self.app.ui)
  5185. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/rotate.png'))
  5186. val, ok = val_box.get_value()
  5187. if ok:
  5188. self.on_rotate(val=val, ref=1)
  5189. self.app.inform.emit('[success] %s...' % _("Rotate done"))
  5190. return
  5191. else:
  5192. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Rotate cancelled"))
  5193. def on_offx_key(self):
  5194. units = self.app.defaults['units'].lower()
  5195. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  5196. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  5197. min=-10000.0000, max=10000.0000, decimals=self.decimals,
  5198. init_val=float(self.app.defaults['tools_transform_offset_x']),
  5199. parent=self.app.ui)
  5200. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsetx32.png'))
  5201. val, ok = val_box.get_value()
  5202. if ok:
  5203. self.on_offx(val=val)
  5204. self.app.inform.emit('[success] %s...' % _("Offset on the X axis done"))
  5205. return
  5206. else:
  5207. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Offset X cancelled"))
  5208. def on_offy_key(self):
  5209. units = self.app.defaults['units'].lower()
  5210. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  5211. text='%s: (%s)' % (_('Enter a distance Value'), str(units)),
  5212. min=-10000.0000, max=10000.0000, decimals=self.decimals,
  5213. init_val=float(self.app.defaults['tools_transform_offset_y']),
  5214. parent=self.app.ui)
  5215. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/offsety32.png'))
  5216. val, ok = val_box.get_value()
  5217. if ok:
  5218. self.on_offx(val=val)
  5219. self.app.inform.emit('[success] %s...' % _("Offset on Y axis done"))
  5220. return
  5221. else:
  5222. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Offset Y cancelled"))
  5223. def on_skewx_key(self):
  5224. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  5225. text='%s:' % _('Enter an Angle Value (degrees)'),
  5226. min=-359.9999, max=360.0000, decimals=self.decimals,
  5227. init_val=float(self.app.defaults['tools_transform_skew_x']),
  5228. parent=self.app.ui)
  5229. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewX.png'))
  5230. val, ok = val_box.get_value()
  5231. if ok:
  5232. self.on_skewx(val=val, ref=3)
  5233. self.app.inform.emit('[success] %s...' % _("Skew on X axis done"))
  5234. return
  5235. else:
  5236. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Skew X cancelled"))
  5237. def on_skewy_key(self):
  5238. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  5239. text='%s:' % _('Enter an Angle Value (degrees)'),
  5240. min=-359.9999, max=360.0000, decimals=self.decimals,
  5241. init_val=float(self.app.defaults['tools_transform_skew_y']),
  5242. parent=self.app.ui)
  5243. val_box.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/skewY.png'))
  5244. val, ok = val_box.get_value()
  5245. if ok:
  5246. self.on_skewx(val=val, ref=3)
  5247. self.app.inform.emit('[success] %s...' % _("Skew on Y axis done"))
  5248. return
  5249. else:
  5250. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Skew Y cancelled"))
  5251. @staticmethod
  5252. def alt_bounds(shapelist):
  5253. """
  5254. Returns coordinates of rectangular bounds of a selection of shapes
  5255. """
  5256. def bounds_rec(lst):
  5257. minx = np.Inf
  5258. miny = np.Inf
  5259. maxx = -np.Inf
  5260. maxy = -np.Inf
  5261. try:
  5262. for shape in lst:
  5263. el = shape.geo
  5264. if 'solid' in el:
  5265. minx_, miny_, maxx_, maxy_ = bounds_rec(el['solid'])
  5266. minx = min(minx, minx_)
  5267. miny = min(miny, miny_)
  5268. maxx = max(maxx, maxx_)
  5269. maxy = max(maxy, maxy_)
  5270. return minx, miny, maxx, maxy
  5271. except TypeError:
  5272. # it's an object, return it's bounds
  5273. return lst.bounds
  5274. return bounds_rec(shapelist)
  5275. def get_shapely_list_bounds(geometry_list):
  5276. xmin = np.Inf
  5277. ymin = np.Inf
  5278. xmax = -np.Inf
  5279. ymax = -np.Inf
  5280. for gs in geometry_list:
  5281. try:
  5282. gxmin, gymin, gxmax, gymax = gs.bounds
  5283. xmin = min([xmin, gxmin])
  5284. ymin = min([ymin, gymin])
  5285. xmax = max([xmax, gxmax])
  5286. ymax = max([ymax, gymax])
  5287. except Exception as e:
  5288. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  5289. return [xmin, ymin, xmax, ymax]