FlatCAMEditor.py 246 KB

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