buffered.py 64 KB

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