FlatCAMEditor.py 247 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from PyQt5 import QtGui, QtCore, QtWidgets
  9. from PyQt5.QtCore import Qt, QSettings
  10. import FlatCAMApp
  11. from camlib import *
  12. from FlatCAMTool import FlatCAMTool
  13. from ObjectUI import LengthEntry, RadioSet
  14. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString
  15. from shapely.geometry import MultiPoint, MultiPolygon
  16. from shapely.geometry import box as shply_box
  17. from shapely.ops import cascaded_union, unary_union
  18. import shapely.affinity as affinity
  19. from shapely.wkt import loads as sloads
  20. from shapely.wkt import dumps as sdumps
  21. from shapely.geometry.base import BaseGeometry
  22. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, sign, dot
  23. from numpy.linalg import solve
  24. from rtree import index as rtindex
  25. from GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCEntry2, FCComboBox, FCTextAreaRich, \
  26. VerticalScrollArea, FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog
  27. from ParseFont import *
  28. from vispy.scene.visuals import Markers
  29. from copy import copy
  30. import freetype as ft
  31. import gettext
  32. import FlatCAMTranslation as fcTranslate
  33. fcTranslate.apply_language('FlatCAMEditor')
  34. class BufferSelectionTool(FlatCAMTool):
  35. """
  36. Simple input for buffer distance.
  37. """
  38. toolName = "Buffer Selection"
  39. def __init__(self, app, draw_app):
  40. FlatCAMTool.__init__(self, app)
  41. self.draw_app = draw_app
  42. # Title
  43. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  44. title_label.setStyleSheet("""
  45. QLabel
  46. {
  47. font-size: 16px;
  48. font-weight: bold;
  49. }
  50. """)
  51. self.layout.addWidget(title_label)
  52. # this way I can hide/show the frame
  53. self.buffer_tool_frame = QtWidgets.QFrame()
  54. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  55. self.layout.addWidget(self.buffer_tool_frame)
  56. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  57. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  58. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  59. # Form Layout
  60. form_layout = QtWidgets.QFormLayout()
  61. self.buffer_tools_box.addLayout(form_layout)
  62. # Buffer distance
  63. self.buffer_distance_entry = FCEntry()
  64. form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  65. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  66. self.buffer_corner_lbl.setToolTip(
  67. _("There are 3 types of corners:\n"
  68. " - 'Round': the corner is rounded for exterior buffer.\n"
  69. " - 'Square:' the corner is met in a sharp angle for exterior buffer.\n"
  70. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  71. )
  72. self.buffer_corner_cb = FCComboBox()
  73. self.buffer_corner_cb.addItem(_("Round"))
  74. self.buffer_corner_cb.addItem(_("Square"))
  75. self.buffer_corner_cb.addItem(_("Beveled"))
  76. form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  77. # Buttons
  78. hlay = QtWidgets.QHBoxLayout()
  79. self.buffer_tools_box.addLayout(hlay)
  80. self.buffer_int_button = QtWidgets.QPushButton(_("Buffer Interior"))
  81. hlay.addWidget(self.buffer_int_button)
  82. self.buffer_ext_button = QtWidgets.QPushButton(_("Buffer Exterior"))
  83. hlay.addWidget(self.buffer_ext_button)
  84. hlay1 = QtWidgets.QHBoxLayout()
  85. self.buffer_tools_box.addLayout(hlay1)
  86. self.buffer_button = QtWidgets.QPushButton(_("Full Buffer"))
  87. hlay1.addWidget(self.buffer_button)
  88. self.layout.addStretch()
  89. # Signals
  90. self.buffer_button.clicked.connect(self.on_buffer)
  91. self.buffer_int_button.clicked.connect(self.on_buffer_int)
  92. self.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  93. # Init GUI
  94. self.buffer_distance_entry.set_value(0.01)
  95. def run(self):
  96. self.app.report_usage("Geo Editor ToolBuffer()")
  97. FlatCAMTool.run(self)
  98. # if the splitter us hidden, display it
  99. if self.app.ui.splitter.sizes()[0] == 0:
  100. self.app.ui.splitter.setSizes([1, 1])
  101. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  102. def on_buffer(self):
  103. try:
  104. buffer_distance = float(self.buffer_distance_entry.get_value())
  105. except ValueError:
  106. # try to convert comma to decimal point. if it's still not working error message and return
  107. try:
  108. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  109. self.buffer_distance_entry.set_value(buffer_distance)
  110. except ValueError:
  111. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  112. "Add it and retry."))
  113. return
  114. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  115. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  116. join_style = self.buffer_corner_cb.currentIndex() + 1
  117. self.draw_app.buffer(buffer_distance, join_style)
  118. def on_buffer_int(self):
  119. try:
  120. buffer_distance = float(self.buffer_distance_entry.get_value())
  121. except ValueError:
  122. # try to convert comma to decimal point. if it's still not working error message and return
  123. try:
  124. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  125. self.buffer_distance_entry.set_value(buffer_distance)
  126. except ValueError:
  127. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  128. "Add it and retry."))
  129. return
  130. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  131. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  132. join_style = self.buffer_corner_cb.currentIndex() + 1
  133. self.draw_app.buffer_int(buffer_distance, join_style)
  134. def on_buffer_ext(self):
  135. try:
  136. buffer_distance = float(self.buffer_distance_entry.get_value())
  137. except ValueError:
  138. # try to convert comma to decimal point. if it's still not working error message and return
  139. try:
  140. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  141. self.buffer_distance_entry.set_value(buffer_distance)
  142. except ValueError:
  143. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  144. "Add it and retry."))
  145. return
  146. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  147. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  148. join_style = self.buffer_corner_cb.currentIndex() + 1
  149. self.draw_app.buffer_ext(buffer_distance, join_style)
  150. def hide_tool(self):
  151. self.buffer_tool_frame.hide()
  152. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  153. class TextInputTool(FlatCAMTool):
  154. """
  155. Simple input for buffer distance.
  156. """
  157. toolName = "Text Input Tool"
  158. def __init__(self, app):
  159. FlatCAMTool.__init__(self, app)
  160. self.app = app
  161. self.text_path = []
  162. self.f_parse = ParseFont(self)
  163. self.f_parse.get_fonts_by_types()
  164. # this way I can hide/show the frame
  165. self.text_tool_frame = QtWidgets.QFrame()
  166. self.text_tool_frame.setContentsMargins(0, 0, 0, 0)
  167. self.layout.addWidget(self.text_tool_frame)
  168. self.text_tools_box = QtWidgets.QVBoxLayout()
  169. self.text_tools_box.setContentsMargins(0, 0, 0, 0)
  170. self.text_tool_frame.setLayout(self.text_tools_box)
  171. # Title
  172. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  173. title_label.setStyleSheet("""
  174. QLabel
  175. {
  176. font-size: 16px;
  177. font-weight: bold;
  178. }
  179. """)
  180. self.text_tools_box.addWidget(title_label)
  181. # Form Layout
  182. self.form_layout = QtWidgets.QFormLayout()
  183. self.text_tools_box.addLayout(self.form_layout)
  184. # Font type
  185. if sys.platform == "win32":
  186. f_current = QtGui.QFont("Arial")
  187. elif sys.platform == "linux":
  188. f_current = QtGui.QFont("FreeMono")
  189. else:
  190. f_current = QtGui.QFont("Helvetica Neue")
  191. self.font_name = f_current.family()
  192. self.font_type_cb = QtWidgets.QFontComboBox(self)
  193. self.font_type_cb.setCurrentFont(f_current)
  194. self.form_layout.addRow("Font:", self.font_type_cb)
  195. # Flag variables to show if font is bold, italic, both or none (regular)
  196. self.font_bold = False
  197. self.font_italic = False
  198. # # Create dictionaries with the filenames of the fonts
  199. # # Key: Fontname
  200. # # Value: Font File Name.ttf
  201. #
  202. # # regular fonts
  203. # self.ff_names_regular ={}
  204. # # bold fonts
  205. # self.ff_names_bold = {}
  206. # # italic fonts
  207. # self.ff_names_italic = {}
  208. # # bold and italic fonts
  209. # self.ff_names_bi = {}
  210. #
  211. # if sys.platform == 'win32':
  212. # from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_LOCAL_MACHINE
  213. # registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
  214. # font_key = OpenKey(registry, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
  215. # try:
  216. # i = 0
  217. # while 1:
  218. # name_font, value, type = EnumValue(font_key, i)
  219. # k = name_font.replace(" (TrueType)", '')
  220. # if 'Bold' in k and 'Italic' in k:
  221. # k = k.replace(" Bold Italic", '')
  222. # self.ff_names_bi.update({k: value})
  223. # elif 'Bold' in k:
  224. # k = k.replace(" Bold", '')
  225. # self.ff_names_bold.update({k: value})
  226. # elif 'Italic' in k:
  227. # k = k.replace(" Italic", '')
  228. # self.ff_names_italic.update({k: value})
  229. # else:
  230. # self.ff_names_regular.update({k: value})
  231. # i += 1
  232. # except WindowsError:
  233. # pass
  234. # Font size
  235. self.font_size_cb = FCComboBox()
  236. self.font_size_cb.setEditable(True)
  237. self.font_size_cb.setMinimumContentsLength(3)
  238. self.font_size_cb.setMaximumWidth(70)
  239. font_sizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14',
  240. '15', '16', '18', '20', '22', '24', '26', '28',
  241. '32', '36', '40', '44', '48', '54', '60', '66',
  242. '72', '80', '88', '96']
  243. for i in font_sizes:
  244. self.font_size_cb.addItem(i)
  245. self.font_size_cb.setCurrentIndex(4)
  246. hlay = QtWidgets.QHBoxLayout()
  247. hlay.addWidget(self.font_size_cb)
  248. hlay.addStretch()
  249. self.font_bold_tb = QtWidgets.QToolButton()
  250. self.font_bold_tb.setCheckable(True)
  251. self.font_bold_tb.setIcon(QtGui.QIcon('share/bold32.png'))
  252. hlay.addWidget(self.font_bold_tb)
  253. self.font_italic_tb = QtWidgets.QToolButton()
  254. self.font_italic_tb.setCheckable(True)
  255. self.font_italic_tb.setIcon(QtGui.QIcon('share/italic32.png'))
  256. hlay.addWidget(self.font_italic_tb)
  257. self.form_layout.addRow("Size:", hlay)
  258. # Text input
  259. self.text_input_entry = FCTextAreaRich()
  260. self.text_input_entry.setTabStopWidth(12)
  261. self.text_input_entry.setMinimumHeight(200)
  262. # self.text_input_entry.setMaximumHeight(150)
  263. self.text_input_entry.setCurrentFont(f_current)
  264. self.text_input_entry.setFontPointSize(10)
  265. self.form_layout.addRow("Text:", self.text_input_entry)
  266. # Buttons
  267. hlay1 = QtWidgets.QHBoxLayout()
  268. self.form_layout.addRow("", hlay1)
  269. hlay1.addStretch()
  270. self.apply_button = QtWidgets.QPushButton("Apply")
  271. hlay1.addWidget(self.apply_button)
  272. # self.layout.addStretch()
  273. # Signals
  274. self.apply_button.clicked.connect(self.on_apply_button)
  275. self.font_type_cb.currentFontChanged.connect(self.font_family)
  276. self.font_size_cb.activated.connect(self.font_size)
  277. self.font_bold_tb.clicked.connect(self.on_bold_button)
  278. self.font_italic_tb.clicked.connect(self.on_italic_button)
  279. def on_apply_button(self):
  280. font_to_geo_type = ""
  281. if self.font_bold is True:
  282. font_to_geo_type = 'bold'
  283. elif self.font_italic is True:
  284. font_to_geo_type = 'italic'
  285. elif self.font_bold is True and self.font_italic is True:
  286. font_to_geo_type = 'bi'
  287. elif self.font_bold is False and self.font_italic is False:
  288. font_to_geo_type = 'regular'
  289. string_to_geo = self.text_input_entry.get_value()
  290. font_to_geo_size = self.font_size_cb.get_value()
  291. self.text_path = self.f_parse.font_to_geometry(
  292. char_string=string_to_geo,
  293. font_name=self.font_name,
  294. font_size=font_to_geo_size,
  295. font_type=font_to_geo_type,
  296. units=self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper())
  297. def font_family(self, font):
  298. self.text_input_entry.selectAll()
  299. font.setPointSize(float(self.font_size_cb.get_value()))
  300. self.text_input_entry.setCurrentFont(font)
  301. self.font_name = self.font_type_cb.currentFont().family()
  302. def font_size(self):
  303. self.text_input_entry.selectAll()
  304. self.text_input_entry.setFontPointSize(float(self.font_size_cb.get_value()))
  305. def on_bold_button(self):
  306. if self.font_bold_tb.isChecked():
  307. self.text_input_entry.selectAll()
  308. self.text_input_entry.setFontWeight(QtGui.QFont.Bold)
  309. self.font_bold = True
  310. else:
  311. self.text_input_entry.selectAll()
  312. self.text_input_entry.setFontWeight(QtGui.QFont.Normal)
  313. self.font_bold = False
  314. def on_italic_button(self):
  315. if self.font_italic_tb.isChecked():
  316. self.text_input_entry.selectAll()
  317. self.text_input_entry.setFontItalic(True)
  318. self.font_italic = True
  319. else:
  320. self.text_input_entry.selectAll()
  321. self.text_input_entry.setFontItalic(False)
  322. self.font_italic = False
  323. def hide_tool(self):
  324. self.text_tool_frame.hide()
  325. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  326. class PaintOptionsTool(FlatCAMTool):
  327. """
  328. Inputs to specify how to paint the selected polygons.
  329. """
  330. toolName = "Paint Tool"
  331. def __init__(self, app, fcdraw):
  332. FlatCAMTool.__init__(self, app)
  333. self.app = app
  334. self.fcdraw = fcdraw
  335. ## Title
  336. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  337. title_label.setStyleSheet("""
  338. QLabel
  339. {
  340. font-size: 16px;
  341. font-weight: bold;
  342. }
  343. """)
  344. self.layout.addWidget(title_label)
  345. grid = QtWidgets.QGridLayout()
  346. self.layout.addLayout(grid)
  347. # Tool dia
  348. ptdlabel = QtWidgets.QLabel(_('Tool dia:'))
  349. ptdlabel.setToolTip(
  350. _( "Diameter of the tool to\n"
  351. "be used in the operation.")
  352. )
  353. grid.addWidget(ptdlabel, 0, 0)
  354. self.painttooldia_entry = FCEntry()
  355. grid.addWidget(self.painttooldia_entry, 0, 1)
  356. # Overlap
  357. ovlabel = QtWidgets.QLabel(_('Overlap:'))
  358. ovlabel.setToolTip(
  359. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  360. "Example:\n"
  361. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  362. "Adjust the value starting with lower values\n"
  363. "and increasing it if areas that should be painted are still \n"
  364. "not painted.\n"
  365. "Lower values = faster processing, faster execution on PCB.\n"
  366. "Higher values = slow processing and slow execution on CNC\n"
  367. "due of too many paths.")
  368. )
  369. grid.addWidget(ovlabel, 1, 0)
  370. self.paintoverlap_entry = FCEntry()
  371. self.paintoverlap_entry.setValidator(QtGui.QDoubleValidator(0.0000, 1.0000, 4))
  372. grid.addWidget(self.paintoverlap_entry, 1, 1)
  373. # Margin
  374. marginlabel = QtWidgets.QLabel(_('Margin:'))
  375. marginlabel.setToolTip(
  376. _( "Distance by which to avoid\n"
  377. "the edges of the polygon to\n"
  378. "be painted.")
  379. )
  380. grid.addWidget(marginlabel, 2, 0)
  381. self.paintmargin_entry = FCEntry()
  382. grid.addWidget(self.paintmargin_entry, 2, 1)
  383. # Method
  384. methodlabel = QtWidgets.QLabel(_('Method:'))
  385. methodlabel.setToolTip(
  386. _("Algorithm to paint the polygon:<BR>"
  387. "<B>Standard</B>: Fixed step inwards.<BR>"
  388. "<B>Seed-based</B>: Outwards from seed.")
  389. )
  390. grid.addWidget(methodlabel, 3, 0)
  391. self.paintmethod_combo = RadioSet([
  392. {"label": _("Standard"), "value": "standard"},
  393. {"label": _("Seed-based"), "value": "seed"},
  394. {"label": _("Straight lines"), "value": "lines"}
  395. ], orientation='vertical', stretch=False)
  396. grid.addWidget(self.paintmethod_combo, 3, 1)
  397. # Connect lines
  398. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  399. pathconnectlabel.setToolTip(
  400. _( "Draw lines between resulting\n"
  401. "segments to minimize tool lifts.")
  402. )
  403. grid.addWidget(pathconnectlabel, 4, 0)
  404. self.pathconnect_cb = FCCheckBox()
  405. grid.addWidget(self.pathconnect_cb, 4, 1)
  406. contourlabel = QtWidgets.QLabel(_("Contour:"))
  407. contourlabel.setToolTip(
  408. _("Cut around the perimeter of the polygon\n"
  409. "to trim rough edges.")
  410. )
  411. grid.addWidget(contourlabel, 5, 0)
  412. self.paintcontour_cb = FCCheckBox()
  413. grid.addWidget(self.paintcontour_cb, 5, 1)
  414. ## Buttons
  415. hlay = QtWidgets.QHBoxLayout()
  416. self.layout.addLayout(hlay)
  417. hlay.addStretch()
  418. self.paint_button = QtWidgets.QPushButton(_("Paint"))
  419. hlay.addWidget(self.paint_button)
  420. self.layout.addStretch()
  421. ## Signals
  422. self.paint_button.clicked.connect(self.on_paint)
  423. self.set_tool_ui()
  424. def run(self):
  425. self.app.report_usage("Geo Editor ToolPaint()")
  426. FlatCAMTool.run(self)
  427. # if the splitter us hidden, display it
  428. if self.app.ui.splitter.sizes()[0] == 0:
  429. self.app.ui.splitter.setSizes([1, 1])
  430. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  431. def set_tool_ui(self):
  432. ## Init GUI
  433. if self.app.defaults["tools_painttooldia"]:
  434. self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
  435. else:
  436. self.painttooldia_entry.set_value(0.0)
  437. if self.app.defaults["tools_paintoverlap"]:
  438. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  439. else:
  440. self.paintoverlap_entry.set_value(0.0)
  441. if self.app.defaults["tools_paintmargin"]:
  442. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  443. else:
  444. self.paintmargin_entry.set_value(0.0)
  445. if self.app.defaults["tools_paintmethod"]:
  446. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  447. else:
  448. self.paintmethod_combo.set_value("seed")
  449. if self.app.defaults["tools_pathconnect"]:
  450. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  451. else:
  452. self.pathconnect_cb.set_value(False)
  453. if self.app.defaults["tools_paintcontour"]:
  454. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  455. else:
  456. self.paintcontour_cb.set_value(False)
  457. def on_paint(self):
  458. if not self.fcdraw.selected:
  459. self.app.inform.emit(_("[WARNING_NOTCL] Paint cancelled. No shape selected."))
  460. return
  461. try:
  462. tooldia = float(self.painttooldia_entry.get_value())
  463. except ValueError:
  464. # try to convert comma to decimal point. if it's still not working error message and return
  465. try:
  466. tooldia = float(self.painttooldia_entry.get_value().replace(',', '.'))
  467. self.painttooldia_entry.set_value(tooldia)
  468. except ValueError:
  469. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  470. "Add it and retry."))
  471. return
  472. try:
  473. overlap = float(self.paintoverlap_entry.get_value())
  474. except ValueError:
  475. # try to convert comma to decimal point. if it's still not working error message and return
  476. try:
  477. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  478. self.paintoverlap_entry.set_value(overlap)
  479. except ValueError:
  480. self.app.inform.emit(_("[WARNING_NOTCL] Overlap value is missing or wrong format. "
  481. "Add it and retry."))
  482. return
  483. try:
  484. margin = float(self.paintmargin_entry.get_value())
  485. except ValueError:
  486. # try to convert comma to decimal point. if it's still not working error message and return
  487. try:
  488. margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  489. self.paintmargin_entry.set_value(margin)
  490. except ValueError:
  491. self.app.inform.emit(_("[WARNING_NOTCL] Margin distance value is missing or wrong format. "
  492. "Add it and retry."))
  493. return
  494. method = self.paintmethod_combo.get_value()
  495. contour = self.paintcontour_cb.get_value()
  496. connect = self.pathconnect_cb.get_value()
  497. self.fcdraw.paint(tooldia, overlap, margin, connect=connect, contour=contour, method=method)
  498. self.fcdraw.select_tool("select")
  499. self.app.ui.notebook.setTabText(2, _("Tools"))
  500. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  501. self.app.ui.splitter.setSizes([0, 1])
  502. class TransformEditorTool(FlatCAMTool):
  503. """
  504. Inputs to specify how to paint the selected polygons.
  505. """
  506. toolName = _("Transform Tool")
  507. rotateName = _("Rotate")
  508. skewName = _("Skew/Shear")
  509. scaleName = _("Scale")
  510. flipName = _("Mirror (Flip)")
  511. offsetName = _("Offset")
  512. def __init__(self, app, draw_app):
  513. FlatCAMTool.__init__(self, app)
  514. self.app = app
  515. self.draw_app = draw_app
  516. self.transform_lay = QtWidgets.QVBoxLayout()
  517. self.layout.addLayout(self.transform_lay)
  518. ## Title
  519. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  520. title_label.setStyleSheet("""
  521. QLabel
  522. {
  523. font-size: 16px;
  524. font-weight: bold;
  525. }
  526. """)
  527. self.transform_lay.addWidget(title_label)
  528. self.empty_label = QtWidgets.QLabel("")
  529. self.empty_label.setFixedWidth(50)
  530. self.empty_label1 = QtWidgets.QLabel("")
  531. self.empty_label1.setFixedWidth(70)
  532. self.empty_label2 = QtWidgets.QLabel("")
  533. self.empty_label2.setFixedWidth(70)
  534. self.empty_label3 = QtWidgets.QLabel("")
  535. self.empty_label3.setFixedWidth(70)
  536. self.empty_label4 = QtWidgets.QLabel("")
  537. self.empty_label4.setFixedWidth(70)
  538. self.transform_lay.addWidget(self.empty_label)
  539. ## Rotate Title
  540. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  541. self.transform_lay.addWidget(rotate_title_label)
  542. ## Layout
  543. form_layout = QtWidgets.QFormLayout()
  544. self.transform_lay.addLayout(form_layout)
  545. form_child = QtWidgets.QHBoxLayout()
  546. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  547. self.rotate_label.setToolTip(
  548. _( "Angle for Rotation action, in degrees.\n"
  549. "Float number between -360 and 359.\n"
  550. "Positive numbers for CW motion.\n"
  551. "Negative numbers for CCW motion.")
  552. )
  553. self.rotate_label.setFixedWidth(50)
  554. self.rotate_entry = FCEntry()
  555. # self.rotate_entry.setFixedWidth(60)
  556. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  557. self.rotate_button = FCButton()
  558. self.rotate_button.set_value(_("Rotate"))
  559. self.rotate_button.setToolTip(
  560. _("Rotate the selected shape(s).\n"
  561. "The point of reference is the middle of\n"
  562. "the bounding box for all selected shapes.")
  563. )
  564. self.rotate_button.setFixedWidth(60)
  565. form_child.addWidget(self.rotate_entry)
  566. form_child.addWidget(self.rotate_button)
  567. form_layout.addRow(self.rotate_label, form_child)
  568. self.transform_lay.addWidget(self.empty_label1)
  569. ## Skew Title
  570. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  571. self.transform_lay.addWidget(skew_title_label)
  572. ## Form Layout
  573. form1_layout = QtWidgets.QFormLayout()
  574. self.transform_lay.addLayout(form1_layout)
  575. form1_child_1 = QtWidgets.QHBoxLayout()
  576. form1_child_2 = QtWidgets.QHBoxLayout()
  577. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  578. self.skewx_label.setToolTip(
  579. _( "Angle for Skew action, in degrees.\n"
  580. "Float number between -360 and 359.")
  581. )
  582. self.skewx_label.setFixedWidth(50)
  583. self.skewx_entry = FCEntry()
  584. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  585. # self.skewx_entry.setFixedWidth(60)
  586. self.skewx_button = FCButton()
  587. self.skewx_button.set_value(_("Skew X"))
  588. self.skewx_button.setToolTip(
  589. _( "Skew/shear the selected shape(s).\n"
  590. "The point of reference is the middle of\n"
  591. "the bounding box for all selected shapes."))
  592. self.skewx_button.setFixedWidth(60)
  593. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  594. self.skewy_label.setToolTip(
  595. _( "Angle for Skew action, in degrees.\n"
  596. "Float number between -360 and 359.")
  597. )
  598. self.skewy_label.setFixedWidth(50)
  599. self.skewy_entry = FCEntry()
  600. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  601. # self.skewy_entry.setFixedWidth(60)
  602. self.skewy_button = FCButton()
  603. self.skewy_button.set_value(_("Skew Y"))
  604. self.skewy_button.setToolTip(
  605. _("Skew/shear the selected shape(s).\n"
  606. "The point of reference is the middle of\n"
  607. "the bounding box for all selected shapes."))
  608. self.skewy_button.setFixedWidth(60)
  609. form1_child_1.addWidget(self.skewx_entry)
  610. form1_child_1.addWidget(self.skewx_button)
  611. form1_child_2.addWidget(self.skewy_entry)
  612. form1_child_2.addWidget(self.skewy_button)
  613. form1_layout.addRow(self.skewx_label, form1_child_1)
  614. form1_layout.addRow(self.skewy_label, form1_child_2)
  615. self.transform_lay.addWidget(self.empty_label2)
  616. ## Scale Title
  617. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  618. self.transform_lay.addWidget(scale_title_label)
  619. ## Form Layout
  620. form2_layout = QtWidgets.QFormLayout()
  621. self.transform_lay.addLayout(form2_layout)
  622. form2_child_1 = QtWidgets.QHBoxLayout()
  623. form2_child_2 = QtWidgets.QHBoxLayout()
  624. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  625. self.scalex_label.setToolTip(
  626. _("Factor for Scale action over X axis.")
  627. )
  628. self.scalex_label.setFixedWidth(50)
  629. self.scalex_entry = FCEntry()
  630. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  631. # self.scalex_entry.setFixedWidth(60)
  632. self.scalex_button = FCButton()
  633. self.scalex_button.set_value(_("Scale X"))
  634. self.scalex_button.setToolTip(
  635. _( "Scale the selected shape(s).\n"
  636. "The point of reference depends on \n"
  637. "the Scale reference checkbox state."))
  638. self.scalex_button.setFixedWidth(60)
  639. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  640. self.scaley_label.setToolTip(
  641. _("Factor for Scale action over Y axis.")
  642. )
  643. self.scaley_label.setFixedWidth(50)
  644. self.scaley_entry = FCEntry()
  645. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  646. # self.scaley_entry.setFixedWidth(60)
  647. self.scaley_button = FCButton()
  648. self.scaley_button.set_value(_("Scale Y"))
  649. self.scaley_button.setToolTip(
  650. _( "Scale the selected shape(s).\n"
  651. "The point of reference depends on \n"
  652. "the Scale reference checkbox state."))
  653. self.scaley_button.setFixedWidth(60)
  654. self.scale_link_cb = FCCheckBox()
  655. self.scale_link_cb.set_value(True)
  656. self.scale_link_cb.setText(_("Link"))
  657. self.scale_link_cb.setToolTip(
  658. _("Scale the selected shape(s)\n"
  659. "using the Scale Factor X for both axis."))
  660. self.scale_link_cb.setFixedWidth(50)
  661. self.scale_zero_ref_cb = FCCheckBox()
  662. self.scale_zero_ref_cb.set_value(True)
  663. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  664. self.scale_zero_ref_cb.setToolTip(
  665. _("Scale the selected shape(s)\n"
  666. "using the origin reference when checked,\n"
  667. "and the center of the biggest bounding box\n"
  668. "of the selected shapes when unchecked."))
  669. form2_child_1.addWidget(self.scalex_entry)
  670. form2_child_1.addWidget(self.scalex_button)
  671. form2_child_2.addWidget(self.scaley_entry)
  672. form2_child_2.addWidget(self.scaley_button)
  673. form2_layout.addRow(self.scalex_label, form2_child_1)
  674. form2_layout.addRow(self.scaley_label, form2_child_2)
  675. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  676. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button], logic=False)
  677. self.transform_lay.addWidget(self.empty_label3)
  678. ## Offset Title
  679. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  680. self.transform_lay.addWidget(offset_title_label)
  681. ## Form Layout
  682. form3_layout = QtWidgets.QFormLayout()
  683. self.transform_lay.addLayout(form3_layout)
  684. form3_child_1 = QtWidgets.QHBoxLayout()
  685. form3_child_2 = QtWidgets.QHBoxLayout()
  686. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  687. self.offx_label.setToolTip(
  688. _("Value for Offset action on X axis.")
  689. )
  690. self.offx_label.setFixedWidth(50)
  691. self.offx_entry = FCEntry()
  692. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  693. # self.offx_entry.setFixedWidth(60)
  694. self.offx_button = FCButton()
  695. self.offx_button.set_value(_("Offset X"))
  696. self.offx_button.setToolTip(
  697. _( "Offset the selected shape(s).\n"
  698. "The point of reference is the middle of\n"
  699. "the bounding box for all selected shapes.\n")
  700. )
  701. self.offx_button.setFixedWidth(60)
  702. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  703. self.offy_label.setToolTip(
  704. _("Value for Offset action on Y axis.")
  705. )
  706. self.offy_label.setFixedWidth(50)
  707. self.offy_entry = FCEntry()
  708. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  709. # self.offy_entry.setFixedWidth(60)
  710. self.offy_button = FCButton()
  711. self.offy_button.set_value(_("Offset Y"))
  712. self.offy_button.setToolTip(
  713. _("Offset the selected shape(s).\n"
  714. "The point of reference is the middle of\n"
  715. "the bounding box for all selected shapes.\n")
  716. )
  717. self.offy_button.setFixedWidth(60)
  718. form3_child_1.addWidget(self.offx_entry)
  719. form3_child_1.addWidget(self.offx_button)
  720. form3_child_2.addWidget(self.offy_entry)
  721. form3_child_2.addWidget(self.offy_button)
  722. form3_layout.addRow(self.offx_label, form3_child_1)
  723. form3_layout.addRow(self.offy_label, form3_child_2)
  724. self.transform_lay.addWidget(self.empty_label4)
  725. ## Flip Title
  726. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  727. self.transform_lay.addWidget(flip_title_label)
  728. ## Form Layout
  729. form4_layout = QtWidgets.QFormLayout()
  730. form4_child_hlay = QtWidgets.QHBoxLayout()
  731. self.transform_lay.addLayout(form4_child_hlay)
  732. self.transform_lay.addLayout(form4_layout)
  733. form4_child_1 = QtWidgets.QHBoxLayout()
  734. self.flipx_button = FCButton()
  735. self.flipx_button.set_value(_("Flip on X"))
  736. self.flipx_button.setToolTip(
  737. _("Flip the selected shape(s) over the X axis.\n"
  738. "Does not create a new shape.")
  739. )
  740. self.flipx_button.setFixedWidth(60)
  741. self.flipy_button = FCButton()
  742. self.flipy_button.set_value(_("Flip on Y"))
  743. self.flipy_button.setToolTip(
  744. _("Flip the selected shape(s) over the X axis.\n"
  745. "Does not create a new shape.")
  746. )
  747. self.flipy_button.setFixedWidth(60)
  748. self.flip_ref_cb = FCCheckBox()
  749. self.flip_ref_cb.set_value(True)
  750. self.flip_ref_cb.setText(_("Ref Pt"))
  751. self.flip_ref_cb.setToolTip(
  752. _("Flip the selected shape(s)\n"
  753. "around the point in Point Entry Field.\n"
  754. "\n"
  755. "The point coordinates can be captured by\n"
  756. "left click on canvas together with pressing\n"
  757. "SHIFT key. \n"
  758. "Then click Add button to insert coordinates.\n"
  759. "Or enter the coords in format (x, y) in the\n"
  760. "Point Entry field and click Flip on X(Y)")
  761. )
  762. self.flip_ref_cb.setFixedWidth(50)
  763. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  764. self.flip_ref_label.setToolTip(
  765. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  766. "The 'x' in (x, y) will be used when using Flip on X and\n"
  767. "the 'y' in (x, y) will be used when using Flip on Y.")
  768. )
  769. self.flip_ref_label.setFixedWidth(50)
  770. self.flip_ref_entry = EvalEntry2("(0, 0)")
  771. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  772. # self.flip_ref_entry.setFixedWidth(60)
  773. self.flip_ref_button = FCButton()
  774. self.flip_ref_button.set_value(_("Add"))
  775. self.flip_ref_button.setToolTip(
  776. _( "The point coordinates can be captured by\n"
  777. "left click on canvas together with pressing\n"
  778. "SHIFT key. Then click Add button to insert.")
  779. )
  780. self.flip_ref_button.setFixedWidth(60)
  781. form4_child_hlay.addStretch()
  782. form4_child_hlay.addWidget(self.flipx_button)
  783. form4_child_hlay.addWidget(self.flipy_button)
  784. form4_child_1.addWidget(self.flip_ref_entry)
  785. form4_child_1.addWidget(self.flip_ref_button)
  786. form4_layout.addRow(self.flip_ref_cb)
  787. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  788. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  789. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  790. self.transform_lay.addStretch()
  791. ## Signals
  792. self.rotate_button.clicked.connect(self.on_rotate)
  793. self.skewx_button.clicked.connect(self.on_skewx)
  794. self.skewy_button.clicked.connect(self.on_skewy)
  795. self.scalex_button.clicked.connect(self.on_scalex)
  796. self.scaley_button.clicked.connect(self.on_scaley)
  797. self.offx_button.clicked.connect(self.on_offx)
  798. self.offy_button.clicked.connect(self.on_offy)
  799. self.flipx_button.clicked.connect(self.on_flipx)
  800. self.flipy_button.clicked.connect(self.on_flipy)
  801. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  802. self.rotate_entry.returnPressed.connect(self.on_rotate)
  803. self.skewx_entry.returnPressed.connect(self.on_skewx)
  804. self.skewy_entry.returnPressed.connect(self.on_skewy)
  805. self.scalex_entry.returnPressed.connect(self.on_scalex)
  806. self.scaley_entry.returnPressed.connect(self.on_scaley)
  807. self.offx_entry.returnPressed.connect(self.on_offx)
  808. self.offy_entry.returnPressed.connect(self.on_offy)
  809. self.set_tool_ui()
  810. def run(self):
  811. self.app.report_usage("Geo Editor Transform Tool()")
  812. FlatCAMTool.run(self)
  813. self.set_tool_ui()
  814. # if the splitter us hidden, display it
  815. if self.app.ui.splitter.sizes()[0] == 0:
  816. self.app.ui.splitter.setSizes([1, 1])
  817. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  818. def install(self, icon=None, separator=None, **kwargs):
  819. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  820. def set_tool_ui(self):
  821. ## Initialize form
  822. if self.app.defaults["tools_transform_rotate"]:
  823. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  824. else:
  825. self.rotate_entry.set_value(0.0)
  826. if self.app.defaults["tools_transform_skew_x"]:
  827. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  828. else:
  829. self.skewx_entry.set_value(0.0)
  830. if self.app.defaults["tools_transform_skew_y"]:
  831. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  832. else:
  833. self.skewy_entry.set_value(0.0)
  834. if self.app.defaults["tools_transform_scale_x"]:
  835. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  836. else:
  837. self.scalex_entry.set_value(1.0)
  838. if self.app.defaults["tools_transform_scale_y"]:
  839. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  840. else:
  841. self.scaley_entry.set_value(1.0)
  842. if self.app.defaults["tools_transform_scale_link"]:
  843. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  844. else:
  845. self.scale_link_cb.set_value(True)
  846. if self.app.defaults["tools_transform_scale_reference"]:
  847. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  848. else:
  849. self.scale_zero_ref_cb.set_value(True)
  850. if self.app.defaults["tools_transform_offset_x"]:
  851. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  852. else:
  853. self.offx_entry.set_value(0.0)
  854. if self.app.defaults["tools_transform_offset_y"]:
  855. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  856. else:
  857. self.offy_entry.set_value(0.0)
  858. if self.app.defaults["tools_transform_mirror_reference"]:
  859. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  860. else:
  861. self.flip_ref_cb.set_value(False)
  862. if self.app.defaults["tools_transform_mirror_point"]:
  863. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  864. else:
  865. self.flip_ref_entry.set_value((0, 0))
  866. def template(self):
  867. if not self.fcdraw.selected:
  868. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  869. return
  870. self.draw_app.select_tool("select")
  871. self.app.ui.notebook.setTabText(2, "Tools")
  872. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  873. self.app.ui.splitter.setSizes([0, 1])
  874. def on_rotate(self, sig=None, val=None):
  875. if val:
  876. value = val
  877. else:
  878. try:
  879. value = float(self.rotate_entry.get_value())
  880. except ValueError:
  881. # try to convert comma to decimal point. if it's still not working error message and return
  882. try:
  883. value = float(self.rotate_entry.get_value().replace(',', '.'))
  884. except ValueError:
  885. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Rotate, "
  886. "use a number."))
  887. return
  888. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  889. 'params': [value]})
  890. # self.on_rotate_action(value)
  891. return
  892. def on_flipx(self):
  893. # self.on_flip("Y")
  894. axis = 'Y'
  895. self.app.worker_task.emit({'fcn': self.on_flip,
  896. 'params': [axis]})
  897. return
  898. def on_flipy(self):
  899. # self.on_flip("X")
  900. axis = 'X'
  901. self.app.worker_task.emit({'fcn': self.on_flip,
  902. 'params': [axis]})
  903. return
  904. def on_flip_add_coords(self):
  905. val = self.app.clipboard.text()
  906. self.flip_ref_entry.set_value(val)
  907. def on_skewx(self, sig=None, val=None):
  908. if val:
  909. value = val
  910. else:
  911. try:
  912. value = float(self.skewx_entry.get_value())
  913. except ValueError:
  914. # try to convert comma to decimal point. if it's still not working error message and return
  915. try:
  916. value = float(self.skewx_entry.get_value().replace(',', '.'))
  917. except ValueError:
  918. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Skew X, "
  919. "use a number."))
  920. return
  921. # self.on_skew("X", value)
  922. axis = 'X'
  923. self.app.worker_task.emit({'fcn': self.on_skew,
  924. 'params': [axis, value]})
  925. return
  926. def on_skewy(self, sig=None, val=None):
  927. if val:
  928. value = val
  929. else:
  930. try:
  931. value = float(self.skewy_entry.get_value())
  932. except ValueError:
  933. # try to convert comma to decimal point. if it's still not working error message and return
  934. try:
  935. value = float(self.skewy_entry.get_value().replace(',', '.'))
  936. except ValueError:
  937. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Skew Y, "
  938. "use a number."))
  939. return
  940. # self.on_skew("Y", value)
  941. axis = 'Y'
  942. self.app.worker_task.emit({'fcn': self.on_skew,
  943. 'params': [axis, value]})
  944. return
  945. def on_scalex(self, sig=None, val=None):
  946. if val:
  947. xvalue = val
  948. else:
  949. try:
  950. xvalue = float(self.scalex_entry.get_value())
  951. except ValueError:
  952. # try to convert comma to decimal point. if it's still not working error message and return
  953. try:
  954. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  955. except ValueError:
  956. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Scale X, "
  957. "use a number."))
  958. return
  959. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  960. if xvalue == 0:
  961. xvalue = 1
  962. if self.scale_link_cb.get_value():
  963. yvalue = xvalue
  964. else:
  965. yvalue = 1
  966. axis = 'X'
  967. point = (0, 0)
  968. if self.scale_zero_ref_cb.get_value():
  969. self.app.worker_task.emit({'fcn': self.on_scale,
  970. 'params': [axis, xvalue, yvalue, point]})
  971. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  972. else:
  973. # self.on_scale("X", xvalue, yvalue)
  974. self.app.worker_task.emit({'fcn': self.on_scale,
  975. 'params': [axis, xvalue, yvalue]})
  976. return
  977. def on_scaley(self, sig=None, val=None):
  978. xvalue = 1
  979. if val:
  980. yvalue = val
  981. else:
  982. try:
  983. yvalue = float(self.scaley_entry.get_value())
  984. except ValueError:
  985. # try to convert comma to decimal point. if it's still not working error message and return
  986. try:
  987. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  988. except ValueError:
  989. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Scale Y, "
  990. "use a number."))
  991. return
  992. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  993. if yvalue == 0:
  994. yvalue = 1
  995. axis = 'Y'
  996. point = (0, 0)
  997. if self.scale_zero_ref_cb.get_value():
  998. self.app.worker_task.emit({'fcn': self.on_scale,
  999. 'params': [axis, xvalue, yvalue, point]})
  1000. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  1001. else:
  1002. # self.on_scale("Y", xvalue, yvalue)
  1003. self.app.worker_task.emit({'fcn': self.on_scale,
  1004. 'params': [axis, xvalue, yvalue]})
  1005. return
  1006. def on_offx(self, sig=None, val=None):
  1007. if val:
  1008. value = val
  1009. else:
  1010. try:
  1011. value = float(self.offx_entry.get_value())
  1012. except ValueError:
  1013. # try to convert comma to decimal point. if it's still not working error message and return
  1014. try:
  1015. value = float(self.offx_entry.get_value().replace(',', '.'))
  1016. except ValueError:
  1017. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Offset X, "
  1018. "use a number."))
  1019. return
  1020. # self.on_offset("X", value)
  1021. axis = 'X'
  1022. self.app.worker_task.emit({'fcn': self.on_offset,
  1023. 'params': [axis, value]})
  1024. return
  1025. def on_offy(self, sig=None, val=None):
  1026. if val:
  1027. value = val
  1028. else:
  1029. try:
  1030. value = float(self.offy_entry.get_value())
  1031. except ValueError:
  1032. # try to convert comma to decimal point. if it's still not working error message and return
  1033. try:
  1034. value = float(self.offy_entry.get_value().replace(',', '.'))
  1035. except ValueError:
  1036. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Offset Y, "
  1037. "use a number."))
  1038. return
  1039. # self.on_offset("Y", value)
  1040. axis = 'Y'
  1041. self.app.worker_task.emit({'fcn': self.on_offset,
  1042. 'params': [axis, value]})
  1043. return
  1044. def on_rotate_action(self, num):
  1045. shape_list = self.draw_app.selected
  1046. xminlist = []
  1047. yminlist = []
  1048. xmaxlist = []
  1049. ymaxlist = []
  1050. if not shape_list:
  1051. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  1052. return
  1053. else:
  1054. with self.app.proc_container.new(_("Appying Rotate")):
  1055. try:
  1056. # first get a bounding box to fit all
  1057. for sha in shape_list:
  1058. xmin, ymin, xmax, ymax = sha.bounds()
  1059. xminlist.append(xmin)
  1060. yminlist.append(ymin)
  1061. xmaxlist.append(xmax)
  1062. ymaxlist.append(ymax)
  1063. # get the minimum x,y and maximum x,y for all objects selected
  1064. xminimal = min(xminlist)
  1065. yminimal = min(yminlist)
  1066. xmaximal = max(xmaxlist)
  1067. ymaximal = max(ymaxlist)
  1068. self.app.progress.emit(20)
  1069. for sel_sha in shape_list:
  1070. px = 0.5 * (xminimal + xmaximal)
  1071. py = 0.5 * (yminimal + ymaximal)
  1072. sel_sha.rotate(-num, point=(px, py))
  1073. self.draw_app.replot()
  1074. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1075. # self.draw_app.transform_complete.emit()
  1076. self.app.inform.emit(_("[success] Done. Rotate completed."))
  1077. self.app.progress.emit(100)
  1078. except Exception as e:
  1079. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  1080. return
  1081. def on_flip(self, axis):
  1082. shape_list = self.draw_app.selected
  1083. xminlist = []
  1084. yminlist = []
  1085. xmaxlist = []
  1086. ymaxlist = []
  1087. if not shape_list:
  1088. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  1089. return
  1090. else:
  1091. with self.app.proc_container.new(_("Applying Flip")):
  1092. try:
  1093. # get mirroring coords from the point entry
  1094. if self.flip_ref_cb.isChecked():
  1095. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1096. # get mirroing coords from the center of an all-enclosing bounding box
  1097. else:
  1098. # first get a bounding box to fit all
  1099. for sha in shape_list:
  1100. xmin, ymin, xmax, ymax = sha.bounds()
  1101. xminlist.append(xmin)
  1102. yminlist.append(ymin)
  1103. xmaxlist.append(xmax)
  1104. ymaxlist.append(ymax)
  1105. # get the minimum x,y and maximum x,y for all objects selected
  1106. xminimal = min(xminlist)
  1107. yminimal = min(yminlist)
  1108. xmaximal = max(xmaxlist)
  1109. ymaximal = max(ymaxlist)
  1110. px = 0.5 * (xminimal + xmaximal)
  1111. py = 0.5 * (yminimal + ymaximal)
  1112. self.app.progress.emit(20)
  1113. # execute mirroring
  1114. for sha in shape_list:
  1115. if axis is 'X':
  1116. sha.mirror('X', (px, py))
  1117. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  1118. elif axis is 'Y':
  1119. sha.mirror('Y', (px, py))
  1120. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  1121. self.draw_app.replot()
  1122. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1123. #
  1124. # self.draw_app.transform_complete.emit()
  1125. self.app.progress.emit(100)
  1126. except Exception as e:
  1127. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  1128. return
  1129. def on_skew(self, axis, num):
  1130. shape_list = self.draw_app.selected
  1131. xminlist = []
  1132. yminlist = []
  1133. if not shape_list:
  1134. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  1135. return
  1136. else:
  1137. with self.app.proc_container.new(_("Applying Skew")):
  1138. try:
  1139. # first get a bounding box to fit all
  1140. for sha in shape_list:
  1141. xmin, ymin, xmax, ymax = sha.bounds()
  1142. xminlist.append(xmin)
  1143. yminlist.append(ymin)
  1144. # get the minimum x,y and maximum x,y for all objects selected
  1145. xminimal = min(xminlist)
  1146. yminimal = min(yminlist)
  1147. self.app.progress.emit(20)
  1148. for sha in shape_list:
  1149. if axis is 'X':
  1150. sha.skew(num, 0, point=(xminimal, yminimal))
  1151. elif axis is 'Y':
  1152. sha.skew(0, num, point=(xminimal, yminimal))
  1153. self.draw_app.replot()
  1154. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1155. #
  1156. # self.draw_app.transform_complete.emit()
  1157. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  1158. self.app.progress.emit(100)
  1159. except Exception as e:
  1160. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  1161. return
  1162. def on_scale(self, axis, xfactor, yfactor, point=None):
  1163. shape_list = self.draw_app.selected
  1164. xminlist = []
  1165. yminlist = []
  1166. xmaxlist = []
  1167. ymaxlist = []
  1168. if not shape_list:
  1169. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  1170. return
  1171. else:
  1172. with self.app.proc_container.new(_("Applying Scale")):
  1173. try:
  1174. # first get a bounding box to fit all
  1175. for sha in shape_list:
  1176. xmin, ymin, xmax, ymax = sha.bounds()
  1177. xminlist.append(xmin)
  1178. yminlist.append(ymin)
  1179. xmaxlist.append(xmax)
  1180. ymaxlist.append(ymax)
  1181. # get the minimum x,y and maximum x,y for all objects selected
  1182. xminimal = min(xminlist)
  1183. yminimal = min(yminlist)
  1184. xmaximal = max(xmaxlist)
  1185. ymaximal = max(ymaxlist)
  1186. self.app.progress.emit(20)
  1187. if point is None:
  1188. px = 0.5 * (xminimal + xmaximal)
  1189. py = 0.5 * (yminimal + ymaximal)
  1190. else:
  1191. px = 0
  1192. py = 0
  1193. for sha in shape_list:
  1194. sha.scale(xfactor, yfactor, point=(px, py))
  1195. self.draw_app.replot()
  1196. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1197. #
  1198. # self.draw_app.transform_complete.emit()
  1199. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  1200. self.app.progress.emit(100)
  1201. except Exception as e:
  1202. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  1203. return
  1204. def on_offset(self, axis, num):
  1205. shape_list = self.draw_app.selected
  1206. xminlist = []
  1207. yminlist = []
  1208. if not shape_list:
  1209. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  1210. return
  1211. else:
  1212. with self.app.proc_container.new(_("Applying Offset")):
  1213. try:
  1214. # first get a bounding box to fit all
  1215. for sha in shape_list:
  1216. xmin, ymin, xmax, ymax = sha.bounds()
  1217. xminlist.append(xmin)
  1218. yminlist.append(ymin)
  1219. # get the minimum x,y and maximum x,y for all objects selected
  1220. xminimal = min(xminlist)
  1221. yminimal = min(yminlist)
  1222. self.app.progress.emit(20)
  1223. for sha in shape_list:
  1224. if axis is 'X':
  1225. sha.offset((num, 0))
  1226. elif axis is 'Y':
  1227. sha.offset((0, num))
  1228. self.draw_app.replot()
  1229. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1230. #
  1231. # self.draw_app.transform_complete.emit()
  1232. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  1233. self.app.progress.emit(100)
  1234. except Exception as e:
  1235. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  1236. return
  1237. def on_rotate_key(self):
  1238. val_box = FCInputDialog(title=_("Rotate ..."),
  1239. text=_('Enter an Angle Value (degrees):'),
  1240. min=-359.9999, max=360.0000, decimals=4,
  1241. init_val=float(self.app.defaults['tools_transform_rotate']))
  1242. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  1243. val, ok = val_box.get_value()
  1244. if ok:
  1245. self.on_rotate(val=val)
  1246. self.app.inform.emit(
  1247. _("[success] Geometry shape rotate done...")
  1248. )
  1249. return
  1250. else:
  1251. self.app.inform.emit(
  1252. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  1253. )
  1254. def on_offx_key(self):
  1255. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1256. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1257. text=(_('Enter a distance Value (%s):') % str(units)),
  1258. min=-9999.9999, max=10000.0000, decimals=4,
  1259. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1260. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  1261. val, ok = val_box.get_value()
  1262. if ok:
  1263. self.on_offx(val=val)
  1264. self.app.inform.emit(
  1265. _("[success] Geometry shape offset on X axis done..."))
  1266. return
  1267. else:
  1268. self.app.inform.emit(
  1269. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  1270. def on_offy_key(self):
  1271. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1272. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1273. text=(_('Enter a distance Value (%s):') % str(units)),
  1274. min=-9999.9999, max=10000.0000, decimals=4,
  1275. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1276. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  1277. val, ok = val_box.get_value()
  1278. if ok:
  1279. self.on_offx(val=val)
  1280. self.app.inform.emit(
  1281. _("[success] Geometry shape offset on Y axis done..."))
  1282. return
  1283. else:
  1284. self.app.inform.emit(
  1285. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  1286. def on_skewx_key(self):
  1287. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1288. text=_('Enter an Angle Value (degrees):'),
  1289. min=-359.9999, max=360.0000, decimals=4,
  1290. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1291. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  1292. val, ok = val_box.get_value()
  1293. if ok:
  1294. self.on_skewx(val=val)
  1295. self.app.inform.emit(
  1296. _("[success] Geometry shape skew on X axis done..."))
  1297. return
  1298. else:
  1299. self.app.inform.emit(
  1300. _( "[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  1301. def on_skewy_key(self):
  1302. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1303. text=_('Enter an Angle Value (degrees):'),
  1304. min=-359.9999, max=360.0000, decimals=4,
  1305. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1306. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  1307. val, ok = val_box.get_value()
  1308. if ok:
  1309. self.on_skewx(val=val)
  1310. self.app.inform.emit(
  1311. _( "[success] Geometry shape skew on Y axis done..."))
  1312. return
  1313. else:
  1314. self.app.inform.emit(
  1315. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))
  1316. class DrawToolShape(object):
  1317. """
  1318. Encapsulates "shapes" under a common class.
  1319. """
  1320. tolerance = None
  1321. @staticmethod
  1322. def get_pts(o):
  1323. """
  1324. Returns a list of all points in the object, where
  1325. the object can be a Polygon, Not a polygon, or a list
  1326. of such. Search is done recursively.
  1327. :param: geometric object
  1328. :return: List of points
  1329. :rtype: list
  1330. """
  1331. pts = []
  1332. ## Iterable: descend into each item.
  1333. try:
  1334. for subo in o:
  1335. pts += DrawToolShape.get_pts(subo)
  1336. ## Non-iterable
  1337. except TypeError:
  1338. if o is not None:
  1339. ## DrawToolShape: descend into .geo.
  1340. if isinstance(o, DrawToolShape):
  1341. pts += DrawToolShape.get_pts(o.geo)
  1342. ## Descend into .exerior and .interiors
  1343. elif type(o) == Polygon:
  1344. pts += DrawToolShape.get_pts(o.exterior)
  1345. for i in o.interiors:
  1346. pts += DrawToolShape.get_pts(i)
  1347. elif type(o) == MultiLineString:
  1348. for line in o:
  1349. pts += DrawToolShape.get_pts(line)
  1350. ## Has .coords: list them.
  1351. else:
  1352. if DrawToolShape.tolerance is not None:
  1353. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1354. else:
  1355. pts += list(o.coords)
  1356. else:
  1357. return
  1358. return pts
  1359. def __init__(self, geo=[]):
  1360. # Shapely type or list of such
  1361. self.geo = geo
  1362. self.utility = False
  1363. def get_all_points(self):
  1364. return DrawToolShape.get_pts(self)
  1365. def bounds(self):
  1366. """
  1367. Returns coordinates of rectangular bounds
  1368. of geometry: (xmin, ymin, xmax, ymax).
  1369. """
  1370. # fixed issue of getting bounds only for one level lists of objects
  1371. # now it can get bounds for nested lists of objects
  1372. def bounds_rec(shape):
  1373. if type(shape) is list:
  1374. minx = Inf
  1375. miny = Inf
  1376. maxx = -Inf
  1377. maxy = -Inf
  1378. for k in shape:
  1379. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1380. minx = min(minx, minx_)
  1381. miny = min(miny, miny_)
  1382. maxx = max(maxx, maxx_)
  1383. maxy = max(maxy, maxy_)
  1384. return minx, miny, maxx, maxy
  1385. else:
  1386. # it's a Shapely object, return it's bounds
  1387. return shape.bounds
  1388. bounds_coords = bounds_rec(self.geo)
  1389. return bounds_coords
  1390. def mirror(self, axis, point):
  1391. """
  1392. Mirrors the shape around a specified axis passing through
  1393. the given point.
  1394. :param axis: "X" or "Y" indicates around which axis to mirror.
  1395. :type axis: str
  1396. :param point: [x, y] point belonging to the mirror axis.
  1397. :type point: list
  1398. :return: None
  1399. """
  1400. px, py = point
  1401. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1402. def mirror_geom(shape):
  1403. if type(shape) is list:
  1404. new_obj = []
  1405. for g in shape:
  1406. new_obj.append(mirror_geom(g))
  1407. return new_obj
  1408. else:
  1409. return affinity.scale(shape, xscale, yscale, origin=(px,py))
  1410. try:
  1411. self.geo = mirror_geom(self.geo)
  1412. except AttributeError:
  1413. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1414. def rotate(self, angle, point):
  1415. """
  1416. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1417. Parameters
  1418. ----------
  1419. The angle of rotation are specified in degrees (default). Positive angles are
  1420. counter-clockwise and negative are clockwise rotations.
  1421. The point of origin can be a keyword 'center' for the bounding box
  1422. center (default), 'centroid' for the geometry's centroid, a Point object
  1423. or a coordinate tuple (x0, y0).
  1424. See shapely manual for more information:
  1425. http://toblerity.org/shapely/manual.html#affine-transformations
  1426. """
  1427. px, py = point
  1428. def rotate_geom(shape):
  1429. if type(shape) is list:
  1430. new_obj = []
  1431. for g in shape:
  1432. new_obj.append(rotate_geom(g))
  1433. return new_obj
  1434. else:
  1435. return affinity.rotate(shape, angle, origin=(px, py))
  1436. try:
  1437. self.geo = rotate_geom(self.geo)
  1438. except AttributeError:
  1439. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1440. def skew(self, angle_x, angle_y, point):
  1441. """
  1442. Shear/Skew a shape by angles along x and y dimensions.
  1443. Parameters
  1444. ----------
  1445. angle_x, angle_y : float, float
  1446. The shear angle(s) for the x and y axes respectively. These can be
  1447. specified in either degrees (default) or radians by setting
  1448. use_radians=True.
  1449. point: tuple of coordinates (x,y)
  1450. See shapely manual for more information:
  1451. http://toblerity.org/shapely/manual.html#affine-transformations
  1452. """
  1453. px, py = point
  1454. def skew_geom(shape):
  1455. if type(shape) is list:
  1456. new_obj = []
  1457. for g in shape:
  1458. new_obj.append(skew_geom(g))
  1459. return new_obj
  1460. else:
  1461. return affinity.skew(shape, angle_x, angle_y, origin=(px, py))
  1462. try:
  1463. self.geo = skew_geom(self.geo)
  1464. except AttributeError:
  1465. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1466. def offset(self, vect):
  1467. """
  1468. Offsets all shapes by a given vector/
  1469. :param vect: (x, y) vector by which to offset the shape geometry
  1470. :type vect: tuple
  1471. :return: None
  1472. :rtype: None
  1473. """
  1474. try:
  1475. dx, dy = vect
  1476. except TypeError:
  1477. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1478. "Probable you entered only one value in the Offset field.")
  1479. return
  1480. def translate_recursion(geom):
  1481. if type(geom) == list:
  1482. geoms=list()
  1483. for local_geom in geom:
  1484. geoms.append(translate_recursion(local_geom))
  1485. return geoms
  1486. else:
  1487. return affinity.translate(geom, xoff=dx, yoff=dy)
  1488. try:
  1489. self.geo = translate_recursion(self.geo)
  1490. except AttributeError:
  1491. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1492. def scale(self, xfactor, yfactor=None, point=None):
  1493. """
  1494. Scales all shape geometry by a given factor.
  1495. :param xfactor: Factor by which to scale the shape's geometry/
  1496. :type xfactor: float
  1497. :param yfactor: Factor by which to scale the shape's geometry/
  1498. :type yfactor: float
  1499. :return: None
  1500. :rtype: None
  1501. """
  1502. try:
  1503. xfactor = float(xfactor)
  1504. except:
  1505. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1506. return
  1507. if yfactor is None:
  1508. yfactor = xfactor
  1509. else:
  1510. try:
  1511. yfactor = float(yfactor)
  1512. except:
  1513. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1514. return
  1515. if point is None:
  1516. px = 0
  1517. py = 0
  1518. else:
  1519. px, py = point
  1520. def scale_recursion(geom):
  1521. if type(geom) == list:
  1522. geoms=list()
  1523. for local_geom in geom:
  1524. geoms.append(scale_recursion(local_geom))
  1525. return geoms
  1526. else:
  1527. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1528. try:
  1529. self.geo = scale_recursion(self.geo)
  1530. except AttributeError:
  1531. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1532. class DrawToolUtilityShape(DrawToolShape):
  1533. """
  1534. Utility shapes are temporary geometry in the editor
  1535. to assist in the creation of shapes. For example it
  1536. will show the outline of a rectangle from the first
  1537. point to the current mouse pointer before the second
  1538. point is clicked and the final geometry is created.
  1539. """
  1540. def __init__(self, geo=[]):
  1541. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1542. self.utility = True
  1543. class DrawTool(object):
  1544. """
  1545. Abstract Class representing a tool in the drawing
  1546. program. Can generate geometry, including temporary
  1547. utility geometry that is updated on user clicks
  1548. and mouse motion.
  1549. """
  1550. def __init__(self, draw_app):
  1551. self.draw_app = draw_app
  1552. self.complete = False
  1553. self.start_msg = "Click on 1st point..."
  1554. self.points = []
  1555. self.geometry = None # DrawToolShape or None
  1556. def click(self, point):
  1557. """
  1558. :param point: [x, y] Coordinate pair.
  1559. """
  1560. return ""
  1561. def click_release(self, point):
  1562. """
  1563. :param point: [x, y] Coordinate pair.
  1564. """
  1565. return ""
  1566. def on_key(self, key):
  1567. return None
  1568. def utility_geometry(self, data=None):
  1569. return None
  1570. class FCShapeTool(DrawTool):
  1571. """
  1572. Abstract class for tools that create a shape.
  1573. """
  1574. def __init__(self, draw_app):
  1575. DrawTool.__init__(self, draw_app)
  1576. def make(self):
  1577. pass
  1578. class FCCircle(FCShapeTool):
  1579. """
  1580. Resulting type: Polygon
  1581. """
  1582. def __init__(self, draw_app):
  1583. DrawTool.__init__(self, draw_app)
  1584. self.name = 'circle'
  1585. self.start_msg = _("Click on CENTER ...")
  1586. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1587. def click(self, point):
  1588. self.points.append(point)
  1589. if len(self.points) == 1:
  1590. self.draw_app.app.inform.emit(_("Click on Circle perimeter point to complete ..."))
  1591. return "Click on perimeter to complete ..."
  1592. if len(self.points) == 2:
  1593. self.make()
  1594. return "Done."
  1595. return ""
  1596. def utility_geometry(self, data=None):
  1597. if len(self.points) == 1:
  1598. p1 = self.points[0]
  1599. p2 = data
  1600. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1601. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1602. return None
  1603. def make(self):
  1604. p1 = self.points[0]
  1605. p2 = self.points[1]
  1606. radius = distance(p1, p2)
  1607. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1608. self.complete = True
  1609. self.draw_app.app.inform.emit(_("[success]Done. Adding Circle completed."))
  1610. class FCArc(FCShapeTool):
  1611. def __init__(self, draw_app):
  1612. DrawTool.__init__(self, draw_app)
  1613. self.name = 'arc'
  1614. self.start_msg = _("Click on CENTER ...")
  1615. # Direction of rotation between point 1 and 2.
  1616. # 'cw' or 'ccw'. Switch direction by hitting the
  1617. # 'o' key.
  1618. self.direction = "cw"
  1619. # Mode
  1620. # C12 = Center, p1, p2
  1621. # 12C = p1, p2, Center
  1622. # 132 = p1, p3, p2
  1623. self.mode = "c12" # Center, p1, p2
  1624. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1625. def click(self, point):
  1626. self.points.append(point)
  1627. if len(self.points) == 1:
  1628. self.draw_app.app.inform.emit(_("Click on Start arc point ..."))
  1629. return "Click on 1st point ..."
  1630. if len(self.points) == 2:
  1631. self.draw_app.app.inform.emit(_("Click on End arc point to complete ..."))
  1632. return "Click on 2nd point to complete ..."
  1633. if len(self.points) == 3:
  1634. self.make()
  1635. return "Done."
  1636. return ""
  1637. def on_key(self, key):
  1638. if key == 'o':
  1639. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1640. return 'Direction: ' + self.direction.upper()
  1641. if key == 'p':
  1642. if self.mode == 'c12':
  1643. self.mode = '12c'
  1644. elif self.mode == '12c':
  1645. self.mode = '132'
  1646. else:
  1647. self.mode = 'c12'
  1648. return 'Mode: ' + self.mode
  1649. def utility_geometry(self, data=None):
  1650. if len(self.points) == 1: # Show the radius
  1651. center = self.points[0]
  1652. p1 = data
  1653. return DrawToolUtilityShape(LineString([center, p1]))
  1654. if len(self.points) == 2: # Show the arc
  1655. if self.mode == 'c12':
  1656. center = self.points[0]
  1657. p1 = self.points[1]
  1658. p2 = data
  1659. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1660. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1661. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1662. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1663. self.direction, self.steps_per_circ)),
  1664. Point(center)])
  1665. elif self.mode == '132':
  1666. p1 = array(self.points[0])
  1667. p3 = array(self.points[1])
  1668. p2 = array(data)
  1669. center, radius, t = three_point_circle(p1, p2, p3)
  1670. direction = 'cw' if sign(t) > 0 else 'ccw'
  1671. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1672. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1673. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1674. direction, self.steps_per_circ)),
  1675. Point(center), Point(p1), Point(p3)])
  1676. else: # '12c'
  1677. p1 = array(self.points[0])
  1678. p2 = array(self.points[1])
  1679. # Midpoint
  1680. a = (p1 + p2) / 2.0
  1681. # Parallel vector
  1682. c = p2 - p1
  1683. # Perpendicular vector
  1684. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1685. b /= norm(b)
  1686. # Distance
  1687. t = distance(data, a)
  1688. # Which side? Cross product with c.
  1689. # cross(M-A, B-A), where line is AB and M is test point.
  1690. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1691. t *= sign(side)
  1692. # Center = a + bt
  1693. center = a + b * t
  1694. radius = norm(center - p1)
  1695. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1696. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1697. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1698. self.direction, self.steps_per_circ)),
  1699. Point(center)])
  1700. return None
  1701. def make(self):
  1702. if self.mode == 'c12':
  1703. center = self.points[0]
  1704. p1 = self.points[1]
  1705. p2 = self.points[2]
  1706. radius = distance(center, p1)
  1707. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1708. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1709. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1710. self.direction, self.steps_per_circ)))
  1711. elif self.mode == '132':
  1712. p1 = array(self.points[0])
  1713. p3 = array(self.points[1])
  1714. p2 = array(self.points[2])
  1715. center, radius, t = three_point_circle(p1, p2, p3)
  1716. direction = 'cw' if sign(t) > 0 else 'ccw'
  1717. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1718. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1719. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1720. direction, self.steps_per_circ)))
  1721. else: # self.mode == '12c'
  1722. p1 = array(self.points[0])
  1723. p2 = array(self.points[1])
  1724. pc = array(self.points[2])
  1725. # Midpoint
  1726. a = (p1 + p2) / 2.0
  1727. # Parallel vector
  1728. c = p2 - p1
  1729. # Perpendicular vector
  1730. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1731. b /= norm(b)
  1732. # Distance
  1733. t = distance(pc, a)
  1734. # Which side? Cross product with c.
  1735. # cross(M-A, B-A), where line is AB and M is test point.
  1736. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1737. t *= sign(side)
  1738. # Center = a + bt
  1739. center = a + b * t
  1740. radius = norm(center - p1)
  1741. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1742. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1743. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1744. self.direction, self.steps_per_circ)))
  1745. self.complete = True
  1746. self.draw_app.app.inform.emit(_("[success]Done. Arc completed."))
  1747. class FCRectangle(FCShapeTool):
  1748. """
  1749. Resulting type: Polygon
  1750. """
  1751. def __init__(self, draw_app):
  1752. DrawTool.__init__(self, draw_app)
  1753. self.name = 'rectangle'
  1754. self.start_msg = _("Click on 1st corner ...")
  1755. def click(self, point):
  1756. self.points.append(point)
  1757. if len(self.points) == 1:
  1758. return "Click on opposite corner to complete ..."
  1759. if len(self.points) == 2:
  1760. self.make()
  1761. return "Done."
  1762. return ""
  1763. def utility_geometry(self, data=None):
  1764. if len(self.points) == 1:
  1765. p1 = self.points[0]
  1766. p2 = data
  1767. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1768. return None
  1769. def make(self):
  1770. p1 = self.points[0]
  1771. p2 = self.points[1]
  1772. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1773. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1774. self.complete = True
  1775. self.draw_app.app.inform.emit("_([success]Done. Rectangle completed.")
  1776. class FCPolygon(FCShapeTool):
  1777. """
  1778. Resulting type: Polygon
  1779. """
  1780. def __init__(self, draw_app):
  1781. DrawTool.__init__(self, draw_app)
  1782. self.name = 'polygon'
  1783. self.start_msg = _("Click on 1st point ...")
  1784. def click(self, point):
  1785. self.draw_app.in_action = True
  1786. self.points.append(point)
  1787. if len(self.points) > 0:
  1788. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  1789. return "Click on next point or hit ENTER to complete ..."
  1790. return ""
  1791. def utility_geometry(self, data=None):
  1792. if len(self.points) == 1:
  1793. temp_points = [x for x in self.points]
  1794. temp_points.append(data)
  1795. return DrawToolUtilityShape(LineString(temp_points))
  1796. if len(self.points) > 1:
  1797. temp_points = [x for x in self.points]
  1798. temp_points.append(data)
  1799. return DrawToolUtilityShape(LinearRing(temp_points))
  1800. return None
  1801. def make(self):
  1802. # self.geometry = LinearRing(self.points)
  1803. self.geometry = DrawToolShape(Polygon(self.points))
  1804. self.draw_app.in_action = False
  1805. self.complete = True
  1806. self.draw_app.app.inform.emit(_("[success]Done. Polygon completed."))
  1807. def on_key(self, key):
  1808. if key == 'backspace':
  1809. if len(self.points) > 0:
  1810. self.points = self.points[0:-1]
  1811. class FCPath(FCPolygon):
  1812. """
  1813. Resulting type: LineString
  1814. """
  1815. def make(self):
  1816. self.geometry = DrawToolShape(LineString(self.points))
  1817. self.name = 'path'
  1818. self.draw_app.in_action = False
  1819. self.complete = True
  1820. self.draw_app.app.inform.emit(_("[success]Done. Path completed."))
  1821. def utility_geometry(self, data=None):
  1822. if len(self.points) > 0:
  1823. temp_points = [x for x in self.points]
  1824. temp_points.append(data)
  1825. return DrawToolUtilityShape(LineString(temp_points))
  1826. return None
  1827. def on_key(self, key):
  1828. if key == 'backspace':
  1829. if len(self.points) > 0:
  1830. self.points = self.points[0:-1]
  1831. class FCSelect(DrawTool):
  1832. def __init__(self, draw_app):
  1833. DrawTool.__init__(self, draw_app)
  1834. self.name = 'select'
  1835. self.storage = self.draw_app.storage
  1836. # self.shape_buffer = self.draw_app.shape_buffer
  1837. # self.selected = self.draw_app.selected
  1838. def click_release(self, point):
  1839. self.select_shapes(point)
  1840. return ""
  1841. def select_shapes(self, pos):
  1842. # list where we store the overlapped shapes under our mouse left click position
  1843. over_shape_list = []
  1844. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1845. for obj_shape in self.storage.get_objects():
  1846. # first method of click selection -> inconvenient
  1847. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1848. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1849. # over_shape_list.append(obj_shape)
  1850. # second method of click selection -> slow
  1851. # outside = obj_shape.geo.buffer(0.1)
  1852. # inside = obj_shape.geo.buffer(-0.1)
  1853. # shape_band = outside.difference(inside)
  1854. # if Point(pos).within(shape_band):
  1855. # over_shape_list.append(obj_shape)
  1856. # 3rd method of click selection -> inconvenient
  1857. try:
  1858. _, closest_shape = self.storage.nearest(pos)
  1859. except StopIteration:
  1860. return ""
  1861. over_shape_list.append(closest_shape)
  1862. try:
  1863. # if there is no shape under our click then deselect all shapes
  1864. # it will not work for 3rd method of click selection
  1865. if not over_shape_list:
  1866. self.draw_app.selected = []
  1867. FlatCAMGeoEditor.draw_shape_idx = -1
  1868. else:
  1869. # if there are shapes under our click then advance through the list of them, one at the time in a
  1870. # circular way
  1871. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  1872. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  1873. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1874. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  1875. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1876. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1877. if key_modifier == Qt.ControlModifier:
  1878. if obj_to_add in self.draw_app.selected:
  1879. self.draw_app.selected.remove(obj_to_add)
  1880. else:
  1881. self.draw_app.selected.append(obj_to_add)
  1882. else:
  1883. self.draw_app.selected = []
  1884. self.draw_app.selected.append(obj_to_add)
  1885. else:
  1886. if key_modifier == Qt.ShiftModifier:
  1887. if obj_to_add in self.draw_app.selected:
  1888. self.draw_app.selected.remove(obj_to_add)
  1889. else:
  1890. self.draw_app.selected.append(obj_to_add)
  1891. else:
  1892. self.draw_app.selected = []
  1893. self.draw_app.selected.append(obj_to_add)
  1894. except Exception as e:
  1895. log.error("[ERROR] Something went bad. %s" % str(e))
  1896. raise
  1897. class FCDrillSelect(DrawTool):
  1898. def __init__(self, exc_editor_app):
  1899. DrawTool.__init__(self, exc_editor_app)
  1900. self.name = 'drill_select'
  1901. self.exc_editor_app = exc_editor_app
  1902. self.storage = self.exc_editor_app.storage_dict
  1903. # self.selected = self.exc_editor_app.selected
  1904. # here we store all shapes that were selected so we can search for the nearest to our click location
  1905. self.sel_storage = FlatCAMExcEditor.make_storage()
  1906. self.exc_editor_app.resize_frame.hide()
  1907. self.exc_editor_app.array_frame.hide()
  1908. def click(self, point):
  1909. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1910. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1911. if key_modifier == Qt.ControlModifier:
  1912. pass
  1913. else:
  1914. self.exc_editor_app.selected = []
  1915. else:
  1916. if key_modifier == Qt.ShiftModifier:
  1917. pass
  1918. else:
  1919. self.exc_editor_app.selected = []
  1920. def click_release(self, point):
  1921. self.select_shapes(point)
  1922. return ""
  1923. def select_shapes(self, pos):
  1924. self.exc_editor_app.tools_table_exc.clearSelection()
  1925. try:
  1926. # for storage in self.exc_editor_app.storage_dict:
  1927. # _, partial_closest_shape = self.exc_editor_app.storage_dict[storage].nearest(pos)
  1928. # if partial_closest_shape is not None:
  1929. # self.sel_storage.insert(partial_closest_shape)
  1930. #
  1931. # _, closest_shape = self.sel_storage.nearest(pos)
  1932. for storage in self.exc_editor_app.storage_dict:
  1933. for shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1934. self.sel_storage.insert(shape)
  1935. _, closest_shape = self.sel_storage.nearest(pos)
  1936. # constrain selection to happen only within a certain bounding box
  1937. x_coord, y_coord = closest_shape.geo[0].xy
  1938. delta = (x_coord[1] - x_coord[0])
  1939. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  1940. xmin = x_coord[0] - (0.7 * delta)
  1941. xmax = x_coord[0] + (1.7 * delta)
  1942. ymin = y_coord[0] - (0.7 * delta)
  1943. ymax = y_coord[0] + (1.7 * delta)
  1944. except StopIteration:
  1945. return ""
  1946. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  1947. self.exc_editor_app.selected = []
  1948. else:
  1949. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1950. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1951. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1952. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1953. if key_modifier == Qt.ControlModifier:
  1954. if closest_shape in self.exc_editor_app.selected:
  1955. self.exc_editor_app.selected.remove(closest_shape)
  1956. else:
  1957. self.exc_editor_app.selected.append(closest_shape)
  1958. else:
  1959. self.exc_editor_app.selected = []
  1960. self.exc_editor_app.selected.append(closest_shape)
  1961. else:
  1962. if key_modifier == Qt.ShiftModifier:
  1963. if closest_shape in self.exc_editor_app.selected:
  1964. self.exc_editor_app.selected.remove(closest_shape)
  1965. else:
  1966. self.exc_editor_app.selected.append(closest_shape)
  1967. else:
  1968. self.exc_editor_app.selected = []
  1969. self.exc_editor_app.selected.append(closest_shape)
  1970. # select the diameter of the selected shape in the tool table
  1971. for storage in self.exc_editor_app.storage_dict:
  1972. for shape_s in self.exc_editor_app.selected:
  1973. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  1974. for key in self.exc_editor_app.tool2tooldia:
  1975. if self.exc_editor_app.tool2tooldia[key] == storage:
  1976. item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1977. self.exc_editor_app.tools_table_exc.setCurrentItem(item)
  1978. # item.setSelected(True)
  1979. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1980. # midx = self.exc_editor_app.tools_table_exc.model().index((key - 1), 0)
  1981. # self.exc_editor_app.tools_table_exc.setCurrentIndex(midx)
  1982. self.draw_app.last_tool_selected = key
  1983. # delete whatever is in selection storage, there is no longer need for those shapes
  1984. self.sel_storage = FlatCAMExcEditor.make_storage()
  1985. return ""
  1986. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1987. # for storage in self.exc_editor_app.storage_dict:
  1988. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1989. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1990. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1991. # over_shape_list.append(obj_shape)
  1992. #
  1993. # try:
  1994. # # if there is no shape under our click then deselect all shapes
  1995. # if not over_shape_list:
  1996. # self.exc_editor_app.selected = []
  1997. # FlatCAMExcEditor.draw_shape_idx = -1
  1998. # self.exc_editor_app.tools_table_exc.clearSelection()
  1999. # else:
  2000. # # if there are shapes under our click then advance through the list of them, one at the time in a
  2001. # # circular way
  2002. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  2003. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  2004. #
  2005. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  2006. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  2007. # if obj_to_add in self.exc_editor_app.selected:
  2008. # self.exc_editor_app.selected.remove(obj_to_add)
  2009. # else:
  2010. # self.exc_editor_app.selected.append(obj_to_add)
  2011. # else:
  2012. # self.exc_editor_app.selected = []
  2013. # self.exc_editor_app.selected.append(obj_to_add)
  2014. # else:
  2015. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  2016. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  2017. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  2018. # if obj_to_add in self.exc_editor_app.selected:
  2019. # self.exc_editor_app.selected.remove(obj_to_add)
  2020. # else:
  2021. # self.exc_editor_app.selected.append(obj_to_add)
  2022. # else:
  2023. # self.exc_editor_app.selected = []
  2024. # self.exc_editor_app.selected.append(obj_to_add)
  2025. #
  2026. # for storage in self.exc_editor_app.storage_dict:
  2027. # for shape in self.exc_editor_app.selected:
  2028. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  2029. # for key in self.exc_editor_app.tool2tooldia:
  2030. # if self.exc_editor_app.tool2tooldia[key] == storage:
  2031. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  2032. # item.setSelected(True)
  2033. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  2034. #
  2035. # except Exception as e:
  2036. # log.error("[ERROR] Something went bad. %s" % str(e))
  2037. # raise
  2038. class FCMove(FCShapeTool):
  2039. def __init__(self, draw_app):
  2040. FCShapeTool.__init__(self, draw_app)
  2041. self.name = 'move'
  2042. # self.shape_buffer = self.draw_app.shape_buffer
  2043. if not self.draw_app.selected:
  2044. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2045. return
  2046. self.origin = None
  2047. self.destination = None
  2048. self.start_msg = _("Click on reference point.")
  2049. def set_origin(self, origin):
  2050. self.draw_app.app.inform.emit(_("Click on destination point."))
  2051. self.origin = origin
  2052. def click(self, point):
  2053. if len(self.draw_app.get_selected()) == 0:
  2054. return "Nothing to move."
  2055. if self.origin is None:
  2056. self.set_origin(point)
  2057. return "Click on final location."
  2058. else:
  2059. self.destination = point
  2060. self.make()
  2061. return "Done."
  2062. def make(self):
  2063. # Create new geometry
  2064. dx = self.destination[0] - self.origin[0]
  2065. dy = self.destination[1] - self.origin[1]
  2066. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2067. for geom in self.draw_app.get_selected()]
  2068. # Delete old
  2069. self.draw_app.delete_selected()
  2070. # # Select the new
  2071. # for g in self.geometry:
  2072. # # Note that g is not in the app's buffer yet!
  2073. # self.draw_app.set_selected(g)
  2074. self.complete = True
  2075. self.draw_app.app.inform.emit(_("[success]Done. Geometry(s) Move completed."))
  2076. def utility_geometry(self, data=None):
  2077. """
  2078. Temporary geometry on screen while using this tool.
  2079. :param data:
  2080. :return:
  2081. """
  2082. geo_list = []
  2083. if self.origin is None:
  2084. return None
  2085. if len(self.draw_app.get_selected()) == 0:
  2086. return None
  2087. dx = data[0] - self.origin[0]
  2088. dy = data[1] - self.origin[1]
  2089. try:
  2090. for geom in self.draw_app.get_selected():
  2091. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2092. except AttributeError:
  2093. self.draw_app.select_tool('select')
  2094. self.draw_app.selected = []
  2095. return
  2096. return DrawToolUtilityShape(geo_list)
  2097. # return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  2098. # for geom in self.draw_app.get_selected()])
  2099. class FCCopy(FCMove):
  2100. def __init__(self, draw_app):
  2101. FCMove.__init__(self, draw_app)
  2102. self.name = 'copy'
  2103. def make(self):
  2104. # Create new geometry
  2105. dx = self.destination[0] - self.origin[0]
  2106. dy = self.destination[1] - self.origin[1]
  2107. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2108. for geom in self.draw_app.get_selected()]
  2109. self.complete = True
  2110. self.draw_app.app.inform.emit(_("[success]Done. Geometry(s) Copy completed."))
  2111. class FCText(FCShapeTool):
  2112. def __init__(self, draw_app):
  2113. FCShapeTool.__init__(self, draw_app)
  2114. self.name = 'text'
  2115. # self.shape_buffer = self.draw_app.shape_buffer
  2116. self.draw_app = draw_app
  2117. self.app = draw_app.app
  2118. self.start_msg = _("Click on the Destination point...")
  2119. self.origin = (0, 0)
  2120. self.text_gui = TextInputTool(self.app)
  2121. self.text_gui.run()
  2122. def click(self, point):
  2123. # Create new geometry
  2124. dx = point[0]
  2125. dy = point[1]
  2126. try:
  2127. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2128. except Exception as e:
  2129. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2130. self.draw_app.app.inform.emit(_("[ERROR]Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2131. "supported. Error: %s") % str(e))
  2132. self.text_gui.text_path = []
  2133. self.text_gui.hide_tool()
  2134. self.draw_app.select_tool('select')
  2135. return
  2136. self.text_gui.text_path = []
  2137. self.text_gui.hide_tool()
  2138. self.complete = True
  2139. self.draw_app.app.inform.emit(_("[success]Done. Adding Text completed."))
  2140. def utility_geometry(self, data=None):
  2141. """
  2142. Temporary geometry on screen while using this tool.
  2143. :param data: mouse position coords
  2144. :return:
  2145. """
  2146. dx = data[0] - self.origin[0]
  2147. dy = data[1] - self.origin[1]
  2148. try:
  2149. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2150. except:
  2151. return
  2152. class FCBuffer(FCShapeTool):
  2153. def __init__(self, draw_app):
  2154. FCShapeTool.__init__(self, draw_app)
  2155. self.name = 'buffer'
  2156. # self.shape_buffer = self.draw_app.shape_buffer
  2157. self.draw_app = draw_app
  2158. self.app = draw_app.app
  2159. self.start_msg = _("Create buffer geometry ...")
  2160. self.origin = (0, 0)
  2161. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2162. self.buff_tool.run()
  2163. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2164. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2165. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2166. self.activate()
  2167. def on_buffer(self):
  2168. if not self.draw_app.selected:
  2169. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2170. return
  2171. try:
  2172. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2173. except ValueError:
  2174. # try to convert comma to decimal point. if it's still not working error message and return
  2175. try:
  2176. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2177. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2178. except ValueError:
  2179. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2180. "Add it and retry."))
  2181. return
  2182. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2183. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2184. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2185. self.draw_app.buffer(buffer_distance, join_style)
  2186. self.app.ui.notebook.setTabText(2, _("Tools"))
  2187. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2188. self.disactivate()
  2189. self.draw_app.app.inform.emit(_("[success]Done. Buffer Tool completed."))
  2190. def on_buffer_int(self):
  2191. if not self.draw_app.selected:
  2192. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2193. return
  2194. try:
  2195. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2196. except ValueError:
  2197. # try to convert comma to decimal point. if it's still not working error message and return
  2198. try:
  2199. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2200. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2201. except ValueError:
  2202. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2203. "Add it and retry."))
  2204. return
  2205. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2206. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2207. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2208. self.draw_app.buffer_int(buffer_distance, join_style)
  2209. self.app.ui.notebook.setTabText(2, _("Tools"))
  2210. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2211. self.disactivate()
  2212. self.draw_app.app.inform.emit(_("[success]Done. Buffer Int Tool completed."))
  2213. def on_buffer_ext(self):
  2214. if not self.draw_app.selected:
  2215. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2216. return
  2217. try:
  2218. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2219. except ValueError:
  2220. # try to convert comma to decimal point. if it's still not working error message and return
  2221. try:
  2222. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2223. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2224. except ValueError:
  2225. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2226. "Add it and retry."))
  2227. return
  2228. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2229. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2230. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2231. self.draw_app.buffer_ext(buffer_distance, join_style)
  2232. self.app.ui.notebook.setTabText(2, _("Tools"))
  2233. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2234. self.disactivate()
  2235. self.draw_app.app.inform.emit(_("[success]Done. Buffer Ext Tool completed."))
  2236. def activate(self):
  2237. self.buff_tool.buffer_button.clicked.disconnect()
  2238. self.buff_tool.buffer_int_button.clicked.disconnect()
  2239. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2240. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2241. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2242. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2243. def disactivate(self):
  2244. self.buff_tool.buffer_button.clicked.disconnect()
  2245. self.buff_tool.buffer_int_button.clicked.disconnect()
  2246. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2247. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2248. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2249. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2250. self.complete = True
  2251. self.draw_app.select_tool("select")
  2252. self.buff_tool.hide_tool()
  2253. class FCPaint(FCShapeTool):
  2254. def __init__(self, draw_app):
  2255. FCShapeTool.__init__(self, draw_app)
  2256. self.name = 'paint'
  2257. # self.shape_buffer = self.draw_app.shape_buffer
  2258. self.draw_app = draw_app
  2259. self.app = draw_app.app
  2260. self.start_msg = _("Create Paint geometry ...")
  2261. self.origin = (0, 0)
  2262. self.draw_app.paint_tool.run()
  2263. class FCTransform(FCShapeTool):
  2264. def __init__(self, draw_app):
  2265. FCShapeTool.__init__(self, draw_app)
  2266. self.name = 'transformation'
  2267. # self.shape_buffer = self.draw_app.shape_buffer
  2268. self.draw_app = draw_app
  2269. self.app = draw_app.app
  2270. self.start_msg = _("Shape transformations ...")
  2271. self.origin = (0, 0)
  2272. self.draw_app.transform_tool.run()
  2273. class FCDrillAdd(FCShapeTool):
  2274. """
  2275. Resulting type: MultiLineString
  2276. """
  2277. def __init__(self, draw_app):
  2278. DrawTool.__init__(self, draw_app)
  2279. self.name = 'drill_add'
  2280. self.selected_dia = None
  2281. try:
  2282. self.draw_app.app.inform.emit(self.start_msg)
  2283. # self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.tools_table_exc.currentRow() + 1]
  2284. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  2285. # as a visual marker, select again in tooltable the actual tool that we are using
  2286. # remember that it was deselected when clicking on canvas
  2287. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  2288. self.draw_app.tools_table_exc.setCurrentItem(item)
  2289. except KeyError:
  2290. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  2291. self.draw_app.select_tool("select")
  2292. return
  2293. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  2294. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2295. self.draw_app.draw_utility_geometry(geo=geo)
  2296. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2297. # Switch notebook to Selected page
  2298. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2299. def click(self, point):
  2300. self.make()
  2301. return "Done."
  2302. def utility_geometry(self, data=None):
  2303. self.points = data
  2304. return DrawToolUtilityShape(self.util_shape(data))
  2305. def util_shape(self, point):
  2306. if point[0] is None and point[1] is None:
  2307. point_x = self.draw_app.x
  2308. point_y = self.draw_app.y
  2309. else:
  2310. point_x = point[0]
  2311. point_y = point[1]
  2312. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  2313. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  2314. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  2315. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  2316. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2317. def make(self):
  2318. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  2319. # to the value, as a list of itself
  2320. if self.selected_dia in self.draw_app.points_edit:
  2321. self.draw_app.points_edit[self.selected_dia].append(self.points)
  2322. else:
  2323. self.draw_app.points_edit[self.selected_dia] = [self.points]
  2324. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  2325. self.geometry = DrawToolShape(self.util_shape(self.points))
  2326. self.complete = True
  2327. self.draw_app.app.inform.emit(_("[success]Done. Drill added."))
  2328. class FCDrillArray(FCShapeTool):
  2329. """
  2330. Resulting type: MultiLineString
  2331. """
  2332. def __init__(self, draw_app):
  2333. DrawTool.__init__(self, draw_app)
  2334. self.name = 'drill_array'
  2335. self.draw_app.array_frame.show()
  2336. self.selected_dia = None
  2337. self.drill_axis = 'X'
  2338. self.drill_array = 'linear'
  2339. self.drill_array_size = None
  2340. self.drill_pitch = None
  2341. self.drill_linear_angle = None
  2342. self.drill_angle = None
  2343. self.drill_direction = None
  2344. self.drill_radius = None
  2345. self.origin = None
  2346. self.destination = None
  2347. self.flag_for_circ_array = None
  2348. self.last_dx = 0
  2349. self.last_dy = 0
  2350. self.pt = []
  2351. try:
  2352. self.draw_app.app.inform.emit(self.start_msg)
  2353. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  2354. # as a visual marker, select again in tooltable the actual tool that we are using
  2355. # remember that it was deselected when clicking on canvas
  2356. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  2357. self.draw_app.tools_table_exc.setCurrentItem(item)
  2358. except KeyError:
  2359. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  2360. return
  2361. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  2362. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2363. self.draw_app.draw_utility_geometry(geo=geo)
  2364. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2365. # Switch notebook to Selected page
  2366. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2367. def click(self, point):
  2368. if self.drill_array == 'Linear':
  2369. self.make()
  2370. return
  2371. else:
  2372. if self.flag_for_circ_array is None:
  2373. self.draw_app.in_action = True
  2374. self.pt.append(point)
  2375. self.flag_for_circ_array = True
  2376. self.set_origin(point)
  2377. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  2378. else:
  2379. self.destination = point
  2380. self.make()
  2381. self.flag_for_circ_array = None
  2382. return
  2383. def set_origin(self, origin):
  2384. self.origin = origin
  2385. def utility_geometry(self, data=None, static=None):
  2386. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  2387. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  2388. self.drill_array = self.draw_app.array_type_combo.get_value()
  2389. try:
  2390. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  2391. try:
  2392. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  2393. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  2394. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  2395. except TypeError:
  2396. self.draw_app.app.inform.emit(
  2397. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  2398. return
  2399. except Exception as e:
  2400. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  2401. return
  2402. if self.drill_array == 'Linear':
  2403. if data[0] is None and data[1] is None:
  2404. dx = self.draw_app.x
  2405. dy = self.draw_app.y
  2406. else:
  2407. dx = data[0]
  2408. dy = data[1]
  2409. geo_list = []
  2410. geo = None
  2411. self.points = [dx, dy]
  2412. for item in range(self.drill_array_size):
  2413. if self.drill_axis == 'X':
  2414. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  2415. if self.drill_axis == 'Y':
  2416. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  2417. if self.drill_axis == 'A':
  2418. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  2419. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  2420. geo = self.util_shape(
  2421. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  2422. )
  2423. if static is None or static is False:
  2424. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  2425. else:
  2426. geo_list.append(geo)
  2427. # self.origin = data
  2428. self.last_dx = dx
  2429. self.last_dy = dy
  2430. return DrawToolUtilityShape(geo_list)
  2431. else:
  2432. if data[0] is None and data[1] is None:
  2433. cdx = self.draw_app.x
  2434. cdy = self.draw_app.y
  2435. else:
  2436. cdx = data[0]
  2437. cdy = data[1]
  2438. if len(self.pt) > 0:
  2439. temp_points = [x for x in self.pt]
  2440. temp_points.append([cdx, cdy])
  2441. return DrawToolUtilityShape(LineString(temp_points))
  2442. def util_shape(self, point):
  2443. if point[0] is None and point[1] is None:
  2444. point_x = self.draw_app.x
  2445. point_y = self.draw_app.y
  2446. else:
  2447. point_x = point[0]
  2448. point_y = point[1]
  2449. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  2450. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  2451. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  2452. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  2453. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2454. def make(self):
  2455. self.geometry = []
  2456. geo = None
  2457. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  2458. # to the value, as a list of itself
  2459. if self.selected_dia not in self.draw_app.points_edit:
  2460. self.draw_app.points_edit[self.selected_dia] = []
  2461. for i in range(self.drill_array_size):
  2462. self.draw_app.points_edit[self.selected_dia].append(self.points)
  2463. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  2464. if self.drill_array == 'Linear':
  2465. for item in range(self.drill_array_size):
  2466. if self.drill_axis == 'X':
  2467. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  2468. if self.drill_axis == 'Y':
  2469. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  2470. if self.drill_axis == 'A':
  2471. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  2472. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  2473. geo = self.util_shape(
  2474. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  2475. )
  2476. self.geometry.append(DrawToolShape(geo))
  2477. else:
  2478. if (self.drill_angle * self.drill_array_size) > 360:
  2479. self.draw_app.app.inform.emit(_("[WARNING_NOTCL]Too many drills for the selected spacing angle."))
  2480. return
  2481. radius = distance(self.destination, self.origin)
  2482. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  2483. for i in range(self.drill_array_size):
  2484. angle_radians = math.radians(self.drill_angle * i)
  2485. if self.drill_direction == 'CW':
  2486. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  2487. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  2488. else:
  2489. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  2490. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  2491. geo = self.util_shape((x, y))
  2492. self.geometry.append(DrawToolShape(geo))
  2493. self.complete = True
  2494. self.draw_app.app.inform.emit(_("[success]Done. Drill Array added."))
  2495. self.draw_app.in_action = True
  2496. self.draw_app.array_frame.hide()
  2497. return
  2498. class FCDrillResize(FCShapeTool):
  2499. def __init__(self, draw_app):
  2500. DrawTool.__init__(self, draw_app)
  2501. self.name = 'drill_resize'
  2502. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  2503. self.resize_dia = None
  2504. self.draw_app.resize_frame.show()
  2505. self.points = None
  2506. self.selected_dia_list = []
  2507. self.current_storage = None
  2508. self.geometry = []
  2509. self.destination_storage = None
  2510. self.draw_app.resize_btn.clicked.connect(self.make)
  2511. # Switch notebook to Selected page
  2512. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2513. def make(self):
  2514. self.draw_app.is_modified = True
  2515. try:
  2516. new_dia = self.draw_app.resdrill_entry.get_value()
  2517. except:
  2518. self.draw_app.app.inform.emit(_("[ERROR_NOTCL]Resize drill(s) failed. Please enter a diameter for resize."))
  2519. return
  2520. if new_dia not in self.draw_app.olddia_newdia:
  2521. self.destination_storage = FlatCAMGeoEditor.make_storage()
  2522. self.draw_app.storage_dict[new_dia] = self.destination_storage
  2523. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  2524. # each time a tool diameter is edited or added
  2525. self.draw_app.olddia_newdia[new_dia] = new_dia
  2526. else:
  2527. self.destination_storage = self.draw_app.storage_dict[new_dia]
  2528. for index in self.draw_app.tools_table_exc.selectedIndexes():
  2529. row = index.row()
  2530. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  2531. # therefore below we convert to float
  2532. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  2533. self.selected_dia_list.append(float(dia_on_row))
  2534. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  2535. # we add a new entry in the tool2tooldia dict
  2536. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  2537. sel_shapes_to_be_deleted = []
  2538. for sel_dia in self.selected_dia_list:
  2539. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2540. for select_shape in self.draw_app.get_selected():
  2541. if select_shape in self.current_storage.get_objects():
  2542. factor = new_dia / sel_dia
  2543. self.geometry.append(
  2544. DrawToolShape(affinity.scale(select_shape.geo, xfact=factor, yfact=factor, origin='center'))
  2545. )
  2546. self.current_storage.remove(select_shape)
  2547. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  2548. # self.points_edit it's only useful first time when we load the data into the storage
  2549. # but is still used as reference when building tool_table in self.build_ui()
  2550. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2551. # deleting self.points_edit elements (doesn't matter who but just the number)
  2552. # solved the display issue.
  2553. del self.draw_app.points_edit[sel_dia][0]
  2554. sel_shapes_to_be_deleted.append(select_shape)
  2555. self.draw_app.on_exc_shape_complete(self.destination_storage)
  2556. # a hack to make the tool_table display more drills per diameter when shape(drill) is added
  2557. # self.points_edit it's only useful first time when we load the data into the storage
  2558. # but is still used as reference when building tool_table in self.build_ui()
  2559. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2560. # deleting self.points_edit elements (doesn't matter who but just the number)
  2561. # solved the display issue.
  2562. if new_dia not in self.draw_app.points_edit:
  2563. self.draw_app.points_edit[new_dia] = [(0, 0)]
  2564. else:
  2565. self.draw_app.points_edit[new_dia].append((0,0))
  2566. self.geometry = []
  2567. # if following the resize of the drills there will be no more drills for the selected tool then
  2568. # delete that tool
  2569. if not self.draw_app.points_edit[sel_dia]:
  2570. self.draw_app.on_tool_delete(sel_dia)
  2571. for shp in sel_shapes_to_be_deleted:
  2572. self.draw_app.selected.remove(shp)
  2573. sel_shapes_to_be_deleted = []
  2574. self.draw_app.build_ui()
  2575. self.draw_app.replot()
  2576. self.draw_app.resize_frame.hide()
  2577. self.complete = True
  2578. self.draw_app.app.inform.emit(_("[success]Done. Drill Resize completed."))
  2579. # MS: always return to the Select Tool
  2580. self.draw_app.select_tool("select")
  2581. class FCDrillMove(FCShapeTool):
  2582. def __init__(self, draw_app):
  2583. DrawTool.__init__(self, draw_app)
  2584. self.name = 'drill_move'
  2585. # self.shape_buffer = self.draw_app.shape_buffer
  2586. self.origin = None
  2587. self.destination = None
  2588. self.selected_dia_list = []
  2589. if self.draw_app.launched_from_shortcuts is True:
  2590. self.draw_app.launched_from_shortcuts = False
  2591. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2592. else:
  2593. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  2594. self.current_storage = None
  2595. self.geometry = []
  2596. for index in self.draw_app.tools_table_exc.selectedIndexes():
  2597. row = index.row()
  2598. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  2599. # therefore below we convert to float
  2600. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  2601. self.selected_dia_list.append(float(dia_on_row))
  2602. # Switch notebook to Selected page
  2603. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2604. def set_origin(self, origin):
  2605. self.origin = origin
  2606. def click(self, point):
  2607. if len(self.draw_app.get_selected()) == 0:
  2608. return "Nothing to move."
  2609. if self.origin is None:
  2610. self.set_origin(point)
  2611. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2612. return
  2613. else:
  2614. self.destination = point
  2615. self.make()
  2616. # MS: always return to the Select Tool
  2617. self.draw_app.select_tool("select")
  2618. return
  2619. def make(self):
  2620. # Create new geometry
  2621. dx = self.destination[0] - self.origin[0]
  2622. dy = self.destination[1] - self.origin[1]
  2623. sel_shapes_to_be_deleted = []
  2624. for sel_dia in self.selected_dia_list:
  2625. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2626. for select_shape in self.draw_app.get_selected():
  2627. if select_shape in self.current_storage.get_objects():
  2628. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  2629. self.current_storage.remove(select_shape)
  2630. sel_shapes_to_be_deleted.append(select_shape)
  2631. self.draw_app.on_exc_shape_complete(self.current_storage)
  2632. self.geometry = []
  2633. for shp in sel_shapes_to_be_deleted:
  2634. self.draw_app.selected.remove(shp)
  2635. sel_shapes_to_be_deleted = []
  2636. self.draw_app.build_ui()
  2637. self.draw_app.app.inform.emit(_("[success]Done. Drill(s) Move completed."))
  2638. def utility_geometry(self, data=None):
  2639. """
  2640. Temporary geometry on screen while using this tool.
  2641. :param data:
  2642. :return:
  2643. """
  2644. geo_list = []
  2645. if self.origin is None:
  2646. return None
  2647. if len(self.draw_app.get_selected()) == 0:
  2648. return None
  2649. dx = data[0] - self.origin[0]
  2650. dy = data[1] - self.origin[1]
  2651. for geom in self.draw_app.get_selected():
  2652. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2653. return DrawToolUtilityShape(geo_list)
  2654. class FCDrillCopy(FCDrillMove):
  2655. def __init__(self, draw_app):
  2656. FCDrillMove.__init__(self, draw_app)
  2657. self.name = 'drill_copy'
  2658. def make(self):
  2659. # Create new geometry
  2660. dx = self.destination[0] - self.origin[0]
  2661. dy = self.destination[1] - self.origin[1]
  2662. sel_shapes_to_be_deleted = []
  2663. for sel_dia in self.selected_dia_list:
  2664. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2665. for select_shape in self.draw_app.get_selected():
  2666. if select_shape in self.current_storage.get_objects():
  2667. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  2668. # add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  2669. self.draw_app.points_edit[sel_dia].append((0, 0))
  2670. sel_shapes_to_be_deleted.append(select_shape)
  2671. self.draw_app.on_exc_shape_complete(self.current_storage)
  2672. self.geometry = []
  2673. for shp in sel_shapes_to_be_deleted:
  2674. self.draw_app.selected.remove(shp)
  2675. sel_shapes_to_be_deleted = []
  2676. self.draw_app.build_ui()
  2677. self.draw_app.app.inform.emit(_("[success]Done. Drill(s) copied."))
  2678. ########################
  2679. ### Main Application ###
  2680. ########################
  2681. class FlatCAMGeoEditor(QtCore.QObject):
  2682. transform_complete = QtCore.pyqtSignal()
  2683. draw_shape_idx = -1
  2684. def __init__(self, app, disabled=False):
  2685. assert isinstance(app, FlatCAMApp.App), \
  2686. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2687. super(FlatCAMGeoEditor, self).__init__()
  2688. self.app = app
  2689. self.canvas = app.plotcanvas
  2690. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2691. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2692. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2693. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2694. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2695. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2696. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2697. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2698. self.app.ui.geo_transform_menuitem.triggered.connect(self.on_transform_tool)
  2699. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2700. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2701. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2702. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2703. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2704. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2705. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2706. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2707. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2708. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2709. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2710. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2711. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2712. self.transform_complete.connect(self.on_transform_complete)
  2713. ## Toolbar events and properties
  2714. self.tools = {
  2715. "select": {"button": self.app.ui.geo_select_btn,
  2716. "constructor": FCSelect},
  2717. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2718. "constructor": FCArc},
  2719. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2720. "constructor": FCCircle},
  2721. "path": {"button": self.app.ui.geo_add_path_btn,
  2722. "constructor": FCPath},
  2723. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2724. "constructor": FCRectangle},
  2725. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2726. "constructor": FCPolygon},
  2727. "text": {"button": self.app.ui.geo_add_text_btn,
  2728. "constructor": FCText},
  2729. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2730. "constructor": FCBuffer},
  2731. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2732. "constructor": FCPaint},
  2733. "move": {"button": self.app.ui.geo_move_btn,
  2734. "constructor": FCMove},
  2735. "transform": {"button": self.app.ui.geo_transform_btn,
  2736. "constructor": FCTransform},
  2737. "copy": {"button": self.app.ui.geo_copy_btn,
  2738. "constructor": FCCopy}
  2739. }
  2740. ### Data
  2741. self.active_tool = None
  2742. self.storage = FlatCAMGeoEditor.make_storage()
  2743. self.utility = []
  2744. # VisPy visuals
  2745. self.fcgeometry = None
  2746. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2747. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2748. self.app.pool_recreated.connect(self.pool_recreated)
  2749. # Remove from scene
  2750. self.shapes.enabled = False
  2751. self.tool_shape.enabled = False
  2752. ## List of selected shapes.
  2753. self.selected = []
  2754. self.flat_geo = []
  2755. self.move_timer = QtCore.QTimer()
  2756. self.move_timer.setSingleShot(True)
  2757. # this var will store the state of the toolbar before starting the editor
  2758. self.toolbar_old_state = False
  2759. self.key = None # Currently pressed key
  2760. self.geo_key_modifiers = None
  2761. self.x = None # Current mouse cursor pos
  2762. self.y = None
  2763. # Current snapped mouse pos
  2764. self.snap_x = None
  2765. self.snap_y = None
  2766. self.pos = None
  2767. # signal that there is an action active like polygon or path
  2768. self.in_action = False
  2769. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2770. self.launched_from_shortcuts = False
  2771. def make_callback(thetool):
  2772. def f():
  2773. self.on_tool_select(thetool)
  2774. return f
  2775. for tool in self.tools:
  2776. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2777. self.tools[tool]["button"].setCheckable(True) # Checkable
  2778. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2779. self.app.ui.corner_snap_btn.setCheckable(True)
  2780. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2781. self.options = {
  2782. "global_gridx": 0.1,
  2783. "global_gridy": 0.1,
  2784. "global_snap_max": 0.05,
  2785. "grid_snap": True,
  2786. "corner_snap": False,
  2787. "grid_gap_link": True
  2788. }
  2789. self.app.options_read_form()
  2790. for option in self.options:
  2791. if option in self.app.options:
  2792. self.options[option] = self.app.options[option]
  2793. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2794. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2795. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2796. self.app.ui.grid_gap_link_cb.setChecked(True)
  2797. self.rtree_index = rtindex.Index()
  2798. def entry2option(option, entry):
  2799. try:
  2800. self.options[option] = float(entry.text())
  2801. except Exception as e:
  2802. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2803. return
  2804. def gridx_changed(goption, gentry):
  2805. entry2option(option=goption, entry=gentry)
  2806. # if the grid link is checked copy the value in the GridX field to GridY
  2807. if self.app.ui.grid_gap_link_cb.isChecked():
  2808. self.app.ui.grid_gap_y_entry.set_value(self.app.ui.grid_gap_x_entry.get_value())
  2809. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2810. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2811. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2812. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2813. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2814. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2815. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2816. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2817. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2818. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2819. self.editor_active = False
  2820. # if using Paint store here the tool diameter used
  2821. self.paint_tooldia = None
  2822. self.paint_tool = PaintOptionsTool(self.app, self)
  2823. self.transform_tool = TransformEditorTool(self.app, self)
  2824. def pool_recreated(self, pool):
  2825. self.shapes.pool = pool
  2826. self.tool_shape.pool = pool
  2827. def on_transform_complete(self):
  2828. self.delete_selected()
  2829. self.replot()
  2830. def activate(self):
  2831. self.connect_canvas_event_handlers()
  2832. self.shapes.enabled = True
  2833. self.tool_shape.enabled = True
  2834. self.app.app_cursor.enabled = True
  2835. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2836. self.app.ui.corner_snap_btn.setEnabled(True)
  2837. self.app.ui.snap_magnet.setVisible(True)
  2838. self.app.ui.corner_snap_btn.setVisible(True)
  2839. self.app.ui.geo_editor_menu.setDisabled(False)
  2840. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2841. self.app.ui.update_obj_btn.setEnabled(True)
  2842. self.app.ui.g_editor_cmenu.setEnabled(True)
  2843. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2844. self.app.ui.geo_edit_toolbar.setVisible(True)
  2845. self.app.ui.snap_toolbar.setDisabled(False)
  2846. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2847. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2848. for w in sel_tab_widget_list:
  2849. w.setEnabled(False)
  2850. # Tell the App that the editor is active
  2851. self.editor_active = True
  2852. def deactivate(self):
  2853. self.disconnect_canvas_event_handlers()
  2854. self.clear()
  2855. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2856. settings = QSettings("Open Source", "FlatCAM")
  2857. if settings.contains("layout"):
  2858. layout = settings.value('layout', type=str)
  2859. if layout == 'standard':
  2860. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2861. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2862. self.app.ui.corner_snap_btn.setEnabled(False)
  2863. self.app.ui.snap_magnet.setVisible(False)
  2864. self.app.ui.corner_snap_btn.setVisible(False)
  2865. elif layout == 'compact':
  2866. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2867. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2868. self.app.ui.corner_snap_btn.setEnabled(False)
  2869. else:
  2870. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2871. self.app.ui.snap_magnet.setVisible(False)
  2872. self.app.ui.corner_snap_btn.setVisible(False)
  2873. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2874. self.app.ui.corner_snap_btn.setEnabled(False)
  2875. # set the Editor Toolbar visibility to what was before entering in the Editor
  2876. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2877. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2878. # Disable visuals
  2879. self.shapes.enabled = False
  2880. self.tool_shape.enabled = False
  2881. self.app.app_cursor.enabled = False
  2882. self.app.ui.geo_editor_menu.setDisabled(True)
  2883. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2884. self.app.ui.update_obj_btn.setEnabled(False)
  2885. self.app.ui.g_editor_cmenu.setEnabled(False)
  2886. self.app.ui.e_editor_cmenu.setEnabled(False)
  2887. # Tell the app that the editor is no longer active
  2888. self.editor_active = False
  2889. # Show original geometry
  2890. if self.fcgeometry:
  2891. self.fcgeometry.visible = True
  2892. def connect_canvas_event_handlers(self):
  2893. ## Canvas events
  2894. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2895. # but those from FlatCAMGeoEditor
  2896. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2897. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2898. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2899. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2900. self.app.collection.view.clicked.disconnect()
  2901. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2902. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2903. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  2904. def disconnect_canvas_event_handlers(self):
  2905. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2906. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2907. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  2908. # we restore the key and mouse control to FlatCAMApp method
  2909. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2910. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2911. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2912. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2913. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2914. def add_shape(self, shape):
  2915. """
  2916. Adds a shape to the shape storage.
  2917. :param shape: Shape to be added.
  2918. :type shape: DrawToolShape
  2919. :return: None
  2920. """
  2921. # List of DrawToolShape?
  2922. if isinstance(shape, list):
  2923. for subshape in shape:
  2924. self.add_shape(subshape)
  2925. return
  2926. assert isinstance(shape, DrawToolShape), \
  2927. "Expected a DrawToolShape, got %s" % type(shape)
  2928. assert shape.geo is not None, \
  2929. "Shape object has empty geometry (None)"
  2930. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2931. not isinstance(shape.geo, list), \
  2932. "Shape objects has empty geometry ([])"
  2933. if isinstance(shape, DrawToolUtilityShape):
  2934. self.utility.append(shape)
  2935. else:
  2936. self.storage.insert(shape) # TODO: Check performance
  2937. def delete_utility_geometry(self):
  2938. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2939. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2940. for_deletion = [shape for shape in self.utility]
  2941. for shape in for_deletion:
  2942. self.delete_shape(shape)
  2943. self.tool_shape.clear(update=True)
  2944. self.tool_shape.redraw()
  2945. def cutpath(self):
  2946. selected = self.get_selected()
  2947. tools = selected[1:]
  2948. toolgeo = cascaded_union([shp.geo for shp in tools])
  2949. target = selected[0]
  2950. if type(target.geo) == Polygon:
  2951. for ring in poly2rings(target.geo):
  2952. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  2953. self.delete_shape(target)
  2954. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  2955. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  2956. self.delete_shape(target)
  2957. elif type(target.geo) == MultiLineString:
  2958. try:
  2959. for linestring in target.geo:
  2960. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  2961. except:
  2962. self.app.log.warning("Current LinearString does not intersect the target")
  2963. self.delete_shape(target)
  2964. else:
  2965. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  2966. self.replot()
  2967. def toolbar_tool_toggle(self, key):
  2968. self.options[key] = self.sender().isChecked()
  2969. if self.options[key] == True:
  2970. return 1
  2971. else:
  2972. return 0
  2973. def clear(self):
  2974. self.active_tool = None
  2975. # self.shape_buffer = []
  2976. self.selected = []
  2977. self.shapes.clear(update=True)
  2978. self.tool_shape.clear(update=True)
  2979. self.storage = FlatCAMGeoEditor.make_storage()
  2980. self.replot()
  2981. def edit_fcgeometry(self, fcgeometry):
  2982. """
  2983. Imports the geometry from the given FlatCAM Geometry object
  2984. into the editor.
  2985. :param fcgeometry: FlatCAMGeometry
  2986. :return: None
  2987. """
  2988. assert isinstance(fcgeometry, Geometry), \
  2989. "Expected a Geometry, got %s" % type(fcgeometry)
  2990. self.deactivate()
  2991. self.activate()
  2992. # Hide original geometry
  2993. self.fcgeometry = fcgeometry
  2994. fcgeometry.visible = False
  2995. # Set selection tolerance
  2996. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2997. self.select_tool("select")
  2998. # Link shapes into editor.
  2999. for shape in fcgeometry.flatten():
  3000. if shape is not None: # TODO: Make flatten never create a None
  3001. if type(shape) == Polygon:
  3002. self.add_shape(DrawToolShape(shape.exterior))
  3003. for inter in shape.interiors:
  3004. self.add_shape(DrawToolShape(inter))
  3005. else:
  3006. self.add_shape(DrawToolShape(shape))
  3007. self.replot()
  3008. # start with GRID toolbar activated
  3009. if self.app.ui.grid_snap_btn.isChecked() == False:
  3010. self.app.ui.grid_snap_btn.trigger()
  3011. def on_buffer_tool(self):
  3012. buff_tool = BufferSelectionTool(self.app, self)
  3013. buff_tool.run()
  3014. def on_paint_tool(self):
  3015. paint_tool = PaintOptionsTool(self.app, self)
  3016. paint_tool.run()
  3017. def on_transform_tool(self):
  3018. transform_tool = TransformEditorTool(self.app, self)
  3019. transform_tool.run()
  3020. def on_tool_select(self, tool):
  3021. """
  3022. Behavior of the toolbar. Tool initialization.
  3023. :rtype : None
  3024. """
  3025. self.app.log.debug("on_tool_select('%s')" % tool)
  3026. # This is to make the group behave as radio group
  3027. if tool in self.tools:
  3028. if self.tools[tool]["button"].isChecked():
  3029. self.app.log.debug("%s is checked." % tool)
  3030. for t in self.tools:
  3031. if t != tool:
  3032. self.tools[t]["button"].setChecked(False)
  3033. self.active_tool = self.tools[tool]["constructor"](self)
  3034. if not isinstance(self.active_tool, FCSelect):
  3035. self.app.inform.emit(self.active_tool.start_msg)
  3036. else:
  3037. self.app.log.debug("%s is NOT checked." % tool)
  3038. for t in self.tools:
  3039. self.tools[t]["button"].setChecked(False)
  3040. self.active_tool = None
  3041. def draw_tool_path(self):
  3042. self.select_tool('path')
  3043. return
  3044. def draw_tool_rectangle(self):
  3045. self.select_tool('rectangle')
  3046. return
  3047. def on_grid_toggled(self):
  3048. self.toolbar_tool_toggle("grid_snap")
  3049. # make sure that the cursor shape is enabled/disabled, too
  3050. if self.options['grid_snap'] is True:
  3051. self.app.app_cursor.enabled = True
  3052. else:
  3053. self.app.app_cursor.enabled = False
  3054. def on_canvas_click(self, event):
  3055. """
  3056. event.x and .y have canvas coordinates
  3057. event.xdaya and .ydata have plot coordinates
  3058. :param event: Event object dispatched by Matplotlib
  3059. :return: None
  3060. """
  3061. if event.button is 1:
  3062. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3063. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3064. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3065. ### Snap coordinates
  3066. x, y = self.snap(self.pos[0], self.pos[1])
  3067. self.pos = (x, y)
  3068. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3069. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3070. if modifiers == QtCore.Qt.ShiftModifier:
  3071. self.app.clipboard.setText(
  3072. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3073. return
  3074. # Selection with left mouse button
  3075. if self.active_tool is not None and event.button is 1:
  3076. # Dispatch event to active_tool
  3077. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3078. msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3079. # If it is a shape generating tool
  3080. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3081. self.on_shape_complete()
  3082. # MS: always return to the Select Tool if modifier key is not pressed
  3083. # else return to the current tool
  3084. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3085. if self.app.defaults["global_mselect_key"] == 'Control':
  3086. modifier_to_use = Qt.ControlModifier
  3087. else:
  3088. modifier_to_use = Qt.ShiftModifier
  3089. # if modifier key is pressed then we add to the selected list the current shape but if
  3090. # it's already in the selected list, we removed it. Therefore first click selects, second deselects.
  3091. if key_modifier == modifier_to_use:
  3092. self.select_tool(self.active_tool.name)
  3093. else:
  3094. self.select_tool("select")
  3095. return
  3096. if isinstance(self.active_tool, FCSelect):
  3097. # self.app.log.debug("Replotting after click.")
  3098. self.replot()
  3099. else:
  3100. self.app.log.debug("No active tool to respond to click!")
  3101. def on_canvas_move(self, event):
  3102. """
  3103. Called on 'mouse_move' event
  3104. event.pos have canvas screen coordinates
  3105. :param event: Event object dispatched by VisPy SceneCavas
  3106. :return: None
  3107. """
  3108. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3109. event.xdata, event.ydata = pos[0], pos[1]
  3110. self.x = event.xdata
  3111. self.y = event.ydata
  3112. # Prevent updates on pan
  3113. # if len(event.buttons) > 0:
  3114. # return
  3115. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3116. if event.button == 2:
  3117. self.app.panning_action = True
  3118. return
  3119. else:
  3120. self.app.panning_action = False
  3121. try:
  3122. x = float(event.xdata)
  3123. y = float(event.ydata)
  3124. except TypeError:
  3125. return
  3126. if self.active_tool is None:
  3127. return
  3128. ### Snap coordinates
  3129. x, y = self.snap(x, y)
  3130. self.snap_x = x
  3131. self.snap_y = y
  3132. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3133. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3134. "<b>Y</b>: %.4f" % (x, y))
  3135. if self.pos is None:
  3136. self.pos = (0, 0)
  3137. dx = x - self.pos[0]
  3138. dy = y - self.pos[1]
  3139. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3140. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3141. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3142. ### Utility geometry (animated)
  3143. geo = self.active_tool.utility_geometry(data=(x, y))
  3144. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3145. # Remove any previous utility shape
  3146. self.tool_shape.clear(update=True)
  3147. self.draw_utility_geometry(geo=geo)
  3148. ### Selection area on canvas section ###
  3149. dx = pos[0] - self.pos[0]
  3150. if event.is_dragging == 1 and event.button == 1:
  3151. self.app.delete_selection_shape()
  3152. if dx < 0:
  3153. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  3154. color=self.app.defaults["global_alt_sel_line"],
  3155. face_color=self.app.defaults['global_alt_sel_fill'])
  3156. self.app.selection_type = False
  3157. else:
  3158. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  3159. self.app.selection_type = True
  3160. else:
  3161. self.app.selection_type = None
  3162. # Update cursor
  3163. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  3164. def on_canvas_click_release(self, event):
  3165. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  3166. if self.app.grid_status():
  3167. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3168. else:
  3169. pos = (pos_canvas[0], pos_canvas[1])
  3170. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3171. # canvas menu
  3172. try:
  3173. if event.button == 2: # right click
  3174. if self.app.panning_action is True:
  3175. self.app.panning_action = False
  3176. else:
  3177. if self.in_action is False:
  3178. self.app.cursor = QtGui.QCursor()
  3179. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3180. else:
  3181. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3182. # right mouse click will finish the action
  3183. if isinstance(self.active_tool, FCShapeTool):
  3184. self.active_tool.click(self.snap(self.x, self.y))
  3185. self.active_tool.make()
  3186. if self.active_tool.complete:
  3187. self.on_shape_complete()
  3188. self.app.inform.emit(_("[success]Done."))
  3189. # MS: always return to the Select Tool if modifier key is not pressed
  3190. # else return to the current tool
  3191. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3192. if self.app.defaults["global_mselect_key"] == 'Control':
  3193. modifier_to_use = Qt.ControlModifier
  3194. else:
  3195. modifier_to_use = Qt.ShiftModifier
  3196. if key_modifier == modifier_to_use:
  3197. self.select_tool(self.active_tool.name)
  3198. else:
  3199. self.select_tool("select")
  3200. except Exception as e:
  3201. log.warning("Error: %s" % str(e))
  3202. return
  3203. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3204. # selection and then select a type of selection ("enclosing" or "touching")
  3205. try:
  3206. if event.button == 1: # left click
  3207. if self.app.selection_type is not None:
  3208. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3209. self.app.selection_type = None
  3210. elif isinstance(self.active_tool, FCSelect):
  3211. # Dispatch event to active_tool
  3212. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3213. msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  3214. # self.app.inform.emit(msg)
  3215. self.replot()
  3216. except Exception as e:
  3217. log.warning("Error: %s" % str(e))
  3218. return
  3219. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3220. """
  3221. :param start_pos: mouse position when the selection LMB click was done
  3222. :param end_pos: mouse position when the left mouse button is released
  3223. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3224. :type Bool
  3225. :return:
  3226. """
  3227. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3228. self.app.delete_selection_shape()
  3229. for obj in self.storage.get_objects():
  3230. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  3231. (sel_type is False and poly_selection.intersects(obj.geo)):
  3232. if self.key == self.app.defaults["global_mselect_key"]:
  3233. if obj in self.selected:
  3234. self.selected.remove(obj)
  3235. else:
  3236. # add the object to the selected shapes
  3237. self.selected.append(obj)
  3238. else:
  3239. if obj not in self.selected:
  3240. self.selected.append(obj)
  3241. self.replot()
  3242. def draw_utility_geometry(self, geo):
  3243. # Add the new utility shape
  3244. try:
  3245. # this case is for the Font Parse
  3246. for el in list(geo.geo):
  3247. if type(el) == MultiPolygon:
  3248. for poly in el:
  3249. self.tool_shape.add(
  3250. shape=poly,
  3251. color=(self.app.defaults["global_draw_color"] + '80'),
  3252. update=False,
  3253. layer=0,
  3254. tolerance=None
  3255. )
  3256. elif type(el) == MultiLineString:
  3257. for linestring in el:
  3258. self.tool_shape.add(
  3259. shape=linestring,
  3260. color=(self.app.defaults["global_draw_color"] + '80'),
  3261. update=False,
  3262. layer=0,
  3263. tolerance=None
  3264. )
  3265. else:
  3266. self.tool_shape.add(
  3267. shape=el,
  3268. color=(self.app.defaults["global_draw_color"] + '80'),
  3269. update=False,
  3270. layer=0,
  3271. tolerance=None
  3272. )
  3273. except TypeError:
  3274. self.tool_shape.add(
  3275. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3276. update=False, layer=0, tolerance=None)
  3277. self.tool_shape.redraw()
  3278. def on_delete_btn(self):
  3279. self.delete_selected()
  3280. self.replot()
  3281. def delete_selected(self):
  3282. tempref = [s for s in self.selected]
  3283. for shape in tempref:
  3284. self.delete_shape(shape)
  3285. self.selected = []
  3286. def delete_shape(self, shape):
  3287. if shape in self.utility:
  3288. self.utility.remove(shape)
  3289. return
  3290. self.storage.remove(shape)
  3291. if shape in self.selected:
  3292. self.selected.remove(shape) # TODO: Check performance
  3293. def on_move(self):
  3294. self.app.ui.geo_move_btn.setChecked(True)
  3295. self.on_tool_select('move')
  3296. def on_move_click(self):
  3297. if not self.selected:
  3298. self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3299. return
  3300. self.on_move()
  3301. self.active_tool.set_origin(self.snap(self.x, self.y))
  3302. def on_copy_click(self):
  3303. if not self.selected:
  3304. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  3305. return
  3306. self.app.ui.geo_copy_btn.setChecked(True)
  3307. self.app.geo_editor.on_tool_select('copy')
  3308. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3309. self.app.geo_editor.x, self.app.geo_editor.y))
  3310. self.app.inform.emit(_("Click on target point."))
  3311. def on_corner_snap(self):
  3312. self.app.ui.corner_snap_btn.trigger()
  3313. def get_selected(self):
  3314. """
  3315. Returns list of shapes that are selected in the editor.
  3316. :return: List of shapes.
  3317. """
  3318. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3319. return self.selected
  3320. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3321. """
  3322. Plots a geometric object or list of objects without rendering. Plotted objects
  3323. are returned as a list. This allows for efficient/animated rendering.
  3324. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3325. :param color: Shape color
  3326. :param linewidth: Width of lines in # of pixels.
  3327. :return: List of plotted elements.
  3328. """
  3329. plot_elements = []
  3330. if geometry is None:
  3331. geometry = self.active_tool.geometry
  3332. try:
  3333. for geo in geometry:
  3334. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3335. ## Non-iterable
  3336. except TypeError:
  3337. ## DrawToolShape
  3338. if isinstance(geometry, DrawToolShape):
  3339. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3340. ## Polygon: Descend into exterior and each interior.
  3341. if type(geometry) == Polygon:
  3342. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3343. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3344. if type(geometry) == LineString or type(geometry) == LinearRing:
  3345. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3346. tolerance=self.fcgeometry.drawing_tolerance))
  3347. if type(geometry) == Point:
  3348. pass
  3349. return plot_elements
  3350. def plot_all(self):
  3351. """
  3352. Plots all shapes in the editor.
  3353. :return: None
  3354. :rtype: None
  3355. """
  3356. # self.app.log.debug("plot_all()")
  3357. self.shapes.clear(update=True)
  3358. for shape in self.storage.get_objects():
  3359. if shape.geo is None: # TODO: This shouldn't have happened
  3360. continue
  3361. if shape in self.selected:
  3362. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3363. continue
  3364. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3365. for shape in self.utility:
  3366. self.plot_shape(geometry=shape.geo, linewidth=1)
  3367. continue
  3368. self.shapes.redraw()
  3369. def replot(self):
  3370. self.plot_all()
  3371. def on_shape_complete(self):
  3372. self.app.log.debug("on_shape_complete()")
  3373. # Add shape
  3374. self.add_shape(self.active_tool.geometry)
  3375. # Remove any utility shapes
  3376. self.delete_utility_geometry()
  3377. self.tool_shape.clear(update=True)
  3378. # Replot and reset tool.
  3379. self.replot()
  3380. # self.active_tool = type(self.active_tool)(self)
  3381. @staticmethod
  3382. def make_storage():
  3383. ## Shape storage.
  3384. storage = FlatCAMRTreeStorage()
  3385. storage.get_points = DrawToolShape.get_pts
  3386. return storage
  3387. def select_tool(self, toolname):
  3388. """
  3389. Selects a drawing tool. Impacts the object and GUI.
  3390. :param toolname: Name of the tool.
  3391. :return: None
  3392. """
  3393. self.tools[toolname]["button"].setChecked(True)
  3394. self.on_tool_select(toolname)
  3395. def set_selected(self, shape):
  3396. # Remove and add to the end.
  3397. if shape in self.selected:
  3398. self.selected.remove(shape)
  3399. self.selected.append(shape)
  3400. def set_unselected(self, shape):
  3401. if shape in self.selected:
  3402. self.selected.remove(shape)
  3403. def snap(self, x, y):
  3404. """
  3405. Adjusts coordinates to snap settings.
  3406. :param x: Input coordinate X
  3407. :param y: Input coordinate Y
  3408. :return: Snapped (x, y)
  3409. """
  3410. snap_x, snap_y = (x, y)
  3411. snap_distance = Inf
  3412. ### Object (corner?) snap
  3413. ### No need for the objects, just the coordinates
  3414. ### in the index.
  3415. if self.options["corner_snap"]:
  3416. try:
  3417. nearest_pt, shape = self.storage.nearest((x, y))
  3418. nearest_pt_distance = distance((x, y), nearest_pt)
  3419. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3420. snap_distance = nearest_pt_distance
  3421. snap_x, snap_y = nearest_pt
  3422. except (StopIteration, AssertionError):
  3423. pass
  3424. ### Grid snap
  3425. if self.options["grid_snap"]:
  3426. if self.options["global_gridx"] != 0:
  3427. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3428. else:
  3429. snap_x_ = x
  3430. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3431. # and it will use the snap distance from GridX entry
  3432. if self.app.ui.grid_gap_link_cb.isChecked():
  3433. if self.options["global_gridx"] != 0:
  3434. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3435. else:
  3436. snap_y_ = y
  3437. else:
  3438. if self.options["global_gridy"] != 0:
  3439. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3440. else:
  3441. snap_y_ = y
  3442. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3443. if nearest_grid_distance < snap_distance:
  3444. snap_x, snap_y = (snap_x_, snap_y_)
  3445. return snap_x, snap_y
  3446. def update_fcgeometry(self, fcgeometry):
  3447. """
  3448. Transfers the geometry tool shape buffer to the selected geometry
  3449. object. The geometry already in the object are removed.
  3450. :param fcgeometry: FlatCAMGeometry
  3451. :return: None
  3452. """
  3453. fcgeometry.solid_geometry = []
  3454. # for shape in self.shape_buffer:
  3455. for shape in self.storage.get_objects():
  3456. fcgeometry.solid_geometry.append(shape.geo)
  3457. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  3458. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  3459. for w in sel_tab_widget_list:
  3460. w.setEnabled(True)
  3461. def update_options(self, obj):
  3462. if self.paint_tooldia:
  3463. obj.options['cnctooldia'] = self.paint_tooldia
  3464. self.paint_tooldia = None
  3465. return True
  3466. else:
  3467. return False
  3468. def union(self):
  3469. """
  3470. Makes union of selected polygons. Original polygons
  3471. are deleted.
  3472. :return: None.
  3473. """
  3474. results = cascaded_union([t.geo for t in self.get_selected()])
  3475. # Delete originals.
  3476. for_deletion = [s for s in self.get_selected()]
  3477. for shape in for_deletion:
  3478. self.delete_shape(shape)
  3479. # Selected geometry is now gone!
  3480. self.selected = []
  3481. self.add_shape(DrawToolShape(results))
  3482. self.replot()
  3483. def intersection(self):
  3484. """
  3485. Makes intersectino of selected polygons. Original polygons are deleted.
  3486. :return: None
  3487. """
  3488. shapes = self.get_selected()
  3489. try:
  3490. results = shapes[0].geo
  3491. except Exception as e:
  3492. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3493. self.app.inform.emit(_("[WARNING_NOTCL]A selection of at least 2 geo items is required to do Intersection."))
  3494. self.select_tool('select')
  3495. return
  3496. for shape in shapes[1:]:
  3497. results = results.intersection(shape.geo)
  3498. # Delete originals.
  3499. for_deletion = [s for s in self.get_selected()]
  3500. for shape in for_deletion:
  3501. self.delete_shape(shape)
  3502. # Selected geometry is now gone!
  3503. self.selected = []
  3504. self.add_shape(DrawToolShape(results))
  3505. self.replot()
  3506. def subtract(self):
  3507. selected = self.get_selected()
  3508. try:
  3509. tools = selected[1:]
  3510. toolgeo = cascaded_union([shp.geo for shp in tools])
  3511. result = selected[0].geo.difference(toolgeo)
  3512. self.delete_shape(selected[0])
  3513. self.add_shape(DrawToolShape(result))
  3514. self.replot()
  3515. except Exception as e:
  3516. log.debug(str(e))
  3517. def buffer(self, buf_distance, join_style):
  3518. selected = self.get_selected()
  3519. if buf_distance < 0:
  3520. self.app.inform.emit(
  3521. _( "[ERROR_NOTCL]Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape"))
  3522. # deselect everything
  3523. self.selected = []
  3524. self.replot()
  3525. return
  3526. if len(selected) == 0:
  3527. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3528. return
  3529. if not isinstance(buf_distance, float):
  3530. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3531. # deselect everything
  3532. self.selected = []
  3533. self.replot()
  3534. return
  3535. pre_buffer = cascaded_union([t.geo for t in selected])
  3536. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3537. if results.is_empty:
  3538. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3539. # deselect everything
  3540. self.selected = []
  3541. self.replot()
  3542. return
  3543. self.add_shape(DrawToolShape(results))
  3544. self.replot()
  3545. self.app.inform.emit(_("[success]Full buffer geometry created."))
  3546. def buffer_int(self, buf_distance, join_style):
  3547. selected = self.get_selected()
  3548. if buf_distance < 0:
  3549. self.app.inform.emit(
  3550. _("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3551. "Use Buffer interior to generate an 'inside' shape")
  3552. )
  3553. # deselect everything
  3554. self.selected = []
  3555. self.replot()
  3556. return
  3557. if len(selected) == 0:
  3558. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3559. return
  3560. if not isinstance(buf_distance, float):
  3561. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3562. # deselect everything
  3563. self.selected = []
  3564. self.replot()
  3565. return
  3566. pre_buffer = cascaded_union([t.geo for t in selected])
  3567. results = pre_buffer.buffer(-buf_distance + 1e-10, resolution=32, join_style=join_style)
  3568. if results.is_empty:
  3569. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a smaller buffer value."))
  3570. # deselect everything
  3571. self.selected = []
  3572. self.replot()
  3573. return
  3574. if type(results) == MultiPolygon:
  3575. for poly in results:
  3576. self.add_shape(DrawToolShape(poly.exterior))
  3577. else:
  3578. self.add_shape(DrawToolShape(results.exterior))
  3579. self.replot()
  3580. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3581. # selected = self.get_selected()
  3582. #
  3583. # if len(selected) == 0:
  3584. # self.app.inform.emit("[WARNING] Nothing selected for buffering.")
  3585. # return
  3586. #
  3587. # if not isinstance(buf_distance, float):
  3588. # self.app.inform.emit("[WARNING] Invalid distance for buffering.")
  3589. # return
  3590. #
  3591. # pre_buffer = cascaded_union([t.geo for t in selected])
  3592. # results = pre_buffer.buffer(buf_distance)
  3593. # if results.is_empty:
  3594. # self.app.inform.emit("Failed. Choose a smaller buffer value.")
  3595. # return
  3596. #
  3597. # int_geo = []
  3598. # if type(results) == MultiPolygon:
  3599. # for poly in results:
  3600. # for g in poly.interiors:
  3601. # int_geo.append(g)
  3602. # res = cascaded_union(int_geo)
  3603. # self.add_shape(DrawToolShape(res))
  3604. # else:
  3605. # print(results.interiors)
  3606. # for g in results.interiors:
  3607. # int_geo.append(g)
  3608. # res = cascaded_union(int_geo)
  3609. # self.add_shape(DrawToolShape(res))
  3610. #
  3611. # self.replot()
  3612. # self.app.inform.emit("Interior buffer geometry created.")
  3613. def buffer_ext(self, buf_distance, join_style):
  3614. selected = self.get_selected()
  3615. if buf_distance < 0:
  3616. self.app.inform.emit(_("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3617. "Use Buffer interior to generate an 'inside' shape"))
  3618. # deselect everything
  3619. self.selected = []
  3620. self.replot()
  3621. return
  3622. if len(selected) == 0:
  3623. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3624. return
  3625. if not isinstance(buf_distance, float):
  3626. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3627. # deselect everything
  3628. self.selected = []
  3629. self.replot()
  3630. return
  3631. pre_buffer = cascaded_union([t.geo for t in selected])
  3632. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3633. if results.is_empty:
  3634. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3635. # deselect everything
  3636. self.selected = []
  3637. self.replot()
  3638. return
  3639. if type(results) == MultiPolygon:
  3640. for poly in results:
  3641. self.add_shape(DrawToolShape(poly.exterior))
  3642. else:
  3643. self.add_shape(DrawToolShape(results.exterior))
  3644. self.replot()
  3645. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3646. # def paint(self, tooldia, overlap, margin, method):
  3647. # selected = self.get_selected()
  3648. #
  3649. # if len(selected) == 0:
  3650. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3651. # return
  3652. #
  3653. # for param in [tooldia, overlap, margin]:
  3654. # if not isinstance(param, float):
  3655. # param_name = [k for k, v in locals().items() if v is param][0]
  3656. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3657. #
  3658. # # Todo: Check for valid method.
  3659. #
  3660. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3661. #
  3662. # results = []
  3663. #
  3664. # def recurse(geo):
  3665. # try:
  3666. # for subg in geo:
  3667. # for subsubg in recurse(subg):
  3668. # yield subsubg
  3669. # except TypeError:
  3670. # if isinstance(geo, LinearRing):
  3671. # yield geo
  3672. #
  3673. # raise StopIteration
  3674. #
  3675. # for geo in selected:
  3676. # print(type(geo.geo))
  3677. #
  3678. # local_results = []
  3679. # for poly in recurse(geo.geo):
  3680. # if method == "seed":
  3681. # # Type(cp) == FlatCAMRTreeStorage | None
  3682. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3683. # tooldia, overlap=overlap)
  3684. #
  3685. # else:
  3686. # # Type(cp) == FlatCAMRTreeStorage | None
  3687. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3688. # tooldia, overlap=overlap)
  3689. #
  3690. # if cp is not None:
  3691. # local_results += list(cp.get_objects())
  3692. #
  3693. # results.append(cascaded_union(local_results))
  3694. #
  3695. # # This is a dirty patch:
  3696. # for r in results:
  3697. # self.add_shape(DrawToolShape(r))
  3698. #
  3699. # self.replot()
  3700. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3701. self.paint_tooldia = tooldia
  3702. selected = self.get_selected()
  3703. if len(selected) == 0:
  3704. self.app.inform.emit(_("[WARNING_NOTCL]Nothing selected for painting."))
  3705. return
  3706. for param in [tooldia, overlap, margin]:
  3707. if not isinstance(param, float):
  3708. param_name = [k for k, v in locals().items() if v is param][0]
  3709. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3710. results = []
  3711. if overlap >= 1:
  3712. self.app.inform.emit(
  3713. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3714. return
  3715. def recurse(geometry, reset=True):
  3716. """
  3717. Creates a list of non-iterable linear geometry objects.
  3718. Results are placed in self.flat_geometry
  3719. :param geometry: Shapely type or list or list of list of such.
  3720. :param reset: Clears the contents of self.flat_geometry.
  3721. """
  3722. if geometry is None:
  3723. return
  3724. if reset:
  3725. self.flat_geo = []
  3726. ## If iterable, expand recursively.
  3727. try:
  3728. for geo in geometry:
  3729. if geo is not None:
  3730. recurse(geometry=geo, reset=False)
  3731. ## Not iterable, do the actual indexing and add.
  3732. except TypeError:
  3733. self.flat_geo.append(geometry)
  3734. return self.flat_geo
  3735. for geo in selected:
  3736. local_results = []
  3737. for geo_obj in recurse(geo.geo):
  3738. try:
  3739. if type(geo_obj) == Polygon:
  3740. poly_buf = geo_obj.buffer(-margin)
  3741. else:
  3742. poly_buf = Polygon(geo_obj).buffer(-margin)
  3743. if method == "seed":
  3744. cp = Geometry.clear_polygon2(poly_buf,
  3745. tooldia, self.app.defaults["geometry_circle_steps"],
  3746. overlap=overlap, contour=contour, connect=connect)
  3747. elif method == "lines":
  3748. cp = Geometry.clear_polygon3(poly_buf,
  3749. tooldia, self.app.defaults["geometry_circle_steps"],
  3750. overlap=overlap, contour=contour, connect=connect)
  3751. else:
  3752. cp = Geometry.clear_polygon(poly_buf,
  3753. tooldia, self.app.defaults["geometry_circle_steps"],
  3754. overlap=overlap, contour=contour, connect=connect)
  3755. if cp is not None:
  3756. local_results += list(cp.get_objects())
  3757. except Exception as e:
  3758. log.debug("Could not Paint the polygons. %s" % str(e))
  3759. self.app.inform.emit(
  3760. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3761. "Or a different method of Paint\n%s") % str(e))
  3762. return
  3763. # add the result to the results list
  3764. results.append(cascaded_union(local_results))
  3765. # This is a dirty patch:
  3766. for r in results:
  3767. self.add_shape(DrawToolShape(r))
  3768. self.app.inform.emit(
  3769. _("[success] Paint done."))
  3770. self.replot()
  3771. class FlatCAMExcEditor(QtCore.QObject):
  3772. draw_shape_idx = -1
  3773. def __init__(self, app):
  3774. assert isinstance(app, FlatCAMApp.App), \
  3775. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  3776. super(FlatCAMExcEditor, self).__init__()
  3777. self.app = app
  3778. self.canvas = self.app.plotcanvas
  3779. self.exc_edit_widget = QtWidgets.QWidget()
  3780. layout = QtWidgets.QVBoxLayout()
  3781. self.exc_edit_widget.setLayout(layout)
  3782. ## Page Title box (spacing between children)
  3783. self.title_box = QtWidgets.QHBoxLayout()
  3784. layout.addLayout(self.title_box)
  3785. ## Page Title icon
  3786. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  3787. self.icon = QtWidgets.QLabel()
  3788. self.icon.setPixmap(pixmap)
  3789. self.title_box.addWidget(self.icon, stretch=0)
  3790. ## Title label
  3791. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  3792. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  3793. self.title_box.addWidget(self.title_label, stretch=1)
  3794. ## Object name
  3795. self.name_box = QtWidgets.QHBoxLayout()
  3796. layout.addLayout(self.name_box)
  3797. name_label = QtWidgets.QLabel(_("Name:"))
  3798. self.name_box.addWidget(name_label)
  3799. self.name_entry = FCEntry()
  3800. self.name_box.addWidget(self.name_entry)
  3801. ## Box box for custom widgets
  3802. # This gets populated in offspring implementations.
  3803. self.custom_box = QtWidgets.QVBoxLayout()
  3804. layout.addLayout(self.custom_box)
  3805. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3806. # this way I can hide/show the frame
  3807. self.drills_frame = QtWidgets.QFrame()
  3808. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  3809. self.custom_box.addWidget(self.drills_frame)
  3810. self.tools_box = QtWidgets.QVBoxLayout()
  3811. self.tools_box.setContentsMargins(0, 0, 0, 0)
  3812. self.drills_frame.setLayout(self.tools_box)
  3813. #### Tools Drills ####
  3814. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  3815. self.tools_table_label.setToolTip(
  3816. _( "Tools in this Excellon object\n"
  3817. "when are used for drilling.")
  3818. )
  3819. self.tools_box.addWidget(self.tools_table_label)
  3820. self.tools_table_exc = FCTable()
  3821. self.tools_box.addWidget(self.tools_table_exc)
  3822. self.tools_table_exc.setColumnCount(4)
  3823. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  3824. self.tools_table_exc.setSortingEnabled(False)
  3825. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  3826. self.empty_label = QtWidgets.QLabel('')
  3827. self.tools_box.addWidget(self.empty_label)
  3828. #### Add a new Tool ####
  3829. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  3830. self.addtool_label.setToolTip(
  3831. _("Add/Delete a tool to the tool list\n"
  3832. "for this Excellon object.")
  3833. )
  3834. self.tools_box.addWidget(self.addtool_label)
  3835. grid1 = QtWidgets.QGridLayout()
  3836. self.tools_box.addLayout(grid1)
  3837. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  3838. addtool_entry_lbl.setToolTip(
  3839. _("Diameter for the new tool")
  3840. )
  3841. grid1.addWidget(addtool_entry_lbl, 0, 0)
  3842. hlay = QtWidgets.QHBoxLayout()
  3843. self.addtool_entry = FCEntry()
  3844. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  3845. hlay.addWidget(self.addtool_entry)
  3846. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  3847. self.addtool_btn.setToolTip(
  3848. _( "Add a new tool to the tool list\n"
  3849. "with the diameter specified above.")
  3850. )
  3851. self.addtool_btn.setFixedWidth(80)
  3852. hlay.addWidget(self.addtool_btn)
  3853. grid1.addLayout(hlay, 0, 1)
  3854. grid2 = QtWidgets.QGridLayout()
  3855. self.tools_box.addLayout(grid2)
  3856. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  3857. self.deltool_btn.setToolTip(
  3858. _( "Delete a tool in the tool list\n"
  3859. "by selecting a row in the tool table.")
  3860. )
  3861. grid2.addWidget(self.deltool_btn, 0, 1)
  3862. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3863. # this way I can hide/show the frame
  3864. self.resize_frame = QtWidgets.QFrame()
  3865. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  3866. self.tools_box.addWidget(self.resize_frame)
  3867. self.resize_box = QtWidgets.QVBoxLayout()
  3868. self.resize_box.setContentsMargins(0, 0, 0, 0)
  3869. self.resize_frame.setLayout(self.resize_box)
  3870. #### Resize a drill ####
  3871. self.emptyresize_label = QtWidgets.QLabel('')
  3872. self.resize_box.addWidget(self.emptyresize_label)
  3873. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  3874. self.drillresize_label.setToolTip(
  3875. _("Resize a drill or a selection of drills.")
  3876. )
  3877. self.resize_box.addWidget(self.drillresize_label)
  3878. grid3 = QtWidgets.QGridLayout()
  3879. self.resize_box.addLayout(grid3)
  3880. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  3881. res_entry_lbl.setToolTip(
  3882. _( "Diameter to resize to.")
  3883. )
  3884. grid3.addWidget(addtool_entry_lbl, 0, 0)
  3885. hlay2 = QtWidgets.QHBoxLayout()
  3886. self.resdrill_entry = LengthEntry()
  3887. hlay2.addWidget(self.resdrill_entry)
  3888. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  3889. self.resize_btn.setToolTip(
  3890. _("Resize drill(s)")
  3891. )
  3892. self.resize_btn.setFixedWidth(80)
  3893. hlay2.addWidget(self.resize_btn)
  3894. grid3.addLayout(hlay2, 0, 1)
  3895. self.resize_frame.hide()
  3896. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  3897. # all the add drill array widgets
  3898. # this way I can hide/show the frame
  3899. self.array_frame = QtWidgets.QFrame()
  3900. self.array_frame.setContentsMargins(0, 0, 0, 0)
  3901. self.tools_box.addWidget(self.array_frame)
  3902. self.array_box = QtWidgets.QVBoxLayout()
  3903. self.array_box.setContentsMargins(0, 0, 0, 0)
  3904. self.array_frame.setLayout(self.array_box)
  3905. #### Add DRILL Array ####
  3906. self.emptyarray_label = QtWidgets.QLabel('')
  3907. self.array_box.addWidget(self.emptyarray_label)
  3908. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  3909. self.drillarray_label.setToolTip(
  3910. _("Add an array of drills (linear or circular array)")
  3911. )
  3912. self.array_box.addWidget(self.drillarray_label)
  3913. self.array_type_combo = FCComboBox()
  3914. self.array_type_combo.setToolTip(
  3915. _( "Select the type of drills array to create.\n"
  3916. "It can be Linear X(Y) or Circular")
  3917. )
  3918. self.array_type_combo.addItem(_("Linear"))
  3919. self.array_type_combo.addItem(_("Circular"))
  3920. self.array_box.addWidget(self.array_type_combo)
  3921. self.array_form = QtWidgets.QFormLayout()
  3922. self.array_box.addLayout(self.array_form)
  3923. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  3924. self.drill_array_size_label.setToolTip(
  3925. _("Specify how many drills to be in the array.")
  3926. )
  3927. self.drill_array_size_label.setFixedWidth(100)
  3928. self.drill_array_size_entry = LengthEntry()
  3929. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  3930. self.array_linear_frame = QtWidgets.QFrame()
  3931. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  3932. self.array_box.addWidget(self.array_linear_frame)
  3933. self.linear_box = QtWidgets.QVBoxLayout()
  3934. self.linear_box.setContentsMargins(0, 0, 0, 0)
  3935. self.array_linear_frame.setLayout(self.linear_box)
  3936. self.linear_form = QtWidgets.QFormLayout()
  3937. self.linear_box.addLayout(self.linear_form)
  3938. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  3939. self.drill_axis_label.setToolTip(
  3940. _("Direction on which the linear array is oriented:\n"
  3941. "- 'X' - horizontal axis \n"
  3942. "- 'Y' - vertical axis or \n"
  3943. "- 'Angle' - a custom angle for the array inclination")
  3944. )
  3945. self.drill_axis_label.setFixedWidth(100)
  3946. self.drill_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  3947. {'label': 'Y', 'value': 'Y'},
  3948. {'label': _('Angle'), 'value': 'A'}])
  3949. self.drill_axis_radio.set_value('X')
  3950. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  3951. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  3952. self.drill_pitch_label.setToolTip(
  3953. _("Pitch = Distance between elements of the array.")
  3954. )
  3955. self.drill_pitch_label.setFixedWidth(100)
  3956. self.drill_pitch_entry = LengthEntry()
  3957. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  3958. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  3959. self.linear_angle_label.setToolTip(
  3960. _( "Angle at which the linear array is placed.\n"
  3961. "The precision is of max 2 decimals.\n"
  3962. "Min value is: -359.99 degrees.\n"
  3963. "Max value is: 360.00 degrees.")
  3964. )
  3965. self.linear_angle_label.setFixedWidth(100)
  3966. self.linear_angle_spinner = FCDoubleSpinner()
  3967. self.linear_angle_spinner.set_precision(2)
  3968. self.linear_angle_spinner.setRange(-359.99, 360.00)
  3969. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  3970. self.array_circular_frame = QtWidgets.QFrame()
  3971. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  3972. self.array_box.addWidget(self.array_circular_frame)
  3973. self.circular_box = QtWidgets.QVBoxLayout()
  3974. self.circular_box.setContentsMargins(0, 0, 0, 0)
  3975. self.array_circular_frame.setLayout(self.circular_box)
  3976. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  3977. self.drill_direction_label.setToolTip(
  3978. _( "Direction for circular array."
  3979. "Can be CW = clockwise or CCW = counter clockwise.")
  3980. )
  3981. self.drill_direction_label.setFixedWidth(100)
  3982. self.circular_form = QtWidgets.QFormLayout()
  3983. self.circular_box.addLayout(self.circular_form)
  3984. self.drill_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  3985. {'label': 'CCW.', 'value': 'CCW'}])
  3986. self.drill_direction_radio.set_value('CW')
  3987. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  3988. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  3989. self.drill_angle_label.setToolTip(
  3990. _("Angle at which each element in circular array is placed.")
  3991. )
  3992. self.drill_angle_label.setFixedWidth(100)
  3993. self.drill_angle_entry = LengthEntry()
  3994. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  3995. self.array_circular_frame.hide()
  3996. self.linear_angle_spinner.hide()
  3997. self.linear_angle_label.hide()
  3998. self.array_frame.hide()
  3999. self.tools_box.addStretch()
  4000. ## Toolbar events and properties
  4001. self.tools_exc = {
  4002. "select": {"button": self.app.ui.select_drill_btn,
  4003. "constructor": FCDrillSelect},
  4004. "drill_add": {"button": self.app.ui.add_drill_btn,
  4005. "constructor": FCDrillAdd},
  4006. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  4007. "constructor": FCDrillArray},
  4008. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  4009. "constructor": FCDrillResize},
  4010. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  4011. "constructor": FCDrillCopy},
  4012. "drill_move": {"button": self.app.ui.move_drill_btn,
  4013. "constructor": FCDrillMove},
  4014. }
  4015. ### Data
  4016. self.active_tool = None
  4017. self.storage_dict = {}
  4018. self.current_storage = []
  4019. # build the data from the Excellon point into a dictionary
  4020. # {tool_dia: [geometry_in_points]}
  4021. self.points_edit = {}
  4022. self.sorted_diameters =[]
  4023. self.new_drills = []
  4024. self.new_tools = {}
  4025. self.new_slots = {}
  4026. self.new_tool_offset = {}
  4027. # dictionary to store the tool_row and diameters in Tool_table
  4028. # it will be updated everytime self.build_ui() is called
  4029. self.olddia_newdia = {}
  4030. self.tool2tooldia = {}
  4031. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  4032. # is cleared but as a side effect also the selected tool is cleared
  4033. self.last_tool_selected = None
  4034. self.utility = []
  4035. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  4036. self.launched_from_shortcuts = False
  4037. # this var will store the state of the toolbar before starting the editor
  4038. self.toolbar_old_state = False
  4039. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  4040. self.name_entry.returnPressed.connect(self.on_name_activate)
  4041. self.addtool_btn.clicked.connect(self.on_tool_add)
  4042. # self.addtool_entry.editingFinished.connect(self.on_tool_add)
  4043. self.deltool_btn.clicked.connect(self.on_tool_delete)
  4044. self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4045. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  4046. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  4047. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  4048. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  4049. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  4050. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  4051. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  4052. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  4053. # Init GUI
  4054. self.drill_array_size_entry.set_value(5)
  4055. self.drill_pitch_entry.set_value(2.54)
  4056. self.drill_angle_entry.set_value(12)
  4057. self.drill_direction_radio.set_value('CW')
  4058. self.drill_axis_radio.set_value('X')
  4059. self.exc_obj = None
  4060. # VisPy Visuals
  4061. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  4062. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  4063. self.app.pool_recreated.connect(self.pool_recreated)
  4064. # Remove from scene
  4065. self.shapes.enabled = False
  4066. self.tool_shape.enabled = False
  4067. ## List of selected shapes.
  4068. self.selected = []
  4069. self.move_timer = QtCore.QTimer()
  4070. self.move_timer.setSingleShot(True)
  4071. ## Current application units in Upper Case
  4072. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4073. self.key = None # Currently pressed key
  4074. self.modifiers = None
  4075. self.x = None # Current mouse cursor pos
  4076. self.y = None
  4077. # Current snapped mouse pos
  4078. self.snap_x = None
  4079. self.snap_y = None
  4080. self.pos = None
  4081. def make_callback(thetool):
  4082. def f():
  4083. self.on_tool_select(thetool)
  4084. return f
  4085. for tool in self.tools_exc:
  4086. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  4087. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  4088. self.options = {
  4089. "global_gridx": 0.1,
  4090. "global_gridy": 0.1,
  4091. "snap_max": 0.05,
  4092. "grid_snap": True,
  4093. "corner_snap": False,
  4094. "grid_gap_link": True
  4095. }
  4096. self.app.options_read_form()
  4097. for option in self.options:
  4098. if option in self.app.options:
  4099. self.options[option] = self.app.options[option]
  4100. self.rtree_exc_index = rtindex.Index()
  4101. # flag to show if the object was modified
  4102. self.is_modified = False
  4103. self.edited_obj_name = ""
  4104. # variable to store the total amount of drills per job
  4105. self.tot_drill_cnt = 0
  4106. self.tool_row = 0
  4107. # variable to store the total amount of slots per job
  4108. self.tot_slot_cnt = 0
  4109. self.tool_row_slots = 0
  4110. self.tool_row = 0
  4111. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4112. self.editor_active = False
  4113. def entry2option(option, entry):
  4114. self.options[option] = float(entry.text())
  4115. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4116. self.editor_active = False
  4117. def pool_recreated(self, pool):
  4118. self.shapes.pool = pool
  4119. self.tool_shape.pool = pool
  4120. @staticmethod
  4121. def make_storage():
  4122. ## Shape storage.
  4123. storage = FlatCAMRTreeStorage()
  4124. storage.get_points = DrawToolShape.get_pts
  4125. return storage
  4126. def set_ui(self):
  4127. # updated units
  4128. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4129. self.olddia_newdia.clear()
  4130. self.tool2tooldia.clear()
  4131. # build the self.points_edit dict {dimaters: [point_list]}
  4132. for drill in self.exc_obj.drills:
  4133. if drill['tool'] in self.exc_obj.tools:
  4134. if self.units == 'IN':
  4135. tool_dia = float('%.3f' % self.exc_obj.tools[drill['tool']]['C'])
  4136. else:
  4137. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  4138. try:
  4139. self.points_edit[tool_dia].append(drill['point'])
  4140. except KeyError:
  4141. self.points_edit[tool_dia] = [drill['point']]
  4142. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  4143. for key in self.points_edit:
  4144. self.olddia_newdia[key] = key
  4145. sort_temp = []
  4146. for diam in self.olddia_newdia:
  4147. sort_temp.append(float(diam))
  4148. self.sorted_diameters = sorted(sort_temp)
  4149. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  4150. for i in range(len(self.sorted_diameters)):
  4151. tt_dia = self.sorted_diameters[i]
  4152. self.tool2tooldia[i + 1] = tt_dia
  4153. def build_ui(self):
  4154. try:
  4155. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4156. self.tools_table_exc.itemChanged.disconnect()
  4157. except:
  4158. pass
  4159. # updated units
  4160. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4161. # make a new name for the new Excellon object (the one with edited content)
  4162. self.edited_obj_name = self.exc_obj.options['name']
  4163. self.name_entry.set_value(self.edited_obj_name)
  4164. if self.units == "IN":
  4165. self.addtool_entry.set_value(0.039)
  4166. else:
  4167. self.addtool_entry.set_value(1.00)
  4168. sort_temp = []
  4169. for diam in self.olddia_newdia:
  4170. sort_temp.append(float(diam))
  4171. self.sorted_diameters = sorted(sort_temp)
  4172. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  4173. n = len(self.sorted_diameters)
  4174. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  4175. self.tools_table_exc.setRowCount(n + 2)
  4176. self.tot_drill_cnt = 0
  4177. self.tot_slot_cnt = 0
  4178. self.tool_row = 0
  4179. # this variable will serve as the real tool_number
  4180. tool_id = 0
  4181. for tool_no in self.sorted_diameters:
  4182. tool_id += 1
  4183. drill_cnt = 0 # variable to store the nr of drills per tool
  4184. slot_cnt = 0 # variable to store the nr of slots per tool
  4185. # Find no of drills for the current tool
  4186. for tool_dia in self.points_edit:
  4187. if float(tool_dia) == tool_no:
  4188. drill_cnt = len(self.points_edit[tool_dia])
  4189. self.tot_drill_cnt += drill_cnt
  4190. try:
  4191. # Find no of slots for the current tool
  4192. for slot in self.slots:
  4193. if slot['tool'] == tool_no:
  4194. slot_cnt += 1
  4195. self.tot_slot_cnt += slot_cnt
  4196. except AttributeError:
  4197. # log.debug("No slots in the Excellon file")
  4198. # slot editing not implemented
  4199. pass
  4200. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  4201. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4202. self.tools_table_exc.setItem(self.tool_row, 0, id) # Tool name/id
  4203. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  4204. # There are no drill bits in MM with more than 3 decimals diameter
  4205. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  4206. if self.units == 'MM':
  4207. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  4208. else:
  4209. dia = QtWidgets.QTableWidgetItem('%.3f' % self.olddia_newdia[tool_no])
  4210. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  4211. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  4212. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4213. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  4214. if slot_cnt > 0:
  4215. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  4216. else:
  4217. slot_count = QtWidgets.QTableWidgetItem('')
  4218. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4219. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  4220. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  4221. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  4222. self.tool_row += 1
  4223. # make the diameter column editable
  4224. for row in range(self.tool_row):
  4225. self.tools_table_exc.item(row, 1).setFlags(
  4226. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4227. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  4228. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  4229. # add a last row with the Total number of drills
  4230. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  4231. # it will have to have the foreground color (font color) white
  4232. empty = QtWidgets.QTableWidgetItem('9998')
  4233. empty.setForeground(QtGui.QColor(255, 255, 255))
  4234. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  4235. empty_b = QtWidgets.QTableWidgetItem('')
  4236. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  4237. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  4238. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  4239. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4240. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4241. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  4242. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  4243. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  4244. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  4245. font = QtGui.QFont()
  4246. font.setBold(True)
  4247. font.setWeight(75)
  4248. for k in [1, 2]:
  4249. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  4250. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  4251. self.tool_row += 1
  4252. # add a last row with the Total number of slots
  4253. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  4254. # it will have to have the foreground color (font color) white
  4255. empty_2 = QtWidgets.QTableWidgetItem('9999')
  4256. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  4257. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  4258. empty_3 = QtWidgets.QTableWidgetItem('')
  4259. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  4260. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  4261. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  4262. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4263. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4264. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  4265. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  4266. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  4267. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  4268. for kl in [1, 2, 3]:
  4269. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  4270. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  4271. # all the tools are selected by default
  4272. self.tools_table_exc.selectColumn(0)
  4273. #
  4274. self.tools_table_exc.resizeColumnsToContents()
  4275. self.tools_table_exc.resizeRowsToContents()
  4276. vertical_header = self.tools_table_exc.verticalHeader()
  4277. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4278. vertical_header.hide()
  4279. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4280. horizontal_header = self.tools_table_exc.horizontalHeader()
  4281. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  4282. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4283. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  4284. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4285. # horizontal_header.setStretchLastSection(True)
  4286. # self.tools_table_exc.setSortingEnabled(True)
  4287. # sort by tool diameter
  4288. self.tools_table_exc.sortItems(1)
  4289. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  4290. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  4291. # use them
  4292. self.tool2tooldia.clear()
  4293. for row in range(self.tools_table_exc.rowCount() - 2):
  4294. tool = int(self.tools_table_exc.item(row, 0).text())
  4295. diameter = float(self.tools_table_exc.item(row, 1).text())
  4296. self.tool2tooldia[tool] = diameter
  4297. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  4298. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  4299. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  4300. self.tools_table_exc.clearSelection()
  4301. # Remove anything else in the GUI Selected Tab
  4302. self.app.ui.selected_scroll_area.takeWidget()
  4303. # Put ourself in the GUI Selected Tab
  4304. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  4305. # Switch notebook to Selected page
  4306. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4307. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  4308. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4309. def on_tool_add(self, tooldia=None):
  4310. self.is_modified = True
  4311. if tooldia:
  4312. tool_dia = tooldia
  4313. else:
  4314. try:
  4315. tool_dia = float(self.addtool_entry.get_value())
  4316. except ValueError:
  4317. # try to convert comma to decimal point. if it's still not working error message and return
  4318. try:
  4319. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  4320. except ValueError:
  4321. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  4322. "use a number.")
  4323. )
  4324. return
  4325. if tool_dia not in self.olddia_newdia:
  4326. storage_elem = FlatCAMGeoEditor.make_storage()
  4327. self.storage_dict[tool_dia] = storage_elem
  4328. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  4329. # each time a tool diameter is edited or added
  4330. self.olddia_newdia[tool_dia] = tool_dia
  4331. else:
  4332. self.app.inform.emit(_("[WARNING_NOTCL]Tool already in the original or actual tool list.\n"
  4333. "Save and reedit Excellon if you need to add this tool. ")
  4334. )
  4335. return
  4336. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  4337. # we add a new entry in the tool2tooldia dict
  4338. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  4339. self.app.inform.emit(_("[success]Added new tool with dia: %s %s") % (str(tool_dia), str(self.units)))
  4340. self.build_ui()
  4341. # make a quick sort through the tool2tooldia dict so we find which row to select
  4342. row_to_be_selected = None
  4343. for key in sorted(self.tool2tooldia):
  4344. if self.tool2tooldia[key] == tool_dia:
  4345. row_to_be_selected = int(key) - 1
  4346. break
  4347. self.tools_table_exc.selectRow(row_to_be_selected)
  4348. def on_tool_delete(self, dia=None):
  4349. self.is_modified = True
  4350. deleted_tool_dia_list = []
  4351. deleted_tool_offset_list = []
  4352. try:
  4353. if dia is None or dia is False:
  4354. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  4355. for index in self.tools_table_exc.selectionModel().selectedRows():
  4356. row = index.row()
  4357. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  4358. else:
  4359. if isinstance(dia, list):
  4360. for dd in dia:
  4361. deleted_tool_dia_list.append(float('%.4f' % dd))
  4362. else:
  4363. deleted_tool_dia_list.append(float('%.4f' % dia))
  4364. except:
  4365. self.app.inform.emit(_("[WARNING_NOTCL]Select a tool in Tool Table"))
  4366. return
  4367. for deleted_tool_dia in deleted_tool_dia_list:
  4368. # delete de tool offset
  4369. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  4370. # delete the storage used for that tool
  4371. storage_elem = FlatCAMGeoEditor.make_storage()
  4372. self.storage_dict[deleted_tool_dia] = storage_elem
  4373. self.storage_dict.pop(deleted_tool_dia, None)
  4374. # I've added this flag_del variable because dictionary don't like
  4375. # having keys deleted while iterating through them
  4376. flag_del = []
  4377. # self.points_edit.pop(deleted_tool_dia, None)
  4378. for deleted_tool in self.tool2tooldia:
  4379. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  4380. flag_del.append(deleted_tool)
  4381. if flag_del:
  4382. for tool_to_be_deleted in flag_del:
  4383. # delete the tool
  4384. self.tool2tooldia.pop(tool_to_be_deleted, None)
  4385. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  4386. # number of drills from before was deleter
  4387. self.points_edit[deleted_tool_dia] = []
  4388. flag_del = []
  4389. self.olddia_newdia.pop(deleted_tool_dia, None)
  4390. self.app.inform.emit(_("[success]Deleted tool with dia: %s %s") % (str(deleted_tool_dia), str(self.units)))
  4391. self.replot()
  4392. # self.app.inform.emit("Could not delete selected tool")
  4393. self.build_ui()
  4394. def on_tool_edit(self):
  4395. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4396. self.tools_table_exc.itemChanged.disconnect()
  4397. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  4398. self.is_modified = True
  4399. geometry = []
  4400. current_table_dia_edited = None
  4401. if self.tools_table_exc.currentItem() is not None:
  4402. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  4403. row_of_item_changed = self.tools_table_exc.currentRow()
  4404. # rows start with 0, tools start with 1 so we adjust the value by 1
  4405. key_in_tool2tooldia = row_of_item_changed + 1
  4406. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  4407. # tool diameter is not used so we create a new tool with the desired diameter
  4408. if current_table_dia_edited not in self.olddia_newdia.values():
  4409. # update the dict that holds as keys our initial diameters and as values the edited diameters
  4410. self.olddia_newdia[dia_changed] = current_table_dia_edited
  4411. # update the dict that holds tool_no as key and tool_dia as value
  4412. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  4413. # update the tool offset
  4414. modified_offset = self.exc_obj.tool_offset.pop(dia_changed)
  4415. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  4416. self.replot()
  4417. else:
  4418. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  4419. factor = current_table_dia_edited / dia_changed
  4420. for shape in self.storage_dict[dia_changed].get_objects():
  4421. geometry.append(DrawToolShape(
  4422. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  4423. self.points_edit[current_table_dia_edited].append((0, 0))
  4424. self.add_exc_shape(geometry, self.storage_dict[current_table_dia_edited])
  4425. self.on_tool_delete(dia=dia_changed)
  4426. # delete the tool offset
  4427. self.exc_obj.tool_offset.pop(dia_changed, None)
  4428. # we reactivate the signals after the after the tool editing
  4429. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4430. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4431. def on_name_activate(self):
  4432. self.edited_obj_name = self.name_entry.get_value()
  4433. def activate(self):
  4434. self.connect_canvas_event_handlers()
  4435. # self.app.collection.view.keyPressed.connect(self.on_canvas_key)
  4436. self.shapes.enabled = True
  4437. self.tool_shape.enabled = True
  4438. # self.app.app_cursor.enabled = True
  4439. self.app.ui.snap_max_dist_entry.setEnabled(True)
  4440. self.app.ui.corner_snap_btn.setEnabled(True)
  4441. self.app.ui.snap_magnet.setVisible(True)
  4442. self.app.ui.corner_snap_btn.setVisible(True)
  4443. self.app.ui.exc_editor_menu.setDisabled(False)
  4444. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  4445. self.app.ui.update_obj_btn.setEnabled(True)
  4446. self.app.ui.e_editor_cmenu.setEnabled(True)
  4447. self.app.ui.exc_edit_toolbar.setDisabled(False)
  4448. self.app.ui.exc_edit_toolbar.setVisible(True)
  4449. # self.app.ui.snap_toolbar.setDisabled(False)
  4450. # start with GRID toolbar activated
  4451. if self.app.ui.grid_snap_btn.isChecked() is False:
  4452. self.app.ui.grid_snap_btn.trigger()
  4453. # Tell the App that the editor is active
  4454. self.editor_active = True
  4455. def deactivate(self):
  4456. self.disconnect_canvas_event_handlers()
  4457. self.clear()
  4458. self.app.ui.exc_edit_toolbar.setDisabled(True)
  4459. settings = QSettings("Open Source", "FlatCAM")
  4460. if settings.contains("layout"):
  4461. layout = settings.value('layout', type=str)
  4462. if layout == 'standard':
  4463. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4464. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4465. self.app.ui.corner_snap_btn.setEnabled(False)
  4466. self.app.ui.snap_magnet.setVisible(False)
  4467. self.app.ui.corner_snap_btn.setVisible(False)
  4468. elif layout == 'compact':
  4469. # self.app.ui.exc_edit_toolbar.setVisible(True)
  4470. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4471. self.app.ui.corner_snap_btn.setEnabled(False)
  4472. self.app.ui.snap_magnet.setVisible(True)
  4473. self.app.ui.corner_snap_btn.setVisible(True)
  4474. else:
  4475. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4476. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4477. self.app.ui.corner_snap_btn.setEnabled(False)
  4478. self.app.ui.snap_magnet.setVisible(False)
  4479. self.app.ui.corner_snap_btn.setVisible(False)
  4480. # set the Editor Toolbar visibility to what was before entering in the Editor
  4481. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  4482. else self.app.ui.exc_edit_toolbar.setVisible(True)
  4483. # Disable visuals
  4484. self.shapes.enabled = False
  4485. self.tool_shape.enabled = False
  4486. # self.app.app_cursor.enabled = False
  4487. # Tell the app that the editor is no longer active
  4488. self.editor_active = False
  4489. self.app.ui.exc_editor_menu.setDisabled(True)
  4490. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  4491. self.app.ui.update_obj_btn.setEnabled(False)
  4492. self.app.ui.g_editor_cmenu.setEnabled(False)
  4493. self.app.ui.e_editor_cmenu.setEnabled(False)
  4494. # Show original geometry
  4495. if self.exc_obj:
  4496. self.exc_obj.visible = True
  4497. def connect_canvas_event_handlers(self):
  4498. ## Canvas events
  4499. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  4500. # but those from FlatCAMGeoEditor
  4501. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  4502. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  4503. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4504. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  4505. self.app.collection.view.clicked.disconnect()
  4506. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  4507. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  4508. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  4509. def disconnect_canvas_event_handlers(self):
  4510. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  4511. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  4512. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  4513. # we restore the key and mouse control to FlatCAMApp method
  4514. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  4515. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  4516. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4517. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  4518. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  4519. def clear(self):
  4520. self.active_tool = None
  4521. # self.shape_buffer = []
  4522. self.selected = []
  4523. self.points_edit = {}
  4524. self.new_tools = {}
  4525. self.new_drills = []
  4526. self.storage_dict = {}
  4527. self.shapes.clear(update=True)
  4528. self.tool_shape.clear(update=True)
  4529. # self.storage = FlatCAMExcEditor.make_storage()
  4530. self.replot()
  4531. def edit_fcexcellon(self, exc_obj):
  4532. """
  4533. Imports the geometry from the given FlatCAM Excellon object
  4534. into the editor.
  4535. :param fcgeometry: FlatCAMExcellon
  4536. :return: None
  4537. """
  4538. assert isinstance(exc_obj, Excellon), \
  4539. "Expected an Excellon Object, got %s" % type(exc_obj)
  4540. self.deactivate()
  4541. self.activate()
  4542. # Hide original geometry
  4543. self.exc_obj = exc_obj
  4544. exc_obj.visible = False
  4545. # Set selection tolerance
  4546. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  4547. self.select_tool("select")
  4548. self.set_ui()
  4549. # now that we hava data, create the GUI interface and add it to the Tool Tab
  4550. self.build_ui()
  4551. # we activate this after the initial build as we don't need to see the tool been populated
  4552. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4553. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  4554. # and then add it to the storage elements (each storage elements is a member of a list
  4555. for tool_dia in self.points_edit:
  4556. storage_elem = FlatCAMGeoEditor.make_storage()
  4557. for point in self.points_edit[tool_dia]:
  4558. # make a '+' sign, the line length is the tool diameter
  4559. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  4560. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  4561. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  4562. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  4563. shape = MultiLineString([(start_hor_line, stop_hor_line),(start_vert_line, stop_vert_line)])
  4564. if shape is not None:
  4565. self.add_exc_shape(DrawToolShape(shape), storage_elem)
  4566. self.storage_dict[tool_dia] = storage_elem
  4567. self.replot()
  4568. # add a first tool in the Tool Table but only if the Excellon Object is empty
  4569. if not self.tool2tooldia:
  4570. self.on_tool_add(tooldia=1.00)
  4571. def update_fcexcellon(self, exc_obj):
  4572. """
  4573. Create a new Excellon object that contain the edited content of the source Excellon object
  4574. :param exc_obj: FlatCAMExcellon
  4575. :return: None
  4576. """
  4577. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  4578. # the values of this dict are coordinates of the holes (drills)
  4579. edited_points = {}
  4580. for storage_tooldia in self.storage_dict:
  4581. for x in self.storage_dict[storage_tooldia].get_objects():
  4582. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  4583. # each MultiLineString is made out of Linestrings
  4584. # select first Linestring object in the current MultiLineString
  4585. first_linestring = x.geo[0]
  4586. # get it's coordinates
  4587. first_linestring_coords = first_linestring.coords
  4588. x_coord = first_linestring_coords[0][0] + (float(storage_tooldia) / 2)
  4589. y_coord = first_linestring_coords[0][1]
  4590. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  4591. # edited_points dictionary
  4592. point = (x_coord, y_coord)
  4593. if not storage_tooldia in edited_points:
  4594. edited_points[storage_tooldia] = [point]
  4595. else:
  4596. edited_points[storage_tooldia].append(point)
  4597. # recreate the drills and tools to be added to the new Excellon edited object
  4598. # first, we look in the tool table if one of the tool diameters was changed then
  4599. # append that a tuple formed by (old_dia, edited_dia) to a list
  4600. changed_key = []
  4601. for initial_dia in self.olddia_newdia:
  4602. edited_dia = self.olddia_newdia[initial_dia]
  4603. if edited_dia != initial_dia:
  4604. for old_dia in edited_points:
  4605. if old_dia == initial_dia:
  4606. changed_key.append((old_dia, edited_dia))
  4607. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  4608. # (and we have to add it)
  4609. # because in case we have drill points it will have to be already added in edited_points
  4610. # if initial_dia not in edited_points.keys():
  4611. # edited_points[initial_dia] = []
  4612. for el in changed_key:
  4613. edited_points[el[1]] = edited_points.pop(el[0])
  4614. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  4615. # ordered_edited_points is a ordered list of tuples;
  4616. # element[0] of the tuple is the diameter and
  4617. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  4618. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  4619. current_tool = 0
  4620. for tool_dia in ordered_edited_points:
  4621. current_tool += 1
  4622. # create the self.tools for the new Excellon object (the one with edited content)
  4623. name = str(current_tool)
  4624. spec = {"C": float(tool_dia[0])}
  4625. self.new_tools[name] = spec
  4626. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  4627. self.new_tools[name]['solid_geometry'] = []
  4628. # create the self.drills for the new Excellon object (the one with edited content)
  4629. for point in tool_dia[1]:
  4630. self.new_drills.append(
  4631. {
  4632. 'point': Point(point),
  4633. 'tool': str(current_tool)
  4634. }
  4635. )
  4636. # repopulate the 'solid_geometry' for each tool
  4637. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  4638. self.new_tools[name]['solid_geometry'].append(poly)
  4639. if self.is_modified is True:
  4640. if "_edit" in self.edited_obj_name:
  4641. try:
  4642. id = int(self.edited_obj_name[-1]) + 1
  4643. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  4644. except ValueError:
  4645. self.edited_obj_name += "_1"
  4646. else:
  4647. self.edited_obj_name += "_edit"
  4648. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  4649. 'params': [self.edited_obj_name]})
  4650. if self.exc_obj.slots:
  4651. self.new_slots = self.exc_obj.slots
  4652. self.new_tool_offset = self.exc_obj.tool_offset
  4653. # reset the tool table
  4654. self.tools_table_exc.clear()
  4655. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  4656. self.last_tool_selected = None
  4657. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  4658. self.app.collection.set_active(self.exc_obj.options['name'])
  4659. self.app.collection.delete_active()
  4660. # restore GUI to the Selected TAB
  4661. # Remove anything else in the GUI
  4662. self.app.ui.tool_scroll_area.takeWidget()
  4663. # Switch notebook to Selected page
  4664. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4665. def update_options(self, obj):
  4666. try:
  4667. if not obj.options:
  4668. obj.options = {}
  4669. obj.options['xmin'] = 0
  4670. obj.options['ymin'] = 0
  4671. obj.options['xmax'] = 0
  4672. obj.options['ymax'] = 0
  4673. return True
  4674. else:
  4675. return False
  4676. except AttributeError:
  4677. obj.options = {}
  4678. return True
  4679. def new_edited_excellon(self, outname):
  4680. """
  4681. Creates a new Excellon object for the edited Excellon. Thread-safe.
  4682. :param outname: Name of the resulting object. None causes the
  4683. name to be that of the file.
  4684. :type outname: str
  4685. :return: None
  4686. """
  4687. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  4688. self.exc_obj.options['name'])
  4689. # How the object should be initialized
  4690. def obj_init(excellon_obj, app_obj):
  4691. # self.progress.emit(20)
  4692. excellon_obj.drills = self.new_drills
  4693. excellon_obj.tools = self.new_tools
  4694. excellon_obj.slots = self.new_slots
  4695. excellon_obj.tool_offset = self.new_tool_offset
  4696. excellon_obj.options['name'] = outname
  4697. try:
  4698. excellon_obj.create_geometry()
  4699. except KeyError:
  4700. self.app.inform.emit(
  4701. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  4702. )
  4703. except:
  4704. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  4705. msg += traceback.format_exc()
  4706. app_obj.inform.emit(msg)
  4707. raise
  4708. # raise
  4709. with self.app.proc_container.new(_("Creating Excellon.")):
  4710. try:
  4711. self.app.new_object("excellon", outname, obj_init)
  4712. except Exception as e:
  4713. log.error("Error on object creation: %s" % str(e))
  4714. self.app.progress.emit(100)
  4715. return
  4716. self.app.inform.emit(_("[success]Excellon editing finished."))
  4717. # self.progress.emit(100)
  4718. def on_tool_select(self, tool):
  4719. """
  4720. Behavior of the toolbar. Tool initialization.
  4721. :rtype : None
  4722. """
  4723. current_tool = tool
  4724. self.app.log.debug("on_tool_select('%s')" % tool)
  4725. if self.last_tool_selected is None and current_tool is not 'select':
  4726. # self.draw_app.select_tool('select')
  4727. self.complete = True
  4728. current_tool = 'select'
  4729. self.app.inform.emit(_("[WARNING_NOTCL]Cancelled. There is no Tool/Drill selected"))
  4730. # This is to make the group behave as radio group
  4731. if current_tool in self.tools_exc:
  4732. if self.tools_exc[current_tool]["button"].isChecked():
  4733. self.app.log.debug("%s is checked." % current_tool)
  4734. for t in self.tools_exc:
  4735. if t != current_tool:
  4736. self.tools_exc[t]["button"].setChecked(False)
  4737. # this is where the Editor toolbar classes (button's) are instantiated
  4738. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  4739. # self.app.inform.emit(self.active_tool.start_msg)
  4740. else:
  4741. self.app.log.debug("%s is NOT checked." % current_tool)
  4742. for t in self.tools_exc:
  4743. self.tools_exc[t]["button"].setChecked(False)
  4744. self.active_tool = None
  4745. def on_row_selected(self):
  4746. self.selected = []
  4747. try:
  4748. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  4749. self.last_tool_selected = self.tools_table_exc.currentRow() + 1
  4750. for obj in self.storage_dict[selected_dia].get_objects():
  4751. self.selected.append(obj)
  4752. except Exception as e:
  4753. self.app.log.debug(str(e))
  4754. self.replot()
  4755. def toolbar_tool_toggle(self, key):
  4756. self.options[key] = self.sender().isChecked()
  4757. if self.options[key] == True:
  4758. return 1
  4759. else:
  4760. return 0
  4761. def on_canvas_click(self, event):
  4762. """
  4763. event.x and .y have canvas coordinates
  4764. event.xdaya and .ydata have plot coordinates
  4765. :param event: Event object dispatched by Matplotlib
  4766. :return: None
  4767. """
  4768. if event.button is 1:
  4769. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4770. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  4771. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4772. ### Snap coordinates
  4773. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  4774. self.pos = (x, y)
  4775. # print(self.active_tool)
  4776. # Selection with left mouse button
  4777. if self.active_tool is not None and event.button is 1:
  4778. # Dispatch event to active_tool
  4779. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4780. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  4781. # If it is a shape generating tool
  4782. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  4783. if self.current_storage is not None:
  4784. self.on_exc_shape_complete(self.current_storage)
  4785. self.build_ui()
  4786. # MS: always return to the Select Tool if modifier key is not pressed
  4787. # else return to the current tool
  4788. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4789. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  4790. modifier_to_use = Qt.ControlModifier
  4791. else:
  4792. modifier_to_use = Qt.ShiftModifier
  4793. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  4794. # in the selected list, we removed it. Therefore first click selects, second deselects.
  4795. if key_modifier == modifier_to_use:
  4796. self.select_tool(self.active_tool.name)
  4797. else:
  4798. self.select_tool("select")
  4799. return
  4800. if isinstance(self.active_tool, FCDrillSelect):
  4801. # self.app.log.debug("Replotting after click.")
  4802. self.replot()
  4803. else:
  4804. self.app.log.debug("No active tool to respond to click!")
  4805. def on_exc_shape_complete(self, storage):
  4806. self.app.log.debug("on_shape_complete()")
  4807. # Add shape
  4808. if type(storage) is list:
  4809. for item_storage in storage:
  4810. self.add_exc_shape(self.active_tool.geometry, item_storage)
  4811. else:
  4812. self.add_exc_shape(self.active_tool.geometry, storage)
  4813. # Remove any utility shapes
  4814. self.delete_utility_geometry()
  4815. self.tool_shape.clear(update=True)
  4816. # Replot and reset tool.
  4817. self.replot()
  4818. # self.active_tool = type(self.active_tool)(self)
  4819. def add_exc_shape(self, shape, storage):
  4820. """
  4821. Adds a shape to the shape storage.
  4822. :param shape: Shape to be added.
  4823. :type shape: DrawToolShape
  4824. :return: None
  4825. """
  4826. # List of DrawToolShape?
  4827. if isinstance(shape, list):
  4828. for subshape in shape:
  4829. self.add_exc_shape(subshape, storage)
  4830. return
  4831. assert isinstance(shape, DrawToolShape), \
  4832. "Expected a DrawToolShape, got %s" % str(type(shape))
  4833. assert shape.geo is not None, \
  4834. "Shape object has empty geometry (None)"
  4835. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4836. not isinstance(shape.geo, list), \
  4837. "Shape objects has empty geometry ([])"
  4838. if isinstance(shape, DrawToolUtilityShape):
  4839. self.utility.append(shape)
  4840. else:
  4841. storage.insert(shape) # TODO: Check performance
  4842. def add_shape(self, shape):
  4843. """
  4844. Adds a shape to the shape storage.
  4845. :param shape: Shape to be added.
  4846. :type shape: DrawToolShape
  4847. :return: None
  4848. """
  4849. # List of DrawToolShape?
  4850. if isinstance(shape, list):
  4851. for subshape in shape:
  4852. self.add_shape(subshape)
  4853. return
  4854. assert isinstance(shape, DrawToolShape), \
  4855. "Expected a DrawToolShape, got %s" % type(shape)
  4856. assert shape.geo is not None, \
  4857. "Shape object has empty geometry (None)"
  4858. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4859. not isinstance(shape.geo, list), \
  4860. "Shape objects has empty geometry ([])"
  4861. if isinstance(shape, DrawToolUtilityShape):
  4862. self.utility.append(shape)
  4863. else:
  4864. self.storage.insert(shape) # TODO: Check performance
  4865. def on_canvas_click_release(self, event):
  4866. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  4867. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  4868. if self.app.grid_status():
  4869. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4870. else:
  4871. pos = (pos_canvas[0], pos_canvas[1])
  4872. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4873. # canvas menu
  4874. try:
  4875. if event.button == 2: # right click
  4876. if self.app.panning_action is True:
  4877. self.app.panning_action = False
  4878. else:
  4879. self.app.cursor = QtGui.QCursor()
  4880. self.app.ui.popMenu.popup(self.app.cursor.pos())
  4881. except Exception as e:
  4882. log.warning("Error: %s" % str(e))
  4883. raise
  4884. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4885. # selection and then select a type of selection ("enclosing" or "touching")
  4886. try:
  4887. if event.button == 1: # left click
  4888. if self.app.selection_type is not None:
  4889. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  4890. self.app.selection_type = None
  4891. elif isinstance(self.active_tool, FCDrillSelect):
  4892. # Dispatch event to active_tool
  4893. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4894. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  4895. # self.app.inform.emit(msg)
  4896. self.active_tool.click_release((self.pos[0], self.pos[1]))
  4897. self.replot()
  4898. except Exception as e:
  4899. log.warning("Error: %s" % str(e))
  4900. raise
  4901. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  4902. """
  4903. :param start_pos: mouse position when the selection LMB click was done
  4904. :param end_pos: mouse position when the left mouse button is released
  4905. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4906. :type Bool
  4907. :return:
  4908. """
  4909. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4910. self.app.delete_selection_shape()
  4911. for storage in self.storage_dict:
  4912. for obj in self.storage_dict[storage].get_objects():
  4913. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  4914. (sel_type is False and poly_selection.intersects(obj.geo)):
  4915. if self.key == self.app.defaults["global_mselect_key"]:
  4916. if obj in self.selected:
  4917. self.selected.remove(obj)
  4918. else:
  4919. # add the object to the selected shapes
  4920. self.selected.append(obj)
  4921. else:
  4922. self.selected.append(obj)
  4923. # select the diameter of the selected shape in the tool table
  4924. for storage in self.storage_dict:
  4925. for shape_s in self.selected:
  4926. if shape_s in self.storage_dict[storage].get_objects():
  4927. for key in self.tool2tooldia:
  4928. if self.tool2tooldia[key] == storage:
  4929. item = self.tools_table_exc.item((key - 1), 1)
  4930. self.tools_table_exc.setCurrentItem(item)
  4931. self.last_tool_selected = key
  4932. # item.setSelected(True)
  4933. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  4934. self.replot()
  4935. def on_canvas_move(self, event):
  4936. """
  4937. Called on 'mouse_move' event
  4938. event.pos have canvas screen coordinates
  4939. :param event: Event object dispatched by VisPy SceneCavas
  4940. :return: None
  4941. """
  4942. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4943. event.xdata, event.ydata = pos[0], pos[1]
  4944. self.x = event.xdata
  4945. self.y = event.ydata
  4946. # Prevent updates on pan
  4947. # if len(event.buttons) > 0:
  4948. # return
  4949. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4950. if event.button == 2:
  4951. self.app.panning_action = True
  4952. return
  4953. else:
  4954. self.app.panning_action = False
  4955. try:
  4956. x = float(event.xdata)
  4957. y = float(event.ydata)
  4958. except TypeError:
  4959. return
  4960. if self.active_tool is None:
  4961. return
  4962. ### Snap coordinates
  4963. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  4964. self.snap_x = x
  4965. self.snap_y = y
  4966. # update the position label in the infobar since the APP mouse event handlers are disconnected
  4967. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4968. "<b>Y</b>: %.4f" % (x, y))
  4969. if self.pos is None:
  4970. self.pos = (0, 0)
  4971. dx = x - self.pos[0]
  4972. dy = y - self.pos[1]
  4973. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  4974. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4975. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4976. ### Utility geometry (animated)
  4977. geo = self.active_tool.utility_geometry(data=(x, y))
  4978. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  4979. # Remove any previous utility shape
  4980. self.tool_shape.clear(update=True)
  4981. self.draw_utility_geometry(geo=geo)
  4982. ### Selection area on canvas section ###
  4983. dx = pos[0] - self.pos[0]
  4984. if event.is_dragging == 1 and event.button == 1:
  4985. self.app.delete_selection_shape()
  4986. if dx < 0:
  4987. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  4988. color=self.app.defaults["global_alt_sel_line"],
  4989. face_color=self.app.defaults['global_alt_sel_fill'])
  4990. self.app.selection_type = False
  4991. else:
  4992. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  4993. self.app.selection_type = True
  4994. else:
  4995. self.app.selection_type = None
  4996. # Update cursor
  4997. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  4998. def on_canvas_key_release(self, event):
  4999. self.key = None
  5000. def draw_utility_geometry(self, geo):
  5001. # Add the new utility shape
  5002. try:
  5003. # this case is for the Font Parse
  5004. for el in list(geo.geo):
  5005. if type(el) == MultiPolygon:
  5006. for poly in el:
  5007. self.tool_shape.add(
  5008. shape=poly,
  5009. color=(self.app.defaults["global_draw_color"] + '80'),
  5010. update=False,
  5011. layer=0,
  5012. tolerance=None
  5013. )
  5014. elif type(el) == MultiLineString:
  5015. for linestring in el:
  5016. self.tool_shape.add(
  5017. shape=linestring,
  5018. color=(self.app.defaults["global_draw_color"] + '80'),
  5019. update=False,
  5020. layer=0,
  5021. tolerance=None
  5022. )
  5023. else:
  5024. self.tool_shape.add(
  5025. shape=el,
  5026. color=(self.app.defaults["global_draw_color"] + '80'),
  5027. update=False,
  5028. layer=0,
  5029. tolerance=None
  5030. )
  5031. except TypeError:
  5032. self.tool_shape.add(
  5033. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  5034. update=False, layer=0, tolerance=None)
  5035. self.tool_shape.redraw()
  5036. def replot(self):
  5037. self.plot_all()
  5038. def plot_all(self):
  5039. """
  5040. Plots all shapes in the editor.
  5041. :return: None
  5042. :rtype: None
  5043. """
  5044. # self.app.log.debug("plot_all()")
  5045. self.shapes.clear(update=True)
  5046. for storage in self.storage_dict:
  5047. for shape_plus in self.storage_dict[storage].get_objects():
  5048. if shape_plus.geo is None:
  5049. continue
  5050. if shape_plus in self.selected:
  5051. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  5052. linewidth=2)
  5053. continue
  5054. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  5055. # for shape in self.storage.get_objects():
  5056. # if shape.geo is None: # TODO: This shouldn't have happened
  5057. # continue
  5058. #
  5059. # if shape in self.selected:
  5060. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  5061. # continue
  5062. #
  5063. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  5064. for shape in self.utility:
  5065. self.plot_shape(geometry=shape.geo, linewidth=1)
  5066. continue
  5067. self.shapes.redraw()
  5068. def plot_shape(self, geometry=None, color='black', linewidth=1):
  5069. """
  5070. Plots a geometric object or list of objects without rendering. Plotted objects
  5071. are returned as a list. This allows for efficient/animated rendering.
  5072. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  5073. :param color: Shape color
  5074. :param linewidth: Width of lines in # of pixels.
  5075. :return: List of plotted elements.
  5076. """
  5077. plot_elements = []
  5078. if geometry is None:
  5079. geometry = self.active_tool.geometry
  5080. try:
  5081. for geo in geometry:
  5082. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  5083. ## Non-iterable
  5084. except TypeError:
  5085. ## DrawToolShape
  5086. if isinstance(geometry, DrawToolShape):
  5087. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  5088. ## Polygon: Descend into exterior and each interior.
  5089. if type(geometry) == Polygon:
  5090. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  5091. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  5092. if type(geometry) == LineString or type(geometry) == LinearRing:
  5093. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  5094. if type(geometry) == Point:
  5095. pass
  5096. return plot_elements
  5097. def on_shape_complete(self):
  5098. self.app.log.debug("on_shape_complete()")
  5099. # Add shape
  5100. self.add_shape(self.active_tool.geometry)
  5101. # Remove any utility shapes
  5102. self.delete_utility_geometry()
  5103. self.tool_shape.clear(update=True)
  5104. # Replot and reset tool.
  5105. self.replot()
  5106. # self.active_tool = type(self.active_tool)(self)
  5107. def get_selected(self):
  5108. """
  5109. Returns list of shapes that are selected in the editor.
  5110. :return: List of shapes.
  5111. """
  5112. # return [shape for shape in self.shape_buffer if shape["selected"]]
  5113. return self.selected
  5114. def delete_selected(self):
  5115. temp_ref = [s for s in self.selected]
  5116. for shape_sel in temp_ref:
  5117. self.delete_shape(shape_sel)
  5118. self.selected = []
  5119. self.build_ui()
  5120. self.app.inform.emit(_("[success]Done. Drill(s) deleted."))
  5121. def delete_shape(self, shape):
  5122. self.is_modified = True
  5123. if shape in self.utility:
  5124. self.utility.remove(shape)
  5125. return
  5126. for storage in self.storage_dict:
  5127. # try:
  5128. # self.storage_dict[storage].remove(shape)
  5129. # except:
  5130. # pass
  5131. if shape in self.storage_dict[storage].get_objects():
  5132. self.storage_dict[storage].remove(shape)
  5133. # a hack to make the tool_table display less drills per diameter
  5134. # self.points_edit it's only useful first time when we load the data into the storage
  5135. # but is still used as referecen when building tool_table in self.build_ui()
  5136. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  5137. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  5138. del self.points_edit[storage][0]
  5139. if shape in self.selected:
  5140. self.selected.remove(shape) # TODO: Check performance
  5141. def delete_utility_geometry(self):
  5142. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  5143. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  5144. for_deletion = [shape for shape in self.utility]
  5145. for shape in for_deletion:
  5146. self.delete_shape(shape)
  5147. self.tool_shape.clear(update=True)
  5148. self.tool_shape.redraw()
  5149. def on_delete_btn(self):
  5150. self.delete_selected()
  5151. self.replot()
  5152. def select_tool(self, toolname):
  5153. """
  5154. Selects a drawing tool. Impacts the object and GUI.
  5155. :param toolname: Name of the tool.
  5156. :return: None
  5157. """
  5158. self.tools_exc[toolname]["button"].setChecked(True)
  5159. self.on_tool_select(toolname)
  5160. def set_selected(self, shape):
  5161. # Remove and add to the end.
  5162. if shape in self.selected:
  5163. self.selected.remove(shape)
  5164. self.selected.append(shape)
  5165. def set_unselected(self, shape):
  5166. if shape in self.selected:
  5167. self.selected.remove(shape)
  5168. def on_array_type_combo(self):
  5169. if self.array_type_combo.currentIndex() == 0:
  5170. self.array_circular_frame.hide()
  5171. self.array_linear_frame.show()
  5172. else:
  5173. self.delete_utility_geometry()
  5174. self.array_circular_frame.show()
  5175. self.array_linear_frame.hide()
  5176. self.app.inform.emit(_("Click on the circular array Center position"))
  5177. def on_linear_angle_radio(self):
  5178. val = self.drill_axis_radio.get_value()
  5179. if val == 'A':
  5180. self.linear_angle_spinner.show()
  5181. self.linear_angle_label.show()
  5182. else:
  5183. self.linear_angle_spinner.hide()
  5184. self.linear_angle_label.hide()
  5185. def exc_add_drill(self):
  5186. self.select_tool('add')
  5187. return
  5188. def exc_add_drill_array(self):
  5189. self.select_tool('add_array')
  5190. return
  5191. def exc_resize_drills(self):
  5192. self.select_tool('resize')
  5193. return
  5194. def exc_copy_drills(self):
  5195. self.select_tool('copy')
  5196. return
  5197. def exc_move_drills(self):
  5198. self.select_tool('move')
  5199. return
  5200. def distance(pt1, pt2):
  5201. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  5202. def mag(vec):
  5203. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  5204. def poly2rings(poly):
  5205. return [poly.exterior] + [interior for interior in poly.interiors]