buffered.py 76 KB

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