buffered.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258
  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):
  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._busy = wx.BusyInfo(message=_("Please wait, exporting image..."),
  587. parent=self)
  588. wx.Yield()
  589. self.Map.ChangeMapSize((width, height))
  590. self.Map.Render(force=True, windres=self._properties.resolution)
  591. renderMgr = self.Map.GetRenderMgr()
  592. renderMgr.renderDone.disconnect(self._updateMFinished)
  593. renderMgr.renderDone.connect(self._saveToFileDone)
  594. def _saveToFileDone(self):
  595. renderMgr = self.Map.GetRenderMgr()
  596. renderMgr.renderDone.disconnect(self._saveToFileDone)
  597. ibuffer = wx.EmptyBitmap(
  598. max(1, self.Map.width),
  599. max(1, self.Map.height))
  600. img = self.GetImage()
  601. self.pdc.RemoveAll()
  602. self.Draw(self.pdc, img, drawid=99)
  603. # compute size ratio to move overlay accordingly
  604. cSize = self.GetClientSizeTuple()
  605. ratio = float(
  606. self.Map.width) / cSize[0], float(self.Map.height) / cSize[1]
  607. # redraw legend, scalebar
  608. for img in self.GetOverlay():
  609. # draw any active and defined overlays
  610. if self.imagedict[img]['layer'].IsActive():
  611. id = self.imagedict[img]['id']
  612. coords = int(ratio[0] * self.overlays[id].coords[0]),\
  613. int(ratio[1] * self.overlays[id].coords[1])
  614. self.Draw(self.pdc, img=img, drawid=id,
  615. pdctype=self.overlays[id].pdcType, coords=coords)
  616. # redraw text labels
  617. for id in self.textdict.keys():
  618. textinfo = self.textdict[id]
  619. oldCoords = textinfo['coords']
  620. textinfo['coords'] = ratio[0] * textinfo['coords'][0],\
  621. ratio[1] * textinfo['coords'][1]
  622. self.Draw(self.pdc, img=self.textdict[id], drawid=id,
  623. pdctype='text')
  624. # set back old coordinates
  625. textinfo['coords'] = oldCoords
  626. dc = wx.BufferedDC(None, ibuffer)
  627. dc.Clear()
  628. # probably does nothing, removed from wxPython 2.9
  629. # self.PrepareDC(dc)
  630. self.pdc.DrawToDC(dc)
  631. if self.digit:
  632. self.pdcVector.DrawToDC(dc)
  633. ibuffer.SaveFile(self._fileName, self._fileType)
  634. self._busy.Destroy()
  635. del self._busy
  636. del self._fileName
  637. del self._fileType
  638. renderMgr.renderDone.connect(self._updateMFinished)
  639. self.UpdateMap(render=True)
  640. self.Refresh()
  641. def GetOverlay(self):
  642. """Converts rendered overlay files to wx.Image
  643. Updates self.imagedict
  644. :return: list of images
  645. """
  646. imgs = []
  647. for overlay in self.Map.GetListOfLayers(ltype="overlay", active=True):
  648. if overlay.mapfile is not None and os.path.isfile(
  649. overlay.mapfile) and os.path.getsize(
  650. overlay.mapfile):
  651. img = utils.autoCropImageFromFile(overlay.mapfile)
  652. for key in self.imagedict.keys():
  653. if self.imagedict[key]['id'] == overlay.id:
  654. del self.imagedict[key]
  655. self.imagedict[img] = {'id': overlay.id,
  656. 'layer': overlay}
  657. imgs.append(img)
  658. return imgs
  659. def GetImage(self):
  660. """Converts redered map files to wx.Image
  661. Updates self.imagedict (id=99)
  662. :return: wx.Image instance (map composition)
  663. """
  664. imgId = 99
  665. if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  666. os.path.getsize(self.Map.mapfile):
  667. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  668. else:
  669. img = None
  670. for key in self.imagedict.keys():
  671. if self.imagedict[key]['id'] == imgId:
  672. del self.imagedict[key]
  673. self.imagedict[img] = {'id': imgId}
  674. return img
  675. def SetAlwaysRenderEnabled(self, alwaysRender=True):
  676. self.alwaysRender = alwaysRender
  677. def IsAlwaysRenderEnabled(self):
  678. return self.alwaysRender
  679. def UpdateMap(self, render=True, renderVector=True, delay=0.0):
  680. """Updates the canvas anytime there is a change to the
  681. underlaying images or to the geometry of the canvas.
  682. This method should not be called directly.
  683. .. todo::
  684. change direct calling of UpdateMap method to emitting grass
  685. interface updateMap signal
  686. .. todo::
  687. consider using strong/weak signal instead of delay limit in
  688. giface
  689. :param render: re-render map composition
  690. :param renderVector: re-render vector map layer enabled for editing (used for digitizer)
  691. :param delay: defines time threshold in seconds for postponing
  692. rendering to merge more update requests.
  693. If another request comes within the limit, rendering is delayed
  694. again. Next delay limit is chosen according to the smallest
  695. delay value of all requests which have come during waiting period.
  696. Let say that first UpdateMap request come with 5 second delay
  697. limit. After 4 seconds of waiting another UpdateMap request
  698. come with delay limit of 2.5 seconds. New waiting period is set
  699. to 2.5 seconds, because limit of the second request is the
  700. smallest. If no other request comes rendering will be done
  701. after 6.5 seconds from the first request.
  702. Arguments 'render' and 'renderVector' have priority for True.
  703. It means that if more UpdateMap requests come within waiting
  704. period and at least one request has argument set for True, map
  705. will be updated with the True value of the argument.
  706. """
  707. if self.timerRunId is None or delay < self.updDelay:
  708. self.updDelay = delay
  709. if render:
  710. self.render = render
  711. if renderVector:
  712. self.renderVector = renderVector
  713. updTime = time.time()
  714. self.lastUpdateMapReq = updTime
  715. if self.updDelay <= 0.0:
  716. self._runUpdateMap()
  717. else:
  718. self.timerRunId = self.renderTimingThr.GetId()
  719. self.renderTimingThr.Run(callable=self._timingFunction,
  720. ondone=self._onUpdateMap,
  721. pid=self.timerRunId)
  722. def _timingFunction(self, pid):
  723. """Timer measuring elapsed time, since last update request.
  724. It terminates, when delay limit is exceeded.
  725. :param pid: id which defines whether it is newest timer, or
  726. there is another one (representing newer Update map
  727. request). If it is not the newest, it is terminated.
  728. """
  729. while True:
  730. updTime = time.time()
  731. time.sleep(.01)
  732. if updTime > self.lastUpdateMapReq + self.updDelay or pid != self.timerRunId:
  733. return
  734. def _onUpdateMap(self, event):
  735. if self.timerRunId == event.pid:
  736. self._runUpdateMap()
  737. def _runUpdateMap(self):
  738. """Update map when delay limit is over."""
  739. self.timerRunId = None
  740. self._updateM(self.render, self.renderVector)
  741. self.render = self.renderVector = False
  742. def _updateM(self, render=True, renderVector=True):
  743. """
  744. :func:`UpdateMap` for arguments description.
  745. """
  746. Debug.msg(1, "BufferedWindow.UpdateMap(): started "
  747. "(render=%s, renderVector=%s)" % (render, renderVector))
  748. self.resize = False
  749. # was if self.Map.cmdfile and ...
  750. if self.IsAlwaysRenderEnabled() and self.img is None:
  751. render = True
  752. try:
  753. if render:
  754. # update display size
  755. self.Map.ChangeMapSize(self.GetClientSize())
  756. self.Map.Render(force=render,
  757. windres=self._properties.resolution)
  758. except GException as e:
  759. GError(message=e.value)
  760. def _updateMFinished(self, renderVector=True):
  761. Debug.msg(1, "BufferedWindow.UpdateMap(): finished")
  762. self.img = self.GetImage() # id=99
  763. #
  764. # clear pseudoDcs
  765. #
  766. for pdc in (self.pdc,
  767. self.pdcTransparent,
  768. self.pdcTmp):
  769. pdc.Clear()
  770. pdc.RemoveAll()
  771. #
  772. # draw background map image to PseudoDC
  773. #
  774. if not self.img:
  775. self.Draw(self.pdc, pdctype='clear')
  776. else:
  777. try:
  778. id = self.imagedict[self.img]['id']
  779. except Exception as e:
  780. Debug.mgs(1, "UpdateMap() failed: %s", e)
  781. return False
  782. self.Draw(self.pdc, self.img, drawid=id)
  783. #
  784. # render vector map layer
  785. #
  786. if renderVector and self.digit:
  787. self._updateMap()
  788. #
  789. # render overlays
  790. #
  791. for img in self.GetOverlay():
  792. # draw any active and defined overlays
  793. if self.imagedict[img]['layer'].IsActive():
  794. id = self.imagedict[img]['id']
  795. self.Draw(self.pdc, img=img, drawid=id,
  796. pdctype=self.overlays[id].pdcType,
  797. coords=self.overlays[id].coords)
  798. for id in self.textdict.keys():
  799. self.Draw(self.pdc, img=self.textdict[id], drawid=id,
  800. pdctype='text', coords=[10, 10, 10, 10])
  801. # optionally draw computational extent box
  802. self.DrawCompRegionExtent()
  803. #
  804. # redraw pdcTmp if needed
  805. #
  806. # draw registered graphics
  807. if len(self.graphicsSetList) > 0:
  808. penOrig = self.pen
  809. polypenOrig = self.polypen
  810. for item in self.graphicsSetList:
  811. try:
  812. item.Draw()
  813. except:
  814. GError(parent=self,
  815. message=_('Unable to draw registered graphics. '
  816. 'The graphics was unregistered.'))
  817. self.UnregisterGraphicsToDraw(item)
  818. self.pen = penOrig
  819. self.polypen = polypenOrig
  820. if len(self.polycoords) > 0:
  821. self.DrawLines(self.pdcTmp)
  822. return True
  823. def DrawCompRegionExtent(self):
  824. """Draw computational region extent in the display
  825. Display region is drawn as a blue box inside the computational region,
  826. computational region inside a display region as a red box).
  827. """
  828. if self._properties.showRegion:
  829. compReg = self.Map.GetRegion()
  830. dispReg = self.Map.GetCurrentRegion()
  831. reg = None
  832. if utils.isInRegion(dispReg, compReg):
  833. self.polypen = wx.Pen(
  834. colour=wx.Colour(0, 0, 255, 128),
  835. width=3, style=wx.SOLID)
  836. reg = dispReg
  837. else:
  838. self.polypen = wx.Pen(colour=wx.Colour(255, 0, 0, 128),
  839. width=3, style=wx.SOLID)
  840. reg = compReg
  841. regionCoords = []
  842. regionCoords.append((reg['w'], reg['n']))
  843. regionCoords.append((reg['e'], reg['n']))
  844. regionCoords.append((reg['e'], reg['s']))
  845. regionCoords.append((reg['w'], reg['s']))
  846. regionCoords.append((reg['w'], reg['n']))
  847. # draw region extent
  848. self.DrawLines(pdc=self.pdcTransparent, polycoords=regionCoords)
  849. def EraseMap(self):
  850. """Erase map canvas
  851. """
  852. self.Draw(self.pdc, pdctype='clear')
  853. if self.digit:
  854. self.Draw(self.pdcVector, pdctype='clear')
  855. self.Draw(self.pdcTransparent, pdctype='clear')
  856. self.Draw(self.pdcTmp, pdctype='clear')
  857. self.Map.AbortAllThreads()
  858. def DragMap(self, moveto):
  859. """Drag the entire map image for panning.
  860. :param moveto: dx,dy
  861. """
  862. dc = wx.BufferedDC(wx.ClientDC(self))
  863. dc.SetBackground(wx.Brush("White"))
  864. dc.Clear()
  865. self.dragimg = wx.DragImage(self._buffer)
  866. self.dragimg.BeginDrag((0, 0), self)
  867. self.dragimg.GetImageRect(moveto)
  868. self.dragimg.Move(moveto)
  869. self.dragimg.DoDrawImage(dc, moveto)
  870. self.dragimg.EndDrag()
  871. def DragItem(self, id, coords):
  872. """Drag an overlay decoration item
  873. """
  874. if id == 99 or id == '' or id is None:
  875. return
  876. Debug.msg(5, "BufferedWindow.DragItem(): id=%d" % id)
  877. x, y = self.lastpos
  878. dx = coords[0] - x
  879. dy = coords[1] - y
  880. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  881. r = self.pdc.GetIdBounds(id)
  882. if isinstance(r, list):
  883. r = wx.Rect(r[0], r[1], r[2], r[3])
  884. if id in self.textdict: # text dragging
  885. rtop = (r[0], r[1] - r[3], r[2], r[3])
  886. r = r.Union(rtop)
  887. rleft = (r[0] - r[2], r[1], r[2], r[3])
  888. r = r.Union(rleft)
  889. self.pdc.TranslateId(id, dx, dy)
  890. r2 = self.pdc.GetIdBounds(id)
  891. if isinstance(r2, list):
  892. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  893. if id in self.textdict: # text
  894. self.textdict[id]['bbox'] = r2
  895. self.textdict[id]['coords'][0] += dx
  896. self.textdict[id]['coords'][1] += dy
  897. r = r.Union(r2)
  898. r.Inflate(4, 4)
  899. self.RefreshRect(r, False)
  900. self.lastpos = (coords[0], coords[1])
  901. def MouseDraw(self, pdc=None, begin=None, end=None):
  902. """Mouse box or line from 'begin' to 'end'
  903. If not given from self.mouse['begin'] to self.mouse['end'].
  904. """
  905. if not pdc:
  906. return
  907. if begin is None:
  908. begin = self.mouse['begin']
  909. if end is None:
  910. end = self.mouse['end']
  911. Debug.msg(
  912. 5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" %
  913. (self.mouse['use'], self.mouse['box'], begin[0], begin[1], end[0], end[1]))
  914. if self.mouse['box'] == "box":
  915. boxid = wx.ID_NEW
  916. mousecoords = [begin[0], begin[1],
  917. end[0], end[1]]
  918. r = pdc.GetIdBounds(boxid)
  919. if isinstance(r, list):
  920. r = wx.Rect(r[0], r[1], r[2], r[3])
  921. r.Inflate(4, 4)
  922. try:
  923. pdc.ClearId(boxid)
  924. except:
  925. pass
  926. self.RefreshRect(r, False)
  927. pdc.SetId(boxid)
  928. self.Draw(pdc, drawid=boxid, pdctype='box', coords=mousecoords)
  929. elif self.mouse['box'] == "line":
  930. self.lineid = wx.ID_NEW
  931. mousecoords = [begin[0], begin[1],
  932. end[0], end[1]]
  933. x1 = min(begin[0], end[0])
  934. x2 = max(begin[0], end[0])
  935. y1 = min(begin[1], end[1])
  936. y2 = max(begin[1], end[1])
  937. r = wx.Rect(x1, y1, x2 - x1, y2 - y1)
  938. r.Inflate(4, 4)
  939. try:
  940. pdc.ClearId(self.lineid)
  941. except:
  942. pass
  943. self.RefreshRect(r, False)
  944. pdc.SetId(self.lineid)
  945. self.Draw(
  946. pdc,
  947. drawid=self.lineid,
  948. pdctype='line',
  949. coords=mousecoords)
  950. def DrawLines(self, pdc=None, polycoords=None):
  951. """Draw polyline in PseudoDC
  952. Set self.pline to wx.NEW_ID + 1
  953. :param polycoords: list of polyline vertices, geographical
  954. coordinates (if not given, self.polycoords
  955. is used)
  956. """
  957. if not pdc:
  958. pdc = self.pdcTmp
  959. if not polycoords:
  960. polycoords = self.polycoords
  961. if len(polycoords) > 0:
  962. self.plineid = wx.ID_NEW + 1
  963. # convert from EN to XY
  964. coords = []
  965. for p in polycoords:
  966. coords.append(self.Cell2Pixel(p))
  967. self.Draw(
  968. pdc,
  969. drawid=self.plineid,
  970. pdctype='polyline',
  971. coords=coords)
  972. Debug.msg(4, "BufferedWindow.DrawLines(): coords=%s, id=%s" %
  973. (coords, self.plineid))
  974. return self.plineid
  975. return -1
  976. def DrawPolylines(self, pdc, coords, pen, drawid=None):
  977. """Draw polyline in PseudoDC.
  978. This is similar to DrawLines but this is used with GraphicsSet,
  979. coordinates should be always in pixels.
  980. :param pdc: PseudoDC
  981. :param coords: list of coordinates (pixel coordinates)
  982. :param pen: pen to be used
  983. :param drawid: id of the drawn object (used by PseudoDC)
  984. """
  985. Debug.msg(4, "BufferedWindow.DrawPolylines(): coords=%s" % coords)
  986. self.lineId = self.Draw(
  987. pdc,
  988. drawid=None,
  989. pdctype='polyline',
  990. coords=coords,
  991. pen=pen)
  992. return self.lineid
  993. def DrawCross(self, pdc, coords, size, rotation=0, pen=None,
  994. text=None, textAlign='lr', textOffset=(5, 5), drawid=None):
  995. """Draw cross in PseudoDC
  996. .. todo::
  997. implement rotation
  998. :param pdc: PseudoDC
  999. :param coords: center coordinates (pixel coordinates)
  1000. :param rotation: rotate symbol
  1001. :param text: draw also text (text, font, color, rotation)
  1002. :param textAlign: alignment (default 'lower-right')
  1003. :param textOffset: offset for text (from center point)
  1004. :param drawid: id of the drawn object (used by PseudoDC)
  1005. """
  1006. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" %
  1007. (pdc, coords, size))
  1008. coordsCross = (
  1009. (coords[0],
  1010. coords[1] - size,
  1011. coords[0],
  1012. coords[1] + size),
  1013. (coords[0] - size,
  1014. coords[1],
  1015. coords[0] + size,
  1016. coords[1]))
  1017. self.lineid = self.Draw(
  1018. pdc,
  1019. drawid=drawid,
  1020. pdctype='lines',
  1021. coords=coordsCross,
  1022. pen=pen)
  1023. if not text:
  1024. return self.lineid
  1025. if textAlign == 'ul':
  1026. coord = [
  1027. coords[0] -
  1028. textOffset[0],
  1029. coords[1] -
  1030. textOffset[1],
  1031. 0,
  1032. 0]
  1033. elif textAlign == 'ur':
  1034. coord = [
  1035. coords[0] +
  1036. textOffset[0],
  1037. coords[1] -
  1038. textOffset[1],
  1039. 0,
  1040. 0]
  1041. elif textAlign == 'lr':
  1042. coord = [
  1043. coords[0] +
  1044. textOffset[0],
  1045. coords[1] +
  1046. textOffset[1],
  1047. 0,
  1048. 0]
  1049. else:
  1050. coord = [
  1051. coords[0] -
  1052. textOffset[0],
  1053. coords[1] +
  1054. textOffset[1],
  1055. 0,
  1056. 0]
  1057. self.Draw(pdc, img=text,
  1058. pdctype='text', coords=coord, pen=pen)
  1059. return self.lineid
  1060. def DrawRectangle(self, pdc, point1, point2, pen, brush=None, drawid=None):
  1061. """Draw rectangle (not filled) in PseudoDC
  1062. :param pdc: PseudoDC
  1063. :param point1: top left corner (pixel coordinates)
  1064. :param point2: bottom right corner (pixel coordinates)
  1065. :param pen: pen
  1066. :param drawid: id of the drawn object (used by PseudoDC)
  1067. """
  1068. Debug.msg(
  1069. 4, "BufferedWindow.DrawRectangle(): pdc=%s, point1=%s, point2=%s" %
  1070. (pdc, point1, point2))
  1071. coords = [point1[0], point1[1], point2[0], point2[1]]
  1072. self.lineid = self.Draw(
  1073. pdc,
  1074. drawid=drawid,
  1075. pdctype='box',
  1076. coords=coords,
  1077. pen=pen,
  1078. brush=brush)
  1079. return self.lineid
  1080. def DrawCircle(self, pdc, coords, radius, pen, brush=None, drawid=None):
  1081. """Draw circle (not filled) in PseudoDC
  1082. :param pdc: PseudoDC
  1083. :param coords: center (pixel coordinates)
  1084. :param radius: radius
  1085. :param pen: pen
  1086. :param drawid: id of the drawn object (used by PseudoDC)
  1087. """
  1088. Debug.msg(
  1089. 4, "BufferedWindow.DrawCircle(): pdc=%s, coords=%s, radius=%s" %
  1090. (pdc, coords, radius))
  1091. newcoords = [coords[0] - radius, coords[1] - radius,
  1092. coords[0] + radius, coords[1] + radius]
  1093. self.lineid = self.Draw(
  1094. pdc,
  1095. drawid=drawid,
  1096. pdctype='circle',
  1097. coords=newcoords,
  1098. pen=pen,
  1099. brush=brush)
  1100. return self.lineid
  1101. def DrawPolygon(self, pdc, coords, pen, brush=None, drawid=None):
  1102. """Draws polygon from a list of points (do not append the first point)
  1103. :param pdc: PseudoDC
  1104. :param coords: list of coordinates (pixel coordinates)
  1105. :param pen: pen
  1106. :param drawid: id of the drawn object (used by PseudoDC)
  1107. """
  1108. # avid wx.GCDC assert
  1109. if len(coords) <= 1:
  1110. return None
  1111. self.lineid = self.Draw(pdc, drawid=drawid, pdctype='polygon',
  1112. coords=coords, pen=pen, brush=brush)
  1113. return self.lineid
  1114. def _computeZoomToPointAndRecenter(self, position, zoomtype):
  1115. """Computes zoom parameters for recenter mode.
  1116. Computes begin and end parameters for Zoom() method.
  1117. Used for zooming by single click (not box)
  1118. and mouse wheel zooming (zoom and recenter mode).
  1119. """
  1120. if zoomtype > 0:
  1121. begin = (position[0] - self.Map.width / 4,
  1122. position[1] - self.Map.height / 4)
  1123. end = (position[0] + self.Map.width / 4,
  1124. position[1] + self.Map.height / 4)
  1125. else:
  1126. begin = ((self.Map.width - position[0]) / 2,
  1127. (self.Map.height - position[1]) / 2)
  1128. end = (begin[0] + self.Map.width / 2,
  1129. begin[1] + self.Map.height / 2)
  1130. return begin, end
  1131. def MouseActions(self, event):
  1132. """Mouse motion and button click notifier
  1133. """
  1134. if not self.processMouse:
  1135. return
  1136. # zoom with mouse wheel
  1137. if event.GetWheelRotation() != 0:
  1138. self.OnMouseWheel(event)
  1139. # left mouse button pressed
  1140. elif event.LeftDown():
  1141. self.OnLeftDown(event)
  1142. # left mouse button released
  1143. elif event.LeftUp():
  1144. self.OnLeftUp(event)
  1145. # dragging
  1146. elif event.Dragging():
  1147. self.OnDragging(event)
  1148. # double click
  1149. elif event.ButtonDClick():
  1150. self.OnButtonDClick(event)
  1151. # middle mouse button pressed
  1152. elif event.MiddleDown():
  1153. self.OnMiddleDown(event)
  1154. # middle mouse button relesed
  1155. elif event.MiddleUp():
  1156. self.OnMiddleUp(event)
  1157. # right mouse button pressed
  1158. elif event.RightDown():
  1159. self.OnRightDown(event)
  1160. # right mouse button released
  1161. elif event.RightUp():
  1162. self.OnRightUp(event)
  1163. elif event.Entering():
  1164. self.OnMouseEnter(event)
  1165. elif event.Moving():
  1166. pixelCoordinates = event.GetPositionTuple()[:]
  1167. coordinates = self.Pixel2Cell(pixelCoordinates)
  1168. self.mouseMoving.emit(x=coordinates[0], y=coordinates[1])
  1169. self.OnMouseMoving(event)
  1170. def OnMouseWheel(self, event):
  1171. """Mouse wheel moved
  1172. """
  1173. zoomBehaviour = UserSettings.Get(group='display',
  1174. key='mouseWheelZoom',
  1175. subkey='selection')
  1176. if zoomBehaviour == 2:
  1177. event.Skip()
  1178. return
  1179. self.processMouse = False
  1180. current = event.GetPositionTuple()[:]
  1181. wheel = event.GetWheelRotation()
  1182. Debug.msg(5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  1183. if wheel > 0:
  1184. zoomtype = 1
  1185. else:
  1186. zoomtype = -1
  1187. if UserSettings.Get(group='display',
  1188. key='scrollDirection',
  1189. subkey='selection'):
  1190. zoomtype *= -1
  1191. # zoom 1/2 of the screen (TODO: settings)
  1192. if zoomBehaviour == 0: # zoom and recenter
  1193. begin, end = self._computeZoomToPointAndRecenter(
  1194. position=current, zoomtype=zoomtype)
  1195. elif zoomBehaviour == 1: # zoom to current cursor position
  1196. begin = (current[0] / 2, current[1] / 2)
  1197. end = ((self.Map.width - current[0]) / 2 + current[0],
  1198. (self.Map.height - current[1]) / 2 + current[1])
  1199. # zoom
  1200. self.Zoom(begin, end, zoomtype)
  1201. # redraw map
  1202. self.UpdateMap(delay=0.2)
  1203. self.Refresh()
  1204. self.processMouse = True
  1205. def OnDragging(self, event):
  1206. """Mouse dragging
  1207. """
  1208. Debug.msg(5, "BufferedWindow.MouseAction(): Dragging")
  1209. current = event.GetPositionTuple()[:]
  1210. previous = self.mouse['begin']
  1211. move = (current[0] - previous[0],
  1212. current[1] - previous[1])
  1213. if self.digit:
  1214. digitToolbar = self.toolbar
  1215. else:
  1216. digitToolbar = None
  1217. # dragging or drawing box with left button
  1218. if self.mouse['use'] == 'pan' or \
  1219. event.MiddleIsDown():
  1220. self.DragMap(move)
  1221. # dragging decoration overlay item
  1222. elif (self.mouse['use'] == 'pointer' and
  1223. not digitToolbar and
  1224. self.dragid is not None):
  1225. coords = event.GetPositionTuple()
  1226. self.DragItem(self.dragid, coords)
  1227. # dragging anything else - rubber band box or line
  1228. else:
  1229. if (self.mouse['use'] == 'pointer' and
  1230. not digitToolbar):
  1231. return
  1232. self.mouse['end'] = event.GetPositionTuple()[:]
  1233. if (event.LeftIsDown() and
  1234. not (digitToolbar and
  1235. digitToolbar.GetAction() in ("moveLine",) and
  1236. self.digit.GetDisplay().GetSelected() > 0)):
  1237. self.MouseDraw(pdc=self.pdcTmp)
  1238. def OnLeftDown(self, event):
  1239. """Left mouse button pressed
  1240. """
  1241. Debug.msg(5, "BufferedWindow.OnLeftDown(): use=%s" %
  1242. self.mouse["use"])
  1243. self.mouse['begin'] = event.GetPositionTuple()[:]
  1244. # vector digizer
  1245. if self.mouse["use"] == "pointer" and \
  1246. self.digit:
  1247. if event.ControlDown():
  1248. self.OnLeftDownUndo(event)
  1249. else:
  1250. self._onLeftDown(event)
  1251. elif self.mouse['use'] == 'pointer':
  1252. # get decoration or text id
  1253. idlist = []
  1254. self.dragid = ''
  1255. self.lastpos = self.mouse['begin']
  1256. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  1257. self.hitradius)
  1258. if 99 in idlist:
  1259. idlist.remove(99)
  1260. if idlist != []:
  1261. self.dragid = idlist[0] # drag whatever is on top
  1262. else:
  1263. pass
  1264. coords = self.Pixel2Cell(self.mouse['begin'])
  1265. self.mouseLeftDown.emit(x=coords[0], y=coords[1])
  1266. event.Skip()
  1267. def OnLeftUp(self, event):
  1268. """Left mouse button released
  1269. Emits mapQueried signal when mouse use is 'query'.
  1270. """
  1271. Debug.msg(5, "BufferedWindow.OnLeftUp(): use=%s" %
  1272. self.mouse["use"])
  1273. self.mouse['end'] = event.GetPositionTuple()[:]
  1274. coordinates = self.Pixel2Cell(self.mouse['end'])
  1275. if self.mouse['use'] in ["zoom", "pan"]:
  1276. # set region in zoom or pan
  1277. begin = self.mouse['begin']
  1278. end = self.mouse['end']
  1279. if self.mouse['use'] == 'zoom':
  1280. # set region for click (zero-width box)
  1281. if begin[0] - end[0] == 0 or \
  1282. begin[1] - end[1] == 0:
  1283. begin, end = self._computeZoomToPointAndRecenter(
  1284. position=end, zoomtype=self.zoomtype)
  1285. self.Zoom(begin, end, self.zoomtype)
  1286. # redraw map
  1287. self.UpdateMap(render=True)
  1288. elif self.mouse["use"] == "query":
  1289. self.mapQueried.emit(
  1290. x=self.mouse['end'][0],
  1291. y=self.mouse['end'][1])
  1292. elif self.mouse["use"] == "pointer" and \
  1293. self.digit:
  1294. self._onLeftUp(event)
  1295. elif (self.mouse['use'] == 'pointer' and
  1296. self.dragid >= 0):
  1297. # end drag of overlay decoration
  1298. if self.overlays and self.dragid in self.overlays:
  1299. self.overlays[
  1300. self.dragid].coords = self.pdc.GetIdBounds(
  1301. self.dragid)
  1302. elif self.dragid in self.textdict:
  1303. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  1304. else:
  1305. pass
  1306. self.dragid = None
  1307. self.mouseLeftUpPointer.emit(x=coordinates[0], y=coordinates[1])
  1308. elif self.mouse['use'] == 'drawRegion':
  1309. coordinatesBegin = self.Pixel2Cell(self.mouse['begin'])
  1310. if coordinatesBegin[0] < coordinates[0]:
  1311. west = coordinatesBegin[0]
  1312. east = coordinates[0]
  1313. else:
  1314. west = coordinates[0]
  1315. east = coordinatesBegin[0]
  1316. if coordinatesBegin[1] < coordinates[1]:
  1317. south = coordinatesBegin[1]
  1318. north = coordinates[1]
  1319. else:
  1320. south = coordinates[1]
  1321. north = coordinatesBegin[1]
  1322. region = self.Map.GetRegion()
  1323. RunCommand('g.region',
  1324. parent=self,
  1325. flags='a', nsres=region['nsres'], ewres=region['ewres'],
  1326. n=north, s=south, e=east, w=west)
  1327. # redraw map
  1328. self.UpdateMap(render=False)
  1329. # TODO: decide which coordinates to send (e, n, mouse['begin'],
  1330. # mouse['end'])
  1331. self.mouseLeftUp.emit(x=coordinates[0], y=coordinates[1])
  1332. def OnButtonDClick(self, event):
  1333. """Mouse button double click
  1334. """
  1335. Debug.msg(5, "BufferedWindow.OnButtonDClick(): use=%s" %
  1336. self.mouse["use"])
  1337. screenCoords = event.GetPosition()
  1338. if self.mouse['use'] == 'pointer':
  1339. # select overlay decoration options dialog
  1340. idlist = self.pdc.FindObjects(
  1341. screenCoords[0],
  1342. screenCoords[1],
  1343. self.hitradius)
  1344. if idlist:
  1345. self.dragid = idlist[0]
  1346. self.overlayActivated.emit(overlayId=self.dragid)
  1347. coords = self.Pixel2Cell(screenCoords)
  1348. self.mouseDClick.emit(x=coords[0], y=coords[1])
  1349. def OnRightDown(self, event):
  1350. """Right mouse button pressed
  1351. """
  1352. Debug.msg(5, "BufferedWindow.OnRightDown(): use=%s" %
  1353. self.mouse["use"])
  1354. if self.digit:
  1355. self._onRightDown(event)
  1356. event.Skip()
  1357. def OnRightUp(self, event):
  1358. """Right mouse button released
  1359. """
  1360. Debug.msg(5, "BufferedWindow.OnRightUp(): use=%s" %
  1361. self.mouse["use"])
  1362. if self.digit:
  1363. self._onRightUp(event)
  1364. self.redrawAll = True
  1365. self.Refresh()
  1366. coords = self.Pixel2Cell(event.GetPosition())
  1367. self.mouseRightUp.emit(x=coords[0], y=coords[1])
  1368. event.Skip()
  1369. def OnMiddleDown(self, event):
  1370. """Middle mouse button pressed
  1371. """
  1372. if not event:
  1373. return
  1374. self.mouse['begin'] = event.GetPositionTuple()[:]
  1375. def OnMiddleUp(self, event):
  1376. """Middle mouse button released
  1377. """
  1378. self.mouse['end'] = event.GetPositionTuple()[:]
  1379. # set region in zoom or pan
  1380. begin = self.mouse['begin']
  1381. end = self.mouse['end']
  1382. self.Zoom(begin, end, 0) # no zoom
  1383. # redraw map
  1384. self.UpdateMap(render=True)
  1385. def OnMouseEnter(self, event):
  1386. """Mouse entered window and no mouse buttons were pressed
  1387. Emits the mouseEntered signal.
  1388. """
  1389. self.mouseEntered.emit()
  1390. event.Skip()
  1391. def OnMouseMoving(self, event):
  1392. """Motion event and no mouse buttons were pressed
  1393. """
  1394. if self.mouse["use"] == "pointer" and \
  1395. self.digit:
  1396. self._onMouseMoving(event)
  1397. pos = event.GetPosition()
  1398. idlist = self.pdc.FindObjects(pos[0], pos[1], self.hitradius)
  1399. if self.overlays and idlist and [i for i in idlist if i in self.overlays.keys()]: # legend, scale bar, north arrow, dtext
  1400. self.SetToolTipString("Double click in Pointer mode to set object"
  1401. " properties,\nright click to remove")
  1402. else:
  1403. self.SetToolTip(None)
  1404. event.Skip()
  1405. def OnCopyCoordinates(self, event):
  1406. """Copy coordinates to cliboard"""
  1407. e, n = self.GetLastEN()
  1408. if wx.TheClipboard.Open():
  1409. do = wx.TextDataObject()
  1410. # TODO: put delimiter in settings and apply also for Go to in
  1411. # statusbar
  1412. delim = ','
  1413. do.SetText(str(e) + delim + str(n))
  1414. wx.TheClipboard.SetData(do)
  1415. wx.TheClipboard.Close()
  1416. def OnShowStatusbar(self, event):
  1417. """Show/hide statusbar"""
  1418. self._giface.ShowStatusbar(not self._giface.IsStatusbarShown())
  1419. def OnShowAllToolbars(self, event):
  1420. """Show/hide all toolbars"""
  1421. self._giface.ShowAllToolbars(not self._giface.AreAllToolbarsShown())
  1422. def ClearLines(self, pdc=None):
  1423. """Clears temporary drawn lines from PseudoDC
  1424. """
  1425. if not pdc:
  1426. pdc = self.pdcTmp
  1427. try:
  1428. pdc.ClearId(self.lineid)
  1429. pdc.RemoveId(self.lineid)
  1430. except:
  1431. pass
  1432. try:
  1433. pdc.ClearId(self.plineid)
  1434. pdc.RemoveId(self.plineid)
  1435. except:
  1436. pass
  1437. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1438. (self.lineid, self.plineid))
  1439. return True
  1440. def Pixel2Cell(self, xyCoords):
  1441. """Convert image coordinates to real word coordinates
  1442. :param xyCoords: image coordinates
  1443. :return: easting, northing
  1444. :return: None on error
  1445. """
  1446. try:
  1447. x = int(xyCoords[0])
  1448. y = int(xyCoords[1])
  1449. except:
  1450. return None
  1451. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1452. res = self.Map.region["ewres"]
  1453. else:
  1454. res = self.Map.region["nsres"]
  1455. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1456. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1457. east = w + x * res
  1458. north = n - y * res
  1459. return (east, north)
  1460. def Cell2Pixel(self, enCoords):
  1461. """Convert real word coordinates to image coordinates
  1462. """
  1463. try:
  1464. east = float(enCoords[0])
  1465. north = float(enCoords[1])
  1466. except:
  1467. return None
  1468. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1469. res = self.Map.region["ewres"]
  1470. else:
  1471. res = self.Map.region["nsres"]
  1472. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1473. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1474. x = (east - w) / res
  1475. y = (n - north) / res
  1476. return (x, y)
  1477. def Zoom(self, begin, end, zoomtype):
  1478. """Calculates new region while (un)zoom/pan-ing
  1479. """
  1480. x1, y1 = begin
  1481. x2, y2 = end
  1482. newreg = {}
  1483. # threshold - too small squares do not make sense
  1484. # can only zoom to windows of > 5x5 screen pixels
  1485. if abs(x2 - x1) > 5 and abs(y2 - y1) > 5 and zoomtype != 0:
  1486. if x1 > x2:
  1487. x1, x2 = x2, x1
  1488. if y1 > y2:
  1489. y1, y2 = y2, y1
  1490. # zoom in
  1491. if zoomtype > 0:
  1492. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1493. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1494. # zoom out
  1495. elif zoomtype < 0:
  1496. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1497. newreg['e'], newreg['s'] = self.Pixel2Cell(
  1498. (self.Map.width + 2 * (self.Map.width - x2),
  1499. self.Map.height + 2 * (self.Map.height - y2)))
  1500. # pan
  1501. elif zoomtype == 0:
  1502. dx = x1 - x2
  1503. dy = y1 - y2
  1504. if dx == 0 and dy == 0:
  1505. dx = x1 - self.Map.width / 2
  1506. dy = y1 - self.Map.height / 2
  1507. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1508. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1509. self.Map.height + dy))
  1510. # if new region has been calculated, set the values
  1511. if newreg != {}:
  1512. # LL locations
  1513. if self.Map.projinfo['proj'] == 'll':
  1514. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1515. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1516. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1517. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1518. # calculate new center point and display resolution
  1519. self.Map.region['center_easting'] = ce
  1520. self.Map.region['center_northing'] = cn
  1521. self.Map.region['ewres'] = (
  1522. newreg['e'] - newreg['w']) / self.Map.width
  1523. self.Map.region['nsres'] = (
  1524. newreg['n'] - newreg['s']) / self.Map.height
  1525. if self._properties.alignExtent:
  1526. self.Map.AlignExtentFromDisplay()
  1527. else:
  1528. for k in ('n', 's', 'e', 'w'):
  1529. self.Map.region[k] = newreg[k]
  1530. if self.digit and \
  1531. hasattr(self, "moveInfo"):
  1532. self._zoom(None)
  1533. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1534. self.Map.region['e'], self.Map.region['w'])
  1535. if self.redrawAll is False:
  1536. self.redrawAll = True
  1537. def ZoomBack(self):
  1538. """Zoom to previous extents in zoomhistory list
  1539. Emits zoomChanged signal.
  1540. Emits zoomHistoryUnavailable signal when stack is empty.
  1541. """
  1542. Debug.msg(4, "BufferedWindow.ZoomBack(): hist)=%s" % self.zoomhistory)
  1543. zoom = list()
  1544. if len(self.zoomhistory) > 1:
  1545. self.zoomhistory.pop()
  1546. zoom = self.zoomhistory[-1]
  1547. if len(self.zoomhistory) < 2:
  1548. self.zoomHistoryUnavailable.emit()
  1549. # zoom to selected region
  1550. self.Map.GetRegion(n=zoom[0], s=zoom[1],
  1551. e=zoom[2], w=zoom[3],
  1552. update=True)
  1553. # update map
  1554. self.UpdateMap()
  1555. self.zoomChanged.emit()
  1556. def ZoomHistory(self, n, s, e, w):
  1557. """Manages a list of last 10 zoom extents
  1558. Emits zoomChanged signal.
  1559. Emits zoomHistoryAvailable signal when stack is not empty.
  1560. Emits zoomHistoryUnavailable signal when stack is empty.
  1561. All methods which are changing zoom should call this method
  1562. to make a record in the history. The signal zoomChanged will be
  1563. then emitted automatically.
  1564. :param n,s,e,w: north, south, east, west
  1565. :return: removed history item if exists (or None)
  1566. """
  1567. removed = None
  1568. self.zoomhistory.append((n, s, e, w))
  1569. if len(self.zoomhistory) > 10:
  1570. removed = self.zoomhistory.pop(0)
  1571. if removed:
  1572. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1573. (self.zoomhistory, removed))
  1574. else:
  1575. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1576. (self.zoomhistory))
  1577. # update toolbar
  1578. if len(self.zoomhistory) > 1:
  1579. self.zoomHistoryAvailable.emit()
  1580. else:
  1581. self.zoomHistoryUnavailable.emit()
  1582. self.zoomChanged.emit()
  1583. return removed
  1584. def InitZoomHistory(self):
  1585. """Initializes zoom history.
  1586. .. todo::
  1587. First item is handled in some special way. Improve the
  1588. documentation or fix the code.
  1589. It does not emits any signals.
  1590. This method can be possibly removed when the history will solve the
  1591. fist item in different way or when GCP manager (and possibly others)
  1592. will handle Map variable in the way that it will be prepared for
  1593. MapWindow/BufferedWindow and thus usable to initialize history.
  1594. """
  1595. self.zoomhistory.append((self.Map.region['n'],
  1596. self.Map.region['s'],
  1597. self.Map.region['e'],
  1598. self.Map.region['w']))
  1599. Debug.msg(4, "BufferedWindow.InitZoomHistory(): hist=%s" %
  1600. (self.zoomhistory))
  1601. def ResetZoomHistory(self):
  1602. """Reset zoom history"""
  1603. self.zoomhistory = list()
  1604. def ZoomToMap(self, layers=None, ignoreNulls=False, render=True):
  1605. """Set display extents to match selected raster
  1606. or vector map(s).
  1607. :param layers: list of layers to be zoom to
  1608. :param ignoreNulls: True to ignore null-values (valid only for rasters)
  1609. :param render: True to re-render display
  1610. """
  1611. if not layers:
  1612. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  1613. layers = [layer.maplayer for layer in layers]
  1614. if not layers:
  1615. return
  1616. rast = []
  1617. rast3d = None
  1618. vect = []
  1619. updated = False
  1620. for l in layers:
  1621. # only one raster is used: g.region does not support multiple
  1622. if l.type == 'raster':
  1623. rast.append(l.GetName())
  1624. elif l.type == 'raster_3d':
  1625. rast3d = l.GetName()
  1626. elif l.type == 'vector':
  1627. if self.digit and \
  1628. self.toolbar.GetLayer() == l:
  1629. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1630. self.Map.GetRegion(n=n, s=s, w=w, e=e,
  1631. update=True)
  1632. updated = True
  1633. else:
  1634. vect.append(l.name)
  1635. elif l.type == 'rgb':
  1636. for rname in l.GetName().splitlines():
  1637. rast.append(rname)
  1638. if not updated:
  1639. self.Map.GetRegion(rast=rast,
  1640. rast3d=rast3d,
  1641. vect=vect,
  1642. zoom=ignoreNulls,
  1643. update=True)
  1644. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1645. self.Map.region['e'], self.Map.region['w'])
  1646. if render:
  1647. self.UpdateMap()
  1648. def ZoomToWind(self):
  1649. """Set display geometry to match computational region
  1650. settings (set with g.region)
  1651. """
  1652. self.Map.region = self.Map.GetRegion()
  1653. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1654. self.Map.region['e'], self.Map.region['w'])
  1655. self.UpdateMap()
  1656. def ZoomToDefault(self):
  1657. """Set display geometry to match default region settings
  1658. """
  1659. self.Map.region = self.Map.GetRegion(default=True)
  1660. self.Map.AdjustRegion() # aling region extent to the display
  1661. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1662. self.Map.region['e'], self.Map.region['w'])
  1663. self.UpdateMap()
  1664. def GoTo(self, e, n):
  1665. region = self.Map.GetCurrentRegion()
  1666. region['center_easting'], region['center_northing'] = e, n
  1667. dn = (region['nsres'] * region['rows']) / 2.
  1668. region['n'] = region['center_northing'] + dn
  1669. region['s'] = region['center_northing'] - dn
  1670. de = (region['ewres'] * region['cols']) / 2.
  1671. region['e'] = region['center_easting'] + de
  1672. region['w'] = region['center_easting'] - de
  1673. self.Map.AdjustRegion()
  1674. # add to zoom history
  1675. self.ZoomHistory(region['n'], region['s'],
  1676. region['e'], region['w'])
  1677. self.UpdateMap()
  1678. def DisplayToWind(self):
  1679. """Set computational region (WIND file) to match display
  1680. extents
  1681. """
  1682. tmpreg = os.getenv("GRASS_REGION")
  1683. if tmpreg:
  1684. del os.environ["GRASS_REGION"]
  1685. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1686. # for user to set explicitly with g.region
  1687. new = self.Map.AlignResolution()
  1688. RunCommand('g.region',
  1689. parent=self,
  1690. overwrite=True,
  1691. n=new['n'],
  1692. s=new['s'],
  1693. e=new['e'],
  1694. w=new['w'],
  1695. rows=int(new['rows']),
  1696. cols=int(new['cols']))
  1697. if tmpreg:
  1698. os.environ["GRASS_REGION"] = tmpreg
  1699. self.UpdateMap(render=False)
  1700. def SetRegion(self, zoomOnly=True):
  1701. """Set display extents/compulational region from named region
  1702. file.
  1703. :param zoomOnly: zoom to named region only (computational region is not saved)
  1704. """
  1705. if zoomOnly:
  1706. label = _('Zoom to saved region extents')
  1707. else:
  1708. label = _('Set compulational region from named region')
  1709. dlg = SavedRegion(parent=self,
  1710. title=label,
  1711. loadsave='load')
  1712. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1713. dlg.Destroy()
  1714. return
  1715. region = dlg.GetName()
  1716. if not grass.find_file(name=region, element='windows')['name']:
  1717. GError(
  1718. parent=self,
  1719. message=_("Region <%s> not found. Operation canceled.") %
  1720. region)
  1721. dlg.Destroy()
  1722. return
  1723. dlg.Destroy()
  1724. if zoomOnly:
  1725. self.Map.GetRegion(regionName=region,
  1726. update=True)
  1727. self.ZoomHistory(self.Map.region['n'],
  1728. self.Map.region['s'],
  1729. self.Map.region['e'],
  1730. self.Map.region['w'])
  1731. else:
  1732. # set computation region from named region file
  1733. RunCommand('g.region',
  1734. parent=self,
  1735. region=region)
  1736. self.UpdateMap()
  1737. def SaveRegion(self, display=True):
  1738. """Save display extents/compulational region to named region
  1739. file.
  1740. :param display: True for display extends otherwise computational region
  1741. """
  1742. if display:
  1743. title = _("Save display extents to region file")
  1744. else:
  1745. title = _("Save computational region to region file")
  1746. dlg = SavedRegion(parent=self, title=title, loadsave='save')
  1747. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1748. dlg.Destroy()
  1749. return
  1750. # test to see if it already exists and ask permission to overwrite
  1751. if grass.find_file(name=dlg.GetName(), element='windows')['name']:
  1752. overwrite = wx.MessageBox(
  1753. parent=self,
  1754. message=_(
  1755. "Region file <%s> already exists. "
  1756. "Do you want to overwrite it?") %
  1757. (dlg.GetName()),
  1758. caption=_("Warning"),
  1759. style=wx.YES_NO | wx.CENTRE)
  1760. if overwrite != wx.YES:
  1761. dlg.Destroy()
  1762. return
  1763. if display:
  1764. self._saveDisplayRegion(dlg.GetName())
  1765. else:
  1766. self._saveCompRegion(dlg.GetName())
  1767. dlg.Destroy()
  1768. def _saveCompRegion(self, name):
  1769. """Save region settings to region file
  1770. :param name: region name
  1771. """
  1772. RunCommand('g.region',
  1773. overwrite=True,
  1774. parent=self,
  1775. flags='u',
  1776. save=name)
  1777. def _saveDisplayRegion(self, name):
  1778. """Save display extents to region file
  1779. :param name: region name
  1780. """
  1781. new = self.Map.GetCurrentRegion()
  1782. tmpreg = os.getenv("GRASS_REGION")
  1783. if tmpreg:
  1784. del os.environ["GRASS_REGION"]
  1785. RunCommand('g.region',
  1786. overwrite=True,
  1787. parent=self,
  1788. flags='u',
  1789. n=new['n'],
  1790. s=new['s'],
  1791. e=new['e'],
  1792. w=new['w'],
  1793. rows=int(new['rows']),
  1794. cols=int(new['cols']),
  1795. save=name)
  1796. if tmpreg:
  1797. os.environ["GRASS_REGION"] = tmpreg
  1798. def Distance(self, beginpt, endpt, screen=True):
  1799. """Calculates distance
  1800. Ctypes required for LL-locations
  1801. :param beginpt: first point
  1802. :param endpt: second point
  1803. :param screen: True for screen coordinates otherwise EN
  1804. """
  1805. if screen:
  1806. e1, n1 = self.Pixel2Cell(beginpt)
  1807. e2, n2 = self.Pixel2Cell(endpt)
  1808. else:
  1809. e1, n1 = beginpt
  1810. e2, n2 = endpt
  1811. dEast = (e2 - e1)
  1812. dNorth = (n2 - n1)
  1813. if self.Map.projinfo['proj'] == 'll' and haveCtypes:
  1814. dist = gislib.G_distance(e1, n1, e2, n2)
  1815. else:
  1816. dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
  1817. return (dist, (dEast, dNorth))
  1818. def GetMap(self):
  1819. """Get render.Map() instance"""
  1820. return self.Map
  1821. def RegisterGraphicsToDraw(
  1822. self, graphicsType, pdc=None, setStatusFunc=None, drawFunc=None,
  1823. mapCoords=True):
  1824. """This method registers graphics to draw.
  1825. :param type: (string) - graphics type: "point", "line" or "rectangle"
  1826. :param pdc: PseudoDC object, default is pdcTmp
  1827. :param setStatusFunc: function called before drawing each item
  1828. Status function should be in this form:
  1829. setStatusFunc(item, itemOrderNum)
  1830. item passes instance of GraphicsSetItem
  1831. which will be drawn itemOrderNum number of item
  1832. in drawing order (from O)
  1833. Hidden items are also counted in drawing order.
  1834. :type setStatusFunc: function
  1835. :param drawFunc: defines own function for drawing, if function
  1836. is not defined DrawCross method is used for
  1837. type "point", DrawLines method for type "line",
  1838. DrawRectangle for "rectangle".
  1839. :param mapCoords: True if map coordinates should be set by user, otherwise pixels
  1840. :return: reference to GraphicsSet, which was added.
  1841. """
  1842. if not pdc:
  1843. pdc = self.pdcTmp
  1844. item = GraphicsSet(parentMapWin=self,
  1845. graphicsType=graphicsType,
  1846. pdc=pdc,
  1847. setStatusFunc=setStatusFunc,
  1848. drawFunc=drawFunc,
  1849. mapCoords=mapCoords)
  1850. self.graphicsSetList.append(item)
  1851. return item
  1852. def UnregisterGraphicsToDraw(self, item):
  1853. """Unregisteres GraphicsSet instance
  1854. :param item: (GraphicsSetItem) - item to unregister
  1855. :return: True - if item was unregistered
  1856. :return: False - if item was not found
  1857. """
  1858. if item in self.graphicsSetList:
  1859. self.graphicsSetList.remove(item)
  1860. return True
  1861. return False