buffered.py 76 KB

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