buffered.py 65 KB

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