psmap_dialogs.py 266 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718
  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. def _rasterLegend(self, notebook):
  3171. panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
  3172. panel.SetupScrolling(scroll_x = False, scroll_y = True)
  3173. notebook.AddPage(page = panel, text = _("Raster legend"))
  3174. border = wx.BoxSizer(wx.VERTICAL)
  3175. # is legend
  3176. self.isRLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show raster legend"))
  3177. self.isRLegend.SetValue(self.rLegendDict['rLegend'])
  3178. border.Add(item = self.isRLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3179. # choose raster
  3180. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source raster"))
  3181. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3182. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  3183. flexSizer.AddGrowableCol(1)
  3184. self.rasterDefault = wx.RadioButton(panel, id = wx.ID_ANY, label = _("current raster"), style = wx.RB_GROUP)
  3185. self.rasterOther = wx.RadioButton(panel, id = wx.ID_ANY, label = _("select raster"))
  3186. self.rasterDefault.SetValue(self.rLegendDict['rasterDefault'])#
  3187. self.rasterOther.SetValue(not self.rLegendDict['rasterDefault'])#
  3188. rasterType = getRasterType(map = self.currRaster)
  3189. self.rasterCurrent = wx.StaticText(panel, id = wx.ID_ANY,
  3190. label = _("%s: type %s" % (self.currRaster, rasterType)))
  3191. self.rasterSelect = Select(panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  3192. type = 'raster', multiple = False,
  3193. updateOnPopup = True, onPopup = None)
  3194. if not self.rLegendDict['rasterDefault']:
  3195. self.rasterSelect.SetValue(self.rLegendDict['raster'])
  3196. else:
  3197. self.rasterSelect.SetValue('')
  3198. flexSizer.Add(self.rasterDefault, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3199. flexSizer.Add(self.rasterCurrent, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
  3200. flexSizer.Add(self.rasterOther, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3201. flexSizer.Add(self.rasterSelect, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3202. sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3203. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3204. # type of legend
  3205. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Type of legend"))
  3206. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3207. vbox = wx.BoxSizer(wx.VERTICAL)
  3208. self.discrete = wx.RadioButton(parent = panel, id = wx.ID_ANY,
  3209. label = " %s " % _("discrete legend (categorical maps)"), style = wx.RB_GROUP)
  3210. self.continuous = wx.RadioButton(parent = panel, id = wx.ID_ANY,
  3211. label = " %s " % _("continuous color gradient legend (floating point map)"))
  3212. vbox.Add(self.discrete, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
  3213. vbox.Add(self.continuous, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0)
  3214. sizer.Add(item = vbox, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3215. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3216. # size, position and font
  3217. self.sizePositionFont(legendType = 'raster', parent = panel, mainSizer = border)
  3218. # advanced settings
  3219. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Advanced legend settings"))
  3220. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3221. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3222. # no data
  3223. self.nodata = wx.CheckBox(panel, id = wx.ID_ANY, label = _('draw "no data" box'))
  3224. if self.rLegendDict['nodata'] == 'y':
  3225. self.nodata.SetValue(True)
  3226. else:
  3227. self.nodata.SetValue(False)
  3228. #tickbar
  3229. self.ticks = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw ticks across color table"))
  3230. if self.rLegendDict['tickbar'] == 'y':
  3231. self.ticks.SetValue(True)
  3232. else:
  3233. self.ticks.SetValue(False)
  3234. # range
  3235. if self.rasterId and self.instruction[self.rasterId]['raster']:
  3236. rinfo = grass.raster_info(self.instruction[self.rasterId]['raster'])
  3237. self.minim, self.maxim = rinfo['min'], rinfo['max']
  3238. else:
  3239. self.minim, self.maxim = 0,0
  3240. self.range = wx.CheckBox(panel, id = wx.ID_ANY, label = _("range"))
  3241. self.range.SetValue(self.rLegendDict['range'])
  3242. self.minText = wx.StaticText(panel, id = wx.ID_ANY, label = "min (%s)" % self.minim)
  3243. self.maxText = wx.StaticText(panel, id = wx.ID_ANY, label = "max (%s)" % self.maxim)
  3244. self.min = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['min']))
  3245. self.max = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['max']))
  3246. gridBagSizer.Add(self.nodata, pos = (0,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3247. gridBagSizer.Add(self.ticks, pos = (1,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3248. gridBagSizer.Add(self.range, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3249. gridBagSizer.Add(self.minText, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3250. gridBagSizer.Add(self.min, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3251. gridBagSizer.Add(self.maxText, pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0)
  3252. gridBagSizer.Add(self.max, pos = (2,4), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3253. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3254. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3255. panel.SetSizer(border)
  3256. panel.Fit()
  3257. # bindings
  3258. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterDefault)
  3259. self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterOther)
  3260. self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isRLegend)
  3261. self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.discrete)
  3262. self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.continuous)
  3263. ## self.Bind(wx.EVT_CHECKBOX, self.OnDefaultSize, panel.defaultSize)
  3264. self.Bind(wx.EVT_CHECKBOX, self.OnRange, self.range)
  3265. self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
  3266. return panel
  3267. def _vectorLegend(self, notebook):
  3268. panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL)
  3269. panel.SetupScrolling(scroll_x = False, scroll_y = True)
  3270. notebook.AddPage(page = panel, text = _("Vector legend"))
  3271. border = wx.BoxSizer(wx.VERTICAL)
  3272. # is legend
  3273. self.isVLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show vector legend"))
  3274. self.isVLegend.SetValue(self.vLegendDict['vLegend'])
  3275. border.Add(item = self.isVLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3276. #vector maps, their order, labels
  3277. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source vector maps"))
  3278. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3279. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3280. gridBagSizer.AddGrowableCol(0,3)
  3281. gridBagSizer.AddGrowableCol(1,1)
  3282. vectorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose vector maps and their order in legend"))
  3283. self.vectorListCtrl = CheckListCtrl(panel)
  3284. self.vectorListCtrl.InsertColumn(0, _("Vector map"))
  3285. self.vectorListCtrl.InsertColumn(1, _("Label"))
  3286. if self.vectorId:
  3287. vectors = sorted(self.instruction[self.vectorId]['list'], key = lambda x: x[3])
  3288. for vector in vectors:
  3289. index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
  3290. self.vectorListCtrl.SetStringItem(index, 1, vector[4])
  3291. self.vectorListCtrl.SetItemData(index, index)
  3292. self.vectorListCtrl.CheckItem(index, True)
  3293. if vector[3] == 0:
  3294. self.vectorListCtrl.CheckItem(index, False)
  3295. if not self.vectorId:
  3296. self.vectorListCtrl.SetColumnWidth(0, 100)
  3297. else:
  3298. self.vectorListCtrl.SetColumnWidth(0, wx.LIST_AUTOSIZE)
  3299. self.vectorListCtrl.SetColumnWidth(1, wx.LIST_AUTOSIZE)
  3300. self.btnUp = wx.Button(panel, id = wx.ID_ANY, label = _("Up"))
  3301. self.btnDown = wx.Button(panel, id = wx.ID_ANY, label = _("Down"))
  3302. self.btnLabel = wx.Button(panel, id = wx.ID_ANY, label = _("Edit label"))
  3303. gridBagSizer.Add(vectorText, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3304. gridBagSizer.Add(self.vectorListCtrl, pos = (1,0), span = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3305. gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3306. gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3307. gridBagSizer.Add(self.btnLabel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3308. sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  3309. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3310. # size, position and font
  3311. self.sizePositionFont(legendType = 'vector', parent = panel, mainSizer = border)
  3312. # border
  3313. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Border"))
  3314. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3315. flexGridSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
  3316. self.borderCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw border around legend"))
  3317. self.borderColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY, style = wx.FNTP_FONTDESC_AS_LABEL)
  3318. if self.vLegendDict['border'] == 'none':
  3319. self.borderColorCtrl.SetColour('black')
  3320. self.borderCheck.SetValue(False)
  3321. else:
  3322. self.borderColorCtrl.SetColour(convertRGB(self.vLegendDict['border']))
  3323. self.borderCheck.SetValue(True)
  3324. flexGridSizer.Add(self.borderCheck, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3325. flexGridSizer.Add(self.borderColorCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3326. sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3327. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3328. self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp)
  3329. self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown)
  3330. self.Bind(wx.EVT_BUTTON, self.OnEditLabel, self.btnLabel)
  3331. self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isVLegend)
  3332. self.Bind(wx.EVT_CHECKBOX, self.OnSpan, panel.spanRadio)
  3333. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck)
  3334. self.Bind(wx.EVT_FONTPICKER_CHANGED, self.OnFont, panel.font['fontCtrl'])
  3335. panel.SetSizer(border)
  3336. panel.Fit()
  3337. return panel
  3338. def sizePositionFont(self, legendType, parent, mainSizer):
  3339. """!Insert widgets for size, position and font control"""
  3340. if legendType == 'raster':
  3341. legendDict = self.rLegendDict
  3342. else:
  3343. legendDict = self.vLegendDict
  3344. panel = parent
  3345. border = mainSizer
  3346. # size and position
  3347. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size and position"))
  3348. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3349. #unit
  3350. self.AddUnits(parent = panel, dialogDict = legendDict)
  3351. unitBox = wx.BoxSizer(wx.HORIZONTAL)
  3352. unitBox.Add(panel.units['unitsLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10)
  3353. unitBox.Add(panel.units['unitsCtrl'], proportion = 1, flag = wx.ALL, border = 5)
  3354. sizer.Add(unitBox, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3355. hBox = wx.BoxSizer(wx.HORIZONTAL)
  3356. posBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Position"))
  3357. posSizer = wx.StaticBoxSizer(posBox, wx.VERTICAL)
  3358. sizeBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  3359. sizeSizer = wx.StaticBoxSizer(sizeBox, wx.VERTICAL)
  3360. posGridBagSizer = wx.GridBagSizer(hgap = 10, vgap = 5)
  3361. posGridBagSizer.AddGrowableRow(2)
  3362. #position
  3363. self.AddPosition(parent = panel, dialogDict = legendDict)
  3364. posGridBagSizer.Add(panel.position['xLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3365. posGridBagSizer.Add(panel.position['xCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3366. posGridBagSizer.Add(panel.position['yLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3367. posGridBagSizer.Add(panel.position['yCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3368. posGridBagSizer.Add(panel.position['comment'], pos = (2,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  3369. posSizer.Add(posGridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3370. #size
  3371. width = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width:"))
  3372. if legendDict['width']:
  3373. w = self.unitConv.convert(value = float(legendDict['width']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3374. else:
  3375. w = ''
  3376. panel.widthCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(w), validator = TCValidator("DIGIT_ONLY"))
  3377. panel.widthCtrl.SetToolTipString(_("Leave the edit field empty, to use default values."))
  3378. if legendType == 'raster':
  3379. ## panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size"))
  3380. ## panel.defaultSize.SetValue(legendDict['defaultSize'])
  3381. panel.heightOrColumnsLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
  3382. if legendDict['height']:
  3383. h = self.unitConv.convert(value = float(legendDict['height']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3384. else:
  3385. h = ''
  3386. panel.heightOrColumnsCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(h), validator = TCValidator("DIGIT_ONLY"))
  3387. self.rSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3388. ## self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3389. self.rSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3390. self.rSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3391. self.rSizeGBSizer.Add(panel.heightOrColumnsLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3392. self.rSizeGBSizer.Add(panel.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3393. sizeSizer.Add(self.rSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3394. if legendType == 'vector':
  3395. panel.widthCtrl.SetToolTipString(_("Width of the color symbol (for lines)\nin front of the legend text"))
  3396. #columns
  3397. minVect, maxVect = 0, 0
  3398. if self.vectorId:
  3399. minVect = 1
  3400. maxVect = min(10, len(self.instruction[self.vectorId]['list']))
  3401. cols = wx.StaticText(panel, id = wx.ID_ANY, label = _("Columns:"))
  3402. panel.colsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, value = "",
  3403. min = minVect, max = maxVect, initial = legendDict['cols'])
  3404. #span
  3405. panel.spanRadio = wx.CheckBox(panel, id = wx.ID_ANY, label = _("column span:"))
  3406. panel.spanTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = '')
  3407. panel.spanTextCtrl.SetToolTipString(_("Column separation distance between the left edges\n"\
  3408. "of two columns in a multicolumn legend"))
  3409. if legendDict['span']:
  3410. panel.spanRadio.SetValue(True)
  3411. s = self.unitConv.convert(value = float(legendDict['span']), fromUnit = 'inch', toUnit = legendDict['unit'])
  3412. panel.spanTextCtrl.SetValue(str(s))
  3413. else:
  3414. panel.spanRadio.SetValue(False)
  3415. self.vSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3416. self.vSizeGBSizer.AddGrowableCol(1)
  3417. self.vSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3418. self.vSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3419. self.vSizeGBSizer.Add(cols, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3420. self.vSizeGBSizer.Add(panel.colsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3421. self.vSizeGBSizer.Add(panel.spanRadio, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3422. self.vSizeGBSizer.Add(panel.spanTextCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3423. sizeSizer.Add(self.vSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3424. hBox.Add(posSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
  3425. hBox.Add(sizeSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3)
  3426. sizer.Add(hBox, proportion = 0, flag = wx.EXPAND, border = 0)
  3427. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3428. # font
  3429. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  3430. fontSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3431. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  3432. flexSizer.AddGrowableCol(1)
  3433. if legendType == 'raster':
  3434. self.AddFont(parent = panel, dialogDict = legendDict, color = True)
  3435. else:
  3436. self.AddFont(parent = panel, dialogDict = legendDict, color = False)
  3437. flexSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3438. flexSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3439. flexSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3440. flexSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3441. if legendType == 'raster':
  3442. flexSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3443. flexSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3444. fontSizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3445. border.Add(item = fontSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3446. # some enable/disable methods
  3447. def OnIsLegend(self, event):
  3448. """!Enables and disables controls, it depends if raster or vector legend is checked"""
  3449. page = self.notebook.GetSelection()
  3450. if page == 0 or event is None:
  3451. children = self.panelRaster.GetChildren()
  3452. if self.isRLegend.GetValue():
  3453. for i,widget in enumerate(children):
  3454. widget.Enable()
  3455. self.OnRaster(None)
  3456. self.OnRange(None)
  3457. self.OnDiscrete(None)
  3458. else:
  3459. for i,widget in enumerate(children):
  3460. if i != 0:
  3461. widget.Disable()
  3462. if page == 1 or event is None:
  3463. children = self.panelVector.GetChildren()
  3464. if self.isVLegend.GetValue():
  3465. for i, widget in enumerate(children):
  3466. widget.Enable()
  3467. self.OnSpan(None)
  3468. self.OnBorder(None)
  3469. else:
  3470. for i, widget in enumerate(children):
  3471. if i != 0:
  3472. widget.Disable()
  3473. def OnRaster(self, event):
  3474. if self.rasterDefault.GetValue():#default
  3475. self.rasterSelect.Disable()
  3476. type = getRasterType(self.currRaster)
  3477. else:#select raster
  3478. self.rasterSelect.Enable()
  3479. map = self.rasterSelect.GetValue()
  3480. type = getRasterType(map)
  3481. if type == 'CELL':
  3482. self.discrete.SetValue(True)
  3483. elif type in ('FCELL', 'DCELL'):
  3484. self.continuous.SetValue(True)
  3485. if event is None:
  3486. if self.rLegendDict['discrete'] == 'y':
  3487. self.discrete.SetValue(True)
  3488. elif self.rLegendDict['discrete'] == 'n':
  3489. self.continuous.SetValue(True)
  3490. self.OnDiscrete(None)
  3491. def OnDiscrete(self, event):
  3492. """! Change control according to the type of legend"""
  3493. enabledSize = self.panelRaster.heightOrColumnsCtrl.IsEnabled()
  3494. self.panelRaster.heightOrColumnsCtrl.Destroy()
  3495. if self.discrete.GetValue():
  3496. self.panelRaster.heightOrColumnsLabel.SetLabel(_("Columns:"))
  3497. self.panelRaster.heightOrColumnsCtrl = wx.SpinCtrl(self.panelRaster, id = wx.ID_ANY, value = "", min = 1, max = 10, initial = self.rLegendDict['cols'])
  3498. self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
  3499. self.nodata.Enable()
  3500. self.range.Disable()
  3501. self.min.Disable()
  3502. self.max.Disable()
  3503. self.minText.Disable()
  3504. self.maxText.Disable()
  3505. self.ticks.Disable()
  3506. else:
  3507. self.panelRaster.heightOrColumnsLabel.SetLabel(_("Height:"))
  3508. if self.rLegendDict['height']:
  3509. h = self.unitConv.convert(value = float(self.rLegendDict['height']), fromUnit = 'inch', toUnit = self.rLegendDict['unit'])
  3510. else:
  3511. h = ''
  3512. self.panelRaster.heightOrColumnsCtrl = wx.TextCtrl(self.panelRaster, id = wx.ID_ANY,
  3513. value = str(h), validator = TCValidator("DIGIT_ONLY"))
  3514. self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
  3515. self.nodata.Disable()
  3516. self.range.Enable()
  3517. if self.range.GetValue():
  3518. self.minText.Enable()
  3519. self.maxText.Enable()
  3520. self.min.Enable()
  3521. self.max.Enable()
  3522. self.ticks.Enable()
  3523. self.rSizeGBSizer.Add(self.panelRaster.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3524. self.panelRaster.Layout()
  3525. self.panelRaster.Fit()
  3526. def OnRange(self, event):
  3527. if not self.range.GetValue():
  3528. self.min.Disable()
  3529. self.max.Disable()
  3530. self.minText.Disable()
  3531. self.maxText.Disable()
  3532. else:
  3533. self.min.Enable()
  3534. self.max.Enable()
  3535. self.minText.Enable()
  3536. self.maxText.Enable()
  3537. def OnUp(self, event):
  3538. """!Moves selected map up, changes order in vector legend"""
  3539. if self.vectorListCtrl.GetFirstSelected() != -1:
  3540. pos = self.vectorListCtrl.GetFirstSelected()
  3541. if pos:
  3542. idx1 = self.vectorListCtrl.GetItemData(pos) - 1
  3543. idx2 = self.vectorListCtrl.GetItemData(pos - 1) + 1
  3544. self.vectorListCtrl.SetItemData(pos, idx1)
  3545. self.vectorListCtrl.SetItemData(pos - 1, idx2)
  3546. self.vectorListCtrl.SortItems(cmp)
  3547. if pos > 0:
  3548. selected = (pos - 1)
  3549. else:
  3550. selected = 0
  3551. self.vectorListCtrl.Select(selected)
  3552. def OnDown(self, event):
  3553. """!Moves selected map down, changes order in vector legend"""
  3554. if self.vectorListCtrl.GetFirstSelected() != -1:
  3555. pos = self.vectorListCtrl.GetFirstSelected()
  3556. if pos != self.vectorListCtrl.GetItemCount() - 1:
  3557. idx1 = self.vectorListCtrl.GetItemData(pos) + 1
  3558. idx2 = self.vectorListCtrl.GetItemData(pos + 1) - 1
  3559. self.vectorListCtrl.SetItemData(pos, idx1)
  3560. self.vectorListCtrl.SetItemData(pos + 1, idx2)
  3561. self.vectorListCtrl.SortItems(cmp)
  3562. if pos < self.vectorListCtrl.GetItemCount() -1:
  3563. selected = (pos + 1)
  3564. else:
  3565. selected = self.vectorListCtrl.GetItemCount() -1
  3566. self.vectorListCtrl.Select(selected)
  3567. def OnEditLabel(self, event):
  3568. """!Change legend label of vector map"""
  3569. if self.vectorListCtrl.GetFirstSelected() != -1:
  3570. idx = self.vectorListCtrl.GetFirstSelected()
  3571. default = self.vectorListCtrl.GetItem(idx, 1).GetText()
  3572. dlg = wx.TextEntryDialog(self, message = _("Edit legend label:"), caption = _("Edit label"),
  3573. defaultValue = default, style = wx.OK|wx.CANCEL|wx.CENTRE)
  3574. if dlg.ShowModal() == wx.ID_OK:
  3575. new = dlg.GetValue()
  3576. self.vectorListCtrl.SetStringItem(idx, 1, new)
  3577. dlg.Destroy()
  3578. def OnSpan(self, event):
  3579. self.panelVector.spanTextCtrl.Enable(self.panelVector.spanRadio.GetValue())
  3580. def OnFont(self, event):
  3581. """!Changes default width according to fontsize, width [inch] = fontsize[pt]/24"""
  3582. ## fontsize = self.panelVector.font['fontCtrl'].GetSelectedFont().GetPointSize()
  3583. fontsize = self.panelVector.font['fontSizeCtrl'].GetValue()
  3584. unit = self.panelVector.units['unitsCtrl'].GetStringSelection()
  3585. w = fontsize/24.
  3586. width = self.unitConv.convert(value = w, fromUnit = 'inch', toUnit = unit)
  3587. self.panelVector.widthCtrl.SetValue("%3.2f" % width)
  3588. def OnBorder(self, event):
  3589. """!Enables/disables colorPickerCtrl for border"""
  3590. self.borderColorCtrl.Enable(self.borderCheck.GetValue())
  3591. def updateRasterLegend(self):
  3592. """!Save information from raster legend dialog to dictionary"""
  3593. #is raster legend
  3594. if not self.isRLegend.GetValue():
  3595. self.rLegendDict['rLegend'] = False
  3596. else:
  3597. self.rLegendDict['rLegend'] = True
  3598. #units
  3599. currUnit = self.panelRaster.units['unitsCtrl'].GetStringSelection()
  3600. self.rLegendDict['unit'] = currUnit
  3601. # raster
  3602. if self.rasterDefault.GetValue():
  3603. self.rLegendDict['rasterDefault'] = True
  3604. self.rLegendDict['raster'] = self.currRaster
  3605. else:
  3606. self.rLegendDict['rasterDefault'] = False
  3607. self.rLegendDict['raster'] = self.rasterSelect.GetValue()
  3608. if self.rLegendDict['rLegend'] and not self.rLegendDict['raster']:
  3609. wx.MessageBox(message = _("No raster map selected!"),
  3610. caption = _('No raster'), style = wx.OK|wx.ICON_ERROR)
  3611. return False
  3612. if self.rLegendDict['raster']:
  3613. # type and range of map
  3614. rasterType = getRasterType(self.rLegendDict['raster'])
  3615. if rasterType is None:
  3616. return False
  3617. self.rLegendDict['type'] = rasterType
  3618. #discrete
  3619. if self.discrete.GetValue():
  3620. self.rLegendDict['discrete'] = 'y'
  3621. else:
  3622. self.rLegendDict['discrete'] = 'n'
  3623. # font
  3624. self.rLegendDict['font'] = self.panelRaster.font['fontCtrl'].GetStringSelection()
  3625. self.rLegendDict['fontsize'] = self.panelRaster.font['fontSizeCtrl'].GetValue()
  3626. ## font = self.panelRaster.font['fontCtrl'].GetSelectedFont()
  3627. ## self.rLegendDict['font'] = font.GetFaceName()
  3628. ## self.rLegendDict['fontsize'] = font.GetPointSize()
  3629. color = self.panelRaster.font['colorCtrl'].GetColour()
  3630. ## if color.GetAsString(wx.C2S_NAME) in PSMAP_COLORS:
  3631. ## self.rLegendDict['color'] = color.GetAsString(wx.C2S_NAME)
  3632. ## else:
  3633. self.rLegendDict['color'] = convertRGB(color)
  3634. # position
  3635. x = self.unitConv.convert(value = float(self.panelRaster.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3636. y = self.unitConv.convert(value = float(self.panelRaster.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3637. self.rLegendDict['where'] = (x, y)
  3638. # estimated size
  3639. width = self.panelRaster.widthCtrl.GetValue()
  3640. try:
  3641. width = float(width)
  3642. width = self.unitConv.convert(value = width, fromUnit = currUnit, toUnit = 'inch')
  3643. except ValueError:
  3644. width = None
  3645. self.rLegendDict['width'] = width
  3646. if self.rLegendDict['discrete'] == 'n':
  3647. height = self.panelRaster.heightOrColumnsCtrl.GetValue()
  3648. try:
  3649. height = float(height)
  3650. height = self.unitConv.convert(value = height, fromUnit = currUnit, toUnit = 'inch')
  3651. except ValueError:
  3652. height = None
  3653. self.rLegendDict['height'] = height
  3654. else:
  3655. cols = self.panelRaster.heightOrColumnsCtrl.GetValue()
  3656. self.rLegendDict['cols'] = cols
  3657. drawHeight = self.rasterLegend.EstimateHeight(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
  3658. fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
  3659. height = self.rLegendDict['height'])
  3660. drawWidth = self.rasterLegend.EstimateWidth(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
  3661. fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
  3662. width = self.rLegendDict['width'], paperInstr = self.instruction[self.pageId])
  3663. self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
  3664. # no data
  3665. if self.rLegendDict['discrete'] == 'y':
  3666. if self.nodata.GetValue():
  3667. self.rLegendDict['nodata'] = 'y'
  3668. else:
  3669. self.rLegendDict['nodata'] = 'n'
  3670. # tickbar
  3671. elif self.rLegendDict['discrete'] == 'n':
  3672. if self.ticks.GetValue():
  3673. self.rLegendDict['tickbar'] = 'y'
  3674. else:
  3675. self.rLegendDict['tickbar'] = 'n'
  3676. # range
  3677. if self.range.GetValue():
  3678. self.rLegendDict['range'] = True
  3679. self.rLegendDict['min'] = self.min.GetValue()
  3680. self.rLegendDict['max'] = self.max.GetValue()
  3681. else:
  3682. self.rLegendDict['range'] = False
  3683. if not self.id[0] in self.instruction:
  3684. rasterLegend = RasterLegend(self.id[0])
  3685. self.instruction.AddInstruction(rasterLegend)
  3686. self.instruction[self.id[0]].SetInstruction(self.rLegendDict)
  3687. if self.id[0] not in self.parent.objectId:
  3688. self.parent.objectId.append(self.id[0])
  3689. return True
  3690. def updateVectorLegend(self):
  3691. """!Save information from vector legend dialog to dictionary"""
  3692. vector = self.instruction.FindInstructionByType('vector')
  3693. if vector:
  3694. self.vectorId = vector.id
  3695. else:
  3696. self.vectorId = None
  3697. #is vector legend
  3698. if not self.isVLegend.GetValue():
  3699. self.vLegendDict['vLegend'] = False
  3700. else:
  3701. self.vLegendDict['vLegend'] = True
  3702. if self.vLegendDict['vLegend'] == True and self.vectorId is not None:
  3703. # labels
  3704. #reindex order
  3705. idx = 1
  3706. for item in range(self.vectorListCtrl.GetItemCount()):
  3707. if self.vectorListCtrl.IsChecked(item):
  3708. self.vectorListCtrl.SetItemData(item, idx)
  3709. idx += 1
  3710. else:
  3711. self.vectorListCtrl.SetItemData(item, 0)
  3712. if idx == 1:
  3713. self.vLegendDict['vLegend'] = False
  3714. else:
  3715. vList = self.instruction[self.vectorId]['list']
  3716. for i, vector in enumerate(vList):
  3717. item = self.vectorListCtrl.FindItem(start = -1, str = vector[0].split('@')[0])
  3718. vList[i][3] = self.vectorListCtrl.GetItemData(item)
  3719. vList[i][4] = self.vectorListCtrl.GetItem(item, 1).GetText()
  3720. vmaps = self.instruction.FindInstructionByType('vProperties', list = True)
  3721. for vmap, vector in zip(vmaps, vList):
  3722. self.instruction[vmap.id]['lpos'] = vector[3]
  3723. self.instruction[vmap.id]['label'] = vector[4]
  3724. #units
  3725. currUnit = self.panelVector.units['unitsCtrl'].GetStringSelection()
  3726. self.vLegendDict['unit'] = currUnit
  3727. # position
  3728. x = self.unitConv.convert(value = float(self.panelVector.position['xCtrl'].GetValue()),
  3729. fromUnit = currUnit, toUnit = 'inch')
  3730. y = self.unitConv.convert(value = float(self.panelVector.position['yCtrl'].GetValue()),
  3731. fromUnit = currUnit, toUnit = 'inch')
  3732. self.vLegendDict['where'] = (x, y)
  3733. # font
  3734. self.vLegendDict['font'] = self.panelVector.font['fontCtrl'].GetStringSelection()
  3735. self.vLegendDict['fontsize'] = self.panelVector.font['fontSizeCtrl'].GetValue()
  3736. ## self.vLegendDict['font'] = font.GetFaceName()
  3737. ## self.vLegendDict['fontsize'] = font.GetPointSize()
  3738. dc = wx.PaintDC(self)
  3739. font = dc.GetFont()
  3740. dc.SetFont(wx.Font(pointSize = self.vLegendDict['fontsize'], family = font.GetFamily(),
  3741. style = font.GetStyle(), weight = wx.FONTWEIGHT_NORMAL))
  3742. #size
  3743. width = self.unitConv.convert(value = float(self.panelVector.widthCtrl.GetValue()),
  3744. fromUnit = currUnit, toUnit = 'inch')
  3745. self.vLegendDict['width'] = width
  3746. self.vLegendDict['cols'] = self.panelVector.colsCtrl.GetValue()
  3747. if self.panelVector.spanRadio.GetValue() and self.panelVector.spanTextCtrl.GetValue():
  3748. self.vLegendDict['span'] = self.panelVector.spanTextCtrl.GetValue()
  3749. else:
  3750. self.vLegendDict['span'] = None
  3751. # size estimation
  3752. vectors = self.instruction[self.vectorId]['list']
  3753. labels = [vector[4] for vector in vectors if vector[3] != 0]
  3754. extent = dc.GetTextExtent(max(labels, key = len))
  3755. wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'pixel', toUnit = 'inch')
  3756. hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'pixel', toUnit = 'inch')
  3757. w = (width + wExtent) * self.vLegendDict['cols']
  3758. h = len(labels) * hExtent / self.vLegendDict['cols']
  3759. h *= 1.1
  3760. self.vLegendDict['rect'] = wx.Rect2D(x, y, w, h)
  3761. #border
  3762. if self.borderCheck.GetValue():
  3763. color = self.borderColorCtrl.GetColour()
  3764. ## if color.GetAsString(wx.C2S_NAME) in PSMAP_COLORS:
  3765. ## self.vLegendDict['border'] = color.GetAsString(wx.C2S_NAME)
  3766. ## else:
  3767. self.vLegendDict['border'] = convertRGB(color)
  3768. else:
  3769. self.vLegendDict['border'] = 'none'
  3770. if not self.id[1] in self.instruction:
  3771. vectorLegend = VectorLegend(self.id[1])
  3772. self.instruction.AddInstruction(vectorLegend)
  3773. self.instruction[self.id[1]].SetInstruction(self.vLegendDict)
  3774. if self.id[1] not in self.parent.objectId:
  3775. self.parent.objectId.append(self.id[1])
  3776. return True
  3777. def update(self):
  3778. okR = self.updateRasterLegend()
  3779. okV = self.updateVectorLegend()
  3780. if okR and okV:
  3781. return True
  3782. return False
  3783. def updateDialog(self):
  3784. """!Update legend coordinates after moving"""
  3785. # raster legend
  3786. if 'rect' in self.rLegendDict:
  3787. x, y = self.rLegendDict['rect'][:2]
  3788. currUnit = self.panelRaster.units['unitsCtrl'].GetStringSelection()
  3789. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  3790. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  3791. self.panelRaster.position['xCtrl'].SetValue("%5.3f" % x)
  3792. self.panelRaster.position['yCtrl'].SetValue("%5.3f" % y)
  3793. #update name and type of raster
  3794. raster = self.instruction.FindInstructionByType('raster')
  3795. if raster:
  3796. self.rasterId = raster.id
  3797. else:
  3798. self.rasterId = None
  3799. if raster:
  3800. currRaster = raster['raster']
  3801. else:
  3802. currRaster = None
  3803. rasterType = getRasterType(map = currRaster)
  3804. self.rasterCurrent.SetLabel(_("%s: type %s") % (currRaster, str(rasterType)))
  3805. # vector legend
  3806. if 'rect' in self.vLegendDict:
  3807. x, y = self.vLegendDict['rect'][:2]
  3808. currUnit = self.panelVector.units['unitsCtrl'].GetStringSelection()
  3809. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  3810. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  3811. self.panelVector.position['xCtrl'].SetValue("%5.3f" % x)
  3812. self.panelVector.position['yCtrl'].SetValue("%5.3f" % y)
  3813. # update vector maps
  3814. if self.instruction.FindInstructionByType('vector'):
  3815. vectors = sorted(self.instruction.FindInstructionByType('vector')['list'], key = lambda x: x[3])
  3816. self.vectorListCtrl.DeleteAllItems()
  3817. for vector in vectors:
  3818. index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0])
  3819. self.vectorListCtrl.SetStringItem(index, 1, vector[4])
  3820. self.vectorListCtrl.SetItemData(index, index)
  3821. self.vectorListCtrl.CheckItem(index, True)
  3822. if vector[3] == 0:
  3823. self.vectorListCtrl.CheckItem(index, False)
  3824. self.panelVector.colsCtrl.SetRange(1, min(10, len(self.instruction.FindInstructionByType('vector')['list'])))
  3825. self.panelVector.colsCtrl.SetValue(1)
  3826. else:
  3827. self.vectorListCtrl.DeleteAllItems()
  3828. self.panelVector.colsCtrl.SetRange(0,0)
  3829. self.panelVector.colsCtrl.SetValue(0)
  3830. class MapinfoDialog(PsmapDialog):
  3831. def __init__(self, parent, id, settings):
  3832. PsmapDialog.__init__(self, parent = parent, id = id, title = "Mapinfo settings", settings = settings)
  3833. self.objectType = ('mapinfo',)
  3834. if self.id is not None:
  3835. self.mapinfo = self.instruction[self.id]
  3836. self.mapinfoDict = self.mapinfo.GetInstruction()
  3837. else:
  3838. self.id = wx.NewId()
  3839. self.mapinfo = Mapinfo(self.id)
  3840. self.mapinfoDict = self.mapinfo.GetInstruction()
  3841. page = self.instruction.FindInstructionByType('page').GetInstruction()
  3842. self.mapinfoDict['where'] = page['Left'], page['Top']
  3843. self.panel = self._mapinfoPanel()
  3844. self._layout(self.panel)
  3845. self.OnIsBackground(None)
  3846. self.OnIsBorder(None)
  3847. def _mapinfoPanel(self):
  3848. panel = wx.Panel(parent = self, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL)
  3849. #panel.SetupScrolling(scroll_x = False, scroll_y = True)
  3850. border = wx.BoxSizer(wx.VERTICAL)
  3851. # position
  3852. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  3853. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3854. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3855. gridBagSizer.AddGrowableCol(1)
  3856. self.AddPosition(parent = panel, dialogDict = self.mapinfoDict)
  3857. self.AddUnits(parent = panel, dialogDict = self.mapinfoDict)
  3858. gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3859. gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3860. gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3861. gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3862. gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3863. gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3864. gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  3865. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  3866. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3867. # font
  3868. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  3869. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3870. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  3871. gridBagSizer.AddGrowableCol(1)
  3872. self.AddFont(parent = panel, dialogDict = self.mapinfoDict)#creates font color too, used below
  3873. ## gridBagSizer.Add(panel.font['fontLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3874. ## gridBagSizer.Add(panel.font['fontCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3875. ## gridBagSizer.Add(panel.font['colorLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3876. ## gridBagSizer.Add(panel.font['colorCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3877. gridBagSizer.Add(panel.font['fontLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3878. gridBagSizer.Add(panel.font['fontCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3879. gridBagSizer.Add(panel.font['fontSizeLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3880. gridBagSizer.Add(panel.font['fontSizeCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3881. gridBagSizer.Add(panel.font['colorLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3882. gridBagSizer.Add(panel.font['colorCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3883. sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3884. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3885. # colors
  3886. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Color settings"))
  3887. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  3888. flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
  3889. flexSizer.AddGrowableCol(1)
  3890. self.colors = {}
  3891. self.colors['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use border color:"))
  3892. self.colors['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use background color:"))
  3893. self.colors['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  3894. self.colors['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  3895. if self.mapinfoDict['border'] != 'none':
  3896. self.colors['borderCtrl'].SetValue(True)
  3897. else:
  3898. self.colors['borderCtrl'].SetValue(False)
  3899. if self.mapinfoDict['background'] != 'none':
  3900. self.colors['backgroundCtrl'].SetValue(True)
  3901. else:
  3902. self.colors['backgroundCtrl'].SetValue(False)
  3903. if self.mapinfoDict['border'] != 'none':
  3904. self.colors['borderColor'].SetColour(convertRGB(self.mapinfoDict['border']))
  3905. else:
  3906. self.colors['borderColor'].SetColour('black')
  3907. if self.mapinfoDict['background'] != 'none':
  3908. self.colors['backgroundColor'].SetColour(convertRGB(self.mapinfoDict['background']))
  3909. else:
  3910. self.colors['backgroundColor'].SetColour('black')
  3911. flexSizer.Add(self.colors['borderCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3912. flexSizer.Add(self.colors['borderColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3913. flexSizer.Add(self.colors['backgroundCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3914. flexSizer.Add(self.colors['backgroundColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  3915. sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  3916. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  3917. panel.SetSizer(border)
  3918. self.Bind(wx.EVT_CHECKBOX, self.OnIsBorder, self.colors['borderCtrl'])
  3919. self.Bind(wx.EVT_CHECKBOX, self.OnIsBackground, self.colors['backgroundCtrl'])
  3920. return panel
  3921. def OnIsBackground(self, event):
  3922. if self.colors['backgroundCtrl'].GetValue():
  3923. self.colors['backgroundColor'].Enable()
  3924. else:
  3925. self.colors['backgroundColor'].Disable()
  3926. def OnIsBorder(self, event):
  3927. if self.colors['borderCtrl'].GetValue():
  3928. self.colors['borderColor'].Enable()
  3929. else:
  3930. self.colors['borderColor'].Disable()
  3931. def update(self):
  3932. #units
  3933. currUnit = self.panel.units['unitsCtrl'].GetStringSelection()
  3934. self.mapinfoDict['unit'] = currUnit
  3935. # position
  3936. if self.panel.position['xCtrl'].GetValue():
  3937. x = self.panel.position['xCtrl'].GetValue()
  3938. else:
  3939. x = self.mapinfoDict['where'][0]
  3940. if self.panel.position['yCtrl'].GetValue():
  3941. y = self.panel.position['yCtrl'].GetValue()
  3942. else:
  3943. y = self.mapinfoDict['where'][1]
  3944. x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3945. y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  3946. self.mapinfoDict['where'] = (x, y)
  3947. # font
  3948. self.mapinfoDict['font'] = self.panel.font['fontCtrl'].GetStringSelection()
  3949. self.mapinfoDict['fontsize'] = self.panel.font['fontSizeCtrl'].GetValue()
  3950. ## font = self.panel.font['fontCtrl'].GetSelectedFont()
  3951. ## self.mapinfoDict['font'] = font.GetFaceName()
  3952. ## self.mapinfoDict['fontsize'] = font.GetPointSize()
  3953. #colors
  3954. color = self.panel.font['colorCtrl'].GetColour()
  3955. ## if color.GetAsString(wx.C2S_NAME) in PSMAP_COLORS:
  3956. ## self.mapinfoDict['color'] = color.GetAsString(wx.C2S_NAME)
  3957. ## else:
  3958. self.mapinfoDict['color'] = convertRGB(color)
  3959. if self.colors['backgroundCtrl'].GetValue():
  3960. background = self.colors['backgroundColor'].GetColour()
  3961. ## if background.GetAsString(wx.C2S_NAME) in PSMAP_COLORS:
  3962. ## self.mapinfoDict['background'] = background.GetAsString(wx.C2S_NAME)
  3963. ## else:
  3964. self.mapinfoDict['background'] = convertRGB(background)
  3965. else:
  3966. self.mapinfoDict['background'] = 'none'
  3967. if self.colors['borderCtrl'].GetValue():
  3968. border = self.colors['borderColor'].GetColour()
  3969. ## if border.GetAsString(wx.C2S_NAME) in PSMAP_COLORS:
  3970. ## self.mapinfoDict['border'] = border.GetAsString(wx.C2S_NAME)
  3971. ## else:
  3972. self.mapinfoDict['border'] = convertRGB(border)
  3973. else:
  3974. self.mapinfoDict['border'] = 'none'
  3975. # estimation of size
  3976. self.mapinfoDict['rect'] = self.mapinfo.EstimateRect(self.mapinfoDict)
  3977. if self.id not in self.instruction:
  3978. mapinfo = Mapinfo(self.id)
  3979. self.instruction.AddInstruction(mapinfo)
  3980. self.instruction[self.id].SetInstruction(self.mapinfoDict)
  3981. if self.id not in self.parent.objectId:
  3982. self.parent.objectId.append(self.id)
  3983. return True
  3984. def updateDialog(self):
  3985. """!Update mapinfo coordinates, after moving"""
  3986. x, y = self.mapinfoDict['where']
  3987. currUnit = self.panel.units['unitsCtrl'].GetStringSelection()
  3988. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  3989. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  3990. self.panel.position['xCtrl'].SetValue("%5.3f" % x)
  3991. self.panel.position['yCtrl'].SetValue("%5.3f" % y)
  3992. class ScalebarDialog(PsmapDialog):
  3993. """!Dialog for scale bar"""
  3994. def __init__(self, parent, id, settings):
  3995. PsmapDialog.__init__(self, parent = parent, id = id, title = "Scale bar settings", settings = settings)
  3996. self.objectType = ('scalebar',)
  3997. if self.id is not None:
  3998. self.scalebar = self.instruction[id]
  3999. self.scalebarDict = self.scalebar.GetInstruction()
  4000. else:
  4001. self.id = wx.NewId()
  4002. self.scalebar = Scalebar(self.id)
  4003. self.scalebarDict = self.scalebar.GetInstruction()
  4004. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4005. self.scalebarDict['where'] = page['Left'], page['Top']
  4006. self.panel = self._scalebarPanel()
  4007. self._layout(self.panel)
  4008. self.mapUnit = projInfo()['units'].lower()
  4009. if projInfo()['proj'] == 'xy':
  4010. self.mapUnit = 'meters'
  4011. if self.mapUnit not in self.unitConv.getAllUnits():
  4012. wx.MessageBox(message = _("Units of current projection are not supported,\n meters will be used!"),
  4013. caption = _('Unsupported units'),
  4014. style = wx.OK|wx.ICON_ERROR)
  4015. self.mapUnit = 'meters'
  4016. def _scalebarPanel(self):
  4017. panel = wx.Panel(parent = self, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4018. border = wx.BoxSizer(wx.VERTICAL)
  4019. #
  4020. # position
  4021. #
  4022. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4023. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4024. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4025. gridBagSizer.AddGrowableCol(1)
  4026. self.AddUnits(parent = panel, dialogDict = self.scalebarDict)
  4027. self.AddPosition(parent = panel, dialogDict = self.scalebarDict)
  4028. if self.scalebarDict['rect']: # set position, ref point is center and not left top corner
  4029. x = self.unitConv.convert(value = self.scalebarDict['where'][0] - self.scalebarDict['rect'].Get()[2]/2,
  4030. fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
  4031. y = self.unitConv.convert(value = self.scalebarDict['where'][1] - self.scalebarDict['rect'].Get()[3]/2,
  4032. fromUnit = 'inch', toUnit = self.scalebarDict['unit'])
  4033. panel.position['xCtrl'].SetValue("%5.3f" % x)
  4034. panel.position['yCtrl'].SetValue("%5.3f" % y)
  4035. gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4036. gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4037. gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4038. gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4039. gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4040. gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4041. gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0)
  4042. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4043. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4044. #
  4045. # size
  4046. #
  4047. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size"))
  4048. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4049. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4050. gridBagSizer.AddGrowableCol(1)
  4051. lengthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Length:"))
  4052. heightText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
  4053. self.lengthTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
  4054. self.lengthTextCtrl.SetToolTipString(_("Scalebar length is given in map units"))
  4055. self.heightTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY'))
  4056. self.heightTextCtrl.SetToolTipString(_("Scalebar height is real height on paper"))
  4057. choices = ['default'] + self.unitConv.getMapUnits()
  4058. self.unitsLength = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
  4059. choices = self.unitConv.getPageUnits()
  4060. self.unitsHeight = wx.Choice(panel, id = wx.ID_ANY, choices = choices)
  4061. # set values
  4062. ok = self.unitsLength.SetStringSelection(self.scalebarDict['unitsLength'])
  4063. if not ok:
  4064. if self.scalebarDict['unitsLength'] == 'auto':
  4065. self.unitsLength.SetSelection(0)
  4066. elif self.scalebarDict['unitsLength'] == 'nautmiles':
  4067. self.unitsLength.SetStringSelection("nautical miles")
  4068. self.unitsHeight.SetStringSelection(self.scalebarDict['unitsHeight'])
  4069. if self.scalebarDict['length']:
  4070. self.lengthTextCtrl.SetValue(str(self.scalebarDict['length']))
  4071. else: #estimate default
  4072. reg = grass.region()
  4073. w = int((reg['e'] - reg['w'])/3)
  4074. w = round(w, -len(str(w)) + 2) #12345 -> 12000
  4075. self.lengthTextCtrl.SetValue(str(w))
  4076. h = self.unitConv.convert(value = self.scalebarDict['height'], fromUnit = 'inch',
  4077. toUnit = self.scalebarDict['unitsHeight'])
  4078. self.heightTextCtrl.SetValue(str(h))
  4079. gridBagSizer.Add(lengthText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4080. gridBagSizer.Add(self.lengthTextCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4081. gridBagSizer.Add(self.unitsLength, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4082. gridBagSizer.Add(heightText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4083. gridBagSizer.Add(self.heightTextCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4084. gridBagSizer.Add(self.unitsHeight, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4085. sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4086. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4087. #
  4088. #style
  4089. #
  4090. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Style"))
  4091. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4092. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4093. sbTypeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Type:"))
  4094. self.sbCombo = wx.combo.BitmapComboBox(panel, style = wx.CB_READONLY)
  4095. # only temporary, images must be moved away
  4096. imagePath = os.path.join(globalvar.ETCIMGDIR, "scalebar-fancy.png"), os.path.join(globalvar.ETCIMGDIR, "scalebar-simple.png")
  4097. for item, path in zip(['fancy', 'simple'], imagePath):
  4098. if not os.path.exists(path):
  4099. bitmap = wx.EmptyBitmap(0,0)
  4100. else:
  4101. bitmap = wx.Bitmap(path)
  4102. self.sbCombo.Append(item = '', bitmap = bitmap, clientData = item[0])
  4103. #self.sbCombo.Append(item = 'simple', bitmap = wx.Bitmap("./images/scalebar-simple.png"), clientData = 's')
  4104. if self.scalebarDict['scalebar'] == 'f':
  4105. self.sbCombo.SetSelection(0)
  4106. elif self.scalebarDict['scalebar'] == 's':
  4107. self.sbCombo.SetSelection(1)
  4108. sbSegmentsText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Number of segments:"))
  4109. self.sbSegmentsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 4)
  4110. self.sbSegmentsCtrl.SetValue(self.scalebarDict['segment'])
  4111. sbLabelsText1 = wx.StaticText(panel, id = wx.ID_ANY, label = _("Label every "))
  4112. sbLabelsText2 = wx.StaticText(panel, id = wx.ID_ANY, label = _("segments"))
  4113. self.sbLabelsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1)
  4114. self.sbLabelsCtrl.SetValue(self.scalebarDict['numbers'])
  4115. #font
  4116. fontsizeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Font size:"))
  4117. self.fontsizeCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 4, max = 30, initial = 10)
  4118. self.fontsizeCtrl.SetValue(self.scalebarDict['fontsize'])
  4119. self.backgroundCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent text background"))
  4120. if self.scalebarDict['background'] == 'y':
  4121. self.backgroundCheck.SetValue(False)
  4122. else:
  4123. self.backgroundCheck.SetValue(True)
  4124. gridBagSizer.Add(sbTypeText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4125. gridBagSizer.Add(self.sbCombo, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0)
  4126. gridBagSizer.Add(sbSegmentsText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4127. gridBagSizer.Add(self.sbSegmentsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4128. gridBagSizer.Add(sbLabelsText1, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4129. gridBagSizer.Add(self.sbLabelsCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4130. gridBagSizer.Add(sbLabelsText2, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4131. gridBagSizer.Add(fontsizeText, pos = (3,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4132. gridBagSizer.Add(self.fontsizeCtrl, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4133. gridBagSizer.Add(self.backgroundCheck, pos = (4, 0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4134. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL, border = 5)
  4135. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4136. panel.SetSizer(border)
  4137. return panel
  4138. def update(self):
  4139. """!Save information from dialog"""
  4140. #units
  4141. currUnit = self.panel.units['unitsCtrl'].GetStringSelection()
  4142. self.scalebarDict['unit'] = currUnit
  4143. # position
  4144. if self.panel.position['xCtrl'].GetValue():
  4145. x = self.panel.position['xCtrl'].GetValue()
  4146. else:
  4147. x = self.scalebarDict['where'][0]
  4148. if self.panel.position['yCtrl'].GetValue():
  4149. y = self.panel.position['yCtrl'].GetValue()
  4150. else:
  4151. y = self.scalebarDict['where'][1]
  4152. x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4153. y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
  4154. #style
  4155. self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(self.sbCombo.GetSelection())
  4156. self.scalebarDict['segment'] = self.sbSegmentsCtrl.GetValue()
  4157. self.scalebarDict['numbers'] = self.sbLabelsCtrl.GetValue()
  4158. self.scalebarDict['fontsize'] = self.fontsizeCtrl.GetValue()
  4159. if self.backgroundCheck.GetValue():
  4160. self.scalebarDict['background'] = 'n'
  4161. else:
  4162. self.scalebarDict['background'] = 'y'
  4163. # size
  4164. # height
  4165. self.scalebarDict['unitsHeight'] = self.unitsHeight.GetStringSelection()
  4166. try:
  4167. height = float(self.heightTextCtrl.GetValue())
  4168. height = self.unitConv.convert(value = height, fromUnit = self.scalebarDict['unitsHeight'], toUnit = 'inch')
  4169. except (ValueError, SyntaxError):
  4170. height = 0.1 #default in inch
  4171. self.scalebarDict['height'] = height
  4172. #length
  4173. selected = self.unitsLength.GetStringSelection()
  4174. if selected == 'default':
  4175. selected = 'auto'
  4176. elif selected == 'nautical miles':
  4177. selected = 'nautmiles'
  4178. self.scalebarDict['unitsLength'] = selected
  4179. try:
  4180. length = float(self.lengthTextCtrl.GetValue())
  4181. except (ValueError, SyntaxError):
  4182. wx.MessageBox(message = _("Length of scale bar is not defined"),
  4183. caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR)
  4184. return False
  4185. self.scalebarDict['length'] = length
  4186. # estimation of size
  4187. map = self.instruction.FindInstructionByType('map')
  4188. if not map:
  4189. map = self.instruction.FindInstructionByType('initMap')
  4190. mapId = map.id
  4191. rectSize = self.scalebar.EstimateSize(scalebarDict = self.scalebarDict,
  4192. scale = self.instruction[mapId]['scale'])
  4193. self.scalebarDict['rect'] = wx.Rect2D(x = x, y = y, w = rectSize[0], h = rectSize[1])
  4194. self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre()
  4195. if self.id not in self.instruction:
  4196. scalebar = Scalebar(self.id)
  4197. self.instruction.AddInstruction(scalebar)
  4198. self.instruction[self.id].SetInstruction(self.scalebarDict)
  4199. if self.id not in self.parent.objectId:
  4200. self.parent.objectId.append(self.id)
  4201. return True
  4202. def updateDialog(self):
  4203. """!Update scalebar coordinates, after moving"""
  4204. x, y = self.scalebarDict['rect'][:2]
  4205. currUnit = self.panel.units['unitsCtrl'].GetStringSelection()
  4206. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4207. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4208. self.panel.position['xCtrl'].SetValue("%5.3f" % x)
  4209. self.panel.position['yCtrl'].SetValue("%5.3f" % y)
  4210. class TextDialog(PsmapDialog):
  4211. def __init__(self, parent, id, settings):
  4212. PsmapDialog.__init__(self, parent = parent, id = id, title = "Text settings", settings = settings)
  4213. self.objectType = ('text',)
  4214. if self.id is not None:
  4215. self.textDict = self.instruction[id].GetInstruction()
  4216. else:
  4217. self.id = wx.NewId()
  4218. text = Text(self.id)
  4219. self.textDict = text.GetInstruction()
  4220. page = self.instruction.FindInstructionByType('page').GetInstruction()
  4221. self.textDict['where'] = page['Left'], page['Top']
  4222. map = self.instruction.FindInstructionByType('map')
  4223. if not map:
  4224. map = self.instruction.FindInstructionByType('initMap')
  4225. self.mapId = map.id
  4226. self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(map = map, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
  4227. notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  4228. self.textPanel = self._textPanel(notebook)
  4229. self.positionPanel = self._positionPanel(notebook)
  4230. self.OnBackground(None)
  4231. self.OnHighlight(None)
  4232. self.OnBorder(None)
  4233. self.OnPositionType(None)
  4234. self.OnRotation(None)
  4235. self._layout(notebook)
  4236. def _textPanel(self, notebook):
  4237. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4238. notebook.AddPage(page = panel, text = _("Text"))
  4239. border = wx.BoxSizer(wx.VERTICAL)
  4240. # text entry
  4241. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text"))
  4242. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4243. textLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Enter text:"))
  4244. self.textCtrl = ExpandoTextCtrl(panel, id = wx.ID_ANY, value = self.textDict['text'])
  4245. sizer.Add(textLabel, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4246. sizer.Add(self.textCtrl, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4247. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4248. #font
  4249. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings"))
  4250. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4251. flexGridSizer = wx.FlexGridSizer (rows = 3, cols = 2, hgap = 5, vgap = 5)
  4252. flexGridSizer.AddGrowableCol(1)
  4253. self.AddFont(parent = panel, dialogDict = self.textDict)
  4254. flexGridSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4255. flexGridSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4256. flexGridSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4257. flexGridSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4258. flexGridSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4259. flexGridSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4260. sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4261. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4262. #text effects
  4263. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text effects"))
  4264. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  4265. gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
  4266. self.effect = {}
  4267. self.effect['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text background"))
  4268. self.effect['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4269. self.effect['highlightCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("highlight"))
  4270. self.effect['highlightColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4271. self.effect['highlightWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 0, max = 5, initial = 1)
  4272. self.effect['highlightWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  4273. self.effect['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text border"))
  4274. self.effect['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
  4275. self.effect['borderWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 1, max = 25, initial = 1)
  4276. self.effect['borderWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
  4277. #set values
  4278. if self.textDict['background'] != 'none':
  4279. self.effect['backgroundCtrl'].SetValue(True)
  4280. else:
  4281. self.effect['backgroundCtrl'].SetValue(False)
  4282. if self.textDict['background'] != 'none':
  4283. self.effect['backgroundColor'].SetColour(convertRGB(self.textDict['background']))
  4284. else:
  4285. self.effect['backgroundColor'].SetColour('white')
  4286. if self.textDict['hcolor'] != 'none':
  4287. self.effect['highlightCtrl'].SetValue(True)
  4288. else:
  4289. self.effect['highlightCtrl'].SetValue(False)
  4290. if self.textDict['hcolor'] != 'none':
  4291. self.effect['highlightColor'].SetColour(convertRGB(self.textDict['hcolor']))
  4292. else:
  4293. self.effect['highlightColor'].SetColour(convertRGB('grey'))
  4294. self.effect['highlightWidth'].SetValue(float(self.textDict['hwidth']))
  4295. if self.textDict['border'] != 'none':
  4296. self.effect['borderCtrl'].SetValue(True)
  4297. else:
  4298. self.effect['borderCtrl'].SetValue(False)
  4299. if self.textDict['border'] != 'none':
  4300. self.effect['borderColor'].SetColour(convertRGB(self.textDict['border']))
  4301. else:
  4302. self.effect['borderColor'].SetColour('black')
  4303. self.effect['borderWidth'].SetValue(float(self.textDict['width']))
  4304. gridBagSizer.Add(self.effect['backgroundCtrl'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4305. gridBagSizer.Add(self.effect['backgroundColor'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4306. gridBagSizer.Add(self.effect['highlightCtrl'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4307. gridBagSizer.Add(self.effect['highlightColor'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4308. gridBagSizer.Add(self.effect['highlightWidthLabel'], pos = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4309. gridBagSizer.Add(self.effect['highlightWidth'], pos = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4310. gridBagSizer.Add(self.effect['borderCtrl'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4311. gridBagSizer.Add(self.effect['borderColor'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4312. gridBagSizer.Add(self.effect['borderWidthLabel'], pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4313. gridBagSizer.Add(self.effect['borderWidth'], pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4314. sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  4315. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4316. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textCtrl)
  4317. self.Bind(wx.EVT_CHECKBOX, self.OnBackground, self.effect['backgroundCtrl'])
  4318. self.Bind(wx.EVT_CHECKBOX, self.OnHighlight, self.effect['highlightCtrl'])
  4319. self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.effect['borderCtrl'])
  4320. panel.SetSizer(border)
  4321. panel.Fit()
  4322. return panel
  4323. def _positionPanel(self, notebook):
  4324. panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL)
  4325. notebook.AddPage(page = panel, text = _("Position"))
  4326. border = wx.BoxSizer(wx.VERTICAL)
  4327. #Position
  4328. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position"))
  4329. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4330. gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  4331. gridBagSizer.AddGrowableCol(0)
  4332. gridBagSizer.AddGrowableCol(1)
  4333. self.positionLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Position is given:"))
  4334. self.paperPositionCtrl = wx.RadioButton(panel, id = wx.ID_ANY, label = _("relatively to paper"), style = wx.RB_GROUP)
  4335. self.mapPositionCtrl = wx.RadioButton(panel, id = wx.ID_ANY, label = _("by map coordinates"))
  4336. self.paperPositionCtrl.SetValue(self.textDict['XY'])
  4337. self.mapPositionCtrl.SetValue(not self.textDict['XY'])
  4338. gridBagSizer.Add(self.positionLabel, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  4339. gridBagSizer.Add(self.paperPositionCtrl, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  4340. gridBagSizer.Add(self.mapPositionCtrl, pos = (1,1),flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0)
  4341. # first box - paper coordinates
  4342. box1 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
  4343. sizerP = wx.StaticBoxSizer(box1, wx.VERTICAL)
  4344. self.gridBagSizerP = wx.GridBagSizer (hgap = 5, vgap = 5)
  4345. self.gridBagSizerP.AddGrowableCol(1)
  4346. self.gridBagSizerP.AddGrowableRow(3)
  4347. self.AddPosition(parent = panel, dialogDict = self.textDict)
  4348. panel.position['comment'].SetLabel(_("Position from the top left\nedge of the paper"))
  4349. self.AddUnits(parent = panel, dialogDict = self.textDict)
  4350. self.gridBagSizerP.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4351. self.gridBagSizerP.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4352. self.gridBagSizerP.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4353. self.gridBagSizerP.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4354. self.gridBagSizerP.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4355. self.gridBagSizerP.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4356. self.gridBagSizerP.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag = wx.ALIGN_BOTTOM, border = 0)
  4357. sizerP.Add(self.gridBagSizerP, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4358. gridBagSizer.Add(sizerP, pos = (2,0),span = (1,1), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
  4359. # second box - map coordinates
  4360. box2 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "")
  4361. sizerM = wx.StaticBoxSizer(box2, wx.VERTICAL)
  4362. self.gridBagSizerM = wx.GridBagSizer (hgap = 5, vgap = 5)
  4363. self.gridBagSizerM.AddGrowableCol(0)
  4364. self.gridBagSizerM.AddGrowableCol(1)
  4365. self.eastingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "E:")
  4366. self.northingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "N:")
  4367. self.eastingCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  4368. self.northingCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
  4369. east, north = PaperMapCoordinates(map = self.instruction[self.mapId], x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
  4370. self.eastingCtrl.SetValue(str(east))
  4371. self.northingCtrl.SetValue(str(north))
  4372. self.gridBagSizerM.Add(self.eastingLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4373. self.gridBagSizerM.Add(self.northingLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4374. self.gridBagSizerM.Add(self.eastingCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4375. self.gridBagSizerM.Add(self.northingCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4376. sizerM.Add(self.gridBagSizerM, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4377. gridBagSizer.Add(sizerM, pos = (2,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
  4378. #offset
  4379. box3 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Offset"))
  4380. sizerO = wx.StaticBoxSizer(box3, wx.VERTICAL)
  4381. gridBagSizerO = wx.GridBagSizer (hgap = 5, vgap = 5)
  4382. self.xoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("horizontal (pts):"))
  4383. self.yoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("vertical (pts):"))
  4384. self.xoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0)
  4385. self.yoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0)
  4386. self.xoffCtrl.SetValue(self.textDict['xoffset'])
  4387. self.yoffCtrl.SetValue(self.textDict['yoffset'])
  4388. gridBagSizerO.Add(self.xoffLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4389. gridBagSizerO.Add(self.yoffLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4390. gridBagSizerO.Add(self.xoffCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4391. gridBagSizerO.Add(self.yoffCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
  4392. sizerO.Add(gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
  4393. gridBagSizer.Add(sizerO, pos = (3,0), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0)
  4394. # reference point
  4395. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_(" Reference point"))
  4396. sizerR = wx.StaticBoxSizer(box, wx.VERTICAL)
  4397. flexSizer = wx.FlexGridSizer(rows = 3, cols = 3, hgap = 5, vgap = 5)
  4398. flexSizer.AddGrowableCol(0)
  4399. flexSizer.AddGrowableCol(1)
  4400. flexSizer.AddGrowableCol(2)
  4401. ref = []
  4402. for row in ["upper", "center", "lower"]:
  4403. for col in ["left", "center", "right"]:
  4404. ref.append(row + " " + col)
  4405. self.radio = [wx.RadioButton(panel, id = wx.ID_ANY, label = '', style = wx.RB_GROUP, name = ref[0])]
  4406. self.radio[0].SetValue(False)
  4407. flexSizer.Add(self.radio[0], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4408. for i in range(1,9):
  4409. self.radio.append(wx.RadioButton(panel, id = wx.ID_ANY, label = '', name = ref[i]))
  4410. self.radio[-1].SetValue(False)
  4411. flexSizer.Add(self.radio[-1], proportion = 0, flag = wx.ALIGN_CENTER, border = 0)
  4412. self.FindWindowByName(self.textDict['ref']).SetValue(True)
  4413. sizerR.Add(flexSizer, proportion = 1, flag = wx.EXPAND, border = 0)
  4414. gridBagSizer.Add(sizerR, pos = (3,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0)
  4415. sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  4416. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4417. #rotation
  4418. box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text rotation"))
  4419. sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
  4420. self.rotCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate text (counterclockwise)"))
  4421. self.rotValue = wx.SpinCtrl(panel, wx.ID_ANY, size = (50, -1), min = 0, max = 360, initial = 0)
  4422. if self.textDict['rotate']:
  4423. self.rotValue.SetValue(int(self.textDict['rotate']))
  4424. self.rotCtrl.SetValue(True)
  4425. else:
  4426. self.rotValue.SetValue(0)
  4427. self.rotCtrl.SetValue(False)
  4428. sizer.Add(self.rotCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
  4429. sizer.Add(self.rotValue, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5)
  4430. border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  4431. panel.SetSizer(border)
  4432. panel.Fit()
  4433. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, self.paperPositionCtrl)
  4434. self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, self.mapPositionCtrl)
  4435. self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotCtrl)
  4436. return panel
  4437. def OnRefit(self, event):
  4438. self.Fit()
  4439. def OnRotation(self, event):
  4440. if self.rotCtrl.GetValue():
  4441. self.rotValue.Enable()
  4442. else:
  4443. self.rotValue.Disable()
  4444. def OnPositionType(self, event):
  4445. if self.paperPositionCtrl.GetValue():
  4446. for widget in self.gridBagSizerP.GetChildren():
  4447. widget.GetWindow().Enable()
  4448. for widget in self.gridBagSizerM.GetChildren():
  4449. widget.GetWindow().Disable()
  4450. else:
  4451. for widget in self.gridBagSizerM.GetChildren():
  4452. widget.GetWindow().Enable()
  4453. for widget in self.gridBagSizerP.GetChildren():
  4454. widget.GetWindow().Disable()
  4455. def OnBackground(self, event):
  4456. if self.effect['backgroundCtrl'].GetValue():
  4457. self.effect['backgroundColor'].Enable()
  4458. else:
  4459. self.effect['backgroundColor'].Disable()
  4460. def OnHighlight(self, event):
  4461. if self.effect['highlightCtrl'].GetValue():
  4462. self.effect['highlightColor'].Enable()
  4463. self.effect['highlightWidth'].Enable()
  4464. self.effect['highlightWidthLabel'].Enable()
  4465. else:
  4466. self.effect['highlightColor'].Disable()
  4467. self.effect['highlightWidth'].Disable()
  4468. self.effect['highlightWidthLabel'].Disable()
  4469. def OnBorder(self, event):
  4470. if self.effect['borderCtrl'].GetValue():
  4471. self.effect['borderColor'].Enable()
  4472. self.effect['borderWidth'].Enable()
  4473. self.effect['borderWidthLabel'].Enable()
  4474. else:
  4475. self.effect['borderColor'].Disable()
  4476. self.effect['borderWidth'].Disable()
  4477. self.effect['borderWidthLabel'].Disable()
  4478. def update(self):
  4479. #text
  4480. self.textDict['text'] = self.textCtrl.GetValue()
  4481. if not self.textDict['text']:
  4482. wx.MessageBox(_("No text entered!"), _("Error"))
  4483. return False
  4484. #font
  4485. self.textDict['font'] = self.textPanel.font['fontCtrl'].GetStringSelection()
  4486. self.textDict['fontsize'] = self.textPanel.font['fontSizeCtrl'].GetValue()
  4487. ## font = self.textPanel.font['fontCtrl'].GetSelectedFont()
  4488. ## self.textDict['font'] = font.GetFaceName()
  4489. ## self.textDict['fontsize'] = font.GetPointSize()
  4490. color = self.textPanel.font['colorCtrl'].GetColour()
  4491. ## if color.GetAsString(wx.C2S_NAME) in PSMAP_COLORS:
  4492. ## self.textDict['color'] = color.GetAsString(wx.C2S_NAME)
  4493. ## else:
  4494. self.textDict['color'] = convertRGB(color)
  4495. #effects
  4496. if self.effect['backgroundCtrl'].GetValue():
  4497. background = self.effect['backgroundColor'].GetColour()
  4498. self.textDict['background'] = convertRGB(background)
  4499. else:
  4500. self.textDict['background'] = 'none'
  4501. if self.effect['borderCtrl'].GetValue():
  4502. border = self.effect['borderColor'].GetColour()
  4503. self.textDict['border'] = convertRGB(border)
  4504. else:
  4505. self.textDict['border'] = 'none'
  4506. self.textDict['width'] = self.effect['borderWidth'].GetValue()
  4507. if self.effect['highlightCtrl'].GetValue():
  4508. highlight = self.effect['highlightColor'].GetColour()
  4509. self.textDict['hcolor'] = convertRGB(highlight)
  4510. else:
  4511. self.textDict['hcolor'] = 'none'
  4512. self.textDict['hwidth'] = self.effect['highlightWidth'].GetValue()
  4513. #offset
  4514. self.textDict['xoffset'] = self.xoffCtrl.GetValue()
  4515. self.textDict['yoffset'] = self.yoffCtrl.GetValue()
  4516. #position
  4517. if self.paperPositionCtrl.GetValue():
  4518. self.textDict['XY'] = True
  4519. currUnit = self.positionPanel.units['unitsCtrl'].GetStringSelection()
  4520. self.textDict['unit'] = currUnit
  4521. if self.positionPanel.position['xCtrl'].GetValue():
  4522. x = self.positionPanel.position['xCtrl'].GetValue()
  4523. else:
  4524. x = self.textDict['where'][0]
  4525. if self.positionPanel.position['yCtrl'].GetValue():
  4526. y = self.positionPanel.position['yCtrl'].GetValue()
  4527. else:
  4528. y = self.textDict['where'][1]
  4529. x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
  4530. y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
  4531. self.textDict['where'] = x, y
  4532. self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(self.instruction[self.mapId], x, y, paperToMap = True)
  4533. else:
  4534. self.textDict['XY'] = False
  4535. if self.eastingCtrl.GetValue():
  4536. self.textDict['east'] = self.eastingCtrl.GetValue()
  4537. else:
  4538. self.textDict['east'] = self.textDict['east']
  4539. if self.northingCtrl.GetValue():
  4540. self.textDict['north'] = self.northingCtrl.GetValue()
  4541. else:
  4542. self.textDict['north'] = self.textDict['north']
  4543. self.textDict['where'] = PaperMapCoordinates(map = self.instruction[self.mapId], x = float(self.textDict['east']),
  4544. y = float(self.textDict['north']), paperToMap = False)
  4545. #rotation
  4546. if self.rotCtrl.GetValue():
  4547. self.textDict['rotate'] = self.rotValue.GetValue()
  4548. else:
  4549. self.textDict['rotate'] = None
  4550. #reference point
  4551. for radio in self.radio:
  4552. if radio.GetValue() == True:
  4553. self.textDict['ref'] = radio.GetName()
  4554. if self.id not in self.instruction:
  4555. text = Text(self.id)
  4556. self.instruction.AddInstruction(text)
  4557. self.instruction[self.id].SetInstruction(self.textDict)
  4558. if self.id not in self.parent.objectId:
  4559. self.parent.objectId.append(self.id)
  4560. return True
  4561. def updateDialog(self):
  4562. """!Update text coordinates, after moving"""
  4563. # XY coordinates
  4564. x, y = self.textDict['where'][:2]
  4565. currUnit = self.positionPanel.units['unitsCtrl'].GetStringSelection()
  4566. x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit)
  4567. y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit)
  4568. self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x)
  4569. self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y)
  4570. # EN coordinates
  4571. e, n = self.textDict['east'], self.textDict['north']
  4572. self.eastingCtrl.SetValue(str(self.textDict['east']))
  4573. self.northingCtrl.SetValue(str(self.textDict['north']))
  4574. def convertRGB(rgb):
  4575. """!Converts wx.Colour(255,255,255,255) and string '255:255:255',
  4576. depends on input"""
  4577. psmapColors = { "white" : (1.00, 1.00, 1.00),
  4578. "black" : (0.00, 0.00, 0.00),
  4579. "red" : (1.00, 0.00, 0.00),
  4580. "green" : (0.00, 1.00, 0.00),
  4581. "blue" : (0.00, 0.00, 1.00),
  4582. "yellow" : (1.00, 1.00, 0.00),
  4583. "magenta" : (1.00, 0.00, 1.00),
  4584. "cyan" : (0.00, 1.00, 1.00),
  4585. "aqua" : (0.00, 0.75, 0.75),
  4586. "grey" : (0.75, 0.75, 0.75),
  4587. "gray" : (0.75, 0.75, 0.75),
  4588. "orange" : (1.00, 0.50, 0.00),
  4589. "brown" : (0.75, 0.50, 0.25),
  4590. "purple" : (0.50, 0.00, 1.00),
  4591. "violet" : (0.50, 0.00, 1.00),
  4592. "indigo" : (0.00, 0.50, 1.00)}
  4593. if type(rgb) == wx.Colour:
  4594. for name, color in psmapColors.items():
  4595. if rgb.Red() == int(color[0] * 255) and\
  4596. rgb.Green() == int(color[1] * 255) and\
  4597. rgb.Blue() == int(color[2] * 255):
  4598. return name
  4599. return str(rgb.Red()) + ':' + str(rgb.Green()) + ':' + str(rgb.Blue())
  4600. elif type(rgb) == str or type(rgb) == unicode:
  4601. if ':' in rgb:
  4602. return wx.Colour(*map(int, rgb.split(':')))
  4603. else:
  4604. color = map(lambda x: int(x * 255), psmapColors[rgb])
  4605. color = wx.Color(*color)
  4606. if color.IsOk():
  4607. return color
  4608. return None
  4609. def PaperMapCoordinates(map, x, y, paperToMap = True):
  4610. """!Converts paper (inch) coordinates -> map coordinates"""
  4611. unitConv = UnitConversion()
  4612. currRegionDict = grass.region()
  4613. cornerEasting, cornerNorthing = currRegionDict['w'], currRegionDict['n']
  4614. xMap = map['rect'][0]
  4615. yMap = map['rect'][1]
  4616. widthMap = map['rect'][2] * 0.0254 # to meter
  4617. heightMap = map['rect'][3] * 0.0254
  4618. xScale = widthMap / abs(currRegionDict['w'] - currRegionDict['e'])
  4619. yScale = heightMap / abs(currRegionDict['n'] - currRegionDict['s'])
  4620. currScale = (xScale + yScale) / 2
  4621. if not paperToMap:
  4622. textEasting, textNorthing = x, y
  4623. eastingDiff = textEasting - cornerEasting
  4624. if currRegionDict['w'] > currRegionDict['e']:
  4625. eastingDiff = - eastingDiff
  4626. else:
  4627. eastingDiff = eastingDiff
  4628. northingDiff = textNorthing - cornerNorthing
  4629. if currRegionDict['n'] > currRegionDict['s']:
  4630. northingDiff = - northingDiff
  4631. else:
  4632. northingDiff = northingDiff
  4633. xPaper = xMap + unitConv.convert(value = eastingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale
  4634. yPaper = yMap + unitConv.convert(value = northingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale
  4635. return xPaper, yPaper
  4636. else:
  4637. if currRegionDict['w'] < currRegionDict['e']:
  4638. eastingDiff = (x - xMap)
  4639. else:
  4640. eastingDiff = (xMap - x)
  4641. if currRegionDict['n'] < currRegionDict['s']:
  4642. northingDiff = (y - yMap)
  4643. else:
  4644. northingDiff = (yMap - y)
  4645. textEasting = cornerEasting + unitConv.convert(value = eastingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale
  4646. textNorthing = cornerNorthing + unitConv.convert(value = northingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale
  4647. return int(textEasting), int(textNorthing)
  4648. def AutoAdjust(self, scaleType, rect, map = None, mapType = None, region = None):
  4649. """!Computes map scale, center and map frame rectangle to fit region (scale is not fixed)"""
  4650. currRegionDict = {}
  4651. if scaleType == 0 and map:# automatic, region from raster or vector
  4652. res = ''
  4653. if mapType == 'raster':
  4654. try:
  4655. res = grass.read_command("g.region", flags = 'gu', rast = map)
  4656. except grass.ScriptError:
  4657. pass
  4658. elif mapType == 'vector':
  4659. res = grass.read_command("g.region", flags = 'gu', vect = map)
  4660. currRegionDict = grass.parse_key_val(res, val_type = float)
  4661. elif scaleType == 1 and region: # saved region
  4662. res = grass.read_command("g.region", flags = 'gu', region = region)
  4663. currRegionDict = grass.parse_key_val(res, val_type = float)
  4664. elif scaleType == 2: # current region
  4665. env = grass.gisenv()
  4666. windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND')
  4667. try:
  4668. windFile = open(windFilePath, 'r').read()
  4669. except IOError:
  4670. currRegionDict = grass.region()
  4671. regionDict = grass.parse_key_val(windFile, sep = ':', val_type = float)
  4672. region = grass.read_command("g.region", flags = 'gu', n = regionDict['north'], s = regionDict['south'],
  4673. e = regionDict['east'], w = regionDict['west'])
  4674. currRegionDict = grass.parse_key_val(region, val_type = float)
  4675. else:
  4676. return None, None, None
  4677. if not currRegionDict:
  4678. return None, None, None
  4679. rX = rect.x
  4680. rY = rect.y
  4681. rW = rect.width
  4682. rH = rect.height
  4683. if not hasattr(self, 'unitConv'):
  4684. self.unitConv = UnitConversion(self)
  4685. toM = 1
  4686. if projInfo()['proj'] != 'xy':
  4687. toM = float(projInfo()['meters'])
  4688. mW = self.unitConv.convert(value = (currRegionDict['e'] - currRegionDict['w']) * toM, fromUnit = 'meter', toUnit = 'inch')
  4689. mH = self.unitConv.convert(value = (currRegionDict['n'] - currRegionDict['s']) * toM, fromUnit = 'meter', toUnit = 'inch')
  4690. scale = min(rW/mW, rH/mH)
  4691. if rW/rH > mW/mH:
  4692. x = rX - (rH*(mW/mH) - rW)/2
  4693. y = rY
  4694. rWNew = rH*(mW/mH)
  4695. rHNew = rH
  4696. else:
  4697. x = rX
  4698. y = rY - (rW*(mH/mW) - rH)/2
  4699. rHNew = rW*(mH/mW)
  4700. rWNew = rW
  4701. # center
  4702. cE = (currRegionDict['w'] + currRegionDict['e'])/2
  4703. cN = (currRegionDict['n'] + currRegionDict['s'])/2
  4704. return scale, (cE, cN), wx.Rect2D(x, y, rWNew, rHNew) #inch
  4705. def SetResolution(dpi, width, height):
  4706. """!If resolution is too high, lower it
  4707. @param dpi max DPI
  4708. @param width map frame width
  4709. @param height map frame height
  4710. """
  4711. region = grass.region()
  4712. if region['cols'] > width * dpi or region['rows'] > height * dpi:
  4713. rows = height * dpi
  4714. cols = width * dpi
  4715. RunCommand('g.region', rows = rows, cols = cols)
  4716. def ComputeSetRegion(self, mapDict):
  4717. """!Computes and sets region from current scale, map center coordinates and map rectangle"""
  4718. if mapDict['scaleType'] == 3: # fixed scale
  4719. scale = mapDict['scale']
  4720. if not hasattr(self, 'unitConv'):
  4721. self.unitConv = UnitConversion(self)
  4722. fromM = 1
  4723. if projInfo()['proj'] != 'xy':
  4724. fromM = float(projInfo()['meters'])
  4725. rectHalfInch = (mapDict['rect'].width/2, mapDict['rect'].height/2)
  4726. rectHalfMeter = (self.unitConv.convert(value = rectHalfInch[0], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale,
  4727. self.unitConv.convert(value = rectHalfInch[1], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale)
  4728. centerE = mapDict['center'][0]
  4729. centerN = mapDict['center'][1]
  4730. raster = self.instruction.FindInstructionByType('raster')
  4731. if raster:
  4732. rasterId = raster.id
  4733. else:
  4734. rasterId = None
  4735. if rasterId:
  4736. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  4737. s = floor(centerN - rectHalfMeter[1]),
  4738. e = ceil(centerE + rectHalfMeter[0]),
  4739. w = floor(centerE - rectHalfMeter[0]),
  4740. rast = self.instruction[rasterId]['raster'])
  4741. else:
  4742. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  4743. s = floor(centerN - rectHalfMeter[1]),
  4744. e = ceil(centerE + rectHalfMeter[0]),
  4745. w = floor(centerE - rectHalfMeter[0]))
  4746. def projInfo():
  4747. """!Return region projection and map units information,
  4748. taken from render.py"""
  4749. projinfo = dict()
  4750. ret = RunCommand('g.proj', read = True, flags = 'p')
  4751. if not ret:
  4752. return projinfo
  4753. for line in ret.splitlines():
  4754. if ':' in line:
  4755. key, val = line.split(':')
  4756. projinfo[key.strip()] = val.strip()
  4757. elif "XY location (unprojected)" in line:
  4758. projinfo['proj'] = 'xy'
  4759. projinfo['units'] = ''
  4760. break
  4761. return projinfo
  4762. def GetMapBounds(filename):
  4763. """!Run ps.map -b to get information about map bounding box"""
  4764. try:
  4765. bb = map(float, grass.read_command('ps.map',
  4766. flags = 'b',
  4767. quiet = True,
  4768. input = filename).strip().split('=')[1].split(','))
  4769. except (grass.ScriptError, IndexError):
  4770. GError(message = _("Unable to run `ps.map -b`"))
  4771. return None
  4772. return wx.Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3])
  4773. def getRasterType(map):
  4774. """!Returns type of raster map (CELL, FCELL, DCELL)"""
  4775. if map is None:
  4776. map = ''
  4777. file = grass.find_file(name = map, element = 'cell')
  4778. if file['file']:
  4779. rasterType = grass.raster_info(map)['datatype']
  4780. return rasterType
  4781. else:
  4782. return None