buffered.py 72 KB

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