buffered.py 65 KB

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