buffered.py 71 KB

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