mapdisp.py 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098
  1. """
  2. @package mapdisp.py
  3. @brief GIS map display canvas, with toolbar for various display
  4. management functions, and second toolbar for vector
  5. digitizing.
  6. Can be used either from GIS Manager or as p.mon backend.
  7. Classes:
  8. - Command
  9. - MapWindow
  10. - BufferedWindow
  11. - MapFrame
  12. - MapApp
  13. Usage:
  14. python mapdisp.py monitor-identifier /path/to/command/file
  15. (C) 2006-2008 by the GRASS Development Team
  16. This program is free software under the GNU General Public
  17. License (>=v2). Read the file COPYING that comes with GRASS
  18. for details.
  19. @author Michael Barton
  20. @author Jachym Cepicky
  21. @author Martin Landa <landa.martin gmail.com>
  22. """
  23. import os
  24. import sys
  25. import time
  26. import glob
  27. import math
  28. import tempfile
  29. import copy
  30. import wx
  31. import wx.aui
  32. from threading import Thread
  33. import globalvar
  34. try:
  35. import subprocess
  36. except:
  37. CompatPath = os.path.join(globalvar.ETCWXDIR)
  38. sys.path.append(CompatPath)
  39. from compat import subprocess
  40. import grass
  41. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  42. sys.path.append(gmpath)
  43. import render
  44. import toolbars
  45. import track
  46. import menuform
  47. import gselect
  48. import disp_print
  49. import gcmd
  50. import dbm
  51. import histogram
  52. import profile
  53. import globalvar
  54. import utils
  55. import gdialogs
  56. from vdigit import VDigitCategoryDialog as VDigitCategoryDialog
  57. from vdigit import VDigitZBulkDialog as VDigitZBulkDialog
  58. from vdigit import VDigitDuplicatesDialog as VDigitDuplicatesDialog
  59. from vdigit import GV_LINES as VDigit_Lines_Type
  60. from debug import Debug as Debug
  61. from icon import Icons as Icons
  62. from preferences import globalSettings as UserSettings
  63. import images
  64. imagepath = images.__path__[0]
  65. sys.path.append(imagepath)
  66. ###
  67. ### global variables
  68. ###
  69. # for standalone app
  70. cmdfilename = None
  71. class Command(Thread):
  72. """
  73. Creates thread which will observe the command file and see, if
  74. there is new command to be executed
  75. """
  76. def __init__ (self, parent, Map):
  77. Thread.__init__(self)
  78. global cmdfilename
  79. self.parent = parent
  80. self.map = Map
  81. self.cmdfile = open(cmdfilename, "r")
  82. def run(self):
  83. """
  84. Run this in thread
  85. """
  86. dispcmd = []
  87. while 1:
  88. self.parent.redraw = False
  89. line = self.cmdfile.readline().strip()
  90. if line == "quit":
  91. break
  92. if line:
  93. try:
  94. Debug.msg (3, "Command.run(): cmd=%s" % (line))
  95. self.map.AddLayer(item=None, type="raster",
  96. name='',
  97. command=line,
  98. l_opacity=1)
  99. self.parent.redraw =True
  100. except Exception, e:
  101. print "Command Thread: ",e
  102. time.sleep(0.1)
  103. sys.exit()
  104. class MapWindow(object):
  105. """
  106. Abstract map window class
  107. Parent for BufferedWindow class (2D display mode) and
  108. GLWindow (3D display mode)
  109. """
  110. def __init__(self, parent, id=wx.ID_ANY,
  111. pos=wx.DefaultPosition,
  112. size=wx.DefaultSize,
  113. style=wx.NO_FULL_REPAINT_ON_RESIZE,
  114. Map=None, tree=None, gismgr=None):
  115. self.parent = parent # MapFrame
  116. def EraseMap(self):
  117. """
  118. Erase the canvas (virtual method)
  119. """
  120. pass
  121. def UpdateMap(self):
  122. """
  123. Updates the canvas anytime there is a change to the
  124. underlaying images or to the geometry of the canvas.
  125. """
  126. pass
  127. def OnLeftDown(self, event):
  128. pass
  129. def OnLeftUp(self, event):
  130. pass
  131. def OnMouseMotion(self, event):
  132. pass
  133. def OnZoomToMap(self, event):
  134. pass
  135. def OnZoomToRaster(self, event):
  136. pass
  137. def GetSelectedLayer(self, type='layer'):
  138. """
  139. Get selected layer from layer tree
  140. @param type 'item' / 'layer' / 'nviz'
  141. @return layer / map layer properties / nviz properties
  142. @return None on failure
  143. """
  144. # get currently selected map layer
  145. if not self.tree or not self.tree.GetSelection():
  146. return None
  147. item = self.tree.GetSelection()
  148. if not item.IsChecked():
  149. return None
  150. if type == 'item':
  151. return item
  152. try:
  153. if type == 'nviz':
  154. layer = self.tree.GetPyData(item)[0]['nviz']
  155. else:
  156. layer = self.tree.GetPyData(item)[0]['maplayer']
  157. except:
  158. layer = None
  159. return layer
  160. class BufferedWindow(MapWindow, wx.Window):
  161. """
  162. A Buffered window class.
  163. When the drawing needs to change, you app needs to call the
  164. UpdateMap() method. Since the drawing is stored in a bitmap, you
  165. can also save the drawing to file by calling the
  166. SaveToFile(self,file_name,file_type) method.
  167. """
  168. def __init__(self, parent, id,
  169. pos = wx.DefaultPosition,
  170. size = wx.DefaultSize,
  171. style=wx.NO_FULL_REPAINT_ON_RESIZE,
  172. Map=None, tree=None, gismgr=None):
  173. MapWindow.__init__(self, parent, id, pos, size, style,
  174. Map, tree, gismgr)
  175. wx.Window.__init__(self, parent, id, pos, size, style)
  176. self.Map = Map
  177. self.tree = tree
  178. self.gismanager = gismgr
  179. #
  180. # Flags
  181. #
  182. self.resize = False # indicates whether or not a resize event has taken place
  183. self.dragimg = None # initialize variable for map panning
  184. #
  185. # Variable for drawing on DC
  186. #
  187. self.pen = None # pen for drawing zoom boxes, etc.
  188. self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
  189. # List of wx.Point tuples defining a polyline (geographical coordinates)
  190. self.polycoords = []
  191. # ID of rubber band line
  192. self.lineid = None
  193. # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
  194. self.plineid = None
  195. #
  196. # Event bindings
  197. #
  198. self.Bind(wx.EVT_PAINT, self.OnPaint)
  199. self.Bind(wx.EVT_SIZE, self.OnSize)
  200. self.Bind(wx.EVT_IDLE, self.OnIdle)
  201. self.Bind(wx.EVT_MOTION, self.MouseActions)
  202. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  203. self.processMouse = True
  204. #
  205. # Render output objects
  206. #
  207. self.mapfile = None # image file to be rendered
  208. self.img = "" # wx.Image object (self.mapfile)
  209. # used in digitization tool (do not redraw vector map)
  210. self.imgVectorMap = None
  211. # decoration overlays
  212. self.overlays = {}
  213. # images and their PseudoDC ID's for painting and dragging
  214. self.imagedict = {}
  215. self.select = {} # selecting/unselecting decorations for dragging
  216. self.textdict = {} # text, font, and color indexed by id
  217. self.currtxtid = None # PseudoDC id for currently selected text
  218. #
  219. # Zoom objects
  220. #
  221. self.zoomhistory = [] # list of past zoom extents
  222. self.currzoom = 0 # current set of extents in zoom history being used
  223. #
  224. # mouse attributes like currently pressed buttons, position on
  225. # the screen, begin and end of dragging, and type of drawing
  226. #
  227. self.mouse = {
  228. 'l' : False,
  229. 'r' : False,
  230. 'm' : False,
  231. 'begin': [0, 0], # screen coordinates
  232. 'end' : [0, 0],
  233. 'use' : "pointer",
  234. 'box' : "point"
  235. }
  236. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  237. self.hitradius = 10 # distance for selecting map decorations
  238. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  239. # OnSize called to make sure the buffer is initialized.
  240. # This might result in OnSize getting called twice on some
  241. # platforms at initialization, but little harm done.
  242. ### self.OnSize(None)
  243. # create PseudoDC used for background map, map decorations like scales and legends
  244. self.pdc = wx.PseudoDC()
  245. # used for digitization tool
  246. self.pdcVector = None
  247. # decorations (region box, etc.)
  248. self.pdcDec = wx.PseudoDC()
  249. # pseudoDC for temporal objects (select box, measurement tool, etc.)
  250. self.pdcTmp = wx.PseudoDC()
  251. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  252. self.redrawAll = True
  253. # will store an off screen empty bitmap for saving to file
  254. self._buffer = ''
  255. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  256. # vars for handling mouse clicks
  257. self.dragid = -1
  258. self.lastpos = (0, 0)
  259. def Draw(self, pdc, img=None, drawid=None, pdctype='image', coords=[0, 0, 0, 0]):
  260. """
  261. Draws map and overlay decorations
  262. """
  263. if drawid == None:
  264. if pdctype == 'image' and img:
  265. drawid = self.imagedict[img]
  266. elif pdctype == 'clear':
  267. drawid == None
  268. else:
  269. drawid = wx.NewId()
  270. if img and pdctype == 'image':
  271. # self.imagedict[img]['coords'] = coords
  272. self.select[self.imagedict[img]['id']] = False # ?
  273. pdc.BeginDrawing()
  274. if drawid != 99:
  275. bg = wx.TRANSPARENT_BRUSH
  276. else:
  277. bg = wx.Brush(self.GetBackgroundColour())
  278. pdc.SetBackground(bg)
  279. ### pdc.Clear()
  280. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % \
  281. (drawid, pdctype, coords))
  282. # set PseudoDC id
  283. if drawid is not None:
  284. pdc.SetId(drawid)
  285. if pdctype == 'clear': # erase the display
  286. bg = wx.WHITE_BRUSH
  287. # bg = wx.Brush(self.GetBackgroundColour())
  288. pdc.SetBackground(bg)
  289. pdc.RemoveAll()
  290. pdc.Clear()
  291. pdc.EndDrawing()
  292. self.Refresh()
  293. return
  294. if pdctype == 'image': # draw selected image
  295. bitmap = wx.BitmapFromImage(img)
  296. w,h = bitmap.GetSize()
  297. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  298. pdc.SetIdBounds(drawid, (coords[0],coords[1], w, h))
  299. elif pdctype == 'box': # draw a box on top of the map
  300. if self.pen:
  301. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  302. pdc.SetPen(self.pen)
  303. x2 = max(coords[0],coords[2])
  304. x1 = min(coords[0],coords[2])
  305. y2 = max(coords[1],coords[3])
  306. y1 = min(coords[1],coords[3])
  307. rwidth = x2-x1
  308. rheight = y2-y1
  309. rect = wx.Rect(x1,y1,rwidth,rheight)
  310. pdc.DrawRectangleRect(rect)
  311. pdc.SetIdBounds(drawid,rect)
  312. # self.ovlcoords[drawid] = coords
  313. elif pdctype == 'line': # draw a line on top of the map
  314. if self.pen:
  315. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  316. pdc.SetPen(self.pen)
  317. pdc.DrawLine(coords[0], coords[1], coords[2], coords[3])
  318. pdc.SetIdBounds(drawid,(coords[0], coords[1], coords[2], coords[3]))
  319. # self.ovlcoords[drawid] = coords
  320. elif pdctype == 'polyline': # draw a polyline on top of the map
  321. if self.polypen:
  322. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  323. pdc.SetPen(self.polypen)
  324. pdc.DrawLines(coords)
  325. # get bounding rectangle for polyline
  326. xlist = []
  327. ylist = []
  328. if len(coords) > 0:
  329. for point in coords:
  330. x,y = point
  331. xlist.append(x)
  332. ylist.append(y)
  333. x1=min(xlist)
  334. x2=max(xlist)
  335. y1=min(ylist)
  336. y2=max(ylist)
  337. pdc.SetIdBounds(drawid,(x1,y1,x2,y2))
  338. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  339. elif pdctype == 'point': # draw point
  340. if self.pen:
  341. pdc.SetPen(self.pen)
  342. pdc.DrawPoint(coords[0], coords[1])
  343. coordsBound = (coords[0] - 5,
  344. coords[1] - 5,
  345. coords[0] + 5,
  346. coords[1] + 5)
  347. pdc.SetIdBounds(drawid, coordsBound)
  348. # self.ovlcoords[drawid] = coords
  349. elif pdctype == 'text': # draw text on top of map
  350. if img.has_key('rotation'):
  351. rotation = float(img['rotation'])
  352. else:
  353. rotation = 0.0
  354. w, h = self.GetFullTextExtent(img['text'])[0:2]
  355. pdc.SetFont(img['font'])
  356. pdc.SetTextForeground(img['color'])
  357. coords, w, h = self.TextBounds(img)
  358. if rotation == 0:
  359. pdc.DrawText(img['text'], coords[0], coords[1])
  360. else:
  361. pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
  362. pdc.SetIdBounds(drawid, (coords[0], coords[1], w, h))
  363. pdc.EndDrawing()
  364. self.Refresh()
  365. return drawid
  366. def TextBounds(self, textinfo):
  367. """
  368. Return text boundary data
  369. @param textinfo text metadata (text, font, color, rotation)
  370. @param coords reference point
  371. """
  372. if textinfo.has_key('rotation'):
  373. rotation = float(textinfo['rotation'])
  374. else:
  375. rotation = 0.0
  376. coords = textinfo['coords']
  377. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  378. (textinfo['text'], rotation))
  379. self.Update()
  380. ### self.Refresh()
  381. self.SetFont(textinfo['font'])
  382. w, h = self.GetTextExtent(textinfo['text'])
  383. if rotation == 0:
  384. coords[2], coords[3] = coords[0] + w, coords[1] + h
  385. return coords, w, h
  386. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  387. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  388. coords[2] = coords[0] + boxw
  389. coords[3] = coords[1] + boxh
  390. return coords, boxw, boxh
  391. def OnPaint(self, event):
  392. """
  393. Draw PseudoDC's to buffered paint DC
  394. self.pdc for background and decorations
  395. self.pdcVector for vector map which is edited
  396. self.pdcTmp for temporaly drawn objects (self.polycoords)
  397. If self.redrawAll is False on self.pdcTmp content is re-drawn
  398. """
  399. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  400. dc = wx.BufferedPaintDC(self, self.buffer)
  401. ### dc.SetBackground(wx.Brush("White"))
  402. dc.Clear()
  403. # use PrepareDC to set position correctly
  404. self.PrepareDC(dc)
  405. # create a clipping rect from our position and size
  406. # and update region
  407. rgn = self.GetUpdateRegion().GetBox()
  408. dc.SetClippingRect(rgn)
  409. switchDraw = False
  410. if self.redrawAll is None:
  411. self.redrawAll = True
  412. switchDraw = True
  413. if self.redrawAll: # redraw pdc and pdcVector
  414. # draw to the dc using the calculated clipping rect
  415. self.pdc.DrawToDCClipped(dc, rgn)
  416. # draw vector map layer
  417. if self.pdcVector:
  418. # decorate with GDDC (transparency)
  419. try:
  420. gcdc = wx.GCDC(dc)
  421. self.pdcVector.DrawToDCClipped(gcdc, rgn)
  422. except NotImplementedError, e:
  423. print >> sys.stderr, e
  424. self.pdcVector.DrawToDCClipped(dc, rgn)
  425. self.bufferLast = None
  426. else: # do not redraw pdc and pdcVector
  427. if self.bufferLast is None:
  428. # draw to the dc
  429. self.pdc.DrawToDC(dc)
  430. if self.pdcVector:
  431. # decorate with GDDC (transparency)
  432. try:
  433. gcdc = wx.GCDC(dc)
  434. self.pdcVector.DrawToDC(gcdc)
  435. except NotImplementedError, e:
  436. print >> sys.stderr, e
  437. self.pdcVector.DrawToDC(dc)
  438. # store buffered image
  439. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  440. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  441. pdcLast = wx.PseudoDC()
  442. pdcLast.DrawBitmap(bmp=self.bufferLast, x=0, y=0)
  443. pdcLast.DrawToDC(dc)
  444. # draw decorations (e.g. region box)
  445. try:
  446. gcdc = wx.GCDC(dc)
  447. self.pdcDec.DrawToDC(gcdc)
  448. except NotImplementedError, e:
  449. print >> sys.stderr, e
  450. self.pdcDec.DrawToDC(dc)
  451. # draw temporary object on the foreground
  452. ### self.pdcTmp.DrawToDCClipped(dc, rgn)
  453. self.pdcTmp.DrawToDC(dc)
  454. if switchDraw:
  455. self.redrawAll = False
  456. def OnSize(self, event):
  457. """
  458. Scale map image so that it is
  459. the same size as the Window
  460. """
  461. Debug.msg(3, "BufferedWindow.OnSize():")
  462. # set size of the input image
  463. self.Map.ChangeMapSize(self.GetClientSize())
  464. # align extent based on center point and display resolution
  465. # this causes that image is not resized when display windows is resized
  466. # self.Map.AlignExtentFromDisplay()
  467. # Make new off screen bitmap: this bitmap will always have the
  468. # current drawing in it, so it can be used to save the image to
  469. # a file, or whatever.
  470. self.buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  471. # get the image to be rendered
  472. self.img = self.GetImage()
  473. # update map display
  474. if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
  475. self.img = self.img.Scale(self.Map.width, self.Map.height)
  476. if len(self.Map.GetListOfLayers()) > 0:
  477. self.UpdateMap()
  478. # re-render image on idle
  479. self.resize = True
  480. # reposition checkbox in statusbar
  481. self.parent.StatusbarReposition()
  482. # update statusbar
  483. self.parent.StatusbarUpdate()
  484. def OnIdle(self, event):
  485. """
  486. Only re-render a composite map image from GRASS during
  487. idle time instead of multiple times during resizing.
  488. """
  489. if self.resize:
  490. self.UpdateMap(render=True)
  491. event.Skip()
  492. def SaveToFile(self, FileName, FileType):
  493. """
  494. This draws the psuedo DC to a buffer that
  495. can be saved to a file.
  496. """
  497. dc = wx.BufferedPaintDC(self, self.buffer)
  498. self.pdc.DrawToDC(dc)
  499. if self.pdcVector:
  500. self.pdcVector.DrawToDC(dc)
  501. self.buffer.SaveFile(FileName, FileType)
  502. def GetOverlay(self):
  503. """
  504. Converts rendered overlay files to wx.Image
  505. Updates self.imagedict
  506. @return list of images
  507. """
  508. imgs = []
  509. for overlay in self.Map.GetListOfLayers(l_type="overlay", l_active=True):
  510. if os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  511. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  512. self.imagedict[img] = { 'id' : overlay.id,
  513. 'layer' : overlay }
  514. imgs.append(img)
  515. return imgs
  516. def GetImage(self):
  517. """
  518. Converts redered map files to wx.Image
  519. Updates self.imagedict (id=99)
  520. @return wx.Image instance (map composition)
  521. """
  522. imgId = 99
  523. if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  524. os.path.getsize(self.Map.mapfile):
  525. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  526. else:
  527. img = None
  528. self.imagedict[img] = { 'id': imgId }
  529. return img
  530. def UpdateMap(self, render=True, renderVector=True):
  531. """
  532. Updates the canvas anytime there is a change to the
  533. underlaying images or to the geometry of the canvas.
  534. @param render re-render map composition
  535. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  536. """
  537. start = time.clock()
  538. self.resize = False
  539. # if len(self.Map.GetListOfLayers()) == 0:
  540. # return False
  541. if self.img is None:
  542. render = True
  543. #
  544. # initialize process bar (only on 'render')
  545. #
  546. if render is True or renderVector is True:
  547. self.parent.onRenderGauge.Show()
  548. if self.parent.onRenderGauge.GetRange() > 0:
  549. self.parent.onRenderGauge.SetValue(1)
  550. #
  551. # render background image if needed
  552. #
  553. # update layer dictionary if there has been a change in layers
  554. if self.tree and self.tree.reorder == True:
  555. self.tree.ReorderLayers()
  556. # reset flag for auto-rendering
  557. if self.tree:
  558. self.tree.rerender = False
  559. if render:
  560. # update display size
  561. self.Map.ChangeMapSize(self.GetClientSize())
  562. if self.parent.compResolution.IsChecked():
  563. # use computation region resolution for rendering
  564. windres = True
  565. else:
  566. windres = False
  567. self.mapfile = self.Map.Render(force=True, mapWindow=self.parent,
  568. windres=windres)
  569. else:
  570. self.mapfile = self.Map.Render(force=False, mapWindow=self.parent)
  571. self.img = self.GetImage() # id=99
  572. #
  573. # clear pseudoDcs
  574. #
  575. for pdc in (self.pdc,
  576. self.pdcDec,
  577. self.pdcTmp):
  578. pdc.Clear()
  579. pdc.RemoveAll()
  580. #
  581. # draw background map image to PseudoDC
  582. #
  583. if not self.img:
  584. self.Draw(self.pdc, pdctype='clear')
  585. else:
  586. try:
  587. id = self.imagedict[self.img]['id']
  588. except:
  589. return False
  590. self.Draw(self.pdc, self.img, drawid=id)
  591. #
  592. # render vector map layer
  593. #
  594. digitToolbar = self.parent.toolbars['vdigit']
  595. if renderVector and digitToolbar and \
  596. digitToolbar.GetLayer():
  597. # set region
  598. self.parent.digit.driver.UpdateRegion()
  599. # re-calculate threshold for digitization tool
  600. self.parent.digit.driver.GetThreshold()
  601. # draw map
  602. self.pdcVector.Clear()
  603. self.pdcVector.RemoveAll()
  604. try:
  605. item = self.tree.FindItemByData('maplayer', digitToolbar.GetLayer())
  606. except TypeError:
  607. item = None
  608. if item and self.tree.IsItemChecked(item):
  609. self.parent.digit.driver.DrawMap()
  610. # translate tmp objects (pointer position)
  611. if digitToolbar.GetAction() == 'moveLine':
  612. if hasattr(self, "vdigitMove") and \
  613. self.vdigitMove.has_key('beginDiff'):
  614. # move line
  615. for id in self.vdigitMove['id']:
  616. # print self.pdcTmp.GetIdBounds(id)
  617. self.pdcTmp.TranslateId(id,
  618. self.vdigitMove['beginDiff'][0],
  619. self.vdigitMove['beginDiff'][1])
  620. del self.vdigitMove['beginDiff']
  621. #
  622. # render overlays
  623. #
  624. for img in self.GetOverlay():
  625. # draw any active and defined overlays
  626. if self.imagedict[img]['layer'].IsActive():
  627. id = self.imagedict[img]['id']
  628. self.Draw(self.pdc, img=img, drawid=id,
  629. pdctype=self.overlays[id]['pdcType'], coords=self.overlays[id]['coords'])
  630. for id in self.textdict.keys():
  631. self.Draw(self.pdc, img=self.textdict[id], drawid=id,
  632. pdctype='text', coords=[10, 10, 10, 10])
  633. # optionally draw computational extent box
  634. self.DrawCompRegionExtent()
  635. #
  636. # redraw pdcTmp if needed
  637. #
  638. if len(self.polycoords) > 0:
  639. self.DrawLines(self.pdcTmp)
  640. if self.parent.gismanager.georectifying:
  641. # -> georectifier (redraw GCPs)
  642. if self.parent.toolbars['georect']:
  643. coordtype = 'gcpcoord'
  644. else:
  645. coordtype = 'mapcoord'
  646. self.parent.gismanager.georectifying.DrawGCP(coordtype)
  647. stop = time.clock()
  648. #
  649. # hide process bar
  650. #
  651. self.parent.onRenderGauge.Hide()
  652. #
  653. # update statusbar
  654. #
  655. ### self.Map.SetRegion()
  656. self.parent.StatusbarUpdate()
  657. Debug.msg (2, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  658. (render, renderVector, (stop-start)))
  659. return True
  660. def DrawCompRegionExtent(self):
  661. """
  662. Draw computational region extent in the display
  663. Display region is drawn as a blue box inside the computational region,
  664. computational region inside a display region as a red box).
  665. """
  666. if hasattr(self, "regionCoords"):
  667. compReg = self.Map.GetRegion()
  668. dispReg = self.Map.GetCurrentRegion()
  669. reg = None
  670. if self.IsInRegion(dispReg, compReg):
  671. self.polypen = wx.Pen(colour=wx.Colour(0, 0, 255, 128), width=3, style=wx.SOLID)
  672. reg = dispReg
  673. else:
  674. self.polypen = wx.Pen(colour=wx.Colour(255, 0, 0, 128),
  675. width=3, style=wx.SOLID)
  676. reg = compReg
  677. self.regionCoords = []
  678. self.regionCoords.append((reg['w'], reg['n']))
  679. self.regionCoords.append((reg['e'], reg['n']))
  680. self.regionCoords.append((reg['e'], reg['s']))
  681. self.regionCoords.append((reg['w'], reg['s']))
  682. self.regionCoords.append((reg['w'], reg['n']))
  683. # draw region extent
  684. self.DrawLines(pdc=self.pdcDec, polycoords=self.regionCoords)
  685. def IsInRegion(self, region, refRegion):
  686. """
  687. Test if 'region' is inside of 'refRegion'
  688. @param region input region
  689. @param refRegion reference region (e.g. computational region)
  690. @return True if region is inside of refRegion
  691. @return False
  692. """
  693. if region['s'] >= refRegion['s'] and \
  694. region['n'] <= refRegion['n'] and \
  695. region['w'] >= refRegion['w'] and \
  696. region['e'] <= refRegion['e']:
  697. return True
  698. return False
  699. def EraseMap(self):
  700. """
  701. Erase the canvas
  702. """
  703. self.Draw(self.pdc, pdctype='clear')
  704. if self.pdcVector:
  705. self.Draw(self.pdcVector, pdctype='clear')
  706. self.Draw(self.pdcDec, pdctype='clear')
  707. self.Draw(self.pdcTmp, pdctype='clear')
  708. def DragMap(self, moveto):
  709. """
  710. Drag the entire map image for panning.
  711. """
  712. dc = wx.BufferedDC(wx.ClientDC(self))
  713. dc.SetBackground(wx.Brush("White"))
  714. dc.Clear()
  715. self.dragimg = wx.DragImage(self.buffer)
  716. self.dragimg.BeginDrag((0, 0), self)
  717. self.dragimg.GetImageRect(moveto)
  718. self.dragimg.Move(moveto)
  719. self.dragimg.DoDrawImage(dc, moveto)
  720. self.dragimg.EndDrag()
  721. return True
  722. def DragItem(self, id, event):
  723. """
  724. Drag an overlay decoration item
  725. """
  726. if id == 99: return
  727. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  728. x, y = self.lastpos
  729. dx = event.GetX() - x
  730. dy = event.GetY() - y
  731. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  732. r = self.pdc.GetIdBounds(id)
  733. if id > 100: # text dragging
  734. rtop = (r[0],r[1]-r[3],r[2],r[3])
  735. r = r.Union(rtop)
  736. rleft = (r[0]-r[2],r[1],r[2],r[3])
  737. r = r.Union(rleft)
  738. self.pdc.TranslateId(id, dx, dy)
  739. r2 = self.pdc.GetIdBounds(id)
  740. if id > 100: # text
  741. self.textdict[id]['coords'] = r2
  742. r = r.Union(r2)
  743. r.Inflate(4,4)
  744. self.RefreshRect(r, False)
  745. self.lastpos = (event.GetX(), event.GetY())
  746. def MouseDraw(self, pdc=None, begin=None, end=None):
  747. """
  748. Mouse box or line from 'begin' to 'end'
  749. If not given from self.mouse['begin'] to self.mouse['end'].
  750. """
  751. self.redrawAll = False
  752. if not pdc:
  753. return
  754. if begin is None:
  755. begin = self.mouse['begin']
  756. if end is None:
  757. end = self.mouse['end']
  758. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  759. (self.mouse['use'], self.mouse['box'],
  760. begin[0], begin[1], end[0], end[1]))
  761. if self.mouse['box'] == "box":
  762. boxid = wx.ID_NEW
  763. mousecoords = [begin[0], begin[1],
  764. end[0], end[1]]
  765. r = pdc.GetIdBounds(boxid)
  766. r.Inflate(4,4)
  767. pdc.ClearId(boxid)
  768. self.RefreshRect(r, False)
  769. pdc.SetId(boxid)
  770. self.Draw(pdc, drawid=boxid, pdctype='box', coords=mousecoords)
  771. elif self.mouse['box'] == "line":
  772. self.lineid = wx.ID_NEW
  773. mousecoords = [begin[0], begin[1], \
  774. end[0], end[1]]
  775. x1=min(begin[0],end[0])
  776. x2=max(begin[0],end[0])
  777. y1=min(begin[1],end[1])
  778. y2=max(begin[1],end[1])
  779. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  780. r.Inflate(4,4)
  781. try:
  782. pdc.ClearId(self.lineid)
  783. except:
  784. pass
  785. self.RefreshRect(r, False)
  786. pdc.SetId(self.lineid)
  787. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=mousecoords)
  788. def DrawLines(self, pdc=None, polycoords=None):
  789. """
  790. Draw polyline in PseudoDC
  791. Set self.pline to wx.NEW_ID + 1
  792. polycoords - list of polyline vertices, geographical coordinates
  793. (if not given, self.polycoords is used)
  794. """
  795. if not pdc:
  796. pdc = self.pdcTmp
  797. if not polycoords:
  798. polycoords = self.polycoords
  799. if len(polycoords) > 0:
  800. self.plineid = wx.ID_NEW + 1
  801. # convert from EN to XY
  802. coords = []
  803. for p in polycoords:
  804. coords.append(self.Cell2Pixel(p))
  805. self.Draw(pdc, drawid=self.plineid, pdctype='polyline', coords=coords)
  806. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  807. (coords, self.plineid))
  808. return self.plineid
  809. return -1
  810. def DrawCross(self, pdc, coords, size, rotation=0,
  811. text=None, textAlign='lr', textOffset=(5, 5)):
  812. """Draw cross in PseudoDC
  813. @todo implement rotation
  814. @param pdc PseudoDC
  815. @param coord center coordinates
  816. @param rotation rotate symbol
  817. @param text draw also text (text, font, color, rotation)
  818. @param textAlign alignment (default 'lower-right')
  819. @textOffset offset for text (from center point)
  820. """
  821. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  822. (pdc, coords, size))
  823. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  824. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  825. self.lineid = wx.NewId()
  826. for lineCoords in coordsCross:
  827. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=lineCoords)
  828. if not text:
  829. return self.lineid
  830. if textAlign == 'ul':
  831. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  832. elif textAlign == 'ur':
  833. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  834. elif textAlign == 'lr':
  835. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  836. else:
  837. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  838. self.Draw(pdc, img=text,
  839. pdctype='text', coords=coord)
  840. return self.lineid
  841. def MouseActions(self, event):
  842. """
  843. Mouse motion and button click notifier
  844. """
  845. if not self.processMouse:
  846. return
  847. ### if self.redrawAll is False:
  848. ### self.redrawAll = True
  849. # zoom with mouse wheel
  850. if event.GetWheelRotation() != 0:
  851. self.OnMouseWheel(event)
  852. # left mouse button pressed
  853. elif event.LeftDown():
  854. self.OnLeftDown(event)
  855. # left mouse button released
  856. elif event.LeftUp():
  857. self.OnLeftUp(event)
  858. # dragging
  859. elif event.Dragging():
  860. self.OnDragging(event)
  861. # double click
  862. elif event.ButtonDClick():
  863. self.OnButtonDClick(event)
  864. # middle mouse button pressed
  865. elif event.MiddleDown():
  866. self.OnMiddleDown(event)
  867. # right mouse button pressed
  868. elif event.RightDown():
  869. self.OnRightDown(event)
  870. # right mouse button released
  871. elif event.RightUp():
  872. self.OnRightUp(event)
  873. elif event.Moving():
  874. self.OnMouseMoving(event)
  875. event.Skip()
  876. def OnMouseWheel(self, event):
  877. """
  878. Mouse wheel moved
  879. """
  880. self.processMouse = False
  881. current = event.GetPositionTuple()[:]
  882. wheel = event.GetWheelRotation()
  883. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  884. # zoom 1/2 of the screen, centered to current mouse position (TODO: settings)
  885. begin = (current[0] - self.Map.width / 4,
  886. current[1] - self.Map.height / 4)
  887. end = (current[0] + self.Map.width / 4,
  888. current[1] + self.Map.height / 4)
  889. if wheel > 0:
  890. zoomtype = 1
  891. else:
  892. zoomtype = -1
  893. # zoom
  894. self.Zoom(begin, end, zoomtype)
  895. # redraw map
  896. self.UpdateMap()
  897. ### self.OnPaint(None)
  898. # update statusbar
  899. self.parent.StatusbarUpdate()
  900. self.Refresh()
  901. self.processMouse = True
  902. event.Skip()
  903. def OnDragging(self, event):
  904. """
  905. Mouse dragging with left button down
  906. """
  907. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  908. current = event.GetPositionTuple()[:]
  909. previous = self.mouse['begin']
  910. move = (current[0] - previous[0],
  911. current[1] - previous[1])
  912. digitToolbar = self.parent.toolbars['vdigit']
  913. # dragging or drawing box with left button
  914. if self.mouse['use'] == 'pan':
  915. self.DragMap(move)
  916. # dragging decoration overlay item
  917. elif (self.mouse['use'] == 'pointer' and
  918. not digitToolbar and
  919. self.dragid != None):
  920. self.DragItem(self.dragid, event)
  921. # dragging anything else - rubber band box or line
  922. else:
  923. if (self.mouse['use'] == 'pointer' and
  924. not digitToolbar): return
  925. self.mouse['end'] = event.GetPositionTuple()[:]
  926. digitClass = self.parent.digit
  927. if (event.LeftIsDown() and
  928. not (digitToolbar and
  929. digitToolbar.GetAction() in ("moveLine",) and
  930. digitClass.driver.GetSelected() > 0)):
  931. # draw box only when left mouse button is pressed
  932. self.MouseDraw(pdc=self.pdcTmp)
  933. event.Skip()
  934. def OnLeftDown(self, event):
  935. """
  936. Left mouse button pressed
  937. """
  938. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  939. self.mouse["use"])
  940. self.mouse['begin'] = event.GetPositionTuple()[:]
  941. if self.mouse["use"] in ["measure", "profile"]:
  942. # measure or profile
  943. if len(self.polycoords) == 0:
  944. self.mouse['end'] = self.mouse['begin']
  945. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  946. self.ClearLines(pdc=self.pdcTmp)
  947. else:
  948. self.mouse['begin'] = self.mouse['end']
  949. elif self.mouse['use'] == 'zoom':
  950. pass
  951. elif self.mouse["use"] == "pointer" and self.parent.toolbars['vdigit']:
  952. # digitization
  953. digitToolbar = self.parent.toolbars['vdigit']
  954. digitClass = self.parent.digit
  955. east, north = self.Pixel2Cell(self.mouse['begin'])
  956. try:
  957. map = digitToolbar.GetLayer().GetName()
  958. except:
  959. map = None
  960. wx.MessageBox(parent=self,
  961. message=_("No vector map selected for editing."),
  962. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  963. event.Skip()
  964. return
  965. # calculate position of 'update record' dialog
  966. position = self.mouse['begin']
  967. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  968. position[1] + self.dialogOffset))
  969. if digitToolbar.GetAction() not in ("moveVertex", "addVertex",
  970. "removeVertex", "editLine"):
  971. # set pen
  972. self.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  973. self.polypen = wx.Pen(colour='dark green', width=2, style=wx.SOLID)
  974. if digitToolbar.GetAction() in ("addVertex", "removeVertex"):
  975. # unselect
  976. digitClass.driver.SetSelected([])
  977. if digitToolbar.GetAction() == "addLine":
  978. if digitToolbar.GetAction('type') in ["point", "centroid"]:
  979. # add new point
  980. if digitToolbar.GetAction('type') == 'point':
  981. point = True
  982. else:
  983. point = False
  984. fid = digitClass.AddPoint(map, point, east, north)
  985. if fid < 0:
  986. return
  987. self.UpdateMap(render=False) # redraw map
  988. # add new record into atribute table
  989. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') is True:
  990. # select attributes based on layer and category
  991. cats = { fid : {
  992. UserSettings.Get(group='vdigit', key="layer", subkey='value') :
  993. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  994. }}
  995. addRecordDlg = dbm.DisplayAttributesDialog(parent=self, map=map,
  996. cats=cats,
  997. pos=posWindow,
  998. action="add")
  999. if addRecordDlg.mapDBInfo and \
  1000. addRecordDlg.ShowModal() == wx.ID_OK:
  1001. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1002. for sql in addRecordDlg.GetSQLString():
  1003. sqlfile.file.write(sql + ";\n")
  1004. sqlfile.file.flush()
  1005. executeCommand = gcmd.Command(cmd=["db.execute",
  1006. "--q",
  1007. "input=%s" % sqlfile.name])
  1008. elif digitToolbar.GetAction('type') in ["line", "boundary"]:
  1009. # add new point to the line
  1010. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  1011. self.DrawLines(pdc=self.pdcTmp)
  1012. elif digitToolbar.GetAction() == "editLine" and hasattr(self, "vdigitMove"):
  1013. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  1014. self.vdigitMove['id'].append(wx.NewId())
  1015. self.DrawLines(pdc=self.pdcTmp)
  1016. elif digitToolbar.GetAction() == "deleteLine":
  1017. pass
  1018. elif digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] and \
  1019. not hasattr(self, "vdigitMove"):
  1020. self.vdigitMove = {}
  1021. # geographic coordinates of initial position (left-down)
  1022. self.vdigitMove['begin'] = None
  1023. # list of ids to modify
  1024. self.vdigitMove['id'] = []
  1025. # ids geographic coordinates
  1026. self.vdigitMove['coord'] = {}
  1027. if digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  1028. # set pen
  1029. pcolor = UserSettings.Get(group='vdigit', key="symbol",
  1030. subkey=["highlight", "color"])
  1031. self.pen = self.polypen = wx.Pen(colour=pcolor,
  1032. width=2, style=wx.SHORT_DASH)
  1033. self.pdcTmp.SetPen(self.polypen)
  1034. elif digitToolbar.GetAction() == "splitLine":
  1035. # unselect
  1036. digitClass.driver.SetSelected([])
  1037. elif digitToolbar.GetAction() in ["displayAttrs", "displayCats"]:
  1038. qdist = digitClass.driver.GetThreshold(type='selectThresh')
  1039. coords = (east, north)
  1040. if digitClass.type == 'vdigit':
  1041. # unselect
  1042. digitClass.driver.SetSelected([])
  1043. # select feature by point
  1044. cats = {}
  1045. if digitClass.driver.SelectLineByPoint(coords,
  1046. digitClass.GetSelectType()) is not None:
  1047. if UserSettings.Get(group='vdigit', key='checkForDupl',
  1048. subkey='enabled'):
  1049. lines = digitClass.driver.GetSelected()
  1050. else:
  1051. lines = (digitClass.driver.GetSelected()[0],) # only first found
  1052. for line in lines:
  1053. cats[line] = digitClass.GetLineCats(line)
  1054. if digitToolbar.GetAction() == "displayAttrs":
  1055. # select attributes based on coordinates (all layers)
  1056. if self.parent.dialogs['attributes'] is None:
  1057. if digitClass.type == 'vedit':
  1058. self.parent.dialogs['attributes'] = dbm.DisplayAttributesDialog(parent=self, map=map,
  1059. query=(coords, qdist),
  1060. pos=posWindow,
  1061. action="update")
  1062. else:
  1063. self.parent.dialogs['attributes'] = dbm.DisplayAttributesDialog(parent=self, map=map,
  1064. cats=cats,
  1065. action="update")
  1066. else:
  1067. # update currently open dialog
  1068. if digitClass.type == 'vedit':
  1069. self.parent.dialogs['attributes'].UpdateDialog(query=(coords, qdist))
  1070. else:
  1071. # upgrade dialog
  1072. self.parent.dialogs['attributes'].UpdateDialog(cats=cats)
  1073. if self.parent.dialogs['attributes']:
  1074. if len(cats.keys()) > 0:
  1075. # highlight feature & re-draw map
  1076. if not self.parent.dialogs['attributes'].IsShown():
  1077. self.parent.dialogs['attributes'].Show()
  1078. else:
  1079. if self.parent.dialogs['attributes'] and \
  1080. self.parent.dialogs['attributes'].IsShown():
  1081. self.parent.dialogs['attributes'].Hide()
  1082. else: # displayCats
  1083. if self.parent.dialogs['category'] is None:
  1084. # open new dialog
  1085. if digitClass.type == 'vedit':
  1086. dlg = VDigitCategoryDialog(parent=self,
  1087. map=map,
  1088. query=(coords, qdist),
  1089. pos=posWindow,
  1090. title=_("Update categories"))
  1091. self.parent.dialogs['category'] = dlg
  1092. else:
  1093. dlg = VDigitCategoryDialog(parent=self,
  1094. map=map,
  1095. cats=cats,
  1096. pos=posWindow,
  1097. title=_("Update categories"))
  1098. self.parent.dialogs['category'] = dlg
  1099. else:
  1100. # update currently open dialog
  1101. if digitClass.type == 'vedit':
  1102. self.parent.dialogs['category'].UpdateDialog(query=(coords, qdist))
  1103. else:
  1104. # upgrade dialog
  1105. self.parent.dialogs['category'].UpdateDialog(cats=cats)
  1106. if self.parent.dialogs['category']:
  1107. if len(cats.keys()) > 0:
  1108. # highlight feature & re-draw map
  1109. ### digitClass.driver.SetSelected(line)
  1110. if not self.parent.dialogs['category'].IsShown():
  1111. self.parent.dialogs['category'].Show()
  1112. else:
  1113. if self.parent.dialogs['category'].IsShown():
  1114. self.parent.dialogs['category'].Hide()
  1115. self.UpdateMap(render=False)
  1116. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1117. if not hasattr(self, "copyCatsList"):
  1118. self.copyCatsList = []
  1119. else:
  1120. self.copyCatsIds = []
  1121. self.mouse['box'] = 'box'
  1122. elif digitToolbar.GetAction() == "copyLine":
  1123. self.copyIds = []
  1124. self.layerTmp = None
  1125. elif digitToolbar.GetAction() == "zbulkLine":
  1126. if len(self.polycoords) > 1: # start new line
  1127. self.polycoords = []
  1128. self.ClearLines(pdc=self.pdcTmp)
  1129. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  1130. if len(self.polycoords) == 1:
  1131. begin = self.Pixel2Cell(self.polycoords[-1])
  1132. end = self.Pixel2Cell(self.mouse['end'])
  1133. else:
  1134. end = self.Pixel2Cell(self.polycoords[-1])
  1135. begin = self.Pixel2Cell(self.mouse['begin'])
  1136. self.DrawLines(self.pdcTmp, begin, end)
  1137. else:
  1138. # get decoration id
  1139. self.lastpos = self.mouse['begin']
  1140. idlist = self.pdc.FindObjects(x=self.lastpos[0], y=self.lastpos[1],
  1141. radius=self.hitradius)
  1142. if 99 in idlist: idlist.remove(99)
  1143. if idlist != [] :
  1144. self.dragid = idlist[0] #drag whatever is on top
  1145. event.Skip()
  1146. def OnLeftUp(self, event):
  1147. """
  1148. Left mouse button released
  1149. """
  1150. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  1151. self.mouse["use"])
  1152. self.mouse['end'] = event.GetPositionTuple()[:]
  1153. if self.mouse['use'] in ["zoom", "pan"]:
  1154. # set region in zoom or pan
  1155. begin = self.mouse['begin']
  1156. end = self.mouse['end']
  1157. if self.mouse['use'] == 'zoom':
  1158. # set region for click (zero-width box)
  1159. if begin[0] - end[0] == 0 or \
  1160. begin[1] - end[1] == 0:
  1161. # zoom 1/2 of the screen (TODO: settings)
  1162. begin = (end[0] - self.Map.width / 4,
  1163. end[1] - self.Map.height / 4)
  1164. end = (end[0] + self.Map.width / 4,
  1165. end[1] + self.Map.height / 4)
  1166. self.Zoom(begin, end, self.zoomtype)
  1167. # redraw map
  1168. self.UpdateMap(render=True)
  1169. # update statusbar
  1170. self.parent.StatusbarUpdate()
  1171. elif self.mouse["use"] == "query":
  1172. # querying
  1173. self.parent.QueryMap(self.mouse['begin'][0],self.mouse['begin'][1])
  1174. elif self.mouse["use"] == "queryVector":
  1175. # editable mode for vector map layers
  1176. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  1177. # clear temp canvas
  1178. self.UpdateMap(render=False, renderVector=False)
  1179. elif self.mouse["use"] in ["measure", "profile"]:
  1180. # measure or profile
  1181. if self.mouse["use"] == "measure":
  1182. self.parent.MeasureDist(self.mouse['begin'], self.mouse['end'])
  1183. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  1184. self.ClearLines(pdc=self.pdcTmp)
  1185. self.DrawLines(pdc=self.pdcTmp)
  1186. elif self.mouse["use"] == "pointer" and self.parent.gismanager.georectifying:
  1187. # -> georectifying
  1188. coord = self.Pixel2Cell(self.mouse['end'])
  1189. if self.parent.toolbars['georect']:
  1190. coordtype = 'gcpcoord'
  1191. else:
  1192. coordtype = 'mapcoord'
  1193. self.parent.gismanager.georectifying.SetGCPData(coordtype, coord, self)
  1194. self.UpdateMap(render=False, renderVector=False)
  1195. elif self.mouse["use"] == "pointer" and self.parent.toolbars['vdigit']:
  1196. # digitization tool active
  1197. digitToolbar = self.parent.toolbars['vdigit']
  1198. digitClass = self.parent.digit
  1199. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1200. pos2 = self.Pixel2Cell(self.mouse['end'])
  1201. if hasattr(self, "vdigitMove"):
  1202. if len(digitClass.driver.GetSelected()) == 0:
  1203. self.vdigitMove['begin'] = pos1 # left down
  1204. ### else:
  1205. ### dx = pos2[0] - pos1[0] ### ???
  1206. ### dy = pos2[1] - pos1[1]
  1207. ### self.vdigitMove = (self.vdigitMove['begin'][0] + dx,
  1208. ### self.vdigitMove['begin'][1] + dy)
  1209. # eliminate initial mouse moving efect
  1210. self.mouse['begin'] = self.mouse['end']
  1211. if digitToolbar.GetAction() in ["deleteLine", "moveLine", "moveVertex",
  1212. "copyCats", "copyAttrs", "editLine", "flipLine",
  1213. "mergeLine", "snapLine",
  1214. "queryLine", "breakLine", "typeConv", "connectLine"]:
  1215. nselected = 0
  1216. # -> delete line || move line || move vertex
  1217. if digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  1218. if len(digitClass.driver.GetSelected()) == 0:
  1219. nselected = digitClass.driver.SelectLineByPoint(pos1, type=VDigit_Lines_Type)
  1220. if digitToolbar.GetAction() == "editLine":
  1221. try:
  1222. selVertex = digitClass.driver.GetSelectedVertex(pos1)[0]
  1223. except IndexError:
  1224. selVertex = None
  1225. if selVertex:
  1226. # self.UpdateMap(render=False)
  1227. ids = digitClass.driver.GetSelected(grassId=False)
  1228. # move this line to tmp layer
  1229. self.polycoords = []
  1230. for id in ids:
  1231. if id % 2: # register only vertices
  1232. e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
  1233. self.polycoords.append((e, n))
  1234. # self.pdcVector.RemoveId(id)
  1235. digitClass.driver.DrawSelected(False)
  1236. if selVertex < ids[-1] / 2:
  1237. # choose first or last node of line
  1238. self.vdigitMove['id'].reverse()
  1239. self.polycoords.reverse()
  1240. else:
  1241. # unselect
  1242. digitClass.driver.SetSelected([])
  1243. del self.vdigitMove
  1244. self.UpdateMap(render=False)
  1245. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1246. if not hasattr(self, "copyCatsIds"):
  1247. # 'from' -> select by point
  1248. nselected = digitClass.driver.SelectLineByPoint(pos1, digitClass.GetSelectType())
  1249. if nselected:
  1250. self.copyCatsList = digitClass.driver.GetSelected()
  1251. else:
  1252. # -> 'to' -> select by bbox
  1253. digitClass.driver.SetSelected([])
  1254. # return number of selected features (by box/point)
  1255. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1256. digitClass.GetSelectType())
  1257. if nselected == 0:
  1258. if digitClass.driver.SelectLineByPoint(pos1,
  1259. digitClass.GetSelectType()) is not None:
  1260. nselected = 1
  1261. if nselected > 0:
  1262. self.copyCatsIds = digitClass.driver.GetSelected()
  1263. elif digitToolbar.GetAction() == "queryLine":
  1264. selected = digitClass.SelectLinesByQuery(pos1, pos2)
  1265. nselected = len(selected)
  1266. if nselected > 0:
  1267. digitClass.driver.SetSelected(selected)
  1268. else:
  1269. # -> moveLine || deleteLine, etc. (select by point/box)
  1270. if digitToolbar.GetAction() == 'moveLine' and \
  1271. len(digitClass.driver.GetSelected()) > 0:
  1272. nselected = 0
  1273. else:
  1274. if digitToolbar.GetAction() == 'moveLine':
  1275. drawSeg = True
  1276. else:
  1277. drawSeg = False
  1278. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1279. digitClass.GetSelectType(),
  1280. drawSeg)
  1281. if nselected == 0:
  1282. if digitClass.driver.SelectLineByPoint(pos1,
  1283. digitClass.GetSelectType()) is not None:
  1284. nselected = 1
  1285. if nselected > 0:
  1286. if digitToolbar.GetAction() in ["moveLine", "moveVertex"]:
  1287. # get pseudoDC id of objects which should be redrawn
  1288. if digitToolbar.GetAction() == "moveLine":
  1289. # -> move line
  1290. self.vdigitMove['id'] = digitClass.driver.GetSelected(grassId=False)
  1291. self.vdigitMove['coord'] = digitClass.driver.GetSelectedCoord()
  1292. elif digitToolbar.GetAction() == "moveVertex":
  1293. # -> move vertex
  1294. self.vdigitMove['id'] = digitClass.driver.GetSelectedVertex(pos1)
  1295. if len(self.vdigitMove['id']) == 0: # no vertex found
  1296. digitClass.driver.SetSelected([])
  1297. #
  1298. # check for duplicates
  1299. #
  1300. if UserSettings.Get(group='vdigit', key='checkForDupl', subkey='enabled') is True:
  1301. dupl = digitClass.driver.GetDuplicates()
  1302. self.UpdateMap(render=False)
  1303. if dupl:
  1304. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1305. self.mouse['end'][1] + self.dialogOffset))
  1306. dlg = VDigitDuplicatesDialog(parent=self, data=dupl, pos=posWindow)
  1307. if dlg.ShowModal() == wx.ID_OK:
  1308. digitClass.driver.UnSelect(dlg.GetUnSelected())
  1309. # update selected
  1310. self.UpdateMap(render=False)
  1311. if digitToolbar.GetAction() != "editLine":
  1312. # -> move line || move vertex
  1313. self.UpdateMap(render=False)
  1314. else: # no vector object found
  1315. if not (digitToolbar.GetAction() in ["moveLine", "moveVertex"] and \
  1316. len(self.vdigitMove['id']) > 0):
  1317. # avoid left-click when features are already selected
  1318. self.UpdateMap(render=False, renderVector=False)
  1319. elif digitToolbar.GetAction() in ["splitLine", "addVertex", "removeVertex"]:
  1320. pointOnLine = digitClass.driver.SelectLineByPoint(pos1,
  1321. type=VDigit_Lines_Type)
  1322. if pointOnLine:
  1323. if digitToolbar.GetAction() in ["splitLine", "addVertex"]:
  1324. self.UpdateMap(render=False) # highlight object
  1325. self.DrawCross(pdc=self.pdcTmp, coords=self.Cell2Pixel(pointOnLine),
  1326. size=5)
  1327. elif digitToolbar.GetAction() == "removeVertex":
  1328. # get only id of vertex
  1329. try:
  1330. id = digitClass.driver.GetSelectedVertex(pos1)[0]
  1331. except IndexError:
  1332. id = None
  1333. if id:
  1334. x, y = self.pdcVector.GetIdBounds(id)[0:2]
  1335. self.pdcVector.RemoveId(id)
  1336. self.UpdateMap(render=False) # highlight object
  1337. self.DrawCross(pdc=self.pdcTmp, coords=(x, y),
  1338. size=5)
  1339. else:
  1340. # unselect
  1341. digitClass.driver.SetSelected([])
  1342. self.UpdateMap(render=False)
  1343. elif digitToolbar.GetAction() == "copyLine":
  1344. if UserSettings.Get(group='vdigit', key='bgmap',
  1345. subkey='value', internal=True) == '':
  1346. # no background map -> copy from current vector map layer
  1347. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1348. digitClass.GetSelectType())
  1349. if nselected > 0:
  1350. # highlight selected features
  1351. self.UpdateMap(render=False)
  1352. else:
  1353. self.UpdateMap(render=False, renderVector=False)
  1354. else:
  1355. # copy features from background map
  1356. self.copyIds = digitClass.SelectLinesFromBackgroundMap(pos1, pos2)
  1357. if len(self.copyIds) > 0:
  1358. color = UserSettings.Get(group='vdigit', key='symbol',
  1359. subkey=['highlight', 'color'])
  1360. colorStr = str(color[0]) + ":" + \
  1361. str(color[1]) + ":" + \
  1362. str(color[2])
  1363. dVectTmp = ['d.vect',
  1364. 'map=%s' % UserSettings.Get(group='vdigit', key='bgmap',
  1365. subkey='value', internal=True),
  1366. 'cats=%s' % utils.ListOfCatsToRange(self.copyIds),
  1367. '-i',
  1368. 'color=%s' % colorStr,
  1369. 'fcolor=%s' % colorStr,
  1370. 'type=point,line,boundary,centroid',
  1371. 'width=2']
  1372. self.layerTmp = self.Map.AddLayer(type='vector',
  1373. name=globalvar.QUERYLAYER,
  1374. command=dVectTmp)
  1375. self.UpdateMap(render=True, renderVector=False)
  1376. else:
  1377. self.UpdateMap(render=False, renderVector=False)
  1378. self.redrawAll = None
  1379. elif digitToolbar.GetAction() == "zbulkLine" and len(self.polycoords) == 2:
  1380. # select lines to be labeled
  1381. pos1 = self.polycoords[0]
  1382. pos2 = self.polycoords[1]
  1383. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1384. digitClass.GetSelectType())
  1385. if nselected > 0:
  1386. # highlight selected features
  1387. self.UpdateMap(render=False)
  1388. self.DrawLines(pdc=self.pdcTmp) # redraw temp line
  1389. else:
  1390. self.UpdateMap(render=False, renderVector=False)
  1391. elif digitToolbar.GetAction() == "connectLine":
  1392. if len(digitClass.driver.GetSelected()) > 0:
  1393. self.UpdateMap(render=False)
  1394. if len(digitClass.driver.GetSelected()) > 0:
  1395. self.redrawAll = None
  1396. ### self.OnPaint(None)
  1397. elif self.dragid != None:
  1398. # end drag of overlay decoration
  1399. if self.overlays.has_key(self.dragid):
  1400. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1401. self.dragid = None
  1402. self.currtxtid = None
  1403. self.UpdateMap(render=True)
  1404. event.Skip()
  1405. def OnButtonDClick(self, event):
  1406. """
  1407. Mouse button double click
  1408. """
  1409. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  1410. self.mouse["use"])
  1411. if self.mouse["use"] == "measure":
  1412. # measure
  1413. self.ClearLines(pdc=self.pdcTmp)
  1414. self.polycoords = []
  1415. self.mouse['use'] = 'pointer'
  1416. self.mouse['box'] = 'point'
  1417. self.mouse['end'] = [0, 0]
  1418. ### self.Refresh()
  1419. self.SetCursor(self.parent.cursors["default"])
  1420. elif self.mouse["use"] == "profile":
  1421. # profile
  1422. pass
  1423. # self.pdc.ClearId(self.lineid)
  1424. # self.pdc.ClearId(self.plineid)
  1425. # print 'coordinates: ',self.polycoords
  1426. # self.polycoords = []
  1427. # self.mouse['begin'] = self.mouse['end'] = [0, 0]
  1428. # self.Refresh()
  1429. elif self.mouse['use'] == 'pointer' and self.parent.toolbars['vdigit']:
  1430. # digitization tool
  1431. pass
  1432. else:
  1433. # select overlay decoration options dialog
  1434. clickposition = event.GetPositionTuple()[:]
  1435. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1436. if idlist == []:
  1437. return
  1438. self.dragid = idlist[0]
  1439. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1440. if self.dragid > 100:
  1441. self.currtxtid = self.dragid
  1442. self.parent.OnAddText(None)
  1443. elif self.dragid == 0:
  1444. self.parent.OnAddBarscale(None)
  1445. elif self.dragid == 1:
  1446. self.parent.OnAddLegend(None)
  1447. event.Skip()
  1448. def OnRightDown(self, event):
  1449. """
  1450. Right mouse button pressed
  1451. """
  1452. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1453. self.mouse["use"])
  1454. x,y = event.GetPositionTuple()[:]
  1455. l = self.pdc.FindObjects(x=x, y=y, radius=self.hitradius)
  1456. if not l:
  1457. return
  1458. id = l[0]
  1459. if id != 99:
  1460. if self.pdc.GetIdGreyedOut(id) == True:
  1461. self.pdc.SetIdGreyedOut(id, False)
  1462. else:
  1463. self.pdc.SetIdGreyedOut(id, True)
  1464. r = self.pdc.GetIdBounds(id)
  1465. r.Inflate(4,4)
  1466. self.RefreshRect(r, False)
  1467. digitToolbar = self.parent.toolbars['vdigit']
  1468. if digitToolbar:
  1469. digitClass = self.parent.digit
  1470. # digitization tool (confirm action)
  1471. if digitToolbar.GetAction() in ["moveLine", "moveVertex"] and \
  1472. hasattr(self, "vdigitMove"):
  1473. pFrom = self.vdigitMove['begin']
  1474. pTo = self.Pixel2Cell(event.GetPositionTuple())
  1475. move = (pTo[0] - pFrom[0],
  1476. pTo[1] - pFrom[1])
  1477. if digitToolbar.GetAction() == "moveLine":
  1478. # move line
  1479. if digitClass.MoveSelectedLines(move) < 0:
  1480. return
  1481. elif digitToolbar.GetAction() == "moveVertex":
  1482. # move vertex
  1483. if digitClass.MoveSelectedVertex(pFrom, move) < 0:
  1484. return
  1485. del self.vdigitMove
  1486. event.Skip()
  1487. def OnRightUp(self, event):
  1488. """
  1489. Right mouse button released
  1490. """
  1491. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1492. self.mouse["use"])
  1493. digitToolbar = self.parent.toolbars['vdigit']
  1494. if digitToolbar:
  1495. digitClass = self.parent.digit
  1496. # digitization tool (confirm action)
  1497. if digitToolbar.GetAction() == "addLine" and \
  1498. digitToolbar.GetAction('type') in ["line", "boundary"]:
  1499. # -> add new line / boundary
  1500. try:
  1501. map = digitToolbar.GetLayer().GetName()
  1502. except:
  1503. map = None
  1504. wx.MessageBox(parent=self,
  1505. message=_("No vector map selected for editing."),
  1506. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1507. if map:
  1508. # mapcoords = []
  1509. # xy -> EN
  1510. # for coord in self.polycoords:
  1511. # mapcoords.append(self.Pixel2Cell(coord))
  1512. if digitToolbar.GetAction('type') == 'line':
  1513. line = True
  1514. else:
  1515. line = False
  1516. if len(self.polycoords) < 2: # ignore 'one-point' lines
  1517. return
  1518. fid = digitClass.AddLine(map, line, self.polycoords)
  1519. if fid < 0:
  1520. return
  1521. position = self.Cell2Pixel(self.polycoords[-1])
  1522. self.polycoords = []
  1523. self.UpdateMap(render=False)
  1524. self.redrawAll = True
  1525. # add new record into atribute table
  1526. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') is True:
  1527. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  1528. position[1] + self.dialogOffset))
  1529. # select attributes based on layer and category
  1530. cats = { fid : {
  1531. UserSettings.Get(group='vdigit', key="layer", subkey='value') :
  1532. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  1533. }}
  1534. addRecordDlg = dbm.DisplayAttributesDialog(parent=self, map=map,
  1535. cats=cats,
  1536. pos=posWindow,
  1537. action="add")
  1538. if addRecordDlg.mapDBInfo and \
  1539. addRecordDlg.ShowModal() == wx.ID_OK:
  1540. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1541. for sql in addRecordDlg.GetSQLString():
  1542. sqlfile.file.write(sql + ";\n")
  1543. sqlfile.file.flush()
  1544. executeCommand = gcmd.Command(cmd=["db.execute",
  1545. "--q",
  1546. "input=%s" % sqlfile.name])
  1547. elif digitToolbar.GetAction() == "deleteLine":
  1548. # -> delete selected vector features
  1549. if digitClass.DeleteSelectedLines() < 0:
  1550. return
  1551. elif digitToolbar.GetAction() == "splitLine":
  1552. # split line
  1553. if digitClass.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1554. return
  1555. elif digitToolbar.GetAction() == "addVertex":
  1556. # add vertex
  1557. if digitClass.AddVertex(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1558. return
  1559. elif digitToolbar.GetAction() == "removeVertex":
  1560. # remove vertex
  1561. if digitClass.RemoveVertex(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1562. return
  1563. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1564. try:
  1565. if digitToolbar.GetAction() == 'copyCats':
  1566. if digitClass.CopyCats(self.copyCatsList,
  1567. self.copyCatsIds, copyAttrb=False) < 0:
  1568. return
  1569. else:
  1570. if digitClass.CopyCats(self.copyCatsList,
  1571. self.copyCatsIds, copyAttrb=True) < 0:
  1572. return
  1573. del self.copyCatsList
  1574. del self.copyCatsIds
  1575. except AttributeError:
  1576. pass
  1577. elif digitToolbar.GetAction() == "editLine" and \
  1578. hasattr(self, "vdigitMove"):
  1579. line = digitClass.driver.GetSelected()
  1580. if digitClass.EditLine(line, self.polycoords) < 0:
  1581. return
  1582. del self.vdigitMove
  1583. elif digitToolbar.GetAction() == "flipLine":
  1584. if digitClass.FlipLine() < 0:
  1585. return
  1586. elif digitToolbar.GetAction() == "mergeLine":
  1587. if digitClass.MergeLine() < 0:
  1588. return
  1589. elif digitToolbar.GetAction() == "breakLine":
  1590. if digitClass.BreakLine() < 0:
  1591. return
  1592. elif digitToolbar.GetAction() == "snapLine":
  1593. if digitClass.SnapLine() < 0:
  1594. return
  1595. elif digitToolbar.GetAction() == "connectLine":
  1596. if len(digitClass.driver.GetSelected()) > 1:
  1597. if digitClass.ConnectLine() < 0:
  1598. return
  1599. elif digitToolbar.GetAction() == "copyLine":
  1600. if digitClass.CopyLine(self.copyIds) < 0:
  1601. return
  1602. del self.copyIds
  1603. if self.layerTmp:
  1604. self.Map.DeleteLayer(self.layerTmp)
  1605. self.UpdateMap(render=True, renderVector=False)
  1606. del self.layerTmp
  1607. elif digitToolbar.GetAction() == "zbulkLine" and len(self.polycoords) == 2:
  1608. pos1 = self.polycoords[0]
  1609. pos2 = self.polycoords[1]
  1610. selected = digitClass.driver.GetSelected()
  1611. dlg = VDigitZBulkDialog(parent=self, title=_("Z bulk-labeling dialog"),
  1612. nselected=len(selected))
  1613. if dlg.ShowModal() == wx.ID_OK:
  1614. if digitClass.ZBulkLine(pos1, pos2, dlg.value.GetValue(),
  1615. dlg.step.GetValue()) < 0:
  1616. return
  1617. self.UpdateMap(render=False, renderVector=True)
  1618. elif digitToolbar.GetAction() == "typeConv":
  1619. # -> feature type conversion
  1620. # - point <-> centroid
  1621. # - line <-> boundary
  1622. if digitClass.TypeConvForSelectedLines() < 0:
  1623. return
  1624. if digitToolbar.GetAction() != "addLine":
  1625. # unselect and re-render
  1626. digitClass.driver.SetSelected([])
  1627. self.polycoords = []
  1628. self.UpdateMap(render=False)
  1629. self.redrawAll = True
  1630. event.Skip()
  1631. def OnMiddleDown(self, event):
  1632. """
  1633. Middle mouse button pressed
  1634. """
  1635. digitToolbar = self.parent.toolbars['vdigit']
  1636. # digitization tool
  1637. if self.mouse["use"] == "pointer" and digitToolbar:
  1638. digitClass = self.parent.digit
  1639. if (digitToolbar.GetAction() == "addLine" and \
  1640. digitToolbar.GetAction('type') in ["line", "boundary"]) or \
  1641. digitToolbar.GetAction() == "editLine":
  1642. # add line or boundary -> remove last point from the line
  1643. try:
  1644. removed = self.polycoords.pop()
  1645. Debug.msg(4, "BufferedWindow.OnMiddleDown(): polycoords_poped=%s" % \
  1646. [removed,])
  1647. self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1])
  1648. except:
  1649. pass
  1650. if digitToolbar.GetAction() == "editLine":
  1651. # remove last vertex & line
  1652. if len(self.vdigitMove['id']) > 1:
  1653. self.vdigitMove['id'].pop()
  1654. self.UpdateMap(render=False, renderVector=False)
  1655. elif digitToolbar.GetAction() in ["deleteLine", "moveLine", "splitLine",
  1656. "addVertex", "removeVertex", "moveVertex",
  1657. "copyCats", "flipLine", "mergeLine",
  1658. "snapLine", "connectLine", "copyLine",
  1659. "queryLine", "breakLine", "typeConv"]:
  1660. # varios tools -> unselected selected features
  1661. digitClass.driver.SetSelected([])
  1662. if digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] and \
  1663. hasattr(self, "vdigitMove"):
  1664. del self.vdigitMove
  1665. elif digitToolbar.GetAction() == "copyCats":
  1666. try:
  1667. del self.copyCatsList
  1668. del self.copyCatsIds
  1669. except AttributeError:
  1670. pass
  1671. elif digitToolbar.GetAction() == "copyLine":
  1672. del self.copyIds
  1673. if self.layerTmp:
  1674. self.Map.DeleteLayer(self.layerTmp)
  1675. self.UpdateMap(render=True, renderVector=False)
  1676. del self.layerTmp
  1677. self.polycoords = []
  1678. self.UpdateMap(render=False) # render vector
  1679. elif digitToolbar.GetAction() == "zbulkLine":
  1680. # reset polyline
  1681. self.polycoords = []
  1682. digitClass.driver.SetSelected([])
  1683. self.UpdateMap(render=False)
  1684. self.redrawAll = True
  1685. def OnMouseMoving(self, event):
  1686. """
  1687. Motion event and no mouse buttons were pressed
  1688. """
  1689. digitToolbar = self.parent.toolbars['vdigit']
  1690. if self.mouse["use"] == "pointer" and digitToolbar:
  1691. digitClass = self.parent.digit
  1692. self.mouse['end'] = event.GetPositionTuple()[:]
  1693. Debug.msg (5, "BufferedWindow.OnMouseMoving(): coords=%f,%f" % \
  1694. (self.mouse['end'][0], self.mouse['end'][1]))
  1695. if digitToolbar.GetAction() == "addLine" and digitToolbar.GetAction('type') in ["line", "boundary"]:
  1696. if len(self.polycoords) > 0:
  1697. self.MouseDraw(pdc=self.pdcTmp, begin=self.Cell2Pixel(self.polycoords[-1]))
  1698. elif digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] \
  1699. and hasattr(self, "vdigitMove"):
  1700. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  1701. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  1702. if len(self.vdigitMove['id']) > 0:
  1703. # draw lines on new position
  1704. if digitToolbar.GetAction() == "moveLine":
  1705. # move line
  1706. for id in self.vdigitMove['id']:
  1707. self.pdcTmp.TranslateId(id, dx, dy)
  1708. elif digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  1709. # move vertex ->
  1710. # (vertex, left vertex, left line,
  1711. # right vertex, right line)
  1712. # do not draw static lines
  1713. if digitToolbar.GetAction() == "moveVertex":
  1714. self.polycoords = []
  1715. ### self.pdcTmp.TranslateId(self.vdigitMove['id'][0], dx, dy)
  1716. self.pdcTmp.RemoveId(self.vdigitMove['id'][0])
  1717. if self.vdigitMove['id'][1] > 0: # previous vertex
  1718. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][1])[0:2])
  1719. self.pdcTmp.RemoveId(self.vdigitMove['id'][1]+1)
  1720. self.polycoords.append((x, y))
  1721. ### x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][0])[0:2])
  1722. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  1723. if self.vdigitMove['id'][2] > 0: # next vertex
  1724. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][2])[0:2])
  1725. self.pdcTmp.RemoveId(self.vdigitMove['id'][2]-1)
  1726. self.polycoords.append((x, y))
  1727. self.ClearLines(pdc=self.pdcTmp)
  1728. self.DrawLines(pdc=self.pdcTmp)
  1729. else: # edit line
  1730. try:
  1731. if self.vdigitMove['id'][-1] > 0: # previous vertex
  1732. self.MouseDraw(pdc=self.pdcTmp,
  1733. begin=self.Cell2Pixel(self.polycoords[-1]))
  1734. except: # no line
  1735. self.vdigitMove['id'] = []
  1736. self.polycoords = []
  1737. self.Refresh() # TODO: use RefreshRect()
  1738. self.mouse['begin'] = self.mouse['end']
  1739. elif digitToolbar.GetAction() == "zbulkLine":
  1740. if len(self.polycoords) == 1:
  1741. # draw mouse moving
  1742. self.MouseDraw(self.pdcTmp)
  1743. event.Skip()
  1744. def ClearLines(self, pdc=None):
  1745. """
  1746. Clears temporary drawn lines from PseudoDC
  1747. """
  1748. if not pdc:
  1749. pdc=self.pdcTmp
  1750. try:
  1751. pdc.ClearId(self.lineid)
  1752. pdc.RemoveId(self.lineid)
  1753. except:
  1754. pass
  1755. try:
  1756. pdc.ClearId(self.plineid)
  1757. pdc.RemoveId(self.plineid)
  1758. except:
  1759. pass
  1760. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1761. (self.lineid, self.plineid))
  1762. ### self.Refresh()
  1763. return True
  1764. def Pixel2Cell(self, (x, y)):
  1765. """
  1766. Convert image coordinates to real word coordinates
  1767. Input : int x, int y
  1768. Output: float x, float y
  1769. """
  1770. try:
  1771. x = int(x)
  1772. y = int(y)
  1773. except:
  1774. return None
  1775. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1776. res = self.Map.region["ewres"]
  1777. else:
  1778. res = self.Map.region["nsres"]
  1779. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1780. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1781. east = w + x * res
  1782. north = n - y * res
  1783. # extent does not correspond with whole map canvas area...
  1784. # east = self.Map.region['w'] + x * self.Map.region["ewres"]
  1785. # north = self.Map.region['n'] - y * self.Map.region["nsres"]
  1786. return (east, north)
  1787. def Cell2Pixel(self, (east, north)):
  1788. """
  1789. Convert real word coordinates to image coordinates
  1790. """
  1791. try:
  1792. east = float(east)
  1793. north = float(north)
  1794. except:
  1795. return None
  1796. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1797. res = self.Map.region["ewres"]
  1798. else:
  1799. res = self.Map.region["nsres"]
  1800. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1801. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1802. # x = int((east - w) / res)
  1803. # y = int((n - north) / res)
  1804. x = (east - w) / res
  1805. y = (n - north) / res
  1806. return (x, y)
  1807. def Zoom(self, begin, end, zoomtype):
  1808. """
  1809. Calculates new region while (un)zoom/pan-ing
  1810. """
  1811. x1, y1 = begin
  1812. x2, y2 = end
  1813. newreg = {}
  1814. # threshold - too small squares do not make sense
  1815. # can only zoom to windows of > 5x5 screen pixels
  1816. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1817. if x1 > x2:
  1818. x1, x2 = x2, x1
  1819. if y1 > y2:
  1820. y1, y2 = y2, y1
  1821. # zoom in
  1822. if zoomtype > 0:
  1823. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1824. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1825. # zoom out
  1826. elif zoomtype < 0:
  1827. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1828. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1829. (self.Map.width - x2),
  1830. self.Map.height + 2 * \
  1831. (self.Map.height - y2)))
  1832. # pan
  1833. elif zoomtype == 0:
  1834. dx = x1 - x2
  1835. dy = y1 - y2
  1836. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1837. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1838. self.Map.height + dy))
  1839. # if new region has been calculated, set the values
  1840. if newreg != {}:
  1841. # LL locations
  1842. if self.parent.Map.projinfo['proj'] == 'll':
  1843. if newreg['n'] > 90.0:
  1844. newreg['n'] = 90.0
  1845. if newreg['s'] < -90.0:
  1846. newreg['s'] = -90.0
  1847. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1848. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1849. if hasattr(self, "vdigitMove"):
  1850. # xo = self.Cell2Pixel((self.Map.region['center_easting'], self.Map.region['center_northing']))
  1851. # xn = self.Cell2Pixel(ce, cn))
  1852. tmp = self.Pixel2Cell(self.mouse['end'])
  1853. # calculate new center point and display resolution
  1854. self.Map.region['center_easting'] = ce
  1855. self.Map.region['center_northing'] = cn
  1856. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  1857. self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
  1858. self.Map.AlignExtentFromDisplay()
  1859. if hasattr(self, "vdigitMove"):
  1860. tmp1 = self.mouse['end']
  1861. tmp2 = self.Cell2Pixel(self.vdigitMove['begin'])
  1862. dx = tmp1[0] - tmp2[0]
  1863. dy = tmp1[1] - tmp2[1]
  1864. self.vdigitMove['beginDiff'] = (dx, dy)
  1865. for id in self.vdigitMove['id']:
  1866. self.pdcTmp.RemoveId(id)
  1867. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1868. self.Map.region['e'], self.Map.region['w'])
  1869. if self.redrawAll is False:
  1870. self.redrawAll = True
  1871. def ZoomBack(self):
  1872. """
  1873. Zoom to previous extents in zoomhistory list
  1874. """
  1875. zoom = []
  1876. if len(self.zoomhistory) > 1:
  1877. self.zoomhistory.pop()
  1878. zoom = self.zoomhistory[len(self.zoomhistory)-1]
  1879. # (n, s, e, w)
  1880. if zoom:
  1881. # zoom to selected region
  1882. self.Map.region['center_easting'] = zoom[3] + \
  1883. (zoom[2] - zoom[3]) / 2
  1884. self.Map.region['center_northing'] = zoom[1] + \
  1885. (zoom[0] - zoom[1]) / 2
  1886. self.Map.region["ewres"] = (zoom[2] - zoom[3]) / self.Map.width
  1887. self.Map.region["nsres"] = (zoom[0] - zoom[1]) / self.Map.height
  1888. self.Map.AlignExtentFromDisplay()
  1889. # update map
  1890. self.UpdateMap()
  1891. # update statusbar
  1892. self.parent.StatusbarUpdate()
  1893. def ZoomHistory(self, n, s, e, w):
  1894. """
  1895. Manages a list of last 10 zoom extents
  1896. Return removed history item if exists
  1897. """
  1898. removed = None
  1899. self.zoomhistory.append((n,s,e,w))
  1900. if len(self.zoomhistory) > 10:
  1901. removed = self.zoomhistory.pop(0)
  1902. if removed:
  1903. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1904. (self.zoomhistory, removed))
  1905. else:
  1906. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1907. (self.zoomhistory))
  1908. return removed
  1909. def OnZoomToMap(self, event):
  1910. """
  1911. Set display extents to match selected raster (including NULLs)
  1912. or vector map.
  1913. """
  1914. self.ZoomToMap()
  1915. def OnZoomToRaster(self, event):
  1916. """
  1917. Set display extents to match selected raster map (ignore NULLs)
  1918. """
  1919. self.ZoomToMap(zoom=True)
  1920. def ZoomToMap(self, layer=None, zoom=False):
  1921. """
  1922. Set display extents to match selected raster
  1923. or vector map.
  1924. """
  1925. zoomreg = {}
  1926. if not layer:
  1927. layer = self.GetSelectedLayer()
  1928. if layer is None:
  1929. return
  1930. Debug.msg (3, "BufferedWindow.ZoomToMap(): layer=%s, type=%s" % \
  1931. (layer.name, layer.type))
  1932. # selected layer must be a valid map
  1933. if layer.type in ('raster', 'rgb', 'his', 'shaded', 'arrow'):
  1934. if layer.type == 'raster':
  1935. self.Map.region = self.Map.GetRegion(rast="%s" % layer.name)
  1936. else:
  1937. self.Map.region = self.Map.GetRegion(rast="%s" % layer.name)
  1938. elif layer.type in ('vector', 'thememap', 'themechart'):
  1939. if self.parent.digit and layer.name == self.parent.digit.map and \
  1940. self.parent.digit.type == 'vdigit':
  1941. w, s, b, e, n, t = self.parent.digit.driver.GetMapBoundingBox()
  1942. self.Map.region = self.Map.GetRegion(n=n, s=s, w=w, e=e)
  1943. else:
  1944. self.Map.region = self.Map.GetRegion(vect="%s" % layer.name)
  1945. else:
  1946. return
  1947. ### self.Map.SetRegion()
  1948. ### self.Map.AlignExtentFromDisplay()
  1949. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1950. self.Map.region['e'], self.Map.region['w'])
  1951. self.UpdateMap()
  1952. self.parent.StatusbarUpdate()
  1953. def ZoomToWind(self, event):
  1954. """
  1955. Set display geometry to match computational
  1956. region settings (set with g.region)
  1957. """
  1958. self.Map.region = self.Map.GetRegion()
  1959. ### self.Map.SetRegion(windres=True)
  1960. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1961. self.Map.region['e'], self.Map.region['w'])
  1962. self.UpdateMap()
  1963. self.parent.StatusbarUpdate()
  1964. def ZoomToDefault(self, event):
  1965. """
  1966. Set display geometry to match default region settings
  1967. """
  1968. self.Map.region = self.Map.GetRegion(default=True)
  1969. self.Map.AdjustRegion() # aling region extent to the display
  1970. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1971. self.Map.region['e'], self.Map.region['w'])
  1972. self.UpdateMap()
  1973. self.parent.StatusbarUpdate()
  1974. def DisplayToWind(self, event):
  1975. """
  1976. Set computational region (WIND file) to
  1977. match display extents
  1978. """
  1979. tmpreg = os.getenv("GRASS_REGION")
  1980. if tmpreg:
  1981. del os.environ["GRASS_REGION"]
  1982. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1983. # for user to set explicitly with g.region
  1984. new = self.Map.AlignResolution()
  1985. cmdRegion = ["g.region", "--o",
  1986. "n=%f" % new['n'],
  1987. "s=%f" % new['s'],
  1988. "e=%f" % new['e'],
  1989. "w=%f" % new['w'],
  1990. "rows=%d" % int(new['rows']),
  1991. "cols=%d" % int(new['cols'])]
  1992. p = gcmd.Command(cmdRegion)
  1993. if tmpreg:
  1994. os.environ["GRASS_REGION"] = tmpreg
  1995. def ZoomToSaved(self, event):
  1996. """
  1997. Set display geometry to match extents in
  1998. saved region file
  1999. """
  2000. zoomreg = {}
  2001. dlg = gdialogs.SavedRegion(self, wx.ID_ANY, _("Zoom to saved region extents"),
  2002. pos=wx.DefaultPosition, size=wx.DefaultSize,
  2003. style=wx.DEFAULT_DIALOG_STYLE,
  2004. loadsave='load')
  2005. if dlg.ShowModal() == wx.ID_CANCEL:
  2006. dlg.Destroy()
  2007. return
  2008. wind = dlg.wind
  2009. p = gcmd.Command (["g.region", "-ugp", "region=%s" % wind])
  2010. if p.returncode == 0:
  2011. output = p.ReadStdOutput()
  2012. for line in output:
  2013. line = line.strip()
  2014. if '=' in line: key,val = line.split('=')
  2015. zoomreg[key] = float(val)
  2016. self.Map.region['n'] = zoomreg['n']
  2017. self.Map.region['s'] = zoomreg['s']
  2018. self.Map.region['e'] = zoomreg['e']
  2019. self.Map.region['w'] = zoomreg['w']
  2020. self.ZoomHistory(self.Map.region['n'],self.Map.region['s'],self.Map.region['e'],self.Map.region['w'])
  2021. self.UpdateMap()
  2022. dlg.Destroy()
  2023. def SaveDisplayRegion(self, event):
  2024. """
  2025. Save display extents to named region file.
  2026. """
  2027. dlg = gdialogs.SavedRegion(self, wx.ID_ANY, "Save display extents to region file",
  2028. pos=wx.DefaultPosition, size=wx.DefaultSize,
  2029. style=wx.DEFAULT_DIALOG_STYLE,
  2030. loadsave='save')
  2031. if dlg.ShowModal() == wx.ID_CANCEL:
  2032. dlg.Destroy()
  2033. return
  2034. wind = dlg.wind
  2035. # test to see if it already exists and ask permission to overwrite
  2036. windpath = os.path.join(self.Map.env["GISDBASE"], self.Map.env["LOCATION_NAME"],
  2037. self.Map.env["MAPSET"],"windows",wind)
  2038. if windpath and not os.path.exists(windpath):
  2039. self.SaveRegion(wind)
  2040. elif windpath and os.path.exists(windpath):
  2041. overwrite = wx.MessageBox(_("Region file <%s> already exists. "
  2042. "Do you want to overwrite it?") % (wind),
  2043. _("Warning"), wx.YES_NO)
  2044. if (overwrite == wx.YES):
  2045. self.SaveRegion(wind)
  2046. else:
  2047. pass
  2048. dlg.Destroy()
  2049. def SaveRegion(self, wind):
  2050. """
  2051. Save region settings
  2052. """
  2053. new = self.Map.AlignResolution()
  2054. cmdRegion = ["g.region",
  2055. "-u",
  2056. "n=%f" % new['n'],
  2057. "s=%f" % new['s'],
  2058. "e=%f" % new['e'],
  2059. "w=%f" % new['w'],
  2060. "rows=%d" % new['rows'],
  2061. "cols=%d" % new['cols'],
  2062. "save=%s" % wind,
  2063. "--o"]
  2064. tmpreg = os.getenv("GRASS_REGION")
  2065. if tmpreg:
  2066. del os.environ["GRASS_REGION"]
  2067. p = gcmd.Command(cmdRegion)
  2068. if tmpreg:
  2069. os.environ["GRASS_REGION"] = tmpreg
  2070. def Distance(self, beginpt, endpt, screen=True):
  2071. """Calculete distance
  2072. LL-locations not supported
  2073. @todo Use m.distance
  2074. @param beginpt first point
  2075. @param endpt second point
  2076. @param screen True for screen coordinates otherwise EN
  2077. """
  2078. x1, y1 = beginpt
  2079. x2, y2 = endpt
  2080. if screen:
  2081. dEast = (x2 - x1) * self.Map.region["ewres"]
  2082. dNorth = (y2 - y1) * self.Map.region["nsres"]
  2083. else:
  2084. dEast = (x2 - x1)
  2085. dNorth = (y2 - y1)
  2086. return (math.sqrt(math.pow((dEast),2) + math.pow((dNorth),2)), (dEast, dNorth))
  2087. class MapFrame(wx.Frame):
  2088. """
  2089. Main frame for map display window. Drawing takes place in child double buffered
  2090. drawing window.
  2091. """
  2092. def __init__(self, parent=None, id=wx.ID_ANY, title=_("GRASS GIS - Map display"),
  2093. pos=wx.DefaultPosition, size=wx.DefaultSize,
  2094. style=wx.DEFAULT_FRAME_STYLE, toolbars=["map"],
  2095. tree=None, notebook=None, gismgr=None, page=None,
  2096. Map=None, auimgr=None):
  2097. """
  2098. Main map display window with toolbars, statusbar and
  2099. DrawWindow
  2100. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  2101. @param tree reference to layer tree
  2102. @param notebook control book ID in Layer Manager
  2103. @param gismgr Layer Manager panel
  2104. @param page notebook page with layer tree
  2105. @param Map instance of render.Map
  2106. """
  2107. self.gismanager = gismgr # GIS Manager object
  2108. self.Map = Map # instance of render.Map
  2109. self.tree = tree # GIS Manager layer tree object
  2110. self.page = page # Notebook page holding the layer tree
  2111. self.layerbook = notebook # GIS Manager layer tree notebook
  2112. self.parent = parent
  2113. #
  2114. # available cursors
  2115. #
  2116. self.cursors = {
  2117. # default: cross
  2118. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  2119. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  2120. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  2121. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  2122. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  2123. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  2124. }
  2125. wx.Frame.__init__(self, parent, id, title, pos, size, style)
  2126. self.SetName("MapWindow")
  2127. #
  2128. # set the size & system icon
  2129. #
  2130. self.SetClientSize(size)
  2131. self.iconsize = (16, 16)
  2132. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  2133. #
  2134. # Fancy gui
  2135. #
  2136. # self._mgr = auimgr
  2137. self._mgr = wx.aui.AuiManager(self)
  2138. #
  2139. # Add toolbars
  2140. #
  2141. self.toolbars = { 'map' : None,
  2142. 'vdigit' : None,
  2143. 'georect' : None,
  2144. 'nviz' : None }
  2145. for toolb in toolbars:
  2146. self.AddToolbar(toolb)
  2147. #
  2148. # Add statusbar
  2149. #
  2150. self.statusbar = self.CreateStatusBar(number=3, style=0)
  2151. self.statusbar.SetStatusWidths([-5, -2, -1])
  2152. self.toggleStatus = wx.Choice(self.statusbar, wx.ID_ANY,
  2153. choices = globalvar.MAP_DISPLAY_STATUSBAR_MODE)
  2154. self.toggleStatus.SetSelection(UserSettings.Get(group='display', key='statusbarMode', subkey='selection'))
  2155. self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus, self.toggleStatus)
  2156. # auto-rendering checkbox
  2157. self.autoRender = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  2158. label=_("Render"))
  2159. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender, self.autoRender)
  2160. self.autoRender.SetValue(UserSettings.Get(group='display', key='autoRendering', subkey='enabled'))
  2161. self.autoRender.SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  2162. # show region
  2163. self.showRegion = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  2164. label=_("Show computational extent"))
  2165. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion, self.showRegion)
  2166. self.showRegion.SetValue(False)
  2167. self.showRegion.Hide()
  2168. self.showRegion.SetToolTip(wx.ToolTip (_("Show/hide computational "
  2169. "region extent (set with g.region). "
  2170. "Display region drawn as a blue box inside the "
  2171. "computational region, "
  2172. "computational region inside a display region "
  2173. "as a red box).")))
  2174. # set resolution
  2175. self.compResolution = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  2176. label=_("Constrain display resolution to computational settings"))
  2177. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution, self.compResolution)
  2178. self.compResolution.SetValue(UserSettings.Get(group='display', key='compResolution', subkey='enabled'))
  2179. self.compResolution.Hide()
  2180. self.compResolution.SetToolTip(wx.ToolTip (_("Constrain display resolution "
  2181. "to computational region settings. "
  2182. "Default value for new map displays can "
  2183. "be set up in 'User GUI settings' dialog.")))
  2184. # map scale
  2185. self.mapScale = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
  2186. value="", style=wx.TE_PROCESS_ENTER,
  2187. size=(150, -1))
  2188. self.mapScale.Hide()
  2189. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale, self.mapScale)
  2190. # on-render gauge
  2191. self.onRenderGauge = wx.Gauge(parent=self.statusbar, id=wx.ID_ANY,
  2192. range=0, style=wx.GA_HORIZONTAL)
  2193. self.onRenderGauge.Hide()
  2194. self.StatusbarReposition() # reposition statusbar
  2195. #
  2196. # Init map display (buffered DC & set default cursor)
  2197. #
  2198. self.MapWindow2D = BufferedWindow(self, id=wx.ID_ANY,
  2199. Map=self.Map, tree=self.tree, gismgr=self.gismanager)
  2200. # default is 2D display mode
  2201. self.MapWindow = self.MapWindow2D
  2202. self.MapWindow.Bind(wx.EVT_MOTION, self.OnMotion)
  2203. self.MapWindow.SetCursor(self.cursors["default"])
  2204. # used by Nviz (3D display mode)
  2205. self.MapWindow3D = None
  2206. #
  2207. # initialize region values
  2208. #
  2209. self.__InitDisplay()
  2210. #
  2211. # Bind various events
  2212. #
  2213. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  2214. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  2215. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  2216. #
  2217. # Update fancy gui style
  2218. #
  2219. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  2220. Dockable(False).BestSize((-1,-1)).
  2221. CloseButton(False).DestroyOnClose(True).
  2222. Layer(0))
  2223. self._mgr.Update()
  2224. #
  2225. # Init print module and classes
  2226. #
  2227. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  2228. #
  2229. # Initialization of digitization tool
  2230. #
  2231. self.digit = None
  2232. #
  2233. # Init zoom history
  2234. #
  2235. self.MapWindow.ZoomHistory(self.Map.region['n'],
  2236. self.Map.region['s'],
  2237. self.Map.region['e'],
  2238. self.Map.region['w'])
  2239. #
  2240. # Re-use dialogs
  2241. #
  2242. self.dialogs = {}
  2243. self.dialogs['attributes'] = None
  2244. self.dialogs['category'] = None
  2245. self.dialogs['barscale'] = None
  2246. self.dialogs['legend'] = None
  2247. self.decorationDialog = None # decoration/overlays
  2248. def AddToolbar(self, name):
  2249. """
  2250. Add defined toolbar to the window
  2251. Currently known toolbars are:
  2252. - map basic map toolbar
  2253. - digit vector digitizer
  2254. - georect georectifier
  2255. """
  2256. # default toolbar
  2257. if name == "map":
  2258. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  2259. self._mgr.AddPane(self.toolbars['map'].toolbar,
  2260. wx.aui.AuiPaneInfo().
  2261. Name("maptoolbar").Caption(_("Map Toolbar")).
  2262. ToolbarPane().Top().
  2263. LeftDockable(False).RightDockable(False).
  2264. BottomDockable(False).TopDockable(True).
  2265. CloseButton(False).Layer(2))
  2266. # vector digitizer
  2267. elif name == "vdigit":
  2268. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent=self, map=self.Map,
  2269. layerTree=self.tree,
  2270. log=self.gismanager.goutput)
  2271. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  2272. self._mgr.AddPane(self.toolbars['vdigit'].toolbar[toolRow],
  2273. wx.aui.AuiPaneInfo().
  2274. Name("vdigittoolbar" + str(toolRow)).Caption(_("Vector digitizer toolbar")).
  2275. ToolbarPane().Top().Row(toolRow + 1).
  2276. LeftDockable(False).RightDockable(False).
  2277. BottomDockable(False).TopDockable(True).
  2278. CloseButton(False).Layer(2))
  2279. # change mouse to draw digitized line
  2280. self.MapWindow.mouse['box'] = "point"
  2281. self.MapWindow.zoomtype = 0
  2282. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SOLID)
  2283. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SOLID)
  2284. # georectifier
  2285. elif name == "georect":
  2286. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  2287. self._mgr.AddPane(self.toolbars['georect'].toolbar,
  2288. wx.aui.AuiPaneInfo().
  2289. Name("georecttoolbar").Caption(_("Georectification toolbar")).
  2290. ToolbarPane().Top().
  2291. LeftDockable(False).RightDockable(False).
  2292. BottomDockable(False).TopDockable(True).
  2293. CloseButton(False).Layer(2))
  2294. # nviz
  2295. elif name == "nviz":
  2296. import nviz
  2297. # check for GLCanvas and OpenGL
  2298. msg = None
  2299. if not nviz.haveGLCanvas:
  2300. msg = _("Unable to start Nviz. The GLCanvas class has not been "
  2301. "included with this build "
  2302. "of wxPython! Switching back to "
  2303. "2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  2304. if not nviz.haveNviz:
  2305. msg = _("Unable to start Nviz. Python extension "
  2306. "for Nviz was not found or loaded properly. "
  2307. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg)
  2308. if msg:
  2309. wx.MessageBox(parent=self,
  2310. message=msg,
  2311. caption=_("Error"))
  2312. return
  2313. #
  2314. # add Nviz toolbar and disable 2D display mode tools
  2315. #
  2316. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  2317. self.toolbars['map'].Enable2D(False)
  2318. #
  2319. # update layer tree (-> enable 3d-rasters)
  2320. #
  2321. self.tree.EnableItemType(type='3d-raster', enable=True)
  2322. #
  2323. # update status bar
  2324. #
  2325. self.toggleStatus.Enable(False)
  2326. #
  2327. # erase map window
  2328. #
  2329. self.MapWindow.EraseMap()
  2330. busy = wx.BusyInfo(message=_("Please wait, loading data..."),
  2331. parent=self)
  2332. wx.Yield()
  2333. #
  2334. # create GL window & NVIZ toolbar
  2335. #
  2336. if not self.MapWindow3D:
  2337. self.MapWindow3D = nviz.GLWindow(self, id=wx.ID_ANY,
  2338. Map=self.Map, tree=self.tree, gismgr=self.gismanager)
  2339. self.nvizToolWin = nviz.NvizToolWindow(self, id=wx.ID_ANY,
  2340. mapWindow=self.MapWindow3D)
  2341. self.MapWindow3D.OnPaint(None) # -> LoadData
  2342. busy.Destroy()
  2343. self.nvizToolWin.Show()
  2344. #
  2345. # switch from MapWindow to MapWindowGL
  2346. # add nviz toolbar
  2347. #
  2348. self._mgr.DetachPane(self.MapWindow2D)
  2349. self.MapWindow2D.Hide()
  2350. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  2351. Dockable(False).BestSize((-1,-1)).
  2352. CloseButton(False).DestroyOnClose(True).
  2353. Layer(0))
  2354. self._mgr.AddPane(self.toolbars['nviz'].toolbar,
  2355. wx.aui.AuiPaneInfo().
  2356. Name("nviztoolbar").Caption(_("Nviz toolbar")).
  2357. ToolbarPane().Top().Row(1).
  2358. LeftDockable(False).RightDockable(False).
  2359. BottomDockable(False).TopDockable(True).
  2360. CloseButton(False).Layer(2))
  2361. self.MapWindow = self.MapWindow3D
  2362. self.SetStatusText("", 0)
  2363. self._mgr.Update()
  2364. def RemoveToolbar (self, name):
  2365. """
  2366. Removes toolbar from the window
  2367. TODO: Only hide, activate by calling AddToolbar()
  2368. """
  2369. # cannot hide main toolbar
  2370. if name == "map":
  2371. return
  2372. elif name == "vdigit":
  2373. # TODO: not destroy only hide
  2374. for toolRow in range(0, self.toolbars['vdigit'].numOfRows):
  2375. self._mgr.DetachPane (self.toolbars['vdigit'].toolbar[toolRow])
  2376. self.toolbars['vdigit'].toolbar[toolRow].Destroy()
  2377. else:
  2378. self._mgr.DetachPane (self.toolbars[name].toolbar)
  2379. self.toolbars[name].toolbar.Destroy()
  2380. self.toolbars[name] = None
  2381. if name == 'nviz':
  2382. # hide nviz tools
  2383. self.nvizToolWin.Hide()
  2384. # unload data
  2385. self.MapWindow3D.Reset()
  2386. # switch from MapWindowGL to MapWindow
  2387. self._mgr.DetachPane(self.MapWindow3D)
  2388. self.MapWindow3D.Hide()
  2389. self.MapWindow2D.Show()
  2390. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  2391. Dockable(False).BestSize((-1,-1)).
  2392. CloseButton(False).DestroyOnClose(True).
  2393. Layer(0))
  2394. self.MapWindow = self.MapWindow2D
  2395. #
  2396. # update layer tree (-> disable 3d-rasters)
  2397. #
  2398. self.tree.EnableItemType(type='3d-raster', enable=False)
  2399. self.toolbars['map'].combo.SetValue ("Tools")
  2400. self.toolbars['map'].Enable2D(True)
  2401. self.toggleStatus.Enable(True)
  2402. self._mgr.Update()
  2403. def __InitDisplay(self):
  2404. """
  2405. Initialize map display, set dimensions and map region
  2406. """
  2407. self.width, self.height = self.GetClientSize()
  2408. Debug.msg(2, "MapFrame.__InitDisplay():")
  2409. self.Map.ChangeMapSize(self.GetClientSize())
  2410. self.Map.region = self.Map.GetRegion() # g.region -upgc
  2411. # self.Map.SetRegion() # adjust region to match display window
  2412. def OnUpdateProgress(self, event):
  2413. """
  2414. Update progress bar info
  2415. """
  2416. self.onRenderGauge.SetValue(event.value)
  2417. event.Skip()
  2418. def OnFocus(self, event):
  2419. """
  2420. Change choicebook page to match display.
  2421. Or set display for georectifying
  2422. """
  2423. if self.gismanager.georectifying:
  2424. # in georectifying session; display used to get get geographic
  2425. # coordinates for GCPs
  2426. self.OnPointer(event)
  2427. else:
  2428. # change bookcontrol page to page associated with display
  2429. if self.page:
  2430. pgnum = self.layerbook.GetPageIndex(self.page)
  2431. if pgnum > -1:
  2432. self.layerbook.SetSelection(pgnum)
  2433. event.Skip()
  2434. def OnMotion(self, event):
  2435. """
  2436. Mouse moved
  2437. Track mouse motion and update status bar
  2438. """
  2439. # update statusbar if required
  2440. if self.toggleStatus.GetSelection() == 0: # Coordinates
  2441. e, n = self.MapWindow.Pixel2Cell(event.GetPositionTuple())
  2442. if self.toolbars['vdigit'] and \
  2443. self.toolbars['vdigit'].GetAction() == 'addLine' and \
  2444. self.toolbars['vdigit'].GetAction('type') in ('line', 'boundary') and \
  2445. len(self.MapWindow.polycoords) > 0:
  2446. # for linear feature show segment and total length
  2447. distance_seg = self.MapWindow.Distance(self.MapWindow.polycoords[-1],
  2448. (e, n), screen=False)[0]
  2449. distance_tot = distance_seg
  2450. for idx in range(1, len(self.MapWindow.polycoords)):
  2451. distance_tot += self.MapWindow.Distance(self.MapWindow.polycoords[idx-1],
  2452. self.MapWindow.polycoords[idx],
  2453. screen=False )[0]
  2454. self.statusbar.SetStatusText("%.2f, %.2f (seg: %.2f; tot: %.2f)" % \
  2455. (e, n, distance_seg, distance_tot), 0)
  2456. else:
  2457. if self.Map.projinfo['proj'] == 'll':
  2458. self.statusbar.SetStatusText("%s" % utils.Deg2DMS(e, n), 0)
  2459. else:
  2460. self.statusbar.SetStatusText("%.2f, %.2f" % (e, n), 0)
  2461. event.Skip()
  2462. def OnDraw(self, event):
  2463. """
  2464. Re-display current map composition
  2465. """
  2466. self.MapWindow.UpdateMap(render=False)
  2467. def OnRender(self, event):
  2468. """
  2469. Re-render map composition (each map layer)
  2470. """
  2471. # delete tmp map layers (queries)
  2472. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
  2473. for layer in qlayer:
  2474. self.Map.DeleteLayer(layer)
  2475. # delete tmp lines
  2476. if self.MapWindow.mouse["use"] in ["measure", "profile"]:
  2477. self.MapWindow.polycoords = []
  2478. self.MapWindow.ClearLines()
  2479. # deselect features in vdigit
  2480. if self.toolbars['vdigit'] and self.digit:
  2481. self.digit.driver.SetSelected([])
  2482. self.MapWindow.UpdateMap(render=True, renderVector=True)
  2483. else:
  2484. self.MapWindow.UpdateMap(render=True)
  2485. # update statusbar
  2486. self.StatusbarUpdate()
  2487. def OnPointer(self, event):
  2488. """
  2489. Pointer button clicked
  2490. """
  2491. if self.toolbars['map']:
  2492. if event:
  2493. self.toolbars['map'].OnTool(event)
  2494. self.toolbars['map'].action['desc'] = ''
  2495. self.MapWindow.mouse['use'] = "pointer"
  2496. self.MapWindow.mouse['box'] = "point"
  2497. # change the cursor
  2498. if self.toolbars['vdigit']:
  2499. # digitization tool activated
  2500. self.MapWindow.SetCursor(self.cursors["cross"])
  2501. # reset mouse['box'] if needed
  2502. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  2503. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  2504. self.MapWindow.mouse['box'] = 'point'
  2505. else: # line, boundary
  2506. self.MapWindow.mouse['box'] = 'line'
  2507. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  2508. 'editLine', 'displayCats', 'displayAttrs',
  2509. 'copyCats']:
  2510. self.MapWindow.mouse['box'] = 'point'
  2511. else: # moveLine, deleteLine
  2512. self.MapWindow.mouse['box'] = 'box'
  2513. elif self.gismanager.georectifying:
  2514. self.MapWindow.SetCursor(self.cursors["cross"])
  2515. else:
  2516. self.MapWindow.SetCursor(self.cursors["default"])
  2517. def OnZoomIn(self, event):
  2518. """
  2519. Zoom in the map.
  2520. Set mouse cursor, zoombox attributes, and zoom direction
  2521. """
  2522. if self.toolbars['map']:
  2523. self.toolbars['map'].OnTool(event)
  2524. self.toolbars['map'].action['desc'] = ''
  2525. self.MapWindow.mouse['use'] = "zoom"
  2526. self.MapWindow.mouse['box'] = "box"
  2527. self.MapWindow.zoomtype = 1
  2528. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  2529. # change the cursor
  2530. self.MapWindow.SetCursor(self.cursors["cross"])
  2531. def OnZoomOut(self, event):
  2532. """
  2533. Zoom out the map.
  2534. Set mouse cursor, zoombox attributes, and zoom direction
  2535. """
  2536. if self.toolbars['map']:
  2537. self.toolbars['map'].OnTool(event)
  2538. self.toolbars['map'].action['desc'] = ''
  2539. self.MapWindow.mouse['use'] = "zoom"
  2540. self.MapWindow.mouse['box'] = "box"
  2541. self.MapWindow.zoomtype = -1
  2542. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  2543. # change the cursor
  2544. self.MapWindow.SetCursor(self.cursors["cross"])
  2545. def OnZoomBack(self, event):
  2546. """
  2547. Zoom last (previously stored position)
  2548. """
  2549. self.MapWindow.ZoomBack()
  2550. def OnPan(self, event):
  2551. """
  2552. Panning, set mouse to drag
  2553. """
  2554. if self.toolbars['map']:
  2555. self.toolbars['map'].OnTool(event)
  2556. self.toolbars['map'].action['desc'] = ''
  2557. self.MapWindow.mouse['use'] = "pan"
  2558. self.MapWindow.mouse['box'] = "pan"
  2559. self.MapWindow.zoomtype = 0
  2560. # change the cursor
  2561. self.MapWindow.SetCursor(self.cursors["hand"])
  2562. def OnErase(self, event):
  2563. """
  2564. Erase the canvas
  2565. """
  2566. self.MapWindow.EraseMap()
  2567. def OnZoomRegion(self, event):
  2568. """
  2569. Zoom to region
  2570. """
  2571. self.Map.getRegion()
  2572. self.Map.getResolution()
  2573. self.UpdateMap()
  2574. # event.Skip()
  2575. def OnAlignRegion(self, event):
  2576. """
  2577. Align region
  2578. """
  2579. if not self.Map.alignRegion:
  2580. self.Map.alignRegion = True
  2581. else:
  2582. self.Map.alignRegion = False
  2583. # event.Skip()
  2584. def OnToggleRender(self, event):
  2585. """
  2586. Enable/disable auto-rendering
  2587. """
  2588. if self.autoRender.GetValue():
  2589. self.OnRender(None)
  2590. def OnToggleShowRegion(self, event):
  2591. """
  2592. Show/Hide extent in map canvas
  2593. """
  2594. if self.showRegion.GetValue():
  2595. # show extent
  2596. self.MapWindow.regionCoords = []
  2597. else:
  2598. del self.MapWindow.regionCoords
  2599. # redraw map if auto-rendering is enabled
  2600. if self.autoRender.GetValue():
  2601. self.OnRender(None)
  2602. def OnToggleResolution(self, event):
  2603. """
  2604. Use resolution of computation region settings
  2605. for redering image instead of display resolution
  2606. """
  2607. # redraw map if auto-rendering is enabled
  2608. if self.autoRender.GetValue():
  2609. self.OnRender(None)
  2610. def OnToggleStatus(self, event):
  2611. """
  2612. Toggle status text
  2613. """
  2614. self.StatusbarUpdate()
  2615. def OnChangeMapScale(self, event):
  2616. """
  2617. Map scale changed by user
  2618. """
  2619. scale = event.GetString()
  2620. try:
  2621. if scale[:2] != '1:':
  2622. raise ValueError
  2623. value = int(scale[2:])
  2624. except ValueError:
  2625. self.mapScale.SetValue('1:%ld' % int(self.mapScaleValue))
  2626. return
  2627. dEW = value * (self.Map.region['cols'] / self.ppm[0])
  2628. dNS = value * (self.Map.region['rows'] / self.ppm[1])
  2629. self.Map.region['n'] = self.Map.region['center_northing'] + dNS / 2.
  2630. self.Map.region['s'] = self.Map.region['center_northing'] - dNS / 2.
  2631. self.Map.region['w'] = self.Map.region['center_easting'] - dEW / 2.
  2632. self.Map.region['e'] = self.Map.region['center_easting'] + dEW / 2.
  2633. # add to zoom history
  2634. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2635. self.Map.region['e'], self.Map.region['w'])
  2636. # redraw a map
  2637. self.MapWindow.UpdateMap()
  2638. self.mapScale.SetFocus()
  2639. def StatusbarUpdate(self):
  2640. """Update statusbar content"""
  2641. self.showRegion.Hide()
  2642. self.compResolution.Hide()
  2643. self.mapScale.Hide()
  2644. self.mapScaleValue = self.ppm = None
  2645. if self.toggleStatus.GetSelection() == 0: # Coordinates
  2646. self.statusbar.SetStatusText("", 0)
  2647. # enable long help
  2648. self.StatusbarEnableLongHelp()
  2649. elif self.toggleStatus.GetSelection() == 1: # Extent
  2650. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f" %
  2651. (self.Map.region["w"], self.Map.region["e"],
  2652. self.Map.region["s"], self.Map.region["n"]), 0)
  2653. # enable long help
  2654. self.StatusbarEnableLongHelp()
  2655. elif self.toggleStatus.GetSelection() == 2: # Comp. region
  2656. compregion = self.Map.GetRegion()
  2657. self.statusbar.SetStatusText("%.2f - %.2f, %.2f - %.2f (%.2f, %.2f)" %
  2658. (compregion["w"], compregion["e"],
  2659. compregion["s"], compregion["n"],
  2660. compregion["ewres"], compregion["nsres"]), 0)
  2661. # enable long help
  2662. self.StatusbarEnableLongHelp()
  2663. elif self.toggleStatus.GetSelection() == 3: # Show comp. extent
  2664. self.statusbar.SetStatusText("", 0)
  2665. self.showRegion.Show()
  2666. # disable long help
  2667. self.StatusbarEnableLongHelp(False)
  2668. elif self.toggleStatus.GetSelection() == 4: # Display mode
  2669. self.statusbar.SetStatusText("", 0)
  2670. self.compResolution.Show()
  2671. # disable long help
  2672. self.StatusbarEnableLongHelp(False)
  2673. elif self.toggleStatus.GetSelection() == 5: # Display geometry
  2674. self.statusbar.SetStatusText("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
  2675. (self.Map.region["rows"], self.Map.region["cols"],
  2676. self.Map.region["nsres"], self.Map.region["ewres"]), 0)
  2677. # enable long help
  2678. self.StatusbarEnableLongHelp()
  2679. elif self.toggleStatus.GetSelection() == 6: # Map scale
  2680. # TODO: need to be fixed...
  2681. ### screen X region problem
  2682. ### user should specify ppm
  2683. dc = wx.ScreenDC()
  2684. dpSizePx = wx.DisplaySize() # display size in pixels
  2685. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  2686. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  2687. sysPpi = dc.GetPPI()
  2688. comPpi = (dpSizePx[0] / dpSizeIn[0],
  2689. dpSizePx[1] / dpSizeIn[1])
  2690. ppi = comPpi # pixel per inch
  2691. self.ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  2692. (ppi[1] / 2.54) * 100)
  2693. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): size: px=%d,%d mm=%f,%f "
  2694. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  2695. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  2696. dpSizeIn[0], dpSizeIn[1],
  2697. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  2698. self.ppm[0], self.ppm[1]))
  2699. region = self.Map.region
  2700. heightCm = region['rows'] / self.ppm[1] * 100
  2701. widthCm = region['cols'] / self.ppm[0] * 100
  2702. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): width_cm=%f, height_cm=%f" %
  2703. (widthCm, heightCm))
  2704. xscale = (region['e'] - region['w']) / (region['cols'] / self.ppm[0])
  2705. yscale = (region['n'] - region['s']) / (region['rows'] / self.ppm[1])
  2706. scale = (xscale + yscale) / 2.
  2707. Debug.msg(3, "MapFrame.StatusbarUpdate(mapscale): xscale=%f, yscale=%f -> scale=%f" % \
  2708. (xscale, yscale, scale))
  2709. self.statusbar.SetStatusText("")
  2710. try:
  2711. self.mapScale.SetValue("1:%ld" % (scale + 0.5))
  2712. except TypeError:
  2713. pass
  2714. self.mapScaleValue = scale
  2715. self.mapScale.Show()
  2716. # disable long help
  2717. self.StatusbarEnableLongHelp(False)
  2718. else:
  2719. self.statusbar.SetStatusText("", 1)
  2720. def StatusbarEnableLongHelp(self, enable=True):
  2721. """Enable/disable toolbars long help"""
  2722. for toolbar in self.toolbars.itervalues():
  2723. if toolbar:
  2724. toolbar.EnableLongHelp(enable)
  2725. def StatusbarReposition(self):
  2726. """Reposition checkbox in statusbar"""
  2727. # reposition checkbox
  2728. widgets = [(0, self.showRegion),
  2729. (0, self.compResolution),
  2730. (0, self.mapScale),
  2731. (0, self.onRenderGauge),
  2732. (1, self.toggleStatus),
  2733. (2, self.autoRender)]
  2734. for idx, win in widgets:
  2735. rect = self.statusbar.GetFieldRect(idx)
  2736. if idx == 0: # show region / mapscale / process bar
  2737. # -> size
  2738. wWin, hWin = win.GetBestSize()
  2739. if win == self.onRenderGauge:
  2740. wWin = rect.width - 6
  2741. # -> position
  2742. # if win == self.showRegion:
  2743. # x, y = rect.x + rect.width - wWin, rect.y - 1
  2744. # align left
  2745. # else:
  2746. x, y = rect.x + 3, rect.y - 1
  2747. w, h = wWin, rect.height + 2
  2748. else: # choice || auto-rendering
  2749. x, y = rect.x, rect.y - 1
  2750. w, h = rect.width, rect.height + 2
  2751. if idx == 2:
  2752. x += 5
  2753. win.SetPosition((x, y))
  2754. win.SetSize((w, h))
  2755. def SaveToFile(self, event):
  2756. """
  2757. Save image to file
  2758. """
  2759. filetype = "PNG file (*.png)|*.png|"\
  2760. "TIF file (*.tif)|*.tif|"\
  2761. "GIF file (*.gif)|*.gif"
  2762. dlg = wx.FileDialog(self, "Choose a file name to save the image as a PNG to",
  2763. defaultDir = "",
  2764. defaultFile = "",
  2765. wildcard = filetype,
  2766. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  2767. if dlg.ShowModal() == wx.ID_OK:
  2768. base = os.path.splitext(dlg.GetPath())[0]
  2769. ext = os.path.splitext(dlg.GetPath())[1]
  2770. if dlg.GetFilterIndex() == 0:
  2771. type = wx.BITMAP_TYPE_PNG
  2772. path = dlg.GetPath()
  2773. if ext != '.png': path = base+'.png'
  2774. elif dlg.GetFilterIndex() == 1:
  2775. type = wx.BITMAP_TYPE_TIF
  2776. if ext != '.tif': path = base+'.tif'
  2777. elif dlg.GetFilterIndex() == 2:
  2778. type = wx.BITMAP_TYPE_TIF
  2779. if ext != '.gif': path = base+'.gif'
  2780. self.MapWindow.SaveToFile(path, type)
  2781. dlg.Destroy()
  2782. def PrintMenu(self, event):
  2783. """
  2784. Print options and output menu for map display
  2785. """
  2786. point = wx.GetMousePosition()
  2787. printmenu = wx.Menu()
  2788. # Add items to the menu
  2789. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  2790. printmenu.AppendItem(setup)
  2791. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  2792. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  2793. printmenu.AppendItem(preview)
  2794. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  2795. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  2796. printmenu.AppendItem(doprint)
  2797. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  2798. # Popup the menu. If an item is selected then its handler
  2799. # will be called before PopupMenu returns.
  2800. self.PopupMenu(printmenu)
  2801. printmenu.Destroy()
  2802. def OnCloseWindow(self, event):
  2803. """
  2804. Window closed.
  2805. Also close associated layer tree page
  2806. """
  2807. pgnum = None
  2808. self.Map.Clean()
  2809. # close edited map properly
  2810. digitToolbar = self.toolbars['vdigit']
  2811. if digitToolbar:
  2812. maplayer = digitToolbar.GetLayer()
  2813. if maplayer:
  2814. self.toolbars['vdigit'].OnExit()
  2815. self.imgVectorMap = None
  2816. if self.page:
  2817. pgnum = self.layerbook.GetPageIndex(self.page)
  2818. if pgnum > -1:
  2819. self.layerbook.DeletePage(pgnum)
  2820. ### self.Destroy()
  2821. # if event:
  2822. # event.Skip() <- causes application crash
  2823. def GetRender(self):
  2824. """
  2825. Returns the current instance of render.Map()
  2826. """
  2827. return self.Map
  2828. def OnQueryDisplay(self, event):
  2829. """
  2830. Query currrent raster/vector map layers (display mode)
  2831. """
  2832. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  2833. self.toolbars['map'].SelectDefault(event)
  2834. return
  2835. self.toolbars['map'].action['desc'] = 'displayAttrb'
  2836. # switch GIS Manager to output console to show query results
  2837. self.gismanager.notebook.SetSelection(1)
  2838. self.MapWindow.mouse['use'] = "query"
  2839. self.MapWindow.mouse['box'] = "point"
  2840. self.MapWindow.zoomtype = 0
  2841. # change the cursor
  2842. self.MapWindow.SetCursor(self.cursors["cross"])
  2843. def OnQueryModify(self, event):
  2844. """
  2845. Query vector map layer (edit mode)
  2846. """
  2847. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  2848. self.toolbars['map'].SelectDefault(event)
  2849. return
  2850. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  2851. self.MapWindow.mouse['use'] = "queryVector"
  2852. self.MapWindow.mouse['box'] = "point"
  2853. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  2854. self.MapWindow.zoomtype = 0
  2855. # change the cursor
  2856. self.MapWindow.SetCursor(self.cursors["cross"])
  2857. def QueryMap(self, x, y):
  2858. """
  2859. Query map layer features
  2860. Currently only raster and vector map layers are supported
  2861. """
  2862. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  2863. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  2864. east, north = self.MapWindow.Pixel2Cell((x, y))
  2865. if not self.tree.layer_selected:
  2866. dlg = wx.MessageDialog(parent=self,
  2867. message=_('No map layer selected for querying.'),
  2868. caption=_('Message'),
  2869. style=wx.OK | wx.ICON_INFORMATION)
  2870. dlg.ShowModal()
  2871. dlg.Destroy()
  2872. return
  2873. mapname = None
  2874. raststr = ''
  2875. vectstr = ''
  2876. rcmd = []
  2877. vcmd = []
  2878. for layer in self.tree.GetSelections():
  2879. type = self.tree.GetPyData(layer)[0]['maplayer'].type
  2880. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  2881. name = utils.GetLayerNameFromCmd(dcmd)
  2882. if name == '':
  2883. continue
  2884. if type in ('raster', 'rgb', 'his'):
  2885. raststr += "%s," % name
  2886. elif type in ('vector', 'thememap', 'themechart'):
  2887. vectstr += "%s," % name
  2888. # use display region settings instead of computation region settings
  2889. tmpreg = os.getenv("GRASS_REGION")
  2890. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
  2891. # build query commands for any selected rasters and vectors
  2892. if raststr != '':
  2893. rcmd = ['r.what', '--q',
  2894. '-f',
  2895. 'input=%s' % raststr.rstrip(','),
  2896. 'east_north=%f,%f' % (float(east), float(north))]
  2897. if vectstr != '':
  2898. # check for vector maps open to be edited
  2899. digitToolbar = self.toolbars['vdigit']
  2900. if digitToolbar:
  2901. map = digitToolbar.GetLayer().GetName()
  2902. vect = []
  2903. for vector in vectstr.split(','):
  2904. if map == vector:
  2905. self.gismanager.goutput.WriteWarning("Vector map <%s> "
  2906. "opened for editing - skipped." % map)
  2907. continue
  2908. vect.append(vector)
  2909. vectstr = ','.join(vect)
  2910. if len(vectstr) <= 1:
  2911. self.gismanager.goutput.WriteCmdLog("Nothing to query.")
  2912. return
  2913. vcmd = ['v.what', '--q',
  2914. '-a',
  2915. 'map=%s' % vectstr.rstrip(','),
  2916. 'east_north=%f,%f' % (float(east), float(north)),
  2917. 'distance=%f' % qdist]
  2918. # parse query command(s)
  2919. if self.gismanager:
  2920. if rcmd:
  2921. self.gismanager.goutput.RunCmd(rcmd, compReg=False)
  2922. if vcmd:
  2923. self.gismanager.goutput.RunCmd(vcmd)
  2924. else:
  2925. if rcmd:
  2926. gcmd.Command(rcmd)
  2927. if vcmd:
  2928. gcmd.Command(vcmd)
  2929. # restore GRASS_REGION
  2930. if tmpreg:
  2931. os.environ["GRASS_REGION"] = tmpreg
  2932. def QueryVector(self, x, y):
  2933. """
  2934. Query vector map layer features
  2935. Attribute data of selected vector object are displayed in GUI dialog.
  2936. Data can be modified (On Submit)
  2937. """
  2938. if not self.tree.layer_selected or \
  2939. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  2940. wx.MessageBox(parent=self,
  2941. message=_("No vector map selected for querying."),
  2942. caption=_("Message"),
  2943. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  2944. return
  2945. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  2946. y + self.MapWindow.dialogOffset))
  2947. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / \
  2948. self.Map.width)
  2949. east, north = self.MapWindow.Pixel2Cell((x, y))
  2950. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  2951. if self.dialogs['attributes'] is None:
  2952. self.dialogs['attributes'] = dbm.DisplayAttributesDialog(parent=self.MapWindow,
  2953. map=mapName,
  2954. query=((east, north), qdist),
  2955. pos=posWindow,
  2956. action="update")
  2957. else:
  2958. # selection changed?
  2959. if not self.dialogs['attributes'].mapDBInfo or \
  2960. self.dialogs['attributes'].mapDBInfo.map != mapName:
  2961. self.dialogs['attributes'].UpdateDialog(map=mapName, query=((east, north), qdist))
  2962. else:
  2963. self.dialogs['attributes'].UpdateDialog(query=((east, north), qdist))
  2964. cats = self.dialogs['attributes'].GetCats()
  2965. try:
  2966. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)[0]
  2967. except IndexError:
  2968. qlayer = None
  2969. if self.dialogs['attributes'].mapDBInfo and cats:
  2970. # highlight feature & re-draw map
  2971. if qlayer:
  2972. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  2973. useId=False,
  2974. addLayer=False))
  2975. else:
  2976. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId=False)
  2977. # set opacity based on queried layer
  2978. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float=True)
  2979. qlayer.SetOpacity(opacity)
  2980. self.MapWindow.UpdateMap(render=False, renderVector=False)
  2981. if not self.dialogs['attributes'].IsShown():
  2982. self.dialogs['attributes'].Show()
  2983. else:
  2984. if qlayer:
  2985. self.Map.DeleteLayer(qlayer)
  2986. self.MapWindow.UpdateMap(render=False, renderVector=False)
  2987. if self.dialogs['attributes'].IsShown():
  2988. self.dialogs['attributes'].Hide()
  2989. def OnQuery(self, event):
  2990. """Query tools menu"""
  2991. if self.toolbars['map']:
  2992. self.toolbars['map'].OnTool(event)
  2993. action = self.toolbars['map'].GetAction()
  2994. point = wx.GetMousePosition()
  2995. toolsmenu = wx.Menu()
  2996. # Add items to the menu
  2997. display = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  2998. text=_("Query raster/vector map(s) (display mode)"),
  2999. kind=wx.ITEM_CHECK)
  3000. toolsmenu.AppendItem(display)
  3001. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  3002. if action == "displayAttrb":
  3003. display.Check(True)
  3004. modify = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  3005. text=_("Query vector map (edit mode)"),
  3006. kind=wx.ITEM_CHECK)
  3007. toolsmenu.AppendItem(modify)
  3008. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  3009. digitToolbar = self.toolbars['vdigit']
  3010. if self.tree.layer_selected:
  3011. layer_selected = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  3012. if digitToolbar and \
  3013. digitToolbar.GetLayer() == layer_selected:
  3014. modify.Enable(False)
  3015. else:
  3016. if action == "modifyAttrb":
  3017. modify.Check(True)
  3018. self.PopupMenu(toolsmenu)
  3019. toolsmenu.Destroy()
  3020. def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
  3021. """
  3022. Add temporal vector map layer to map composition
  3023. @param name name of map layer
  3024. @param useId use feature id instead of category
  3025. """
  3026. # color settings from ATM
  3027. color = UserSettings.Get(group='atm', key='highlight', subkey='color')
  3028. colorStr = str(color[0]) + ":" + \
  3029. str(color[1]) + ":" + \
  3030. str(color[2])
  3031. pattern = ["d.vect",
  3032. "map=%s" % name,
  3033. "color=%s" % colorStr,
  3034. "fcolor=%s" % colorStr,
  3035. "width=%d" % UserSettings.Get(group='atm', key='highlight', subkey='width')]
  3036. if useId:
  3037. cmd = pattern
  3038. cmd.append('-i')
  3039. cmd.append('cats=%s' % str(cats))
  3040. else:
  3041. cmd = []
  3042. for layer in cats.keys():
  3043. cmd.append(copy.copy(pattern))
  3044. lcats = cats[layer]
  3045. cmd[-1].append("layer=%d" % layer)
  3046. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  3047. # if self.icon:
  3048. # cmd.append("icon=%s" % (self.icon))
  3049. # if self.pointsize:
  3050. # cmd.append("size=%s" % (self.pointsize))
  3051. if addLayer:
  3052. if useId:
  3053. return self.Map.AddLayer(type='vector', name=globalvar.QUERYLAYER, command=cmd,
  3054. l_active=True, l_hidden=True, l_opacity=1.0)
  3055. else:
  3056. return self.Map.AddLayer(type='command', name=globalvar.QUERYLAYER, command=cmd,
  3057. l_active=True, l_hidden=True, l_opacity=1.0)
  3058. else:
  3059. return cmd
  3060. def OnAnalyze(self, event):
  3061. """
  3062. Analysis tools menu
  3063. """
  3064. point = wx.GetMousePosition()
  3065. toolsmenu = wx.Menu()
  3066. # Add items to the menu
  3067. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
  3068. measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
  3069. toolsmenu.AppendItem(measure)
  3070. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  3071. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
  3072. profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
  3073. toolsmenu.AppendItem(profile)
  3074. self.Bind(wx.EVT_MENU, self.Profile, profile)
  3075. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
  3076. histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
  3077. toolsmenu.AppendItem(histogram)
  3078. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  3079. # Popup the menu. If an item is selected then its handler
  3080. # will be called before PopupMenu returns.
  3081. self.PopupMenu(toolsmenu)
  3082. toolsmenu.Destroy()
  3083. def OnMeasure(self, event):
  3084. """
  3085. Init measurement routine that calculates
  3086. map distance along transect drawn on
  3087. map display
  3088. """
  3089. self.totaldist = 0.0 # total measured distance
  3090. # switch GIS Manager to output console to show measure results
  3091. self.gismanager.notebook.SetSelection(1)
  3092. # change mouse to draw line for measurement
  3093. self.MapWindow.mouse['use'] = "measure"
  3094. self.MapWindow.mouse['box'] = "line"
  3095. self.MapWindow.zoomtype = 0
  3096. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  3097. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
  3098. # change the cursor
  3099. self.MapWindow.SetCursor(self.cursors["pencil"])
  3100. # initiating output
  3101. style = self.gismanager.goutput.cmd_output.StyleWarning
  3102. self.gismanager.goutput.WriteLog(_('Click and drag with left mouse button '
  3103. 'to measure.%s'
  3104. 'Double click with left button to clear.') % \
  3105. (os.linesep), style)
  3106. if self.Map.projinfo['proj'] != 'xy':
  3107. units = self.Map.projinfo['units']
  3108. style = self.gismanager.goutput.cmd_output.StyleCommand
  3109. self.gismanager.goutput.WriteLog(_('Measuring distance') + ' ('
  3110. + units + '):',
  3111. style)
  3112. else:
  3113. self.gismanager.goutput.WriteLog(_('Measuring distance:'),
  3114. style)
  3115. def MeasureDist(self, beginpt, endpt):
  3116. """
  3117. Calculate map distance from screen distance
  3118. and print to output window
  3119. """
  3120. if self.gismanager.notebook.GetSelection() != 1:
  3121. self.gismanager.notebook.SetSelection(1)
  3122. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  3123. dist = round(dist, 3)
  3124. d, dunits = self.FormatDist(dist)
  3125. self.totaldist += dist
  3126. td, tdunits = self.FormatDist(self.totaldist)
  3127. strdist = str(d)
  3128. strtotdist = str(td)
  3129. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  3130. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  3131. angle = angle+90
  3132. if angle < 0: angle = 360+angle
  3133. mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
  3134. % (strdist,dunits,strtotdist,tdunits,angle)
  3135. else:
  3136. mstring = 'segment = %s %s\ttotal distance = %s %s' \
  3137. % (strdist,dunits,strtotdist,tdunits)
  3138. self.gismanager.goutput.WriteLog(mstring)
  3139. return dist
  3140. def Profile(self, event):
  3141. """
  3142. Init profile canvas and tools
  3143. """
  3144. raster = []
  3145. if self.tree.layer_selected and \
  3146. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  3147. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  3148. self.profile = profile.ProfileFrame(self,
  3149. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
  3150. style=wx.DEFAULT_FRAME_STYLE, rasterList=raster)
  3151. self.profile.Show()
  3152. # Open raster select dialog to make sure that a raster (and the desired raster)
  3153. # is selected to be profiled
  3154. self.profile.OnSelectRaster(None)
  3155. def FormatDist(self, dist):
  3156. """Format length numbers and units in a nice way,
  3157. as a function of length. From code by Hamish Bowman
  3158. Grass Development Team 2006"""
  3159. mapunits = self.Map.projinfo['units']
  3160. if mapunits == 'metres': mapunits = 'meters'
  3161. outunits = mapunits
  3162. dist = float(dist)
  3163. divisor = 1.0
  3164. # figure out which units to use
  3165. if mapunits == 'meters':
  3166. if dist > 2500.0:
  3167. outunits = 'km'
  3168. divisor = 1000.0
  3169. else: outunits = 'm'
  3170. elif mapunits == 'feet':
  3171. # nano-bug: we match any "feet", but US Survey feet is really
  3172. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  3173. # miles the tick markers are rounded to the nearest 10th of a
  3174. # mile (528'), the difference in foot flavours is ignored.
  3175. if dist > 5280.0:
  3176. outunits = 'miles'
  3177. divisor = 5280.0
  3178. else:
  3179. outunits = 'ft'
  3180. elif 'degree' in mapunits:
  3181. if dist < 1:
  3182. outunits = 'min'
  3183. divisor = (1/60.0)
  3184. else:
  3185. outunits = 'deg'
  3186. # format numbers in a nice way
  3187. if (dist/divisor) >= 2500.0:
  3188. outdist = round(dist/divisor)
  3189. elif (dist/divisor) >= 1000.0:
  3190. outdist = round(dist/divisor,1)
  3191. elif (dist/divisor) > 0.0:
  3192. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  3193. else:
  3194. outdist = float(dist/divisor)
  3195. return (outdist, outunits)
  3196. def Histogram(self, event):
  3197. """
  3198. Init histogram display canvas and tools
  3199. """
  3200. self.histogram = histogram.HistFrame(self,
  3201. id=wx.ID_ANY, size=globalvar.HIST_WINDOW_SIZE,
  3202. style=wx.DEFAULT_FRAME_STYLE)
  3203. #show new display
  3204. self.histogram.Show()
  3205. self.histogram.Refresh()
  3206. self.histogram.Update()
  3207. def OnDecoration(self, event):
  3208. """
  3209. Decorations overlay menu
  3210. """
  3211. point = wx.GetMousePosition()
  3212. decmenu = wx.Menu()
  3213. # Add items to the menu
  3214. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
  3215. AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
  3216. decmenu.AppendItem(AddScale)
  3217. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  3218. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
  3219. AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
  3220. decmenu.AppendItem(AddLegend)
  3221. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  3222. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
  3223. AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
  3224. decmenu.AppendItem(AddText)
  3225. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  3226. # Popup the menu. If an item is selected then its handler
  3227. # will be called before PopupMenu returns.
  3228. self.PopupMenu(decmenu)
  3229. decmenu.Destroy()
  3230. def OnAddBarscale(self, event):
  3231. """
  3232. Handler for scale/arrow map decoration menu selection.
  3233. """
  3234. if self.dialogs['barscale']:
  3235. return
  3236. id = 0 # unique index for overlay layer
  3237. # If location is latlon, only display north arrow (scale won't work)
  3238. # proj = self.Map.projinfo['proj']
  3239. # if proj == 'll':
  3240. # barcmd = 'd.barscale -n'
  3241. # else:
  3242. # barcmd = 'd.barscale'
  3243. # decoration overlay control dialog
  3244. self.dialogs['barscale'] = \
  3245. gdialogs.DecorationDialog(parent=self, title=_('Scale and North arrow'),
  3246. size=(350, 200),
  3247. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  3248. cmd=['d.barscale'],
  3249. ovlId=id,
  3250. name='barscale',
  3251. checktxt = _("Show/hide scale and North arrow"),
  3252. ctrltxt = _("scale object"))
  3253. self.dialogs['barscale'].Show()
  3254. self.MapWindow.mouse['use'] = 'pointer'
  3255. def OnAddLegend(self, event):
  3256. """
  3257. Handler for legend map decoration menu selection.
  3258. """
  3259. if self.dialogs['legend']:
  3260. return
  3261. id = 1 # index for overlay layer in render
  3262. cmd = ['d.legend']
  3263. if self.tree.layer_selected and \
  3264. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  3265. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  3266. # Decoration overlay control dialog
  3267. self.dialogs['legend'] = \
  3268. gdialogs.DecorationDialog(parent=self, title=('Legend'),
  3269. size=(350, 200),
  3270. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  3271. cmd=cmd,
  3272. ovlId=id,
  3273. name='legend',
  3274. checktxt = _("Show/hide legend"),
  3275. ctrltxt = _("legend object"))
  3276. self.dialogs['legend'].Show()
  3277. self.MapWindow.mouse['use'] = 'pointer'
  3278. def OnAddText(self, event):
  3279. """
  3280. Handler for text decoration menu selection.
  3281. """
  3282. if self.MapWindow.dragid > -1:
  3283. id = self.MapWindow.dragid
  3284. else:
  3285. # index for overlay layer in render
  3286. if len(self.MapWindow.textdict.keys()) > 0:
  3287. id = self.MapWindow.textdict.keys()[-1] + 1
  3288. else:
  3289. id = 101
  3290. dlg = gdialogs.TextLayerDialog(parent=self, ovlId=id, title=_('Add text layer'),
  3291. size=(400, 200))
  3292. dlg.CenterOnParent()
  3293. # If OK button pressed in decoration control dialog
  3294. if dlg.ShowModal() == wx.ID_OK:
  3295. text = dlg.GetValues()['text']
  3296. coords, w, h = self.MapWindow.TextBounds(dlg.GetValues())
  3297. # delete object if it has no text
  3298. if text == '':
  3299. try:
  3300. self.MapWindow.pdc.ClearId(id)
  3301. self.MapWindow.pdc.RemoveId(id)
  3302. del self.MapWindow.textdict[id]
  3303. except:
  3304. pass
  3305. return
  3306. self.MapWindow.pdc.ClearId(id)
  3307. self.MapWindow.pdc.SetId(id)
  3308. self.MapWindow.textdict[id] = dlg.GetValues()
  3309. self.MapWindow.Draw(self.MapWindow.pdcDec, img=self.MapWindow.textdict[id],
  3310. drawid=id, pdctype='text', coords=coords)
  3311. self.MapWindow.UpdateMap(render=False, renderVector=False)
  3312. self.MapWindow.mouse['use'] = 'pointer'
  3313. def GetOptData(self, dcmd, type, params, propwin):
  3314. """
  3315. Callback method for decoration overlay command generated by
  3316. dialog created in menuform.py
  3317. """
  3318. # Reset comand and rendering options in render.Map. Always render decoration.
  3319. # Showing/hiding handled by PseudoDC
  3320. self.Map.ChangeOverlay(ovltype=type, type='overlay', name='', command=dcmd,
  3321. l_active=True, l_render=False)
  3322. self.params[type] = params
  3323. self.propwin[type] = propwin
  3324. def OnZoomMenu(self, event):
  3325. """
  3326. Zoom menu
  3327. """
  3328. point = wx.GetMousePosition()
  3329. zoommenu = wx.Menu()
  3330. # Add items to the menu
  3331. zoommap = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to selected map'))
  3332. zoommenu.AppendItem(zoommap)
  3333. self.Bind(wx.EVT_MENU, self.MapWindow.OnZoomToMap, zoommap)
  3334. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
  3335. zoommenu.AppendItem(zoomwind)
  3336. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToWind, zoomwind)
  3337. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  3338. zoommenu.AppendItem(zoomdefault)
  3339. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToDefault, zoomdefault)
  3340. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  3341. zoommenu.AppendItem(zoomsaved)
  3342. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToSaved, zoomsaved)
  3343. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  3344. zoommenu.AppendItem(savewind)
  3345. self.Bind(wx.EVT_MENU, self.MapWindow.DisplayToWind, savewind)
  3346. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  3347. zoommenu.AppendItem(savezoom)
  3348. self.Bind(wx.EVT_MENU, self.MapWindow.SaveDisplayRegion, savezoom)
  3349. # Popup the menu. If an item is selected then its handler
  3350. # will be called before PopupMenu returns.
  3351. self.PopupMenu(zoommenu)
  3352. zoommenu.Destroy()
  3353. def SetProperties(self, render=False, mode=0, showCompExtent=False,
  3354. constrainRes=False):
  3355. """Set properies of map display window"""
  3356. self.autoRender.SetValue(render)
  3357. self.toggleStatus.SetSelection(mode)
  3358. self.StatusbarUpdate()
  3359. self.showRegion.SetValue(showCompExtent)
  3360. self.compResolution.SetValue(constrainRes)
  3361. if showCompExtent:
  3362. self.MapWindow.regionCoords = []
  3363. # end of class MapFrame
  3364. class MapApp(wx.App):
  3365. """
  3366. MapApp class
  3367. """
  3368. def OnInit(self):
  3369. wx.InitAllImageHandlers()
  3370. if __name__ == "__main__":
  3371. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  3372. else:
  3373. Map = None
  3374. self.mapFrm = MapFrame(parent=None, id=wx.ID_ANY, Map=Map, size=(640,480))
  3375. #self.SetTopWindow(Map)
  3376. self.mapFrm.Show()
  3377. if __name__ == "__main__":
  3378. # redraw map, if new command appears
  3379. self.redraw = False
  3380. status = Command(self, Map)
  3381. status.start()
  3382. self.timer = wx.PyTimer(self.watcher)
  3383. # check each 0.1s
  3384. self.timer.Start(100)
  3385. return 1
  3386. def OnExit(self):
  3387. if __name__ == "__main__":
  3388. # stop the timer
  3389. self.timer.Stop()
  3390. # terminate thread (a bit ugly)
  3391. os.system("""echo "quit" >> %s""" % (cmdfilename))
  3392. def watcher(self):
  3393. """Redraw, if new layer appears"""
  3394. if self.redraw:
  3395. self.mapFrm.OnDraw(None)
  3396. self.redraw = False
  3397. return
  3398. # end of class MapApp
  3399. if __name__ == "__main__":
  3400. ###### SET command variable
  3401. if len(sys.argv) != 3:
  3402. print __doc__
  3403. sys.exit()
  3404. title = sys.argv[1]
  3405. cmdfilename = sys.argv[2]
  3406. import gettext
  3407. gettext.install("gm_map") # replace with the appropriate catalog name
  3408. print "Starting monitor <%s>" % (title)
  3409. gm_map = MapApp(0)
  3410. # set title
  3411. gm_map.mapFrm.SetTitle ("GRASS GIS - Map Display: " + title + " - Location: " + \
  3412. grassenv.GetGRASSVariable("LOCATION_NAME"))
  3413. gm_map.MainLoop()
  3414. os.remove(cmdfilename)
  3415. os.system("""g.gisenv set="GRASS_PYCMDFILE" """)
  3416. print "Stoping monitor <%s>" % (title)
  3417. sys.exit()