psmap_dialogs.py 267 KB

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