dialogs.py 298 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405
  1. """!
  2. @package psmap.dialogs
  3. @brief Map feature objects and dialogs for wxPsMap
  4. Classes:
  5. - dialogs::UnitConversion
  6. - dialogs::TCValidator
  7. - dialogs::PenStyleComboBox
  8. - dialogs::CheckListCtrl
  9. - dialogs::Instruction
  10. - dialogs::InstructionObject
  11. - dialogs::InitMap
  12. - dialogs::MapFrame
  13. - dialogs::PageSetup
  14. - dialogs::Mapinfo
  15. - dialogs::Text
  16. - dialogs::Image
  17. - dialogs::NorthArrow
  18. - dialogs::Scalebar
  19. - dialogs::RasterLegend
  20. - dialogs::VectorLegend
  21. - dialogs::Raster
  22. - dialogs::Vector
  23. - dialogs::VProperties
  24. - dialogs::PsmapDialog
  25. - dialogs::PageSetupDialog
  26. - dialogs::MapDialog
  27. - dialogs::MapFramePanel
  28. - dialogs::RasterPanel
  29. - dialogs::VectorPanel
  30. - dialogs::RasterDialog
  31. - dialogs::MainVectorDialog
  32. - dialogs::VPropertiesDialog
  33. - dialogs::LegendDialog
  34. - dialogs::MapinfoDialog
  35. - dialogs::ScalebarDialog
  36. - dialogs::TextDialog
  37. - dialogs::ImageDialog
  38. - dialogs::NorthArrowDialog
  39. (C) 2011 by Anna Kratochvilova, and the GRASS Development Team
  40. This program is free software under the GNU General Public License
  41. (>=v2). Read the file COPYING that comes with GRASS for details.
  42. @author Anna Kratochvilova <kratochanna gmail.com> (bachelor's project)
  43. @author Martin Landa <landa.martin gmail.com> (mentor)
  44. """
  45. import os
  46. import sys
  47. import string
  48. from math import ceil, floor, sin, cos, pi
  49. from copy import deepcopy
  50. from time import strftime, localtime
  51. try:
  52. import Image as PILImage
  53. havePILImage = True
  54. except ImportError:
  55. havePILImage = False
  56. import wx
  57. import wx.lib.scrolledpanel as scrolled
  58. import wx.lib.filebrowsebutton as filebrowse
  59. from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin
  60. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  61. try:
  62. import wx.lib.agw.floatspin as fs
  63. except ImportError:
  64. fs = None
  65. import grass.script as grass
  66. from core import globalvar
  67. from dbm.vinfo import VectorDBInfo
  68. from core.utils import CmdToTuple, GetCmdString
  69. from gui_core.gselect import Select
  70. from core.gcmd import RunCommand, GError, GMessage, GWarning
  71. # grass.set_raise_on_error(True)
  72. PSMAP_COLORS = ['aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'grey', 'green', 'indigo',
  73. 'magenta','orange', 'purple', 'red', 'violet', 'white', 'yellow']
  74. class UnitConversion:
  75. """! Class for converting units"""
  76. def __init__(self, parent = None):
  77. self.parent = parent
  78. if self.parent:
  79. ppi = wx.PaintDC(self.parent).GetPPI()
  80. else:
  81. ppi = (72, 72)
  82. self._unitsPage = { 'inch' : {'val': 1.0, 'tr' : _("inch")},
  83. 'point' : {'val': 72.0, 'tr' : _("point")},
  84. 'centimeter' : {'val': 2.54, 'tr' : _("centimeter")},
  85. 'millimeter' : {'val': 25.4, 'tr' : _("millimeter")}}
  86. self._unitsMap = { 'meters' : {'val': 0.0254, 'tr' : _("meters")},
  87. 'kilometers' : {'val': 2.54e-5, 'tr' : _("kilometers")},
  88. 'feet' : {'val': 1./12, 'tr' : _("feet")},
  89. 'miles' : {'val': 1./63360, 'tr' : _("miles")},
  90. 'nautical miles': {'val': 1/72913.386, 'tr' : _("nautical miles")}}
  91. self._units = { 'pixel' : {'val': ppi[0], 'tr' : _("pixel")},
  92. 'meter' : {'val': 0.0254, 'tr' : _("meter")},
  93. 'nautmiles' : {'val': 1/72913.386, 'tr' :_("nautical miles")},
  94. 'degrees' : {'val': 0.0254 , 'tr' : _("degree")} #like 1 meter, incorrect
  95. }
  96. self._units.update(self._unitsPage)
  97. self._units.update(self._unitsMap)
  98. def getPageUnitsNames(self):
  99. return sorted(self._unitsPage[unit]['tr'] for unit in self._unitsPage.keys())
  100. def getMapUnitsNames(self):
  101. return sorted(self._unitsMap[unit]['tr'] for unit in self._unitsMap.keys())
  102. def getAllUnits(self):
  103. return sorted(self._units.keys())
  104. def findUnit(self, name):
  105. """!Returns unit by its tr. string"""
  106. for unit in self._units.keys():
  107. if self._units[unit]['tr'] == name:
  108. return unit
  109. return None
  110. def findName(self, unit):
  111. """!Returns tr. string of a unit"""
  112. try:
  113. return self._units[unit]['tr']
  114. except KeyError:
  115. return None
  116. def convert(self, value, fromUnit = None, toUnit = None):
  117. return float(value)/self._units[fromUnit]['val']*self._units[toUnit]['val']
  118. class TCValidator(wx.PyValidator):
  119. """!validates input in textctrls, combobox, taken from wxpython demo"""
  120. def __init__(self, flag = None):
  121. wx.PyValidator.__init__(self)
  122. self.flag = flag
  123. self.Bind(wx.EVT_CHAR, self.OnChar)
  124. def Clone(self):
  125. return TCValidator(self.flag)
  126. def Validate(self, win):
  127. tc = self.GetWindow()
  128. val = tc.GetValue()
  129. if self.flag == 'DIGIT_ONLY':
  130. for x in val:
  131. if x not in string.digits:
  132. return False
  133. return True
  134. def OnChar(self, event):
  135. key = event.GetKeyCode()
  136. if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
  137. event.Skip()
  138. return
  139. if self.flag == 'DIGIT_ONLY' and chr(key) in string.digits + '.':
  140. event.Skip()
  141. return
  142. ## if self.flag == 'SCALE' and chr(key) in string.digits + ':':
  143. ## event.Skip()
  144. ## return
  145. if self.flag == 'ZERO_AND_ONE_ONLY' and chr(key) in '01':
  146. event.Skip()
  147. return
  148. if not wx.Validator_IsSilent():
  149. wx.Bell()
  150. # Returning without calling even.Skip eats the event before it
  151. # gets to the text control
  152. return
  153. class PenStyleComboBox(wx.combo.OwnerDrawnComboBox):
  154. """!Combo for selecting line style, taken from wxpython demo"""
  155. # Overridden from OwnerDrawnComboBox, called to draw each
  156. # item in the list
  157. def OnDrawItem(self, dc, rect, item, flags):
  158. if item == wx.NOT_FOUND:
  159. # painting the control, but there is no valid item selected yet
  160. return
  161. r = wx.Rect(*rect) # make a copy
  162. r.Deflate(3, 5)
  163. penStyle = wx.SOLID
  164. if item == 1:
  165. penStyle = wx.LONG_DASH
  166. elif item == 2:
  167. penStyle = wx.DOT
  168. elif item == 3:
  169. penStyle = wx.DOT_DASH
  170. pen = wx.Pen(dc.GetTextForeground(), 3, penStyle)
  171. dc.SetPen(pen)
  172. # for painting the items in the popup
  173. dc.DrawText(self.GetString(item ),
  174. r.x + 3,
  175. (r.y + 0) + ((r.height/2) - dc.GetCharHeight() )/2
  176. )
  177. dc.DrawLine(r.x+5, r.y+((r.height/4)*3)+1, r.x+r.width - 5, r.y+((r.height/4)*3)+1 )
  178. def OnDrawBackground(self, dc, rect, item, flags):
  179. """!Overridden from OwnerDrawnComboBox, called for drawing the
  180. background area of each item."""
  181. # If the item is selected, or its item # iseven, or we are painting the
  182. # combo control itself, then use the default rendering.
  183. if (item & 1 == 0 or flags & (wx.combo.ODCB_PAINTING_CONTROL |
  184. wx.combo.ODCB_PAINTING_SELECTED)):
  185. wx.combo.OwnerDrawnComboBox.OnDrawBackground(self, dc, rect, item, flags)
  186. return
  187. # Otherwise, draw every other background with different colour.
  188. bgCol = wx.Colour(240,240,250)
  189. dc.SetBrush(wx.Brush(bgCol))
  190. dc.SetPen(wx.Pen(bgCol))
  191. dc.DrawRectangleRect(rect);
  192. def OnMeasureItem(self, item):
  193. """!Overridden from OwnerDrawnComboBox, should return the height
  194. needed to display an item in the popup, or -1 for default"""
  195. return 30
  196. def OnMeasureItemWidth(self, item):
  197. """!Overridden from OwnerDrawnComboBox. Callback for item width, or
  198. -1 for default/undetermined"""
  199. return -1; # default - will be measured from text width
  200. class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin):
  201. """!List control for managing order and labels of vector maps in legend"""
  202. def __init__(self, parent):
  203. wx.ListCtrl.__init__(self, parent, id = wx.ID_ANY,
  204. style = wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.BORDER_SUNKEN|wx.LC_VRULES|wx.LC_HRULES)
  205. CheckListCtrlMixin.__init__(self)
  206. ListCtrlAutoWidthMixin.__init__(self)
  207. class Instruction:
  208. """!Class which represents instruction file"""
  209. def __init__(self, parent, objectsToDraw):
  210. self.parent = parent
  211. self.objectsToDraw = objectsToDraw
  212. #here are kept objects like mapinfo, rasterlegend, etc.
  213. self.instruction = list()
  214. def __str__(self):
  215. """!Returns text for instruction file"""
  216. comment = "# timestamp: " + strftime("%Y-%m-%d %H:%M", localtime()) + '\n'
  217. env = grass.gisenv()
  218. comment += "# location: %s\n" % env['LOCATION_NAME']
  219. comment += "# mapset: %s\n" % env['MAPSET']
  220. comment += "# page orientation: %s\n" % self.FindInstructionByType('page')['Orientation']
  221. border = ''
  222. if not self.FindInstructionByType('map'):
  223. border = 'border n\n'
  224. text = [str(each) for each in self.instruction]
  225. return comment + border + '\n'.join(text) + '\nend'
  226. def __getitem__(self, id):
  227. for each in self.instruction:
  228. if each.id == id:
  229. return each
  230. return None
  231. def __contains__(self, id):
  232. """!Test if instruction is included"""
  233. for each in self.instruction:
  234. if each.id == id:
  235. return True
  236. return False
  237. def __delitem__(self, id):
  238. """!Delete instruction"""
  239. for each in self.instruction:
  240. if each.id == id:
  241. if each.type == 'map':
  242. #must remove raster, vector layers too
  243. vektor = self.FindInstructionByType('vector', list = True)
  244. vProperties = self.FindInstructionByType('vProperties', list = True)
  245. raster = self.FindInstructionByType('raster', list = True)
  246. for item in vektor + vProperties + raster:
  247. if item in self.instruction:
  248. self.instruction.remove(item)
  249. self.instruction.remove(each)
  250. if id in self.objectsToDraw:
  251. self.objectsToDraw.remove(id)
  252. return
  253. def AddInstruction(self, instruction):
  254. """!Add instruction"""
  255. # add to instructions
  256. if instruction.type == 'map':
  257. self.instruction.insert(0, instruction)
  258. else:
  259. self.instruction.append(instruction)
  260. # add to drawable objects
  261. if instruction.type not in ('page', 'raster', 'vector', 'vProperties', 'initMap'):
  262. if instruction.type == 'map':
  263. self.objectsToDraw.insert(0, instruction.id)
  264. else:
  265. self.objectsToDraw.append(instruction.id)
  266. def FindInstructionByType(self, type, list = False):
  267. """!Find instruction(s) with the given type"""
  268. inst = []
  269. for each in self.instruction:
  270. if each.type == type:
  271. inst.append(each)
  272. if len(inst) == 1 and not list:
  273. return inst[0]
  274. return inst
  275. def Read(self, filename):
  276. """!Reads instruction file and creates instruction objects"""
  277. self.filename = filename
  278. # open file
  279. try:
  280. file = open(filename, 'r')
  281. except IOError:
  282. GError(message = _("Unable to open file\n%s") % filename)
  283. return
  284. # first read file to get information about region and scaletype
  285. isRegionComment = False
  286. orientation = 'Portrait'
  287. for line in file:
  288. if '# g.region' in line:
  289. self.SetRegion(regionInstruction = line)
  290. isRegionComment = True
  291. break
  292. if '# page orientation' in line:
  293. orientation = line.split(':')[-1].strip()
  294. if not isRegionComment:
  295. self.SetRegion(regionInstruction = None)
  296. # then run ps.map -b to get information for maploc
  297. # compute scale and center
  298. map = self.FindInstructionByType('map')
  299. region = grass.region()
  300. map['center'] = (region['n'] + region['s']) / 2, (region['w'] + region['e']) / 2
  301. mapRect = GetMapBounds(self.filename, portrait = (orientation == 'Portrait'))
  302. map['rect'] = mapRect
  303. proj = projInfo()
  304. toM = 1.0
  305. if proj['units']:
  306. toM = float(proj['meters'])
  307. units = UnitConversion(self.parent)
  308. w = units.convert(value = mapRect.Get()[2], fromUnit = 'inch', toUnit = 'meter') / toM
  309. map['scale'] = w / abs((region['w'] - region['e']))
  310. SetResolution(dpi = 300, width = map['rect'].width, height = map['rect'].height)
  311. # read file again, now with information about map bounds
  312. isBuffer = False
  313. buffer = []
  314. instruction = None
  315. vectorMapNumber = 1
  316. file.seek(0)
  317. for line in file:
  318. if not line.strip():
  319. continue
  320. line = line.strip()
  321. if isBuffer:
  322. buffer.append(line)
  323. if 'end' in line:
  324. isBuffer = False
  325. kwargs = {}
  326. if instruction == 'scalebar':
  327. kwargs['scale'] = map['scale']
  328. elif instruction in ('text', 'eps'):
  329. kwargs['mapInstruction'] = map
  330. elif instruction in ('vpoints', 'vlines', 'vareas'):
  331. kwargs['id'] = wx.NewId()
  332. kwargs['vectorMapNumber'] = vectorMapNumber
  333. vectorMapNumber += 1
  334. elif instruction == 'paper':
  335. kwargs['Orientation'] = orientation
  336. ok = self.SendToRead(instruction, buffer, **kwargs)
  337. if not ok: return False
  338. buffer = []
  339. continue
  340. elif line.startswith('paper'):
  341. instruction = 'paper'
  342. isBuffer = True
  343. buffer.append(line)
  344. elif line.startswith('border'):
  345. if line.split()[1].lower() in ('n', 'no', 'none'):
  346. ok = self.SendToRead('border', [line])
  347. if not ok: return False
  348. elif line.split()[1].lower() in ('y', 'yes'):
  349. instruction = 'border'
  350. isBuffer = True
  351. buffer.append(line)
  352. elif line.startswith('scale '):
  353. if isBuffer:
  354. continue
  355. ok = self.SendToRead('scale', line, isRegionComment = isRegionComment)
  356. if not ok: return False
  357. elif line.startswith('maploc'):
  358. ok = self.SendToRead(instruction = 'maploc', text = line)
  359. if not ok: return False
  360. elif line.startswith('raster'):
  361. ok = self.SendToRead(instruction = 'raster', text = line)
  362. if not ok: return False
  363. elif line.startswith('mapinfo'):
  364. instruction = 'mapinfo'
  365. isBuffer = True
  366. buffer.append(line)
  367. elif line.startswith('scalebar'):
  368. instruction = 'scalebar'
  369. isBuffer = True
  370. buffer.append(line)
  371. elif line.startswith('text'):
  372. instruction = 'text'
  373. isBuffer = True
  374. buffer.append(line)
  375. elif line.startswith('eps'):
  376. instruction = 'eps'
  377. isBuffer = True
  378. buffer.append(line)
  379. elif line.startswith('colortable'):
  380. if len(line.split()) == 2 and line.split()[1].lower() in ('n', 'no', 'none'):
  381. break
  382. instruction = 'colortable'
  383. isBuffer = True
  384. buffer.append(line)
  385. elif line.startswith('vlegend'):
  386. instruction = 'vlegend'
  387. isBuffer = True
  388. buffer.append(line)
  389. elif line.startswith('vpoints'):
  390. instruction = 'vpoints'
  391. isBuffer = True
  392. buffer.append(line)
  393. elif line.startswith('vlines'):
  394. instruction = 'vlines'
  395. isBuffer = True
  396. buffer.append(line)
  397. elif line.startswith('vareas'):
  398. instruction = 'vareas'
  399. isBuffer = True
  400. buffer.append(line)
  401. rasterLegend = self.FindInstructionByType('rasterLegend')
  402. raster = self.FindInstructionByType('raster')
  403. page = self.FindInstructionByType('page')
  404. vector = self.FindInstructionByType('vector')
  405. vectorLegend = self.FindInstructionByType('vectorLegend')
  406. vectorMaps = self.FindInstructionByType('vProperties', list = True)
  407. # check (in case of scaletype 0) if map is drawn also
  408. map['drawMap'] = False
  409. if map['scaleType'] == 0:
  410. mapForRegion = map['map']
  411. if map['mapType'] == 'raster' and raster:
  412. if mapForRegion == raster['raster']:
  413. map['drawMap'] = True
  414. elif map['mapType'] == 'vector' and vector:
  415. for vmap in vector['list']:
  416. if mapForRegion == vmap[0]:
  417. map['drawMap'] = True
  418. # rasterLegend
  419. if rasterLegend:
  420. if rasterLegend['rasterDefault'] and raster:
  421. rasterLegend['raster'] = raster['raster']
  422. if not rasterLegend['discrete']:
  423. rasterType = getRasterType(map = rasterLegend['raster'])
  424. if rasterType == 'CELL':
  425. rasterLegend['discrete'] = 'y'
  426. else:
  427. rasterLegend['discrete'] = 'n'
  428. #estimate size
  429. height = rasterLegend.EstimateHeight(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'],
  430. fontsize = rasterLegend['fontsize'],
  431. cols = rasterLegend['cols'],
  432. height = rasterLegend['height'])
  433. width = rasterLegend.EstimateWidth(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'],
  434. fontsize = rasterLegend['fontsize'],
  435. cols = rasterLegend['cols'] ,
  436. width = rasterLegend['width'],
  437. paperInstr = page)
  438. rasterLegend['rect'] = wx.Rect2D(x = float(rasterLegend['where'][0]), y = float(rasterLegend['where'][1]),
  439. w = width, h = height)
  440. # vectors, vlegend
  441. if vector:
  442. for vmap in vectorMaps:
  443. for i, each in enumerate(vector['list']):
  444. if each[2] == vmap.id:
  445. vector['list'][i][4] = vmap['label']
  446. vector['list'][i][3] = vmap['lpos']
  447. if vectorLegend:
  448. size = vectorLegend.EstimateSize(vectorInstr = vector, fontsize = vectorLegend['fontsize'],
  449. width = vectorLegend['width'], cols = vectorLegend['cols'])
  450. vectorLegend['rect'] = wx.Rect2D(x = float(vectorLegend['where'][0]), y = float(vectorLegend['where'][1]),
  451. w = size[0], h = size[1])
  452. page = self.FindInstructionByType('page')
  453. if not page:
  454. page = PageSetup(wx.NewId())
  455. self.AddInstruction(page)
  456. else:
  457. page['Orientation'] = orientation
  458. #
  459. return True
  460. def SendToRead(self, instruction, text, **kwargs):
  461. psmapInstrDict = dict(paper = ['page'],
  462. maploc = ['map'],
  463. scale = ['map'],
  464. border = ['map'],
  465. raster = ['raster'],
  466. mapinfo = ['mapinfo'],
  467. scalebar = ['scalebar'],
  468. text = ['text'],
  469. eps = ['image', 'northArrow'],
  470. vpoints = ['vector', 'vProperties'],
  471. vlines = ['vector', 'vProperties'],
  472. vareas = ['vector', 'vProperties'],
  473. colortable = ['rasterLegend'],
  474. vlegend = ['vectorLegend']
  475. )
  476. myInstrDict = dict(page = PageSetup,
  477. map = MapFrame,
  478. raster = Raster,
  479. mapinfo = Mapinfo,
  480. scalebar = Scalebar,
  481. text = Text,
  482. image = Image,
  483. northArrow = NorthArrow,
  484. rasterLegend = RasterLegend,
  485. vectorLegend = VectorLegend,
  486. vector = Vector,
  487. vProperties = VProperties
  488. )
  489. myInstruction = psmapInstrDict[instruction]
  490. for i in myInstruction:
  491. instr = self.FindInstructionByType(i)
  492. if i in ('text', 'vProperties', 'image', 'northArrow') or not instr:
  493. id = wx.NewId() #!vProperties expect subtype
  494. if i == 'vProperties':
  495. id = kwargs['id']
  496. newInstr = myInstrDict[i](id, subType = instruction[1:])
  497. elif i in ('image', 'northArrow'):
  498. commentFound = False
  499. for line in text:
  500. if line.find("# north arrow") >= 0:
  501. commentFound = True
  502. if i == 'image' and commentFound or \
  503. i == 'northArrow' and not commentFound:
  504. continue
  505. newInstr = myInstrDict[i](id, settings = self)
  506. else:
  507. newInstr = myInstrDict[i](id)
  508. ok = newInstr.Read(instruction, text, **kwargs)
  509. if ok:
  510. self.AddInstruction(newInstr)
  511. else:
  512. return False
  513. else:
  514. ok = instr.Read(instruction, text, **kwargs)
  515. if not ok:
  516. return False
  517. return True
  518. def SetRegion(self, regionInstruction):
  519. """!Sets region from file comment or sets current region in case of no comment"""
  520. map = MapFrame(wx.NewId())
  521. self.AddInstruction(map)
  522. if regionInstruction:
  523. cmd = CmdToTuple(regionInstruction.strip('# ').split())
  524. # define scaleType
  525. if len(cmd[1]) <= 3:
  526. if 'rast' in cmd[1]:
  527. map['scaleType'] = 0
  528. map['mapType'] = 'raster'
  529. map['map'] = cmd[1]['rast']
  530. elif 'vect' in cmd[1]:
  531. map['scaleType'] = 0
  532. map['mapType'] = 'vector'
  533. map['map'] = cmd[1]['vect']
  534. elif 'region' in cmd[1]:
  535. map['scaleType'] = 1
  536. map['region'] = cmd[1]['region']
  537. else:
  538. map['scaleType'] = 2
  539. else:
  540. map['scaleType'] = 2
  541. grass.del_temp_region()
  542. region = grass.region()
  543. grass.use_temp_region()
  544. cmd = ['g.region', region]
  545. cmdString = GetCmdString(cmd).replace('g.region', '')
  546. GMessage(_("Instruction file will be loaded with following region: %s\n") % cmdString)
  547. try:
  548. RunCommand(cmd[0], **cmd[1])
  549. except grass.ScriptError, e:
  550. GError(_("Region cannot be set\n%s") % e)
  551. return False
  552. class InstructionObject:
  553. """!Abtract class representing single instruction"""
  554. def __init__(self, id):
  555. self.id = id
  556. # default values
  557. self.defaultInstruction = dict()
  558. # current values
  559. self.instruction = self.defaultInstruction
  560. # converting units
  561. self.unitConv = UnitConversion()
  562. def __str__(self):
  563. """!Returns particular part of text instruction"""
  564. return ''
  565. def __getitem__(self, key):
  566. for each in self.instruction.keys():
  567. if each == key:
  568. return self.instruction[key]
  569. return None
  570. def __setitem__(self, key, value):
  571. self.instruction[key] = value
  572. def GetInstruction(self):
  573. """!Get current values"""
  574. return self.instruction
  575. def SetInstruction(self, instruction):
  576. """!Set default values"""
  577. self.instruction = instruction
  578. def Read(self, instruction, text, **kwargs):
  579. """!Read instruction and save them"""
  580. pass
  581. class InitMap(InstructionObject):
  582. """!Class representing virtual map"""
  583. def __init__(self, id):
  584. InstructionObject.__init__(self, id = id)
  585. self.type = 'initMap'
  586. # default values
  587. self.defaultInstruction = dict(rect = None, scale = None)
  588. # current values
  589. self.instruction = dict(self.defaultInstruction)
  590. class MapFrame(InstructionObject):
  591. """!Class representing map (instructions maploc, scale, border)"""
  592. def __init__(self, id):
  593. InstructionObject.__init__(self, id = id)
  594. self.type = 'map'
  595. # default values
  596. self.defaultInstruction = dict(map = None, mapType = None, drawMap = True, region = None,
  597. rect = wx.Rect2D(), scaleType = 0, scale = None, center = None,
  598. resolution = 300, border = 'y', width = 1, color = '0:0:0')
  599. # current values
  600. self.instruction = dict(self.defaultInstruction)
  601. def __str__(self):
  602. instr = ''
  603. comment = ''
  604. #region settings
  605. region = grass.region()
  606. if self.instruction['scaleType'] == 0: #match map
  607. map = self.instruction['map']
  608. if self.instruction['mapType'] == 'raster':
  609. comment = "# g.region rast=%s nsres=%s ewres=%s\n" % (map, region['nsres'], region['ewres'])
  610. else:
  611. comment = "# g.region vect=%s\n" % (map)
  612. elif self.instruction['scaleType'] == 1:# saved region
  613. region = self.instruction['region']
  614. comment = "# g.region region=%s\n" % region
  615. elif self.instruction['scaleType'] in (2, 3): #current region, fixed scale
  616. comment = string.Template("# g.region n=$n s=$s e=$e w=$w rows=$rows cols=$cols \n").substitute(**region)
  617. instr += comment
  618. instr += '\n'
  619. # maploc
  620. maplocInstruction = "maploc %.3f %.3f" % (self.instruction['rect'].x, self.instruction['rect'].y)
  621. if self.instruction['scaleType'] != 3:
  622. maplocInstruction += " %.3f %.3f"% (self.instruction['rect'].width, self.instruction['rect'].height)
  623. instr += maplocInstruction
  624. instr += '\n'
  625. # scale
  626. if self.instruction['scaleType'] == 3: #fixed scale
  627. scaleInstruction = "scale 1:%.0f" % (1/self.instruction['scale'])
  628. instr += scaleInstruction
  629. instr += '\n'
  630. # border
  631. borderInstruction = ''
  632. if self.instruction['border'] == 'n':
  633. borderInstruction = "border n"
  634. else:
  635. borderInstruction = "border y\n"
  636. borderInstruction += string.Template(" width $width\n color $color\n").substitute(self.instruction)
  637. borderInstruction += " end"
  638. instr += borderInstruction
  639. instr += '\n'
  640. return instr
  641. def Read(self, instruction, text, **kwargs):
  642. """!Read instruction and save information"""
  643. if 'isRegionComment' in kwargs:
  644. isRegionComment = kwargs['isRegionComment']
  645. instr = {}
  646. if instruction == 'border':
  647. for line in text:
  648. if line.startswith('end'):
  649. break
  650. try:
  651. if line.split()[1].lower() in ('n', 'no', 'none'):
  652. instr['border'] = 'n'
  653. break
  654. elif line.split()[1].lower() in ('y', 'yes'):
  655. instr['border'] = 'y'
  656. elif line.startswith('width'):
  657. instr['width'] = line.split()[1]
  658. elif line.startswith('color'):
  659. instr['color'] = line.split()[1]
  660. except IndexError:
  661. GError(_("Failed to read instruction %s") % instruction)
  662. return False
  663. elif instruction == 'scale':
  664. try:
  665. scaleText = text.strip('scale ').split(':')[1]
  666. # when scale instruction given and region comment also, then scaletype is fixed scale
  667. if not isRegionComment:
  668. instr['scaleType'] = 2
  669. else:
  670. instr['scaleType'] = 3
  671. scale = 1/float(scaleText)
  672. if abs(scale - self.instruction['scale']) > (0.01 * scale):
  673. GWarning(_("Scale has changed, old value: %(old)s\nnew value: %(new)s") % \
  674. { 'old' : scale, 'new' : self.instruction['scale'] })
  675. except (ValueError, IndexError):
  676. GError(_("Failed to read instruction %s.\nUse 1:25000 notation.") % instruction)
  677. return False
  678. elif instruction == 'maploc':
  679. maploc = text.strip('maploc ').split()
  680. if len(maploc) >= 2:
  681. if abs(self.instruction['rect'].Get()[0] - float(maploc[0])) > 0.5 or \
  682. abs(self.instruction['rect'].Get()[1] - float(maploc[1])) > 0.5:
  683. GWarning(_("Map frame position changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \
  684. { 'old1' : maploc[0], 'old2' : maploc[1],
  685. 'new1' : self.instruction['rect'].Get()[0], 'new2' : self.instruction['rect'].Get()[1] })
  686. #instr['rect'] = wx.Rect2D(float(maploc[0]), float(maploc[1]), self.instruction['rect'][2], self.instruction['rect'][3])
  687. if len(maploc) == 4:
  688. if abs(self.instruction['rect'].Get()[2] - float(maploc[2])) > 0.5 or \
  689. abs(self.instruction['rect'].Get()[3] - float(maploc[3])) > 0.5:
  690. GWarning(_("Map frame size changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \
  691. { 'old1' : maploc[2], 'old2' : maploc[3],
  692. 'new1' : self.instruction['rect'].Get()[2], 'new2' : self.instruction['rect'].Get()[3] })
  693. #instr['rect'] = wx.Rect2D(*map(float, maploc))
  694. self.instruction.update(instr)
  695. return True
  696. class PageSetup(InstructionObject):
  697. """!Class representing page instruction"""
  698. def __init__(self, id):
  699. InstructionObject.__init__(self, id = id)
  700. self.type = 'page'
  701. # default values
  702. self.defaultInstruction = dict(Units = 'inch', Format = 'a4', Orientation = 'Portrait',
  703. Width = 8.268, Height = 11.693, Left = 0.5, Right = 0.5, Top = 1, Bottom = 1)
  704. # current values
  705. self.instruction = dict(self.defaultInstruction)
  706. def __str__(self):
  707. if self.instruction['Format'] == 'custom':
  708. instr = string.Template("paper\n width $Width\n height $Height\n").substitute(self.instruction)
  709. else:
  710. instr = string.Template("paper $Format\n").substitute(self.instruction)
  711. instr += string.Template(" left $Left\n right $Right\n bottom $Bottom\n top $Top\n end").substitute(self.instruction)
  712. return instr
  713. def Read(self, instruction, text, **kwargs):
  714. """!Read instruction and save information"""
  715. instr = {}
  716. self.cats = ['Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
  717. self.subInstr = dict(zip(['width', 'height', 'left', 'right', 'top', 'bottom'], self.cats))
  718. if instruction == 'paper': # just for sure
  719. for line in text:
  720. if line.startswith('paper'):
  721. if len(line.split()) > 1:
  722. pformat = line.split()[1]
  723. availableFormats = self._toDict(grass.read_command('ps.map', flags = 'p',
  724. quiet = True))
  725. # e.g. paper a3
  726. try:
  727. instr['Format'] = pformat
  728. for key, value in availableFormats[pformat].iteritems():
  729. instr[key] = float(value)
  730. break
  731. except KeyError:
  732. GError(_("Failed to read instruction %(file)s.\nUnknown format %(for)s") % \
  733. { 'file' : instruction, 'for' : format })
  734. return False
  735. else:
  736. # paper
  737. # width ...
  738. instr['Format'] = 'custom'
  739. # read subinstructions
  740. elif instr['Format'] == 'custom' and not line.startswith('end'):
  741. text = line.split()
  742. try:
  743. instr[self.subInstr[text[0]]] = float(text[1])
  744. except (IndexError, KeyError):
  745. GError(_("Failed to read instruction %s.") % instruction)
  746. return False
  747. if 'Orientation' in kwargs and kwargs['Orientation'] == 'Landscape':
  748. instr['Width'], instr['Height'] = instr['Height'], instr['Width']
  749. self.instruction.update(instr)
  750. return True
  751. def _toDict(self, paperStr):
  752. sizeDict = dict()
  753. # cats = self.subInstr[ 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
  754. for line in paperStr.strip().split('\n'):
  755. d = dict(zip(self.cats, line.split()[1:]))
  756. sizeDict[line.split()[0]] = d
  757. return sizeDict
  758. class Mapinfo(InstructionObject):
  759. """!Class representing mapinfo instruction"""
  760. def __init__(self, id):
  761. InstructionObject.__init__(self, id = id)
  762. self.type = 'mapinfo'
  763. # default values
  764. self.defaultInstruction = dict(unit = 'inch', where = (0, 0),
  765. font = 'Helvetica', fontsize = 10, color = '0:0:0', background = 'none',
  766. border = 'none', rect = None)
  767. # current values
  768. self.instruction = dict(self.defaultInstruction)
  769. def __str__(self):
  770. instr = "mapinfo\n"
  771. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  772. instr += string.Template(" font $font\n fontsize $fontsize\n color $color\n").substitute(self.instruction)
  773. instr += string.Template(" background $background\n border $border\n").substitute(self.instruction)
  774. instr += " end"
  775. return instr
  776. def Read(self, instruction, text):
  777. """!Read instruction and save information"""
  778. instr = {}
  779. try:
  780. for line in text:
  781. sub = line.split(None,1)
  782. if sub[0] == 'font':
  783. instr['font'] = sub[1]
  784. elif sub[0] == 'fontsize':
  785. instr['fontsize'] = int(sub[1])
  786. elif sub[0] == 'color':
  787. instr['color'] = sub[1]
  788. elif sub[0] == 'background':
  789. instr['background'] = sub[1]
  790. elif sub[0] == 'border':
  791. instr['border'] = sub[1]
  792. elif sub[0] == 'where':
  793. instr['where'] = float(sub[1].split()[0]), float(sub[1].split()[1])
  794. except (ValueError, IndexError):
  795. GError(_("Failed to read instruction %s") % instruction)
  796. return False
  797. self.instruction.update(instr)
  798. self.instruction['rect'] = self.EstimateRect(mapinfoDict = self.instruction)
  799. return True
  800. def EstimateRect(self, mapinfoDict):
  801. """!Estimate size to draw mapinfo"""
  802. w = mapinfoDict['fontsize'] * 20 # any better estimation?
  803. h = mapinfoDict['fontsize'] * 7
  804. width = self.unitConv.convert(value = w, fromUnit = 'point', toUnit = 'inch')
  805. height = self.unitConv.convert(value = h, fromUnit = 'point', toUnit = 'inch')
  806. return wx.Rect2D(x = float(mapinfoDict['where'][0]), y = float(mapinfoDict['where'][1]), w = width, h = height)
  807. class Text(InstructionObject):
  808. """!Class representing text instruction"""
  809. def __init__(self, id):
  810. InstructionObject.__init__(self, id = id)
  811. self.type = 'text'
  812. # default values
  813. self.defaultInstruction = dict(text = "", font = "Helvetica", fontsize = 10, color = 'black', background = 'none',
  814. hcolor = 'none', hwidth = 1, border = 'none', width = '1', XY = True,
  815. where = (0,0), unit = 'inch', rotate = None,
  816. ref = "center center", xoffset = 0, yoffset = 0, east = None, north = None)
  817. # current values
  818. self.instruction = dict(self.defaultInstruction)
  819. def __str__(self):
  820. text = self.instruction['text'].replace('\n','\\n')
  821. instr = "text %s %s" % (self.instruction['east'], self.instruction['north'])
  822. try:
  823. instr += " %s\n" % text.encode('latin_1')
  824. except UnicodeEncodeError, err:
  825. try:
  826. pos = str(err).split('position')[1].split(':')[0].strip()
  827. except IndexError:
  828. pos = ''
  829. if pos:
  830. message = _("Characters on position %s are not supported "
  831. "by ISO-8859-1 (Latin 1) encoding "
  832. "which is required by module ps.map.") % pos
  833. else:
  834. message = _("Not all characters are supported "
  835. "by ISO-8859-1 (Latin 1) encoding "
  836. "which is required by module ps.map.")
  837. GMessage(message = message)
  838. return ''
  839. instr += (string.Template(" font $font\n fontsize $fontsize\n color $color\n").
  840. substitute(self.instruction).
  841. encode('latin_1'))
  842. instr += string.Template(" hcolor $hcolor\n").substitute(self.instruction).encode('latin_1')
  843. if self.instruction['hcolor'] != 'none':
  844. instr += string.Template(" hwidth $hwidth\n").substitute(self.instruction).encode('latin_1')
  845. instr += string.Template(" border $border\n").substitute(self.instruction).encode('latin_1')
  846. if self.instruction['border'] != 'none':
  847. instr += string.Template(" width $width\n").substitute(self.instruction).encode('latin_1')
  848. instr += string.Template(" background $background\n").substitute(self.instruction).encode('latin_1')
  849. if self.instruction["ref"] != '0':
  850. instr += string.Template(" ref $ref\n").substitute(self.instruction).encode('latin_1')
  851. if self.instruction["rotate"]:
  852. instr += string.Template(" rotate $rotate\n").substitute(self.instruction).encode('latin_1')
  853. if float(self.instruction["xoffset"]) or float(self.instruction["yoffset"]):
  854. instr += (string.Template(" xoffset $xoffset\n yoffset $yoffset\n").
  855. substitute(self.instruction).encode('latin_1'))
  856. instr += " end"
  857. return instr
  858. def Read(self, instruction, text, **kwargs):
  859. """!Read instruction and save information"""
  860. map = kwargs['mapInstruction']
  861. instr = {}
  862. for line in text:
  863. try:
  864. sub = line.split(None, 1)[0]
  865. if sub == 'text':
  866. e, n = line.split(None, 3)[1:3]
  867. if '%' in e and '%' in n:
  868. instr['XY'] = True
  869. instr['east'], instr['north'] = self.PercentToReal(e, n)
  870. else:
  871. instr['XY'] = False
  872. instr['east'], instr['north'] = float(e), float(n)
  873. instr['text'] = line.split(None, 3)[3]
  874. elif sub == 'font':
  875. instr['font'] = line.split(None, 1)[1]
  876. elif sub == 'fontsize':
  877. instr['fontsize'] = float(line.split(None, 1)[1])
  878. elif sub == 'color':
  879. instr['color'] = line.split(None, 1)[1]
  880. elif sub == 'width':
  881. instr['width'] = line.split(None, 1)[1]
  882. elif sub == 'hcolor':
  883. instr['hcolor'] = line.split(None, 1)[1]
  884. elif sub == 'hwidth':
  885. instr['hwidth'] = line.split(None, 1)[1]
  886. elif sub == 'background':
  887. instr['background'] = line.split(None, 1)[1]
  888. elif sub == 'border':
  889. instr['border'] = line.split(None, 1)[1]
  890. elif sub == 'ref':
  891. instr['ref'] = line.split(None, 1)[1]
  892. elif sub == 'rotate':
  893. instr['rotate'] = float(line.split(None, 1)[1])
  894. elif sub == 'xoffset':
  895. instr['xoffset'] = int(line.split(None, 1)[1])
  896. elif sub == 'yoffset':
  897. instr['yoffset'] = int(line.split(None, 1)[1])
  898. elif sub == 'opaque':
  899. if line.split(None, 1)[1].lower() in ('n', 'none'):
  900. instr['background'] = 'none'
  901. except(IndexError, ValueError):
  902. GError(_("Failed to read instruction %s") % instruction)
  903. return False
  904. instr['where'] = PaperMapCoordinates(map = map, x = instr['east'], y = instr['north'], paperToMap = False)
  905. self.instruction.update(instr)
  906. return True
  907. def PercentToReal(self, e, n):
  908. """!Converts text coordinates from percent of region to map coordinates"""
  909. e, n = float(e.strip('%')), float(n.strip('%'))
  910. region = grass.region()
  911. N = region['s'] + (region['n'] - region['s']) / 100 * n
  912. E = region['w'] + (region['e'] - region['w']) / 100 * e
  913. return E, N
  914. class Image(InstructionObject):
  915. """!Class representing eps instruction - image"""
  916. def __init__(self, id, settings):
  917. InstructionObject.__init__(self, id = id)
  918. self.settings = settings
  919. self.type = 'image'
  920. # default values
  921. self.defaultInstruction = dict(epsfile = "", XY = True, where = (0,0), unit = 'inch',
  922. east = None, north = None,
  923. rotate = None, scale = 1)
  924. # current values
  925. self.instruction = dict(self.defaultInstruction)
  926. def __str__(self):
  927. self.ChangeRefPoint(toCenter = True)
  928. instr = "eps %s %s\n" % (self.instruction['east'], self.instruction['north'])
  929. instr += string.Template(" epsfile $epsfile\n").substitute(self.instruction)
  930. if self.instruction["rotate"]:
  931. instr += string.Template(" rotate $rotate\n").substitute(self.instruction)
  932. if self.instruction["scale"]:
  933. instr += string.Template(" scale $scale\n").substitute(self.instruction)
  934. instr += " end"
  935. return instr
  936. def Read(self, instruction, text, **kwargs):
  937. """!Read instruction and save information"""
  938. mapInstr = kwargs['mapInstruction']
  939. instr = {}
  940. for line in text:
  941. try:
  942. sub = line.split(None, 1)[0]
  943. if sub == 'eps':
  944. e, n = line.split(None, 3)[1:3]
  945. if '%' in e and '%' in n:
  946. instr['XY'] = True
  947. instr['east'], instr['north'] = self.PercentToReal(e, n)
  948. else:
  949. instr['XY'] = False
  950. instr['east'], instr['north'] = float(e), float(n)
  951. elif sub == 'epsfile':
  952. instr['epsfile'] = line.split(None, 1)[1]
  953. elif sub == 'rotate':
  954. instr['rotate'] = float(line.split(None, 1)[1])
  955. elif sub == 'scale':
  956. instr['scale'] = float(line.split(None, 1)[1])
  957. except(IndexError, ValueError):
  958. GError(_("Failed to read instruction %s") % instruction)
  959. return False
  960. if not os.path.exists(instr['epsfile']):
  961. GError(_("Failed to read instruction %s: file %s not found.") % instruction, instr['epsfile'])
  962. return False
  963. instr['epsfile'] = os.path.abspath(instr['epsfile'])
  964. instr['size'] = self.GetImageOrigSize(instr['epsfile'])
  965. if 'rotate' in instr:
  966. instr['size'] = BBoxAfterRotation(instr['size'][0], instr['size'][1], instr['rotate'])
  967. self.instruction.update(instr)
  968. self.ChangeRefPoint(toCenter = False)
  969. instr['where'] = PaperMapCoordinates(map = mapInstr, x = self.instruction['east'],
  970. y = self.instruction['north'], paperToMap = False)
  971. w = self.unitConv.convert(value = instr['size'][0], fromUnit = 'point', toUnit = 'inch')
  972. h = self.unitConv.convert(value = instr['size'][1], fromUnit = 'point', toUnit = 'inch')
  973. instr['rect'] = wx.Rect2D(x = float(instr['where'][0]), y = float(instr['where'][1]),
  974. w = w * self.instruction['scale'], h = h * self.instruction['scale'])
  975. self.instruction.update(instr)
  976. return True
  977. def PercentToReal(self, e, n):
  978. """!Converts eps coordinates from percent of region to map coordinates"""
  979. e, n = float(e.strip('%')), float(n.strip('%'))
  980. region = grass.region()
  981. N = region['s'] + (region['n'] - region['s']) / 100 * n
  982. E = region['w'] + (region['e'] - region['w']) / 100 * e
  983. return E, N
  984. def ChangeRefPoint(self, toCenter):
  985. """!Change reference point (left top x center)"""
  986. mapInstr = self.settings.FindInstructionByType('map')
  987. if not mapInstr:
  988. mapInstr = self.settings.FindInstructionByType('initMap')
  989. mapId = mapInstr.id
  990. if toCenter:
  991. center = self.instruction['rect'].GetCentre()
  992. ENCenter = PaperMapCoordinates(map = self.settings[mapId],
  993. x = center[0], y = center[1], paperToMap = True)
  994. self.instruction['east'], self.instruction['north'] = ENCenter
  995. else:
  996. x, y = PaperMapCoordinates(map = self.settings[mapId], x = self.instruction['east'],
  997. y = self.instruction['north'], paperToMap = False)
  998. w = self.unitConv.convert(value = self.instruction['size'][0], fromUnit = 'point', toUnit = 'inch')
  999. h = self.unitConv.convert(value = self.instruction['size'][1], fromUnit = 'point', toUnit = 'inch')
  1000. x -= w * self.instruction['scale'] / 2
  1001. y -= h * self.instruction['scale'] / 2
  1002. e, n = PaperMapCoordinates(map = self.settings[mapId], x = x, y = y, paperToMap = True)
  1003. self.instruction['east'], self.instruction['north'] = e, n
  1004. def GetImageOrigSize(self, imagePath):
  1005. """!Get image size.
  1006. If eps, size is read from image header.
  1007. """
  1008. fileName = os.path.split(imagePath)[1]
  1009. # if eps, read info from header
  1010. if os.path.splitext(fileName)[1].lower() == '.eps':
  1011. bbInfo = "%%BoundingBox"
  1012. file = open(imagePath,"r")
  1013. w = h = 0
  1014. while file:
  1015. line = file.readline()
  1016. if line.find(bbInfo) == 0:
  1017. w, h = line.split()[3:5]
  1018. break
  1019. file.close()
  1020. return float(w), float(h)
  1021. else: # we can use wx.Image
  1022. img = wx.Image(fileName, type=wx.BITMAP_TYPE_ANY)
  1023. return img.GetWidth(), img.GetHeight()
  1024. class NorthArrow(Image):
  1025. """!Class representing eps instruction -- North Arrow"""
  1026. def __init__(self, id, settings):
  1027. Image.__init__(self, id = id, settings = settings)
  1028. self.type = 'northArrow'
  1029. def __str__(self):
  1030. self.ChangeRefPoint(toCenter = True)
  1031. instr = "eps %s %s\n" % (self.instruction['east'], self.instruction['north'])
  1032. instr += "# north arrow\n"
  1033. instr += string.Template(" epsfile $epsfile\n").substitute(self.instruction)
  1034. if self.instruction["rotate"]:
  1035. instr += string.Template(" rotate $rotate\n").substitute(self.instruction)
  1036. if self.instruction["scale"]:
  1037. instr += string.Template(" scale $scale\n").substitute(self.instruction)
  1038. instr += " end"
  1039. return instr
  1040. class Scalebar(InstructionObject):
  1041. """!Class representing scalebar instruction"""
  1042. def __init__(self, id):
  1043. InstructionObject.__init__(self, id = id)
  1044. self.type = 'scalebar'
  1045. # default values
  1046. self.defaultInstruction = dict(unit = 'inch', where = (1,1),
  1047. unitsLength = 'auto', unitsHeight = 'inch',
  1048. length = None, height = 0.1, rect = None,
  1049. fontsize = 10, background = 'y',
  1050. scalebar = 'f', segment = 4, numbers = 1)
  1051. # current values
  1052. self.instruction = dict(self.defaultInstruction)
  1053. def __str__(self):
  1054. instr = string.Template("scalebar $scalebar\n").substitute(self.instruction)
  1055. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  1056. instr += string.Template(" length $length\n units $unitsLength\n").substitute(self.instruction)
  1057. instr += string.Template(" height $height\n").substitute(self.instruction)
  1058. instr += string.Template(" segment $segment\n numbers $numbers\n").substitute(self.instruction)
  1059. instr += string.Template(" fontsize $fontsize\n background $background\n").substitute(self.instruction)
  1060. instr += " end"
  1061. return instr
  1062. def Read(self, instruction, text, **kwargs):
  1063. """!Read instruction and save information"""
  1064. scale = kwargs['scale']
  1065. instr = {}
  1066. for line in text:
  1067. try:
  1068. if line.startswith('scalebar'):
  1069. if 'scalebar s' in line:
  1070. instr['scalebar'] = 's'
  1071. else:
  1072. instr['scalebar'] = 'f'
  1073. elif line.startswith('where'):
  1074. instr['where'] = map(float, line.split()[1:3])
  1075. elif line.startswith('length'):
  1076. instr['length'] = float(line.split()[1])
  1077. elif line.startswith('units'):
  1078. if line.split()[1] in ['auto', 'meters', 'kilometers', 'feet', 'miles', 'nautmiles']:
  1079. instr['unitsLength'] = line.split()[1]
  1080. elif line.startswith('height'):
  1081. instr['height'] = float(line.split()[1])
  1082. elif line.startswith('fontsize'):
  1083. instr['fontsize'] = float(line.split()[1])
  1084. elif line.startswith('numbers'):
  1085. instr['numbers'] = int(line.split()[1])
  1086. elif line.startswith('segment'):
  1087. instr['segment'] = int(line.split()[1])
  1088. elif line.startswith('background'):
  1089. if line.split()[1].strip().lower() in ('y','yes'):
  1090. instr['background'] = 'y'
  1091. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1092. instr['background'] = 'n'
  1093. except(IndexError, ValueError):
  1094. GError(_("Failed to read instruction %s") % instruction)
  1095. return False
  1096. self.instruction.update(instr)
  1097. w, h = self.EstimateSize(scalebarDict = self.instruction, scale = scale)
  1098. x = self.instruction['where'][0] - w / 2
  1099. y = self.instruction['where'][1] - h / 2
  1100. self.instruction['rect'] = wx.Rect2D(x, y, w, h)
  1101. return True
  1102. def EstimateSize(self, scalebarDict, scale):
  1103. """!Estimate size to draw scalebar"""
  1104. units = projInfo()['units']
  1105. if not units or units not in self.unitConv.getAllUnits():
  1106. units = 'meters'
  1107. if scalebarDict['unitsLength'] != 'auto':
  1108. length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = scalebarDict['unitsLength'], toUnit = 'inch')
  1109. else:
  1110. length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = units, toUnit = 'inch')
  1111. length *= scale
  1112. length *= 1.1 #for numbers on the edge
  1113. height = scalebarDict['height'] + 2 * self.unitConv.convert(value = scalebarDict['fontsize'], fromUnit = 'point', toUnit = 'inch')
  1114. return (length, height)
  1115. class RasterLegend(InstructionObject):
  1116. """!Class representing colortable instruction"""
  1117. def __init__(self, id):
  1118. InstructionObject.__init__(self, id = id)
  1119. self.type = 'rasterLegend'
  1120. # default values
  1121. self.defaultInstruction = dict(rLegend = False, unit = 'inch', rasterDefault = True, raster = None,
  1122. discrete = None, type = None,
  1123. where = (0, 0),
  1124. width = None, height = None, cols = 1, font = "Helvetica", fontsize = 10,
  1125. #color = '0:0:0', tickbar = False, range = False, min = 0, max = 0,
  1126. color = 'black', tickbar = 'n', range = False, min = 0, max = 0,
  1127. nodata = 'n')
  1128. # current values
  1129. self.instruction = dict(self.defaultInstruction)
  1130. def __str__(self):
  1131. instr = "colortable y\n"
  1132. instr += string.Template(" raster $raster\n").substitute(self.instruction)
  1133. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  1134. if self.instruction['width']:
  1135. instr += string.Template(" width $width\n").substitute(self.instruction)
  1136. instr += string.Template(" discrete $discrete\n").substitute(self.instruction)
  1137. if self.instruction['discrete'] == 'n':
  1138. if self.instruction['height']:
  1139. instr += string.Template(" height $height\n").substitute(self.instruction)
  1140. instr += string.Template(" tickbar $tickbar\n").substitute(self.instruction)
  1141. if self.instruction['range']:
  1142. instr += string.Template(" range $min $max\n").substitute(self.instruction)
  1143. else:
  1144. instr += string.Template(" cols $cols\n").substitute(self.instruction)
  1145. instr += string.Template(" nodata $nodata\n").substitute(self.instruction)
  1146. instr += string.Template(" font $font\n fontsize $fontsize\n color $color\n")\
  1147. .substitute(self.instruction)
  1148. instr += " end"
  1149. return instr
  1150. def Read(self, instruction, text, **kwargs):
  1151. """!Read instruction and save information"""
  1152. instr = {}
  1153. instr['rLegend'] = True
  1154. for line in text:
  1155. try:
  1156. if line.startswith('where'):
  1157. instr['where'] = map(float, line.split()[1:3])
  1158. elif line.startswith('font '):
  1159. instr['font'] = line.split()[1]
  1160. elif line.startswith('fontsize'):
  1161. instr['fontsize'] = float(line.split()[1])
  1162. elif line.startswith('color '):
  1163. instr['color'] = line.split()[1]
  1164. elif line.startswith('raster'):
  1165. instr['raster'] = line.split()[1]
  1166. elif line.startswith('width'):
  1167. instr['width'] = float(line.split()[1])
  1168. elif line.startswith('height'):
  1169. instr['height'] = float(line.split()[1])
  1170. elif line.startswith('cols'):
  1171. instr['cols'] = int(line.split()[1])
  1172. elif line.startswith('range'):
  1173. instr['range'] = True
  1174. instr['min'] = float(line.split()[1])
  1175. instr['max'] = float(line.split()[2])
  1176. elif line.startswith('nodata'):
  1177. if line.split()[1].strip().lower() in ('y','yes'):
  1178. instr['nodata'] = 'y'
  1179. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1180. instr['nodata'] = 'n'
  1181. elif line.startswith('tickbar'):
  1182. if line.split()[1].strip().lower() in ('y','yes'):
  1183. instr['tickbar'] = 'y'
  1184. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1185. instr['tickbar'] = 'n'
  1186. elif line.startswith('discrete'):
  1187. if line.split()[1].strip().lower() in ('y','yes'):
  1188. instr['discrete'] = 'y'
  1189. elif line.split()[1].strip().lower() in ('n','no', 'none'):
  1190. instr['discrete'] = 'n'
  1191. except(IndexError, ValueError):
  1192. GError(_("Failed to read instruction %s") % instruction)
  1193. return False
  1194. if 'raster' in instr:
  1195. instr['rasterDefault'] = False
  1196. if 'discrete' not in instr:
  1197. rasterType = getRasterType(map = instr['raster'])
  1198. instr['type'] = rasterType
  1199. if rasterType == 'CELL':
  1200. instr['discrete'] = 'y'
  1201. else:
  1202. instr['discrete'] = 'n'
  1203. else:
  1204. instr['rasterDefault'] = True
  1205. self.instruction.update(instr)
  1206. # add 'rect' in the end
  1207. return True
  1208. def EstimateHeight(self, raster, discrete, fontsize, cols = None, height = None):
  1209. """!Estimate height to draw raster legend"""
  1210. if discrete == 'n':
  1211. if height:
  1212. height = height
  1213. else:
  1214. height = self.unitConv.convert(value = fontsize * 10,
  1215. fromUnit = 'point', toUnit = 'inch')
  1216. if discrete == 'y':
  1217. if cols:
  1218. cols = cols
  1219. else:
  1220. cols = 1
  1221. rinfo = grass.raster_info(raster)
  1222. if rinfo['datatype'] in ('DCELL', 'FCELL'):
  1223. minim, maxim = rinfo['min'], rinfo['max']
  1224. rows = ceil(maxim / cols )
  1225. else:
  1226. cat = grass.read_command('r.category', map = raster,
  1227. fs = ':').strip().split('\n')
  1228. rows = ceil(float(len(cat)) / cols )
  1229. height = self.unitConv.convert(value = 1.5 * rows * fontsize, fromUnit = 'point', toUnit = 'inch')
  1230. return height
  1231. def EstimateWidth(self, raster, discrete, fontsize, cols = None, width = None, paperInstr = None):
  1232. """!Estimate size to draw raster legend"""
  1233. if discrete == 'n':
  1234. rinfo = grass.raster_info(raster)
  1235. minim, maxim = rinfo['min'], rinfo['max']
  1236. if width:
  1237. width = width
  1238. else:
  1239. width = self.unitConv.convert(value = fontsize * 2,
  1240. fromUnit = 'point', toUnit = 'inch')
  1241. text = len(max(str(minim), str(maxim), key = len))
  1242. textPart = self.unitConv.convert(value = text * fontsize / 2,
  1243. fromUnit = 'point', toUnit = 'inch')
  1244. width += textPart
  1245. elif discrete == 'y':
  1246. if cols:
  1247. cols = cols
  1248. else:
  1249. cols = 1
  1250. if width:
  1251. width = width
  1252. else:
  1253. paperWidth = paperInstr['Width'] - paperInstr['Right'] - paperInstr['Left']
  1254. width = (paperWidth / cols) * (cols - 1) + 1
  1255. return width
  1256. class VectorLegend(InstructionObject):
  1257. """!Class representing colortable instruction"""
  1258. def __init__(self, id):
  1259. InstructionObject.__init__(self, id = id)
  1260. self.type = 'vectorLegend'
  1261. # default values
  1262. self.defaultInstruction = dict(vLegend = False, unit = 'inch', where = (0, 0),
  1263. defaultSize = True, width = 0.4, cols = 1, span = None,
  1264. font = "Helvetica", fontsize = 10,
  1265. border = 'none')
  1266. # current values
  1267. self.instruction = dict(self.defaultInstruction)
  1268. def __str__(self):
  1269. instr = "vlegend\n"
  1270. instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1])
  1271. instr += string.Template(" font $font\n fontsize $fontsize\n").substitute(self.instruction)
  1272. instr += string.Template(" width $width\n cols $cols\n").substitute(self.instruction)
  1273. if self.instruction['span']:
  1274. instr += string.Template(" span $span\n").substitute(self.instruction)
  1275. instr += string.Template(" border $border\n").substitute(self.instruction)
  1276. instr += " end"
  1277. return instr
  1278. def Read(self, instruction, text, **kwargs):
  1279. """!Read instruction and save information"""
  1280. instr = {}
  1281. instr['vLegend'] = True
  1282. for line in text:
  1283. try:
  1284. if line.startswith('where'):
  1285. instr['where'] = map(float, line.split()[1:3])
  1286. elif line.startswith('font '):
  1287. instr['font'] = line.split()[1]
  1288. elif line.startswith('fontsize'):
  1289. instr['fontsize'] = float(line.split()[1])
  1290. elif line.startswith('width'):
  1291. instr['width'] = float(line.split()[1])
  1292. elif line.startswith('cols'):
  1293. instr['cols'] = int(line.split()[1])
  1294. elif line.startswith('span'):
  1295. instr['span'] = float(line.split()[1])
  1296. elif line.startswith('border'):
  1297. instr['border'] = line.split()[1]
  1298. except(IndexError, ValueError):
  1299. GError(_("Failed to read instruction %s") % instruction)
  1300. return False
  1301. self.instruction.update(instr)
  1302. return True
  1303. def EstimateSize(self, vectorInstr, fontsize, width = None, cols = None):
  1304. """!Estimate size to draw vector legend"""
  1305. if width:
  1306. width = width
  1307. else:
  1308. width = fontsize/24.0
  1309. if cols:
  1310. cols = cols
  1311. else:
  1312. cols = 1
  1313. vectors = vectorInstr['list']
  1314. labels = [vector[4] for vector in vectors if vector[3] != 0]
  1315. extent = (len(max(labels, key = len)) * fontsize / 2, fontsize)
  1316. wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'point', toUnit = 'inch')
  1317. hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'point', toUnit = 'inch')
  1318. w = (width + wExtent) * cols
  1319. h = len(labels) * hExtent / cols
  1320. h *= 1.1
  1321. return (w, h)
  1322. class Raster(InstructionObject):
  1323. """!Class representing raster instruction"""
  1324. def __init__(self, id):
  1325. InstructionObject.__init__(self, id = id)
  1326. self.type = 'raster'
  1327. # default values
  1328. self.defaultInstruction = dict(isRaster = False, raster = None)
  1329. # current values
  1330. self.instruction = dict(self.defaultInstruction)
  1331. def __str__(self):
  1332. instr = string.Template("raster $raster").substitute(self.instruction)
  1333. return instr
  1334. def Read(self, instruction, text):
  1335. """!Read instruction and save information"""
  1336. instr = {}
  1337. instr['isRaster'] = True
  1338. try:
  1339. map = text.split()[1]
  1340. except IndexError:
  1341. GError(_("Failed to read instruction %s") % instruction)
  1342. return False
  1343. try:
  1344. info = grass.find_file(map, element = 'cell')
  1345. except grass.ScriptError, e:
  1346. GError(message = e.value)
  1347. return False
  1348. instr['raster'] = info['fullname']
  1349. self.instruction.update(instr)
  1350. return True
  1351. class Vector(InstructionObject):
  1352. """!Class keeps vector layers"""
  1353. def __init__(self, id):
  1354. InstructionObject.__init__(self, id = id)
  1355. self.type = 'vector'
  1356. # default values
  1357. self.defaultInstruction = dict(list = None)# [vmap, type, id, lpos, label]
  1358. # current values
  1359. self.instruction = dict(self.defaultInstruction)
  1360. def __str__(self):
  1361. return ''
  1362. def Read(self, instruction, text, **kwargs):
  1363. """!Read instruction and save information"""
  1364. instr = {}
  1365. for line in text:
  1366. if line.startswith('vpoints') or line.startswith('vlines') or line.startswith('vareas'):
  1367. # subtype
  1368. if line.startswith('vpoints'):
  1369. subType = 'points'
  1370. elif line.startswith('vlines'):
  1371. subType = 'lines'
  1372. elif line.startswith('vareas'):
  1373. subType = 'areas'
  1374. # name of vector map
  1375. vmap = line.split()[1]
  1376. try:
  1377. info = grass.find_file(vmap, element = 'vector')
  1378. except grass.ScriptError, e:
  1379. GError(message = e.value)
  1380. return False
  1381. vmap = info['fullname']
  1382. # id
  1383. id = kwargs['id']
  1384. # lpos
  1385. lpos = kwargs['vectorMapNumber']
  1386. #label
  1387. label = '('.join(vmap.split('@')) + ')'
  1388. break
  1389. instr = [vmap, subType, id, lpos, label]
  1390. if not self.instruction['list']:
  1391. self.instruction['list'] = []
  1392. self.instruction['list'].append(instr)
  1393. return True
  1394. class VProperties(InstructionObject):
  1395. """!Class represents instructions vareas, vlines, vpoints"""
  1396. def __init__(self, id, subType):
  1397. InstructionObject.__init__(self, id = id)
  1398. self.type = 'vProperties'
  1399. self.subType = subType
  1400. # default values
  1401. if self.subType == 'points':
  1402. dd = dict(subType = 'points', name = None, type = 'point or centroid', connection = False, layer = '1',
  1403. masked = 'n', color = '0:0:0', width = 1,
  1404. fcolor = '255:0:0', rgbcolumn = None, symbol = os.path.join('basic', 'x'), eps = None,
  1405. size = 5, sizecolumn = None, scale = None,
  1406. rotation = False, rotate = 0, rotatecolumn = None, label = None, lpos = None)
  1407. elif self.subType == 'lines':
  1408. dd = dict(subType = 'lines', name = None, type = 'line or boundary', connection = False, layer = '1',
  1409. masked = 'n', color = '0:0:0', hwidth = 1,
  1410. hcolor = 'none', rgbcolumn = None,
  1411. width = 1, cwidth = None,
  1412. style = 'solid', linecap = 'butt', label = None, lpos = None)
  1413. else: # areas
  1414. dd = dict(subType = 'areas', name = None, connection = False, layer = '1',
  1415. masked = 'n', color = '0:0:0', width = 1,
  1416. fcolor = 'none', rgbcolumn = None,
  1417. pat = None, pwidth = 1, scale = 1, label = None, lpos = None)
  1418. self.defaultInstruction = dd
  1419. # current values
  1420. self.instruction = dict(self.defaultInstruction)
  1421. def __str__(self):
  1422. dic = self.instruction
  1423. vInstruction = string.Template("v$subType $name\n").substitute(dic)
  1424. #data selection
  1425. if self.subType in ('points', 'lines'):
  1426. vInstruction += string.Template(" type $type\n").substitute(dic)
  1427. if dic['connection']:
  1428. vInstruction += string.Template(" layer $layer\n").substitute(dic)
  1429. if dic.has_key('cats'):
  1430. vInstruction += string.Template(" cats $cats\n").substitute(dic)
  1431. elif dic.has_key('where'):
  1432. vInstruction += string.Template(" where $where\n").substitute(dic)
  1433. vInstruction += string.Template(" masked $masked\n").substitute(dic)
  1434. #colors
  1435. vInstruction += string.Template(" color $color\n").substitute(dic)
  1436. if self.subType in ('points', 'areas'):
  1437. if dic['color'] != 'none':
  1438. vInstruction += string.Template(" width $width\n").substitute(dic)
  1439. if dic['rgbcolumn']:
  1440. vInstruction += string.Template(" rgbcolumn $rgbcolumn\n").substitute(dic)
  1441. vInstruction += string.Template(" fcolor $fcolor\n").substitute(dic)
  1442. else:
  1443. if dic['rgbcolumn']:
  1444. vInstruction += string.Template(" rgbcolumn $rgbcolumn\n").substitute(dic)
  1445. elif dic['hcolor'] != 'none':
  1446. vInstruction += string.Template(" hwidth $hwidth\n").substitute(dic)
  1447. vInstruction += string.Template(" hcolor $hcolor\n").substitute(dic)
  1448. # size and style
  1449. if self.subType == 'points':
  1450. if dic['symbol']:
  1451. vInstruction += string.Template(" symbol $symbol\n").substitute(dic)
  1452. else: #eps
  1453. vInstruction += string.Template(" eps $eps\n").substitute(dic)
  1454. if dic['size']:
  1455. vInstruction += string.Template(" size $size\n").substitute(dic)
  1456. else: # sizecolumn
  1457. vInstruction += string.Template(" sizecolumn $sizecolumn\n").substitute(dic)
  1458. vInstruction += string.Template(" scale $scale\n").substitute(dic)
  1459. if dic['rotation']:
  1460. if dic['rotate'] is not None:
  1461. vInstruction += string.Template(" rotate $rotate\n").substitute(dic)
  1462. else:
  1463. vInstruction += string.Template(" rotatecolumn $rotatecolumn\n").substitute(dic)
  1464. if self.subType == 'areas':
  1465. if dic['pat'] is not None:
  1466. vInstruction += string.Template(" pat $pat\n").substitute(dic)
  1467. vInstruction += string.Template(" pwidth $pwidth\n").substitute(dic)
  1468. vInstruction += string.Template(" scale $scale\n").substitute(dic)
  1469. if self.subType == 'lines':
  1470. if dic['width'] is not None:
  1471. vInstruction += string.Template(" width $width\n").substitute(dic)
  1472. else:
  1473. vInstruction += string.Template(" cwidth $cwidth\n").substitute(dic)
  1474. vInstruction += string.Template(" style $style\n").substitute(dic)
  1475. vInstruction += string.Template(" linecap $linecap\n").substitute(dic)
  1476. #position and label in vlegend
  1477. vInstruction += string.Template(" label $label\n lpos $lpos\n").substitute(dic)
  1478. vInstruction += " end"
  1479. return vInstruction
  1480. def Read(self, instruction, text, **kwargs):
  1481. """!Read instruction and save information"""
  1482. instr = {}
  1483. try:
  1484. info = grass.find_file(name = text[0].split()[1], element = 'vector')
  1485. except grass.ScriptError, e:
  1486. GError(message = e.value)
  1487. return False
  1488. instr['name'] = info['fullname']
  1489. #connection
  1490. instr['connection'] = True
  1491. self.mapDBInfo = VectorDBInfo(instr['name'])
  1492. self.layers = self.mapDBInfo.layers.keys()
  1493. if not self.layers:
  1494. instr['connection'] = False
  1495. # points
  1496. if text[0].startswith('vpoints'):
  1497. for line in text[1:]:
  1498. if line.startswith('type'):
  1499. tp = []
  1500. if line.find('point') != -1:
  1501. tp.append('point')
  1502. if line.find('centroid') != -1:
  1503. tp.append('centroid')
  1504. instr['type'] = ' or '.join(tp)
  1505. elif line.startswith('fcolor'):
  1506. instr['fcolor'] = line.split()[1]
  1507. elif line.startswith('rgbcolumn'):
  1508. instr['rgbcolumn'] = line.split()[1]
  1509. elif line.startswith('symbol'):
  1510. instr['symbol'] = line.split()[1]
  1511. elif line.startswith('eps'):
  1512. instr['eps'] = line.split()[1]
  1513. elif line.startswith('size '):
  1514. instr['size'] = line.split()[1]
  1515. elif line.startswith('sizecolumn'):
  1516. instr['size'] = None
  1517. instr['sizecolumn'] = line.split()[1]
  1518. elif line.startswith('scale '):
  1519. instr['scale'] = float(line.split()[1])
  1520. elif line.startswith('rotate '):
  1521. instr['rotation'] = True
  1522. instr['rotate'] = line.split()[1]
  1523. elif line.startswith('rotatecolumn'):
  1524. instr['rotatecolumn'] = line.split()[1]
  1525. instr['rotation'] = True
  1526. instr['rotate'] = None
  1527. # lines
  1528. elif text[0].startswith('vlines'):
  1529. for line in text[1:]:
  1530. if line.startswith('type'):
  1531. tp = []
  1532. if line.find('line') != -1:
  1533. tp.append('line')
  1534. if line.find('boundary') != -1:
  1535. tp.append('boundary')
  1536. instr['type'] = ' or '.join(tp)
  1537. elif line.startswith('hwidth'):
  1538. instr['hwidth'] = float(line.split()[1])
  1539. elif line.startswith('hcolor'):
  1540. instr['hcolor'] = line.split()[1]
  1541. elif line.startswith('rgbcolumn'):
  1542. instr['rgbcolumn'] = line.split()[1]
  1543. elif line.startswith('cwidth'):
  1544. instr['cwidth'] = float(line.split()[1])
  1545. instr['width'] = None
  1546. elif line.startswith('style'):
  1547. instr['style'] = line.split()[1]
  1548. elif line.startswith('linecap'):
  1549. instr['linecap'] = line.split()[1]
  1550. elif text[0].startswith('vareas'):
  1551. for line in text[1:]:
  1552. if line.startswith('fcolor'):
  1553. instr['fcolor'] = line.split()[1]
  1554. elif line.startswith('pat'):
  1555. instr['pat'] = line.split()[1]
  1556. elif line.startswith('pwidth'):
  1557. instr['pwidth'] = float(line.split()[1])
  1558. elif line.startswith('scale'):
  1559. instr['scale'] = float(line.split()[1])
  1560. # same properties for all
  1561. for line in text[1:]:
  1562. if line.startswith('lpos'):
  1563. instr['lpos'] = int(line.split()[1])
  1564. elif line.startswith('label'):
  1565. instr['label'] = line.split(None, 1)[1]
  1566. elif line.startswith('layer'):
  1567. instr['layer'] = line.split()[1]
  1568. elif line.startswith('masked'):
  1569. if line.split()[1].lower() in ('y', 'yes'):
  1570. instr['masked'] = 'y'
  1571. else:
  1572. instr['masked'] = 'n'
  1573. elif line.startswith('color'):
  1574. instr['color'] = line.split()[1]
  1575. elif line.startswith('rgbcolumn'):
  1576. instr['rgbcolumn'] = line.split()[1]
  1577. elif line.startswith('width'):
  1578. instr['width'] = float(line.split()[1])
  1579. if 'label' not in instr:
  1580. instr['label'] = '('.join(instr['name'].split('@')) + ')'
  1581. if 'lpos' not in instr:
  1582. instr['lpos'] = kwargs['vectorMapNumber']
  1583. self.instruction.update(instr)
  1584. return True
  1585. class PsmapDialog(wx.Dialog):
  1586. def __init__(self, parent, id, title, settings, apply = True):
  1587. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY,
  1588. title = title, size = wx.DefaultSize,
  1589. style = wx.CAPTION|wx.MINIMIZE_BOX|wx.CLOSE_BOX)
  1590. self.apply = apply
  1591. self.id = id
  1592. self.parent = parent
  1593. self.instruction = settings
  1594. self.objectType = None
  1595. self.unitConv = UnitConversion(self)
  1596. self.spinCtrlSize = (65, -1)
  1597. self.Bind(wx.EVT_CLOSE, self.OnClose)
  1598. def AddUnits(self, parent, dialogDict):
  1599. parent.units = dict()
  1600. parent.units['unitsLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Units:"))
  1601. choices = self.unitConv.getPageUnitsNames()
  1602. parent.units['unitsCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = choices)
  1603. parent.units['unitsCtrl'].SetStringSelection(self.unitConv.findName(dialogDict['unit']))
  1604. def AddPosition(self, parent, dialogDict):
  1605. if not hasattr(parent, "position"):
  1606. parent.position = dict()
  1607. parent.position['comment'] = wx.StaticText(parent, id = wx.ID_ANY,\
  1608. label = _("Position of the top left corner\nfrom the top left edge of the paper"))
  1609. parent.position['xLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("X:"))
  1610. parent.position['yLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Y:"))
  1611. parent.position['xCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][0]), validator = TCValidator(flag = 'DIGIT_ONLY'))
  1612. parent.position['yCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][1]), validator = TCValidator(flag = 'DIGIT_ONLY'))
  1613. if dialogDict.has_key('unit'):
  1614. x = self.unitConv.convert(value = dialogDict['where'][0], fromUnit = 'inch', toUnit = dialogDict['unit'])
  1615. y = self.unitConv.convert(value = dialogDict['where'][1], fromUnit = 'inch', toUnit = dialogDict['unit'])
  1616. parent.position['xCtrl'].SetValue("%5.3f" % x)
  1617. parent.position['yCtrl'].SetValue("%5.3f" % y)
  1618. def AddExtendedPosition(self, panel, gridBagSizer, dialogDict):
  1619. """!Add widgets for setting position relative to paper and to map"""
  1620. panel.position = dict()
  1621. positionLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Position is given:"))
  1622. panel.position['toPaper'] = wx.RadioButton(panel, id = wx.ID_ANY, label = _("relatively to paper"), style = wx.RB_GROUP)
  1623. panel.position['toMap'] = wx.RadioButton(panel, id = wx.ID_ANY, label = _("by map coordinates"))
  1624. panel.position['toPaper'].SetValue(dialogDict['XY'])
  1625. panel.position['toMap'].SetValue(not dialogDict['XY'])
  1626. gridBagSizer.Add(positionLabel, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  1627. gridBagSizer.Add(panel.position['toPaper'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  1628. gridBagSizer.Add(panel.position['toMap'], pos = (1,1),flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  1629. # first box - paper coordinates
  1630. box1 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
  1631. sizerP = wx.StaticBoxSizer(box1, wx.VERTICAL)
  1632. self.gridBagSizerP = wx.GridBagSizer (hgap = 5, vgap = 5)
  1633. self.gridBagSizerP.AddGrowableCol(1)
  1634. self.gridBagSizerP.AddGrowableRow(3)
  1635. self.AddPosition(parent = panel, dialogDict = dialogDict)
  1636. panel.position['comment'].SetLabel(_("Position from the top left\nedge of the paper"))
  1637. self.AddUnits(parent = panel, dialogDict = dialogDict)
  1638. self.gridBagSizerP.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1639. self.gridBagSizerP.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1640. self.gridBagSizerP.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1641. self.gridBagSizerP.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1642. self.gridBagSizerP.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1643. self.gridBagSizerP.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1644. self.gridBagSizerP.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag = wx.ALIGN_BOTTOM, border = 0)
  1645. sizerP.Add(self.gridBagSizerP, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  1646. gridBagSizer.Add(sizerP, pos = (2,0),span = (1,1), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
  1647. # second box - map coordinates
  1648. box2 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
  1649. sizerM = wx.StaticBoxSizer(box2, wx.VERTICAL)
  1650. self.gridBagSizerM = wx.GridBagSizer (hgap = 5, vgap = 5)
  1651. self.gridBagSizerM.AddGrowableCol(0)
  1652. self.gridBagSizerM.AddGrowableCol(1)
  1653. eastingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "E:")
  1654. northingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "N:")
  1655. panel.position['eCtrl'] = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  1656. panel.position['nCtrl'] = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  1657. east, north = PaperMapCoordinates(map = self.instruction[self.mapId], x = dialogDict['where'][0], y = dialogDict['where'][1], paperToMap = True)
  1658. panel.position['eCtrl'].SetValue(str(east))
  1659. panel.position['nCtrl'].SetValue(str(north))
  1660. self.gridBagSizerM.Add(eastingLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1661. self.gridBagSizerM.Add(northingLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1662. self.gridBagSizerM.Add(panel.position['eCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1663. self.gridBagSizerM.Add(panel.position['nCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  1664. sizerM.Add(self.gridBagSizerM, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  1665. gridBagSizer.Add(sizerM, pos = (2,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
  1666. def AddFont(self, parent, dialogDict, color = True):
  1667. parent.font = dict()
  1668. ## parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose font:"))
  1669. ## parent.font['fontCtrl'] = wx.FontPickerCtrl(parent, id = wx.ID_ANY)
  1670. ##
  1671. ## parent.font['fontCtrl'].SetSelectedFont(
  1672. ## wx.FontFromNativeInfoString(dialogDict['font'] + " " + str(dialogDict['fontsize'])))
  1673. ## parent.font['fontCtrl'].SetMaxPointSize(50)
  1674. ##
  1675. ## if color:
  1676. ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:"))
  1677. ## parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY, style=wx.FNTP_FONTDESC_AS_LABEL)
  1678. ## parent.font['colorCtrl'].SetColour(dialogDict['color'])
  1679. ## parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color']))
  1680. parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font:"))
  1681. parent.font['fontSizeLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font size:"))
  1682. fontChoices = [ 'Times-Roman', 'Times-Italic', 'Times-Bold', 'Times-BoldItalic', 'Helvetica',\
  1683. 'Helvetica-Oblique', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Courier',\
  1684. 'Courier-Oblique', 'Courier-Bold', 'Courier-BoldOblique']
  1685. parent.font['fontCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = fontChoices)
  1686. if dialogDict['font'] in fontChoices:
  1687. parent.font['fontCtrl'].SetStringSelection(dialogDict['font'])
  1688. else:
  1689. parent.font['fontCtrl'].SetStringSelection('Helvetica')
  1690. parent.font['fontSizeCtrl'] = wx.SpinCtrl(parent, id = wx.ID_ANY, min = 4, max = 50, initial = 10)
  1691. parent.font['fontSizeCtrl'].SetValue(dialogDict['fontsize'])
  1692. if color:
  1693. parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:"))
  1694. parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY)
  1695. parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color']))
  1696. ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Color:"))
  1697. ## colorChoices = [ 'aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'green', 'indigo', 'magenta',\
  1698. ## 'orange', 'purple', 'red', 'violet', 'white', 'yellow']
  1699. ## parent.colorCtrl = wx.Choice(parent, id = wx.ID_ANY, choices = colorChoices)
  1700. ## parent.colorCtrl.SetStringSelection(parent.rLegendDict['color'])
  1701. ## parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY)
  1702. ## parent.font['colorCtrl'].SetColour(dialogDict['color'])
  1703. def OnApply(self, event):
  1704. ok = self.update()
  1705. if ok:
  1706. self.parent.DialogDataChanged(id = self.id)
  1707. return True
  1708. else:
  1709. return False
  1710. def OnOK(self, event):
  1711. """!Apply changes, close dialog"""
  1712. ok = self.OnApply(event)
  1713. if ok:
  1714. self.Close()
  1715. def OnCancel(self, event):
  1716. """!Close dialog"""
  1717. self.Close()
  1718. def OnClose(self, event):
  1719. """!Destroy dialog and delete it from open dialogs"""
  1720. if self.objectType:
  1721. for each in self.objectType:
  1722. if each in self.parent.openDialogs:
  1723. del self.parent.openDialogs[each]
  1724. event.Skip()
  1725. self.Destroy()
  1726. def _layout(self, panel):
  1727. #buttons
  1728. btnCancel = wx.Button(self, wx.ID_CANCEL)
  1729. btnOK = wx.Button(self, wx.ID_OK)
  1730. btnOK.SetDefault()
  1731. if self.apply:
  1732. btnApply = wx.Button(self, wx.ID_APPLY)
  1733. # bindigs
  1734. btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
  1735. btnOK.SetToolTipString(_("Close dialog and apply changes"))
  1736. #btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1737. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1738. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1739. if self.apply:
  1740. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1741. btnApply.SetToolTipString(_("Apply changes"))
  1742. # sizers
  1743. btnSizer = wx.StdDialogButtonSizer()
  1744. btnSizer.AddButton(btnCancel)
  1745. if self.apply:
  1746. btnSizer.AddButton(btnApply)
  1747. btnSizer.AddButton(btnOK)
  1748. btnSizer.Realize()
  1749. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1750. mainSizer.Add(item = panel, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  1751. mainSizer.Add(item = btnSizer, proportion = 0,
  1752. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  1753. self.SetSizer(mainSizer)
  1754. mainSizer.Layout()
  1755. mainSizer.Fit(self)
  1756. class PageSetupDialog(PsmapDialog):
  1757. def __init__(self, parent, id, settings):
  1758. PsmapDialog.__init__(self, parent = parent, id = id, title = "Page setup", settings = settings)
  1759. self.cat = ['Units', 'Format', 'Orientation', 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom']
  1760. labels = [_('Units'), _('Format'), _('Orientation'), _('Width'), _('Height'),
  1761. _('Left'), _('Right'), _('Top'), _('Bottom')]
  1762. self.catsLabels = dict(zip(self.cat, labels))
  1763. paperString = RunCommand('ps.map', flags = 'p', read = True, quiet = True)
  1764. self.paperTable = self._toList(paperString)
  1765. self.unitsList = self.unitConv.getPageUnitsNames()
  1766. self.pageSetupDict = settings[id].GetInstruction()
  1767. self._layout()
  1768. if self.pageSetupDict:
  1769. self.getCtrl('Units').SetStringSelection(self.unitConv.findName(self.pageSetupDict['Units']))
  1770. if self.pageSetupDict['Format'] == 'custom':
  1771. self.getCtrl('Format').SetSelection(self.getCtrl('Format').GetCount() - 1)
  1772. else:
  1773. self.getCtrl('Format').SetStringSelection(self.pageSetupDict['Format'])
  1774. if self.pageSetupDict['Orientation'] == 'Portrait':
  1775. self.getCtrl('Orientation').SetSelection(0)
  1776. else:
  1777. self.getCtrl('Orientation').SetSelection(1)
  1778. for item in self.cat[3:]:
  1779. val = self.unitConv.convert(value = self.pageSetupDict[item],
  1780. fromUnit = 'inch', toUnit = self.pageSetupDict['Units'])
  1781. self.getCtrl(item).SetValue("%4.3f" % val)
  1782. if self.getCtrl('Format').GetSelection() != self.getCtrl('Format').GetCount() - 1: # custom
  1783. self.getCtrl('Width').Disable()
  1784. self.getCtrl('Height').Disable()
  1785. else:
  1786. self.getCtrl('Orientation').Disable()
  1787. # events
  1788. self.getCtrl('Units').Bind(wx.EVT_CHOICE, self.OnChoice)
  1789. self.getCtrl('Format').Bind(wx.EVT_CHOICE, self.OnChoice)
  1790. self.getCtrl('Orientation').Bind(wx.EVT_CHOICE, self.OnChoice)
  1791. self.btnOk.Bind(wx.EVT_BUTTON, self.OnOK)
  1792. def update(self):
  1793. self.pageSetupDict['Units'] = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection())
  1794. self.pageSetupDict['Format'] = self.paperTable[self.getCtrl('Format').GetSelection()]['Format']
  1795. if self.getCtrl('Orientation').GetSelection() == 0:
  1796. self.pageSetupDict['Orientation'] = 'Portrait'
  1797. else:
  1798. self.pageSetupDict['Orientation'] = 'Landscape'
  1799. for item in self.cat[3:]:
  1800. self.pageSetupDict[item] = self.unitConv.convert(value = float(self.getCtrl(item).GetValue()),
  1801. fromUnit = self.pageSetupDict['Units'], toUnit = 'inch')
  1802. def OnOK(self, event):
  1803. try:
  1804. self.update()
  1805. except ValueError:
  1806. wx.MessageBox(message = _("Literal is not allowed!"), caption = _('Invalid input'),
  1807. style = wx.OK|wx.ICON_ERROR)
  1808. else:
  1809. event.Skip()
  1810. def _layout(self):
  1811. size = (110,-1)
  1812. #sizers
  1813. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1814. pageBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Page size"))
  1815. pageSizer = wx.StaticBoxSizer(pageBox, wx.VERTICAL)
  1816. marginBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Margins"))
  1817. marginSizer = wx.StaticBoxSizer(marginBox, wx.VERTICAL)
  1818. horSizer = wx.BoxSizer(wx.HORIZONTAL)
  1819. #staticText + choice
  1820. choices = [self.unitsList, [item['Format'] for item in self.paperTable], [_('Portrait'), _('Landscape')]]
  1821. propor = [0,1,1]
  1822. border = [5,3,3]
  1823. self.hBoxDict={}
  1824. for i, item in enumerate(self.cat[:3]):
  1825. hBox = wx.BoxSizer(wx.HORIZONTAL)
  1826. stText = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':')
  1827. choice = wx.Choice(self, id = wx.ID_ANY, choices = choices[i], size = size)
  1828. hBox.Add(stText, proportion = propor[i], flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = border[i])
  1829. hBox.Add(choice, proportion = 0, flag = wx.ALL, border = border[i])
  1830. if item == 'Units':
  1831. hBox.Add(size,1)
  1832. self.hBoxDict[item] = hBox
  1833. #staticText + TextCtrl
  1834. for item in self.cat[3:]:
  1835. hBox = wx.BoxSizer(wx.HORIZONTAL)
  1836. label = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':')
  1837. textctrl = wx.TextCtrl(self, id = wx.ID_ANY, size = size, value = '')
  1838. hBox.Add(label, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 3)
  1839. hBox.Add(textctrl, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 3)
  1840. self.hBoxDict[item] = hBox
  1841. sizer = list([mainSizer] + [pageSizer]*4 + [marginSizer]*4)
  1842. for i, item in enumerate(self.cat):
  1843. sizer[i].Add(self.hBoxDict[item], 0, wx.GROW|wx.RIGHT|wx.LEFT,5)
  1844. # OK button
  1845. btnSizer = wx.StdDialogButtonSizer()
  1846. self.btnOk = wx.Button(self, wx.ID_OK)
  1847. self.btnOk.SetDefault()
  1848. btnSizer.AddButton(self.btnOk)
  1849. btn = wx.Button(self, wx.ID_CANCEL)
  1850. btnSizer.AddButton(btn)
  1851. btnSizer.Realize()
  1852. horSizer.Add(pageSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM, border = 10)
  1853. horSizer.Add(marginSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border = 10)
  1854. mainSizer.Add(horSizer, proportion = 0, border = 10)
  1855. mainSizer.Add(btnSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT|wx.ALL, border = 10)
  1856. self.SetSizer(mainSizer)
  1857. mainSizer.Fit(self)
  1858. def OnChoice(self, event):
  1859. currPaper = self.paperTable[self.getCtrl('Format').GetSelection()]
  1860. currUnit = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection())
  1861. currOrientIdx = self.getCtrl('Orientation').GetSelection()
  1862. newSize = dict()
  1863. for item in self.cat[3:]:
  1864. newSize[item] = self.unitConv.convert(float(currPaper[item]), fromUnit = 'inch', toUnit = currUnit)
  1865. enable = True
  1866. if currPaper['Format'] != _('custom'):
  1867. if currOrientIdx == 1: # portrait
  1868. newSize['Width'], newSize['Height'] = newSize['Height'], newSize['Width']
  1869. for item in self.cat[3:]:
  1870. self.getCtrl(item).ChangeValue("%4.3f" % newSize[item])
  1871. enable = False
  1872. self.getCtrl('Width').Enable(enable)
  1873. self.getCtrl('Height').Enable(enable)
  1874. self.getCtrl('Orientation').Enable(not enable)
  1875. def getCtrl(self, item):
  1876. return self.hBoxDict[item].GetItem(1).GetWindow()
  1877. def _toList(self, paperStr):
  1878. sizeList = list()
  1879. for line in paperStr.strip().split('\n'):
  1880. d = dict(zip([self.cat[1]]+ self.cat[3:],line.split()))
  1881. sizeList.append(d)
  1882. d = {}.fromkeys([self.cat[1]]+ self.cat[3:], 100)
  1883. d.update(Format = _('custom'))
  1884. sizeList.append(d)
  1885. return sizeList
  1886. class MapDialog(PsmapDialog):
  1887. """!Dialog for map frame settings and optionally raster and vector map selection"""
  1888. def __init__(self, parent, id, settings, rect = None, notebook = False):
  1889. PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings)
  1890. self.isNotebook = notebook
  1891. if self.isNotebook:
  1892. self.objectType = ('mapNotebook',)
  1893. else:
  1894. self.objectType = ('map',)
  1895. #notebook
  1896. if self.isNotebook:
  1897. self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  1898. self.mPanel = MapFramePanel(parent = self.notebook, id = self.id[0], settings = self.instruction,
  1899. rect = rect, notebook = True)
  1900. self.id[0] = self.mPanel.getId()
  1901. self.rPanel = RasterPanel(parent = self.notebook, id = self.id[1], settings = self.instruction,
  1902. notebook = True)
  1903. self.id[1] = self.rPanel.getId()
  1904. self.vPanel = VectorPanel(parent = self.notebook, id = self.id[2], settings = self.instruction,
  1905. notebook = True)
  1906. self.id[2] = self.vPanel.getId()
  1907. self._layout(self.notebook)
  1908. self.SetTitle(_("Map settings"))
  1909. else:
  1910. self.mPanel = MapFramePanel(parent = self, id = self.id[0], settings = self.instruction,
  1911. rect = rect, notebook = False)
  1912. self.id[0] = self.mPanel.getId()
  1913. self._layout(self.mPanel)
  1914. self.SetTitle(_("Map frame settings"))
  1915. def OnApply(self, event):
  1916. """!Apply changes"""
  1917. if self.isNotebook:
  1918. okV = self.vPanel.update()
  1919. okR = self.rPanel.update()
  1920. if okV and self.id[2] in self.instruction:
  1921. self.parent.DialogDataChanged(id = self.id[2])
  1922. if okR and self.id[1] in self.instruction:
  1923. self.parent.DialogDataChanged(id = self.id[1])
  1924. if not okR or not okV:
  1925. return False
  1926. ok = self.mPanel.update()
  1927. if ok:
  1928. self.parent.DialogDataChanged(id = self.id[0])
  1929. return True
  1930. return False
  1931. def OnCancel(self, event):
  1932. """!Close dialog and remove tmp red box"""
  1933. self.parent.canvas.pdcTmp.RemoveId(self.parent.canvas.idZoomBoxTmp)
  1934. self.parent.canvas.Refresh()
  1935. self.Close()
  1936. def updateDialog(self):
  1937. """!Update raster and vector information"""
  1938. if self.mPanel.scaleChoice.GetSelection() == 0:
  1939. if self.mPanel.rasterTypeRadio.GetValue():
  1940. if 'raster' in self.parent.openDialogs:
  1941. if self.parent.openDialogs['raster'].rPanel.rasterYesRadio.GetValue() and \
  1942. self.parent.openDialogs['raster'].rPanel.rasterSelect.GetValue() == self.mPanel.select.GetValue():
  1943. self.mPanel.drawMap.SetValue(True)
  1944. else:
  1945. self.mPanel.drawMap.SetValue(False)
  1946. else:
  1947. if 'vector' in self.parent.openDialogs:
  1948. found = False
  1949. for each in self.parent.openDialogs['vector'].vPanel.vectorList:
  1950. if each[0] == self.mPanel.select.GetValue():
  1951. found = True
  1952. self.mPanel.drawMap.SetValue(found)
  1953. class MapFramePanel(wx.Panel):
  1954. """!wx.Panel with map (scale, region, border) settings"""
  1955. def __init__(self, parent, id, settings, rect, notebook = True):
  1956. wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  1957. self.id = id
  1958. self.instruction = settings
  1959. if notebook:
  1960. self.book = parent
  1961. self.book.AddPage(page = self, text = _("Map frame"))
  1962. self.mapDialog = self.book.GetParent()
  1963. else:
  1964. self.mapDialog = parent
  1965. if self.id is not None:
  1966. self.mapFrameDict = self.instruction[self.id].GetInstruction()
  1967. else:
  1968. self.id = wx.NewId()
  1969. mapFrame = MapFrame(self.id)
  1970. self.mapFrameDict = mapFrame.GetInstruction()
  1971. self.mapFrameDict['rect'] = rect
  1972. self._layout()
  1973. self.scale = [None]*4
  1974. self.center = [None]*4
  1975. self.selectedMap = self.mapFrameDict['map']
  1976. self.selectedRegion = self.mapFrameDict['region']
  1977. self.scaleType = self.mapFrameDict['scaleType']
  1978. self.mapType = self.mapFrameDict['mapType']
  1979. self.scaleChoice.SetSelection(self.mapFrameDict['scaleType'])
  1980. if self.instruction[self.id]:
  1981. self.drawMap.SetValue(self.mapFrameDict['drawMap'])
  1982. else:
  1983. self.drawMap.SetValue(True)
  1984. if self.mapFrameDict['scaleType'] == 0 and self.mapFrameDict['map']:
  1985. self.select.SetValue(self.mapFrameDict['map'])
  1986. if self.mapFrameDict['mapType'] == 'raster':
  1987. self.rasterTypeRadio.SetValue(True)
  1988. self.vectorTypeRadio.SetValue(False)
  1989. else:
  1990. self.rasterTypeRadio.SetValue(False)
  1991. self.vectorTypeRadio.SetValue(True)
  1992. elif self.mapFrameDict['scaleType'] == 1 and self.mapFrameDict['region']:
  1993. self.select.SetValue(self.mapFrameDict['region'])
  1994. self.OnMap(None)
  1995. self.scale[self.mapFrameDict['scaleType']] = self.mapFrameDict['scale']
  1996. self.center[self.mapFrameDict['scaleType']] = self.mapFrameDict['center']
  1997. self.OnScaleChoice(None)
  1998. self.OnElementType(None)
  1999. self.OnBorder(None)
  2000. def _layout(self):
  2001. """!Do layout"""
  2002. border = wx.BoxSizer(wx.VERTICAL)
  2003. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map frame"))
  2004. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2005. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2006. #scale options
  2007. frameText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map frame options:"))
  2008. scaleChoices = [_("fit frame to match selected map"),
  2009. _("fit frame to match saved region"),
  2010. _("fit frame to match current computational region"),
  2011. _("fixed scale and map center")]
  2012. self.scaleChoice = wx.Choice(self, id = wx.ID_ANY, choices = scaleChoices)
  2013. gridBagSizer.Add(frameText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2014. gridBagSizer.Add(self.scaleChoice, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2015. #map and region selection
  2016. self.staticBox = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map selection"))
  2017. sizerM = wx.StaticBoxSizer(self.staticBox, wx.HORIZONTAL)
  2018. self.mapSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2019. self.rasterTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("raster"), style = wx.RB_GROUP)
  2020. self.vectorTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("vector"))
  2021. self.drawMap = wx.CheckBox(self, id = wx.ID_ANY, label = "add selected map")
  2022. self.mapOrRegionText = [_("Map:"), _("Region:")]
  2023. dc = wx.PaintDC(self)# determine size of labels
  2024. width = max(dc.GetTextExtent(self.mapOrRegionText[0])[0], dc.GetTextExtent(self.mapOrRegionText[1])[0])
  2025. self.mapText = wx.StaticText(self, id = wx.ID_ANY, label = self.mapOrRegionText[0], size = (width, -1))
  2026. self.select = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  2027. type = 'raster', multiple = False,
  2028. updateOnPopup = True, onPopup = None)
  2029. self.mapSizer.Add(self.rasterTypeRadio, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2030. self.mapSizer.Add(self.vectorTypeRadio, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2031. self.mapSizer.Add(self.drawMap, pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2032. self.mapSizer.Add(self.mapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2033. self.mapSizer.Add(self.select, pos = (1, 1), span = (1, 3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2034. sizerM.Add(self.mapSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2035. gridBagSizer.Add(sizerM, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2036. #map scale and center
  2037. boxC = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map scale and center"))
  2038. sizerC = wx.StaticBoxSizer(boxC, wx.HORIZONTAL)
  2039. self.centerSizer = wx.FlexGridSizer(rows = 2, cols = 5, hgap = 5, vgap = 5)
  2040. centerText = wx.StaticText(self, id = wx.ID_ANY, label = _("Center:"))
  2041. self.eastingText = wx.StaticText(self, id = wx.ID_ANY, label = _("E:"))
  2042. self.northingText = wx.StaticText(self, id = wx.ID_ANY, label = _("N:"))
  2043. self.eastingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY'))
  2044. self.northingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY'))
  2045. scaleText = wx.StaticText(self, id = wx.ID_ANY, label = _("Scale:"))
  2046. scalePrefixText = wx.StaticText(self, id = wx.ID_ANY, label = _("1 :"))
  2047. self.scaleTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, value = "", style = wx.TE_RIGHT, validator = TCValidator('DIGIT_ONLY'))
  2048. self.centerSizer.Add(centerText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10)
  2049. self.centerSizer.Add(self.eastingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2050. self.centerSizer.Add(self.eastingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2051. self.centerSizer.Add(self.northingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2052. self.centerSizer.Add(self.northingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2053. self.centerSizer.Add(scaleText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10)
  2054. self.centerSizer.Add(scalePrefixText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  2055. self.centerSizer.Add(self.scaleTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2056. sizerC.Add(self.centerSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2057. gridBagSizer.Add(sizerC, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2058. #resolution
  2059. flexSizer = wx.FlexGridSizer(rows = 1, cols = 2, hgap = 5, vgap = 5)
  2060. resolutionText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map max resolution (dpi):"))
  2061. self.resolutionSpin = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 1000, initial = 300)
  2062. flexSizer.Add(resolutionText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2063. flexSizer.Add(self.resolutionSpin, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2064. self.resolutionSpin.SetValue(self.mapFrameDict['resolution'])
  2065. gridBagSizer.Add(flexSizer, pos = (4, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2066. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2067. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2068. # border
  2069. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Border"))
  2070. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2071. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2072. self.borderCheck = wx.CheckBox(self, id = wx.ID_ANY, label = (_("draw border around map frame")))
  2073. if self.mapFrameDict['border'] == 'y':
  2074. self.borderCheck.SetValue(True)
  2075. else:
  2076. self.borderCheck.SetValue(False)
  2077. self.borderColorText = wx.StaticText(self, id = wx.ID_ANY, label = _("border color:"))
  2078. self.borderWidthText = wx.StaticText(self, id = wx.ID_ANY, label = _("border width (pts):"))
  2079. self.borderColourPicker = wx.ColourPickerCtrl(self, id = wx.ID_ANY)
  2080. self.borderWidthCtrl = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 100, initial = 1)
  2081. if self.mapFrameDict['border'] == 'y':
  2082. self.borderWidthCtrl.SetValue(int(self.mapFrameDict['width']))
  2083. self.borderColourPicker.SetColour(convertRGB(self.mapFrameDict['color']))
  2084. gridBagSizer.Add(self.borderCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2085. gridBagSizer.Add(self.borderColorText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2086. gridBagSizer.Add(self.borderWidthText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2087. gridBagSizer.Add(self.borderColourPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2088. gridBagSizer.Add(self.borderWidthCtrl, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2089. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2090. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2091. self.SetSizer(border)
  2092. self.Fit()
  2093. if projInfo()['proj'] == 'll':
  2094. self.scaleChoice.SetItems(self.scaleChoice.GetItems()[0:3])
  2095. boxC.Hide()
  2096. for each in self.centerSizer.GetChildren():
  2097. each.GetWindow().Hide()
  2098. # bindings
  2099. self.scaleChoice.Bind(wx.EVT_CHOICE, self.OnScaleChoice)
  2100. self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnMap)
  2101. self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.vectorTypeRadio)
  2102. self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.rasterTypeRadio)
  2103. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck)
  2104. def OnMap(self, event):
  2105. """!Selected map or region changing"""
  2106. if self.select.GetValue():
  2107. self.selected = self.select.GetValue()
  2108. else:
  2109. self.selected = None
  2110. if self.scaleChoice.GetSelection() == 0:
  2111. self.selectedMap = self.selected
  2112. if self.rasterTypeRadio.GetValue():
  2113. mapType = 'raster'
  2114. else:
  2115. mapType = 'vector'
  2116. self.scale[0], self.center[0], foo = AutoAdjust(self, scaleType = 0, map = self.selected,
  2117. mapType = mapType, rect = self.mapFrameDict['rect'])
  2118. #self.center[0] = self.RegionCenter(self.RegionDict(scaleType = 0))
  2119. elif self.scaleChoice.GetSelection() == 1:
  2120. self.selectedRegion = self.selected
  2121. self.scale[1], self.center[1], foo = AutoAdjust(self, scaleType = 1, region = self.selected, rect = self.mapFrameDict['rect'])
  2122. #self.center[1] = self.RegionCenter(self.RegionDict(scaleType = 1))
  2123. elif self.scaleChoice.GetSelection() == 2:
  2124. self.scale[2], self.center[2], foo = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect'])
  2125. #self.center[2] = self.RegionCenter(self.RegionDict(scaleType = 2))
  2126. else:
  2127. self.scale[3] = None
  2128. self.center[3] = None
  2129. self.OnScaleChoice(None)
  2130. def OnScaleChoice(self, event):
  2131. """!Selected scale type changing"""
  2132. scaleType = self.scaleChoice.GetSelection()
  2133. if self.scaleType != scaleType:
  2134. self.scaleType = scaleType
  2135. self.select.SetValue("")
  2136. if scaleType in (0, 1): # automatic - region from raster map, saved region
  2137. if scaleType == 0:
  2138. # set map selection
  2139. self.rasterTypeRadio.Show()
  2140. self.vectorTypeRadio.Show()
  2141. self.drawMap.Show()
  2142. self.staticBox.SetLabel(" %s " % _("Map selection"))
  2143. if self.rasterTypeRadio.GetValue():
  2144. stype = 'raster'
  2145. else:
  2146. stype = 'vector'
  2147. self.select.SetElementList(type = stype)
  2148. self.mapText.SetLabel(self.mapOrRegionText[0])
  2149. self.select.SetToolTipString(_("Region is set to match this map,\nraster or vector map must be added later"))
  2150. if scaleType == 1:
  2151. # set region selection
  2152. self.rasterTypeRadio.Hide()
  2153. self.vectorTypeRadio.Hide()
  2154. self.drawMap.Hide()
  2155. self.staticBox.SetLabel(" %s " % _("Region selection"))
  2156. stype = 'region'
  2157. self.select.SetElementList(type = stype)
  2158. self.mapText.SetLabel(self.mapOrRegionText[1])
  2159. self.select.SetToolTipString("")
  2160. for each in self.mapSizer.GetChildren():
  2161. each.GetWindow().Enable()
  2162. for each in self.centerSizer.GetChildren():
  2163. each.GetWindow().Disable()
  2164. if self.scale[scaleType]:
  2165. self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
  2166. if self.center[scaleType]:
  2167. self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
  2168. self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
  2169. elif scaleType == 2:
  2170. for each in self.mapSizer.GetChildren():
  2171. each.GetWindow().Disable()
  2172. for each in self.centerSizer.GetChildren():
  2173. each.GetWindow().Disable()
  2174. if self.scale[scaleType]:
  2175. self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
  2176. if self.center[scaleType]:
  2177. self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
  2178. self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
  2179. else: # fixed
  2180. for each in self.mapSizer.GetChildren():
  2181. each.GetWindow().Disable()
  2182. for each in self.centerSizer.GetChildren():
  2183. each.GetWindow().Enable()
  2184. if self.scale[scaleType]:
  2185. self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType]))
  2186. if self.center[scaleType]:
  2187. self.eastingTextCtrl.SetValue(str(self.center[scaleType][0]))
  2188. self.northingTextCtrl.SetValue(str(self.center[scaleType][1]))
  2189. def OnElementType(self, event):
  2190. """!Changes data in map selection tree ctrl popup"""
  2191. if self.rasterTypeRadio.GetValue():
  2192. mapType = 'raster'
  2193. else:
  2194. mapType = 'vector'
  2195. self.select.SetElementList(type = mapType)
  2196. if self.mapType != mapType and event is not None:
  2197. self.mapType = mapType
  2198. self.select.SetValue('')
  2199. self.mapType = mapType
  2200. def OnBorder(self, event):
  2201. """!Enables/disable the part relating to border of map frame"""
  2202. for each in (self.borderColorText, self.borderWidthText, self.borderColourPicker, self.borderWidthCtrl):
  2203. each.Enable(self.borderCheck.GetValue())
  2204. def getId(self):
  2205. """!Returns id of raster map"""
  2206. return self.id
  2207. def update(self):
  2208. """!Save changes"""
  2209. mapFrameDict = dict(self.mapFrameDict)
  2210. # resolution
  2211. mapFrameDict['resolution'] = self.resolutionSpin.GetValue()
  2212. #scale
  2213. scaleType = self.scaleType
  2214. mapFrameDict['scaleType'] = scaleType
  2215. if mapFrameDict['scaleType'] == 0:
  2216. if self.select.GetValue():
  2217. mapFrameDict['drawMap'] = self.drawMap.GetValue()
  2218. mapFrameDict['map'] = self.select.GetValue()
  2219. mapFrameDict['mapType'] = self.mapType
  2220. mapFrameDict['region'] = None
  2221. if mapFrameDict['drawMap']:
  2222. if mapFrameDict['mapType'] == 'raster':
  2223. mapFile = grass.find_file(mapFrameDict['map'], element = 'cell')
  2224. if mapFile['file'] == '':
  2225. GMessage("Raster %s not found" % mapFrameDict['map'])
  2226. return False
  2227. raster = self.instruction.FindInstructionByType('raster')
  2228. if raster:
  2229. raster['raster'] = mapFrameDict['map']
  2230. else:
  2231. raster = Raster(wx.NewId())
  2232. raster['raster'] = mapFrameDict['map']
  2233. raster['isRaster'] = True
  2234. self.instruction.AddInstruction(raster)
  2235. elif mapFrameDict['mapType'] == 'vector':
  2236. mapFile = grass.find_file(mapFrameDict['map'], element = 'vector')
  2237. if mapFile['file'] == '':
  2238. GMessage("Vector %s not found" % mapFrameDict['map'])
  2239. return False
  2240. vector = self.instruction.FindInstructionByType('vector')
  2241. isAdded = False
  2242. if vector:
  2243. for each in vector['list']:
  2244. if each[0] == mapFrameDict['map']:
  2245. isAdded = True
  2246. if not isAdded:
  2247. topoInfo = grass.vector_info_topo(map = mapFrameDict['map'])
  2248. if topoInfo:
  2249. if bool(topoInfo['areas']):
  2250. topoType = 'areas'
  2251. elif bool(topoInfo['lines']):
  2252. topoType = 'lines'
  2253. else:
  2254. topoType = 'points'
  2255. label = '('.join(mapFrameDict['map'].split('@')) + ')'
  2256. if not vector:
  2257. vector = Vector(wx.NewId())
  2258. vector['list'] = []
  2259. self.instruction.AddInstruction(vector)
  2260. id = wx.NewId()
  2261. vector['list'].insert(0, [mapFrameDict['map'], topoType, id, 1, label])
  2262. vProp = VProperties(id, topoType)
  2263. vProp['name'], vProp['label'], vProp['lpos'] = mapFrameDict['map'], label, 1
  2264. self.instruction.AddInstruction(vProp)
  2265. else:
  2266. return False
  2267. self.scale[0], self.center[0], self.rectAdjusted = AutoAdjust(self, scaleType = 0, map = mapFrameDict['map'],
  2268. mapType = self.mapType, rect = self.mapFrameDict['rect'])
  2269. if self.rectAdjusted:
  2270. mapFrameDict['rect'] = self.rectAdjusted
  2271. else:
  2272. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2273. mapFrameDict['scale'] = self.scale[0]
  2274. mapFrameDict['center'] = self.center[0]
  2275. # set region
  2276. if self.mapType == 'raster':
  2277. RunCommand('g.region', rast = mapFrameDict['map'])
  2278. if self.mapType == 'vector':
  2279. raster = self.instruction.FindInstructionByType('raster')
  2280. if raster:
  2281. rasterId = raster.id
  2282. else:
  2283. rasterId = None
  2284. if rasterId:
  2285. RunCommand('g.region', vect = mapFrameDict['map'], rast = self.instruction[rasterId]['raster'])
  2286. else:
  2287. RunCommand('g.region', vect = mapFrameDict['map'])
  2288. else:
  2289. wx.MessageBox(message = _("No map selected!"),
  2290. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  2291. return False
  2292. elif mapFrameDict['scaleType'] == 1:
  2293. if self.select.GetValue():
  2294. mapFrameDict['drawMap'] = False
  2295. mapFrameDict['map'] = None
  2296. mapFrameDict['mapType'] = None
  2297. mapFrameDict['region'] = self.select.GetValue()
  2298. self.scale[1], self.center[1], self.rectAdjusted = AutoAdjust(self, scaleType = 1, region = mapFrameDict['region'],
  2299. rect = self.mapFrameDict['rect'])
  2300. if self.rectAdjusted:
  2301. mapFrameDict['rect'] = self.rectAdjusted
  2302. else:
  2303. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2304. mapFrameDict['scale'] = self.scale[1]
  2305. mapFrameDict['center'] = self.center[1]
  2306. # set region
  2307. RunCommand('g.region', region = mapFrameDict['region'])
  2308. else:
  2309. wx.MessageBox(message = _("No region selected!"),
  2310. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  2311. return False
  2312. elif scaleType == 2:
  2313. mapFrameDict['drawMap'] = False
  2314. mapFrameDict['map'] = None
  2315. mapFrameDict['mapType'] = None
  2316. mapFrameDict['region'] = None
  2317. self.scale[2], self.center[2], self.rectAdjusted = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect'])
  2318. if self.rectAdjusted:
  2319. mapFrameDict['rect'] = self.rectAdjusted
  2320. else:
  2321. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2322. mapFrameDict['scale'] = self.scale[2]
  2323. mapFrameDict['center'] = self.center[2]
  2324. env = grass.gisenv()
  2325. windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND')
  2326. try:
  2327. windFile = open(windFilePath, 'r').read()
  2328. region = grass.parse_key_val(windFile, sep = ':', val_type = float)
  2329. except IOError:
  2330. region = grass.region()
  2331. raster = self.instruction.FindInstructionByType('raster')
  2332. if raster:
  2333. rasterId = raster.id
  2334. else:
  2335. rasterId = None
  2336. if rasterId: # because of resolution
  2337. RunCommand('g.region', n = region['north'], s = region['south'],
  2338. e = region['east'], w = region['west'], rast = self.instruction[rasterId]['raster'])
  2339. else:
  2340. RunCommand('g.region', n = region['north'], s = region['south'],
  2341. e = region['east'], w = region['west'])
  2342. elif scaleType == 3:
  2343. mapFrameDict['drawMap'] = False
  2344. mapFrameDict['map'] = None
  2345. mapFrameDict['mapType'] = None
  2346. mapFrameDict['region'] = None
  2347. mapFrameDict['rect'] = self.mapFrameDict['rect']
  2348. try:
  2349. scaleNumber = float(self.scaleTextCtrl.GetValue())
  2350. centerE = float(self.eastingTextCtrl.GetValue())
  2351. centerN = float(self.northingTextCtrl.GetValue())
  2352. except (ValueError, SyntaxError):
  2353. wx.MessageBox(message = _("Invalid scale or map center!"),
  2354. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  2355. return False
  2356. mapFrameDict['scale'] = 1/scaleNumber
  2357. mapFrameDict['center'] = centerE, centerN
  2358. ComputeSetRegion(self, mapDict = mapFrameDict)
  2359. # check resolution
  2360. SetResolution(dpi = mapFrameDict['resolution'], width = mapFrameDict['rect'].width,
  2361. height = mapFrameDict['rect'].height)
  2362. # border
  2363. if self.borderCheck.GetValue():
  2364. mapFrameDict['border'] = 'y'
  2365. else:
  2366. mapFrameDict['border'] = 'n'
  2367. if mapFrameDict['border'] == 'y':
  2368. mapFrameDict['width'] = self.borderWidthCtrl.GetValue()
  2369. mapFrameDict['color'] = convertRGB(self.borderColourPicker.GetColour())
  2370. if self.id not in self.instruction:
  2371. mapFrame = MapFrame(self.id)
  2372. self.instruction.AddInstruction(mapFrame)
  2373. self.instruction[self.id].SetInstruction(mapFrameDict)
  2374. if self.id not in self.mapDialog.parent.objectId:
  2375. self.mapDialog.parent.objectId.insert(0, self.id)# map frame is drawn first
  2376. return True
  2377. class RasterPanel(wx.Panel):
  2378. """!Panel for raster map settings"""
  2379. def __init__(self, parent, id, settings, notebook = True):
  2380. wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  2381. self.instruction = settings
  2382. if notebook:
  2383. self.book = parent
  2384. self.book.AddPage(page = self, text = _("Raster map"))
  2385. self.mainDialog = self.book.GetParent()
  2386. else:
  2387. self.mainDialog = parent
  2388. if id:
  2389. self.id = id
  2390. self.rasterDict = self.instruction[self.id].GetInstruction()
  2391. else:
  2392. self.id = wx.NewId()
  2393. raster = Raster(self.id)
  2394. self.rasterDict = raster.GetInstruction()
  2395. self._layout()
  2396. self.OnRaster(None)
  2397. def _layout(self):
  2398. """!Do layout"""
  2399. border = wx.BoxSizer(wx.VERTICAL)
  2400. # choose raster map
  2401. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Choose raster map"))
  2402. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2403. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  2404. self.rasterNoRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("no raster map"), style = wx.RB_GROUP)
  2405. self.rasterYesRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("raster:"))
  2406. self.rasterSelect = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  2407. type = 'raster', multiple = False,
  2408. updateOnPopup = True, onPopup = None)
  2409. if self.rasterDict['isRaster']:
  2410. self.rasterYesRadio.SetValue(True)
  2411. self.rasterNoRadio.SetValue(False)
  2412. self.rasterSelect.SetValue(self.rasterDict['raster'])
  2413. else:
  2414. self.rasterYesRadio.SetValue(False)
  2415. self.rasterNoRadio.SetValue(True)
  2416. mapId = self.instruction.FindInstructionByType('map').id
  2417. if self.instruction[mapId]['map'] and self.instruction[mapId]['mapType'] == 'raster':
  2418. self.rasterSelect.SetValue(self.instruction[mapId]['map'])# raster map from map frame dialog if possible
  2419. else:
  2420. self.rasterSelect.SetValue('')
  2421. gridBagSizer.Add(self.rasterNoRadio, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2422. gridBagSizer.Add(self.rasterYesRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2423. gridBagSizer.Add(self.rasterSelect, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2424. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2425. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2426. #self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
  2427. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterNoRadio)
  2428. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterYesRadio)
  2429. self.SetSizer(border)
  2430. self.Fit()
  2431. def OnRaster(self, event):
  2432. """!Enable/disable raster selection"""
  2433. self.rasterSelect.Enable(self.rasterYesRadio.GetValue())
  2434. def update(self):
  2435. #draw raster
  2436. mapInstr = self.instruction.FindInstructionByType('map')
  2437. if not mapInstr: # no map frame
  2438. GMessage(message = _("Please, create map frame first."))
  2439. return
  2440. if self.rasterNoRadio.GetValue() or not self.rasterSelect.GetValue():
  2441. self.rasterDict['isRaster'] = False
  2442. self.rasterDict['raster'] = None
  2443. mapInstr['drawMap'] = False
  2444. if self.id in self.instruction:
  2445. del self.instruction[self.id]
  2446. else:
  2447. self.rasterDict['isRaster'] = True
  2448. self.rasterDict['raster'] = self.rasterSelect.GetValue()
  2449. if self.rasterDict['raster'] != mapInstr['drawMap']:
  2450. mapInstr['drawMap'] = False
  2451. raster = self.instruction.FindInstructionByType('raster')
  2452. if not raster:
  2453. raster = Raster(self.id)
  2454. self.instruction.AddInstruction(raster)
  2455. self.instruction[self.id].SetInstruction(self.rasterDict)
  2456. else:
  2457. self.instruction[raster.id].SetInstruction(self.rasterDict)
  2458. if 'map' in self.mainDialog.parent.openDialogs:
  2459. self.mainDialog.parent.openDialogs['map'].updateDialog()
  2460. return True
  2461. def getId(self):
  2462. return self.id
  2463. class VectorPanel(wx.Panel):
  2464. """!Panel for vector maps settings"""
  2465. def __init__(self, parent, id, settings, notebook = True):
  2466. wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  2467. self.parent = parent
  2468. self.instruction = settings
  2469. self.tmpDialogDict = {}
  2470. vectors = self.instruction.FindInstructionByType('vProperties', list = True)
  2471. for vector in vectors:
  2472. self.tmpDialogDict[vector.id] = dict(self.instruction[vector.id].GetInstruction())
  2473. if id:
  2474. self.id = id
  2475. self.vectorList = deepcopy(self.instruction[id]['list'])
  2476. else:
  2477. self.id = wx.NewId()
  2478. self.vectorList = []
  2479. vLegend = self.instruction.FindInstructionByType('vectorLegend')
  2480. if vLegend:
  2481. self.vLegendId = vLegend.id
  2482. else:
  2483. self.vLegendId = None
  2484. self._layout()
  2485. if notebook:
  2486. self.parent.AddPage(page = self, text = _("Vector maps"))
  2487. self.parent = self.parent.GetParent()
  2488. def _layout(self):
  2489. """!Do layout"""
  2490. border = wx.BoxSizer(wx.VERTICAL)
  2491. # choose vector map
  2492. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Add map"))
  2493. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2494. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  2495. text = wx.StaticText(self, id = wx.ID_ANY, label = _("Map:"))
  2496. self.select = Select(self, id = wx.ID_ANY,# size = globalvar.DIALOG_GSELECT_SIZE,
  2497. type = 'vector', multiple = False,
  2498. updateOnPopup = True, onPopup = None)
  2499. topologyType = [_("points"), _("lines"), _("areas")]
  2500. self.vectorType = wx.RadioBox(self, id = wx.ID_ANY, label = " %s " % _("Data Type"), choices = topologyType,
  2501. majorDimension = 3, style = wx.RA_SPECIFY_COLS)
  2502. self.AddVector = wx.Button(self, id = wx.ID_ANY, label = _("Add"))
  2503. gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2504. gridBagSizer.Add(self.select, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2505. gridBagSizer.Add(self.vectorType, pos = (1,1), flag = wx.ALIGN_CENTER, border = 0)
  2506. gridBagSizer.Add(self.AddVector, pos = (1,2), flag = wx.ALIGN_BOTTOM|wx.ALIGN_RIGHT, border = 0)
  2507. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2508. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2509. # manage vector layers
  2510. box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Manage vector maps"))
  2511. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2512. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  2513. gridBagSizer.AddGrowableCol(0,2)
  2514. gridBagSizer.AddGrowableCol(1,1)
  2515. text = wx.StaticText(self, id = wx.ID_ANY, label = _("The topmost vector map overlaps the others"))
  2516. self.listbox = wx.ListBox(self, id = wx.ID_ANY, choices = [], style = wx.LB_SINGLE|wx.LB_NEEDED_SB)
  2517. self.btnUp = wx.Button(self, id = wx.ID_ANY, label = _("Up"))
  2518. self.btnDown = wx.Button(self, id = wx.ID_ANY, label = _("Down"))
  2519. self.btnDel = wx.Button(self, id = wx.ID_ANY, label = _("Delete"))
  2520. self.btnProp = wx.Button(self, id = wx.ID_ANY, label = _("Properties..."))
  2521. self.updateListBox(selected=0)
  2522. gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2523. gridBagSizer.Add(self.listbox, pos = (1,0), span = (4, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2524. gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2525. gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2526. gridBagSizer.Add(self.btnDel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2527. gridBagSizer.Add(self.btnProp, pos = (4,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2528. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALL, border = 5)
  2529. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2530. self.Bind(wx.EVT_BUTTON, self.OnAddVector, self.AddVector)
  2531. self.Bind(wx.EVT_BUTTON, self.OnDelete, self.btnDel)
  2532. self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp)
  2533. self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)
  2534. self.Bind(wx.EVT_BUTTON, self.OnProperties, self.btnProp)
  2535. self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnVector)
  2536. self.SetSizer(border)
  2537. self.Fit()
  2538. self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnProperties, self.listbox)
  2539. def OnVector(self, event):
  2540. """!Gets info about toplogy and enables/disables choices point/line/area"""
  2541. vmap = self.select.GetValue()
  2542. try:
  2543. topoInfo = grass.vector_info_topo(map = vmap)
  2544. except grass.ScriptError:
  2545. return
  2546. if topoInfo:
  2547. self.vectorType.EnableItem(2, bool(topoInfo['areas']))
  2548. self.vectorType.EnableItem(1, bool(topoInfo['boundaries']) or bool(topoInfo['lines']))
  2549. self.vectorType.EnableItem(0, bool(topoInfo['centroids'] or bool(topoInfo['points']) ))
  2550. for item in range(2,-1,-1):
  2551. if self.vectorType.IsItemEnabled(item):
  2552. self.vectorType.SetSelection(item)
  2553. break
  2554. self.AddVector.SetFocus()
  2555. def OnAddVector(self, event):
  2556. """!Adds vector map to list"""
  2557. vmap = self.select.GetValue()
  2558. if vmap:
  2559. mapname = vmap.split('@')[0]
  2560. try:
  2561. mapset = '(' + vmap.split('@')[1] + ')'
  2562. except IndexError:
  2563. mapset = ''
  2564. type = self.vectorType.GetStringSelection()
  2565. record = "%s - %s" % (vmap,type)
  2566. id = wx.NewId()
  2567. lpos = 1
  2568. label = mapname + mapset
  2569. self.vectorList.insert(0, [vmap, type, id, lpos, label])
  2570. self.reposition()
  2571. self.listbox.InsertItems([record], 0)
  2572. vector = VProperties(id, type)
  2573. self.tmpDialogDict[id] = vector.GetInstruction()
  2574. self.tmpDialogDict[id]['name'] = vmap
  2575. self.listbox.SetSelection(0)
  2576. self.listbox.EnsureVisible(0)
  2577. self.btnProp.SetFocus()
  2578. self.enableButtons()
  2579. def OnDelete(self, event):
  2580. """!Deletes vector map from the list"""
  2581. if self.listbox.GetSelections():
  2582. pos = self.listbox.GetSelection()
  2583. id = self.vectorList[pos][2]
  2584. del self.vectorList[pos]
  2585. del self.tmpDialogDict[id]
  2586. for i in range(pos, len(self.vectorList)):
  2587. if self.vectorList[i][3]:# can be 0
  2588. self.vectorList[i][3] -= 1
  2589. if pos < len(self.vectorList) -1:
  2590. selected = pos
  2591. else:
  2592. selected = len(self.vectorList) -1
  2593. self.updateListBox(selected = selected)
  2594. if self.listbox.IsEmpty():
  2595. self.enableButtons(False)
  2596. def OnUp(self, event):
  2597. """!Moves selected map to top"""
  2598. if self.listbox.GetSelections():
  2599. pos = self.listbox.GetSelection()
  2600. if pos:
  2601. self.vectorList.insert(pos - 1, self.vectorList.pop(pos))
  2602. if not self.vLegendId:
  2603. self.reposition()
  2604. if pos > 0:
  2605. self.updateListBox(selected = (pos - 1))
  2606. else:
  2607. self.updateListBox(selected = 0)
  2608. def OnDown(self, event):
  2609. """!Moves selected map to bottom"""
  2610. if self.listbox.GetSelections():
  2611. pos = self.listbox.GetSelection()
  2612. if pos != len(self.vectorList) - 1:
  2613. self.vectorList.insert(pos + 1, self.vectorList.pop(pos))
  2614. if not self.vLegendId:
  2615. self.reposition()
  2616. if pos < len(self.vectorList) -1:
  2617. self.updateListBox(selected = (pos + 1))
  2618. else:
  2619. self.updateListBox(selected = len(self.vectorList) -1)
  2620. def OnProperties(self, event):
  2621. """!Opens vector map properties dialog"""
  2622. if self.listbox.GetSelections():
  2623. pos = self.listbox.GetSelection()
  2624. id = self.vectorList[pos][2]
  2625. dlg = VPropertiesDialog(self, id = id, settings = self.instruction,
  2626. vectors = self.vectorList, tmpSettings = self.tmpDialogDict[id])
  2627. dlg.ShowModal()
  2628. self.parent.FindWindowById(wx.ID_OK).SetFocus()
  2629. def enableButtons(self, enable = True):
  2630. """!Enable/disable up, down, properties, delete buttons"""
  2631. self.btnUp.Enable(enable)
  2632. self.btnDown.Enable(enable)
  2633. self.btnProp.Enable(enable)
  2634. self.btnDel.Enable(enable)
  2635. def updateListBox(self, selected = None):
  2636. mapList = ["%s - %s" % (item[0], item[1]) for item in self.vectorList]
  2637. self.listbox.Set(mapList)
  2638. if self.listbox.IsEmpty():
  2639. self.enableButtons(False)
  2640. else:
  2641. self.enableButtons(True)
  2642. if selected is not None:
  2643. self.listbox.SetSelection(selected)
  2644. self.listbox.EnsureVisible(selected)
  2645. def reposition(self):
  2646. """!Update position in legend, used only if there is no vlegend yet"""
  2647. for i in range(len(self.vectorList)):
  2648. if self.vectorList[i][3]:
  2649. self.vectorList[i][3] = i + 1
  2650. def getId(self):
  2651. return self.id
  2652. def update(self):
  2653. vectors = self.instruction.FindInstructionByType('vProperties', list = True)
  2654. for vector in vectors:
  2655. del self.instruction[vector.id]
  2656. if self.id in self.instruction:
  2657. del self.instruction[self.id]
  2658. if len(self.vectorList) > 0:
  2659. vector = Vector(self.id)
  2660. self.instruction.AddInstruction(vector)
  2661. vector.SetInstruction({'list': deepcopy(self.vectorList)})
  2662. # save new vectors
  2663. for item in self.vectorList:
  2664. id = item[2]
  2665. vLayer = VProperties(id, item[1])
  2666. self.instruction.AddInstruction(vLayer)
  2667. vLayer.SetInstruction(self.tmpDialogDict[id])
  2668. vLayer['name'] = item[0]
  2669. vLayer['label'] = item[4]
  2670. vLayer['lpos'] = item[3]
  2671. else:
  2672. if self.id in self.instruction:
  2673. del self.instruction[self.id]
  2674. if 'map' in self.parent.parent.openDialogs:
  2675. self.parent.parent.openDialogs['map'].updateDialog()
  2676. return True
  2677. class RasterDialog(PsmapDialog):
  2678. def __init__(self, parent, id, settings):
  2679. PsmapDialog.__init__(self, parent = parent, id = id, title = _("Raster map settings"), settings = settings)
  2680. self.objectType = ('raster',)
  2681. self.rPanel = RasterPanel(parent = self, id = self.id, settings = self.instruction, notebook = False)
  2682. self.id = self.rPanel.getId()
  2683. self._layout(self.rPanel)
  2684. def update(self):
  2685. ok = self.rPanel.update()
  2686. if ok:
  2687. return True
  2688. return False
  2689. def OnApply(self, event):
  2690. ok = self.update()
  2691. if not ok:
  2692. return False
  2693. if self.id in self.instruction:
  2694. self.parent.DialogDataChanged(id = self.id)
  2695. else:
  2696. mapId = self.instruction.FindInstructionByType('map').id
  2697. self.parent.DialogDataChanged(id = mapId)
  2698. return True
  2699. def updateDialog(self):
  2700. """!Update information (not used)"""
  2701. pass
  2702. ## if 'map' in self.parent.openDialogs:
  2703. ## if self.parent.openDialogs['map'].mPanel.rasterTypeRadio.GetValue()\
  2704. ## and self.parent.openDialogs['map'].mPanel.select.GetValue():
  2705. ## if self.parent.openDialogs['map'].mPanel.drawMap.IsChecked():
  2706. ## self.rPanel.rasterSelect.SetValue(self.parent.openDialogs['map'].mPanel.select.GetValue())
  2707. class MainVectorDialog(PsmapDialog):
  2708. def __init__(self, parent, id, settings):
  2709. PsmapDialog.__init__(self, parent = parent, id = id, title = _("Vector maps settings"), settings = settings)
  2710. self.objectType = ('vector',)
  2711. self.vPanel = VectorPanel(parent = self, id = self.id, settings = self.instruction, notebook = False)
  2712. self.id = self.vPanel.getId()
  2713. self._layout(self.vPanel)
  2714. def update(self):
  2715. self.vPanel.update()
  2716. def OnApply(self, event):
  2717. self.update()
  2718. if self.id in self.instruction:
  2719. self.parent.DialogDataChanged(id = self.id)
  2720. else:
  2721. mapId = self.instruction.FindInstructionByType('map').id
  2722. self.parent.DialogDataChanged(id = mapId)
  2723. return True
  2724. def updateDialog(self):
  2725. """!Update information (not used)"""
  2726. pass
  2727. class VPropertiesDialog(PsmapDialog):
  2728. def __init__(self, parent, id, settings, vectors, tmpSettings):
  2729. PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings, apply = False)
  2730. vectorList = vectors
  2731. self.vPropertiesDict = tmpSettings
  2732. # determine map and its type
  2733. for item in vectorList:
  2734. if id == item[2]:
  2735. self.vectorName = item[0]
  2736. self.type = item[1]
  2737. self.SetTitle(self.vectorName + " "+ _("properties"))
  2738. #vector map info
  2739. self.connection = True
  2740. try:
  2741. self.mapDBInfo = VectorDBInfo(self.vectorName)
  2742. self.layers = self.mapDBInfo.layers.keys()
  2743. except grass.ScriptError:
  2744. self.connection = False
  2745. self.layers = []
  2746. if not self.layers:
  2747. self.connection = False
  2748. self.layers = []
  2749. self.currLayer = self.vPropertiesDict['layer']
  2750. #path to symbols, patterns
  2751. gisbase = os.getenv("GISBASE")
  2752. self.symbolPath = os.path.join(gisbase, 'etc', 'symbol')
  2753. self.symbols = []
  2754. for dir in os.listdir(self.symbolPath):
  2755. for symbol in os.listdir(os.path.join(self.symbolPath, dir)):
  2756. self.symbols.append(os.path.join(dir, symbol))
  2757. self.patternPath = os.path.join(gisbase, 'etc', 'paint', 'patterns')
  2758. #notebook
  2759. notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  2760. self.DSpanel = self._DataSelectionPanel(notebook)
  2761. self.EnableLayerSelection(enable = self.connection)
  2762. selectPanel = { 'points': [self._ColorsPointAreaPanel, self._StylePointPanel],
  2763. 'lines': [self._ColorsLinePanel, self._StyleLinePanel],
  2764. 'areas': [self._ColorsPointAreaPanel, self._StyleAreaPanel]}
  2765. self.ColorsPanel = selectPanel[self.type][0](notebook)
  2766. self.OnOutline(None)
  2767. if self.type in ('points', 'areas'):
  2768. self.OnFill(None)
  2769. self.OnColor(None)
  2770. self.StylePanel = selectPanel[self.type][1](notebook)
  2771. if self.type == 'points':
  2772. self.OnSize(None)
  2773. self.OnRotation(None)
  2774. if self.type == 'areas':
  2775. self.OnPattern(None)
  2776. self._layout(notebook)
  2777. def _DataSelectionPanel(self, notebook):
  2778. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  2779. notebook.AddPage(page = panel, text = _("Data selection"))
  2780. border = wx.BoxSizer(wx.VERTICAL)
  2781. # data type
  2782. self.checkType1 = self.checkType2 = None
  2783. if self.type in ('lines', 'points'):
  2784. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Feature type"))
  2785. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2786. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  2787. if self.type == 'points':
  2788. label = (_("points"), _("centroids"))
  2789. else:
  2790. label = (_("lines"), _("boundaries"))
  2791. if self.type == 'points':
  2792. name = ("point", "centroid")
  2793. else:
  2794. name = ("line", "boundary")
  2795. self.checkType1 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[0], name = name[0])
  2796. self.checkType2 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[1], name = name[1])
  2797. self.checkType1.SetValue(self.vPropertiesDict['type'].find(name[0]) >= 0)
  2798. self.checkType2.SetValue(self.vPropertiesDict['type'].find(name[1]) >= 0)
  2799. gridBagSizer.Add(self.checkType1, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2800. gridBagSizer.Add(self.checkType2, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2801. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2802. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2803. # layer selection
  2804. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Layer selection"))
  2805. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2806. self.gridBagSizerL = wx.GridBagSizer(hgap = 5, vgap = 5)
  2807. self.warning = wx.StaticText(panel, id = wx.ID_ANY, label = "")
  2808. if not self.connection:
  2809. self.warning = wx.StaticText(panel, id = wx.ID_ANY, label = _("Database connection is not defined in DB file."))
  2810. text = wx.StaticText(panel, id = wx.ID_ANY, label = _("Select layer:"))
  2811. self.layerChoice = wx.Choice(panel, id = wx.ID_ANY, choices = map(str, self.layers), size = self.spinCtrlSize)
  2812. self.layerChoice.SetStringSelection(self.currLayer)
  2813. if self.connection:
  2814. table = self.mapDBInfo.layers[int(self.currLayer)]['table']
  2815. else:
  2816. table = ""
  2817. self.radioWhere = wx.RadioButton(panel, id = wx.ID_ANY, label = "SELECT * FROM %s WHERE" % table, style = wx.RB_GROUP)
  2818. self.textCtrlWhere = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  2819. if self.connection:
  2820. cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table'])
  2821. else:
  2822. cols = []
  2823. self.choiceColumns = wx.Choice(panel, id = wx.ID_ANY, choices = cols)
  2824. self.radioCats = wx.RadioButton(panel, id = wx.ID_ANY, label = "Choose categories ")
  2825. self.textCtrlCats = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  2826. self.textCtrlCats.SetToolTipString(_("list of categories (e.g. 1,3,5-7)"))
  2827. if self.vPropertiesDict.has_key('cats'):
  2828. self.radioCats.SetValue(True)
  2829. self.textCtrlCats.SetValue(self.vPropertiesDict['cats'])
  2830. if self.vPropertiesDict.has_key('where'):
  2831. self.radioWhere.SetValue(True)
  2832. where = self.vPropertiesDict['where'].strip().split(" ",1)
  2833. self.choiceColumns.SetStringSelection(where[0])
  2834. self.textCtrlWhere.SetValue(where[1])
  2835. row = 0
  2836. if not self.connection:
  2837. self.gridBagSizerL.Add(self.warning, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2838. row = 1
  2839. self.gridBagSizerL.Add(text, pos = (0 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2840. self.gridBagSizerL.Add(self.layerChoice, pos = (0 + row,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2841. self.gridBagSizerL.Add(self.radioWhere, pos = (1 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2842. self.gridBagSizerL.Add(self.choiceColumns, pos = (1 + row,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2843. self.gridBagSizerL.Add(self.textCtrlWhere, pos = (1 + row,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2844. self.gridBagSizerL.Add(self.radioCats, pos = (2 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2845. self.gridBagSizerL.Add(self.textCtrlCats, pos = (2 + row,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2846. sizer.Add(self.gridBagSizerL, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2847. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2848. #mask
  2849. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Mask"))
  2850. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2851. self.mask = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use current mask"))
  2852. if self.vPropertiesDict['masked'] == 'y':
  2853. self.mask.SetValue(True)
  2854. else:
  2855. self.mask.SetValue(False)
  2856. sizer.Add(self.mask, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2857. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2858. self.Bind(wx.EVT_CHOICE, self.OnLayer, self.layerChoice)
  2859. panel.SetSizer(border)
  2860. panel.Fit()
  2861. return panel
  2862. def _ColorsPointAreaPanel(self, notebook):
  2863. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  2864. notebook.AddPage(page = panel, text = _("Colors"))
  2865. border = wx.BoxSizer(wx.VERTICAL)
  2866. #colors - outline
  2867. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline"))
  2868. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2869. self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2)
  2870. self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline"))
  2871. self.outlineCheck.SetValue(self.vPropertiesDict['color'] != 'none')
  2872. widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  2873. if fs:
  2874. self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
  2875. increment = 0.5, value = 1, style = fs.FS_RIGHT)
  2876. self.widthSpin.SetFormat("%f")
  2877. self.widthSpin.SetDigits(2)
  2878. else:
  2879. self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1,
  2880. size = self.spinCtrlSize)
  2881. if self.vPropertiesDict['color'] == None:
  2882. self.vPropertiesDict['color'] = 'none'
  2883. if self.vPropertiesDict['color'] != 'none':
  2884. self.widthSpin.SetValue(self.vPropertiesDict['width'] )
  2885. else:
  2886. self.widthSpin.SetValue(1)
  2887. colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:"))
  2888. self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  2889. if self.vPropertiesDict['color'] != 'none':
  2890. self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['color']))
  2891. else:
  2892. self.colorPicker.SetColour(convertRGB('black'))
  2893. self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2894. self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2895. self.gridBagSizerO.Add(self.widthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2896. self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2897. self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2898. sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2899. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2900. self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck)
  2901. #colors - fill
  2902. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill"))
  2903. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2904. self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2)
  2905. self.fillCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("fill color"))
  2906. self.fillCheck.SetValue(self.vPropertiesDict['fcolor'] != 'none' or self.vPropertiesDict['rgbcolumn'] is not None)
  2907. self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP)
  2908. #set choose color option if there is no db connection
  2909. if self.connection:
  2910. self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn'])
  2911. else:
  2912. self.colorPickerRadio.SetValue(False)
  2913. self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  2914. if self.vPropertiesDict['fcolor'] != 'none':
  2915. self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['fcolor']))
  2916. else:
  2917. self.fillColorPicker.SetColour(convertRGB('red'))
  2918. self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:"))
  2919. self.colorColChoice = self.getColsChoice(parent = panel)
  2920. if self.connection:
  2921. if self.vPropertiesDict['rgbcolumn']:
  2922. self.colorColRadio.SetValue(True)
  2923. self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn'])
  2924. else:
  2925. self.colorColRadio.SetValue(False)
  2926. self.colorColChoice.SetSelection(0)
  2927. self.colorColChoice.Enable(self.connection)
  2928. self.colorColRadio.Enable(self.connection)
  2929. self.gridBagSizerF.Add(self.fillCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2930. self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2931. self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2932. self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2933. self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2934. sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2935. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2936. self.Bind(wx.EVT_CHECKBOX, self.OnFill, self.fillCheck)
  2937. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio)
  2938. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio)
  2939. panel.SetSizer(border)
  2940. panel.Fit()
  2941. return panel
  2942. def _ColorsLinePanel(self, notebook):
  2943. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  2944. notebook.AddPage(page = panel, text = _("Colors"))
  2945. border = wx.BoxSizer(wx.VERTICAL)
  2946. #colors - outline
  2947. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline"))
  2948. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2949. self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2)
  2950. if self.vPropertiesDict['hcolor'] == None:
  2951. self.vPropertiesDict['hcolor'] = 'none'
  2952. if self.vPropertiesDict['color'] == None:
  2953. self.vPropertiesDict['color'] = 'none'
  2954. self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline"))
  2955. self.outlineCheck.SetValue(self.vPropertiesDict['hcolor'] != 'none')
  2956. self.outlineCheck.SetToolTipString(_("No effect for fill color from table column"))
  2957. widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  2958. if fs:
  2959. self.outWidthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
  2960. increment = 0.5, value = 1, style = fs.FS_RIGHT)
  2961. self.outWidthSpin.SetFormat("%f")
  2962. self.outWidthSpin.SetDigits(1)
  2963. else:
  2964. self.outWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1,
  2965. size = self.spinCtrlSize)
  2966. if self.vPropertiesDict['hcolor'] != 'none':
  2967. self.outWidthSpin.SetValue(self.vPropertiesDict['hwidth'] )
  2968. else:
  2969. self.outWidthSpin.SetValue(1)
  2970. colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:"))
  2971. self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  2972. if self.vPropertiesDict['hcolor'] != 'none':
  2973. self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['hcolor']) )
  2974. else:
  2975. self.colorPicker.SetColour(convertRGB('black'))
  2976. self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2977. self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2978. self.gridBagSizerO.Add(self.outWidthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  2979. self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2980. self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  2981. sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  2982. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2983. self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck)
  2984. #colors - fill
  2985. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill"))
  2986. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  2987. self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2)
  2988. fillText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color of lines:"))
  2989. self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP)
  2990. #set choose color option if there is no db connection
  2991. if self.connection:
  2992. self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn'])
  2993. else:
  2994. self.colorPickerRadio.SetValue(False)
  2995. self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  2996. if self.vPropertiesDict['color'] != 'none':
  2997. self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['color']) )
  2998. else:
  2999. self.fillColorPicker.SetColour(convertRGB('black'))
  3000. self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:"))
  3001. self.colorColChoice = self.getColsChoice(parent = panel)
  3002. if self.connection:
  3003. if self.vPropertiesDict['rgbcolumn']:
  3004. self.colorColRadio.SetValue(True)
  3005. self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn'])
  3006. else:
  3007. self.colorColRadio.SetValue(False)
  3008. self.colorColChoice.SetSelection(0)
  3009. self.colorColChoice.Enable(self.connection)
  3010. self.colorColRadio.Enable(self.connection)
  3011. self.gridBagSizerF.Add(fillText, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3012. self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3013. self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3014. self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3015. self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3016. sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3017. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3018. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio)
  3019. self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio)
  3020. panel.SetSizer(border)
  3021. panel.Fit()
  3022. return panel
  3023. def _StylePointPanel(self, notebook):
  3024. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  3025. notebook.AddPage(page = panel, text = _("Size and style"))
  3026. border = wx.BoxSizer(wx.VERTICAL)
  3027. #symbology
  3028. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Symbology"))
  3029. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3030. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3031. gridBagSizer.AddGrowableCol(1)
  3032. self.symbolRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("symbol:"), style = wx.RB_GROUP)
  3033. self.symbolRadio.SetValue(bool(self.vPropertiesDict['symbol']))
  3034. self.symbolChoice = wx.Choice(panel, id = wx.ID_ANY, choices = self.symbols)
  3035. self.epsRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("eps file:"))
  3036. self.epsRadio.SetValue(bool(self.vPropertiesDict['eps']))
  3037. self.epsFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = '',
  3038. buttonText = _("Browse"), toolTip = _("Type filename or click browse to choose file"),
  3039. dialogTitle = _("Choose a file"), startDirectory = '', initialValue = '',
  3040. fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.OPEN)
  3041. if self.vPropertiesDict['symbol']:
  3042. self.symbolChoice.SetStringSelection(self.vPropertiesDict['symbol'])
  3043. self.epsFileCtrl.SetValue('')
  3044. else: #eps chosen
  3045. self.epsFileCtrl.SetValue(self.vPropertiesDict['eps'])
  3046. self.symbolChoice.SetSelection(0)
  3047. gridBagSizer.Add(self.symbolRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3048. gridBagSizer.Add(self.symbolChoice, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3049. gridBagSizer.Add(self.epsRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3050. gridBagSizer.Add(self.epsFileCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3051. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3052. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3053. #size
  3054. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  3055. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3056. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3057. gridBagSizer.AddGrowableCol(0)
  3058. self.sizeRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size:"), style = wx.RB_GROUP)
  3059. self.sizeSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 50, initial = 1)
  3060. self.sizecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size from map table column:"))
  3061. self.sizeColChoice = self.getColsChoice(panel)
  3062. self.scaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("scale:"))
  3063. self.scaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
  3064. self.sizeRadio.SetValue(self.vPropertiesDict['size'] is not None)
  3065. self.sizecolumnRadio.SetValue(bool(self.vPropertiesDict['sizecolumn']))
  3066. if self.vPropertiesDict['size']:
  3067. self.sizeSpin.SetValue(self.vPropertiesDict['size'])
  3068. else: self.sizeSpin.SetValue(5)
  3069. if self.vPropertiesDict['sizecolumn']:
  3070. self.scaleSpin.SetValue(self.vPropertiesDict['scale'])
  3071. self.sizeColChoice.SetStringSelection(self.vPropertiesDict['sizecolumn'])
  3072. else:
  3073. self.scaleSpin.SetValue(1)
  3074. self.sizeColChoice.SetSelection(0)
  3075. if not self.connection:
  3076. for each in (self.sizecolumnRadio, self.sizeColChoice, self.scaleSpin, self.scaleText):
  3077. each.Disable()
  3078. gridBagSizer.Add(self.sizeRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3079. gridBagSizer.Add(self.sizeSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3080. gridBagSizer.Add(self.sizecolumnRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3081. gridBagSizer.Add(self.sizeColChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3082. gridBagSizer.Add(self.scaleText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3083. gridBagSizer.Add(self.scaleSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3084. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3085. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3086. self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizeRadio)
  3087. self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizecolumnRadio)
  3088. #rotation
  3089. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Rotation"))
  3090. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3091. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3092. gridBagSizer.AddGrowableCol(1)
  3093. self.rotateCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate symbols:"))
  3094. self.rotateRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("counterclockwise in degrees:"), style = wx.RB_GROUP)
  3095. self.rotateSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 0, max = 360, initial = 0)
  3096. self.rotatecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("from map table column:"))
  3097. self.rotateColChoice = self.getColsChoice(panel)
  3098. self.rotateCheck.SetValue(self.vPropertiesDict['rotation'])
  3099. self.rotateRadio.SetValue(self.vPropertiesDict['rotate'] is not None)
  3100. self.rotatecolumnRadio.SetValue(bool(self.vPropertiesDict['rotatecolumn']))
  3101. if self.vPropertiesDict['rotate']:
  3102. self.rotateSpin.SetValue(self.vPropertiesDict['rotate'])
  3103. else:
  3104. self.rotateSpin.SetValue(0)
  3105. if self.vPropertiesDict['rotatecolumn']:
  3106. self.rotateColChoice.SetStringSelection(self.vPropertiesDict['rotatecolumn'])
  3107. else:
  3108. self.rotateColChoice.SetSelection(0)
  3109. gridBagSizer.Add(self.rotateCheck, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3110. gridBagSizer.Add(self.rotateRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3111. gridBagSizer.Add(self.rotateSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3112. gridBagSizer.Add(self.rotatecolumnRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3113. gridBagSizer.Add(self.rotateColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3114. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3115. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3116. self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotateCheck)
  3117. self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotateRadio)
  3118. self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotatecolumnRadio)
  3119. panel.SetSizer(border)
  3120. panel.Fit()
  3121. return panel
  3122. def _StyleLinePanel(self, notebook):
  3123. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  3124. notebook.AddPage(page = panel, text = _("Size and style"))
  3125. border = wx.BoxSizer(wx.VERTICAL)
  3126. #width
  3127. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Width"))
  3128. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3129. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3130. widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Set width (pts):"))
  3131. if fs:
  3132. self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30,
  3133. increment = 0.5, value = 1, style = fs.FS_RIGHT)
  3134. self.widthSpin.SetFormat("%f")
  3135. self.widthSpin.SetDigits(1)
  3136. else:
  3137. self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1)
  3138. self.cwidthCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("multiply width by category value"))
  3139. if self.vPropertiesDict['width']:
  3140. self.widthSpin.SetValue(self.vPropertiesDict['width'])
  3141. self.cwidthCheck.SetValue(False)
  3142. else:
  3143. self.widthSpin.SetValue(self.vPropertiesDict['cwidth'])
  3144. self.cwidthCheck.SetValue(True)
  3145. gridBagSizer.Add(widthText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3146. gridBagSizer.Add(self.widthSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3147. gridBagSizer.Add(self.cwidthCheck, pos = (1, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3148. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3149. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3150. #style
  3151. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Line style"))
  3152. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3153. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3154. styleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose line style:"))
  3155. penStyles = ["solid", "dashed", "dotted", "dashdotted"]
  3156. self.styleCombo = PenStyleComboBox(panel, choices = penStyles, validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY'))
  3157. ## self.styleCombo = wx.ComboBox(panel, id = wx.ID_ANY,
  3158. ## choices = ["solid", "dashed", "dotted", "dashdotted"],
  3159. ## validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY'))
  3160. ## self.styleCombo.SetToolTipString(_("It's possible to enter a series of 0's and 1's too. "\
  3161. ## "The first block of repeated zeros or ones represents 'draw', "\
  3162. ## "the second block represents 'blank'. An even number of blocks "\
  3163. ## "will repeat the pattern, an odd number of blocks will alternate the pattern."))
  3164. linecapText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose linecap:"))
  3165. self.linecapChoice = wx.Choice(panel, id = wx.ID_ANY, choices = ["butt", "round", "extended_butt"])
  3166. self.styleCombo.SetValue(self.vPropertiesDict['style'])
  3167. self.linecapChoice.SetStringSelection(self.vPropertiesDict['linecap'])
  3168. gridBagSizer.Add(styleText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3169. gridBagSizer.Add(self.styleCombo, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3170. gridBagSizer.Add(linecapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3171. gridBagSizer.Add(self.linecapChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3172. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3173. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3174. panel.SetSizer(border)
  3175. panel.Fit()
  3176. return panel
  3177. def _StyleAreaPanel(self, notebook):
  3178. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  3179. notebook.AddPage(page = panel, text = _("Size and style"))
  3180. border = wx.BoxSizer(wx.VERTICAL)
  3181. #pattern
  3182. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Pattern"))
  3183. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  3184. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3185. gridBagSizer.AddGrowableCol(1)
  3186. self.patternCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use pattern:"))
  3187. self.patFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = _("Choose pattern file:"),
  3188. buttonText = _("Browse"), toolTip = _("Type filename or click browse to choose file"),
  3189. dialogTitle = _("Choose a file"), startDirectory = self.patternPath, initialValue = '',
  3190. fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.OPEN)
  3191. self.patWidthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern line width (pts):"))
  3192. self.patWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
  3193. self.patScaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern scale factor:"))
  3194. self.patScaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1)
  3195. self.patternCheck.SetValue(bool(self.vPropertiesDict['pat']))
  3196. if self.patternCheck.GetValue():
  3197. self.patFileCtrl.SetValue(self.vPropertiesDict['pat'])
  3198. self.patWidthSpin.SetValue(self.vPropertiesDict['pwidth'])
  3199. self.patScaleSpin.SetValue(self.vPropertiesDict['scale'])
  3200. gridBagSizer.Add(self.patternCheck, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3201. gridBagSizer.Add(self.patFileCtrl, pos = (1, 0), span = (1, 2),flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3202. gridBagSizer.Add(self.patWidthText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3203. gridBagSizer.Add(self.patWidthSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3204. gridBagSizer.Add(self.patScaleText, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3205. gridBagSizer.Add(self.patScaleSpin, pos = (3, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3206. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3207. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3208. self.Bind(wx.EVT_CHECKBOX, self.OnPattern, self.patternCheck)
  3209. panel.SetSizer(border)
  3210. panel.Fit()
  3211. return panel
  3212. def OnLayer(self, event):
  3213. """!Change columns on layer change """
  3214. if self.layerChoice.GetStringSelection() == self.currLayer:
  3215. return
  3216. self.currLayer = self.layerChoice.GetStringSelection()
  3217. if self.connection:
  3218. cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table'])
  3219. else:
  3220. cols = []
  3221. self.choiceColumns.SetItems(cols)
  3222. self.choiceColumns.SetSelection(0)
  3223. if self.type in ('points', 'lines'):
  3224. self.colorColChoice.SetItems(cols)
  3225. self.colorColChoice.SetSelection(0)
  3226. def OnOutline(self, event):
  3227. for widget in self.gridBagSizerO.GetChildren():
  3228. if widget.GetWindow() != self.outlineCheck:
  3229. widget.GetWindow().Enable(self.outlineCheck.GetValue())
  3230. def OnFill(self, event):
  3231. enable = self.fillCheck.GetValue()
  3232. self.colorColChoice.Enable(enable)
  3233. self.colorColRadio.Enable(enable)
  3234. self.fillColorPicker.Enable(enable)
  3235. self.colorPickerRadio.Enable(enable)
  3236. if enable:
  3237. self.OnColor(None)
  3238. if not self.connection:
  3239. self.colorColChoice.Disable()
  3240. self.colorColRadio.Disable()
  3241. def OnColor(self, event):
  3242. self.colorColChoice.Enable(self.colorColRadio.GetValue())
  3243. self.fillColorPicker.Enable(self.colorPickerRadio.GetValue())
  3244. def OnSize(self, event):
  3245. self.sizeSpin.Enable(self.sizeRadio.GetValue())
  3246. self.sizeColChoice.Enable(self.sizecolumnRadio.GetValue())
  3247. self.scaleText.Enable(self.sizecolumnRadio.GetValue())
  3248. self.scaleSpin.Enable(self.sizecolumnRadio.GetValue())
  3249. def OnRotation(self, event):
  3250. for each in (self.rotateRadio, self.rotatecolumnRadio, self.rotateColChoice, self.rotateSpin):
  3251. if self.rotateCheck.GetValue():
  3252. each.Enable()
  3253. self.OnRotationType(event = None)
  3254. else:
  3255. each.Disable()
  3256. def OnRotationType(self, event):
  3257. self.rotateSpin.Enable(self.rotateRadio.GetValue())
  3258. self.rotateColChoice.Enable(self.rotatecolumnRadio.GetValue())
  3259. def OnPattern(self, event):
  3260. for each in (self.patFileCtrl, self.patWidthText, self.patWidthSpin, self.patScaleText, self.patScaleSpin):
  3261. each.Enable(self.patternCheck.GetValue())
  3262. def EnableLayerSelection(self, enable = True):
  3263. for widget in self.gridBagSizerL.GetChildren():
  3264. if widget.GetWindow() != self.warning:
  3265. widget.GetWindow().Enable(enable)
  3266. def getColsChoice(self, parent):
  3267. """!Returns a wx.Choice with table columns"""
  3268. if self.connection:
  3269. cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table'])
  3270. else:
  3271. cols = []
  3272. choice = wx.Choice(parent = parent, id = wx.ID_ANY, choices = cols)
  3273. return choice
  3274. def update(self):
  3275. #feature type
  3276. if self.type in ('lines', 'points'):
  3277. featureType = None
  3278. if self.checkType1.GetValue():
  3279. featureType = self.checkType1.GetName()
  3280. if self.checkType2.GetValue():
  3281. featureType += " or " + self.checkType2.GetName()
  3282. elif self.checkType2.GetValue():
  3283. featureType = self.checkType2.GetName()
  3284. if featureType:
  3285. self.vPropertiesDict['type'] = featureType
  3286. # is connection
  3287. self.vPropertiesDict['connection'] = self.connection
  3288. if self.connection:
  3289. self.vPropertiesDict['layer'] = self.layerChoice.GetStringSelection()
  3290. if self.radioCats.GetValue() and not self.textCtrlCats.IsEmpty():
  3291. self.vPropertiesDict['cats'] = self.textCtrlCats.GetValue()
  3292. elif self.radioWhere.GetValue() and not self.textCtrlWhere.IsEmpty():
  3293. self.vPropertiesDict['where'] = self.choiceColumns.GetStringSelection() + " " \
  3294. + self.textCtrlWhere.GetValue()
  3295. #mask
  3296. if self.mask.GetValue():
  3297. self.vPropertiesDict['masked'] = 'y'
  3298. else:
  3299. self.vPropertiesDict['masked'] = 'n'
  3300. #colors
  3301. if self.type in ('points', 'areas'):
  3302. if self.outlineCheck.GetValue():
  3303. self.vPropertiesDict['color'] = convertRGB(self.colorPicker.GetColour())
  3304. self.vPropertiesDict['width'] = self.widthSpin.GetValue()
  3305. else:
  3306. self.vPropertiesDict['color'] = 'none'
  3307. if self.fillCheck.GetValue():
  3308. if self.colorPickerRadio.GetValue():
  3309. self.vPropertiesDict['fcolor'] = convertRGB(self.fillColorPicker.GetColour())
  3310. self.vPropertiesDict['rgbcolumn'] = None
  3311. if self.colorColRadio.GetValue():
  3312. self.vPropertiesDict['fcolor'] = 'none'# this color is taken in case of no record in rgb column
  3313. self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection()
  3314. else:
  3315. self.vPropertiesDict['fcolor'] = 'none'
  3316. if self.type == 'lines':
  3317. #hcolor only when no rgbcolumn
  3318. if self.outlineCheck.GetValue():# and self.fillCheck.GetValue() and self.colorColRadio.GetValue():
  3319. self.vPropertiesDict['hcolor'] = convertRGB(self.colorPicker.GetColour())
  3320. self.vPropertiesDict['hwidth'] = self.outWidthSpin.GetValue()
  3321. else:
  3322. self.vPropertiesDict['hcolor'] = 'none'
  3323. if self.colorPickerRadio.GetValue():
  3324. self.vPropertiesDict['color'] = convertRGB(self.fillColorPicker.GetColour())
  3325. self.vPropertiesDict['rgbcolumn'] = None
  3326. if self.colorColRadio.GetValue():
  3327. self.vPropertiesDict['color'] = 'none'# this color is taken in case of no record in rgb column
  3328. self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection()
  3329. #
  3330. #size and style
  3331. #
  3332. if self.type == 'points':
  3333. #symbols
  3334. if self.symbolRadio.GetValue():
  3335. self.vPropertiesDict['symbol'] = self.symbolChoice.GetStringSelection()
  3336. self.vPropertiesDict['eps'] = None
  3337. else:
  3338. self.vPropertiesDict['eps'] = self.epsFileCtrl.GetValue()
  3339. self.vPropertiesDict['symbol'] = None
  3340. #size
  3341. if self.sizeRadio.GetValue():
  3342. self.vPropertiesDict['size'] = self.sizeSpin.GetValue()
  3343. self.vPropertiesDict['sizecolumn'] = None
  3344. self.vPropertiesDict['scale'] = None
  3345. else:
  3346. self.vPropertiesDict['sizecolumn'] = self.sizeColChoice.GetStringSelection()
  3347. self.vPropertiesDict['scale'] = self.scaleSpin.GetValue()
  3348. self.vPropertiesDict['size'] = None
  3349. #rotation
  3350. self.vPropertiesDict['rotate'] = None
  3351. self.vPropertiesDict['rotatecolumn'] = None
  3352. self.vPropertiesDict['rotation'] = False
  3353. if self.rotateCheck.GetValue():
  3354. self.vPropertiesDict['rotation'] = True
  3355. if self.rotateRadio.GetValue():
  3356. self.vPropertiesDict['rotate'] = self.rotateSpin.GetValue()
  3357. else:
  3358. self.vPropertiesDict['rotatecolumn'] = self.rotateColChoice.GetStringSelection()
  3359. if self.type == 'areas':
  3360. #pattern
  3361. self.vPropertiesDict['pat'] = None
  3362. if self.patternCheck.GetValue() and bool(self.patFileCtrl.GetValue()):
  3363. self.vPropertiesDict['pat'] = self.patFileCtrl.GetValue()
  3364. self.vPropertiesDict['pwidth'] = self.patWidthSpin.GetValue()
  3365. self.vPropertiesDict['scale'] = self.patScaleSpin.GetValue()
  3366. if self.type == 'lines':
  3367. #width
  3368. if self.cwidthCheck.GetValue():
  3369. self.vPropertiesDict['cwidth'] = self.widthSpin.GetValue()
  3370. self.vPropertiesDict['width'] = None
  3371. else:
  3372. self.vPropertiesDict['width'] = self.widthSpin.GetValue()
  3373. self.vPropertiesDict['cwidth'] = None
  3374. #line style
  3375. if self.styleCombo.GetValue():
  3376. self.vPropertiesDict['style'] = self.styleCombo.GetValue()
  3377. else:
  3378. self.vPropertiesDict['style'] = 'solid'
  3379. self.vPropertiesDict['linecap'] = self.linecapChoice.GetStringSelection()
  3380. def OnOK(self, event):
  3381. self.update()
  3382. event.Skip()
  3383. class LegendDialog(PsmapDialog):
  3384. def __init__(self, parent, id, settings, page):
  3385. PsmapDialog.__init__(self, parent = parent, id = id, title = "Legend settings", settings = settings)
  3386. self.objectType = ('rasterLegend', 'vectorLegend')
  3387. self.instruction = settings
  3388. map = self.instruction.FindInstructionByType('map')
  3389. if map:
  3390. self.mapId = map.id
  3391. else:
  3392. self.mapId = None
  3393. vector = self.instruction.FindInstructionByType('vector')
  3394. if vector:
  3395. self.vectorId = vector.id
  3396. else:
  3397. self.vectorId = None
  3398. raster = self.instruction.FindInstructionByType('raster')
  3399. if raster:
  3400. self.rasterId = raster.id
  3401. else:
  3402. self.rasterId = None
  3403. self.pageId = self.instruction.FindInstructionByType('page').id
  3404. currPage = self.instruction[self.pageId].GetInstruction()
  3405. #raster legend
  3406. if self.id[0] is not None:
  3407. self.rasterLegend = self.instruction[self.id[0]]
  3408. self.rLegendDict = self.rasterLegend.GetInstruction()
  3409. else:
  3410. self.id[0] = wx.NewId()
  3411. self.rasterLegend = RasterLegend(self.id[0])
  3412. self.rLegendDict = self.rasterLegend.GetInstruction()
  3413. self.rLegendDict['where'] = currPage['Left'], currPage['Top']
  3414. #vector legend
  3415. if self.id[1] is not None:
  3416. self.vLegendDict = self.instruction[self.id[1]].GetInstruction()
  3417. else:
  3418. self.id[1] = wx.NewId()
  3419. vectorLegend = VectorLegend(self.id[1])
  3420. self.vLegendDict = vectorLegend.GetInstruction()
  3421. self.vLegendDict['where'] = currPage['Left'], currPage['Top']
  3422. if self.rasterId:
  3423. self.currRaster = self.instruction[self.rasterId]['raster']
  3424. else:
  3425. self.currRaster = None
  3426. #notebook
  3427. self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  3428. self.panelRaster = self._rasterLegend(self.notebook)
  3429. self.panelVector = self._vectorLegend(self.notebook)
  3430. self.OnRaster(None)
  3431. self.OnRange(None)
  3432. self.OnIsLegend(None)
  3433. self.OnSpan(None)
  3434. self.OnBorder(None)
  3435. self._layout(self.notebook)
  3436. self.notebook.ChangeSelection(page)
  3437. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  3438. def OnPageChanging(self, event):
  3439. """!Workaround to scroll up to see the checkbox"""
  3440. wx.CallAfter(self.FindWindowByName('rasterPanel').ScrollChildIntoView,
  3441. self.FindWindowByName('showRLegend'))
  3442. wx.CallAfter(self.FindWindowByName('vectorPanel').ScrollChildIntoView,
  3443. self.FindWindowByName('showVLegend'))
  3444. def _rasterLegend(self, notebook):
  3445. panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
  3446. panel.SetupScrolling(scroll_x = False, scroll_y = True)
  3447. panel.SetName('rasterPanel')
  3448. notebook.AddPage(page = panel, text = _("Raster legend"))
  3449. border = wx.BoxSizer(wx.VERTICAL)
  3450. # is legend
  3451. self.isRLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show raster legend"))
  3452. self.isRLegend.SetValue(self.rLegendDict['rLegend'])
  3453. self.isRLegend.SetName("showRLegend")
  3454. border.Add(item = self.isRLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3455. # choose raster
  3456. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source raster"))
  3457. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3458. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  3459. flexSizer.AddGrowableCol(1)
  3460. self.rasterDefault = wx.RadioButton(panel, id = wx.ID_ANY, label = _("current raster"), style = wx.RB_GROUP)
  3461. self.rasterOther = wx.RadioButton(panel, id = wx.ID_ANY, label = _("select raster"))
  3462. self.rasterDefault.SetValue(self.rLegendDict['rasterDefault'])#
  3463. self.rasterOther.SetValue(not self.rLegendDict['rasterDefault'])#
  3464. rasterType = getRasterType(map = self.currRaster)
  3465. self.rasterCurrent = wx.StaticText(panel, id = wx.ID_ANY,
  3466. label = _("%(rast)s: type %(type)s") % { 'rast' : self.currRaster,
  3467. 'type' : rasterType })
  3468. self.rasterSelect = Select(panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  3469. type = 'raster', multiple = False,
  3470. updateOnPopup = True, onPopup = None)
  3471. if not self.rLegendDict['rasterDefault']:
  3472. self.rasterSelect.SetValue(self.rLegendDict['raster'])
  3473. else:
  3474. self.rasterSelect.SetValue('')
  3475. flexSizer.Add(self.rasterDefault, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3476. flexSizer.Add(self.rasterCurrent, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
  3477. flexSizer.Add(self.rasterOther, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3478. flexSizer.Add(self.rasterSelect, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3479. sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3480. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3481. # type of legend
  3482. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Type of legend"))
  3483. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3484. vbox = wx.BoxSizer(wx.VERTICAL)
  3485. self.discrete = wx.RadioButton(parent = panel, id = wx.ID_ANY,
  3486. label = " %s " % _("discrete legend (categorical maps)"), style = wx.RB_GROUP)
  3487. self.continuous = wx.RadioButton(parent = panel, id = wx.ID_ANY,
  3488. label = " %s " % _("continuous color gradient legend (floating point map)"))
  3489. vbox.Add(self.discrete, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
  3490. vbox.Add(self.continuous, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
  3491. sizer.Add(item = vbox, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3492. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3493. # size, position and font
  3494. self.sizePositionFont(legendType = 'raster', parent = panel, mainSizer = border)
  3495. # advanced settings
  3496. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Advanced legend settings"))
  3497. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3498. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3499. # no data
  3500. self.nodata = wx.CheckBox(panel, id = wx.ID_ANY, label = _('draw "no data" box'))
  3501. if self.rLegendDict['nodata'] == 'y':
  3502. self.nodata.SetValue(True)
  3503. else:
  3504. self.nodata.SetValue(False)
  3505. #tickbar
  3506. self.ticks = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw ticks across color table"))
  3507. if self.rLegendDict['tickbar'] == 'y':
  3508. self.ticks.SetValue(True)
  3509. else:
  3510. self.ticks.SetValue(False)
  3511. # range
  3512. if self.rasterId and self.instruction[self.rasterId]['raster']:
  3513. rinfo = grass.raster_info(self.instruction[self.rasterId]['raster'])
  3514. self.minim, self.maxim = rinfo['min'], rinfo['max']
  3515. else:
  3516. self.minim, self.maxim = 0,0
  3517. self.range = wx.CheckBox(panel, id = wx.ID_ANY, label = _("range"))
  3518. self.range.SetValue(self.rLegendDict['range'])
  3519. self.minText = wx.StaticText(panel, id = wx.ID_ANY, label = "min (%s)" % self.minim)
  3520. self.maxText = wx.StaticText(panel, id = wx.ID_ANY, label = "max (%s)" % self.maxim)
  3521. self.min = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['min']))
  3522. self.max = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['max']))
  3523. gridBagSizer.Add(self.nodata, pos = (0,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3524. gridBagSizer.Add(self.ticks, pos = (1,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3525. gridBagSizer.Add(self.range, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3526. gridBagSizer.Add(self.minText, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3527. gridBagSizer.Add(self.min, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3528. gridBagSizer.Add(self.maxText, pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3529. gridBagSizer.Add(self.max, pos = (2,4), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3530. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3531. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3532. panel.SetSizer(border)
  3533. panel.Fit()
  3534. # bindings
  3535. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterDefault)
  3536. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterOther)
  3537. self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isRLegend)
  3538. self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.discrete)
  3539. self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.continuous)
  3540. ## self.Bind(wx.EVT_CHECKBOX, self.OnDefaultSize, panel.defaultSize)
  3541. self.Bind(wx.EVT_CHECKBOX, self.OnRange, self.range)
  3542. self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
  3543. return panel
  3544. def _vectorLegend(self, notebook):
  3545. panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
  3546. panel.SetupScrolling(scroll_x = False, scroll_y = True)
  3547. panel.SetName('vectorPanel')
  3548. notebook.AddPage(page = panel, text = _("Vector legend"))
  3549. border = wx.BoxSizer(wx.VERTICAL)
  3550. # is legend
  3551. self.isVLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show vector legend"))
  3552. self.isVLegend.SetValue(self.vLegendDict['vLegend'])
  3553. self.isVLegend.SetName("showVLegend")
  3554. border.Add(item = self.isVLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3555. #vector maps, their order, labels
  3556. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source vector maps"))
  3557. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3558. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3559. gridBagSizer.AddGrowableCol(0,3)
  3560. gridBagSizer.AddGrowableCol(1,1)
  3561. vectorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose vector maps and their order in legend"))
  3562. self.vectorListCtrl = CheckListCtrl(panel)
  3563. self.vectorListCtrl.InsertColumn(0, _("Vector map"))
  3564. self.vectorListCtrl.InsertColumn(1, _("Label"))
  3565. if self.vectorId:
  3566. vectors = sorted(self.instruction[self.vectorId]['list'], key = lambda x: x[3])
  3567. for vector in vectors:
  3568. index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
  3569. self.vectorListCtrl.SetStringItem(index, 1, vector[4])
  3570. self.vectorListCtrl.SetItemData(index, index)
  3571. self.vectorListCtrl.CheckItem(index, True)
  3572. if vector[3] == 0:
  3573. self.vectorListCtrl.CheckItem(index, False)
  3574. if not self.vectorId:
  3575. self.vectorListCtrl.SetColumnWidth(0, 100)
  3576. else:
  3577. self.vectorListCtrl.SetColumnWidth(0, wx.LIST_AUTOSIZE)
  3578. self.vectorListCtrl.SetColumnWidth(1, wx.LIST_AUTOSIZE)
  3579. self.btnUp = wx.Button(panel, id = wx.ID_ANY, label = _("Up"))
  3580. self.btnDown = wx.Button(panel, id = wx.ID_ANY, label = _("Down"))
  3581. self.btnLabel = wx.Button(panel, id = wx.ID_ANY, label = _("Edit label"))
  3582. gridBagSizer.Add(vectorText, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3583. gridBagSizer.Add(self.vectorListCtrl, pos = (1,0), span = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3584. gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3585. gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3586. gridBagSizer.Add(self.btnLabel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3587. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3588. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3589. # size, position and font
  3590. self.sizePositionFont(legendType = 'vector', parent = panel, mainSizer = border)
  3591. # border
  3592. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Border"))
  3593. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3594. flexGridSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
  3595. self.borderCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw border around legend"))
  3596. self.borderColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY, style = wx.FNTP_FONTDESC_AS_LABEL)
  3597. if self.vLegendDict['border'] == 'none':
  3598. self.borderColorCtrl.SetColour(wx.BLACK)
  3599. self.borderCheck.SetValue(False)
  3600. else:
  3601. self.borderColorCtrl.SetColour(convertRGB(self.vLegendDict['border']))
  3602. self.borderCheck.SetValue(True)
  3603. flexGridSizer.Add(self.borderCheck, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3604. flexGridSizer.Add(self.borderColorCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3605. sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3606. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3607. self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp)
  3608. self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)
  3609. self.Bind(wx.EVT_BUTTON, self.OnEditLabel, self.btnLabel)
  3610. self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isVLegend)
  3611. self.Bind(wx.EVT_CHECKBOX, self.OnSpan, panel.spanRadio)
  3612. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck)
  3613. self.Bind(wx.EVT_FONTPICKER_CHANGED, self.OnFont, panel.font['fontCtrl'])
  3614. panel.SetSizer(border)
  3615. panel.Fit()
  3616. return panel
  3617. def sizePositionFont(self, legendType, parent, mainSizer):
  3618. """!Insert widgets for size, position and font control"""
  3619. if legendType == 'raster':
  3620. legendDict = self.rLegendDict
  3621. else:
  3622. legendDict = self.vLegendDict
  3623. panel = parent
  3624. border = mainSizer
  3625. # size and position
  3626. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size and position"))
  3627. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3628. #unit
  3629. self.AddUnits(parent = panel, dialogDict = legendDict)
  3630. unitBox = wx.BoxSizer(wx.HORIZONTAL)
  3631. unitBox.Add(panel.units['unitsLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
  3632. unitBox.Add(panel.units['unitsCtrl'], proportion = 1, flag = wx.ALL, border = 5)
  3633. sizer.Add(unitBox, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3634. hBox = wx.BoxSizer(wx.HORIZONTAL)
  3635. posBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Position"))
  3636. posSizer = wx.StaticBoxSizer(posBox, wx.VERTICAL)
  3637. sizeBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  3638. sizeSizer = wx.StaticBoxSizer(sizeBox, wx.VERTICAL)
  3639. posGridBagSizer = wx.GridBagSizer(hgap = 10, vgap = 5)
  3640. posGridBagSizer.AddGrowableRow(2)
  3641. #position
  3642. self.AddPosition(parent = panel, dialogDict = legendDict)
  3643. posGridBagSizer.Add(panel.position['xLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3644. posGridBagSizer.Add(panel.position['xCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3645. posGridBagSizer.Add(panel.position['yLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3646. posGridBagSizer.Add(panel.position['yCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3647. posGridBagSizer.Add(panel.position['comment'], pos = (2,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  3648. posSizer.Add(posGridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3649. #size
  3650. width = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width:"))
  3651. if legendDict['width']:
  3652. w = self.unitConv.convert(value = float(legendDict['width']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3653. else:
  3654. w = ''
  3655. panel.widthCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(w), validator = TCValidator("DIGIT_ONLY"))
  3656. panel.widthCtrl.SetToolTipString(_("Leave the edit field empty, to use default values."))
  3657. if legendType == 'raster':
  3658. ## panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size"))
  3659. ## panel.defaultSize.SetValue(legendDict['defaultSize'])
  3660. panel.heightOrColumnsLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
  3661. if legendDict['height']:
  3662. h = self.unitConv.convert(value = float(legendDict['height']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3663. else:
  3664. h = ''
  3665. panel.heightOrColumnsCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(h), validator = TCValidator("DIGIT_ONLY"))
  3666. self.rSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3667. ## self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3668. self.rSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3669. self.rSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3670. self.rSizeGBSizer.Add(panel.heightOrColumnsLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3671. self.rSizeGBSizer.Add(panel.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3672. sizeSizer.Add(self.rSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3673. if legendType == 'vector':
  3674. panel.widthCtrl.SetToolTipString(_("Width of the color symbol (for lines)\nin front of the legend text"))
  3675. #columns
  3676. minVect, maxVect = 0, 0
  3677. if self.vectorId:
  3678. minVect = 1
  3679. maxVect = min(10, len(self.instruction[self.vectorId]['list']))
  3680. cols = wx.StaticText(panel, id = wx.ID_ANY, label = _("Columns:"))
  3681. panel.colsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, value = "",
  3682. min = minVect, max = maxVect, initial = legendDict['cols'])
  3683. #span
  3684. panel.spanRadio = wx.CheckBox(panel, id = wx.ID_ANY, label = _("column span:"))
  3685. panel.spanTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = '')
  3686. panel.spanTextCtrl.SetToolTipString(_("Column separation distance between the left edges\n"\
  3687. "of two columns in a multicolumn legend"))
  3688. if legendDict['span']:
  3689. panel.spanRadio.SetValue(True)
  3690. s = self.unitConv.convert(value = float(legendDict['span']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3691. panel.spanTextCtrl.SetValue(str(s))
  3692. else:
  3693. panel.spanRadio.SetValue(False)
  3694. self.vSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3695. self.vSizeGBSizer.AddGrowableCol(1)
  3696. self.vSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3697. self.vSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3698. self.vSizeGBSizer.Add(cols, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3699. self.vSizeGBSizer.Add(panel.colsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3700. self.vSizeGBSizer.Add(panel.spanRadio, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3701. self.vSizeGBSizer.Add(panel.spanTextCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3702. sizeSizer.Add(self.vSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3703. hBox.Add(posSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
  3704. hBox.Add(sizeSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
  3705. sizer.Add(hBox, proportion = 0, flag = wx.EXPAND, border = 0)
  3706. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3707. # font
  3708. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  3709. fontSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3710. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  3711. flexSizer.AddGrowableCol(1)
  3712. if legendType == 'raster':
  3713. self.AddFont(parent = panel, dialogDict = legendDict, color = True)
  3714. else:
  3715. self.AddFont(parent = panel, dialogDict = legendDict, color = False)
  3716. flexSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3717. flexSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3718. flexSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3719. flexSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3720. if legendType == 'raster':
  3721. flexSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3722. flexSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3723. fontSizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3724. border.Add(item = fontSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3725. # some enable/disable methods
  3726. def OnIsLegend(self, event):
  3727. """!Enables and disables controls, it depends if raster or vector legend is checked"""
  3728. page = self.notebook.GetSelection()
  3729. if page == 0 or event is None:
  3730. children = self.panelRaster.GetChildren()
  3731. if self.isRLegend.GetValue():
  3732. for i,widget in enumerate(children):
  3733. widget.Enable()
  3734. self.OnRaster(None)
  3735. self.OnRange(None)
  3736. self.OnDiscrete(None)
  3737. else:
  3738. for widget in children:
  3739. if widget.GetName() != 'showRLegend':
  3740. widget.Disable()
  3741. if page == 1 or event is None:
  3742. children = self.panelVector.GetChildren()
  3743. if self.isVLegend.GetValue():
  3744. for i, widget in enumerate(children):
  3745. widget.Enable()
  3746. self.OnSpan(None)
  3747. self.OnBorder(None)
  3748. else:
  3749. for widget in children:
  3750. if widget.GetName() != 'showVLegend':
  3751. widget.Disable()
  3752. def OnRaster(self, event):
  3753. if self.rasterDefault.GetValue():#default
  3754. self.rasterSelect.Disable()
  3755. type = getRasterType(self.currRaster)
  3756. else:#select raster
  3757. self.rasterSelect.Enable()
  3758. map = self.rasterSelect.GetValue()
  3759. type = getRasterType(map)
  3760. if type == 'CELL':
  3761. self.discrete.SetValue(True)
  3762. elif type in ('FCELL', 'DCELL'):
  3763. self.continuous.SetValue(True)
  3764. if event is None:
  3765. if self.rLegendDict['discrete'] == 'y':
  3766. self.discrete.SetValue(True)
  3767. elif self.rLegendDict['discrete'] == 'n':
  3768. self.continuous.SetValue(True)
  3769. self.OnDiscrete(None)
  3770. def OnDiscrete(self, event):
  3771. """! Change control according to the type of legend"""
  3772. enabledSize = self.panelRaster.heightOrColumnsCtrl.IsEnabled()
  3773. self.panelRaster.heightOrColumnsCtrl.Destroy()
  3774. if self.discrete.GetValue():
  3775. self.panelRaster.heightOrColumnsLabel.SetLabel(_("Columns:"))
  3776. self.panelRaster.heightOrColumnsCtrl = wx.SpinCtrl(self.panelRaster, id = wx.ID_ANY, value = "", min = 1, max = 10, initial = self.rLegendDict['cols'])
  3777. self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
  3778. self.nodata.Enable()
  3779. self.range.Disable()
  3780. self.min.Disable()
  3781. self.max.Disable()
  3782. self.minText.Disable()
  3783. self.maxText.Disable()
  3784. self.ticks.Disable()
  3785. else:
  3786. self.panelRaster.heightOrColumnsLabel.SetLabel(_("Height:"))
  3787. if self.rLegendDict['height']:
  3788. h = self.unitConv.convert(value = float(self.rLegendDict['height']), fromUnit = 'inch', toUnit = self.rLegendDict['unit'])
  3789. else:
  3790. h = ''
  3791. self.panelRaster.heightOrColumnsCtrl = wx.TextCtrl(self.panelRaster, id = wx.ID_ANY,
  3792. value = str(h), validator = TCValidator("DIGIT_ONLY"))
  3793. self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
  3794. self.nodata.Disable()
  3795. self.range.Enable()
  3796. if self.range.GetValue():
  3797. self.minText.Enable()
  3798. self.maxText.Enable()
  3799. self.min.Enable()
  3800. self.max.Enable()
  3801. self.ticks.Enable()
  3802. self.rSizeGBSizer.Add(self.panelRaster.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3803. self.panelRaster.Layout()
  3804. self.panelRaster.Fit()
  3805. def OnRange(self, event):
  3806. if not self.range.GetValue():
  3807. self.min.Disable()
  3808. self.max.Disable()
  3809. self.minText.Disable()
  3810. self.maxText.Disable()
  3811. else:
  3812. self.min.Enable()
  3813. self.max.Enable()
  3814. self.minText.Enable()
  3815. self.maxText.Enable()
  3816. def OnUp(self, event):
  3817. """!Moves selected map up, changes order in vector legend"""
  3818. if self.vectorListCtrl.GetFirstSelected() != -1:
  3819. pos = self.vectorListCtrl.GetFirstSelected()
  3820. if pos:
  3821. idx1 = self.vectorListCtrl.GetItemData(pos) - 1
  3822. idx2 = self.vectorListCtrl.GetItemData(pos - 1) + 1
  3823. self.vectorListCtrl.SetItemData(pos, idx1)
  3824. self.vectorListCtrl.SetItemData(pos - 1, idx2)
  3825. self.vectorListCtrl.SortItems(cmp)
  3826. if pos > 0:
  3827. selected = (pos - 1)
  3828. else:
  3829. selected = 0
  3830. self.vectorListCtrl.Select(selected)
  3831. def OnDown(self, event):
  3832. """!Moves selected map down, changes order in vector legend"""
  3833. if self.vectorListCtrl.GetFirstSelected() != -1:
  3834. pos = self.vectorListCtrl.GetFirstSelected()
  3835. if pos != self.vectorListCtrl.GetItemCount() - 1:
  3836. idx1 = self.vectorListCtrl.GetItemData(pos) + 1
  3837. idx2 = self.vectorListCtrl.GetItemData(pos + 1) - 1
  3838. self.vectorListCtrl.SetItemData(pos, idx1)
  3839. self.vectorListCtrl.SetItemData(pos + 1, idx2)
  3840. self.vectorListCtrl.SortItems(cmp)
  3841. if pos < self.vectorListCtrl.GetItemCount() -1:
  3842. selected = (pos + 1)
  3843. else:
  3844. selected = self.vectorListCtrl.GetItemCount() -1
  3845. self.vectorListCtrl.Select(selected)
  3846. def OnEditLabel(self, event):
  3847. """!Change legend label of vector map"""
  3848. if self.vectorListCtrl.GetFirstSelected() != -1:
  3849. idx = self.vectorListCtrl.GetFirstSelected()
  3850. default = self.vectorListCtrl.GetItem(idx, 1).GetText()
  3851. dlg = wx.TextEntryDialog(self, message = _("Edit legend label:"), caption = _("Edit label"),
  3852. defaultValue = default, style = wx.OK|wx.CANCEL|wx.CENTRE)
  3853. if dlg.ShowModal() == wx.ID_OK:
  3854. new = dlg.GetValue()
  3855. self.vectorListCtrl.SetStringItem(idx, 1, new)
  3856. dlg.Destroy()
  3857. def OnSpan(self, event):
  3858. self.panelVector.spanTextCtrl.Enable(self.panelVector.spanRadio.GetValue())
  3859. def OnFont(self, event):
  3860. """!Changes default width according to fontsize, width [inch] = fontsize[pt]/24"""
  3861. ## fontsize = self.panelVector.font['fontCtrl'].GetSelectedFont().GetPointSize()
  3862. fontsize = self.panelVector.font['fontSizeCtrl'].GetValue()
  3863. unit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
  3864. w = fontsize/24.
  3865. width = self.unitConv.convert(value = w, fromUnit = 'inch', toUnit = unit)
  3866. self.panelVector.widthCtrl.SetValue("%3.2f" % width)
  3867. def OnBorder(self, event):
  3868. """!Enables/disables colorPickerCtrl for border"""
  3869. self.borderColorCtrl.Enable(self.borderCheck.GetValue())
  3870. def updateRasterLegend(self):
  3871. """!Save information from raster legend dialog to dictionary"""
  3872. #is raster legend
  3873. if not self.isRLegend.GetValue():
  3874. self.rLegendDict['rLegend'] = False
  3875. else:
  3876. self.rLegendDict['rLegend'] = True
  3877. #units
  3878. currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection())
  3879. self.rLegendDict['unit'] = currUnit
  3880. # raster
  3881. if self.rasterDefault.GetValue():
  3882. self.rLegendDict['rasterDefault'] = True
  3883. self.rLegendDict['raster'] = self.currRaster
  3884. else:
  3885. self.rLegendDict['rasterDefault'] = False
  3886. self.rLegendDict['raster'] = self.rasterSelect.GetValue()
  3887. if self.rLegendDict['rLegend'] and not self.rLegendDict['raster']:
  3888. wx.MessageBox(message = _("No raster map selected!"),
  3889. caption = _('No raster'), style = wx.OK|wx.ICON_ERROR)
  3890. return False
  3891. if self.rLegendDict['raster']:
  3892. # type and range of map
  3893. rasterType = getRasterType(self.rLegendDict['raster'])
  3894. if rasterType is None:
  3895. return False
  3896. self.rLegendDict['type'] = rasterType
  3897. #discrete
  3898. if self.discrete.GetValue():
  3899. self.rLegendDict['discrete'] = 'y'
  3900. else:
  3901. self.rLegendDict['discrete'] = 'n'
  3902. # font
  3903. self.rLegendDict['font'] = self.panelRaster.font['fontCtrl'].GetStringSelection()
  3904. self.rLegendDict['fontsize'] = self.panelRaster.font['fontSizeCtrl'].GetValue()
  3905. color = self.panelRaster.font['colorCtrl'].GetColour()
  3906. self.rLegendDict['color'] = convertRGB(color)
  3907. # position
  3908. x = self.unitConv.convert(value = float(self.panelRaster.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3909. y = self.unitConv.convert(value = float(self.panelRaster.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3910. self.rLegendDict['where'] = (x, y)
  3911. # estimated size
  3912. width = self.panelRaster.widthCtrl.GetValue()
  3913. try:
  3914. width = float(width)
  3915. width = self.unitConv.convert(value = width, fromUnit = currUnit, toUnit = 'inch')
  3916. except ValueError:
  3917. width = None
  3918. self.rLegendDict['width'] = width
  3919. if self.rLegendDict['discrete'] == 'n':
  3920. height = self.panelRaster.heightOrColumnsCtrl.GetValue()
  3921. try:
  3922. height = float(height)
  3923. height = self.unitConv.convert(value = height, fromUnit = currUnit, toUnit = 'inch')
  3924. except ValueError:
  3925. height = None
  3926. self.rLegendDict['height'] = height
  3927. else:
  3928. cols = self.panelRaster.heightOrColumnsCtrl.GetValue()
  3929. self.rLegendDict['cols'] = cols
  3930. drawHeight = self.rasterLegend.EstimateHeight(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
  3931. fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
  3932. height = self.rLegendDict['height'])
  3933. drawWidth = self.rasterLegend.EstimateWidth(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
  3934. fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
  3935. width = self.rLegendDict['width'], paperInstr = self.instruction[self.pageId])
  3936. self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
  3937. # no data
  3938. if self.rLegendDict['discrete'] == 'y':
  3939. if self.nodata.GetValue():
  3940. self.rLegendDict['nodata'] = 'y'
  3941. else:
  3942. self.rLegendDict['nodata'] = 'n'
  3943. # tickbar
  3944. elif self.rLegendDict['discrete'] == 'n':
  3945. if self.ticks.GetValue():
  3946. self.rLegendDict['tickbar'] = 'y'
  3947. else:
  3948. self.rLegendDict['tickbar'] = 'n'
  3949. # range
  3950. if self.range.GetValue():
  3951. self.rLegendDict['range'] = True
  3952. self.rLegendDict['min'] = self.min.GetValue()
  3953. self.rLegendDict['max'] = self.max.GetValue()
  3954. else:
  3955. self.rLegendDict['range'] = False
  3956. if not self.id[0] in self.instruction:
  3957. rasterLegend = RasterLegend(self.id[0])
  3958. self.instruction.AddInstruction(rasterLegend)
  3959. self.instruction[self.id[0]].SetInstruction(self.rLegendDict)
  3960. if self.id[0] not in self.parent.objectId:
  3961. self.parent.objectId.append(self.id[0])
  3962. return True
  3963. def updateVectorLegend(self):
  3964. """!Save information from vector legend dialog to dictionary"""
  3965. vector = self.instruction.FindInstructionByType('vector')
  3966. if vector:
  3967. self.vectorId = vector.id
  3968. else:
  3969. self.vectorId = None
  3970. #is vector legend
  3971. if not self.isVLegend.GetValue():
  3972. self.vLegendDict['vLegend'] = False
  3973. else:
  3974. self.vLegendDict['vLegend'] = True
  3975. if self.vLegendDict['vLegend'] == True and self.vectorId is not None:
  3976. # labels
  3977. #reindex order
  3978. idx = 1
  3979. for item in range(self.vectorListCtrl.GetItemCount()):
  3980. if self.vectorListCtrl.IsChecked(item):
  3981. self.vectorListCtrl.SetItemData(item, idx)
  3982. idx += 1
  3983. else:
  3984. self.vectorListCtrl.SetItemData(item, 0)
  3985. if idx == 1:
  3986. self.vLegendDict['vLegend'] = False
  3987. else:
  3988. vList = self.instruction[self.vectorId]['list']
  3989. for i, vector in enumerate(vList):
  3990. item = self.vectorListCtrl.FindItem(start = -1, str = vector[0].split('@')[0])
  3991. vList[i][3] = self.vectorListCtrl.GetItemData(item)
  3992. vList[i][4] = self.vectorListCtrl.GetItem(item, 1).GetText()
  3993. vmaps = self.instruction.FindInstructionByType('vProperties', list = True)
  3994. for vmap, vector in zip(vmaps, vList):
  3995. self.instruction[vmap.id]['lpos'] = vector[3]
  3996. self.instruction[vmap.id]['label'] = vector[4]
  3997. #units
  3998. currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
  3999. self.vLegendDict['unit'] = currUnit
  4000. # position
  4001. x = self.unitConv.convert(value = float(self.panelVector.position['xCtrl'].GetValue()),
  4002. fromUnit = currUnit, toUnit = 'inch')
  4003. y = self.unitConv.convert(value = float(self.panelVector.position['yCtrl'].GetValue()),
  4004. fromUnit = currUnit, toUnit = 'inch')
  4005. self.vLegendDict['where'] = (x, y)
  4006. # font
  4007. self.vLegendDict['font'] = self.panelVector.font['fontCtrl'].GetStringSelection()
  4008. self.vLegendDict['fontsize'] = self.panelVector.font['fontSizeCtrl'].GetValue()
  4009. dc = wx.PaintDC(self)
  4010. font = dc.GetFont()
  4011. dc.SetFont(wx.Font(pointSize = self.vLegendDict['fontsize'], family = font.GetFamily(),
  4012. style = font.GetStyle(), weight = wx.FONTWEIGHT_NORMAL))
  4013. #size
  4014. width = self.unitConv.convert(value = float(self.panelVector.widthCtrl.GetValue()),
  4015. fromUnit = currUnit, toUnit = 'inch')
  4016. self.vLegendDict['width'] = width
  4017. self.vLegendDict['cols'] = self.panelVector.colsCtrl.GetValue()
  4018. if self.panelVector.spanRadio.GetValue() and self.panelVector.spanTextCtrl.GetValue():
  4019. self.vLegendDict['span'] = self.panelVector.spanTextCtrl.GetValue()
  4020. else:
  4021. self.vLegendDict['span'] = None
  4022. # size estimation
  4023. vectors = self.instruction[self.vectorId]['list']
  4024. labels = [vector[4] for vector in vectors if vector[3] != 0]
  4025. extent = dc.GetTextExtent(max(labels, key = len))
  4026. wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'pixel', toUnit = 'inch')
  4027. hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'pixel', toUnit = 'inch')
  4028. w = (width + wExtent) * self.vLegendDict['cols']
  4029. h = len(labels) * hExtent / self.vLegendDict['cols']
  4030. h *= 1.1
  4031. self.vLegendDict['rect'] = wx.Rect2D(x, y, w, h)
  4032. #border
  4033. if self.borderCheck.GetValue():
  4034. color = self.borderColorCtrl.GetColour()
  4035. self.vLegendDict['border'] = convertRGB(color)
  4036. else:
  4037. self.vLegendDict['border'] = 'none'
  4038. if not self.id[1] in self.instruction:
  4039. vectorLegend = VectorLegend(self.id[1])
  4040. self.instruction.AddInstruction(vectorLegend)
  4041. self.instruction[self.id[1]].SetInstruction(self.vLegendDict)
  4042. if self.id[1] not in self.parent.objectId:
  4043. self.parent.objectId.append(self.id[1])
  4044. return True
  4045. def update(self):
  4046. okR = self.updateRasterLegend()
  4047. okV = self.updateVectorLegend()
  4048. if okR and okV:
  4049. return True
  4050. return False
  4051. def updateDialog(self):
  4052. """!Update legend coordinates after moving"""
  4053. # raster legend
  4054. if 'rect' in self.rLegendDict:
  4055. x, y = self.rLegendDict['rect'][:2]
  4056. currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection())
  4057. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4058. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4059. self.panelRaster.position['xCtrl'].SetValue("%5.3f" % x)
  4060. self.panelRaster.position['yCtrl'].SetValue("%5.3f" % y)
  4061. #update name and type of raster
  4062. raster = self.instruction.FindInstructionByType('raster')
  4063. if raster:
  4064. self.rasterId = raster.id
  4065. else:
  4066. self.rasterId = None
  4067. if raster:
  4068. currRaster = raster['raster']
  4069. else:
  4070. currRaster = None
  4071. rasterType = getRasterType(map = currRaster)
  4072. self.rasterCurrent.SetLabel(_("%(rast)s: type %(type)s") % \
  4073. { 'rast' : currRaster, 'type' : str(rasterType) })
  4074. # vector legend
  4075. if 'rect' in self.vLegendDict:
  4076. x, y = self.vLegendDict['rect'][:2]
  4077. currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection())
  4078. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4079. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4080. self.panelVector.position['xCtrl'].SetValue("%5.3f" % x)
  4081. self.panelVector.position['yCtrl'].SetValue("%5.3f" % y)
  4082. # update vector maps
  4083. if self.instruction.FindInstructionByType('vector'):
  4084. vectors = sorted(self.instruction.FindInstructionByType('vector')['list'], key = lambda x: x[3])
  4085. self.vectorListCtrl.DeleteAllItems()
  4086. for vector in vectors:
  4087. index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
  4088. self.vectorListCtrl.SetStringItem(index, 1, vector[4])
  4089. self.vectorListCtrl.SetItemData(index, index)
  4090. self.vectorListCtrl.CheckItem(index, True)
  4091. if vector[3] == 0:
  4092. self.vectorListCtrl.CheckItem(index, False)
  4093. self.panelVector.colsCtrl.SetRange(1, min(10, len(self.instruction.FindInstructionByType('vector')['list'])))
  4094. self.panelVector.colsCtrl.SetValue(1)
  4095. else:
  4096. self.vectorListCtrl.DeleteAllItems()
  4097. self.panelVector.colsCtrl.SetRange(0,0)
  4098. self.panelVector.colsCtrl.SetValue(0)
  4099. class MapinfoDialog(PsmapDialog):
  4100. def __init__(self, parent, id, settings):
  4101. PsmapDialog.__init__(self, parent = parent, id = id, title = "Mapinfo settings", settings = settings)
  4102. self.objectType = ('mapinfo',)
  4103. if self.id is not None:
  4104. self.mapinfo = self.instruction[self.id]
  4105. self.mapinfoDict = self.mapinfo.GetInstruction()
  4106. else:
  4107. self.id = wx.NewId()
  4108. self.mapinfo = Mapinfo(self.id)
  4109. self.mapinfoDict = self.mapinfo.GetInstruction()
  4110. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4111. self.mapinfoDict['where'] = page['Left'], page['Top']
  4112. self.panel = self._mapinfoPanel()
  4113. self._layout(self.panel)
  4114. self.OnIsBackground(None)
  4115. self.OnIsBorder(None)
  4116. def _mapinfoPanel(self):
  4117. panel = wx.Panel(parent = self, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  4118. #panel.SetupScrolling(scroll_x = False, scroll_y = True)
  4119. border = wx.BoxSizer(wx.VERTICAL)
  4120. # position
  4121. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4122. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4123. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4124. gridBagSizer.AddGrowableCol(1)
  4125. self.AddPosition(parent = panel, dialogDict = self.mapinfoDict)
  4126. self.AddUnits(parent = panel, dialogDict = self.mapinfoDict)
  4127. gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4128. gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4129. gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4130. gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4131. gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4132. gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4133. gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  4134. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4135. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4136. # font
  4137. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  4138. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4139. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4140. gridBagSizer.AddGrowableCol(1)
  4141. self.AddFont(parent = panel, dialogDict = self.mapinfoDict)#creates font color too, used below
  4142. gridBagSizer.Add(panel.font['fontLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4143. gridBagSizer.Add(panel.font['fontCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4144. gridBagSizer.Add(panel.font['fontSizeLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4145. gridBagSizer.Add(panel.font['fontSizeCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4146. gridBagSizer.Add(panel.font['colorLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4147. gridBagSizer.Add(panel.font['colorCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4148. sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4149. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4150. # colors
  4151. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Color settings"))
  4152. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4153. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  4154. flexSizer.AddGrowableCol(1)
  4155. self.colors = {}
  4156. self.colors['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use border color:"))
  4157. self.colors['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use background color:"))
  4158. self.colors['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4159. self.colors['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4160. if self.mapinfoDict['border'] == None:
  4161. self.mapinfoDict['border'] = 'none'
  4162. if self.mapinfoDict['border'] != 'none':
  4163. self.colors['borderCtrl'].SetValue(True)
  4164. self.colors['borderColor'].SetColour(convertRGB(self.mapinfoDict['border']))
  4165. else:
  4166. self.colors['borderCtrl'].SetValue(False)
  4167. self.colors['borderColor'].SetColour(convertRGB('black'))
  4168. if self.mapinfoDict['background'] == None:
  4169. self.mapinfoDict['background'] == 'none'
  4170. if self.mapinfoDict['background'] != 'none':
  4171. self.colors['backgroundCtrl'].SetValue(True)
  4172. self.colors['backgroundColor'].SetColour(convertRGB(self.mapinfoDict['background']))
  4173. else:
  4174. self.colors['backgroundCtrl'].SetValue(False)
  4175. self.colors['backgroundColor'].SetColour(convertRGB('white'))
  4176. flexSizer.Add(self.colors['borderCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4177. flexSizer.Add(self.colors['borderColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4178. flexSizer.Add(self.colors['backgroundCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4179. flexSizer.Add(self.colors['backgroundColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4180. sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4181. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4182. panel.SetSizer(border)
  4183. self.Bind(wx.EVT_CHECKBOX, self.OnIsBorder, self.colors['borderCtrl'])
  4184. self.Bind(wx.EVT_CHECKBOX, self.OnIsBackground, self.colors['backgroundCtrl'])
  4185. return panel
  4186. def OnIsBackground(self, event):
  4187. if self.colors['backgroundCtrl'].GetValue():
  4188. self.colors['backgroundColor'].Enable()
  4189. self.update()
  4190. else:
  4191. self.colors['backgroundColor'].Disable()
  4192. def OnIsBorder(self, event):
  4193. if self.colors['borderCtrl'].GetValue():
  4194. self.colors['borderColor'].Enable()
  4195. self.update()
  4196. else:
  4197. self.colors['borderColor'].Disable()
  4198. def update(self):
  4199. #units
  4200. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4201. self.mapinfoDict['unit'] = currUnit
  4202. # position
  4203. if self.panel.position['xCtrl'].GetValue():
  4204. x = self.panel.position['xCtrl'].GetValue()
  4205. else:
  4206. x = self.mapinfoDict['where'][0]
  4207. if self.panel.position['yCtrl'].GetValue():
  4208. y = self.panel.position['yCtrl'].GetValue()
  4209. else:
  4210. y = self.mapinfoDict['where'][1]
  4211. x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4212. y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4213. self.mapinfoDict['where'] = (x, y)
  4214. # font
  4215. self.mapinfoDict['font'] = self.panel.font['fontCtrl'].GetStringSelection()
  4216. self.mapinfoDict['fontsize'] = self.panel.font['fontSizeCtrl'].GetValue()
  4217. #colors
  4218. color = self.panel.font['colorCtrl'].GetColour()
  4219. self.mapinfoDict['color'] = convertRGB(color)
  4220. if self.colors['backgroundCtrl'].GetValue():
  4221. background = self.colors['backgroundColor'].GetColour()
  4222. self.mapinfoDict['background'] = convertRGB(background)
  4223. else:
  4224. self.mapinfoDict['background'] = 'none'
  4225. if self.colors['borderCtrl'].GetValue():
  4226. border = self.colors['borderColor'].GetColour()
  4227. self.mapinfoDict['border'] = convertRGB(border)
  4228. else:
  4229. self.mapinfoDict['border'] = 'none'
  4230. # estimation of size
  4231. self.mapinfoDict['rect'] = self.mapinfo.EstimateRect(self.mapinfoDict)
  4232. if self.id not in self.instruction:
  4233. mapinfo = Mapinfo(self.id)
  4234. self.instruction.AddInstruction(mapinfo)
  4235. self.instruction[self.id].SetInstruction(self.mapinfoDict)
  4236. if self.id not in self.parent.objectId:
  4237. self.parent.objectId.append(self.id)
  4238. self.updateDialog()
  4239. return True
  4240. def updateDialog(self):
  4241. """!Update mapinfo coordinates, after moving"""
  4242. x, y = self.mapinfoDict['where']
  4243. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4244. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4245. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4246. self.panel.position['xCtrl'].SetValue("%5.3f" % x)
  4247. self.panel.position['yCtrl'].SetValue("%5.3f" % y)
  4248. class ScalebarDialog(PsmapDialog):
  4249. """!Dialog for scale bar"""
  4250. def __init__(self, parent, id, settings):
  4251. PsmapDialog.__init__(self, parent = parent, id = id, title = "Scale bar settings", settings = settings)
  4252. self.objectType = ('scalebar',)
  4253. if self.id is not None:
  4254. self.scalebar = self.instruction[id]
  4255. self.scalebarDict = self.scalebar.GetInstruction()
  4256. else:
  4257. self.id = wx.NewId()
  4258. self.scalebar = Scalebar(self.id)
  4259. self.scalebarDict = self.scalebar.GetInstruction()
  4260. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4261. self.scalebarDict['where'] = page['Left'], page['Top']
  4262. self.panel = self._scalebarPanel()
  4263. self._layout(self.panel)
  4264. self.mapUnit = projInfo()['units'].lower()
  4265. if projInfo()['proj'] == 'xy':
  4266. self.mapUnit = 'meters'
  4267. if self.mapUnit not in self.unitConv.getAllUnits():
  4268. wx.MessageBox(message = _("Units of current projection are not supported,\n meters will be used!"),
  4269. caption = _('Unsupported units'),
  4270. style = wx.OK|wx.ICON_ERROR)
  4271. self.mapUnit = 'meters'
  4272. def _scalebarPanel(self):
  4273. panel = wx.Panel(parent = self, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4274. border = wx.BoxSizer(wx.VERTICAL)
  4275. #
  4276. # position
  4277. #
  4278. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4279. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4280. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4281. gridBagSizer.AddGrowableCol(1)
  4282. self.AddUnits(parent = panel, dialogDict = self.scalebarDict)
  4283. self.AddPosition(parent = panel, dialogDict = self.scalebarDict)
  4284. if self.scalebarDict['rect']: # set position, ref point is center and not left top corner
  4285. x = self.unitConv.convert(value = self.scalebarDict['where'][0] - self.scalebarDict['rect'].Get()[2]/2,
  4286. fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
  4287. y = self.unitConv.convert(value = self.scalebarDict['where'][1] - self.scalebarDict['rect'].Get()[3]/2,
  4288. fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
  4289. panel.position['xCtrl'].SetValue("%5.3f" % x)
  4290. panel.position['yCtrl'].SetValue("%5.3f" % y)
  4291. gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4292. gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4293. gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4294. gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4295. gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4296. gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4297. gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  4298. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4299. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4300. #
  4301. # size
  4302. #
  4303. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  4304. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4305. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4306. gridBagSizer.AddGrowableCol(1)
  4307. lengthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Length:"))
  4308. heightText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
  4309. self.lengthTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
  4310. self.lengthTextCtrl.SetToolTipString(_("Scalebar length is given in map units"))
  4311. self.heightTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
  4312. self.heightTextCtrl.SetToolTipString(_("Scalebar height is real height on paper"))
  4313. choices = [_('default')] + self.unitConv.getMapUnitsNames()
  4314. self.unitsLength = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
  4315. choices = self.unitConv.getPageUnitsNames()
  4316. self.unitsHeight = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
  4317. # set values
  4318. unitName = self.unitConv.findName(self.scalebarDict['unitsLength'])
  4319. if unitName:
  4320. self.unitsLength.SetStringSelection(unitName)
  4321. else:
  4322. if self.scalebarDict['unitsLength'] == 'auto':
  4323. self.unitsLength.SetSelection(0)
  4324. elif self.scalebarDict['unitsLength'] == 'nautmiles':
  4325. self.unitsLength.SetStringSelection(self.unitConv.findName("nautical miles"))
  4326. self.unitsHeight.SetStringSelection(self.unitConv.findName(self.scalebarDict['unitsHeight']))
  4327. if self.scalebarDict['length']:
  4328. self.lengthTextCtrl.SetValue(str(self.scalebarDict['length']))
  4329. else: #estimate default
  4330. reg = grass.region()
  4331. w = int((reg['e'] - reg['w'])/3)
  4332. w = round(w, -len(str(w)) + 2) #12345 -> 12000
  4333. self.lengthTextCtrl.SetValue(str(w))
  4334. h = self.unitConv.convert(value = self.scalebarDict['height'], fromUnit = 'inch',
  4335. toUnit = self.scalebarDict['unitsHeight'])
  4336. self.heightTextCtrl.SetValue(str(h))
  4337. gridBagSizer.Add(lengthText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4338. gridBagSizer.Add(self.lengthTextCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4339. gridBagSizer.Add(self.unitsLength, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4340. gridBagSizer.Add(heightText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4341. gridBagSizer.Add(self.heightTextCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4342. gridBagSizer.Add(self.unitsHeight, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4343. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4344. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4345. #
  4346. #style
  4347. #
  4348. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Style"))
  4349. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4350. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4351. sbTypeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Type:"))
  4352. self.sbCombo = wx.combo.BitmapComboBox(panel, style = wx.CB_READONLY)
  4353. # only temporary, images must be moved away
  4354. imagePath = os.path.join(globalvar.ETCIMGDIR, "scalebar-fancy.png"), os.path.join(globalvar.ETCIMGDIR, "scalebar-simple.png")
  4355. for item, path in zip(['fancy', 'simple'], imagePath):
  4356. if not os.path.exists(path):
  4357. bitmap = wx.EmptyBitmap(0,0)
  4358. else:
  4359. bitmap = wx.Bitmap(path)
  4360. self.sbCombo.Append(item = '', bitmap = bitmap, clientData = item[0])
  4361. #self.sbCombo.Append(item = 'simple', bitmap = wx.Bitmap("./images/scalebar-simple.png"), clientData = 's')
  4362. if self.scalebarDict['scalebar'] == 'f':
  4363. self.sbCombo.SetSelection(0)
  4364. elif self.scalebarDict['scalebar'] == 's':
  4365. self.sbCombo.SetSelection(1)
  4366. sbSegmentsText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Number of segments:"))
  4367. self.sbSegmentsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 4)
  4368. self.sbSegmentsCtrl.SetValue(self.scalebarDict['segment'])
  4369. sbLabelsText1 = wx.StaticText(panel, id = wx.ID_ANY, label = _("Label every "))
  4370. sbLabelsText2 = wx.StaticText(panel, id = wx.ID_ANY, label = _("segments"))
  4371. self.sbLabelsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1)
  4372. self.sbLabelsCtrl.SetValue(self.scalebarDict['numbers'])
  4373. #font
  4374. fontsizeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Font size:"))
  4375. self.fontsizeCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 4, max = 30, initial = 10)
  4376. self.fontsizeCtrl.SetValue(self.scalebarDict['fontsize'])
  4377. self.backgroundCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent text background"))
  4378. if self.scalebarDict['background'] == 'y':
  4379. self.backgroundCheck.SetValue(False)
  4380. else:
  4381. self.backgroundCheck.SetValue(True)
  4382. gridBagSizer.Add(sbTypeText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4383. gridBagSizer.Add(self.sbCombo, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4384. gridBagSizer.Add(sbSegmentsText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4385. gridBagSizer.Add(self.sbSegmentsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4386. gridBagSizer.Add(sbLabelsText1, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4387. gridBagSizer.Add(self.sbLabelsCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4388. gridBagSizer.Add(sbLabelsText2, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4389. gridBagSizer.Add(fontsizeText, pos = (3,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4390. gridBagSizer.Add(self.fontsizeCtrl, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4391. gridBagSizer.Add(self.backgroundCheck, pos = (4, 0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4392. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL, border = 5)
  4393. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4394. panel.SetSizer(border)
  4395. return panel
  4396. def update(self):
  4397. """!Save information from dialog"""
  4398. #units
  4399. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4400. self.scalebarDict['unit'] = currUnit
  4401. # position
  4402. if self.panel.position['xCtrl'].GetValue():
  4403. x = self.panel.position['xCtrl'].GetValue()
  4404. else:
  4405. x = self.scalebarDict['where'][0]
  4406. if self.panel.position['yCtrl'].GetValue():
  4407. y = self.panel.position['yCtrl'].GetValue()
  4408. else:
  4409. y = self.scalebarDict['where'][1]
  4410. x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4411. y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4412. #style
  4413. self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(self.sbCombo.GetSelection())
  4414. self.scalebarDict['segment'] = self.sbSegmentsCtrl.GetValue()
  4415. self.scalebarDict['numbers'] = self.sbLabelsCtrl.GetValue()
  4416. self.scalebarDict['fontsize'] = self.fontsizeCtrl.GetValue()
  4417. if self.backgroundCheck.GetValue():
  4418. self.scalebarDict['background'] = 'n'
  4419. else:
  4420. self.scalebarDict['background'] = 'y'
  4421. # size
  4422. # height
  4423. self.scalebarDict['unitsHeight'] = self.unitConv.findUnit(self.unitsHeight.GetStringSelection())
  4424. try:
  4425. height = float(self.heightTextCtrl.GetValue())
  4426. height = self.unitConv.convert(value = height, fromUnit = self.scalebarDict['unitsHeight'], toUnit = 'inch')
  4427. except (ValueError, SyntaxError):
  4428. height = 0.1 #default in inch
  4429. self.scalebarDict['height'] = height
  4430. #length
  4431. if self.unitsLength.GetSelection() == 0:
  4432. selected = 'auto'
  4433. else:
  4434. selected = self.unitConv.findUnit(self.unitsLength.GetStringSelection())
  4435. if selected == 'nautical miles':
  4436. selected = 'nautmiles'
  4437. self.scalebarDict['unitsLength'] = selected
  4438. try:
  4439. length = float(self.lengthTextCtrl.GetValue())
  4440. except (ValueError, SyntaxError):
  4441. wx.MessageBox(message = _("Length of scale bar is not defined"),
  4442. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  4443. return False
  4444. self.scalebarDict['length'] = length
  4445. # estimation of size
  4446. map = self.instruction.FindInstructionByType('map')
  4447. if not map:
  4448. map = self.instruction.FindInstructionByType('initMap')
  4449. mapId = map.id
  4450. rectSize = self.scalebar.EstimateSize(scalebarDict = self.scalebarDict,
  4451. scale = self.instruction[mapId]['scale'])
  4452. self.scalebarDict['rect'] = wx.Rect2D(x = x, y = y, w = rectSize[0], h = rectSize[1])
  4453. self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre()
  4454. if self.id not in self.instruction:
  4455. scalebar = Scalebar(self.id)
  4456. self.instruction.AddInstruction(scalebar)
  4457. self.instruction[self.id].SetInstruction(self.scalebarDict)
  4458. if self.id not in self.parent.objectId:
  4459. self.parent.objectId.append(self.id)
  4460. return True
  4461. def updateDialog(self):
  4462. """!Update scalebar coordinates, after moving"""
  4463. x, y = self.scalebarDict['rect'][:2]
  4464. currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection())
  4465. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4466. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4467. self.panel.position['xCtrl'].SetValue("%5.3f" % x)
  4468. self.panel.position['yCtrl'].SetValue("%5.3f" % y)
  4469. class TextDialog(PsmapDialog):
  4470. def __init__(self, parent, id, settings):
  4471. PsmapDialog.__init__(self, parent = parent, id = id, title = "Text settings", settings = settings)
  4472. self.objectType = ('text',)
  4473. if self.id is not None:
  4474. self.textDict = self.instruction[id].GetInstruction()
  4475. else:
  4476. self.id = wx.NewId()
  4477. text = Text(self.id)
  4478. self.textDict = text.GetInstruction()
  4479. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4480. self.textDict['where'] = page['Left'], page['Top']
  4481. map = self.instruction.FindInstructionByType('map')
  4482. if not map:
  4483. map = self.instruction.FindInstructionByType('initMap')
  4484. self.mapId = map.id
  4485. self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(map = map, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
  4486. notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  4487. self.textPanel = self._textPanel(notebook)
  4488. self.positionPanel = self._positionPanel(notebook)
  4489. self.OnBackground(None)
  4490. self.OnHighlight(None)
  4491. self.OnBorder(None)
  4492. self.OnPositionType(None)
  4493. self.OnRotation(None)
  4494. self._layout(notebook)
  4495. def _textPanel(self, notebook):
  4496. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4497. notebook.AddPage(page = panel, text = _("Text"))
  4498. border = wx.BoxSizer(wx.VERTICAL)
  4499. # text entry
  4500. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text"))
  4501. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4502. textLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Enter text:"))
  4503. self.textCtrl = ExpandoTextCtrl(panel, id = wx.ID_ANY, value = self.textDict['text'])
  4504. sizer.Add(textLabel, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4505. sizer.Add(self.textCtrl, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4506. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4507. #font
  4508. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  4509. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4510. flexGridSizer = wx.FlexGridSizer (rows = 3, cols = 2, hgap = 5, vgap = 5)
  4511. flexGridSizer.AddGrowableCol(1)
  4512. self.AddFont(parent = panel, dialogDict = self.textDict)
  4513. flexGridSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4514. flexGridSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4515. flexGridSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4516. flexGridSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4517. flexGridSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4518. flexGridSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4519. sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4520. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4521. #text effects
  4522. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text effects"))
  4523. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4524. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4525. self.effect = {}
  4526. self.effect['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text background"))
  4527. self.effect['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4528. self.effect['highlightCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("highlight"))
  4529. self.effect['highlightColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4530. self.effect['highlightWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 0, max = 5, initial = 1)
  4531. self.effect['highlightWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  4532. self.effect['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text border"))
  4533. self.effect['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4534. self.effect['borderWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 1, max = 25, initial = 1)
  4535. self.effect['borderWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  4536. #set values
  4537. if self.textDict['background'] == None:
  4538. self.textDict['background'] = 'none'
  4539. if self.textDict['background'] != 'none':
  4540. self.effect['backgroundCtrl'].SetValue(True)
  4541. self.effect['backgroundColor'].SetColour(convertRGB(self.textDict['background']))
  4542. else:
  4543. self.effect['backgroundCtrl'].SetValue(False)
  4544. self.effect['backgroundColor'].SetColour(convertRGB('white'))
  4545. if self.textDict['hcolor'] == None:
  4546. self.textDict['hcolor'] = 'none'
  4547. if self.textDict['hcolor'] != 'none':
  4548. self.effect['highlightCtrl'].SetValue(True)
  4549. self.effect['highlightColor'].SetColour(convertRGB(self.textDict['hcolor']))
  4550. else:
  4551. self.effect['highlightCtrl'].SetValue(False)
  4552. self.effect['highlightColor'].SetColour(convertRGB('grey'))
  4553. self.effect['highlightWidth'].SetValue(float(self.textDict['hwidth']))
  4554. if self.textDict['border'] == None:
  4555. self.textDict['border'] = 'none'
  4556. if self.textDict['border'] != 'none':
  4557. self.effect['borderCtrl'].SetValue(True)
  4558. self.effect['borderColor'].SetColour(convertRGB(self.textDict['border']))
  4559. else:
  4560. self.effect['borderCtrl'].SetValue(False)
  4561. self.effect['borderColor'].SetColour(convertRGB('black'))
  4562. self.effect['borderWidth'].SetValue(float(self.textDict['width']))
  4563. gridBagSizer.Add(self.effect['backgroundCtrl'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4564. gridBagSizer.Add(self.effect['backgroundColor'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4565. gridBagSizer.Add(self.effect['highlightCtrl'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4566. gridBagSizer.Add(self.effect['highlightColor'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4567. gridBagSizer.Add(self.effect['highlightWidthLabel'], pos = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4568. gridBagSizer.Add(self.effect['highlightWidth'], pos = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4569. gridBagSizer.Add(self.effect['borderCtrl'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4570. gridBagSizer.Add(self.effect['borderColor'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4571. gridBagSizer.Add(self.effect['borderWidthLabel'], pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4572. gridBagSizer.Add(self.effect['borderWidth'], pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4573. sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4574. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4575. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textCtrl)
  4576. self.Bind(wx.EVT_CHECKBOX, self.OnBackground, self.effect['backgroundCtrl'])
  4577. self.Bind(wx.EVT_CHECKBOX, self.OnHighlight, self.effect['highlightCtrl'])
  4578. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.effect['borderCtrl'])
  4579. panel.SetSizer(border)
  4580. panel.Fit()
  4581. return panel
  4582. def _positionPanel(self, notebook):
  4583. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4584. notebook.AddPage(page = panel, text = _("Position"))
  4585. border = wx.BoxSizer(wx.VERTICAL)
  4586. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4587. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4588. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  4589. gridBagSizer.AddGrowableCol(0)
  4590. gridBagSizer.AddGrowableCol(1)
  4591. #Position
  4592. self.AddExtendedPosition(panel, gridBagSizer, self.textDict)
  4593. #offset
  4594. box3 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Offset"))
  4595. sizerO = wx.StaticBoxSizer(box3, wx.VERTICAL)
  4596. gridBagSizerO = wx.GridBagSizer (hgap = 5, vgap = 5)
  4597. self.xoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("horizontal (pts):"))
  4598. self.yoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("vertical (pts):"))
  4599. self.xoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0)
  4600. self.yoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0)
  4601. self.xoffCtrl.SetValue(self.textDict['xoffset'])
  4602. self.yoffCtrl.SetValue(self.textDict['yoffset'])
  4603. gridBagSizerO.Add(self.xoffLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4604. gridBagSizerO.Add(self.yoffLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4605. gridBagSizerO.Add(self.xoffCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4606. gridBagSizerO.Add(self.yoffCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4607. sizerO.Add(gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4608. gridBagSizer.Add(sizerO, pos = (3,0), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
  4609. # reference point
  4610. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_(" Reference point"))
  4611. sizerR = wx.StaticBoxSizer(box, wx.VERTICAL)
  4612. flexSizer = wx.FlexGridSizer(rows = 3, cols = 3, hgap = 5, vgap = 5)
  4613. flexSizer.AddGrowableCol(0)
  4614. flexSizer.AddGrowableCol(1)
  4615. flexSizer.AddGrowableCol(2)
  4616. ref = []
  4617. for row in ["upper", "center", "lower"]:
  4618. for col in ["left", "center", "right"]:
  4619. ref.append(row + " " + col)
  4620. self.radio = [wx.RadioButton(panel, id = wx.ID_ANY, label = '', style = wx.RB_GROUP, name = ref[0])]
  4621. self.radio[0].SetValue(False)
  4622. flexSizer.Add(self.radio[0], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4623. for i in range(1,9):
  4624. self.radio.append(wx.RadioButton(panel, id = wx.ID_ANY, label = '', name = ref[i]))
  4625. self.radio[-1].SetValue(False)
  4626. flexSizer.Add(self.radio[-1], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4627. self.FindWindowByName(self.textDict['ref']).SetValue(True)
  4628. sizerR.Add(flexSizer, proportion = 1, flag = wx.EXPAND, border = 0)
  4629. gridBagSizer.Add(sizerR, pos = (3,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
  4630. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4631. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4632. #rotation
  4633. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text rotation"))
  4634. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4635. self.rotCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate text (counterclockwise)"))
  4636. self.rotValue = wx.SpinCtrl(panel, wx.ID_ANY, size = (50, -1), min = 0, max = 360, initial = 0)
  4637. if self.textDict['rotate']:
  4638. self.rotValue.SetValue(int(self.textDict['rotate']))
  4639. self.rotCtrl.SetValue(True)
  4640. else:
  4641. self.rotValue.SetValue(0)
  4642. self.rotCtrl.SetValue(False)
  4643. sizer.Add(self.rotCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
  4644. sizer.Add(self.rotValue, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
  4645. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4646. panel.SetSizer(border)
  4647. panel.Fit()
  4648. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toPaper'])
  4649. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toMap'])
  4650. self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotCtrl)
  4651. return panel
  4652. def OnRefit(self, event):
  4653. self.Fit()
  4654. def OnRotation(self, event):
  4655. if self.rotCtrl.GetValue():
  4656. self.rotValue.Enable()
  4657. else:
  4658. self.rotValue.Disable()
  4659. def OnPositionType(self, event):
  4660. if self.positionPanel.position['toPaper'].GetValue():
  4661. for widget in self.gridBagSizerP.GetChildren():
  4662. widget.GetWindow().Enable()
  4663. for widget in self.gridBagSizerM.GetChildren():
  4664. widget.GetWindow().Disable()
  4665. else:
  4666. for widget in self.gridBagSizerM.GetChildren():
  4667. widget.GetWindow().Enable()
  4668. for widget in self.gridBagSizerP.GetChildren():
  4669. widget.GetWindow().Disable()
  4670. def OnBackground(self, event):
  4671. if self.effect['backgroundCtrl'].GetValue():
  4672. self.effect['backgroundColor'].Enable()
  4673. self.update()
  4674. else:
  4675. self.effect['backgroundColor'].Disable()
  4676. def OnHighlight(self, event):
  4677. if self.effect['highlightCtrl'].GetValue():
  4678. self.effect['highlightColor'].Enable()
  4679. self.effect['highlightWidth'].Enable()
  4680. self.effect['highlightWidthLabel'].Enable()
  4681. self.update()
  4682. else:
  4683. self.effect['highlightColor'].Disable()
  4684. self.effect['highlightWidth'].Disable()
  4685. self.effect['highlightWidthLabel'].Disable()
  4686. def OnBorder(self, event):
  4687. if self.effect['borderCtrl'].GetValue():
  4688. self.effect['borderColor'].Enable()
  4689. self.effect['borderWidth'].Enable()
  4690. self.effect['borderWidthLabel'].Enable()
  4691. self.update()
  4692. else:
  4693. self.effect['borderColor'].Disable()
  4694. self.effect['borderWidth'].Disable()
  4695. self.effect['borderWidthLabel'].Disable()
  4696. def update(self):
  4697. #text
  4698. self.textDict['text'] = self.textCtrl.GetValue()
  4699. if not self.textDict['text']:
  4700. wx.MessageBox(_("No text entered!"), _("Error"))
  4701. return False
  4702. #font
  4703. self.textDict['font'] = self.textPanel.font['fontCtrl'].GetStringSelection()
  4704. self.textDict['fontsize'] = self.textPanel.font['fontSizeCtrl'].GetValue()
  4705. color = self.textPanel.font['colorCtrl'].GetColour()
  4706. self.textDict['color'] = convertRGB(color)
  4707. #effects
  4708. if self.effect['backgroundCtrl'].GetValue():
  4709. background = self.effect['backgroundColor'].GetColour()
  4710. self.textDict['background'] = convertRGB(background)
  4711. else:
  4712. self.textDict['background'] = 'none'
  4713. if self.effect['borderCtrl'].GetValue():
  4714. border = self.effect['borderColor'].GetColour()
  4715. self.textDict['border'] = convertRGB(border)
  4716. else:
  4717. self.textDict['border'] = 'none'
  4718. self.textDict['width'] = self.effect['borderWidth'].GetValue()
  4719. if self.effect['highlightCtrl'].GetValue():
  4720. highlight = self.effect['highlightColor'].GetColour()
  4721. self.textDict['hcolor'] = convertRGB(highlight)
  4722. else:
  4723. self.textDict['hcolor'] = 'none'
  4724. self.textDict['hwidth'] = self.effect['highlightWidth'].GetValue()
  4725. #offset
  4726. self.textDict['xoffset'] = self.xoffCtrl.GetValue()
  4727. self.textDict['yoffset'] = self.yoffCtrl.GetValue()
  4728. #position
  4729. if self.positionPanel.position['toPaper'].GetValue():
  4730. self.textDict['XY'] = True
  4731. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  4732. self.textDict['unit'] = currUnit
  4733. if self.positionPanel.position['xCtrl'].GetValue():
  4734. x = self.positionPanel.position['xCtrl'].GetValue()
  4735. else:
  4736. x = self.textDict['where'][0]
  4737. if self.positionPanel.position['yCtrl'].GetValue():
  4738. y = self.positionPanel.position['yCtrl'].GetValue()
  4739. else:
  4740. y = self.textDict['where'][1]
  4741. x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
  4742. y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
  4743. self.textDict['where'] = x, y
  4744. self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(self.instruction[self.mapId], x, y, paperToMap = True)
  4745. else:
  4746. self.textDict['XY'] = False
  4747. if self.positionPanel.position['eCtrl'].GetValue():
  4748. self.textDict['east'] = self.positionPanel.position['eCtrl'].GetValue()
  4749. else:
  4750. self.textDict['east'] = self.textDict['east']
  4751. if self.positionPanel.position['nCtrl'].GetValue():
  4752. self.textDict['north'] = self.positionPanel.position['nCtrl'].GetValue()
  4753. else:
  4754. self.textDict['north'] = self.textDict['north']
  4755. self.textDict['where'] = PaperMapCoordinates(map = self.instruction[self.mapId], x = float(self.textDict['east']),
  4756. y = float(self.textDict['north']), paperToMap = False)
  4757. #rotation
  4758. if self.rotCtrl.GetValue():
  4759. self.textDict['rotate'] = self.rotValue.GetValue()
  4760. else:
  4761. self.textDict['rotate'] = None
  4762. #reference point
  4763. for radio in self.radio:
  4764. if radio.GetValue() == True:
  4765. self.textDict['ref'] = radio.GetName()
  4766. if self.id not in self.instruction:
  4767. text = Text(self.id)
  4768. self.instruction.AddInstruction(text)
  4769. self.instruction[self.id].SetInstruction(self.textDict)
  4770. if self.id not in self.parent.objectId:
  4771. self.parent.objectId.append(self.id)
  4772. # self.updateDialog()
  4773. return True
  4774. def updateDialog(self):
  4775. """!Update text coordinates, after moving"""
  4776. # XY coordinates
  4777. x, y = self.textDict['where'][:2]
  4778. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  4779. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4780. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4781. self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
  4782. self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
  4783. # EN coordinates
  4784. e, n = self.textDict['east'], self.textDict['north']
  4785. self.positionPanel.position['eCtrl'].SetValue(str(self.textDict['east']))
  4786. self.positionPanel.position['nCtrl'].SetValue(str(self.textDict['north']))
  4787. class ImageDialog(PsmapDialog):
  4788. """!Dialog for setting image properties.
  4789. It's base dialog for North Arrow dialog.
  4790. """
  4791. def __init__(self, parent, id, settings, imagePanelName = _("Image")):
  4792. PsmapDialog.__init__(self, parent = parent, id = id, title = "Image settings",
  4793. settings = settings)
  4794. self.objectType = ('image',)
  4795. if self.id is not None:
  4796. self.imageObj = self.instruction[self.id]
  4797. self.imageDict = self.instruction[id].GetInstruction()
  4798. else:
  4799. self.id = wx.NewId()
  4800. self.imageObj = self._newObject()
  4801. self.imageDict = self.imageObj.GetInstruction()
  4802. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4803. self.imageDict['where'] = page['Left'], page['Top']
  4804. map = self.instruction.FindInstructionByType('map')
  4805. if not map:
  4806. map = self.instruction.FindInstructionByType('initMap')
  4807. self.mapId = map.id
  4808. self.imageDict['east'], self.imageDict['north'] = PaperMapCoordinates(map = map, x = self.imageDict['where'][0], y = self.imageDict['where'][1], paperToMap = True)
  4809. notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  4810. self.imagePanelName = imagePanelName
  4811. self.imagePanel = self._imagePanel(notebook)
  4812. self.positionPanel = self._positionPanel(notebook)
  4813. self.OnPositionType(None)
  4814. if self.imageDict['epsfile']:
  4815. self.imagePanel.image['dir'].SetValue(os.path.dirname(self.imageDict['epsfile']))
  4816. else:
  4817. self.imagePanel.image['dir'].SetValue(self._getImageDirectory())
  4818. self.OnDirChanged(None)
  4819. self._layout(notebook)
  4820. def _newObject(self):
  4821. """!Create corresponding instruction object"""
  4822. return Image(self.id, self.instruction)
  4823. def _imagePanel(self, notebook):
  4824. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  4825. notebook.AddPage(page = panel, text = self.imagePanelName)
  4826. border = wx.BoxSizer(wx.VERTICAL)
  4827. #
  4828. # choose image
  4829. #
  4830. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Image"))
  4831. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4832. # choose directory
  4833. panel.image = {}
  4834. if self.imageDict['epsfile']:
  4835. startDir = os.path.dirname(self.imageDict['epsfile'])
  4836. else:
  4837. startDir = self._getImageDirectory()
  4838. dir = filebrowse.DirBrowseButton(parent = panel, id = wx.ID_ANY,
  4839. labelText = _("Choose a directory:"),
  4840. dialogTitle = _("Choose a directory with images"),
  4841. buttonText = _('Browse'),
  4842. startDirectory = startDir,
  4843. changeCallback = self.OnDirChanged)
  4844. panel.image['dir'] = dir
  4845. sizer.Add(item = dir, proportion = 0, flag = wx.EXPAND, border = 0)
  4846. # image list
  4847. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  4848. imageList = wx.ListBox(parent = panel, id = wx.ID_ANY)
  4849. panel.image['list'] = imageList
  4850. imageList.Bind(wx.EVT_LISTBOX, self.OnImageSelectionChanged)
  4851. hSizer.Add(item = imageList, proportion = 1, flag = wx.EXPAND | wx.RIGHT, border = 10)
  4852. # image preview
  4853. vSizer = wx.BoxSizer(wx.VERTICAL)
  4854. self.previewSize = (150, 150)
  4855. img = wx.EmptyImage(*self.previewSize)
  4856. panel.image['preview'] = wx.StaticBitmap(parent = panel, id = wx.ID_ANY,
  4857. bitmap = wx.BitmapFromImage(img))
  4858. vSizer.Add(item = panel.image['preview'], proportion = 0, flag = wx.EXPAND | wx.BOTTOM, border = 5)
  4859. panel.image['sizeInfo'] = wx.StaticText(parent = panel, id = wx.ID_ANY)
  4860. vSizer.Add(item = panel.image['sizeInfo'], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4861. hSizer.Add(item = vSizer, proportion = 0, flag = wx.EXPAND, border = 0)
  4862. sizer.Add(item = hSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 3)
  4863. epsInfo = wx.StaticText(parent = panel, id = wx.ID_ANY,
  4864. label = _("Note: only EPS format supported"))
  4865. sizer.Add(item = epsInfo, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 3)
  4866. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4867. #
  4868. # rotation
  4869. #
  4870. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Scale And Rotation"))
  4871. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4872. gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  4873. scaleLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Scale:"))
  4874. if fs:
  4875. panel.image['scale'] = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 50,
  4876. increment = 0.5, value = 1, style = fs.FS_RIGHT, size = self.spinCtrlSize)
  4877. panel.image['scale'].SetFormat("%f")
  4878. panel.image['scale'].SetDigits(1)
  4879. else:
  4880. panel.image['scale'] = wx.TextCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize,
  4881. validator = TCValidator(flag = 'DIGIT_ONLY'))
  4882. if self.imageDict['scale']:
  4883. if fs:
  4884. value = float(self.imageDict['scale'])
  4885. else:
  4886. value = str(self.imageDict['scale'])
  4887. else:
  4888. if fs:
  4889. value = 0
  4890. else:
  4891. value = '0'
  4892. panel.image['scale'].SetValue(value)
  4893. gridSizer.Add(item = scaleLabel, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
  4894. gridSizer.Add(item = panel.image['scale'], pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL)
  4895. rotLabel = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Rotation angle (deg):"))
  4896. if fs:
  4897. panel.image['rotate'] = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 360,
  4898. increment = 0.5, value = 0, style = fs.FS_RIGHT, size = self.spinCtrlSize)
  4899. panel.image['rotate'].SetFormat("%f")
  4900. panel.image['rotate'].SetDigits(1)
  4901. else:
  4902. panel.image['rotate'] = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = self.spinCtrlSize,
  4903. min = 0, max = 359, initial = 0)
  4904. panel.image['rotate'].SetToolTipString(_("Counterclockwise rotation in degrees"))
  4905. if self.imageDict['rotate']:
  4906. panel.image['rotate'].SetValue(int(self.imageDict['rotate']))
  4907. else:
  4908. panel.image['rotate'].SetValue(0)
  4909. gridSizer.Add(item = rotLabel, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4910. gridSizer.Add(item = panel.image['rotate'], pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL)
  4911. self._addConvergence(panel = panel, gridBagSizer = gridSizer)
  4912. sizer.Add(item = gridSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
  4913. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4914. panel.SetSizer(border)
  4915. panel.Fit()
  4916. return panel
  4917. def _positionPanel(self, notebook):
  4918. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  4919. notebook.AddPage(page = panel, text = _("Position"))
  4920. border = wx.BoxSizer(wx.VERTICAL)
  4921. #
  4922. # set position
  4923. #
  4924. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4925. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4926. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  4927. gridBagSizer.AddGrowableCol(0)
  4928. gridBagSizer.AddGrowableCol(1)
  4929. self.AddExtendedPosition(panel, gridBagSizer, self.imageDict)
  4930. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toPaper'])
  4931. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, panel.position['toMap'])
  4932. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL| wx.ALL, border = 5)
  4933. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4934. panel.SetSizer(border)
  4935. panel.Fit()
  4936. return panel
  4937. def OnDirChanged(self, event):
  4938. """!Image directory changed"""
  4939. path = self.imagePanel.image['dir'].GetValue()
  4940. try:
  4941. files = os.listdir(path)
  4942. except OSError: # no such directory
  4943. files = []
  4944. imageList = []
  4945. # no setter for startDirectory?
  4946. try:
  4947. self.imagePanel.image['dir'].startDirectory = path
  4948. except AttributeError: # for sure
  4949. pass
  4950. for file in files:
  4951. if os.path.splitext(file)[1].lower() == '.eps':
  4952. imageList.append(file)
  4953. imageList.sort()
  4954. self.imagePanel.image['list'].SetItems(imageList)
  4955. if self.imageDict['epsfile']:
  4956. file = os.path.basename(self.imageDict['epsfile'])
  4957. self.imagePanel.image['list'].SetStringSelection(file)
  4958. elif imageList:
  4959. self.imagePanel.image['list'].SetSelection(0)
  4960. self.OnImageSelectionChanged(None)
  4961. def OnPositionType(self, event):
  4962. if self.positionPanel.position['toPaper'].GetValue():
  4963. for widget in self.gridBagSizerP.GetChildren():
  4964. widget.GetWindow().Enable()
  4965. for widget in self.gridBagSizerM.GetChildren():
  4966. widget.GetWindow().Disable()
  4967. else:
  4968. for widget in self.gridBagSizerM.GetChildren():
  4969. widget.GetWindow().Enable()
  4970. for widget in self.gridBagSizerP.GetChildren():
  4971. widget.GetWindow().Disable()
  4972. def _getImageDirectory(self):
  4973. """!Default image directory"""
  4974. return os.getcwd()
  4975. def _addConvergence(self, panel, gridBagSizer):
  4976. pass
  4977. def OnImageSelectionChanged(self, event):
  4978. """!Image selected, show preview and size"""
  4979. if not self.imagePanel.image['dir']: # event is emitted when closing dialog an it causes error
  4980. return
  4981. if not havePILImage:
  4982. self.DrawWarningText(_("PIL\nmissing"))
  4983. return
  4984. imageName = self.imagePanel.image['list'].GetStringSelection()
  4985. if not imageName:
  4986. self.ClearPreview()
  4987. return
  4988. basePath = self.imagePanel.image['dir'].GetValue()
  4989. file = os.path.join(basePath, imageName)
  4990. if not os.path.exists(file):
  4991. return
  4992. if os.path.splitext(file)[1].lower() == '.eps':
  4993. try:
  4994. pImg = PILImage.open(file)
  4995. img = PilImageToWxImage(pImg)
  4996. except IOError, e:
  4997. GError(message = _("Unable to read file %s") % file)
  4998. self.ClearPreview()
  4999. return
  5000. self.SetSizeInfoLabel(img)
  5001. img = self.ScaleToPreview(img)
  5002. bitmap = img.ConvertToBitmap()
  5003. self.DrawBitmap(bitmap)
  5004. else:
  5005. # TODO: read other formats and convert by PIL to eps
  5006. pass
  5007. def ScaleToPreview(self, img):
  5008. """!Scale image to preview size"""
  5009. w = img.GetWidth()
  5010. h = img.GetHeight()
  5011. if w <= self.previewSize[0] and h <= self.previewSize[1]:
  5012. return img
  5013. if w > h:
  5014. newW = self.previewSize[0]
  5015. newH = self.previewSize[0] * h / w
  5016. else:
  5017. newH = self.previewSize[0]
  5018. newW = self.previewSize[0] * w / h
  5019. return img.Scale(newW, newH, wx.IMAGE_QUALITY_HIGH)
  5020. def DrawWarningText(self, warning):
  5021. """!Draw text on preview window"""
  5022. buffer = wx.EmptyBitmap(*self.previewSize)
  5023. dc = wx.MemoryDC()
  5024. dc.SelectObject(buffer)
  5025. dc.SetBrush(wx.Brush(wx.Color(250, 250, 250)))
  5026. dc.Clear()
  5027. extent = dc.GetTextExtent(warning)
  5028. posX = self.previewSize[0] / 2 - extent[0] / 2
  5029. posY = self.previewSize[1] / 2 - extent[1] / 2
  5030. dc.DrawText(warning, posX, posY)
  5031. self.imagePanel.image['preview'].SetBitmap(buffer)
  5032. dc.SelectObject(wx.NullBitmap)
  5033. def DrawBitmap(self, bitmap):
  5034. """!Draw bitmap, center it if smaller than preview size"""
  5035. if bitmap.GetWidth() <= self.previewSize[0] and bitmap.GetHeight() <= self.previewSize[1]:
  5036. buffer = wx.EmptyBitmap(*self.previewSize)
  5037. dc = wx.MemoryDC()
  5038. dc.SelectObject(buffer)
  5039. dc.SetBrush(dc.GetBrush())
  5040. dc.Clear()
  5041. posX = self.previewSize[0] / 2 - bitmap.GetWidth() / 2
  5042. posY = self.previewSize[1] / 2 - bitmap.GetHeight() / 2
  5043. dc.DrawBitmap(bitmap, posX, posY)
  5044. self.imagePanel.image['preview'].SetBitmap(buffer)
  5045. dc.SelectObject(wx.NullBitmap)
  5046. else:
  5047. self.imagePanel.image['preview'].SetBitmap(bitmap)
  5048. def SetSizeInfoLabel(self, image):
  5049. """!Update image size label"""
  5050. self.imagePanel.image['sizeInfo'].SetLabel(_("size: %s x %s pts") % (image.GetWidth(), image.GetHeight()))
  5051. self.imagePanel.image['sizeInfo'].GetContainingSizer().Layout()
  5052. def ClearPreview(self):
  5053. """!Clear preview window"""
  5054. buffer = wx.EmptyBitmap(*self.previewSize)
  5055. dc = wx.MemoryDC()
  5056. dc.SelectObject(buffer)
  5057. dc.SetBrush(wx.WHITE_BRUSH)
  5058. dc.Clear()
  5059. mask = wx.Mask(buffer, wx.WHITE)
  5060. buffer.SetMask(mask)
  5061. self.imagePanel.image['preview'].SetBitmap(buffer)
  5062. dc.SelectObject(wx.NullBitmap)
  5063. def update(self):
  5064. # epsfile
  5065. selected = self.imagePanel.image['list'].GetStringSelection()
  5066. basePath = self.imagePanel.image['dir'].GetValue()
  5067. if not selected:
  5068. gcmd.GMessage(parent = self, message = _("No image selected."))
  5069. return False
  5070. self.imageDict['epsfile'] = os.path.join(basePath, selected)
  5071. #position
  5072. if self.positionPanel.position['toPaper'].GetValue():
  5073. self.imageDict['XY'] = True
  5074. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  5075. self.imageDict['unit'] = currUnit
  5076. if self.positionPanel.position['xCtrl'].GetValue():
  5077. x = self.positionPanel.position['xCtrl'].GetValue()
  5078. else:
  5079. x = self.imageDict['where'][0]
  5080. if self.positionPanel.position['yCtrl'].GetValue():
  5081. y = self.positionPanel.position['yCtrl'].GetValue()
  5082. else:
  5083. y = self.imageDict['where'][1]
  5084. x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
  5085. y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
  5086. self.imageDict['where'] = x, y
  5087. else:
  5088. self.imageDict['XY'] = False
  5089. if self.positionPanel.position['eCtrl'].GetValue():
  5090. e = self.positionPanel.position['eCtrl'].GetValue()
  5091. else:
  5092. self.imageDict['east'] = self.imageDict['east']
  5093. if self.positionPanel.position['nCtrl'].GetValue():
  5094. n = self.positionPanel.position['nCtrl'].GetValue()
  5095. else:
  5096. self.imageDict['north'] = self.imageDict['north']
  5097. x, y = PaperMapCoordinates(map = self.instruction[self.mapId], x = float(self.imageDict['east']),
  5098. y = float(self.imageDict['north']), paperToMap = False)
  5099. #rotation
  5100. rot = self.imagePanel.image['rotate'].GetValue()
  5101. if rot == 0:
  5102. self.imageDict['rotate'] = None
  5103. else:
  5104. self.imageDict['rotate'] = rot
  5105. #scale
  5106. self.imageDict['scale'] = self.imagePanel.image['scale'].GetValue()
  5107. # scale
  5108. w, h = self.imageObj.GetImageOrigSize(self.imageDict['epsfile'])
  5109. if self.imageDict['rotate']:
  5110. self.imageDict['size'] = BBoxAfterRotation(w, h, self.imageDict['rotate'])
  5111. else:
  5112. self.imageDict['size'] = w, h
  5113. w = self.unitConv.convert(value = self.imageDict['size'][0],
  5114. fromUnit = 'point', toUnit = 'inch')
  5115. h = self.unitConv.convert(value = self.imageDict['size'][1],
  5116. fromUnit = 'point', toUnit = 'inch')
  5117. self.imageDict['rect'] = wx.Rect2D(x = x, y = y,
  5118. w = w * self.imageDict['scale'],
  5119. h = h * self.imageDict['scale'])
  5120. if self.id not in self.instruction:
  5121. image = self._newObject()
  5122. self.instruction.AddInstruction(image)
  5123. self.instruction[self.id].SetInstruction(self.imageDict)
  5124. if self.id not in self.parent.objectId:
  5125. self.parent.objectId.append(self.id)
  5126. return True
  5127. def updateDialog(self):
  5128. """!Update text coordinates, after moving"""
  5129. # XY coordinates
  5130. x, y = self.imageDict['where'][:2]
  5131. currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection())
  5132. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  5133. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  5134. self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
  5135. self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
  5136. # EN coordinates
  5137. e, n = self.imageDict['east'], self.imageDict['north']
  5138. self.positionPanel.position['eCtrl'].SetValue(str(self.imageDict['east']))
  5139. self.positionPanel.position['nCtrl'].SetValue(str(self.imageDict['north']))
  5140. class NorthArrowDialog(ImageDialog):
  5141. def __init__(self, parent, id, settings):
  5142. ImageDialog.__init__(self, parent = parent, id = id, settings = settings,
  5143. imagePanelName = _("North Arrow"))
  5144. self.objectType = ('northArrow',)
  5145. self.SetTitle(_("North Arrow settings"))
  5146. def _newObject(self):
  5147. return NorthArrow(self.id, self.instruction)
  5148. def _getImageDirectory(self):
  5149. gisbase = os.getenv("GISBASE")
  5150. return os.path.join(gisbase, 'etc', 'paint', 'decorations')
  5151. def _addConvergence(self, panel, gridBagSizer):
  5152. convergence = wx.Button(parent = panel, id = wx.ID_ANY,
  5153. label = _("Compute convergence"))
  5154. gridBagSizer.Add(item = convergence, pos = (1, 2),
  5155. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  5156. convergence.Bind(wx.EVT_BUTTON, self.OnConvergence)
  5157. panel.image['convergence'] = convergence
  5158. def OnConvergence(self, event):
  5159. ret = RunCommand('g.region', read = True, flags = 'ng')
  5160. if ret:
  5161. convergence = float(ret.strip().split('=')[1])
  5162. if convergence < 0:
  5163. self.imagePanel.image['rotate'].SetValue(abs(convergence))
  5164. else:
  5165. self.imagePanel.image['rotate'].SetValue(360 - convergence)
  5166. def convertRGB(rgb):
  5167. """!Converts wx.Colour(r,g,b,a) to string 'r:g:b' or named color,
  5168. or named color/r:g:b string to wx.Colour, depending on input"""
  5169. # transform a wx.Colour tuple into an r:g:b string
  5170. if type(rgb) == wx.Colour:
  5171. for name, color in grass.named_colors.items():
  5172. if rgb.Red() == int(color[0] * 255) and\
  5173. rgb.Green() == int(color[1] * 255) and\
  5174. rgb.Blue() == int(color[2] * 255):
  5175. return name
  5176. return str(rgb.Red()) + ':' + str(rgb.Green()) + ':' + str(rgb.Blue())
  5177. # transform a GRASS named color or an r:g:b string into a wx.Colour tuple
  5178. else:
  5179. color = (grass.parse_color(rgb)[0]*255,
  5180. grass.parse_color(rgb)[1]*255,
  5181. grass.parse_color(rgb)[2]*255)
  5182. color = wx.Color(*color)
  5183. if color.IsOk():
  5184. return color
  5185. else:
  5186. return None
  5187. def PaperMapCoordinates(map, x, y, paperToMap = True):
  5188. """!Converts paper (inch) coordinates -> map coordinates"""
  5189. unitConv = UnitConversion()
  5190. currRegionDict = grass.region()
  5191. cornerEasting, cornerNorthing = currRegionDict['w'], currRegionDict['n']
  5192. xMap = map['rect'][0]
  5193. yMap = map['rect'][1]
  5194. widthMap = map['rect'][2] * 0.0254 # to meter
  5195. heightMap = map['rect'][3] * 0.0254
  5196. xScale = widthMap / abs(currRegionDict['w'] - currRegionDict['e'])
  5197. yScale = heightMap / abs(currRegionDict['n'] - currRegionDict['s'])
  5198. currScale = (xScale + yScale) / 2
  5199. if not paperToMap:
  5200. textEasting, textNorthing = x, y
  5201. eastingDiff = textEasting - cornerEasting
  5202. if currRegionDict['w'] > currRegionDict['e']:
  5203. eastingDiff = - eastingDiff
  5204. else:
  5205. eastingDiff = eastingDiff
  5206. northingDiff = textNorthing - cornerNorthing
  5207. if currRegionDict['n'] > currRegionDict['s']:
  5208. northingDiff = - northingDiff
  5209. else:
  5210. northingDiff = northingDiff
  5211. xPaper = xMap + unitConv.convert(value = eastingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale
  5212. yPaper = yMap + unitConv.convert(value = northingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale
  5213. return xPaper, yPaper
  5214. else:
  5215. if currRegionDict['w'] < currRegionDict['e']:
  5216. eastingDiff = (x - xMap)
  5217. else:
  5218. eastingDiff = (xMap - x)
  5219. if currRegionDict['n'] < currRegionDict['s']:
  5220. northingDiff = (y - yMap)
  5221. else:
  5222. northingDiff = (yMap - y)
  5223. textEasting = cornerEasting + unitConv.convert(value = eastingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale
  5224. textNorthing = cornerNorthing + unitConv.convert(value = northingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale
  5225. return int(textEasting), int(textNorthing)
  5226. def AutoAdjust(self, scaleType, rect, map = None, mapType = None, region = None):
  5227. """!Computes map scale, center and map frame rectangle to fit region (scale is not fixed)"""
  5228. currRegionDict = {}
  5229. if scaleType == 0 and map:# automatic, region from raster or vector
  5230. res = ''
  5231. if mapType == 'raster':
  5232. try:
  5233. res = grass.read_command("g.region", flags = 'gu', rast = map)
  5234. except grass.ScriptError:
  5235. pass
  5236. elif mapType == 'vector':
  5237. res = grass.read_command("g.region", flags = 'gu', vect = map)
  5238. currRegionDict = grass.parse_key_val(res, val_type = float)
  5239. elif scaleType == 1 and region: # saved region
  5240. res = grass.read_command("g.region", flags = 'gu', region = region)
  5241. currRegionDict = grass.parse_key_val(res, val_type = float)
  5242. elif scaleType == 2: # current region
  5243. env = grass.gisenv()
  5244. windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND')
  5245. try:
  5246. windFile = open(windFilePath, 'r').read()
  5247. except IOError:
  5248. currRegionDict = grass.region()
  5249. regionDict = grass.parse_key_val(windFile, sep = ':', val_type = float)
  5250. region = grass.read_command("g.region", flags = 'gu', n = regionDict['north'], s = regionDict['south'],
  5251. e = regionDict['east'], w = regionDict['west'])
  5252. currRegionDict = grass.parse_key_val(region, val_type = float)
  5253. else:
  5254. return None, None, None
  5255. if not currRegionDict:
  5256. return None, None, None
  5257. rX = rect.x
  5258. rY = rect.y
  5259. rW = rect.width
  5260. rH = rect.height
  5261. if not hasattr(self, 'unitConv'):
  5262. self.unitConv = UnitConversion(self)
  5263. toM = 1
  5264. if projInfo()['proj'] != 'xy':
  5265. toM = float(projInfo()['meters'])
  5266. mW = self.unitConv.convert(value = (currRegionDict['e'] - currRegionDict['w']) * toM, fromUnit = 'meter', toUnit = 'inch')
  5267. mH = self.unitConv.convert(value = (currRegionDict['n'] - currRegionDict['s']) * toM, fromUnit = 'meter', toUnit = 'inch')
  5268. scale = min(rW/mW, rH/mH)
  5269. if rW/rH > mW/mH:
  5270. x = rX - (rH*(mW/mH) - rW)/2
  5271. y = rY
  5272. rWNew = rH*(mW/mH)
  5273. rHNew = rH
  5274. else:
  5275. x = rX
  5276. y = rY - (rW*(mH/mW) - rH)/2
  5277. rHNew = rW*(mH/mW)
  5278. rWNew = rW
  5279. # center
  5280. cE = (currRegionDict['w'] + currRegionDict['e'])/2
  5281. cN = (currRegionDict['n'] + currRegionDict['s'])/2
  5282. return scale, (cE, cN), wx.Rect2D(x, y, rWNew, rHNew) #inch
  5283. def SetResolution(dpi, width, height):
  5284. """!If resolution is too high, lower it
  5285. @param dpi max DPI
  5286. @param width map frame width
  5287. @param height map frame height
  5288. """
  5289. region = grass.region()
  5290. if region['cols'] > width * dpi or region['rows'] > height * dpi:
  5291. rows = height * dpi
  5292. cols = width * dpi
  5293. RunCommand('g.region', rows = rows, cols = cols)
  5294. def ComputeSetRegion(self, mapDict):
  5295. """!Computes and sets region from current scale, map center coordinates and map rectangle"""
  5296. if mapDict['scaleType'] == 3: # fixed scale
  5297. scale = mapDict['scale']
  5298. if not hasattr(self, 'unitConv'):
  5299. self.unitConv = UnitConversion(self)
  5300. fromM = 1
  5301. if projInfo()['proj'] != 'xy':
  5302. fromM = float(projInfo()['meters'])
  5303. rectHalfInch = (mapDict['rect'].width/2, mapDict['rect'].height/2)
  5304. rectHalfMeter = (self.unitConv.convert(value = rectHalfInch[0], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale,
  5305. self.unitConv.convert(value = rectHalfInch[1], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale)
  5306. centerE = mapDict['center'][0]
  5307. centerN = mapDict['center'][1]
  5308. raster = self.instruction.FindInstructionByType('raster')
  5309. if raster:
  5310. rasterId = raster.id
  5311. else:
  5312. rasterId = None
  5313. if rasterId:
  5314. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  5315. s = floor(centerN - rectHalfMeter[1]),
  5316. e = ceil(centerE + rectHalfMeter[0]),
  5317. w = floor(centerE - rectHalfMeter[0]),
  5318. rast = self.instruction[rasterId]['raster'])
  5319. else:
  5320. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  5321. s = floor(centerN - rectHalfMeter[1]),
  5322. e = ceil(centerE + rectHalfMeter[0]),
  5323. w = floor(centerE - rectHalfMeter[0]))
  5324. def projInfo():
  5325. """!Return region projection and map units information,
  5326. taken from render.py"""
  5327. projinfo = dict()
  5328. ret = RunCommand('g.proj', read = True, flags = 'p')
  5329. if not ret:
  5330. return projinfo
  5331. for line in ret.splitlines():
  5332. if ':' in line:
  5333. key, val = line.split(':')
  5334. projinfo[key.strip()] = val.strip()
  5335. elif "XY location (unprojected)" in line:
  5336. projinfo['proj'] = 'xy'
  5337. projinfo['units'] = ''
  5338. break
  5339. return projinfo
  5340. def GetMapBounds(filename, portrait = True):
  5341. """!Run ps.map -b to get information about map bounding box
  5342. @param filename psmap input file
  5343. @param portrait page orientation"""
  5344. orient = ''
  5345. if not portrait:
  5346. orient = 'r'
  5347. try:
  5348. bb = map(float, grass.read_command('ps.map',
  5349. flags = 'b' + orient,
  5350. quiet = True,
  5351. input = filename).strip().split('=')[1].split(','))
  5352. except (grass.ScriptError, IndexError):
  5353. GError(message = _("Unable to run `ps.map -b`"))
  5354. return None
  5355. return wx.Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3])
  5356. def getRasterType(map):
  5357. """!Returns type of raster map (CELL, FCELL, DCELL)"""
  5358. if map is None:
  5359. map = ''
  5360. file = grass.find_file(name = map, element = 'cell')
  5361. if file['file']:
  5362. rasterType = grass.raster_info(map)['datatype']
  5363. return rasterType
  5364. else:
  5365. return None
  5366. def PilImageToWxImage(pilImage, copyAlpha = True):
  5367. """!Convert PIL image to wx.Image
  5368. Based on http://wiki.wxpython.org/WorkingWithImages
  5369. """
  5370. hasAlpha = pilImage.mode[-1] == 'A'
  5371. if copyAlpha and hasAlpha : # Make sure there is an alpha layer copy.
  5372. wxImage = wx.EmptyImage( *pilImage.size )
  5373. pilImageCopyRGBA = pilImage.copy()
  5374. pilImageCopyRGB = pilImageCopyRGBA.convert('RGB') # RGBA --> RGB
  5375. pilImageRgbData = pilImageCopyRGB.tostring()
  5376. wxImage.SetData(pilImageRgbData)
  5377. wxImage.SetAlphaData(pilImageCopyRGBA.tostring()[3::4]) # Create layer and insert alpha values.
  5378. else : # The resulting image will not have alpha.
  5379. wxImage = wx.EmptyImage(*pilImage.size)
  5380. pilImageCopy = pilImage.copy()
  5381. pilImageCopyRGB = pilImageCopy.convert('RGB') # Discard any alpha from the PIL image.
  5382. pilImageRgbData = pilImageCopyRGB.tostring()
  5383. wxImage.SetData(pilImageRgbData)
  5384. return wxImage
  5385. def BBoxAfterRotation(w, h, angle):
  5386. """!Compute bounding box or rotated rectangle
  5387. @param w rectangle width
  5388. @param h rectangle height
  5389. @param angle angle (0, 360) in degrees
  5390. """
  5391. angleRad = angle / 180. * pi
  5392. ct = cos(angleRad)
  5393. st = sin(angleRad)
  5394. hct = h * ct
  5395. wct = w * ct
  5396. hst = h * st
  5397. wst = w * st
  5398. y = x = 0
  5399. if 0 < angle <= 90:
  5400. y_min = y
  5401. y_max = y + hct + wst
  5402. x_min = x - hst
  5403. x_max = x + wct
  5404. elif 90 < angle <= 180:
  5405. y_min = y + hct
  5406. y_max = y + wst
  5407. x_min = x - hst + wct
  5408. x_max = x
  5409. elif 180 < angle <= 270:
  5410. y_min = y + wst + hct
  5411. y_max = y
  5412. x_min = x + wct
  5413. x_max = x - hst
  5414. elif 270 < angle <= 360:
  5415. y_min = y + wst
  5416. y_max = y + hct
  5417. x_min = x
  5418. x_max = x + wct - hst
  5419. width = int(ceil(abs(x_max) + abs(x_min)))
  5420. height = int(ceil(abs(y_max) + abs(y_min)))
  5421. return width, height