FlatCAMEditor.py 246 KB

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