mapwindow.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  1. """!
  2. @package mapdisp.mapwindow
  3. @brief Map display canvas - buffered window.
  4. Classes:
  5. - mapwindow::BufferedWindow
  6. (C) 2006-2011 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Martin Landa <landa.martin gmail.com>
  10. @author Michael Barton
  11. @author Jachym Cepicky
  12. """
  13. import os
  14. import time
  15. import math
  16. import sys
  17. import wx
  18. import grass.script as grass
  19. from gui_core.dialogs import SavedRegion
  20. from core.gcmd import RunCommand, GException, GError
  21. from core.debug import Debug
  22. from core.settings import UserSettings
  23. from gui_core.mapwindow import MapWindow
  24. try:
  25. import grass.lib.gis as gislib
  26. haveCtypes = True
  27. except ImportError:
  28. haveCtypes = False
  29. class BufferedWindow(MapWindow, wx.Window):
  30. """!A Buffered window class (2D view mode)
  31. Superclass for VDigitWindow (vector digitizer).
  32. When the drawing needs to change, you app needs to call the
  33. UpdateMap() method. Since the drawing is stored in a bitmap, you
  34. can also save the drawing to file by calling the
  35. SaveToFile() method.
  36. """
  37. def __init__(self, parent, id = wx.ID_ANY,
  38. Map = None, tree = None, lmgr = None,
  39. style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
  40. MapWindow.__init__(self, parent, id, Map, tree, lmgr, **kwargs)
  41. wx.Window.__init__(self, parent, id, style = style, **kwargs)
  42. # flags
  43. self.resize = False # indicates whether or not a resize event has taken place
  44. self.dragimg = None # initialize variable for map panning
  45. # variables for drawing on DC
  46. self.pen = None # pen for drawing zoom boxes, etc.
  47. self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
  48. # List of wx.Point tuples defining a polyline (geographical coordinates)
  49. self.polycoords = []
  50. # ID of rubber band line
  51. self.lineid = None
  52. # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
  53. self.plineid = None
  54. # event bindings
  55. self.Bind(wx.EVT_PAINT, self.OnPaint)
  56. self.Bind(wx.EVT_SIZE, self.OnSize)
  57. self.Bind(wx.EVT_IDLE, self.OnIdle)
  58. self._bindMouseEvents()
  59. self.processMouse = True
  60. # render output objects
  61. self.mapfile = None # image file to be rendered
  62. self.img = None # wx.Image object (self.mapfile)
  63. # decoration overlays
  64. self.overlays = {}
  65. # images and their PseudoDC ID's for painting and dragging
  66. self.imagedict = {}
  67. self.select = {} # selecting/unselecting decorations for dragging
  68. self.textdict = {} # text, font, and color indexed by id
  69. self.currtxtid = None # PseudoDC id for currently selected text
  70. # zoom objects
  71. self.zoomhistory = [] # list of past zoom extents
  72. self.currzoom = 0 # current set of extents in zoom history being used
  73. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  74. self.hitradius = 10 # distance for selecting map decorations
  75. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  76. # OnSize called to make sure the buffer is initialized.
  77. # This might result in OnSize getting called twice on some
  78. # platforms at initialization, but little harm done.
  79. ### self.OnSize(None)
  80. self._definePseudoDC()
  81. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  82. self.redrawAll = True
  83. # will store an off screen empty bitmap for saving to file
  84. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  85. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  86. # vars for handling mouse clicks
  87. self.dragid = -1
  88. self.lastpos = (0, 0)
  89. def _definePseudoDC(self):
  90. """!Define PseudoDC objects to use
  91. """
  92. # create PseudoDC used for background map, map decorations like scales and legends
  93. self.pdc = wx.PseudoDC()
  94. # used for digitization tool
  95. self.pdcVector = None
  96. # decorations (region box, etc.)
  97. self.pdcDec = wx.PseudoDC()
  98. # pseudoDC for temporal objects (select box, measurement tool, etc.)
  99. self.pdcTmp = wx.PseudoDC()
  100. def _bindMouseEvents(self):
  101. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  102. self.Bind(wx.EVT_MOTION, self.OnMotion)
  103. def Draw(self, pdc, img = None, drawid = None, pdctype = 'image', coords = [0, 0, 0, 0]):
  104. """!Draws map and overlay decorations
  105. """
  106. if drawid == None:
  107. if pdctype == 'image' and img:
  108. drawid = self.imagedict[img]
  109. elif pdctype == 'clear':
  110. drawid == None
  111. else:
  112. drawid = wx.NewId()
  113. if img and pdctype == 'image':
  114. # self.imagedict[img]['coords'] = coords
  115. self.select[self.imagedict[img]['id']] = False # ?
  116. pdc.BeginDrawing()
  117. if drawid != 99:
  118. bg = wx.TRANSPARENT_BRUSH
  119. else:
  120. bg = wx.Brush(self.GetBackgroundColour())
  121. pdc.SetBackground(bg)
  122. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype = %s, coord=%s" % \
  123. (drawid, pdctype, coords))
  124. # set PseudoDC id
  125. if drawid is not None:
  126. pdc.SetId(drawid)
  127. if pdctype == 'clear': # erase the display
  128. bg = wx.WHITE_BRUSH
  129. # bg = wx.Brush(self.GetBackgroundColour())
  130. pdc.SetBackground(bg)
  131. pdc.RemoveAll()
  132. pdc.Clear()
  133. pdc.EndDrawing()
  134. self.Refresh()
  135. return
  136. if pdctype == 'image': # draw selected image
  137. bitmap = wx.BitmapFromImage(img)
  138. w,h = bitmap.GetSize()
  139. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  140. pdc.SetIdBounds(drawid, wx.Rect(coords[0],coords[1], w, h))
  141. elif pdctype == 'box': # draw a box on top of the map
  142. if self.pen:
  143. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  144. pdc.SetPen(self.pen)
  145. x2 = max(coords[0],coords[2])
  146. x1 = min(coords[0],coords[2])
  147. y2 = max(coords[1],coords[3])
  148. y1 = min(coords[1],coords[3])
  149. rwidth = x2-x1
  150. rheight = y2-y1
  151. rect = wx.Rect(x1, y1, rwidth, rheight)
  152. pdc.DrawRectangleRect(rect)
  153. pdc.SetIdBounds(drawid, rect)
  154. elif pdctype == 'line': # draw a line on top of the map
  155. if self.pen:
  156. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  157. pdc.SetPen(self.pen)
  158. pdc.DrawLinePoint(wx.Point(coords[0], coords[1]),wx.Point(coords[2], coords[3]))
  159. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
  160. elif pdctype == 'polyline': # draw a polyline on top of the map
  161. if self.polypen:
  162. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  163. pdc.SetPen(self.polypen)
  164. if (len(coords) < 2):
  165. return
  166. i = 1
  167. while i < len(coords):
  168. pdc.DrawLinePoint(wx.Point(coords[i-1][0], coords[i-1][1]),
  169. wx.Point(coords[i][0], coords[i][1]))
  170. i += 1
  171. # get bounding rectangle for polyline
  172. xlist = []
  173. ylist = []
  174. if len(coords) > 0:
  175. for point in coords:
  176. x,y = point
  177. xlist.append(x)
  178. ylist.append(y)
  179. x1 = min(xlist)
  180. x2 = max(xlist)
  181. y1 = min(ylist)
  182. y2 = max(ylist)
  183. pdc.SetIdBounds(drawid, wx.Rect(x1,y1,x2,y2))
  184. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  185. elif pdctype == 'point': # draw point
  186. if self.pen:
  187. pdc.SetPen(self.pen)
  188. pdc.DrawPoint(coords[0], coords[1])
  189. coordsBound = (coords[0] - 5,
  190. coords[1] - 5,
  191. coords[0] + 5,
  192. coords[1] + 5)
  193. pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
  194. elif pdctype == 'text': # draw text on top of map
  195. if not img['active']:
  196. return # only draw active text
  197. if 'rotation' in img:
  198. rotation = float(img['rotation'])
  199. else:
  200. rotation = 0.0
  201. w, h = self.GetFullTextExtent(img['text'])[0:2]
  202. pdc.SetFont(img['font'])
  203. pdc.SetTextForeground(img['color'])
  204. coords, bbox = self.TextBounds(img)
  205. if rotation == 0:
  206. pdc.DrawText(img['text'], coords[0], coords[1])
  207. else:
  208. pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
  209. pdc.SetIdBounds(drawid, bbox)
  210. pdc.EndDrawing()
  211. self.Refresh()
  212. return drawid
  213. def TextBounds(self, textinfo, relcoords = False):
  214. """!Return text boundary data
  215. @param textinfo text metadata (text, font, color, rotation)
  216. @param coords reference point
  217. @return coords of nonrotated text bbox (TL corner)
  218. @return bbox of rotated text bbox (wx.Rect)
  219. @return relCoords are text coord inside bbox
  220. """
  221. if 'rotation' in textinfo:
  222. rotation = float(textinfo['rotation'])
  223. else:
  224. rotation = 0.0
  225. coords = textinfo['coords']
  226. bbox = wx.Rect(coords[0], coords[1], 0, 0)
  227. relCoords = (0, 0)
  228. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  229. (textinfo['text'], rotation))
  230. self.Update()
  231. self.SetFont(textinfo['font'])
  232. w, h = self.GetTextExtent(textinfo['text'])
  233. if rotation == 0:
  234. bbox[2], bbox[3] = w, h
  235. if relcoords:
  236. return coords, bbox, relCoords
  237. else:
  238. return coords, bbox
  239. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  240. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  241. if rotation > 0 and rotation < 90:
  242. bbox[1] -= boxh
  243. relCoords = (0, boxh)
  244. elif rotation >= 90 and rotation < 180:
  245. bbox[0] -= boxw
  246. bbox[1] -= boxh
  247. relCoords = (boxw, boxh)
  248. elif rotation >= 180 and rotation < 270:
  249. bbox[0] -= boxw
  250. relCoords = (boxw, 0)
  251. bbox[2] = boxw
  252. bbox[3] = boxh
  253. bbox.Inflate(h,h)
  254. if relcoords:
  255. return coords, bbox, relCoords
  256. else:
  257. return coords, bbox
  258. def OnPaint(self, event):
  259. """!Draw PseudoDC's to buffered paint DC
  260. If self.redrawAll is False on self.pdcTmp content is re-drawn
  261. """
  262. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  263. dc = wx.BufferedPaintDC(self, self._buffer)
  264. dc.Clear()
  265. # use PrepareDC to set position correctly
  266. self.PrepareDC(dc)
  267. # create a clipping rect from our position and size
  268. # and update region
  269. rgn = self.GetUpdateRegion().GetBox()
  270. dc.SetClippingRect(rgn)
  271. switchDraw = False
  272. if self.redrawAll is None:
  273. self.redrawAll = True
  274. switchDraw = True
  275. if self.redrawAll: # redraw pdc and pdcVector
  276. # draw to the dc using the calculated clipping rect
  277. self.pdc.DrawToDCClipped(dc, rgn)
  278. # draw vector map layer
  279. if hasattr(self, "digit"):
  280. # decorate with GDDC (transparency)
  281. try:
  282. gcdc = wx.GCDC(dc)
  283. self.pdcVector.DrawToDCClipped(gcdc, rgn)
  284. except NotImplementedError, e:
  285. print >> sys.stderr, e
  286. self.pdcVector.DrawToDCClipped(dc, rgn)
  287. self.bufferLast = None
  288. else: # do not redraw pdc and pdcVector
  289. if self.bufferLast is None:
  290. # draw to the dc
  291. self.pdc.DrawToDC(dc)
  292. if hasattr(self, "digit"):
  293. # decorate with GDDC (transparency)
  294. try:
  295. gcdc = wx.GCDC(dc)
  296. self.pdcVector.DrawToDC(gcdc)
  297. except NotImplementedError, e:
  298. print >> sys.stderr, e
  299. self.pdcVector.DrawToDC(dc)
  300. # store buffered image
  301. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  302. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  303. self.pdc.DrawBitmap(self.bufferLast, 0, 0, False)
  304. self.pdc.DrawToDC(dc)
  305. # draw decorations (e.g. region box)
  306. try:
  307. gcdc = wx.GCDC(dc)
  308. self.pdcDec.DrawToDC(gcdc)
  309. except NotImplementedError, e:
  310. print >> sys.stderr, e
  311. self.pdcDec.DrawToDC(dc)
  312. # draw temporary object on the foreground
  313. ### self.pdcTmp.DrawToDCClipped(dc, rgn)
  314. self.pdcTmp.DrawToDC(dc)
  315. if switchDraw:
  316. self.redrawAll = False
  317. def OnSize(self, event):
  318. """!Scale map image so that it is the same size as the Window
  319. """
  320. # re-render image on idle
  321. self.resize = time.clock()
  322. def OnIdle(self, event):
  323. """!Only re-render a composite map image from GRASS during
  324. idle time instead of multiple times during resizing.
  325. """
  326. # use OnInternalIdle() instead ?
  327. if self.resize and self.resize + 0.2 < time.clock():
  328. Debug.msg(3, "BufferedWindow.OnSize():")
  329. # set size of the input image
  330. self.Map.ChangeMapSize(self.GetClientSize())
  331. # Make new off screen bitmap: this bitmap will always have the
  332. # current drawing in it, so it can be used to save the image to
  333. # a file, or whatever.
  334. self._buffer.Destroy()
  335. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  336. # get the image to be rendered
  337. self.img = self.GetImage()
  338. # update map display
  339. updatemap = True
  340. if self.img and self.Map.width + self.Map.height > 0: # scale image after resize
  341. self.img = self.img.Scale(self.Map.width, self.Map.height)
  342. if len(self.Map.GetListOfLayers()) > 0:
  343. self.UpdateMap()
  344. updatemap = False
  345. # reposition checkbox in statusbar
  346. self.parent.StatusbarReposition()
  347. # update statusbar
  348. self.parent.StatusbarUpdate()
  349. if updatemap:
  350. self.UpdateMap(render = True)
  351. self.resize = False
  352. elif self.resize:
  353. event.RequestMore()
  354. event.Skip()
  355. def SaveToFile(self, FileName, FileType, width, height):
  356. """!This draws the pseudo DC to a buffer that can be saved to
  357. a file.
  358. @param FileName file name
  359. @param FileType type of bitmap
  360. @param width image width
  361. @param height image height
  362. """
  363. busy = wx.BusyInfo(message = _("Please wait, exporting image..."),
  364. parent = self)
  365. wx.Yield()
  366. self.Map.ChangeMapSize((width, height))
  367. ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
  368. self.Map.Render(force = True, windres = False)
  369. img = self.GetImage()
  370. self.pdc.RemoveAll()
  371. self.Draw(self.pdc, img, drawid = 99)
  372. # compute size ratio to move overlay accordingly
  373. cSize = self.GetClientSizeTuple()
  374. ratio = float(width) / cSize[0], float(height) / cSize[1]
  375. # redraw legend, scalebar
  376. for img in self.GetOverlay():
  377. # draw any active and defined overlays
  378. if self.imagedict[img]['layer'].IsActive():
  379. id = self.imagedict[img]['id']
  380. coords = int(ratio[0] * self.overlays[id]['coords'][0]),\
  381. int(ratio[1] * self.overlays[id]['coords'][1])
  382. self.Draw(self.pdc, img = img, drawid = id,
  383. pdctype = self.overlays[id]['pdcType'], coords = coords)
  384. # redraw text labels
  385. for id in self.textdict.keys():
  386. textinfo = self.textdict[id]
  387. oldCoords = textinfo['coords']
  388. textinfo['coords'] = ratio[0] * textinfo['coords'][0],\
  389. ratio[1] * textinfo['coords'][1]
  390. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  391. pdctype = 'text')
  392. # set back old coordinates
  393. textinfo['coords'] = oldCoords
  394. dc = wx.BufferedDC(None, ibuffer)
  395. dc.Clear()
  396. self.PrepareDC(dc)
  397. self.pdc.DrawToDC(dc)
  398. if self.pdcVector:
  399. self.pdcVector.DrawToDC(dc)
  400. ibuffer.SaveFile(FileName, FileType)
  401. busy.Destroy()
  402. self.UpdateMap(render = True)
  403. self.Refresh()
  404. def GetOverlay(self):
  405. """!Converts rendered overlay files to wx.Image
  406. Updates self.imagedict
  407. @return list of images
  408. """
  409. imgs = []
  410. for overlay in self.Map.GetListOfLayers(l_type = "overlay", l_active = True):
  411. if os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  412. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  413. self.imagedict[img] = { 'id' : overlay.id,
  414. 'layer' : overlay }
  415. imgs.append(img)
  416. return imgs
  417. def GetImage(self):
  418. """!Converts redered map files to wx.Image
  419. Updates self.imagedict (id=99)
  420. @return wx.Image instance (map composition)
  421. """
  422. imgId = 99
  423. if self.mapfile and self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  424. os.path.getsize(self.Map.mapfile):
  425. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  426. else:
  427. img = None
  428. self.imagedict[img] = { 'id': imgId }
  429. return img
  430. def UpdateMap(self, render = True, renderVector = True):
  431. """!Updates the canvas anytime there is a change to the
  432. underlaying images or to the geometry of the canvas.
  433. @param render re-render map composition
  434. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  435. """
  436. start = time.clock()
  437. self.resize = False
  438. if not self.Map.cmdfile and self.img is None:
  439. render = True
  440. #
  441. # initialize process bar (only on 'render')
  442. #
  443. if render or renderVector:
  444. self.parent.GetProgressBar().Show()
  445. if self.parent.GetProgressBar().GetRange() > 0:
  446. self.parent.GetProgressBar().SetValue(1)
  447. #
  448. # render background image if needed
  449. #
  450. # update layer dictionary if there has been a change in layers
  451. if self.tree and self.tree.reorder:
  452. self.tree.ReorderLayers()
  453. # reset flag for auto-rendering
  454. if self.tree:
  455. self.tree.rerender = False
  456. try:
  457. if render:
  458. # update display size
  459. self.Map.ChangeMapSize(self.GetClientSize())
  460. if self.parent.GetProperty('resolution'):
  461. # use computation region resolution for rendering
  462. windres = True
  463. else:
  464. windres = False
  465. self.mapfile = self.Map.Render(force = True, mapWindow = self.parent,
  466. windres = windres)
  467. else:
  468. self.mapfile = self.Map.Render(force = False, mapWindow = self.parent)
  469. except GException, e:
  470. GError(message = e.value)
  471. self.mapfile = None
  472. self.img = self.GetImage() # id=99
  473. #
  474. # clear pseudoDcs
  475. #
  476. for pdc in (self.pdc,
  477. self.pdcDec,
  478. self.pdcTmp):
  479. pdc.Clear()
  480. pdc.RemoveAll()
  481. #
  482. # draw background map image to PseudoDC
  483. #
  484. if not self.img:
  485. self.Draw(self.pdc, pdctype = 'clear')
  486. else:
  487. try:
  488. id = self.imagedict[self.img]['id']
  489. except:
  490. return False
  491. self.Draw(self.pdc, self.img, drawid = id)
  492. #
  493. # render vector map layer
  494. #
  495. if renderVector and hasattr(self, "digit"):
  496. self._updateMap()
  497. #
  498. # render overlays
  499. #
  500. for img in self.GetOverlay():
  501. # draw any active and defined overlays
  502. if self.imagedict[img]['layer'].IsActive():
  503. id = self.imagedict[img]['id']
  504. self.Draw(self.pdc, img = img, drawid = id,
  505. pdctype = self.overlays[id]['pdcType'], coords = self.overlays[id]['coords'])
  506. for id in self.textdict.keys():
  507. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  508. pdctype = 'text', coords = [10, 10, 10, 10])
  509. # optionally draw computational extent box
  510. self.DrawCompRegionExtent()
  511. #
  512. # redraw pdcTmp if needed
  513. #
  514. if len(self.polycoords) > 0:
  515. self.DrawLines(self.pdcTmp)
  516. if not self.parent.IsStandalone() and \
  517. self.parent.GetLayerManager().gcpmanagement:
  518. # -> georectifier (redraw GCPs)
  519. if 'gcpdisp' in self.parent.toolbars.keys():
  520. if self == self.parent.TgtMapWindow:
  521. coordtype = 'target'
  522. else:
  523. coordtype = 'source'
  524. self.parent.DrawGCP(coordtype)
  525. #
  526. # clear measurement
  527. #
  528. if self.mouse["use"] == "measure":
  529. self.ClearLines(pdc = self.pdcTmp)
  530. self.polycoords = []
  531. self.mouse['use'] = 'pointer'
  532. self.mouse['box'] = 'point'
  533. self.mouse['end'] = [0, 0]
  534. self.SetCursor(self.parent.cursors["default"])
  535. stop = time.clock()
  536. #
  537. # hide process bar
  538. #
  539. self.parent.GetProgressBar().Hide()
  540. #
  541. # update statusbar
  542. #
  543. ### self.Map.SetRegion()
  544. self.parent.StatusbarUpdate()
  545. Debug.msg (1, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  546. (render, renderVector, (stop-start)))
  547. return True
  548. def DrawCompRegionExtent(self):
  549. """!Draw computational region extent in the display
  550. Display region is drawn as a blue box inside the computational region,
  551. computational region inside a display region as a red box).
  552. """
  553. if hasattr(self, "regionCoords"):
  554. compReg = self.Map.GetRegion()
  555. dispReg = self.Map.GetCurrentRegion()
  556. reg = None
  557. if self.IsInRegion(dispReg, compReg):
  558. self.polypen = wx.Pen(colour = wx.Colour(0, 0, 255, 128), width = 3, style = wx.SOLID)
  559. reg = dispReg
  560. else:
  561. self.polypen = wx.Pen(colour = wx.Colour(255, 0, 0, 128),
  562. width = 3, style = wx.SOLID)
  563. reg = compReg
  564. self.regionCoords = []
  565. self.regionCoords.append((reg['w'], reg['n']))
  566. self.regionCoords.append((reg['e'], reg['n']))
  567. self.regionCoords.append((reg['e'], reg['s']))
  568. self.regionCoords.append((reg['w'], reg['s']))
  569. self.regionCoords.append((reg['w'], reg['n']))
  570. # draw region extent
  571. self.DrawLines(pdc = self.pdcDec, polycoords = self.regionCoords)
  572. def IsInRegion(self, region, refRegion):
  573. """!
  574. Test if 'region' is inside of 'refRegion'
  575. @param region input region
  576. @param refRegion reference region (e.g. computational region)
  577. @return True if region is inside of refRegion
  578. @return False
  579. """
  580. if region['s'] >= refRegion['s'] and \
  581. region['n'] <= refRegion['n'] and \
  582. region['w'] >= refRegion['w'] and \
  583. region['e'] <= refRegion['e']:
  584. return True
  585. return False
  586. def EraseMap(self):
  587. """!Erase map canvas
  588. """
  589. self.Draw(self.pdc, pdctype = 'clear')
  590. if hasattr(self, "digit"):
  591. self.Draw(self.pdcVector, pdctype = 'clear')
  592. self.Draw(self.pdcDec, pdctype = 'clear')
  593. self.Draw(self.pdcTmp, pdctype = 'clear')
  594. def DragMap(self, moveto):
  595. """!Drag the entire map image for panning.
  596. @param moveto dx,dy
  597. """
  598. dc = wx.BufferedDC(wx.ClientDC(self))
  599. dc.SetBackground(wx.Brush("White"))
  600. dc.Clear()
  601. self.dragimg = wx.DragImage(self._buffer)
  602. self.dragimg.BeginDrag((0, 0), self)
  603. self.dragimg.GetImageRect(moveto)
  604. self.dragimg.Move(moveto)
  605. self.dragimg.DoDrawImage(dc, moveto)
  606. self.dragimg.EndDrag()
  607. def DragItem(self, id, event):
  608. """!Drag an overlay decoration item
  609. """
  610. if id == 99 or id == '' or id == None: return
  611. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  612. x, y = self.lastpos
  613. dx = event.GetX() - x
  614. dy = event.GetY() - y
  615. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  616. r = self.pdc.GetIdBounds(id)
  617. if type(r) is list:
  618. r = wx.Rect(r[0], r[1], r[2], r[3])
  619. if id > 100: # text dragging
  620. rtop = (r[0],r[1]-r[3],r[2],r[3])
  621. r = r.Union(rtop)
  622. rleft = (r[0]-r[2],r[1],r[2],r[3])
  623. r = r.Union(rleft)
  624. self.pdc.TranslateId(id, dx, dy)
  625. r2 = self.pdc.GetIdBounds(id)
  626. if type(r2) is list:
  627. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  628. if id > 100: # text
  629. self.textdict[id]['bbox'] = r2
  630. self.textdict[id]['coords'][0] += dx
  631. self.textdict[id]['coords'][1] += dy
  632. r = r.Union(r2)
  633. r.Inflate(4,4)
  634. self.RefreshRect(r, False)
  635. self.lastpos = (event.GetX(), event.GetY())
  636. def MouseDraw(self, pdc = None, begin = None, end = None):
  637. """!Mouse box or line from 'begin' to 'end'
  638. If not given from self.mouse['begin'] to self.mouse['end'].
  639. """
  640. if not pdc:
  641. return
  642. if begin is None:
  643. begin = self.mouse['begin']
  644. if end is None:
  645. end = self.mouse['end']
  646. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  647. (self.mouse['use'], self.mouse['box'],
  648. begin[0], begin[1], end[0], end[1]))
  649. if self.mouse['box'] == "box":
  650. boxid = wx.ID_NEW
  651. mousecoords = [begin[0], begin[1],
  652. end[0], end[1]]
  653. r = pdc.GetIdBounds(boxid)
  654. if type(r) is list:
  655. r = wx.Rect(r[0], r[1], r[2], r[3])
  656. r.Inflate(4, 4)
  657. try:
  658. pdc.ClearId(boxid)
  659. except:
  660. pass
  661. self.RefreshRect(r, False)
  662. pdc.SetId(boxid)
  663. self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
  664. elif self.mouse['box'] == "line":
  665. self.lineid = wx.ID_NEW
  666. mousecoords = [begin[0], begin[1], \
  667. end[0], end[1]]
  668. x1 = min(begin[0],end[0])
  669. x2 = max(begin[0],end[0])
  670. y1 = min(begin[1],end[1])
  671. y2 = max(begin[1],end[1])
  672. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  673. r.Inflate(4,4)
  674. try:
  675. pdc.ClearId(self.lineid)
  676. except:
  677. pass
  678. self.RefreshRect(r, False)
  679. pdc.SetId(self.lineid)
  680. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = mousecoords)
  681. def DrawLines(self, pdc = None, polycoords = None):
  682. """!Draw polyline in PseudoDC
  683. Set self.pline to wx.NEW_ID + 1
  684. polycoords - list of polyline vertices, geographical coordinates
  685. (if not given, self.polycoords is used)
  686. """
  687. if not pdc:
  688. pdc = self.pdcTmp
  689. if not polycoords:
  690. polycoords = self.polycoords
  691. if len(polycoords) > 0:
  692. self.plineid = wx.ID_NEW + 1
  693. # convert from EN to XY
  694. coords = []
  695. for p in polycoords:
  696. coords.append(self.Cell2Pixel(p))
  697. self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
  698. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  699. (coords, self.plineid))
  700. return self.plineid
  701. return -1
  702. def DrawCross(self, pdc, coords, size, rotation = 0,
  703. text = None, textAlign = 'lr', textOffset = (5, 5)):
  704. """!Draw cross in PseudoDC
  705. @todo implement rotation
  706. @param pdc PseudoDC
  707. @param coord center coordinates
  708. @param rotation rotate symbol
  709. @param text draw also text (text, font, color, rotation)
  710. @param textAlign alignment (default 'lower-right')
  711. @textOffset offset for text (from center point)
  712. """
  713. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  714. (pdc, coords, size))
  715. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  716. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  717. self.lineid = wx.NewId()
  718. for lineCoords in coordsCross:
  719. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = lineCoords)
  720. if not text:
  721. return self.lineid
  722. if textAlign == 'ul':
  723. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  724. elif textAlign == 'ur':
  725. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  726. elif textAlign == 'lr':
  727. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  728. else:
  729. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  730. self.Draw(pdc, img = text,
  731. pdctype = 'text', coords = coord)
  732. return self.lineid
  733. def MouseActions(self, event):
  734. """!Mouse motion and button click notifier
  735. """
  736. if not self.processMouse:
  737. return
  738. # zoom with mouse wheel
  739. if event.GetWheelRotation() != 0:
  740. self.OnMouseWheel(event)
  741. # left mouse button pressed
  742. elif event.LeftDown():
  743. self.OnLeftDown(event)
  744. # left mouse button released
  745. elif event.LeftUp():
  746. self.OnLeftUp(event)
  747. # dragging
  748. elif event.Dragging():
  749. self.OnDragging(event)
  750. # double click
  751. elif event.ButtonDClick():
  752. self.OnButtonDClick(event)
  753. # middle mouse button pressed
  754. elif event.MiddleDown():
  755. self.OnMiddleDown(event)
  756. # middle mouse button relesed
  757. elif event.MiddleUp():
  758. self.OnMiddleUp(event)
  759. # right mouse button pressed
  760. elif event.RightDown():
  761. self.OnRightDown(event)
  762. # right mouse button released
  763. elif event.RightUp():
  764. self.OnRightUp(event)
  765. elif event.Entering():
  766. self.OnMouseEnter(event)
  767. elif event.Moving():
  768. self.OnMouseMoving(event)
  769. def OnMouseWheel(self, event):
  770. """!Mouse wheel moved
  771. """
  772. if not UserSettings.Get(group = 'display',
  773. key = 'mouseWheelZoom',
  774. subkey = 'enabled'):
  775. event.Skip()
  776. return
  777. self.processMouse = False
  778. current = event.GetPositionTuple()[:]
  779. wheel = event.GetWheelRotation()
  780. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  781. # zoom 1/2 of the screen, centered to current mouse position (TODO: settings)
  782. begin = (current[0] - self.Map.width / 4,
  783. current[1] - self.Map.height / 4)
  784. end = (current[0] + self.Map.width / 4,
  785. current[1] + self.Map.height / 4)
  786. if wheel > 0:
  787. zoomtype = 1
  788. else:
  789. zoomtype = -1
  790. if UserSettings.Get(group = 'display',
  791. key = 'mouseWheelZoom',
  792. subkey = 'selection'):
  793. zoomtype *= -1
  794. # zoom
  795. self.Zoom(begin, end, zoomtype)
  796. # redraw map
  797. self.UpdateMap()
  798. # update statusbar
  799. self.parent.StatusbarUpdate()
  800. self.Refresh()
  801. self.processMouse = True
  802. def OnDragging(self, event):
  803. """!Mouse dragging
  804. """
  805. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  806. current = event.GetPositionTuple()[:]
  807. previous = self.mouse['begin']
  808. move = (current[0] - previous[0],
  809. current[1] - previous[1])
  810. if hasattr(self, "digit"):
  811. digitToolbar = self.toolbar
  812. else:
  813. digitToolbar = None
  814. # dragging or drawing box with left button
  815. if self.mouse['use'] == 'pan' or \
  816. event.MiddleIsDown():
  817. self.DragMap(move)
  818. # dragging decoration overlay item
  819. elif (self.mouse['use'] == 'pointer' and
  820. not digitToolbar and
  821. self.dragid != None):
  822. self.DragItem(self.dragid, event)
  823. # dragging anything else - rubber band box or line
  824. else:
  825. if (self.mouse['use'] == 'pointer' and
  826. not digitToolbar):
  827. return
  828. self.mouse['end'] = event.GetPositionTuple()[:]
  829. if (event.LeftIsDown() and
  830. not (digitToolbar and
  831. digitToolbar.GetAction() in ("moveLine",) and
  832. self.digit.GetDisplay().GetSelected() > 0)):
  833. self.MouseDraw(pdc = self.pdcTmp)
  834. def OnLeftDown(self, event):
  835. """!Left mouse button pressed
  836. """
  837. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  838. self.mouse["use"])
  839. self.mouse['begin'] = event.GetPositionTuple()[:]
  840. if self.mouse["use"] in ["measure", "profile"]:
  841. # measure or profile
  842. if len(self.polycoords) == 0:
  843. self.mouse['end'] = self.mouse['begin']
  844. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  845. self.ClearLines(pdc=self.pdcTmp)
  846. else:
  847. self.mouse['begin'] = self.mouse['end']
  848. elif self.mouse['use'] in ('zoom', 'legend'):
  849. pass
  850. # vector digizer
  851. elif self.mouse["use"] == "pointer" and \
  852. hasattr(self, "digit"):
  853. if event.ControlDown():
  854. self.OnLeftDownUndo(event)
  855. else:
  856. self._onLeftDown(event)
  857. elif self.mouse['use'] == 'pointer':
  858. # get decoration or text id
  859. self.idlist = []
  860. self.dragid = ''
  861. self.lastpos = self.mouse['begin']
  862. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  863. self.hitradius)
  864. if 99 in idlist:
  865. idlist.remove(99)
  866. if idlist != []:
  867. self.dragid = idlist[0] #drag whatever is on top
  868. else:
  869. pass
  870. event.Skip()
  871. def OnLeftUp(self, event):
  872. """!Left mouse button released
  873. """
  874. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  875. self.mouse["use"])
  876. self.mouse['end'] = event.GetPositionTuple()[:]
  877. if self.mouse['use'] in ["zoom", "pan"]:
  878. # set region in zoom or pan
  879. begin = self.mouse['begin']
  880. end = self.mouse['end']
  881. if self.mouse['use'] == 'zoom':
  882. # set region for click (zero-width box)
  883. if begin[0] - end[0] == 0 or \
  884. begin[1] - end[1] == 0:
  885. # zoom 1/2 of the screen (TODO: settings)
  886. begin = (end[0] - self.Map.width / 4,
  887. end[1] - self.Map.height / 4)
  888. end = (end[0] + self.Map.width / 4,
  889. end[1] + self.Map.height / 4)
  890. self.Zoom(begin, end, self.zoomtype)
  891. # redraw map
  892. self.UpdateMap(render = True)
  893. # update statusbar
  894. self.parent.StatusbarUpdate()
  895. elif self.mouse["use"] == "query":
  896. # querying
  897. layers = self.GetSelectedLayer(multi = True)
  898. isRaster = False
  899. nVectors = 0
  900. for l in layers:
  901. if l.GetType() == 'raster':
  902. isRaster = True
  903. break
  904. if l.GetType() == 'vector':
  905. nVectors += 1
  906. if isRaster or nVectors > 1:
  907. self.parent.QueryMap(self.mouse['begin'][0],self.mouse['begin'][1])
  908. else:
  909. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  910. # clear temp canvas
  911. self.UpdateMap(render = False, renderVector = False)
  912. elif self.mouse["use"] == "queryVector":
  913. # editable mode for vector map layers
  914. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  915. # clear temp canvas
  916. self.UpdateMap(render = False, renderVector = False)
  917. elif self.mouse["use"] in ["measure", "profile"]:
  918. # measure or profile
  919. if self.mouse["use"] == "measure":
  920. self.parent.MeasureDist(self.mouse['begin'], self.mouse['end'])
  921. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  922. self.ClearLines(pdc = self.pdcTmp)
  923. self.DrawLines(pdc = self.pdcTmp)
  924. elif self.mouse["use"] == "pointer" and \
  925. not self.parent.IsStandalone() and \
  926. self.parent.GetLayerManager().gcpmanagement:
  927. # -> GCP manager
  928. if self.parent.GetToolbar('gcpdisp'):
  929. coord = self.Pixel2Cell(self.mouse['end'])
  930. if self.parent.MapWindow == self.parent.SrcMapWindow:
  931. coordtype = 'source'
  932. else:
  933. coordtype = 'target'
  934. self.parent.GetLayerManager().gcpmanagement.SetGCPData(coordtype, coord, self, confirm = True)
  935. self.UpdateMap(render = False, renderVector = False)
  936. elif self.mouse["use"] == "pointer" and \
  937. hasattr(self, "digit"):
  938. self._onLeftUp(event)
  939. elif (self.mouse['use'] == 'pointer' and
  940. self.dragid >= 0):
  941. # end drag of overlay decoration
  942. if self.dragid < 99 and self.dragid in self.overlays:
  943. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  944. elif self.dragid > 100 and self.dragid in self.textdict:
  945. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  946. else:
  947. pass
  948. self.dragid = None
  949. self.currtxtid = None
  950. elif self.mouse['use'] == 'legend':
  951. self.ResizeLegend(self.mouse["begin"], self.mouse["end"])
  952. self.parent.dialogs['legend'].FindWindowByName("resize").SetValue(False)
  953. self.Map.GetOverlay(1).SetActive(True)
  954. self.parent.MapWindow.SetCursor(self.parent.cursors["default"])
  955. self.parent.MapWindow.mouse['use'] = 'pointer'
  956. self.UpdateMap()
  957. def OnButtonDClick(self, event):
  958. """!Mouse button double click
  959. """
  960. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  961. self.mouse["use"])
  962. if self.mouse["use"] == "measure":
  963. # measure
  964. self.ClearLines(pdc=self.pdcTmp)
  965. self.polycoords = []
  966. self.mouse['use'] = 'pointer'
  967. self.mouse['box'] = 'point'
  968. self.mouse['end'] = [0, 0]
  969. self.Refresh()
  970. self.SetCursor(self.parent.cursors["default"])
  971. elif self.mouse["use"] != "profile" or \
  972. (self.mouse['use'] != 'pointer' and \
  973. hasattr(self, "digit")):
  974. # select overlay decoration options dialog
  975. clickposition = event.GetPositionTuple()[:]
  976. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  977. if idlist == []:
  978. return
  979. self.dragid = idlist[0]
  980. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  981. if self.dragid > 100:
  982. self.currtxtid = self.dragid
  983. self.parent.OnAddText(None)
  984. elif self.dragid == 0:
  985. self.parent.OnAddBarscale(None)
  986. elif self.dragid == 1:
  987. self.parent.OnAddLegend(None)
  988. def OnRightDown(self, event):
  989. """!Right mouse button pressed
  990. """
  991. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  992. self.mouse["use"])
  993. if hasattr(self, "digit"):
  994. self._onRightDown(event)
  995. event.Skip()
  996. def OnRightUp(self, event):
  997. """!Right mouse button released
  998. """
  999. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1000. self.mouse["use"])
  1001. if hasattr(self, "digit"):
  1002. self._onRightUp(event)
  1003. self.redrawAll = True
  1004. self.Refresh()
  1005. event.Skip()
  1006. def OnMiddleDown(self, event):
  1007. """!Middle mouse button pressed
  1008. """
  1009. if not event:
  1010. return
  1011. self.mouse['begin'] = event.GetPositionTuple()[:]
  1012. def OnMiddleUp(self, event):
  1013. """!Middle mouse button released
  1014. """
  1015. self.mouse['end'] = event.GetPositionTuple()[:]
  1016. # set region in zoom or pan
  1017. begin = self.mouse['begin']
  1018. end = self.mouse['end']
  1019. self.Zoom(begin, end, 0) # no zoom
  1020. # redraw map
  1021. self.UpdateMap(render = True)
  1022. # update statusbar
  1023. self.parent.StatusbarUpdate()
  1024. def OnMouseEnter(self, event):
  1025. """!Mouse entered window and no mouse buttons were pressed
  1026. """
  1027. if not self.parent.IsStandalone() and \
  1028. self.parent.GetLayerManager().gcpmanagement:
  1029. if self.parent.GetToolbar('gcpdisp'):
  1030. if not self.parent.MapWindow == self:
  1031. self.parent.MapWindow = self
  1032. self.parent.Map = self.Map
  1033. self.parent.UpdateActive(self)
  1034. # needed for wingrass
  1035. self.SetFocus()
  1036. else:
  1037. event.Skip()
  1038. def OnMouseMoving(self, event):
  1039. """!Motion event and no mouse buttons were pressed
  1040. """
  1041. if self.mouse["use"] == "pointer" and \
  1042. hasattr(self, "digit"):
  1043. self._onMouseMoving(event)
  1044. event.Skip()
  1045. def ClearLines(self, pdc = None):
  1046. """!Clears temporary drawn lines from PseudoDC
  1047. """
  1048. if not pdc:
  1049. pdc = self.pdcTmp
  1050. try:
  1051. pdc.ClearId(self.lineid)
  1052. pdc.RemoveId(self.lineid)
  1053. except:
  1054. pass
  1055. try:
  1056. pdc.ClearId(self.plineid)
  1057. pdc.RemoveId(self.plineid)
  1058. except:
  1059. pass
  1060. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1061. (self.lineid, self.plineid))
  1062. return True
  1063. def Pixel2Cell(self, (x, y)):
  1064. """!Convert image coordinates to real word coordinates
  1065. @param x, y image coordinates
  1066. @return easting, northing
  1067. @return None on error
  1068. """
  1069. try:
  1070. x = int(x)
  1071. y = int(y)
  1072. except:
  1073. return None
  1074. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1075. res = self.Map.region["ewres"]
  1076. else:
  1077. res = self.Map.region["nsres"]
  1078. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1079. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1080. east = w + x * res
  1081. north = n - y * res
  1082. return (east, north)
  1083. def Cell2Pixel(self, (east, north)):
  1084. """!Convert real word coordinates to image coordinates
  1085. """
  1086. try:
  1087. east = float(east)
  1088. north = float(north)
  1089. except:
  1090. return None
  1091. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1092. res = self.Map.region["ewres"]
  1093. else:
  1094. res = self.Map.region["nsres"]
  1095. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1096. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1097. x = (east - w) / res
  1098. y = (n - north) / res
  1099. return (x, y)
  1100. def ResizeLegend(self, begin, end):
  1101. w = abs(begin[0] - end[0])
  1102. h = abs(begin[1] - end[1])
  1103. if begin[0] < end[0]:
  1104. x = begin[0]
  1105. else:
  1106. x = end[0]
  1107. if begin[1] < end[1]:
  1108. y = begin[1]
  1109. else:
  1110. y = end[1]
  1111. screenRect = wx.Rect(x, y, w, h)
  1112. screenSize = self.GetClientSizeTuple()
  1113. at = [(screenSize[1] - (y + h)) / float(screenSize[1]) * 100,
  1114. (screenSize[1] - y) / float(screenSize[1]) * 100,
  1115. x / float(screenSize[0]) * 100,
  1116. (x + w) / float(screenSize[0]) * 100]
  1117. for i, subcmd in enumerate(self.overlays[1]['cmd']):
  1118. if subcmd.startswith('at='):
  1119. self.overlays[1]['cmd'][i] = "at=%d,%d,%d,%d" % (at[0], at[1], at[2], at[3])
  1120. self.Map.ChangeOverlay(1, True, command = self.overlays[1]['cmd'])
  1121. self.overlays[1]['coords'] = (0,0)
  1122. def Zoom(self, begin, end, zoomtype):
  1123. """!Calculates new region while (un)zoom/pan-ing
  1124. """
  1125. x1, y1 = begin
  1126. x2, y2 = end
  1127. newreg = {}
  1128. # threshold - too small squares do not make sense
  1129. # can only zoom to windows of > 5x5 screen pixels
  1130. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1131. if x1 > x2:
  1132. x1, x2 = x2, x1
  1133. if y1 > y2:
  1134. y1, y2 = y2, y1
  1135. # zoom in
  1136. if zoomtype > 0:
  1137. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1138. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1139. # zoom out
  1140. elif zoomtype < 0:
  1141. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1142. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1143. (self.Map.width - x2),
  1144. self.Map.height + 2 * \
  1145. (self.Map.height - y2)))
  1146. # pan
  1147. elif zoomtype == 0:
  1148. dx = x1 - x2
  1149. dy = y1 - y2
  1150. if dx == 0 and dy == 0:
  1151. dx = x1 - self.Map.width / 2
  1152. dy = y1 - self.Map.height / 2
  1153. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1154. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1155. self.Map.height + dy))
  1156. # if new region has been calculated, set the values
  1157. if newreg != {}:
  1158. # LL locations
  1159. if self.Map.projinfo['proj'] == 'll':
  1160. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1161. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1162. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1163. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1164. # calculate new center point and display resolution
  1165. self.Map.region['center_easting'] = ce
  1166. self.Map.region['center_northing'] = cn
  1167. self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
  1168. self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
  1169. if not self.parent.HasProperty('alignExtent') or \
  1170. self.parent.GetProperty('alignExtent'):
  1171. self.Map.AlignExtentFromDisplay()
  1172. else:
  1173. for k in ('n', 's', 'e', 'w'):
  1174. self.Map.region[k] = newreg[k]
  1175. if hasattr(self, "digit") and \
  1176. hasattr(self, "moveInfo"):
  1177. self._zoom(None)
  1178. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1179. self.Map.region['e'], self.Map.region['w'])
  1180. if self.redrawAll is False:
  1181. self.redrawAll = True
  1182. def ZoomBack(self):
  1183. """!Zoom to previous extents in zoomhistory list
  1184. """
  1185. zoom = list()
  1186. if len(self.zoomhistory) > 1:
  1187. self.zoomhistory.pop()
  1188. zoom = self.zoomhistory[-1]
  1189. # disable tool if stack is empty
  1190. if len(self.zoomhistory) < 2: # disable tool
  1191. toolbar = self.parent.GetMapToolbar()
  1192. toolbar.Enable('zoomBack', enable = False)
  1193. # zoom to selected region
  1194. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  1195. e = zoom[2], w = zoom[3],
  1196. update = True)
  1197. # update map
  1198. self.UpdateMap()
  1199. # update statusbar
  1200. self.parent.StatusbarUpdate()
  1201. def ZoomHistory(self, n, s, e, w):
  1202. """!Manages a list of last 10 zoom extents
  1203. @param n,s,e,w north, south, east, west
  1204. @return removed history item if exists (or None)
  1205. """
  1206. removed = None
  1207. self.zoomhistory.append((n,s,e,w))
  1208. if len(self.zoomhistory) > 10:
  1209. removed = self.zoomhistory.pop(0)
  1210. if removed:
  1211. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1212. (self.zoomhistory, removed))
  1213. else:
  1214. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1215. (self.zoomhistory))
  1216. # update toolbar
  1217. if len(self.zoomhistory) > 1:
  1218. enable = True
  1219. else:
  1220. enable = False
  1221. toolbar = self.parent.GetMapToolbar()
  1222. toolbar.Enable('zoomBack', enable)
  1223. return removed
  1224. def ResetZoomHistory(self):
  1225. """!Reset zoom history"""
  1226. self.zoomhistory = list()
  1227. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  1228. """!Set display extents to match selected raster
  1229. or vector map(s).
  1230. @param layers list of layers to be zoom to
  1231. @param ignoreNulls True to ignore null-values (valid only for rasters)
  1232. @param render True to re-render display
  1233. """
  1234. zoomreg = {}
  1235. if not layers:
  1236. layers = self.GetSelectedLayer(multi = True)
  1237. if not layers:
  1238. return
  1239. rast = []
  1240. vect = []
  1241. updated = False
  1242. for l in layers:
  1243. # only raster/vector layers are currently supported
  1244. if l.type == 'raster':
  1245. rast.append(l.GetName())
  1246. elif l.type == 'vector':
  1247. if hasattr(self, "digit") and \
  1248. self.toolbar.GetLayer() == l:
  1249. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1250. self.Map.GetRegion(n = n, s = s, w = w, e = e,
  1251. update = True)
  1252. updated = True
  1253. else:
  1254. vect.append(l.name)
  1255. elif l.type == 'rgb':
  1256. for rname in l.GetName().splitlines():
  1257. rast.append(rname)
  1258. if not updated:
  1259. self.Map.GetRegion(rast = rast,
  1260. vect = vect,
  1261. update = True)
  1262. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1263. self.Map.region['e'], self.Map.region['w'])
  1264. if render:
  1265. self.UpdateMap()
  1266. self.parent.StatusbarUpdate()
  1267. def ZoomToWind(self):
  1268. """!Set display geometry to match computational region
  1269. settings (set with g.region)
  1270. """
  1271. self.Map.region = self.Map.GetRegion()
  1272. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1273. self.Map.region['e'], self.Map.region['w'])
  1274. self.UpdateMap()
  1275. self.parent.StatusbarUpdate()
  1276. def ZoomToDefault(self):
  1277. """!Set display geometry to match default region settings
  1278. """
  1279. self.Map.region = self.Map.GetRegion(default = True)
  1280. self.Map.AdjustRegion() # aling region extent to the display
  1281. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1282. self.Map.region['e'], self.Map.region['w'])
  1283. self.UpdateMap()
  1284. self.parent.StatusbarUpdate()
  1285. def GoTo(self, e, n):
  1286. region = self.Map.GetCurrentRegion()
  1287. region['center_easting'], region['center_northing'] = e, n
  1288. dn = (region['nsres'] * region['rows']) / 2.
  1289. region['n'] = region['center_northing'] + dn
  1290. region['s'] = region['center_northing'] - dn
  1291. de = (region['ewres'] * region['cols']) / 2.
  1292. region['e'] = region['center_easting'] + de
  1293. region['w'] = region['center_easting'] - de
  1294. self.Map.AdjustRegion()
  1295. # add to zoom history
  1296. self.ZoomHistory(region['n'], region['s'],
  1297. region['e'], region['w'])
  1298. self.UpdateMap()
  1299. def DisplayToWind(self):
  1300. """!Set computational region (WIND file) to match display
  1301. extents
  1302. """
  1303. tmpreg = os.getenv("GRASS_REGION")
  1304. if tmpreg:
  1305. del os.environ["GRASS_REGION"]
  1306. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1307. # for user to set explicitly with g.region
  1308. new = self.Map.AlignResolution()
  1309. RunCommand('g.region',
  1310. parent = self,
  1311. overwrite = True,
  1312. n = new['n'],
  1313. s = new['s'],
  1314. e = new['e'],
  1315. w = new['w'],
  1316. rows = int(new['rows']),
  1317. cols = int(new['cols']))
  1318. if tmpreg:
  1319. os.environ["GRASS_REGION"] = tmpreg
  1320. def ZoomToSaved(self):
  1321. """!Set display geometry to match extents in
  1322. saved region file
  1323. """
  1324. dlg = SavedRegion(parent = self,
  1325. title = _("Zoom to saved region extents"),
  1326. loadsave='load')
  1327. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.wind:
  1328. dlg.Destroy()
  1329. return
  1330. if not grass.find_file(name = dlg.wind, element = 'windows')['name']:
  1331. wx.MessageBox(parent = self,
  1332. message = _("Region <%s> not found. Operation canceled.") % dlg.wind,
  1333. caption = _("Error"), style = wx.ICON_ERROR | wx.OK | wx.CENTRE)
  1334. dlg.Destroy()
  1335. return
  1336. self.Map.GetRegion(regionName = dlg.wind,
  1337. update = True)
  1338. dlg.Destroy()
  1339. self.ZoomHistory(self.Map.region['n'],
  1340. self.Map.region['s'],
  1341. self.Map.region['e'],
  1342. self.Map.region['w'])
  1343. self.UpdateMap()
  1344. def SaveDisplayRegion(self):
  1345. """!Save display extents to named region file.
  1346. """
  1347. dlg = SavedRegion(parent = self,
  1348. title = _("Save display extents to region file"),
  1349. loadsave='save')
  1350. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.wind:
  1351. dlg.Destroy()
  1352. return
  1353. # test to see if it already exists and ask permission to overwrite
  1354. if grass.find_file(name = dlg.wind, element = 'windows')['name']:
  1355. overwrite = wx.MessageBox(parent = self,
  1356. message = _("Region file <%s> already exists. "
  1357. "Do you want to overwrite it?") % (dlg.wind),
  1358. caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
  1359. if (overwrite == wx.YES):
  1360. self.SaveRegion(dlg.wind)
  1361. else:
  1362. self.SaveRegion(dlg.wind)
  1363. dlg.Destroy()
  1364. def SaveRegion(self, wind):
  1365. """!Save region settings
  1366. @param wind region name
  1367. """
  1368. new = self.Map.GetCurrentRegion()
  1369. tmpreg = os.getenv("GRASS_REGION")
  1370. if tmpreg:
  1371. del os.environ["GRASS_REGION"]
  1372. RunCommand('g.region',
  1373. overwrite = True,
  1374. parent = self,
  1375. flags = 'u',
  1376. n = new['n'],
  1377. s = new['s'],
  1378. e = new['e'],
  1379. w = new['w'],
  1380. rows = int(new['rows']),
  1381. cols = int(new['cols']),
  1382. save = wind)
  1383. if tmpreg:
  1384. os.environ["GRASS_REGION"] = tmpreg
  1385. def Distance(self, beginpt, endpt, screen = True):
  1386. """!Calculete distance
  1387. Ctypes required for LL-locations
  1388. @param beginpt first point
  1389. @param endpt second point
  1390. @param screen True for screen coordinates otherwise EN
  1391. """
  1392. if screen:
  1393. e1, n1 = self.Pixel2Cell(beginpt)
  1394. e2, n2 = self.Pixel2Cell(endpt)
  1395. else:
  1396. e1, n1 = beginpt
  1397. e2, n2 = endpt
  1398. dEast = (e2 - e1)
  1399. dNorth = (n2 - n1)
  1400. if self.parent.Map.projinfo['proj'] == 'll' and haveCtypes:
  1401. dist = gislib.G_distance(e1, n1, e2, n2)
  1402. else:
  1403. dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
  1404. return (dist, (dEast, dNorth))
  1405. def GetMap(self):
  1406. """!Get render.Map() instance"""
  1407. return self.Map