buffered.py 76 KB

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