FlatCAMEditor.py 245 KB

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