buffered.py 73 KB

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