buffered.py 73 KB

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