FlatCAMEditor.py 248 KB

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