FlatCAMEditor.py 242 KB

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