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