psmap_dialogs.py 266 KB

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