buffered.py 73 KB

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