FlatCAMEditor.py 248 KB

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