FlatCAMEditor.py 247 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426
  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. # Current snapped mouse pos
  2761. self.snap_x = None
  2762. self.snap_y = None
  2763. self.pos = None
  2764. # signal that there is an action active like polygon or path
  2765. self.in_action = False
  2766. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2767. self.launched_from_shortcuts = False
  2768. def make_callback(thetool):
  2769. def f():
  2770. self.on_tool_select(thetool)
  2771. return f
  2772. for tool in self.tools:
  2773. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2774. self.tools[tool]["button"].setCheckable(True) # Checkable
  2775. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2776. self.app.ui.corner_snap_btn.setCheckable(True)
  2777. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2778. self.options = {
  2779. "global_gridx": 0.1,
  2780. "global_gridy": 0.1,
  2781. "global_snap_max": 0.05,
  2782. "grid_snap": True,
  2783. "corner_snap": False,
  2784. "grid_gap_link": True
  2785. }
  2786. self.app.options_read_form()
  2787. for option in self.options:
  2788. if option in self.app.options:
  2789. self.options[option] = self.app.options[option]
  2790. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2791. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2792. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2793. self.app.ui.grid_gap_link_cb.setChecked(True)
  2794. self.rtree_index = rtindex.Index()
  2795. def entry2option(option, entry):
  2796. try:
  2797. self.options[option] = float(entry.text())
  2798. except Exception as e:
  2799. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2800. return
  2801. def gridx_changed(goption, gentry):
  2802. entry2option(option=goption, entry=gentry)
  2803. # if the grid link is checked copy the value in the GridX field to GridY
  2804. if self.app.ui.grid_gap_link_cb.isChecked():
  2805. self.app.ui.grid_gap_y_entry.set_value(self.app.ui.grid_gap_x_entry.get_value())
  2806. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2807. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2808. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2809. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2810. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2811. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2812. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2813. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2814. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2815. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2816. self.editor_active = False
  2817. # if using Paint store here the tool diameter used
  2818. self.paint_tooldia = None
  2819. self.paint_tool = PaintOptionsTool(self.app, self)
  2820. self.transform_tool = TransformEditorTool(self.app, self)
  2821. def pool_recreated(self, pool):
  2822. self.shapes.pool = pool
  2823. self.tool_shape.pool = pool
  2824. def on_transform_complete(self):
  2825. self.delete_selected()
  2826. self.replot()
  2827. def activate(self):
  2828. self.connect_canvas_event_handlers()
  2829. self.shapes.enabled = True
  2830. self.tool_shape.enabled = True
  2831. self.app.app_cursor.enabled = True
  2832. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2833. self.app.ui.corner_snap_btn.setEnabled(True)
  2834. self.app.ui.snap_magnet.setVisible(True)
  2835. self.app.ui.corner_snap_btn.setVisible(True)
  2836. self.app.ui.geo_editor_menu.setDisabled(False)
  2837. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2838. self.app.ui.update_obj_btn.setEnabled(True)
  2839. self.app.ui.g_editor_cmenu.setEnabled(True)
  2840. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2841. self.app.ui.geo_edit_toolbar.setVisible(True)
  2842. self.app.ui.snap_toolbar.setDisabled(False)
  2843. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2844. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2845. for w in sel_tab_widget_list:
  2846. w.setEnabled(False)
  2847. # Tell the App that the editor is active
  2848. self.editor_active = True
  2849. def deactivate(self):
  2850. self.disconnect_canvas_event_handlers()
  2851. self.clear()
  2852. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2853. settings = QSettings("Open Source", "FlatCAM")
  2854. if settings.contains("layout"):
  2855. layout = settings.value('layout', type=str)
  2856. if layout == 'Standard':
  2857. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2858. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2859. self.app.ui.corner_snap_btn.setEnabled(False)
  2860. self.app.ui.snap_magnet.setVisible(False)
  2861. self.app.ui.corner_snap_btn.setVisible(False)
  2862. elif layout == 'Compact':
  2863. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2864. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2865. self.app.ui.corner_snap_btn.setEnabled(False)
  2866. else:
  2867. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2868. self.app.ui.snap_magnet.setVisible(False)
  2869. self.app.ui.corner_snap_btn.setVisible(False)
  2870. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2871. self.app.ui.corner_snap_btn.setEnabled(False)
  2872. # set the Editor Toolbar visibility to what was before entering in the Editor
  2873. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2874. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2875. # Disable visuals
  2876. self.shapes.enabled = False
  2877. self.tool_shape.enabled = False
  2878. self.app.app_cursor.enabled = False
  2879. self.app.ui.geo_editor_menu.setDisabled(True)
  2880. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2881. self.app.ui.update_obj_btn.setEnabled(False)
  2882. self.app.ui.g_editor_cmenu.setEnabled(False)
  2883. self.app.ui.e_editor_cmenu.setEnabled(False)
  2884. # Tell the app that the editor is no longer active
  2885. self.editor_active = False
  2886. # Show original geometry
  2887. if self.fcgeometry:
  2888. self.fcgeometry.visible = True
  2889. def connect_canvas_event_handlers(self):
  2890. ## Canvas events
  2891. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2892. # but those from FlatCAMGeoEditor
  2893. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2894. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2895. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2896. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2897. self.app.collection.view.clicked.disconnect()
  2898. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2899. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2900. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  2901. def disconnect_canvas_event_handlers(self):
  2902. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2903. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2904. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  2905. # we restore the key and mouse control to FlatCAMApp method
  2906. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2907. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2908. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2909. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2910. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2911. def add_shape(self, shape):
  2912. """
  2913. Adds a shape to the shape storage.
  2914. :param shape: Shape to be added.
  2915. :type shape: DrawToolShape
  2916. :return: None
  2917. """
  2918. # List of DrawToolShape?
  2919. if isinstance(shape, list):
  2920. for subshape in shape:
  2921. self.add_shape(subshape)
  2922. return
  2923. assert isinstance(shape, DrawToolShape), \
  2924. "Expected a DrawToolShape, got %s" % type(shape)
  2925. assert shape.geo is not None, \
  2926. "Shape object has empty geometry (None)"
  2927. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2928. not isinstance(shape.geo, list), \
  2929. "Shape objects has empty geometry ([])"
  2930. if isinstance(shape, DrawToolUtilityShape):
  2931. self.utility.append(shape)
  2932. else:
  2933. self.storage.insert(shape) # TODO: Check performance
  2934. def delete_utility_geometry(self):
  2935. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2936. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2937. for_deletion = [shape for shape in self.utility]
  2938. for shape in for_deletion:
  2939. self.delete_shape(shape)
  2940. self.tool_shape.clear(update=True)
  2941. self.tool_shape.redraw()
  2942. def cutpath(self):
  2943. selected = self.get_selected()
  2944. tools = selected[1:]
  2945. toolgeo = cascaded_union([shp.geo for shp in tools])
  2946. target = selected[0]
  2947. if type(target.geo) == Polygon:
  2948. for ring in poly2rings(target.geo):
  2949. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  2950. self.delete_shape(target)
  2951. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  2952. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  2953. self.delete_shape(target)
  2954. elif type(target.geo) == MultiLineString:
  2955. try:
  2956. for linestring in target.geo:
  2957. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  2958. except:
  2959. self.app.log.warning("Current LinearString does not intersect the target")
  2960. self.delete_shape(target)
  2961. else:
  2962. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  2963. self.replot()
  2964. def toolbar_tool_toggle(self, key):
  2965. self.options[key] = self.sender().isChecked()
  2966. if self.options[key] == True:
  2967. return 1
  2968. else:
  2969. return 0
  2970. def clear(self):
  2971. self.active_tool = None
  2972. # self.shape_buffer = []
  2973. self.selected = []
  2974. self.shapes.clear(update=True)
  2975. self.tool_shape.clear(update=True)
  2976. self.storage = FlatCAMGeoEditor.make_storage()
  2977. self.replot()
  2978. def edit_fcgeometry(self, fcgeometry):
  2979. """
  2980. Imports the geometry from the given FlatCAM Geometry object
  2981. into the editor.
  2982. :param fcgeometry: FlatCAMGeometry
  2983. :return: None
  2984. """
  2985. assert isinstance(fcgeometry, Geometry), \
  2986. "Expected a Geometry, got %s" % type(fcgeometry)
  2987. self.deactivate()
  2988. self.activate()
  2989. # Hide original geometry
  2990. self.fcgeometry = fcgeometry
  2991. fcgeometry.visible = False
  2992. # Set selection tolerance
  2993. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  2994. self.select_tool("select")
  2995. # Link shapes into editor.
  2996. for shape in fcgeometry.flatten():
  2997. if shape is not None: # TODO: Make flatten never create a None
  2998. if type(shape) == Polygon:
  2999. self.add_shape(DrawToolShape(shape.exterior))
  3000. for inter in shape.interiors:
  3001. self.add_shape(DrawToolShape(inter))
  3002. else:
  3003. self.add_shape(DrawToolShape(shape))
  3004. self.replot()
  3005. # start with GRID toolbar activated
  3006. if self.app.ui.grid_snap_btn.isChecked() == False:
  3007. self.app.ui.grid_snap_btn.trigger()
  3008. def on_buffer_tool(self):
  3009. buff_tool = BufferSelectionTool(self.app, self)
  3010. buff_tool.run()
  3011. def on_paint_tool(self):
  3012. paint_tool = PaintOptionsTool(self.app, self)
  3013. paint_tool.run()
  3014. def on_transform_tool(self):
  3015. transform_tool = TransformEditorTool(self.app, self)
  3016. transform_tool.run()
  3017. def on_tool_select(self, tool):
  3018. """
  3019. Behavior of the toolbar. Tool initialization.
  3020. :rtype : None
  3021. """
  3022. self.app.log.debug("on_tool_select('%s')" % tool)
  3023. # This is to make the group behave as radio group
  3024. if tool in self.tools:
  3025. if self.tools[tool]["button"].isChecked():
  3026. self.app.log.debug("%s is checked." % tool)
  3027. for t in self.tools:
  3028. if t != tool:
  3029. self.tools[t]["button"].setChecked(False)
  3030. self.active_tool = self.tools[tool]["constructor"](self)
  3031. if not isinstance(self.active_tool, FCSelect):
  3032. self.app.inform.emit(self.active_tool.start_msg)
  3033. else:
  3034. self.app.log.debug("%s is NOT checked." % tool)
  3035. for t in self.tools:
  3036. self.tools[t]["button"].setChecked(False)
  3037. self.active_tool = None
  3038. def draw_tool_path(self):
  3039. self.select_tool('path')
  3040. return
  3041. def draw_tool_rectangle(self):
  3042. self.select_tool('rectangle')
  3043. return
  3044. def on_grid_toggled(self):
  3045. self.toolbar_tool_toggle("grid_snap")
  3046. # make sure that the cursor shape is enabled/disabled, too
  3047. if self.options['grid_snap'] is True:
  3048. self.app.app_cursor.enabled = True
  3049. else:
  3050. self.app.app_cursor.enabled = False
  3051. def on_canvas_click(self, event):
  3052. """
  3053. event.x and .y have canvas coordinates
  3054. event.xdaya and .ydata have plot coordinates
  3055. :param event: Event object dispatched by Matplotlib
  3056. :return: None
  3057. """
  3058. if event.button is 1:
  3059. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3060. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3061. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3062. ### Snap coordinates
  3063. x, y = self.snap(self.pos[0], self.pos[1])
  3064. self.pos = (x, y)
  3065. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3066. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3067. if modifiers == QtCore.Qt.ShiftModifier:
  3068. self.app.clipboard.setText(
  3069. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3070. return
  3071. # Selection with left mouse button
  3072. if self.active_tool is not None and event.button is 1:
  3073. # Dispatch event to active_tool
  3074. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3075. msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3076. # If it is a shape generating tool
  3077. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3078. self.on_shape_complete()
  3079. # MS: always return to the Select Tool if modifier key is not pressed
  3080. # else return to the current tool
  3081. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3082. if self.app.defaults["global_mselect_key"] == 'Control':
  3083. modifier_to_use = Qt.ControlModifier
  3084. else:
  3085. modifier_to_use = Qt.ShiftModifier
  3086. # if modifier key is pressed then we add to the selected list the current shape but if
  3087. # it's already in the selected list, we removed it. Therefore first click selects, second deselects.
  3088. if key_modifier == modifier_to_use:
  3089. self.select_tool(self.active_tool.name)
  3090. else:
  3091. self.select_tool("select")
  3092. return
  3093. if isinstance(self.active_tool, FCSelect):
  3094. # self.app.log.debug("Replotting after click.")
  3095. self.replot()
  3096. else:
  3097. self.app.log.debug("No active tool to respond to click!")
  3098. def on_canvas_move(self, event):
  3099. """
  3100. Called on 'mouse_move' event
  3101. event.pos have canvas screen coordinates
  3102. :param event: Event object dispatched by VisPy SceneCavas
  3103. :return: None
  3104. """
  3105. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3106. event.xdata, event.ydata = pos[0], pos[1]
  3107. self.x = event.xdata
  3108. self.y = event.ydata
  3109. # Prevent updates on pan
  3110. # if len(event.buttons) > 0:
  3111. # return
  3112. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3113. if event.button == 2:
  3114. self.app.panning_action = True
  3115. return
  3116. else:
  3117. self.app.panning_action = False
  3118. try:
  3119. x = float(event.xdata)
  3120. y = float(event.ydata)
  3121. except TypeError:
  3122. return
  3123. if self.active_tool is None:
  3124. return
  3125. ### Snap coordinates
  3126. x, y = self.snap(x, y)
  3127. self.snap_x = x
  3128. self.snap_y = y
  3129. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3130. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3131. "<b>Y</b>: %.4f" % (x, y))
  3132. if self.pos is None:
  3133. self.pos = (0, 0)
  3134. dx = x - self.pos[0]
  3135. dy = y - self.pos[1]
  3136. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3137. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3138. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3139. ### Utility geometry (animated)
  3140. geo = self.active_tool.utility_geometry(data=(x, y))
  3141. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3142. # Remove any previous utility shape
  3143. self.tool_shape.clear(update=True)
  3144. self.draw_utility_geometry(geo=geo)
  3145. ### Selection area on canvas section ###
  3146. dx = pos[0] - self.pos[0]
  3147. if event.is_dragging == 1 and event.button == 1:
  3148. self.app.delete_selection_shape()
  3149. if dx < 0:
  3150. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  3151. color=self.app.defaults["global_alt_sel_line"],
  3152. face_color=self.app.defaults['global_alt_sel_fill'])
  3153. self.app.selection_type = False
  3154. else:
  3155. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  3156. self.app.selection_type = True
  3157. else:
  3158. self.app.selection_type = None
  3159. # Update cursor
  3160. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  3161. def on_canvas_click_release(self, event):
  3162. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  3163. if self.app.grid_status():
  3164. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3165. else:
  3166. pos = (pos_canvas[0], pos_canvas[1])
  3167. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3168. # canvas menu
  3169. try:
  3170. if event.button == 2: # right click
  3171. if self.app.panning_action is True:
  3172. self.app.panning_action = False
  3173. else:
  3174. if self.in_action is False:
  3175. self.app.cursor = QtGui.QCursor()
  3176. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3177. else:
  3178. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3179. # right mouse click will finish the action
  3180. if isinstance(self.active_tool, FCShapeTool):
  3181. self.active_tool.click(self.snap(self.x, self.y))
  3182. self.active_tool.make()
  3183. if self.active_tool.complete:
  3184. self.on_shape_complete()
  3185. self.app.inform.emit(_("[success]Done."))
  3186. # MS: always return to the Select Tool if modifier key is not pressed
  3187. # else return to the current tool
  3188. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3189. if self.app.defaults["global_mselect_key"] == 'Control':
  3190. modifier_to_use = Qt.ControlModifier
  3191. else:
  3192. modifier_to_use = Qt.ShiftModifier
  3193. if key_modifier == modifier_to_use:
  3194. self.select_tool(self.active_tool.name)
  3195. else:
  3196. self.select_tool("select")
  3197. except Exception as e:
  3198. log.warning("Error: %s" % str(e))
  3199. return
  3200. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3201. # selection and then select a type of selection ("enclosing" or "touching")
  3202. try:
  3203. if event.button == 1: # left click
  3204. if self.app.selection_type is not None:
  3205. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3206. self.app.selection_type = None
  3207. elif isinstance(self.active_tool, FCSelect):
  3208. # Dispatch event to active_tool
  3209. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3210. msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  3211. # self.app.inform.emit(msg)
  3212. self.replot()
  3213. except Exception as e:
  3214. log.warning("Error: %s" % str(e))
  3215. return
  3216. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3217. """
  3218. :param start_pos: mouse position when the selection LMB click was done
  3219. :param end_pos: mouse position when the left mouse button is released
  3220. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3221. :type Bool
  3222. :return:
  3223. """
  3224. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3225. self.app.delete_selection_shape()
  3226. for obj in self.storage.get_objects():
  3227. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  3228. (sel_type is False and poly_selection.intersects(obj.geo)):
  3229. if self.key == self.app.defaults["global_mselect_key"]:
  3230. if obj in self.selected:
  3231. self.selected.remove(obj)
  3232. else:
  3233. # add the object to the selected shapes
  3234. self.selected.append(obj)
  3235. else:
  3236. if obj not in self.selected:
  3237. self.selected.append(obj)
  3238. self.replot()
  3239. def draw_utility_geometry(self, geo):
  3240. # Add the new utility shape
  3241. try:
  3242. # this case is for the Font Parse
  3243. for el in list(geo.geo):
  3244. if type(el) == MultiPolygon:
  3245. for poly in el:
  3246. self.tool_shape.add(
  3247. shape=poly,
  3248. color=(self.app.defaults["global_draw_color"] + '80'),
  3249. update=False,
  3250. layer=0,
  3251. tolerance=None
  3252. )
  3253. elif type(el) == MultiLineString:
  3254. for linestring in el:
  3255. self.tool_shape.add(
  3256. shape=linestring,
  3257. color=(self.app.defaults["global_draw_color"] + '80'),
  3258. update=False,
  3259. layer=0,
  3260. tolerance=None
  3261. )
  3262. else:
  3263. self.tool_shape.add(
  3264. shape=el,
  3265. color=(self.app.defaults["global_draw_color"] + '80'),
  3266. update=False,
  3267. layer=0,
  3268. tolerance=None
  3269. )
  3270. except TypeError:
  3271. self.tool_shape.add(
  3272. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3273. update=False, layer=0, tolerance=None)
  3274. self.tool_shape.redraw()
  3275. def on_delete_btn(self):
  3276. self.delete_selected()
  3277. self.replot()
  3278. def delete_selected(self):
  3279. tempref = [s for s in self.selected]
  3280. for shape in tempref:
  3281. self.delete_shape(shape)
  3282. self.selected = []
  3283. def delete_shape(self, shape):
  3284. if shape in self.utility:
  3285. self.utility.remove(shape)
  3286. return
  3287. self.storage.remove(shape)
  3288. if shape in self.selected:
  3289. self.selected.remove(shape) # TODO: Check performance
  3290. def on_move(self):
  3291. self.app.ui.geo_move_btn.setChecked(True)
  3292. self.on_tool_select('move')
  3293. def on_move_click(self):
  3294. if not self.selected:
  3295. self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3296. return
  3297. self.on_move()
  3298. self.active_tool.set_origin(self.snap(self.x, self.y))
  3299. def on_copy_click(self):
  3300. if not self.selected:
  3301. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  3302. return
  3303. self.app.ui.geo_copy_btn.setChecked(True)
  3304. self.app.geo_editor.on_tool_select('copy')
  3305. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3306. self.app.geo_editor.x, self.app.geo_editor.y))
  3307. self.app.inform.emit(_("Click on target point."))
  3308. def on_corner_snap(self):
  3309. self.app.ui.corner_snap_btn.trigger()
  3310. def get_selected(self):
  3311. """
  3312. Returns list of shapes that are selected in the editor.
  3313. :return: List of shapes.
  3314. """
  3315. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3316. return self.selected
  3317. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3318. """
  3319. Plots a geometric object or list of objects without rendering. Plotted objects
  3320. are returned as a list. This allows for efficient/animated rendering.
  3321. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3322. :param color: Shape color
  3323. :param linewidth: Width of lines in # of pixels.
  3324. :return: List of plotted elements.
  3325. """
  3326. plot_elements = []
  3327. if geometry is None:
  3328. geometry = self.active_tool.geometry
  3329. try:
  3330. for geo in geometry:
  3331. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3332. ## Non-iterable
  3333. except TypeError:
  3334. ## DrawToolShape
  3335. if isinstance(geometry, DrawToolShape):
  3336. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3337. ## Polygon: Descend into exterior and each interior.
  3338. if type(geometry) == Polygon:
  3339. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3340. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3341. if type(geometry) == LineString or type(geometry) == LinearRing:
  3342. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3343. tolerance=self.fcgeometry.drawing_tolerance))
  3344. if type(geometry) == Point:
  3345. pass
  3346. return plot_elements
  3347. def plot_all(self):
  3348. """
  3349. Plots all shapes in the editor.
  3350. :return: None
  3351. :rtype: None
  3352. """
  3353. # self.app.log.debug("plot_all()")
  3354. self.shapes.clear(update=True)
  3355. for shape in self.storage.get_objects():
  3356. if shape.geo is None: # TODO: This shouldn't have happened
  3357. continue
  3358. if shape in self.selected:
  3359. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3360. continue
  3361. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3362. for shape in self.utility:
  3363. self.plot_shape(geometry=shape.geo, linewidth=1)
  3364. continue
  3365. self.shapes.redraw()
  3366. def replot(self):
  3367. self.plot_all()
  3368. def on_shape_complete(self):
  3369. self.app.log.debug("on_shape_complete()")
  3370. # Add shape
  3371. self.add_shape(self.active_tool.geometry)
  3372. # Remove any utility shapes
  3373. self.delete_utility_geometry()
  3374. self.tool_shape.clear(update=True)
  3375. # Replot and reset tool.
  3376. self.replot()
  3377. # self.active_tool = type(self.active_tool)(self)
  3378. @staticmethod
  3379. def make_storage():
  3380. ## Shape storage.
  3381. storage = FlatCAMRTreeStorage()
  3382. storage.get_points = DrawToolShape.get_pts
  3383. return storage
  3384. def select_tool(self, toolname):
  3385. """
  3386. Selects a drawing tool. Impacts the object and GUI.
  3387. :param toolname: Name of the tool.
  3388. :return: None
  3389. """
  3390. self.tools[toolname]["button"].setChecked(True)
  3391. self.on_tool_select(toolname)
  3392. def set_selected(self, shape):
  3393. # Remove and add to the end.
  3394. if shape in self.selected:
  3395. self.selected.remove(shape)
  3396. self.selected.append(shape)
  3397. def set_unselected(self, shape):
  3398. if shape in self.selected:
  3399. self.selected.remove(shape)
  3400. def snap(self, x, y):
  3401. """
  3402. Adjusts coordinates to snap settings.
  3403. :param x: Input coordinate X
  3404. :param y: Input coordinate Y
  3405. :return: Snapped (x, y)
  3406. """
  3407. snap_x, snap_y = (x, y)
  3408. snap_distance = Inf
  3409. ### Object (corner?) snap
  3410. ### No need for the objects, just the coordinates
  3411. ### in the index.
  3412. if self.options["corner_snap"]:
  3413. try:
  3414. nearest_pt, shape = self.storage.nearest((x, y))
  3415. nearest_pt_distance = distance((x, y), nearest_pt)
  3416. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3417. snap_distance = nearest_pt_distance
  3418. snap_x, snap_y = nearest_pt
  3419. except (StopIteration, AssertionError):
  3420. pass
  3421. ### Grid snap
  3422. if self.options["grid_snap"]:
  3423. if self.options["global_gridx"] != 0:
  3424. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3425. else:
  3426. snap_x_ = x
  3427. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3428. # and it will use the snap distance from GridX entry
  3429. if self.app.ui.grid_gap_link_cb.isChecked():
  3430. if self.options["global_gridx"] != 0:
  3431. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3432. else:
  3433. snap_y_ = y
  3434. else:
  3435. if self.options["global_gridy"] != 0:
  3436. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3437. else:
  3438. snap_y_ = y
  3439. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3440. if nearest_grid_distance < snap_distance:
  3441. snap_x, snap_y = (snap_x_, snap_y_)
  3442. return snap_x, snap_y
  3443. def update_fcgeometry(self, fcgeometry):
  3444. """
  3445. Transfers the geometry tool shape buffer to the selected geometry
  3446. object. The geometry already in the object are removed.
  3447. :param fcgeometry: FlatCAMGeometry
  3448. :return: None
  3449. """
  3450. fcgeometry.solid_geometry = []
  3451. # for shape in self.shape_buffer:
  3452. for shape in self.storage.get_objects():
  3453. fcgeometry.solid_geometry.append(shape.geo)
  3454. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  3455. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  3456. for w in sel_tab_widget_list:
  3457. w.setEnabled(True)
  3458. def update_options(self, obj):
  3459. if self.paint_tooldia:
  3460. obj.options['cnctooldia'] = self.paint_tooldia
  3461. self.paint_tooldia = None
  3462. return True
  3463. else:
  3464. return False
  3465. def union(self):
  3466. """
  3467. Makes union of selected polygons. Original polygons
  3468. are deleted.
  3469. :return: None.
  3470. """
  3471. results = cascaded_union([t.geo for t in self.get_selected()])
  3472. # Delete originals.
  3473. for_deletion = [s for s in self.get_selected()]
  3474. for shape in for_deletion:
  3475. self.delete_shape(shape)
  3476. # Selected geometry is now gone!
  3477. self.selected = []
  3478. self.add_shape(DrawToolShape(results))
  3479. self.replot()
  3480. def intersection(self):
  3481. """
  3482. Makes intersectino of selected polygons. Original polygons are deleted.
  3483. :return: None
  3484. """
  3485. shapes = self.get_selected()
  3486. try:
  3487. results = shapes[0].geo
  3488. except Exception as e:
  3489. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3490. self.app.inform.emit(_("[WARNING_NOTCL]A selection of at least 2 geo items is required to do Intersection."))
  3491. self.select_tool('select')
  3492. return
  3493. for shape in shapes[1:]:
  3494. results = results.intersection(shape.geo)
  3495. # Delete originals.
  3496. for_deletion = [s for s in self.get_selected()]
  3497. for shape in for_deletion:
  3498. self.delete_shape(shape)
  3499. # Selected geometry is now gone!
  3500. self.selected = []
  3501. self.add_shape(DrawToolShape(results))
  3502. self.replot()
  3503. def subtract(self):
  3504. selected = self.get_selected()
  3505. try:
  3506. tools = selected[1:]
  3507. toolgeo = cascaded_union([shp.geo for shp in tools])
  3508. result = selected[0].geo.difference(toolgeo)
  3509. self.delete_shape(selected[0])
  3510. self.add_shape(DrawToolShape(result))
  3511. self.replot()
  3512. except Exception as e:
  3513. log.debug(str(e))
  3514. def buffer(self, buf_distance, join_style):
  3515. selected = self.get_selected()
  3516. if buf_distance < 0:
  3517. self.app.inform.emit(
  3518. _( "[ERROR_NOTCL]Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape"))
  3519. # deselect everything
  3520. self.selected = []
  3521. self.replot()
  3522. return
  3523. if len(selected) == 0:
  3524. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3525. return
  3526. if not isinstance(buf_distance, float):
  3527. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3528. # deselect everything
  3529. self.selected = []
  3530. self.replot()
  3531. return
  3532. pre_buffer = cascaded_union([t.geo for t in selected])
  3533. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3534. if results.is_empty:
  3535. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3536. # deselect everything
  3537. self.selected = []
  3538. self.replot()
  3539. return
  3540. self.add_shape(DrawToolShape(results))
  3541. self.replot()
  3542. self.app.inform.emit(_("[success]Full buffer geometry created."))
  3543. def buffer_int(self, buf_distance, join_style):
  3544. selected = self.get_selected()
  3545. if buf_distance < 0:
  3546. self.app.inform.emit(
  3547. _("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3548. "Use Buffer interior to generate an 'inside' shape")
  3549. )
  3550. # deselect everything
  3551. self.selected = []
  3552. self.replot()
  3553. return
  3554. if len(selected) == 0:
  3555. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3556. return
  3557. if not isinstance(buf_distance, float):
  3558. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3559. # deselect everything
  3560. self.selected = []
  3561. self.replot()
  3562. return
  3563. pre_buffer = cascaded_union([t.geo for t in selected])
  3564. results = pre_buffer.buffer(-buf_distance + 1e-10, resolution=32, join_style=join_style)
  3565. if results.is_empty:
  3566. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a smaller buffer value."))
  3567. # deselect everything
  3568. self.selected = []
  3569. self.replot()
  3570. return
  3571. if type(results) == MultiPolygon:
  3572. for poly in results:
  3573. self.add_shape(DrawToolShape(poly.exterior))
  3574. else:
  3575. self.add_shape(DrawToolShape(results.exterior))
  3576. self.replot()
  3577. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3578. # selected = self.get_selected()
  3579. #
  3580. # if len(selected) == 0:
  3581. # self.app.inform.emit("[WARNING] Nothing selected for buffering.")
  3582. # return
  3583. #
  3584. # if not isinstance(buf_distance, float):
  3585. # self.app.inform.emit("[WARNING] Invalid distance for buffering.")
  3586. # return
  3587. #
  3588. # pre_buffer = cascaded_union([t.geo for t in selected])
  3589. # results = pre_buffer.buffer(buf_distance)
  3590. # if results.is_empty:
  3591. # self.app.inform.emit("Failed. Choose a smaller buffer value.")
  3592. # return
  3593. #
  3594. # int_geo = []
  3595. # if type(results) == MultiPolygon:
  3596. # for poly in results:
  3597. # for g in poly.interiors:
  3598. # int_geo.append(g)
  3599. # res = cascaded_union(int_geo)
  3600. # self.add_shape(DrawToolShape(res))
  3601. # else:
  3602. # print(results.interiors)
  3603. # for g in results.interiors:
  3604. # int_geo.append(g)
  3605. # res = cascaded_union(int_geo)
  3606. # self.add_shape(DrawToolShape(res))
  3607. #
  3608. # self.replot()
  3609. # self.app.inform.emit("Interior buffer geometry created.")
  3610. def buffer_ext(self, buf_distance, join_style):
  3611. selected = self.get_selected()
  3612. if buf_distance < 0:
  3613. self.app.inform.emit(_("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3614. "Use Buffer interior to generate an 'inside' shape"))
  3615. # deselect everything
  3616. self.selected = []
  3617. self.replot()
  3618. return
  3619. if len(selected) == 0:
  3620. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3621. return
  3622. if not isinstance(buf_distance, float):
  3623. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3624. # deselect everything
  3625. self.selected = []
  3626. self.replot()
  3627. return
  3628. pre_buffer = cascaded_union([t.geo for t in selected])
  3629. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3630. if results.is_empty:
  3631. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3632. # deselect everything
  3633. self.selected = []
  3634. self.replot()
  3635. return
  3636. if type(results) == MultiPolygon:
  3637. for poly in results:
  3638. self.add_shape(DrawToolShape(poly.exterior))
  3639. else:
  3640. self.add_shape(DrawToolShape(results.exterior))
  3641. self.replot()
  3642. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3643. # def paint(self, tooldia, overlap, margin, method):
  3644. # selected = self.get_selected()
  3645. #
  3646. # if len(selected) == 0:
  3647. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3648. # return
  3649. #
  3650. # for param in [tooldia, overlap, margin]:
  3651. # if not isinstance(param, float):
  3652. # param_name = [k for k, v in locals().items() if v is param][0]
  3653. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3654. #
  3655. # # Todo: Check for valid method.
  3656. #
  3657. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3658. #
  3659. # results = []
  3660. #
  3661. # def recurse(geo):
  3662. # try:
  3663. # for subg in geo:
  3664. # for subsubg in recurse(subg):
  3665. # yield subsubg
  3666. # except TypeError:
  3667. # if isinstance(geo, LinearRing):
  3668. # yield geo
  3669. #
  3670. # raise StopIteration
  3671. #
  3672. # for geo in selected:
  3673. # print(type(geo.geo))
  3674. #
  3675. # local_results = []
  3676. # for poly in recurse(geo.geo):
  3677. # if method == "seed":
  3678. # # Type(cp) == FlatCAMRTreeStorage | None
  3679. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3680. # tooldia, overlap=overlap)
  3681. #
  3682. # else:
  3683. # # Type(cp) == FlatCAMRTreeStorage | None
  3684. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3685. # tooldia, overlap=overlap)
  3686. #
  3687. # if cp is not None:
  3688. # local_results += list(cp.get_objects())
  3689. #
  3690. # results.append(cascaded_union(local_results))
  3691. #
  3692. # # This is a dirty patch:
  3693. # for r in results:
  3694. # self.add_shape(DrawToolShape(r))
  3695. #
  3696. # self.replot()
  3697. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3698. self.paint_tooldia = tooldia
  3699. selected = self.get_selected()
  3700. if len(selected) == 0:
  3701. self.app.inform.emit(_("[WARNING_NOTCL]Nothing selected for painting."))
  3702. return
  3703. for param in [tooldia, overlap, margin]:
  3704. if not isinstance(param, float):
  3705. param_name = [k for k, v in locals().items() if v is param][0]
  3706. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3707. results = []
  3708. if overlap >= 1:
  3709. self.app.inform.emit(
  3710. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3711. return
  3712. def recurse(geometry, reset=True):
  3713. """
  3714. Creates a list of non-iterable linear geometry objects.
  3715. Results are placed in self.flat_geometry
  3716. :param geometry: Shapely type or list or list of list of such.
  3717. :param reset: Clears the contents of self.flat_geometry.
  3718. """
  3719. if geometry is None:
  3720. return
  3721. if reset:
  3722. self.flat_geo = []
  3723. ## If iterable, expand recursively.
  3724. try:
  3725. for geo in geometry:
  3726. if geo is not None:
  3727. recurse(geometry=geo, reset=False)
  3728. ## Not iterable, do the actual indexing and add.
  3729. except TypeError:
  3730. self.flat_geo.append(geometry)
  3731. return self.flat_geo
  3732. for geo in selected:
  3733. local_results = []
  3734. for geo_obj in recurse(geo.geo):
  3735. try:
  3736. if type(geo_obj) == Polygon:
  3737. poly_buf = geo_obj.buffer(-margin)
  3738. else:
  3739. poly_buf = Polygon(geo_obj).buffer(-margin)
  3740. if method == "seed":
  3741. cp = Geometry.clear_polygon2(poly_buf,
  3742. tooldia, self.app.defaults["geometry_circle_steps"],
  3743. overlap=overlap, contour=contour, connect=connect)
  3744. elif method == "lines":
  3745. cp = Geometry.clear_polygon3(poly_buf,
  3746. tooldia, self.app.defaults["geometry_circle_steps"],
  3747. overlap=overlap, contour=contour, connect=connect)
  3748. else:
  3749. cp = Geometry.clear_polygon(poly_buf,
  3750. tooldia, self.app.defaults["geometry_circle_steps"],
  3751. overlap=overlap, contour=contour, connect=connect)
  3752. if cp is not None:
  3753. local_results += list(cp.get_objects())
  3754. except Exception as e:
  3755. log.debug("Could not Paint the polygons. %s" % str(e))
  3756. self.app.inform.emit(
  3757. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3758. "Or a different method of Paint\n%s") % str(e))
  3759. return
  3760. # add the result to the results list
  3761. results.append(cascaded_union(local_results))
  3762. # This is a dirty patch:
  3763. for r in results:
  3764. self.add_shape(DrawToolShape(r))
  3765. self.app.inform.emit(
  3766. _("[success] Paint done."))
  3767. self.replot()
  3768. class FlatCAMExcEditor(QtCore.QObject):
  3769. draw_shape_idx = -1
  3770. def __init__(self, app):
  3771. assert isinstance(app, FlatCAMApp.App), \
  3772. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  3773. super(FlatCAMExcEditor, self).__init__()
  3774. self.app = app
  3775. self.canvas = self.app.plotcanvas
  3776. self.exc_edit_widget = QtWidgets.QWidget()
  3777. layout = QtWidgets.QVBoxLayout()
  3778. self.exc_edit_widget.setLayout(layout)
  3779. ## Page Title box (spacing between children)
  3780. self.title_box = QtWidgets.QHBoxLayout()
  3781. layout.addLayout(self.title_box)
  3782. ## Page Title icon
  3783. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  3784. self.icon = QtWidgets.QLabel()
  3785. self.icon.setPixmap(pixmap)
  3786. self.title_box.addWidget(self.icon, stretch=0)
  3787. ## Title label
  3788. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  3789. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  3790. self.title_box.addWidget(self.title_label, stretch=1)
  3791. ## Object name
  3792. self.name_box = QtWidgets.QHBoxLayout()
  3793. layout.addLayout(self.name_box)
  3794. name_label = QtWidgets.QLabel(_("Name:"))
  3795. self.name_box.addWidget(name_label)
  3796. self.name_entry = FCEntry()
  3797. self.name_box.addWidget(self.name_entry)
  3798. ## Box box for custom widgets
  3799. # This gets populated in offspring implementations.
  3800. self.custom_box = QtWidgets.QVBoxLayout()
  3801. layout.addLayout(self.custom_box)
  3802. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3803. # this way I can hide/show the frame
  3804. self.drills_frame = QtWidgets.QFrame()
  3805. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  3806. self.custom_box.addWidget(self.drills_frame)
  3807. self.tools_box = QtWidgets.QVBoxLayout()
  3808. self.tools_box.setContentsMargins(0, 0, 0, 0)
  3809. self.drills_frame.setLayout(self.tools_box)
  3810. #### Tools Drills ####
  3811. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  3812. self.tools_table_label.setToolTip(
  3813. _( "Tools in this Excellon object\n"
  3814. "when are used for drilling.")
  3815. )
  3816. self.tools_box.addWidget(self.tools_table_label)
  3817. self.tools_table_exc = FCTable()
  3818. self.tools_box.addWidget(self.tools_table_exc)
  3819. self.tools_table_exc.setColumnCount(4)
  3820. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  3821. self.tools_table_exc.setSortingEnabled(False)
  3822. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  3823. self.empty_label = QtWidgets.QLabel('')
  3824. self.tools_box.addWidget(self.empty_label)
  3825. #### Add a new Tool ####
  3826. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  3827. self.addtool_label.setToolTip(
  3828. _("Add/Delete a tool to the tool list\n"
  3829. "for this Excellon object.")
  3830. )
  3831. self.tools_box.addWidget(self.addtool_label)
  3832. grid1 = QtWidgets.QGridLayout()
  3833. self.tools_box.addLayout(grid1)
  3834. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  3835. addtool_entry_lbl.setToolTip(
  3836. _("Diameter for the new tool")
  3837. )
  3838. grid1.addWidget(addtool_entry_lbl, 0, 0)
  3839. hlay = QtWidgets.QHBoxLayout()
  3840. self.addtool_entry = FCEntry()
  3841. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  3842. hlay.addWidget(self.addtool_entry)
  3843. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  3844. self.addtool_btn.setToolTip(
  3845. _( "Add a new tool to the tool list\n"
  3846. "with the diameter specified above.")
  3847. )
  3848. self.addtool_btn.setFixedWidth(80)
  3849. hlay.addWidget(self.addtool_btn)
  3850. grid1.addLayout(hlay, 0, 1)
  3851. grid2 = QtWidgets.QGridLayout()
  3852. self.tools_box.addLayout(grid2)
  3853. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  3854. self.deltool_btn.setToolTip(
  3855. _( "Delete a tool in the tool list\n"
  3856. "by selecting a row in the tool table.")
  3857. )
  3858. grid2.addWidget(self.deltool_btn, 0, 1)
  3859. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3860. # this way I can hide/show the frame
  3861. self.resize_frame = QtWidgets.QFrame()
  3862. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  3863. self.tools_box.addWidget(self.resize_frame)
  3864. self.resize_box = QtWidgets.QVBoxLayout()
  3865. self.resize_box.setContentsMargins(0, 0, 0, 0)
  3866. self.resize_frame.setLayout(self.resize_box)
  3867. #### Resize a drill ####
  3868. self.emptyresize_label = QtWidgets.QLabel('')
  3869. self.resize_box.addWidget(self.emptyresize_label)
  3870. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  3871. self.drillresize_label.setToolTip(
  3872. _("Resize a drill or a selection of drills.")
  3873. )
  3874. self.resize_box.addWidget(self.drillresize_label)
  3875. grid3 = QtWidgets.QGridLayout()
  3876. self.resize_box.addLayout(grid3)
  3877. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  3878. res_entry_lbl.setToolTip(
  3879. _( "Diameter to resize to.")
  3880. )
  3881. grid3.addWidget(addtool_entry_lbl, 0, 0)
  3882. hlay2 = QtWidgets.QHBoxLayout()
  3883. self.resdrill_entry = LengthEntry()
  3884. hlay2.addWidget(self.resdrill_entry)
  3885. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  3886. self.resize_btn.setToolTip(
  3887. _("Resize drill(s)")
  3888. )
  3889. self.resize_btn.setFixedWidth(80)
  3890. hlay2.addWidget(self.resize_btn)
  3891. grid3.addLayout(hlay2, 0, 1)
  3892. self.resize_frame.hide()
  3893. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  3894. # all the add drill array widgets
  3895. # this way I can hide/show the frame
  3896. self.array_frame = QtWidgets.QFrame()
  3897. self.array_frame.setContentsMargins(0, 0, 0, 0)
  3898. self.tools_box.addWidget(self.array_frame)
  3899. self.array_box = QtWidgets.QVBoxLayout()
  3900. self.array_box.setContentsMargins(0, 0, 0, 0)
  3901. self.array_frame.setLayout(self.array_box)
  3902. #### Add DRILL Array ####
  3903. self.emptyarray_label = QtWidgets.QLabel('')
  3904. self.array_box.addWidget(self.emptyarray_label)
  3905. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  3906. self.drillarray_label.setToolTip(
  3907. _("Add an array of drills (linear or circular array)")
  3908. )
  3909. self.array_box.addWidget(self.drillarray_label)
  3910. self.array_type_combo = FCComboBox()
  3911. self.array_type_combo.setToolTip(
  3912. _( "Select the type of drills array to create.\n"
  3913. "It can be Linear X(Y) or Circular")
  3914. )
  3915. self.array_type_combo.addItem(_("Linear"))
  3916. self.array_type_combo.addItem(_("Circular"))
  3917. self.array_box.addWidget(self.array_type_combo)
  3918. self.array_form = QtWidgets.QFormLayout()
  3919. self.array_box.addLayout(self.array_form)
  3920. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  3921. self.drill_array_size_label.setToolTip(
  3922. _("Specify how many drills to be in the array.")
  3923. )
  3924. self.drill_array_size_label.setFixedWidth(100)
  3925. self.drill_array_size_entry = LengthEntry()
  3926. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  3927. self.array_linear_frame = QtWidgets.QFrame()
  3928. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  3929. self.array_box.addWidget(self.array_linear_frame)
  3930. self.linear_box = QtWidgets.QVBoxLayout()
  3931. self.linear_box.setContentsMargins(0, 0, 0, 0)
  3932. self.array_linear_frame.setLayout(self.linear_box)
  3933. self.linear_form = QtWidgets.QFormLayout()
  3934. self.linear_box.addLayout(self.linear_form)
  3935. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  3936. self.drill_axis_label.setToolTip(
  3937. _("Direction on which the linear array is oriented:\n"
  3938. "- 'X' - horizontal axis \n"
  3939. "- 'Y' - vertical axis or \n"
  3940. "- 'Angle' - a custom angle for the array inclination")
  3941. )
  3942. self.drill_axis_label.setFixedWidth(100)
  3943. self.drill_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  3944. {'label': 'Y', 'value': 'Y'},
  3945. {'label': _('Angle'), 'value': 'A'}])
  3946. self.drill_axis_radio.set_value('X')
  3947. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  3948. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  3949. self.drill_pitch_label.setToolTip(
  3950. _("Pitch = Distance between elements of the array.")
  3951. )
  3952. self.drill_pitch_label.setFixedWidth(100)
  3953. self.drill_pitch_entry = LengthEntry()
  3954. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  3955. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  3956. self.linear_angle_label.setToolTip(
  3957. _( "Angle at which the linear array is placed.\n"
  3958. "The precision is of max 2 decimals.\n"
  3959. "Min value is: -359.99 degrees.\n"
  3960. "Max value is: 360.00 degrees.")
  3961. )
  3962. self.linear_angle_label.setFixedWidth(100)
  3963. self.linear_angle_spinner = FCDoubleSpinner()
  3964. self.linear_angle_spinner.set_precision(2)
  3965. self.linear_angle_spinner.setRange(-359.99, 360.00)
  3966. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  3967. self.array_circular_frame = QtWidgets.QFrame()
  3968. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  3969. self.array_box.addWidget(self.array_circular_frame)
  3970. self.circular_box = QtWidgets.QVBoxLayout()
  3971. self.circular_box.setContentsMargins(0, 0, 0, 0)
  3972. self.array_circular_frame.setLayout(self.circular_box)
  3973. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  3974. self.drill_direction_label.setToolTip(
  3975. _( "Direction for circular array."
  3976. "Can be CW = clockwise or CCW = counter clockwise.")
  3977. )
  3978. self.drill_direction_label.setFixedWidth(100)
  3979. self.circular_form = QtWidgets.QFormLayout()
  3980. self.circular_box.addLayout(self.circular_form)
  3981. self.drill_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  3982. {'label': 'CCW.', 'value': 'CCW'}])
  3983. self.drill_direction_radio.set_value('CW')
  3984. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  3985. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  3986. self.drill_angle_label.setToolTip(
  3987. _("Angle at which each element in circular array is placed.")
  3988. )
  3989. self.drill_angle_label.setFixedWidth(100)
  3990. self.drill_angle_entry = LengthEntry()
  3991. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  3992. self.array_circular_frame.hide()
  3993. self.linear_angle_spinner.hide()
  3994. self.linear_angle_label.hide()
  3995. self.array_frame.hide()
  3996. self.tools_box.addStretch()
  3997. ## Toolbar events and properties
  3998. self.tools_exc = {
  3999. "select": {"button": self.app.ui.select_drill_btn,
  4000. "constructor": FCDrillSelect},
  4001. "drill_add": {"button": self.app.ui.add_drill_btn,
  4002. "constructor": FCDrillAdd},
  4003. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  4004. "constructor": FCDrillArray},
  4005. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  4006. "constructor": FCDrillResize},
  4007. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  4008. "constructor": FCDrillCopy},
  4009. "drill_move": {"button": self.app.ui.move_drill_btn,
  4010. "constructor": FCDrillMove},
  4011. }
  4012. ### Data
  4013. self.active_tool = None
  4014. self.storage_dict = {}
  4015. self.current_storage = []
  4016. # build the data from the Excellon point into a dictionary
  4017. # {tool_dia: [geometry_in_points]}
  4018. self.points_edit = {}
  4019. self.sorted_diameters =[]
  4020. self.new_drills = []
  4021. self.new_tools = {}
  4022. self.new_slots = {}
  4023. self.new_tool_offset = {}
  4024. # dictionary to store the tool_row and diameters in Tool_table
  4025. # it will be updated everytime self.build_ui() is called
  4026. self.olddia_newdia = {}
  4027. self.tool2tooldia = {}
  4028. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  4029. # is cleared but as a side effect also the selected tool is cleared
  4030. self.last_tool_selected = None
  4031. self.utility = []
  4032. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  4033. self.launched_from_shortcuts = False
  4034. # this var will store the state of the toolbar before starting the editor
  4035. self.toolbar_old_state = False
  4036. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  4037. self.name_entry.returnPressed.connect(self.on_name_activate)
  4038. self.addtool_btn.clicked.connect(self.on_tool_add)
  4039. # self.addtool_entry.editingFinished.connect(self.on_tool_add)
  4040. self.deltool_btn.clicked.connect(self.on_tool_delete)
  4041. self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4042. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  4043. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  4044. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  4045. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  4046. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  4047. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  4048. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  4049. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  4050. # Init GUI
  4051. self.drill_array_size_entry.set_value(5)
  4052. self.drill_pitch_entry.set_value(2.54)
  4053. self.drill_angle_entry.set_value(12)
  4054. self.drill_direction_radio.set_value('CW')
  4055. self.drill_axis_radio.set_value('X')
  4056. self.exc_obj = None
  4057. # VisPy Visuals
  4058. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  4059. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  4060. self.app.pool_recreated.connect(self.pool_recreated)
  4061. # Remove from scene
  4062. self.shapes.enabled = False
  4063. self.tool_shape.enabled = False
  4064. ## List of selected shapes.
  4065. self.selected = []
  4066. self.move_timer = QtCore.QTimer()
  4067. self.move_timer.setSingleShot(True)
  4068. ## Current application units in Upper Case
  4069. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4070. self.key = None # Currently pressed key
  4071. self.modifiers = None
  4072. self.x = None # Current mouse cursor pos
  4073. self.y = None
  4074. # Current snapped mouse pos
  4075. self.snap_x = None
  4076. self.snap_y = None
  4077. self.pos = None
  4078. def make_callback(thetool):
  4079. def f():
  4080. self.on_tool_select(thetool)
  4081. return f
  4082. for tool in self.tools_exc:
  4083. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  4084. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  4085. self.options = {
  4086. "global_gridx": 0.1,
  4087. "global_gridy": 0.1,
  4088. "snap_max": 0.05,
  4089. "grid_snap": True,
  4090. "corner_snap": False,
  4091. "grid_gap_link": True
  4092. }
  4093. self.app.options_read_form()
  4094. for option in self.options:
  4095. if option in self.app.options:
  4096. self.options[option] = self.app.options[option]
  4097. self.rtree_exc_index = rtindex.Index()
  4098. # flag to show if the object was modified
  4099. self.is_modified = False
  4100. self.edited_obj_name = ""
  4101. # variable to store the total amount of drills per job
  4102. self.tot_drill_cnt = 0
  4103. self.tool_row = 0
  4104. # variable to store the total amount of slots per job
  4105. self.tot_slot_cnt = 0
  4106. self.tool_row_slots = 0
  4107. self.tool_row = 0
  4108. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4109. self.editor_active = False
  4110. def entry2option(option, entry):
  4111. self.options[option] = float(entry.text())
  4112. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4113. self.editor_active = False
  4114. def pool_recreated(self, pool):
  4115. self.shapes.pool = pool
  4116. self.tool_shape.pool = pool
  4117. @staticmethod
  4118. def make_storage():
  4119. ## Shape storage.
  4120. storage = FlatCAMRTreeStorage()
  4121. storage.get_points = DrawToolShape.get_pts
  4122. return storage
  4123. def set_ui(self):
  4124. # updated units
  4125. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4126. self.olddia_newdia.clear()
  4127. self.tool2tooldia.clear()
  4128. # build the self.points_edit dict {dimaters: [point_list]}
  4129. for drill in self.exc_obj.drills:
  4130. if drill['tool'] in self.exc_obj.tools:
  4131. if self.units == 'IN':
  4132. tool_dia = float('%.3f' % self.exc_obj.tools[drill['tool']]['C'])
  4133. else:
  4134. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  4135. try:
  4136. self.points_edit[tool_dia].append(drill['point'])
  4137. except KeyError:
  4138. self.points_edit[tool_dia] = [drill['point']]
  4139. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  4140. for key in self.points_edit:
  4141. self.olddia_newdia[key] = key
  4142. sort_temp = []
  4143. for diam in self.olddia_newdia:
  4144. sort_temp.append(float(diam))
  4145. self.sorted_diameters = sorted(sort_temp)
  4146. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  4147. for i in range(len(self.sorted_diameters)):
  4148. tt_dia = self.sorted_diameters[i]
  4149. self.tool2tooldia[i + 1] = tt_dia
  4150. def build_ui(self):
  4151. try:
  4152. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4153. self.tools_table_exc.itemChanged.disconnect()
  4154. except:
  4155. pass
  4156. # updated units
  4157. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4158. # make a new name for the new Excellon object (the one with edited content)
  4159. self.edited_obj_name = self.exc_obj.options['name']
  4160. self.name_entry.set_value(self.edited_obj_name)
  4161. if self.units == "IN":
  4162. self.addtool_entry.set_value(0.039)
  4163. else:
  4164. self.addtool_entry.set_value(1.00)
  4165. sort_temp = []
  4166. for diam in self.olddia_newdia:
  4167. sort_temp.append(float(diam))
  4168. self.sorted_diameters = sorted(sort_temp)
  4169. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  4170. n = len(self.sorted_diameters)
  4171. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  4172. self.tools_table_exc.setRowCount(n + 2)
  4173. self.tot_drill_cnt = 0
  4174. self.tot_slot_cnt = 0
  4175. self.tool_row = 0
  4176. # this variable will serve as the real tool_number
  4177. tool_id = 0
  4178. for tool_no in self.sorted_diameters:
  4179. tool_id += 1
  4180. drill_cnt = 0 # variable to store the nr of drills per tool
  4181. slot_cnt = 0 # variable to store the nr of slots per tool
  4182. # Find no of drills for the current tool
  4183. for tool_dia in self.points_edit:
  4184. if float(tool_dia) == tool_no:
  4185. drill_cnt = len(self.points_edit[tool_dia])
  4186. self.tot_drill_cnt += drill_cnt
  4187. try:
  4188. # Find no of slots for the current tool
  4189. for slot in self.slots:
  4190. if slot['tool'] == tool_no:
  4191. slot_cnt += 1
  4192. self.tot_slot_cnt += slot_cnt
  4193. except AttributeError:
  4194. # log.debug("No slots in the Excellon file")
  4195. # slot editing not implemented
  4196. pass
  4197. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  4198. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4199. self.tools_table_exc.setItem(self.tool_row, 0, id) # Tool name/id
  4200. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  4201. # There are no drill bits in MM with more than 3 decimals diameter
  4202. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  4203. if self.units == 'MM':
  4204. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  4205. else:
  4206. dia = QtWidgets.QTableWidgetItem('%.3f' % self.olddia_newdia[tool_no])
  4207. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  4208. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  4209. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4210. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  4211. if slot_cnt > 0:
  4212. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  4213. else:
  4214. slot_count = QtWidgets.QTableWidgetItem('')
  4215. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4216. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  4217. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  4218. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  4219. self.tool_row += 1
  4220. # make the diameter column editable
  4221. for row in range(self.tool_row):
  4222. self.tools_table_exc.item(row, 1).setFlags(
  4223. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4224. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  4225. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  4226. # add a last row with the Total number of drills
  4227. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  4228. # it will have to have the foreground color (font color) white
  4229. empty = QtWidgets.QTableWidgetItem('9998')
  4230. empty.setForeground(QtGui.QColor(255, 255, 255))
  4231. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  4232. empty_b = QtWidgets.QTableWidgetItem('')
  4233. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  4234. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  4235. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  4236. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4237. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4238. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  4239. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  4240. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  4241. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  4242. font = QtGui.QFont()
  4243. font.setBold(True)
  4244. font.setWeight(75)
  4245. for k in [1, 2]:
  4246. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  4247. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  4248. self.tool_row += 1
  4249. # add a last row with the Total number of slots
  4250. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  4251. # it will have to have the foreground color (font color) white
  4252. empty_2 = QtWidgets.QTableWidgetItem('9999')
  4253. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  4254. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  4255. empty_3 = QtWidgets.QTableWidgetItem('')
  4256. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  4257. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  4258. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  4259. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4260. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4261. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  4262. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  4263. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  4264. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  4265. for kl in [1, 2, 3]:
  4266. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  4267. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  4268. # all the tools are selected by default
  4269. self.tools_table_exc.selectColumn(0)
  4270. #
  4271. self.tools_table_exc.resizeColumnsToContents()
  4272. self.tools_table_exc.resizeRowsToContents()
  4273. vertical_header = self.tools_table_exc.verticalHeader()
  4274. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4275. vertical_header.hide()
  4276. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4277. horizontal_header = self.tools_table_exc.horizontalHeader()
  4278. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  4279. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4280. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  4281. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4282. # horizontal_header.setStretchLastSection(True)
  4283. # self.tools_table_exc.setSortingEnabled(True)
  4284. # sort by tool diameter
  4285. self.tools_table_exc.sortItems(1)
  4286. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  4287. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  4288. # use them
  4289. self.tool2tooldia.clear()
  4290. for row in range(self.tools_table_exc.rowCount() - 2):
  4291. tool = int(self.tools_table_exc.item(row, 0).text())
  4292. diameter = float(self.tools_table_exc.item(row, 1).text())
  4293. self.tool2tooldia[tool] = diameter
  4294. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  4295. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  4296. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  4297. self.tools_table_exc.clearSelection()
  4298. # Remove anything else in the GUI Selected Tab
  4299. self.app.ui.selected_scroll_area.takeWidget()
  4300. # Put ourself in the GUI Selected Tab
  4301. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  4302. # Switch notebook to Selected page
  4303. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4304. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  4305. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4306. def on_tool_add(self, tooldia=None):
  4307. self.is_modified = True
  4308. if tooldia:
  4309. tool_dia = tooldia
  4310. else:
  4311. try:
  4312. tool_dia = float(self.addtool_entry.get_value())
  4313. except ValueError:
  4314. # try to convert comma to decimal point. if it's still not working error message and return
  4315. try:
  4316. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  4317. except ValueError:
  4318. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  4319. "use a number.")
  4320. )
  4321. return
  4322. if tool_dia not in self.olddia_newdia:
  4323. storage_elem = FlatCAMGeoEditor.make_storage()
  4324. self.storage_dict[tool_dia] = storage_elem
  4325. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  4326. # each time a tool diameter is edited or added
  4327. self.olddia_newdia[tool_dia] = tool_dia
  4328. else:
  4329. self.app.inform.emit(_("[WARNING_NOTCL]Tool already in the original or actual tool list.\n"
  4330. "Save and reedit Excellon if you need to add this tool. ")
  4331. )
  4332. return
  4333. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  4334. # we add a new entry in the tool2tooldia dict
  4335. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  4336. self.app.inform.emit(_("[success]Added new tool with dia: {dia} {units}").format(dia=str(tool_dia), units=str(self.units)))
  4337. self.build_ui()
  4338. # make a quick sort through the tool2tooldia dict so we find which row to select
  4339. row_to_be_selected = None
  4340. for key in sorted(self.tool2tooldia):
  4341. if self.tool2tooldia[key] == tool_dia:
  4342. row_to_be_selected = int(key) - 1
  4343. break
  4344. self.tools_table_exc.selectRow(row_to_be_selected)
  4345. def on_tool_delete(self, dia=None):
  4346. self.is_modified = True
  4347. deleted_tool_dia_list = []
  4348. deleted_tool_offset_list = []
  4349. try:
  4350. if dia is None or dia is False:
  4351. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  4352. for index in self.tools_table_exc.selectionModel().selectedRows():
  4353. row = index.row()
  4354. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  4355. else:
  4356. if isinstance(dia, list):
  4357. for dd in dia:
  4358. deleted_tool_dia_list.append(float('%.4f' % dd))
  4359. else:
  4360. deleted_tool_dia_list.append(float('%.4f' % dia))
  4361. except:
  4362. self.app.inform.emit(_("[WARNING_NOTCL]Select a tool in Tool Table"))
  4363. return
  4364. for deleted_tool_dia in deleted_tool_dia_list:
  4365. # delete de tool offset
  4366. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  4367. # delete the storage used for that tool
  4368. storage_elem = FlatCAMGeoEditor.make_storage()
  4369. self.storage_dict[deleted_tool_dia] = storage_elem
  4370. self.storage_dict.pop(deleted_tool_dia, None)
  4371. # I've added this flag_del variable because dictionary don't like
  4372. # having keys deleted while iterating through them
  4373. flag_del = []
  4374. # self.points_edit.pop(deleted_tool_dia, None)
  4375. for deleted_tool in self.tool2tooldia:
  4376. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  4377. flag_del.append(deleted_tool)
  4378. if flag_del:
  4379. for tool_to_be_deleted in flag_del:
  4380. # delete the tool
  4381. self.tool2tooldia.pop(tool_to_be_deleted, None)
  4382. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  4383. # number of drills from before was deleter
  4384. self.points_edit[deleted_tool_dia] = []
  4385. flag_del = []
  4386. self.olddia_newdia.pop(deleted_tool_dia, None)
  4387. self.app.inform.emit(_("[success]Deleted tool with dia: {del_dia} {units}").format(del_dia=str(deleted_tool_dia), units=str(self.units)))
  4388. self.replot()
  4389. # self.app.inform.emit("Could not delete selected tool")
  4390. self.build_ui()
  4391. def on_tool_edit(self):
  4392. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4393. self.tools_table_exc.itemChanged.disconnect()
  4394. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  4395. self.is_modified = True
  4396. geometry = []
  4397. current_table_dia_edited = None
  4398. if self.tools_table_exc.currentItem() is not None:
  4399. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  4400. row_of_item_changed = self.tools_table_exc.currentRow()
  4401. # rows start with 0, tools start with 1 so we adjust the value by 1
  4402. key_in_tool2tooldia = row_of_item_changed + 1
  4403. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  4404. # tool diameter is not used so we create a new tool with the desired diameter
  4405. if current_table_dia_edited not in self.olddia_newdia.values():
  4406. # update the dict that holds as keys our initial diameters and as values the edited diameters
  4407. self.olddia_newdia[dia_changed] = current_table_dia_edited
  4408. # update the dict that holds tool_no as key and tool_dia as value
  4409. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  4410. # update the tool offset
  4411. modified_offset = self.exc_obj.tool_offset.pop(dia_changed)
  4412. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  4413. self.replot()
  4414. else:
  4415. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  4416. factor = current_table_dia_edited / dia_changed
  4417. for shape in self.storage_dict[dia_changed].get_objects():
  4418. geometry.append(DrawToolShape(
  4419. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  4420. self.points_edit[current_table_dia_edited].append((0, 0))
  4421. self.add_exc_shape(geometry, self.storage_dict[current_table_dia_edited])
  4422. self.on_tool_delete(dia=dia_changed)
  4423. # delete the tool offset
  4424. self.exc_obj.tool_offset.pop(dia_changed, None)
  4425. # we reactivate the signals after the after the tool editing
  4426. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4427. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4428. def on_name_activate(self):
  4429. self.edited_obj_name = self.name_entry.get_value()
  4430. def activate(self):
  4431. self.connect_canvas_event_handlers()
  4432. # self.app.collection.view.keyPressed.connect(self.on_canvas_key)
  4433. self.shapes.enabled = True
  4434. self.tool_shape.enabled = True
  4435. # self.app.app_cursor.enabled = True
  4436. self.app.ui.snap_max_dist_entry.setEnabled(True)
  4437. self.app.ui.corner_snap_btn.setEnabled(True)
  4438. self.app.ui.snap_magnet.setVisible(True)
  4439. self.app.ui.corner_snap_btn.setVisible(True)
  4440. self.app.ui.exc_editor_menu.setDisabled(False)
  4441. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  4442. self.app.ui.update_obj_btn.setEnabled(True)
  4443. self.app.ui.e_editor_cmenu.setEnabled(True)
  4444. self.app.ui.exc_edit_toolbar.setDisabled(False)
  4445. self.app.ui.exc_edit_toolbar.setVisible(True)
  4446. # self.app.ui.snap_toolbar.setDisabled(False)
  4447. # start with GRID toolbar activated
  4448. if self.app.ui.grid_snap_btn.isChecked() is False:
  4449. self.app.ui.grid_snap_btn.trigger()
  4450. # Tell the App that the editor is active
  4451. self.editor_active = True
  4452. def deactivate(self):
  4453. self.disconnect_canvas_event_handlers()
  4454. self.clear()
  4455. self.app.ui.exc_edit_toolbar.setDisabled(True)
  4456. settings = QSettings("Open Source", "FlatCAM")
  4457. if settings.contains("layout"):
  4458. layout = settings.value('layout', type=str)
  4459. if layout == 'standard':
  4460. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4461. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4462. self.app.ui.corner_snap_btn.setEnabled(False)
  4463. self.app.ui.snap_magnet.setVisible(False)
  4464. self.app.ui.corner_snap_btn.setVisible(False)
  4465. elif layout == 'compact':
  4466. # self.app.ui.exc_edit_toolbar.setVisible(True)
  4467. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4468. self.app.ui.corner_snap_btn.setEnabled(False)
  4469. self.app.ui.snap_magnet.setVisible(True)
  4470. self.app.ui.corner_snap_btn.setVisible(True)
  4471. else:
  4472. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4473. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4474. self.app.ui.corner_snap_btn.setEnabled(False)
  4475. self.app.ui.snap_magnet.setVisible(False)
  4476. self.app.ui.corner_snap_btn.setVisible(False)
  4477. # set the Editor Toolbar visibility to what was before entering in the Editor
  4478. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  4479. else self.app.ui.exc_edit_toolbar.setVisible(True)
  4480. # Disable visuals
  4481. self.shapes.enabled = False
  4482. self.tool_shape.enabled = False
  4483. # self.app.app_cursor.enabled = False
  4484. # Tell the app that the editor is no longer active
  4485. self.editor_active = False
  4486. self.app.ui.exc_editor_menu.setDisabled(True)
  4487. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  4488. self.app.ui.update_obj_btn.setEnabled(False)
  4489. self.app.ui.g_editor_cmenu.setEnabled(False)
  4490. self.app.ui.e_editor_cmenu.setEnabled(False)
  4491. # Show original geometry
  4492. if self.exc_obj:
  4493. self.exc_obj.visible = True
  4494. def connect_canvas_event_handlers(self):
  4495. ## Canvas events
  4496. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  4497. # but those from FlatCAMGeoEditor
  4498. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  4499. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  4500. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4501. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  4502. self.app.collection.view.clicked.disconnect()
  4503. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  4504. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  4505. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  4506. def disconnect_canvas_event_handlers(self):
  4507. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  4508. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  4509. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  4510. # we restore the key and mouse control to FlatCAMApp method
  4511. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  4512. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  4513. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4514. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  4515. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  4516. def clear(self):
  4517. self.active_tool = None
  4518. # self.shape_buffer = []
  4519. self.selected = []
  4520. self.points_edit = {}
  4521. self.new_tools = {}
  4522. self.new_drills = []
  4523. self.storage_dict = {}
  4524. self.shapes.clear(update=True)
  4525. self.tool_shape.clear(update=True)
  4526. # self.storage = FlatCAMExcEditor.make_storage()
  4527. self.replot()
  4528. def edit_fcexcellon(self, exc_obj):
  4529. """
  4530. Imports the geometry from the given FlatCAM Excellon object
  4531. into the editor.
  4532. :param fcgeometry: FlatCAMExcellon
  4533. :return: None
  4534. """
  4535. assert isinstance(exc_obj, Excellon), \
  4536. "Expected an Excellon Object, got %s" % type(exc_obj)
  4537. self.deactivate()
  4538. self.activate()
  4539. # Hide original geometry
  4540. self.exc_obj = exc_obj
  4541. exc_obj.visible = False
  4542. # Set selection tolerance
  4543. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  4544. self.select_tool("select")
  4545. self.set_ui()
  4546. # now that we hava data, create the GUI interface and add it to the Tool Tab
  4547. self.build_ui()
  4548. # we activate this after the initial build as we don't need to see the tool been populated
  4549. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4550. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  4551. # and then add it to the storage elements (each storage elements is a member of a list
  4552. for tool_dia in self.points_edit:
  4553. storage_elem = FlatCAMGeoEditor.make_storage()
  4554. for point in self.points_edit[tool_dia]:
  4555. # make a '+' sign, the line length is the tool diameter
  4556. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  4557. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  4558. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  4559. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  4560. shape = MultiLineString([(start_hor_line, stop_hor_line),(start_vert_line, stop_vert_line)])
  4561. if shape is not None:
  4562. self.add_exc_shape(DrawToolShape(shape), storage_elem)
  4563. self.storage_dict[tool_dia] = storage_elem
  4564. self.replot()
  4565. # add a first tool in the Tool Table but only if the Excellon Object is empty
  4566. if not self.tool2tooldia:
  4567. self.on_tool_add(tooldia=1.00)
  4568. def update_fcexcellon(self, exc_obj):
  4569. """
  4570. Create a new Excellon object that contain the edited content of the source Excellon object
  4571. :param exc_obj: FlatCAMExcellon
  4572. :return: None
  4573. """
  4574. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  4575. # the values of this dict are coordinates of the holes (drills)
  4576. edited_points = {}
  4577. for storage_tooldia in self.storage_dict:
  4578. for x in self.storage_dict[storage_tooldia].get_objects():
  4579. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  4580. # each MultiLineString is made out of Linestrings
  4581. # select first Linestring object in the current MultiLineString
  4582. first_linestring = x.geo[0]
  4583. # get it's coordinates
  4584. first_linestring_coords = first_linestring.coords
  4585. x_coord = first_linestring_coords[0][0] + (float(storage_tooldia) / 2)
  4586. y_coord = first_linestring_coords[0][1]
  4587. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  4588. # edited_points dictionary
  4589. point = (x_coord, y_coord)
  4590. if not storage_tooldia in edited_points:
  4591. edited_points[storage_tooldia] = [point]
  4592. else:
  4593. edited_points[storage_tooldia].append(point)
  4594. # recreate the drills and tools to be added to the new Excellon edited object
  4595. # first, we look in the tool table if one of the tool diameters was changed then
  4596. # append that a tuple formed by (old_dia, edited_dia) to a list
  4597. changed_key = []
  4598. for initial_dia in self.olddia_newdia:
  4599. edited_dia = self.olddia_newdia[initial_dia]
  4600. if edited_dia != initial_dia:
  4601. for old_dia in edited_points:
  4602. if old_dia == initial_dia:
  4603. changed_key.append((old_dia, edited_dia))
  4604. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  4605. # (and we have to add it)
  4606. # because in case we have drill points it will have to be already added in edited_points
  4607. # if initial_dia not in edited_points.keys():
  4608. # edited_points[initial_dia] = []
  4609. for el in changed_key:
  4610. edited_points[el[1]] = edited_points.pop(el[0])
  4611. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  4612. # ordered_edited_points is a ordered list of tuples;
  4613. # element[0] of the tuple is the diameter and
  4614. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  4615. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  4616. current_tool = 0
  4617. for tool_dia in ordered_edited_points:
  4618. current_tool += 1
  4619. # create the self.tools for the new Excellon object (the one with edited content)
  4620. name = str(current_tool)
  4621. spec = {"C": float(tool_dia[0])}
  4622. self.new_tools[name] = spec
  4623. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  4624. self.new_tools[name]['solid_geometry'] = []
  4625. # create the self.drills for the new Excellon object (the one with edited content)
  4626. for point in tool_dia[1]:
  4627. self.new_drills.append(
  4628. {
  4629. 'point': Point(point),
  4630. 'tool': str(current_tool)
  4631. }
  4632. )
  4633. # repopulate the 'solid_geometry' for each tool
  4634. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  4635. self.new_tools[name]['solid_geometry'].append(poly)
  4636. if self.is_modified is True:
  4637. if "_edit" in self.edited_obj_name:
  4638. try:
  4639. id = int(self.edited_obj_name[-1]) + 1
  4640. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  4641. except ValueError:
  4642. self.edited_obj_name += "_1"
  4643. else:
  4644. self.edited_obj_name += "_edit"
  4645. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  4646. 'params': [self.edited_obj_name]})
  4647. if self.exc_obj.slots:
  4648. self.new_slots = self.exc_obj.slots
  4649. self.new_tool_offset = self.exc_obj.tool_offset
  4650. # reset the tool table
  4651. self.tools_table_exc.clear()
  4652. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  4653. self.last_tool_selected = None
  4654. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  4655. self.app.collection.set_active(self.exc_obj.options['name'])
  4656. self.app.collection.delete_active()
  4657. # restore GUI to the Selected TAB
  4658. # Remove anything else in the GUI
  4659. self.app.ui.tool_scroll_area.takeWidget()
  4660. # Switch notebook to Selected page
  4661. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4662. def update_options(self, obj):
  4663. try:
  4664. if not obj.options:
  4665. obj.options = {}
  4666. obj.options['xmin'] = 0
  4667. obj.options['ymin'] = 0
  4668. obj.options['xmax'] = 0
  4669. obj.options['ymax'] = 0
  4670. return True
  4671. else:
  4672. return False
  4673. except AttributeError:
  4674. obj.options = {}
  4675. return True
  4676. def new_edited_excellon(self, outname):
  4677. """
  4678. Creates a new Excellon object for the edited Excellon. Thread-safe.
  4679. :param outname: Name of the resulting object. None causes the
  4680. name to be that of the file.
  4681. :type outname: str
  4682. :return: None
  4683. """
  4684. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  4685. self.exc_obj.options['name'])
  4686. # How the object should be initialized
  4687. def obj_init(excellon_obj, app_obj):
  4688. # self.progress.emit(20)
  4689. excellon_obj.drills = self.new_drills
  4690. excellon_obj.tools = self.new_tools
  4691. excellon_obj.slots = self.new_slots
  4692. excellon_obj.tool_offset = self.new_tool_offset
  4693. excellon_obj.options['name'] = outname
  4694. try:
  4695. excellon_obj.create_geometry()
  4696. except KeyError:
  4697. self.app.inform.emit(
  4698. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  4699. )
  4700. except:
  4701. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  4702. msg += traceback.format_exc()
  4703. app_obj.inform.emit(msg)
  4704. raise
  4705. # raise
  4706. with self.app.proc_container.new(_("Creating Excellon.")):
  4707. try:
  4708. self.app.new_object("excellon", outname, obj_init)
  4709. except Exception as e:
  4710. log.error("Error on object creation: %s" % str(e))
  4711. self.app.progress.emit(100)
  4712. return
  4713. self.app.inform.emit(_("[success]Excellon editing finished."))
  4714. # self.progress.emit(100)
  4715. def on_tool_select(self, tool):
  4716. """
  4717. Behavior of the toolbar. Tool initialization.
  4718. :rtype : None
  4719. """
  4720. current_tool = tool
  4721. self.app.log.debug("on_tool_select('%s')" % tool)
  4722. if self.last_tool_selected is None and current_tool is not 'select':
  4723. # self.draw_app.select_tool('select')
  4724. self.complete = True
  4725. current_tool = 'select'
  4726. self.app.inform.emit(_("[WARNING_NOTCL]Cancelled. There is no Tool/Drill selected"))
  4727. # This is to make the group behave as radio group
  4728. if current_tool in self.tools_exc:
  4729. if self.tools_exc[current_tool]["button"].isChecked():
  4730. self.app.log.debug("%s is checked." % current_tool)
  4731. for t in self.tools_exc:
  4732. if t != current_tool:
  4733. self.tools_exc[t]["button"].setChecked(False)
  4734. # this is where the Editor toolbar classes (button's) are instantiated
  4735. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  4736. # self.app.inform.emit(self.active_tool.start_msg)
  4737. else:
  4738. self.app.log.debug("%s is NOT checked." % current_tool)
  4739. for t in self.tools_exc:
  4740. self.tools_exc[t]["button"].setChecked(False)
  4741. self.active_tool = None
  4742. def on_row_selected(self):
  4743. self.selected = []
  4744. try:
  4745. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  4746. self.last_tool_selected = self.tools_table_exc.currentRow() + 1
  4747. for obj in self.storage_dict[selected_dia].get_objects():
  4748. self.selected.append(obj)
  4749. except Exception as e:
  4750. self.app.log.debug(str(e))
  4751. self.replot()
  4752. def toolbar_tool_toggle(self, key):
  4753. self.options[key] = self.sender().isChecked()
  4754. if self.options[key] == True:
  4755. return 1
  4756. else:
  4757. return 0
  4758. def on_canvas_click(self, event):
  4759. """
  4760. event.x and .y have canvas coordinates
  4761. event.xdaya and .ydata have plot coordinates
  4762. :param event: Event object dispatched by Matplotlib
  4763. :return: None
  4764. """
  4765. if event.button is 1:
  4766. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4767. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  4768. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4769. ### Snap coordinates
  4770. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  4771. self.pos = (x, y)
  4772. # print(self.active_tool)
  4773. # Selection with left mouse button
  4774. if self.active_tool is not None and event.button is 1:
  4775. # Dispatch event to active_tool
  4776. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4777. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  4778. # If it is a shape generating tool
  4779. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  4780. if self.current_storage is not None:
  4781. self.on_exc_shape_complete(self.current_storage)
  4782. self.build_ui()
  4783. # MS: always return to the Select Tool if modifier key is not pressed
  4784. # else return to the current tool
  4785. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4786. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  4787. modifier_to_use = Qt.ControlModifier
  4788. else:
  4789. modifier_to_use = Qt.ShiftModifier
  4790. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  4791. # in the selected list, we removed it. Therefore first click selects, second deselects.
  4792. if key_modifier == modifier_to_use:
  4793. self.select_tool(self.active_tool.name)
  4794. else:
  4795. self.select_tool("select")
  4796. return
  4797. if isinstance(self.active_tool, FCDrillSelect):
  4798. # self.app.log.debug("Replotting after click.")
  4799. self.replot()
  4800. else:
  4801. self.app.log.debug("No active tool to respond to click!")
  4802. def on_exc_shape_complete(self, storage):
  4803. self.app.log.debug("on_shape_complete()")
  4804. # Add shape
  4805. if type(storage) is list:
  4806. for item_storage in storage:
  4807. self.add_exc_shape(self.active_tool.geometry, item_storage)
  4808. else:
  4809. self.add_exc_shape(self.active_tool.geometry, storage)
  4810. # Remove any utility shapes
  4811. self.delete_utility_geometry()
  4812. self.tool_shape.clear(update=True)
  4813. # Replot and reset tool.
  4814. self.replot()
  4815. # self.active_tool = type(self.active_tool)(self)
  4816. def add_exc_shape(self, shape, storage):
  4817. """
  4818. Adds a shape to the shape storage.
  4819. :param shape: Shape to be added.
  4820. :type shape: DrawToolShape
  4821. :return: None
  4822. """
  4823. # List of DrawToolShape?
  4824. if isinstance(shape, list):
  4825. for subshape in shape:
  4826. self.add_exc_shape(subshape, storage)
  4827. return
  4828. assert isinstance(shape, DrawToolShape), \
  4829. "Expected a DrawToolShape, got %s" % str(type(shape))
  4830. assert shape.geo is not None, \
  4831. "Shape object has empty geometry (None)"
  4832. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4833. not isinstance(shape.geo, list), \
  4834. "Shape objects has empty geometry ([])"
  4835. if isinstance(shape, DrawToolUtilityShape):
  4836. self.utility.append(shape)
  4837. else:
  4838. storage.insert(shape) # TODO: Check performance
  4839. def add_shape(self, shape):
  4840. """
  4841. Adds a shape to the shape storage.
  4842. :param shape: Shape to be added.
  4843. :type shape: DrawToolShape
  4844. :return: None
  4845. """
  4846. # List of DrawToolShape?
  4847. if isinstance(shape, list):
  4848. for subshape in shape:
  4849. self.add_shape(subshape)
  4850. return
  4851. assert isinstance(shape, DrawToolShape), \
  4852. "Expected a DrawToolShape, got %s" % type(shape)
  4853. assert shape.geo is not None, \
  4854. "Shape object has empty geometry (None)"
  4855. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4856. not isinstance(shape.geo, list), \
  4857. "Shape objects has empty geometry ([])"
  4858. if isinstance(shape, DrawToolUtilityShape):
  4859. self.utility.append(shape)
  4860. else:
  4861. self.storage.insert(shape) # TODO: Check performance
  4862. def on_canvas_click_release(self, event):
  4863. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  4864. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  4865. if self.app.grid_status():
  4866. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4867. else:
  4868. pos = (pos_canvas[0], pos_canvas[1])
  4869. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4870. # canvas menu
  4871. try:
  4872. if event.button == 2: # right click
  4873. if self.app.panning_action is True:
  4874. self.app.panning_action = False
  4875. else:
  4876. self.app.cursor = QtGui.QCursor()
  4877. self.app.ui.popMenu.popup(self.app.cursor.pos())
  4878. except Exception as e:
  4879. log.warning("Error: %s" % str(e))
  4880. raise
  4881. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4882. # selection and then select a type of selection ("enclosing" or "touching")
  4883. try:
  4884. if event.button == 1: # left click
  4885. if self.app.selection_type is not None:
  4886. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  4887. self.app.selection_type = None
  4888. elif isinstance(self.active_tool, FCDrillSelect):
  4889. # Dispatch event to active_tool
  4890. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4891. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  4892. # self.app.inform.emit(msg)
  4893. self.active_tool.click_release((self.pos[0], self.pos[1]))
  4894. self.replot()
  4895. except Exception as e:
  4896. log.warning("Error: %s" % str(e))
  4897. raise
  4898. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  4899. """
  4900. :param start_pos: mouse position when the selection LMB click was done
  4901. :param end_pos: mouse position when the left mouse button is released
  4902. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4903. :type Bool
  4904. :return:
  4905. """
  4906. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4907. self.app.delete_selection_shape()
  4908. for storage in self.storage_dict:
  4909. for obj in self.storage_dict[storage].get_objects():
  4910. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  4911. (sel_type is False and poly_selection.intersects(obj.geo)):
  4912. if self.key == self.app.defaults["global_mselect_key"]:
  4913. if obj in self.selected:
  4914. self.selected.remove(obj)
  4915. else:
  4916. # add the object to the selected shapes
  4917. self.selected.append(obj)
  4918. else:
  4919. self.selected.append(obj)
  4920. # select the diameter of the selected shape in the tool table
  4921. for storage in self.storage_dict:
  4922. for shape_s in self.selected:
  4923. if shape_s in self.storage_dict[storage].get_objects():
  4924. for key in self.tool2tooldia:
  4925. if self.tool2tooldia[key] == storage:
  4926. item = self.tools_table_exc.item((key - 1), 1)
  4927. self.tools_table_exc.setCurrentItem(item)
  4928. self.last_tool_selected = key
  4929. # item.setSelected(True)
  4930. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  4931. self.replot()
  4932. def on_canvas_move(self, event):
  4933. """
  4934. Called on 'mouse_move' event
  4935. event.pos have canvas screen coordinates
  4936. :param event: Event object dispatched by VisPy SceneCavas
  4937. :return: None
  4938. """
  4939. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4940. event.xdata, event.ydata = pos[0], pos[1]
  4941. self.x = event.xdata
  4942. self.y = event.ydata
  4943. # Prevent updates on pan
  4944. # if len(event.buttons) > 0:
  4945. # return
  4946. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4947. if event.button == 2:
  4948. self.app.panning_action = True
  4949. return
  4950. else:
  4951. self.app.panning_action = False
  4952. try:
  4953. x = float(event.xdata)
  4954. y = float(event.ydata)
  4955. except TypeError:
  4956. return
  4957. if self.active_tool is None:
  4958. return
  4959. ### Snap coordinates
  4960. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  4961. self.snap_x = x
  4962. self.snap_y = y
  4963. # update the position label in the infobar since the APP mouse event handlers are disconnected
  4964. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4965. "<b>Y</b>: %.4f" % (x, y))
  4966. if self.pos is None:
  4967. self.pos = (0, 0)
  4968. dx = x - self.pos[0]
  4969. dy = y - self.pos[1]
  4970. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  4971. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4972. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4973. ### Utility geometry (animated)
  4974. geo = self.active_tool.utility_geometry(data=(x, y))
  4975. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  4976. # Remove any previous utility shape
  4977. self.tool_shape.clear(update=True)
  4978. self.draw_utility_geometry(geo=geo)
  4979. ### Selection area on canvas section ###
  4980. dx = pos[0] - self.pos[0]
  4981. if event.is_dragging == 1 and event.button == 1:
  4982. self.app.delete_selection_shape()
  4983. if dx < 0:
  4984. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  4985. color=self.app.defaults["global_alt_sel_line"],
  4986. face_color=self.app.defaults['global_alt_sel_fill'])
  4987. self.app.selection_type = False
  4988. else:
  4989. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  4990. self.app.selection_type = True
  4991. else:
  4992. self.app.selection_type = None
  4993. # Update cursor
  4994. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  4995. def on_canvas_key_release(self, event):
  4996. self.key = None
  4997. def draw_utility_geometry(self, geo):
  4998. # Add the new utility shape
  4999. try:
  5000. # this case is for the Font Parse
  5001. for el in list(geo.geo):
  5002. if type(el) == MultiPolygon:
  5003. for poly in el:
  5004. self.tool_shape.add(
  5005. shape=poly,
  5006. color=(self.app.defaults["global_draw_color"] + '80'),
  5007. update=False,
  5008. layer=0,
  5009. tolerance=None
  5010. )
  5011. elif type(el) == MultiLineString:
  5012. for linestring in el:
  5013. self.tool_shape.add(
  5014. shape=linestring,
  5015. color=(self.app.defaults["global_draw_color"] + '80'),
  5016. update=False,
  5017. layer=0,
  5018. tolerance=None
  5019. )
  5020. else:
  5021. self.tool_shape.add(
  5022. shape=el,
  5023. color=(self.app.defaults["global_draw_color"] + '80'),
  5024. update=False,
  5025. layer=0,
  5026. tolerance=None
  5027. )
  5028. except TypeError:
  5029. self.tool_shape.add(
  5030. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  5031. update=False, layer=0, tolerance=None)
  5032. self.tool_shape.redraw()
  5033. def replot(self):
  5034. self.plot_all()
  5035. def plot_all(self):
  5036. """
  5037. Plots all shapes in the editor.
  5038. :return: None
  5039. :rtype: None
  5040. """
  5041. # self.app.log.debug("plot_all()")
  5042. self.shapes.clear(update=True)
  5043. for storage in self.storage_dict:
  5044. for shape_plus in self.storage_dict[storage].get_objects():
  5045. if shape_plus.geo is None:
  5046. continue
  5047. if shape_plus in self.selected:
  5048. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  5049. linewidth=2)
  5050. continue
  5051. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  5052. # for shape in self.storage.get_objects():
  5053. # if shape.geo is None: # TODO: This shouldn't have happened
  5054. # continue
  5055. #
  5056. # if shape in self.selected:
  5057. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  5058. # continue
  5059. #
  5060. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  5061. for shape in self.utility:
  5062. self.plot_shape(geometry=shape.geo, linewidth=1)
  5063. continue
  5064. self.shapes.redraw()
  5065. def plot_shape(self, geometry=None, color='black', linewidth=1):
  5066. """
  5067. Plots a geometric object or list of objects without rendering. Plotted objects
  5068. are returned as a list. This allows for efficient/animated rendering.
  5069. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  5070. :param color: Shape color
  5071. :param linewidth: Width of lines in # of pixels.
  5072. :return: List of plotted elements.
  5073. """
  5074. plot_elements = []
  5075. if geometry is None:
  5076. geometry = self.active_tool.geometry
  5077. try:
  5078. for geo in geometry:
  5079. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  5080. ## Non-iterable
  5081. except TypeError:
  5082. ## DrawToolShape
  5083. if isinstance(geometry, DrawToolShape):
  5084. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  5085. ## Polygon: Descend into exterior and each interior.
  5086. if type(geometry) == Polygon:
  5087. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  5088. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  5089. if type(geometry) == LineString or type(geometry) == LinearRing:
  5090. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  5091. if type(geometry) == Point:
  5092. pass
  5093. return plot_elements
  5094. def on_shape_complete(self):
  5095. self.app.log.debug("on_shape_complete()")
  5096. # Add shape
  5097. self.add_shape(self.active_tool.geometry)
  5098. # Remove any utility shapes
  5099. self.delete_utility_geometry()
  5100. self.tool_shape.clear(update=True)
  5101. # Replot and reset tool.
  5102. self.replot()
  5103. # self.active_tool = type(self.active_tool)(self)
  5104. def get_selected(self):
  5105. """
  5106. Returns list of shapes that are selected in the editor.
  5107. :return: List of shapes.
  5108. """
  5109. # return [shape for shape in self.shape_buffer if shape["selected"]]
  5110. return self.selected
  5111. def delete_selected(self):
  5112. temp_ref = [s for s in self.selected]
  5113. for shape_sel in temp_ref:
  5114. self.delete_shape(shape_sel)
  5115. self.selected = []
  5116. self.build_ui()
  5117. self.app.inform.emit(_("[success]Done. Drill(s) deleted."))
  5118. def delete_shape(self, shape):
  5119. self.is_modified = True
  5120. if shape in self.utility:
  5121. self.utility.remove(shape)
  5122. return
  5123. for storage in self.storage_dict:
  5124. # try:
  5125. # self.storage_dict[storage].remove(shape)
  5126. # except:
  5127. # pass
  5128. if shape in self.storage_dict[storage].get_objects():
  5129. self.storage_dict[storage].remove(shape)
  5130. # a hack to make the tool_table display less drills per diameter
  5131. # self.points_edit it's only useful first time when we load the data into the storage
  5132. # but is still used as referecen when building tool_table in self.build_ui()
  5133. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  5134. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  5135. del self.points_edit[storage][0]
  5136. if shape in self.selected:
  5137. self.selected.remove(shape) # TODO: Check performance
  5138. def delete_utility_geometry(self):
  5139. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  5140. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  5141. for_deletion = [shape for shape in self.utility]
  5142. for shape in for_deletion:
  5143. self.delete_shape(shape)
  5144. self.tool_shape.clear(update=True)
  5145. self.tool_shape.redraw()
  5146. def on_delete_btn(self):
  5147. self.delete_selected()
  5148. self.replot()
  5149. def select_tool(self, toolname):
  5150. """
  5151. Selects a drawing tool. Impacts the object and GUI.
  5152. :param toolname: Name of the tool.
  5153. :return: None
  5154. """
  5155. self.tools_exc[toolname]["button"].setChecked(True)
  5156. self.on_tool_select(toolname)
  5157. def set_selected(self, shape):
  5158. # Remove and add to the end.
  5159. if shape in self.selected:
  5160. self.selected.remove(shape)
  5161. self.selected.append(shape)
  5162. def set_unselected(self, shape):
  5163. if shape in self.selected:
  5164. self.selected.remove(shape)
  5165. def on_array_type_combo(self):
  5166. if self.array_type_combo.currentIndex() == 0:
  5167. self.array_circular_frame.hide()
  5168. self.array_linear_frame.show()
  5169. else:
  5170. self.delete_utility_geometry()
  5171. self.array_circular_frame.show()
  5172. self.array_linear_frame.hide()
  5173. self.app.inform.emit(_("Click on the circular array Center position"))
  5174. def on_linear_angle_radio(self):
  5175. val = self.drill_axis_radio.get_value()
  5176. if val == 'A':
  5177. self.linear_angle_spinner.show()
  5178. self.linear_angle_label.show()
  5179. else:
  5180. self.linear_angle_spinner.hide()
  5181. self.linear_angle_label.hide()
  5182. def exc_add_drill(self):
  5183. self.select_tool('add')
  5184. return
  5185. def exc_add_drill_array(self):
  5186. self.select_tool('add_array')
  5187. return
  5188. def exc_resize_drills(self):
  5189. self.select_tool('resize')
  5190. return
  5191. def exc_copy_drills(self):
  5192. self.select_tool('copy')
  5193. return
  5194. def exc_move_drills(self):
  5195. self.select_tool('move')
  5196. return
  5197. def distance(pt1, pt2):
  5198. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  5199. def mag(vec):
  5200. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  5201. def poly2rings(poly):
  5202. return [poly.exterior] + [interior for interior in poly.interiors]