FlatCAMEditor.py 243 KB

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