FlatCAMEditor.py 242 KB

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