buffered.py 73 KB

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