psmap_dialogs.py 269 KB

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