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