buffered.py 74 KB

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