buffered.py 76 KB

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