buffered.py 73 KB

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