buffered.py 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  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.mapfile = None # image file to be rendered
  125. self.img = None # wx.Image object (self.mapfile)
  126. # decoration overlays
  127. self.overlays = overlays
  128. self._overlayNames = {0: _("legend"), 1: _("scale bar"), 2: _("north arrow")}
  129. # images and their PseudoDC ID's for painting and dragging
  130. self.imagedict = {}
  131. self.select = {} # selecting/unselecting decorations for dragging
  132. self.textdict = {} # text, font, and color indexed by id
  133. # zoom objects
  134. self.zoomhistory = [] # list of past zoom extents
  135. self.currzoom = 0 # current set of extents in zoom history being used
  136. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  137. self.hitradius = 10 # distance for selecting map decorations
  138. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  139. # OnSize called to make sure the buffer is initialized.
  140. # This might result in OnSize getting called twice on some
  141. # platforms at initialization, but little harm done.
  142. ### self.OnSize(None)
  143. self._definePseudoDC()
  144. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  145. self.redrawAll = True
  146. # will store an off screen empty bitmap for saving to file
  147. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  148. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  149. # rerender when Map reports change
  150. self.Map.layerChanged.connect(self.OnUpdateMap)
  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.mapfile and 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. self.resize = False
  670. # was if self.Map.cmdfile and ...
  671. if self.IsAlwaysRenderEnabled() and self.img is None:
  672. render = True
  673. #
  674. # render background image if needed
  675. #
  676. # here was the change of the layertree rerender variable
  677. # but it is fully the problem of layertree
  678. # and so it is handled there
  679. # remove this comment when it is old enough
  680. try:
  681. if render:
  682. # update display size
  683. self.Map.ChangeMapSize(self.GetClientSize())
  684. if self._properties.resolution:
  685. # use computation region resolution for rendering
  686. windres = True
  687. else:
  688. windres = False
  689. self.mapfile = self.Map.Render(force = True,
  690. windres = windres)
  691. else:
  692. self.mapfile = self.Map.Render(force = False)
  693. except GException as e:
  694. GError(message = e.value)
  695. self.mapfile = None
  696. self.img = self.GetImage() # id=99
  697. #
  698. # clear pseudoDcs
  699. #
  700. for pdc in (self.pdc,
  701. self.pdcTransparent,
  702. self.pdcTmp):
  703. pdc.Clear()
  704. pdc.RemoveAll()
  705. #
  706. # draw background map image to PseudoDC
  707. #
  708. if not self.img:
  709. self.Draw(self.pdc, pdctype = 'clear')
  710. else:
  711. try:
  712. id = self.imagedict[self.img]['id']
  713. except:
  714. return False
  715. self.Draw(self.pdc, self.img, drawid = id)
  716. #
  717. # render vector map layer
  718. #
  719. if renderVector and hasattr(self, "digit"):
  720. self._updateMap()
  721. #
  722. # render overlays
  723. #
  724. for img in self.GetOverlay():
  725. # draw any active and defined overlays
  726. if self.imagedict[img]['layer'].IsActive():
  727. id = self.imagedict[img]['id']
  728. self.Draw(self.pdc, img = img, drawid = id,
  729. pdctype = self.overlays[id].pdcType, coords = self.overlays[id].coords)
  730. for id in self.textdict.keys():
  731. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  732. pdctype = 'text', coords = [10, 10, 10, 10])
  733. # optionally draw computational extent box
  734. self.DrawCompRegionExtent()
  735. #
  736. # redraw pdcTmp if needed
  737. #
  738. # draw registered graphics
  739. if len(self.graphicsSetList) > 0:
  740. penOrig = self.pen
  741. polypenOrig = self.polypen
  742. for item in self.graphicsSetList:
  743. try:
  744. item.Draw()
  745. except:
  746. GError(parent = self,
  747. message = _('Unable to draw registered graphics. '
  748. 'The graphics was unregistered.'))
  749. self.UnregisterGraphicsToDraw(item)
  750. self.pen = penOrig
  751. self.polypen = polypenOrig
  752. if len(self.polycoords) > 0:
  753. self.DrawLines(self.pdcTmp)
  754. Debug.msg (1, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s" % \
  755. (render, renderVector))
  756. return True
  757. def DrawCompRegionExtent(self):
  758. """Draw computational region extent in the display
  759. Display region is drawn as a blue box inside the computational region,
  760. computational region inside a display region as a red box).
  761. """
  762. if self._properties.showRegion:
  763. compReg = self.Map.GetRegion()
  764. dispReg = self.Map.GetCurrentRegion()
  765. reg = None
  766. if utils.isInRegion(dispReg, compReg):
  767. self.polypen = wx.Pen(colour = wx.Colour(0, 0, 255, 128), width = 3, style = wx.SOLID)
  768. reg = dispReg
  769. else:
  770. self.polypen = wx.Pen(colour = wx.Colour(255, 0, 0, 128),
  771. width = 3, style = wx.SOLID)
  772. reg = compReg
  773. regionCoords = []
  774. regionCoords.append((reg['w'], reg['n']))
  775. regionCoords.append((reg['e'], reg['n']))
  776. regionCoords.append((reg['e'], reg['s']))
  777. regionCoords.append((reg['w'], reg['s']))
  778. regionCoords.append((reg['w'], reg['n']))
  779. # draw region extent
  780. self.DrawLines(pdc=self.pdcTransparent, polycoords=regionCoords)
  781. def EraseMap(self):
  782. """Erase map canvas
  783. """
  784. self.Draw(self.pdc, pdctype = 'clear')
  785. if hasattr(self, "digit"):
  786. self.Draw(self.pdcVector, pdctype = 'clear')
  787. self.Draw(self.pdcTransparent, pdctype='clear')
  788. self.Draw(self.pdcTmp, pdctype = 'clear')
  789. self.Map.AbortAllThreads()
  790. def DragMap(self, moveto):
  791. """Drag the entire map image for panning.
  792. :param moveto: dx,dy
  793. """
  794. dc = wx.BufferedDC(wx.ClientDC(self))
  795. dc.SetBackground(wx.Brush("White"))
  796. dc.Clear()
  797. self.dragimg = wx.DragImage(self._buffer)
  798. self.dragimg.BeginDrag((0, 0), self)
  799. self.dragimg.GetImageRect(moveto)
  800. self.dragimg.Move(moveto)
  801. self.dragimg.DoDrawImage(dc, moveto)
  802. self.dragimg.EndDrag()
  803. def DragItem(self, id, coords):
  804. """Drag an overlay decoration item
  805. """
  806. if id == 99 or id == '' or id is None: return
  807. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  808. x, y = self.lastpos
  809. dx = coords[0] - x
  810. dy = coords[1] - y
  811. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  812. r = self.pdc.GetIdBounds(id)
  813. if type(r) is list:
  814. r = wx.Rect(r[0], r[1], r[2], r[3])
  815. if id > 100: # text dragging
  816. rtop = (r[0],r[1]-r[3],r[2],r[3])
  817. r = r.Union(rtop)
  818. rleft = (r[0]-r[2],r[1],r[2],r[3])
  819. r = r.Union(rleft)
  820. self.pdc.TranslateId(id, dx, dy)
  821. r2 = self.pdc.GetIdBounds(id)
  822. if type(r2) is list:
  823. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  824. if id > 100: # text
  825. self.textdict[id]['bbox'] = r2
  826. self.textdict[id]['coords'][0] += dx
  827. self.textdict[id]['coords'][1] += dy
  828. r = r.Union(r2)
  829. r.Inflate(4,4)
  830. self.RefreshRect(r, False)
  831. self.lastpos = (coords[0], coords[1])
  832. def MouseDraw(self, pdc = None, begin = None, end = None):
  833. """Mouse box or line from 'begin' to 'end'
  834. If not given from self.mouse['begin'] to self.mouse['end'].
  835. """
  836. if not pdc:
  837. return
  838. if begin is None:
  839. begin = self.mouse['begin']
  840. if end is None:
  841. end = self.mouse['end']
  842. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  843. (self.mouse['use'], self.mouse['box'],
  844. begin[0], begin[1], end[0], end[1]))
  845. if self.mouse['box'] == "box":
  846. boxid = wx.ID_NEW
  847. mousecoords = [begin[0], begin[1],
  848. end[0], end[1]]
  849. r = pdc.GetIdBounds(boxid)
  850. if type(r) is list:
  851. r = wx.Rect(r[0], r[1], r[2], r[3])
  852. r.Inflate(4, 4)
  853. try:
  854. pdc.ClearId(boxid)
  855. except:
  856. pass
  857. self.RefreshRect(r, False)
  858. pdc.SetId(boxid)
  859. self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
  860. elif self.mouse['box'] == "line":
  861. self.lineid = wx.ID_NEW
  862. mousecoords = [begin[0], begin[1], \
  863. end[0], end[1]]
  864. x1 = min(begin[0],end[0])
  865. x2 = max(begin[0],end[0])
  866. y1 = min(begin[1],end[1])
  867. y2 = max(begin[1],end[1])
  868. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  869. r.Inflate(4,4)
  870. try:
  871. pdc.ClearId(self.lineid)
  872. except:
  873. pass
  874. self.RefreshRect(r, False)
  875. pdc.SetId(self.lineid)
  876. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = mousecoords)
  877. def DrawLines(self, pdc = None, polycoords = None):
  878. """Draw polyline in PseudoDC
  879. Set self.pline to wx.NEW_ID + 1
  880. :param polycoords: list of polyline vertices, geographical
  881. coordinates (if not given, self.polycoords
  882. is used)
  883. """
  884. if not pdc:
  885. pdc = self.pdcTmp
  886. if not polycoords:
  887. polycoords = self.polycoords
  888. if len(polycoords) > 0:
  889. self.plineid = wx.ID_NEW + 1
  890. # convert from EN to XY
  891. coords = []
  892. for p in polycoords:
  893. coords.append(self.Cell2Pixel(p))
  894. self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
  895. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  896. (coords, self.plineid))
  897. return self.plineid
  898. return -1
  899. def DrawPolylines(self, pdc, coords, pen, drawid=None):
  900. """Draw polyline in PseudoDC.
  901. This is similar to DrawLines but this is used with GraphicsSet,
  902. coordinates should be always in pixels.
  903. :param pdc: PseudoDC
  904. :param coords: list of coordinates (pixel coordinates)
  905. :param pen: pen to be used
  906. :param drawid: id of the drawn object (used by PseudoDC)
  907. """
  908. Debug.msg (4, "BufferedWindow.DrawPolylines(): coords=%s" % coords)
  909. self.lineId = self.Draw(pdc, drawid=None, pdctype='polyline', coords=coords, pen=pen)
  910. return self.lineid
  911. def DrawCross(self, pdc, coords, size, rotation = 0, pen = None,
  912. text = None, textAlign = 'lr', textOffset = (5, 5), drawid=None):
  913. """Draw cross in PseudoDC
  914. .. todo::
  915. implement rotation
  916. :param pdc: PseudoDC
  917. :param coords: center coordinates (pixel coordinates)
  918. :param rotation: rotate symbol
  919. :param text: draw also text (text, font, color, rotation)
  920. :param textAlign: alignment (default 'lower-right')
  921. :param textOffset: offset for text (from center point)
  922. :param drawid: id of the drawn object (used by PseudoDC)
  923. """
  924. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  925. (pdc, coords, size))
  926. coordsCross = ((coords[0], coords[1] - size, coords[0], coords[1] + size),
  927. (coords[0] - size, coords[1], coords[0] + size, coords[1]))
  928. self.lineid = self.Draw(pdc, drawid=drawid, pdctype='lines', coords=coordsCross, pen=pen)
  929. if not text:
  930. return self.lineid
  931. if textAlign == 'ul':
  932. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  933. elif textAlign == 'ur':
  934. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  935. elif textAlign == 'lr':
  936. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  937. else:
  938. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  939. self.Draw(pdc, img = text,
  940. pdctype = 'text', coords = coord, pen = pen)
  941. return self.lineid
  942. def DrawRectangle(self, pdc, point1, point2, pen, brush=None, drawid=None):
  943. """Draw rectangle (not filled) in PseudoDC
  944. :param pdc: PseudoDC
  945. :param point1: top left corner (pixel coordinates)
  946. :param point2: bottom right corner (pixel coordinates)
  947. :param pen: pen
  948. :param drawid: id of the drawn object (used by PseudoDC)
  949. """
  950. Debug.msg(4, "BufferedWindow.DrawRectangle(): pdc=%s, point1=%s, point2=%s" % \
  951. (pdc, point1, point2))
  952. coords = [point1[0], point1[1], point2[0], point2[1]]
  953. self.lineid = self.Draw(pdc, drawid=drawid, pdctype='box', coords=coords,
  954. pen=pen, brush=brush)
  955. return self.lineid
  956. def DrawCircle(self, pdc, coords, radius, pen, brush=None, drawid=None):
  957. """Draw circle (not filled) in PseudoDC
  958. :param pdc: PseudoDC
  959. :param coords: center (pixel coordinates)
  960. :param radius: radius
  961. :param pen: pen
  962. :param drawid: id of the drawn object (used by PseudoDC)
  963. """
  964. Debug.msg(4, "BufferedWindow.DrawCircle(): pdc=%s, coords=%s, radius=%s" %
  965. (pdc, coords, radius))
  966. newcoords = [coords[0] - radius, coords[1] - radius,
  967. coords[0] + radius, coords[1] + radius]
  968. self.lineid = self.Draw(pdc, drawid=drawid, pdctype='circle', coords=newcoords,
  969. pen=pen, brush=brush)
  970. return self.lineid
  971. def DrawPolygon(self, pdc, coords, pen, brush=None, drawid=None):
  972. """Draws polygon from a list of points (do not append the first point)
  973. :param pdc: PseudoDC
  974. :param coords: list of coordinates (pixel coordinates)
  975. :param pen: pen
  976. :param drawid: id of the drawn object (used by PseudoDC)
  977. """
  978. # avid wx.GCDC assert
  979. if len(coords) <= 1:
  980. return None
  981. self.lineid = self.Draw(pdc, drawid=drawid, pdctype='polygon',
  982. coords=coords, pen=pen, brush=brush)
  983. return self.lineid
  984. def _computeZoomToPointAndRecenter(self, position, zoomtype):
  985. """Computes zoom parameters for recenter mode.
  986. Computes begin and end parameters for Zoom() method.
  987. Used for zooming by single click (not box)
  988. and mouse wheel zooming (zoom and recenter mode).
  989. """
  990. if zoomtype > 0:
  991. begin = (position[0] - self.Map.width / 4,
  992. position[1] - self.Map.height / 4)
  993. end = (position[0] + self.Map.width / 4,
  994. position[1] + self.Map.height / 4)
  995. else:
  996. begin = ((self.Map.width - position[0]) / 2,
  997. (self.Map.height - position[1]) / 2)
  998. end = (begin[0] + self.Map.width / 2,
  999. begin[1] + self.Map.height / 2)
  1000. return begin, end
  1001. def MouseActions(self, event):
  1002. """Mouse motion and button click notifier
  1003. """
  1004. if not self.processMouse:
  1005. return
  1006. # zoom with mouse wheel
  1007. if event.GetWheelRotation() != 0:
  1008. self.OnMouseWheel(event)
  1009. # left mouse button pressed
  1010. elif event.LeftDown():
  1011. self.OnLeftDown(event)
  1012. # left mouse button released
  1013. elif event.LeftUp():
  1014. self.OnLeftUp(event)
  1015. # dragging
  1016. elif event.Dragging():
  1017. self.OnDragging(event)
  1018. # double click
  1019. elif event.ButtonDClick():
  1020. self.OnButtonDClick(event)
  1021. # middle mouse button pressed
  1022. elif event.MiddleDown():
  1023. self.OnMiddleDown(event)
  1024. # middle mouse button relesed
  1025. elif event.MiddleUp():
  1026. self.OnMiddleUp(event)
  1027. # right mouse button pressed
  1028. elif event.RightDown():
  1029. self.OnRightDown(event)
  1030. # right mouse button released
  1031. elif event.RightUp():
  1032. self.OnRightUp(event)
  1033. elif event.Entering():
  1034. self.OnMouseEnter(event)
  1035. elif event.Moving():
  1036. pixelCoordinates = event.GetPositionTuple()[:]
  1037. coordinates = self.Pixel2Cell(pixelCoordinates)
  1038. self.mouseMoving.emit(x=coordinates[0], y=coordinates[1])
  1039. self.OnMouseMoving(event)
  1040. def OnMouseWheel(self, event):
  1041. """Mouse wheel moved
  1042. """
  1043. zoomBehaviour = UserSettings.Get(group = 'display',
  1044. key = 'mouseWheelZoom',
  1045. subkey = 'selection')
  1046. if zoomBehaviour == 2:
  1047. event.Skip()
  1048. return
  1049. self.processMouse = False
  1050. current = event.GetPositionTuple()[:]
  1051. wheel = event.GetWheelRotation()
  1052. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  1053. if wheel > 0:
  1054. zoomtype = 1
  1055. else:
  1056. zoomtype = -1
  1057. if UserSettings.Get(group = 'display',
  1058. key = 'scrollDirection',
  1059. subkey = 'selection'):
  1060. zoomtype *= -1
  1061. # zoom 1/2 of the screen (TODO: settings)
  1062. if zoomBehaviour == 0: # zoom and recenter
  1063. begin, end = self._computeZoomToPointAndRecenter(position = current, zoomtype = zoomtype)
  1064. elif zoomBehaviour == 1: # zoom to current cursor position
  1065. begin = (current[0]/2, current[1]/2)
  1066. end = ((self.Map.width - current[0])/2 + current[0],
  1067. (self.Map.height - current[1])/2 + current[1])
  1068. # zoom
  1069. self.Zoom(begin, end, zoomtype)
  1070. # redraw map
  1071. self.UpdateMap(delay=0.2)
  1072. self.Refresh()
  1073. self.processMouse = True
  1074. def OnDragging(self, event):
  1075. """Mouse dragging
  1076. """
  1077. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  1078. current = event.GetPositionTuple()[:]
  1079. previous = self.mouse['begin']
  1080. move = (current[0] - previous[0],
  1081. current[1] - previous[1])
  1082. if hasattr(self, "digit"):
  1083. digitToolbar = self.toolbar
  1084. else:
  1085. digitToolbar = None
  1086. # dragging or drawing box with left button
  1087. if self.mouse['use'] == 'pan' or \
  1088. event.MiddleIsDown():
  1089. self.DragMap(move)
  1090. # dragging decoration overlay item
  1091. elif (self.mouse['use'] == 'pointer' and
  1092. not digitToolbar and
  1093. self.dragid != None):
  1094. coords = event.GetPositionTuple()
  1095. self.DragItem(self.dragid, coords)
  1096. # dragging anything else - rubber band box or line
  1097. else:
  1098. if (self.mouse['use'] == 'pointer' and
  1099. not digitToolbar):
  1100. return
  1101. self.mouse['end'] = event.GetPositionTuple()[:]
  1102. if (event.LeftIsDown() and
  1103. not (digitToolbar and
  1104. digitToolbar.GetAction() in ("moveLine",) and
  1105. self.digit.GetDisplay().GetSelected() > 0)):
  1106. self.MouseDraw(pdc = self.pdcTmp)
  1107. def OnLeftDown(self, event):
  1108. """Left mouse button pressed
  1109. """
  1110. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  1111. self.mouse["use"])
  1112. self.mouse['begin'] = event.GetPositionTuple()[:]
  1113. # vector digizer
  1114. if self.mouse["use"] == "pointer" and \
  1115. hasattr(self, "digit"):
  1116. if event.ControlDown():
  1117. self.OnLeftDownUndo(event)
  1118. else:
  1119. self._onLeftDown(event)
  1120. elif self.mouse['use'] == 'pointer':
  1121. # get decoration or text id
  1122. idlist = []
  1123. self.dragid = ''
  1124. self.lastpos = self.mouse['begin']
  1125. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  1126. self.hitradius)
  1127. if 99 in idlist:
  1128. idlist.remove(99)
  1129. if idlist != []:
  1130. self.dragid = idlist[0] #drag whatever is on top
  1131. else:
  1132. pass
  1133. coords = self.Pixel2Cell(self.mouse['begin'])
  1134. self.mouseLeftDown.emit(x=coords[0], y=coords[1])
  1135. event.Skip()
  1136. def OnLeftUp(self, event):
  1137. """Left mouse button released
  1138. Emits mapQueried signal when mouse use is 'query'.
  1139. """
  1140. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  1141. self.mouse["use"])
  1142. self.mouse['end'] = event.GetPositionTuple()[:]
  1143. coordinates = self.Pixel2Cell(self.mouse['end'])
  1144. if self.mouse['use'] in ["zoom", "pan"]:
  1145. # set region in zoom or pan
  1146. begin = self.mouse['begin']
  1147. end = self.mouse['end']
  1148. if self.mouse['use'] == 'zoom':
  1149. # set region for click (zero-width box)
  1150. if begin[0] - end[0] == 0 or \
  1151. begin[1] - end[1] == 0:
  1152. begin, end = self._computeZoomToPointAndRecenter(position = end, zoomtype = self.zoomtype)
  1153. self.Zoom(begin, end, self.zoomtype)
  1154. # redraw map
  1155. self.UpdateMap(render = True)
  1156. elif self.mouse["use"] == "query":
  1157. self.mapQueried.emit(x=self.mouse['end'][0], y=self.mouse['end'][1])
  1158. elif self.mouse["use"] == "pointer" and \
  1159. hasattr(self, "digit"):
  1160. self._onLeftUp(event)
  1161. elif (self.mouse['use'] == 'pointer' and
  1162. self.dragid >= 0):
  1163. # end drag of overlay decoration
  1164. if self.dragid < 99 and self.dragid in self.overlays:
  1165. self.overlays[self.dragid].coords = self.pdc.GetIdBounds(self.dragid)
  1166. elif self.dragid > 100 and self.dragid in self.textdict:
  1167. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  1168. else:
  1169. pass
  1170. self.dragid = None
  1171. self.mouseLeftUpPointer.emit(x=coordinates[0], y=coordinates[1])
  1172. elif self.mouse['use'] == 'drawRegion':
  1173. coordinatesBegin = self.Pixel2Cell(self.mouse['begin'])
  1174. if coordinatesBegin[0] < coordinates[0]:
  1175. west = coordinatesBegin[0]
  1176. east = coordinates[0]
  1177. else:
  1178. west = coordinates[0]
  1179. east = coordinatesBegin[0]
  1180. if coordinatesBegin[1] < coordinates[1]:
  1181. south = coordinatesBegin[1]
  1182. north = coordinates[1]
  1183. else:
  1184. south = coordinates[1]
  1185. north = coordinatesBegin[1]
  1186. region = self.Map.GetRegion()
  1187. RunCommand('g.region',
  1188. parent=self,
  1189. flags='a', nsres=region['nsres'], ewres=region['ewres'],
  1190. n=north, s=south, e=east, w=west)
  1191. # redraw map
  1192. self.UpdateMap(render = False)
  1193. # TODO: decide which coordinates to send (e, n, mouse['begin'], mouse['end'])
  1194. self.mouseLeftUp.emit(x=coordinates[0], y=coordinates[1])
  1195. def OnButtonDClick(self, event):
  1196. """Mouse button double click
  1197. """
  1198. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  1199. self.mouse["use"])
  1200. screenCoords = event.GetPosition()
  1201. if self.mouse['use'] == 'pointer':
  1202. # select overlay decoration options dialog
  1203. idlist = self.pdc.FindObjects(screenCoords[0], screenCoords[1], self.hitradius)
  1204. if idlist:
  1205. self.dragid = idlist[0]
  1206. self.overlayActivated.emit(overlayId=self.dragid)
  1207. coords = self.Pixel2Cell(screenCoords)
  1208. self.mouseDClick.emit(x=coords[0], y=coords[1])
  1209. def OnRightDown(self, event):
  1210. """Right mouse button pressed
  1211. """
  1212. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1213. self.mouse["use"])
  1214. if hasattr(self, "digit"):
  1215. self._onRightDown(event)
  1216. event.Skip()
  1217. def OnRightUp(self, event):
  1218. """Right mouse button released
  1219. """
  1220. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1221. self.mouse["use"])
  1222. if hasattr(self, "digit"):
  1223. self._onRightUp(event)
  1224. self.redrawAll = True
  1225. self.Refresh()
  1226. coords = self.Pixel2Cell(event.GetPosition())
  1227. self.mouseRightUp.emit(x=coords[0], y=coords[1])
  1228. event.Skip()
  1229. def OnMiddleDown(self, event):
  1230. """Middle mouse button pressed
  1231. """
  1232. if not event:
  1233. return
  1234. self.mouse['begin'] = event.GetPositionTuple()[:]
  1235. def OnMiddleUp(self, event):
  1236. """Middle mouse button released
  1237. """
  1238. self.mouse['end'] = event.GetPositionTuple()[:]
  1239. # set region in zoom or pan
  1240. begin = self.mouse['begin']
  1241. end = self.mouse['end']
  1242. self.Zoom(begin, end, 0) # no zoom
  1243. # redraw map
  1244. self.UpdateMap(render = True)
  1245. def OnMouseEnter(self, event):
  1246. """Mouse entered window and no mouse buttons were pressed
  1247. Emits the mouseEntered signal.
  1248. """
  1249. self.mouseEntered.emit()
  1250. event.Skip()
  1251. def OnMouseMoving(self, event):
  1252. """Motion event and no mouse buttons were pressed
  1253. """
  1254. if self.mouse["use"] == "pointer" and \
  1255. hasattr(self, "digit"):
  1256. self._onMouseMoving(event)
  1257. event.Skip()
  1258. def OnCopyCoordinates(self, event):
  1259. """Copy coordinates to cliboard"""
  1260. e, n = self.GetLastEN()
  1261. if wx.TheClipboard.Open():
  1262. do = wx.TextDataObject()
  1263. # TODO: put delimiter in settings and apply also for Go to in statusbar
  1264. delim = ','
  1265. do.SetText(str(e) + delim + str(n))
  1266. wx.TheClipboard.SetData(do)
  1267. wx.TheClipboard.Close()
  1268. def OnShowStatusbar(self, event):
  1269. """Show/hide statusbar"""
  1270. self._giface.ShowStatusbar(not self._giface.IsStatusbarShown())
  1271. def OnShowAllToolbars(self, event):
  1272. """Show/hide all toolbars"""
  1273. self._giface.ShowAllToolbars(not self._giface.AreAllToolbarsShown())
  1274. def ClearLines(self, pdc = None):
  1275. """Clears temporary drawn lines from PseudoDC
  1276. """
  1277. if not pdc:
  1278. pdc = self.pdcTmp
  1279. try:
  1280. pdc.ClearId(self.lineid)
  1281. pdc.RemoveId(self.lineid)
  1282. except:
  1283. pass
  1284. try:
  1285. pdc.ClearId(self.plineid)
  1286. pdc.RemoveId(self.plineid)
  1287. except:
  1288. pass
  1289. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1290. (self.lineid, self.plineid))
  1291. return True
  1292. def Pixel2Cell(self, xyCoords):
  1293. """Convert image coordinates to real word coordinates
  1294. :param xyCoords: image coordinates
  1295. :return: easting, northing
  1296. :return: None on error
  1297. """
  1298. try:
  1299. x = int(xyCoords[0])
  1300. y = int(xyCoords[1])
  1301. except:
  1302. return None
  1303. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1304. res = self.Map.region["ewres"]
  1305. else:
  1306. res = self.Map.region["nsres"]
  1307. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1308. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1309. east = w + x * res
  1310. north = n - y * res
  1311. return (east, north)
  1312. def Cell2Pixel(self, enCoords):
  1313. """Convert real word coordinates to image coordinates
  1314. """
  1315. try:
  1316. east = float(enCoords[0])
  1317. north = float(enCoords[1])
  1318. except:
  1319. return None
  1320. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1321. res = self.Map.region["ewres"]
  1322. else:
  1323. res = self.Map.region["nsres"]
  1324. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1325. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1326. x = (east - w) / res
  1327. y = (n - north) / res
  1328. return (x, y)
  1329. def Zoom(self, begin, end, zoomtype):
  1330. """Calculates new region while (un)zoom/pan-ing
  1331. """
  1332. x1, y1 = begin
  1333. x2, y2 = end
  1334. newreg = {}
  1335. # threshold - too small squares do not make sense
  1336. # can only zoom to windows of > 5x5 screen pixels
  1337. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1338. if x1 > x2:
  1339. x1, x2 = x2, x1
  1340. if y1 > y2:
  1341. y1, y2 = y2, y1
  1342. # zoom in
  1343. if zoomtype > 0:
  1344. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1345. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1346. # zoom out
  1347. elif zoomtype < 0:
  1348. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1349. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1350. (self.Map.width - x2),
  1351. self.Map.height + 2 * \
  1352. (self.Map.height - y2)))
  1353. # pan
  1354. elif zoomtype == 0:
  1355. dx = x1 - x2
  1356. dy = y1 - y2
  1357. if dx == 0 and dy == 0:
  1358. dx = x1 - self.Map.width / 2
  1359. dy = y1 - self.Map.height / 2
  1360. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1361. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1362. self.Map.height + dy))
  1363. # if new region has been calculated, set the values
  1364. if newreg != {}:
  1365. # LL locations
  1366. if self.Map.projinfo['proj'] == 'll':
  1367. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1368. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1369. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1370. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1371. # calculate new center point and display resolution
  1372. self.Map.region['center_easting'] = ce
  1373. self.Map.region['center_northing'] = cn
  1374. self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
  1375. self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
  1376. if self._properties.alignExtent:
  1377. self.Map.AlignExtentFromDisplay()
  1378. else:
  1379. for k in ('n', 's', 'e', 'w'):
  1380. self.Map.region[k] = newreg[k]
  1381. if hasattr(self, "digit") and \
  1382. hasattr(self, "moveInfo"):
  1383. self._zoom(None)
  1384. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1385. self.Map.region['e'], self.Map.region['w'])
  1386. if self.redrawAll is False:
  1387. self.redrawAll = True
  1388. def ZoomBack(self):
  1389. """Zoom to previous extents in zoomhistory list
  1390. Emits zoomChanged signal.
  1391. Emits zoomHistoryUnavailable signal when stack is empty.
  1392. """
  1393. Debug.msg(4, "BufferedWindow.ZoomBack(): hist)=%s" % self.zoomhistory)
  1394. zoom = list()
  1395. if len(self.zoomhistory) > 1:
  1396. self.zoomhistory.pop()
  1397. zoom = self.zoomhistory[-1]
  1398. if len(self.zoomhistory) < 2:
  1399. self.zoomHistoryUnavailable.emit()
  1400. # zoom to selected region
  1401. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  1402. e = zoom[2], w = zoom[3],
  1403. update = True)
  1404. # update map
  1405. self.UpdateMap()
  1406. self.zoomChanged.emit()
  1407. def ZoomHistory(self, n, s, e, w):
  1408. """Manages a list of last 10 zoom extents
  1409. Emits zoomChanged signal.
  1410. Emits zoomHistoryAvailable signal when stack is not empty.
  1411. Emits zoomHistoryUnavailable signal when stack is empty.
  1412. All methods which are changing zoom should call this method
  1413. to make a record in the history. The signal zoomChanged will be
  1414. then emitted automatically.
  1415. :param n,s,e,w: north, south, east, west
  1416. :return: removed history item if exists (or None)
  1417. """
  1418. removed = None
  1419. self.zoomhistory.append((n,s,e,w))
  1420. if len(self.zoomhistory) > 10:
  1421. removed = self.zoomhistory.pop(0)
  1422. if removed:
  1423. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1424. (self.zoomhistory, removed))
  1425. else:
  1426. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1427. (self.zoomhistory))
  1428. # update toolbar
  1429. if len(self.zoomhistory) > 1:
  1430. self.zoomHistoryAvailable.emit()
  1431. else:
  1432. self.zoomHistoryUnavailable.emit()
  1433. self.zoomChanged.emit()
  1434. return removed
  1435. def InitZoomHistory(self):
  1436. """Initializes zoom history.
  1437. .. todo::
  1438. First item is handled in some special way. Improve the
  1439. documentation or fix the code.
  1440. It does not emits any signals.
  1441. This method can be possibly removed when the history will solve the
  1442. fist item in different way or when GCP manager (and possibly others)
  1443. will handle Map variable in the way that it will be prepared for
  1444. MapWindow/BufferedWindow and thus usable to initialize history.
  1445. """
  1446. self.zoomhistory.append((self.Map.region['n'],
  1447. self.Map.region['s'],
  1448. self.Map.region['e'],
  1449. self.Map.region['w']))
  1450. Debug.msg(4, "BufferedWindow.InitZoomHistory(): hist=%s" %
  1451. (self.zoomhistory))
  1452. def ResetZoomHistory(self):
  1453. """Reset zoom history"""
  1454. self.zoomhistory = list()
  1455. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  1456. """Set display extents to match selected raster
  1457. or vector map(s).
  1458. :param layers: list of layers to be zoom to
  1459. :param ignoreNulls: True to ignore null-values (valid only for rasters)
  1460. :param render: True to re-render display
  1461. """
  1462. if not layers:
  1463. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  1464. layers = [layer.maplayer for layer in layers]
  1465. if not layers:
  1466. return
  1467. rast = []
  1468. rast3d = None
  1469. vect = []
  1470. updated = False
  1471. for l in layers:
  1472. # only one raster is used: g.region does not support multiple
  1473. if l.type == 'raster':
  1474. rast.append(l.GetName())
  1475. elif l.type == '3d-raster':
  1476. rast3d = l.GetName()
  1477. elif l.type == 'vector':
  1478. if hasattr(self, "digit") and \
  1479. self.toolbar.GetLayer() == l:
  1480. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1481. self.Map.GetRegion(n = n, s = s, w = w, e = e,
  1482. update = True)
  1483. updated = True
  1484. else:
  1485. vect.append(l.name)
  1486. elif l.type == 'rgb':
  1487. for rname in l.GetName().splitlines():
  1488. rast.append(rname)
  1489. if not updated:
  1490. self.Map.GetRegion(rast=rast,
  1491. rast3d=rast3d,
  1492. vect=vect,
  1493. zoom=ignoreNulls,
  1494. update=True)
  1495. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1496. self.Map.region['e'], self.Map.region['w'])
  1497. if render:
  1498. self.UpdateMap()
  1499. def ZoomToWind(self):
  1500. """Set display geometry to match computational region
  1501. settings (set with g.region)
  1502. """
  1503. self.Map.region = self.Map.GetRegion()
  1504. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1505. self.Map.region['e'], self.Map.region['w'])
  1506. self.UpdateMap()
  1507. def ZoomToDefault(self):
  1508. """Set display geometry to match default region settings
  1509. """
  1510. self.Map.region = self.Map.GetRegion(default = True)
  1511. self.Map.AdjustRegion() # aling region extent to the display
  1512. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1513. self.Map.region['e'], self.Map.region['w'])
  1514. self.UpdateMap()
  1515. def GoTo(self, e, n):
  1516. region = self.Map.GetCurrentRegion()
  1517. region['center_easting'], region['center_northing'] = e, n
  1518. dn = (region['nsres'] * region['rows']) / 2.
  1519. region['n'] = region['center_northing'] + dn
  1520. region['s'] = region['center_northing'] - dn
  1521. de = (region['ewres'] * region['cols']) / 2.
  1522. region['e'] = region['center_easting'] + de
  1523. region['w'] = region['center_easting'] - de
  1524. self.Map.AdjustRegion()
  1525. # add to zoom history
  1526. self.ZoomHistory(region['n'], region['s'],
  1527. region['e'], region['w'])
  1528. self.UpdateMap()
  1529. def DisplayToWind(self):
  1530. """Set computational region (WIND file) to match display
  1531. extents
  1532. """
  1533. tmpreg = os.getenv("GRASS_REGION")
  1534. if tmpreg:
  1535. del os.environ["GRASS_REGION"]
  1536. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1537. # for user to set explicitly with g.region
  1538. new = self.Map.AlignResolution()
  1539. RunCommand('g.region',
  1540. parent = self,
  1541. overwrite = True,
  1542. n = new['n'],
  1543. s = new['s'],
  1544. e = new['e'],
  1545. w = new['w'],
  1546. rows = int(new['rows']),
  1547. cols = int(new['cols']))
  1548. if tmpreg:
  1549. os.environ["GRASS_REGION"] = tmpreg
  1550. self.UpdateMap(render = False)
  1551. def SetRegion(self, zoomOnly=True):
  1552. """Set display extents/compulational region from named region
  1553. file.
  1554. :param zoomOnly: zoom to named region only (computational region is not saved)
  1555. """
  1556. if zoomOnly:
  1557. label = _('Zoom to saved region extents')
  1558. else:
  1559. label = _('Set compulational region from named region')
  1560. dlg = SavedRegion(parent = self,
  1561. title = label,
  1562. loadsave = 'load')
  1563. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1564. dlg.Destroy()
  1565. return
  1566. region = dlg.GetName()
  1567. if not grass.find_file(name = region, element = 'windows')['name']:
  1568. GError(parent = self,
  1569. message = _("Region <%s> not found. Operation canceled.") % region)
  1570. dlg.Destroy()
  1571. return
  1572. dlg.Destroy()
  1573. if zoomOnly:
  1574. self.Map.GetRegion(regionName = region,
  1575. update = True)
  1576. self.ZoomHistory(self.Map.region['n'],
  1577. self.Map.region['s'],
  1578. self.Map.region['e'],
  1579. self.Map.region['w'])
  1580. else:
  1581. # set computation region from named region file
  1582. RunCommand('g.region',
  1583. parent = self,
  1584. region = region)
  1585. self.UpdateMap()
  1586. def SaveRegion(self, display = True):
  1587. """Save display extents/compulational region to named region
  1588. file.
  1589. :param display: True for display extends otherwise computational region
  1590. """
  1591. if display:
  1592. title = _("Save display extents to region file")
  1593. else:
  1594. title = _("Save computational region to region file")
  1595. dlg = SavedRegion(parent = self, title = title, loadsave = 'save')
  1596. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1597. dlg.Destroy()
  1598. return
  1599. # test to see if it already exists and ask permission to overwrite
  1600. if grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
  1601. overwrite = wx.MessageBox(parent = self,
  1602. message = _("Region file <%s> already exists. "
  1603. "Do you want to overwrite it?") % (dlg.GetName()),
  1604. caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
  1605. if overwrite != wx.YES:
  1606. dlg.Destroy()
  1607. return
  1608. if display:
  1609. self._saveDisplayRegion(dlg.GetName())
  1610. else:
  1611. self._saveCompRegion(dlg.GetName())
  1612. dlg.Destroy()
  1613. def _saveCompRegion(self, name):
  1614. """Save region settings to region file
  1615. :param name: region name
  1616. """
  1617. RunCommand('g.region',
  1618. overwrite = True,
  1619. parent = self,
  1620. flags = 'u',
  1621. save = name)
  1622. def _saveDisplayRegion(self, name):
  1623. """Save display extents to region file
  1624. :param name: region name
  1625. """
  1626. new = self.Map.GetCurrentRegion()
  1627. tmpreg = os.getenv("GRASS_REGION")
  1628. if tmpreg:
  1629. del os.environ["GRASS_REGION"]
  1630. RunCommand('g.region',
  1631. overwrite = True,
  1632. parent = self,
  1633. flags = 'u',
  1634. n = new['n'],
  1635. s = new['s'],
  1636. e = new['e'],
  1637. w = new['w'],
  1638. rows = int(new['rows']),
  1639. cols = int(new['cols']),
  1640. save = name)
  1641. if tmpreg:
  1642. os.environ["GRASS_REGION"] = tmpreg
  1643. def Distance(self, beginpt, endpt, screen = True):
  1644. """Calculates distance
  1645. Ctypes required for LL-locations
  1646. :param beginpt: first point
  1647. :param endpt: second point
  1648. :param screen: True for screen coordinates otherwise EN
  1649. """
  1650. if screen:
  1651. e1, n1 = self.Pixel2Cell(beginpt)
  1652. e2, n2 = self.Pixel2Cell(endpt)
  1653. else:
  1654. e1, n1 = beginpt
  1655. e2, n2 = endpt
  1656. dEast = (e2 - e1)
  1657. dNorth = (n2 - n1)
  1658. if self.Map.projinfo['proj'] == 'll' and haveCtypes:
  1659. dist = gislib.G_distance(e1, n1, e2, n2)
  1660. else:
  1661. dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
  1662. return (dist, (dEast, dNorth))
  1663. def GetMap(self):
  1664. """Get render.Map() instance"""
  1665. return self.Map
  1666. def RegisterGraphicsToDraw(self, graphicsType, pdc=None, setStatusFunc=None, drawFunc=None,
  1667. mapCoords=True):
  1668. """This method registers graphics to draw.
  1669. :param type: (string) - graphics type: "point", "line" or "rectangle"
  1670. :param pdc: PseudoDC object, default is pdcTmp
  1671. :param setStatusFunc: function called before drawing each item
  1672. Status function should be in this form:
  1673. setStatusFunc(item, itemOrderNum)
  1674. item passes instance of GraphicsSetItem
  1675. which will be drawn itemOrderNum number of item
  1676. in drawing order (from O)
  1677. Hidden items are also counted in drawing order.
  1678. :type setStatusFunc: function
  1679. :param drawFunc: defines own function for drawing, if function
  1680. is not defined DrawCross method is used for
  1681. type "point", DrawLines method for type "line",
  1682. DrawRectangle for "rectangle".
  1683. :param mapCoords: True if map coordinates should be set by user, otherwise pixels
  1684. :return: reference to GraphicsSet, which was added.
  1685. """
  1686. if not pdc:
  1687. pdc = self.pdcTmp
  1688. item = GraphicsSet(parentMapWin=self,
  1689. graphicsType=graphicsType,
  1690. pdc=pdc,
  1691. setStatusFunc=setStatusFunc,
  1692. drawFunc=drawFunc,
  1693. mapCoords=mapCoords)
  1694. self.graphicsSetList.append(item)
  1695. return item
  1696. def UnregisterGraphicsToDraw(self, item):
  1697. """Unregisteres GraphicsSet instance
  1698. :param item: (GraphicsSetItem) - item to unregister
  1699. :return: True - if item was unregistered
  1700. :return: False - if item was not found
  1701. """
  1702. if item in self.graphicsSetList:
  1703. self.graphicsSetList.remove(item)
  1704. return True
  1705. return False