buffered.py 66 KB

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