mapwindow.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. """!
  2. @package animation.mapwindow
  3. @brief Animation window and bitmaps management
  4. Classes:
  5. - mapwindow::BufferedWindow
  6. - mapwindow::AnimationWindow
  7. - mapwindow::BitmapProvider
  8. - mapwindow::BitmapPool
  9. (C) 2012 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Anna Kratochvilova <kratochanna gmail.com>
  13. """
  14. import os
  15. import wx
  16. import grass.script as grass
  17. from core.gcmd import RunCommand
  18. from utils import ComputeScaledRect
  19. class BufferedWindow(wx.Window):
  20. """
  21. A Buffered window class (http://wiki.wxpython.org/DoubleBufferedDrawing).
  22. To use it, subclass it and define a Draw(DC) method that takes a DC
  23. to draw to. In that method, put the code needed to draw the picture
  24. you want. The window will automatically be double buffered, and the
  25. screen will be automatically updated when a Paint event is received.
  26. When the drawing needs to change, you app needs to call the
  27. UpdateDrawing() method. Since the drawing is stored in a bitmap, you
  28. can also save the drawing to file by calling the
  29. SaveToFile(self, file_name, file_type) method.
  30. """
  31. def __init__(self, *args, **kwargs):
  32. # make sure the NO_FULL_REPAINT_ON_RESIZE style flag is set.
  33. kwargs['style'] = kwargs.setdefault('style', wx.NO_FULL_REPAINT_ON_RESIZE) | wx.NO_FULL_REPAINT_ON_RESIZE
  34. wx.Window.__init__(self, *args, **kwargs)
  35. wx.EVT_PAINT(self, self.OnPaint)
  36. wx.EVT_SIZE(self, self.OnSize)
  37. self._Buffer = wx.EmptyBitmap(0, 0)
  38. # OnSize called to make sure the buffer is initialized.
  39. # This might result in OnSize getting called twice on some
  40. # platforms at initialization, but little harm done.
  41. self.OnSize(None)
  42. def Draw(self, dc):
  43. ## just here as a place holder.
  44. ## This method should be over-ridden when subclassed
  45. pass
  46. def OnPaint(self, event):
  47. # All that is needed here is to draw the buffer to screen
  48. dc = wx.BufferedPaintDC(self, self._Buffer)
  49. def OnSize(self, event):
  50. # The Buffer init is done here, to make sure the buffer is always
  51. # the same size as the Window
  52. #Size = self.GetClientSizeTuple()
  53. size = self.ClientSize
  54. # Make new offscreen bitmap: this bitmap will always have the
  55. # current drawing in it, so it can be used to save the image to
  56. # a file, or whatever.
  57. self._Buffer = wx.EmptyBitmap(*size)
  58. self.UpdateDrawing()
  59. # event.Skip()
  60. def SaveToFile(self, FileName, FileType=wx.BITMAP_TYPE_PNG):
  61. ## This will save the contents of the buffer
  62. ## to the specified file. See the wxWindows docs for
  63. ## wx.Bitmap::SaveFile for the details
  64. self._Buffer.SaveFile(FileName, FileType)
  65. def UpdateDrawing(self):
  66. """
  67. This would get called if the drawing needed to change, for whatever reason.
  68. The idea here is that the drawing is based on some data generated
  69. elsewhere in the system. If that data changes, the drawing needs to
  70. be updated.
  71. This code re-draws the buffer, then calls Update, which forces a paint event.
  72. """
  73. dc = wx.MemoryDC()
  74. dc.SelectObject(self._Buffer)
  75. self.Draw(dc)
  76. del dc # need to get rid of the MemoryDC before Update() is called.
  77. self.Refresh()
  78. self.Update()
  79. class AnimationWindow(BufferedWindow):
  80. def __init__(self, parent, id = wx.ID_ANY,
  81. style = wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE | wx.BORDER_RAISED):
  82. self.bitmap = wx.EmptyBitmap(0, 0)
  83. self.x = self.y = 0
  84. self.text = ''
  85. self.size = wx.Size()
  86. self.rescaleNeeded = False
  87. self.region = None
  88. self.parent = parent
  89. BufferedWindow.__init__(self, parent = parent, id = id, style = style)
  90. self.SetBackgroundColour(wx.BLACK)
  91. self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
  92. self.Bind(wx.EVT_SIZE, self.OnSize)
  93. def Draw(self, dc):
  94. """!Draws bitmap."""
  95. dc.Clear() # make sure you clear the bitmap!
  96. dc.DrawBitmap(self.bitmap, x = self.x, y = self.y)
  97. dc.DrawText(self.text, 0, 0)
  98. def OnSize(self, event):
  99. self._computeBitmapCoordinates()
  100. self.DrawBitmap(self.bitmap, self.text)
  101. BufferedWindow.OnSize(self, event)
  102. if event:
  103. event.Skip()
  104. def IsRescaled(self):
  105. return self.rescaleNeeded
  106. def _rescaleIfNeeded(self, bitmap):
  107. """!If the bitmap has different size than the window, rescale it."""
  108. bW, bH = bitmap.GetSize()
  109. wW, wH = self.size
  110. if abs(bW - wW) > 5 and abs(bH - wH) > 5:
  111. self.rescaleNeeded = True
  112. im = wx.ImageFromBitmap(bitmap)
  113. im.Rescale(*self.size)
  114. bitmap = wx.BitmapFromImage(im)
  115. else:
  116. self.rescaleNeeded = False
  117. return bitmap
  118. def DrawBitmap(self, bitmap, text):
  119. """!Draws bitmap.
  120. Does not draw the bitmap if it is the same one as last time.
  121. """
  122. bmp = self._rescaleIfNeeded(bitmap)
  123. if self.bitmap == bmp:
  124. return
  125. self.bitmap = bmp
  126. self.text = text
  127. self.UpdateDrawing()
  128. def _computeBitmapCoordinates(self):
  129. """!Computes where to place the bitmap
  130. to be in the center of the window."""
  131. if not self.region:
  132. return
  133. cols = self.region['cols']
  134. rows = self.region['rows']
  135. params = ComputeScaledRect((cols, rows), self.GetClientSize())
  136. self.x = params['x']
  137. self.y = params['y']
  138. self.size = (params['width'], params['height'])
  139. def SetRegion(self, region):
  140. """!Sets region for size computations.
  141. Region is set from outside to avoid calling g.region multiple times.
  142. """
  143. self.region = region
  144. self._computeBitmapCoordinates()
  145. def GetAdjustedSize(self):
  146. return self.size
  147. def GetAdjustedPosition(self):
  148. return self.x, self.y
  149. class BitmapProvider(object):
  150. """!Class responsible for loading data and providing bitmaps"""
  151. def __init__(self, frame, bitmapPool):
  152. self.datasource = None
  153. self.dataNames = None
  154. self.dataType = None
  155. self.region = None
  156. self.bitmapPool = bitmapPool
  157. self.frame = frame
  158. self.size = wx.Size()
  159. self.loadSize = wx.Size()
  160. self.suffix = ''
  161. self.nvizRegion = None
  162. def GetDataNames(self):
  163. return self.dataNames
  164. def SetData(self, datasource, dataNames = None, dataType = 'rast',
  165. suffix = '', nvizRegion = None):
  166. """!Sets data.
  167. @param datasource data to load (raster maps, m.nviz.image commands)
  168. @param dataNames data labels (keys)
  169. @param dataType 'rast', 'nviz'
  170. @param nvizRegion region which must be set for m.nviz.image
  171. """
  172. self.datasource = datasource
  173. self.dataType = dataType
  174. self.suffix = suffix
  175. self.nvizRegion = nvizRegion
  176. if dataNames:
  177. self.dataNames = dataNames
  178. else:
  179. self.dataNames = datasource
  180. self.dataNames = [name + self.suffix for name in self.dataNames]
  181. def GetBitmap(self, dataId):
  182. """!Returns bitmap with given key
  183. or 'no data' bitmap if no such key exists.
  184. @param dataId name of bitmap
  185. """
  186. if dataId:
  187. dataId += self.suffix
  188. try:
  189. bitmap = self.bitmapPool[dataId]
  190. except KeyError:
  191. bitmap = self.bitmapPool[None]
  192. return bitmap
  193. def GetLoadSize(self):
  194. return self.loadSize
  195. def WindowSizeChanged(self, event, sizeMethod):
  196. """!Sets size when size of related window changes."""
  197. # sizeMethod is GetClientSize, must be used instead of GetSize
  198. self.size = sizeMethod()
  199. event.Skip()
  200. def _createNoDataBitmap(self, ncols, nrows):
  201. """!Creates 'no data' bitmap.
  202. Used when requested bitmap is not available (loading data was not successful) or
  203. we want to show 'no data' bitmap.
  204. """
  205. bitmap = wx.EmptyBitmap(ncols, nrows)
  206. dc = wx.MemoryDC()
  207. dc.SelectObject(bitmap)
  208. dc.Clear()
  209. text = _("No data")
  210. dc.SetFont(wx.Font(pointSize = 40, family = wx.FONTFAMILY_SCRIPT,
  211. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_BOLD))
  212. tw, th = dc.GetTextExtent(text)
  213. dc.DrawText(text, (ncols-tw)/2, (nrows-th)/2)
  214. dc.SelectObject(wx.NullBitmap)
  215. return bitmap
  216. def Load(self, force = False):
  217. """!Loads data.
  218. Shows progress dialog.
  219. @param force if True reload all data, otherwise only missing data
  220. """
  221. count, maxLength = self._dryLoad(rasters = self.datasource,
  222. names = self.dataNames, force = force)
  223. progress = None
  224. if self.dataType == 'rast' and count > 5 or \
  225. self.dataType == 'nviz':
  226. progress = wx.ProgressDialog(title = "Loading data",
  227. message = " " * (maxLength + 20), # ?
  228. maximum = count,
  229. parent = self.frame,
  230. style = wx.PD_CAN_ABORT | wx.PD_APP_MODAL |
  231. wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
  232. updateFunction = progress.Update
  233. else:
  234. updateFunction = None
  235. if self.dataType == 'rast':
  236. size, scale = self._computeScale()
  237. # loading ...
  238. self._loadRasters(rasters = self.datasource, names = self.dataNames,
  239. size = size, scale = scale, force = force, updateFunction = updateFunction)
  240. elif self.dataType == 'nviz':
  241. self._load3D(commands = self.datasource, region = self.nvizRegion, names = self.dataNames,
  242. force = force, updateFunction = updateFunction)
  243. if progress:
  244. progress.Destroy()
  245. def Unload(self):
  246. self.datasource = None
  247. self.dataNames = None
  248. self.dataType = None
  249. def _computeScale(self):
  250. """!Computes parameters for creating bitmaps."""
  251. region = grass.region()
  252. ncols, nrows = region['cols'], region['rows']
  253. params = ComputeScaledRect((ncols, nrows), self.size)
  254. return ((params['width'], params['height']), params['scale'])
  255. def _dryLoad(self, rasters, names, force):
  256. """!Tries how many bitmaps will be loaded.
  257. Used for progress dialog.
  258. @param rasters raster maps to be loaded
  259. @param names names used as keys for bitmaps
  260. @param force load everything even though it is already there
  261. """
  262. count = 0
  263. maxLength = 0
  264. for raster, name in zip(rasters, names):
  265. if not(name in self.bitmapPool and force is False):
  266. count += 1
  267. if len(raster) > maxLength:
  268. maxLength = len(raster)
  269. return count, maxLength
  270. def _loadRasters(self, rasters, names, size, scale, force, updateFunction):
  271. """!Loads rasters (also rasters from temporal dataset).
  272. Uses r.out.ppm.
  273. @param rasters raster maps to be loaded
  274. @param names names used as keys for bitmaps
  275. @param size size of new bitmaps
  276. @param scale used for adjustment of region resolution for r.out.ppm
  277. @param force load everything even though it is already there
  278. @param updateFunction function called for updating progress dialog
  279. """
  280. region = grass.region()
  281. for key in ('rows', 'cols', 'cells'):
  282. region.pop(key)
  283. # sometimes it renderes nonsense - depends on resolution
  284. # should we set the resolution of the raster?
  285. region['nsres'] /= scale
  286. region['ewres'] /= scale
  287. os.environ['GRASS_REGION'] = grass.region_env(**region)
  288. ncols, nrows = size
  289. self.loadSize = size
  290. count = 0
  291. # create no data bitmap
  292. if None not in self.bitmapPool or force:
  293. self.bitmapPool[None] = self._createNoDataBitmap(ncols, nrows)
  294. for raster, name in zip(rasters, names):
  295. if name in self.bitmapPool and force is False:
  296. continue
  297. count += 1
  298. # RunCommand has problem with DecodeString
  299. returncode, stdout, messages = read2_command('r.out.ppm', input = raster,
  300. flags = 'h', output = '-', quiet = True)
  301. if returncode != 0:
  302. self.bitmapPool[name] = wx.EmptyBitmap(ncols, nrows)
  303. continue
  304. bitmap = wx.BitmapFromBuffer(ncols, nrows, stdout)
  305. self.bitmapPool[name] = bitmap
  306. if updateFunction:
  307. keepGoing, skip = updateFunction(count, raster)
  308. if not keepGoing:
  309. break
  310. os.environ.pop('GRASS_REGION')
  311. def _load3D(self, commands, region, names, force, updateFunction):
  312. """!Load 3D view images using m.nviz.image.
  313. @param commands
  314. @param region
  315. @param names names used as keys for bitmaps
  316. @param force load everything even though it is already there
  317. @param updateFunction function called for updating progress dialog
  318. """
  319. ncols, nrows = self.size
  320. self.loadSize = ncols, nrows
  321. count = 0
  322. format = 'ppm'
  323. tempFile = grass.tempfile(False)
  324. tempFileFormat = tempFile + '.' + format
  325. os.environ['GRASS_REGION'] = grass.region_env(**region)
  326. # create no data bitmap
  327. if None not in self.bitmapPool or force:
  328. self.bitmapPool[None] = self._createNoDataBitmap(ncols, nrows)
  329. for command, name in zip(commands, names):
  330. if name in self.bitmapPool and force is False:
  331. continue
  332. count += 1
  333. # set temporary file
  334. command[1]['output'] = tempFile
  335. # set size
  336. command[1]['size'] = '%d,%d' % (ncols, nrows)
  337. # set format
  338. command[1]['format'] = format
  339. returncode, messages = RunCommand(getErrorMsg = True, prog = command[0], **command[1])
  340. if returncode != 0:
  341. self.bitmapPool[name] = wx.EmptyBitmap(ncols, nrows)
  342. continue
  343. self.bitmapPool[name] = wx.Bitmap(tempFileFormat)
  344. if updateFunction:
  345. keepGoing, skip = updateFunction(count, name)
  346. if not keepGoing:
  347. break
  348. grass.try_remove(tempFileFormat)
  349. os.environ.pop('GRASS_REGION')
  350. class BitmapPool():
  351. """!Class storing bitmaps (emulates dictionary)"""
  352. def __init__(self):
  353. self.bitmaps = {}
  354. def __getitem__(self, key):
  355. return self.bitmaps[key]
  356. def __setitem__(self, key, bitmap):
  357. self.bitmaps[key] = bitmap
  358. def __contains__(self, key):
  359. return key in self.bitmaps
  360. def Clear(self, usedKeys):
  361. """!Removes all bitmaps which are currentlu not used.
  362. @param usedKeys keys which are currently used
  363. """
  364. for key in self.bitmaps.keys():
  365. if key not in usedKeys and key is not None:
  366. del self.bitmaps[key]
  367. def read2_command(*args, **kwargs):
  368. kwargs['stdout'] = grass.PIPE
  369. kwargs['stderr'] = grass.PIPE
  370. ps = grass.start_command(*args, **kwargs)
  371. stdout, stderr = ps.communicate()
  372. return ps.returncode, stdout, stderr