buffered.py 75 KB

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