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