buffered.py 76 KB

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