buffered.py 74 KB

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