buffered.py 72 KB

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