buffered.py 73 KB

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