FlatCAMEditor.py 246 KB

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