buffered.py 73 KB

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