buffered.py 71 KB

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