buffered.py 72 KB

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