mapwindow.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. from multiprocessing import Process, Queue
  17. import tempfile
  18. import grass.script as grass
  19. from core.gcmd import RunCommand
  20. from core.debug import Debug
  21. from grass.pydispatch.signal import Signal
  22. class BufferedWindow(wx.Window):
  23. """
  24. A Buffered window class (http://wiki.wxpython.org/DoubleBufferedDrawing).
  25. To use it, subclass it and define a Draw(DC) method that takes a DC
  26. to draw to. In that method, put the code needed to draw the picture
  27. you want. The window will automatically be double buffered, and the
  28. screen will be automatically updated when a Paint event is received.
  29. When the drawing needs to change, you app needs to call the
  30. UpdateDrawing() method. Since the drawing is stored in a bitmap, you
  31. can also save the drawing to file by calling the
  32. SaveToFile(self, file_name, file_type) method.
  33. """
  34. def __init__(self, *args, **kwargs):
  35. # make sure the NO_FULL_REPAINT_ON_RESIZE style flag is set.
  36. kwargs['style'] = kwargs.setdefault('style', wx.NO_FULL_REPAINT_ON_RESIZE) | wx.NO_FULL_REPAINT_ON_RESIZE
  37. wx.Window.__init__(self, *args, **kwargs)
  38. Debug.msg(2, "BufferedWindow.__init__()")
  39. wx.EVT_PAINT(self, self.OnPaint)
  40. wx.EVT_SIZE(self, self.OnSize)
  41. # OnSize called to make sure the buffer is initialized.
  42. # This might result in OnSize getting called twice on some
  43. # platforms at initialization, but little harm done.
  44. self.OnSize(None)
  45. def Draw(self, dc):
  46. ## just here as a place holder.
  47. ## This method should be over-ridden when subclassed
  48. pass
  49. def OnPaint(self, event):
  50. Debug.msg(5, "BufferedWindow.OnPaint()")
  51. # All that is needed here is to draw the buffer to screen
  52. dc = wx.BufferedPaintDC(self, self._Buffer)
  53. def OnSize(self, event):
  54. Debug.msg(5, "BufferedWindow.OnSize()")
  55. # The Buffer init is done here, to make sure the buffer is always
  56. # the same size as the Window
  57. #Size = self.GetClientSizeTuple()
  58. size = self.ClientSize
  59. # Make new offscreen bitmap: this bitmap will always have the
  60. # current drawing in it, so it can be used to save the image to
  61. # a file, or whatever.
  62. self._Buffer = wx.EmptyBitmap(*size)
  63. self.UpdateDrawing()
  64. # event.Skip()
  65. def SaveToFile(self, FileName, FileType=wx.BITMAP_TYPE_PNG):
  66. ## This will save the contents of the buffer
  67. ## to the specified file. See the wxWindows docs for
  68. ## wx.Bitmap::SaveFile for the details
  69. self._Buffer.SaveFile(FileName, FileType)
  70. def UpdateDrawing(self):
  71. """
  72. This would get called if the drawing needed to change, for whatever reason.
  73. The idea here is that the drawing is based on some data generated
  74. elsewhere in the system. If that data changes, the drawing needs to
  75. be updated.
  76. This code re-draws the buffer, then calls Update, which forces a paint event.
  77. """
  78. dc = wx.MemoryDC()
  79. dc.SelectObject(self._Buffer)
  80. self.Draw(dc)
  81. del dc # need to get rid of the MemoryDC before Update() is called.
  82. self.Refresh()
  83. self.Update()
  84. class AnimationWindow(BufferedWindow):
  85. def __init__(self, parent, id = wx.ID_ANY,
  86. style = wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE | wx.BORDER_RAISED):
  87. Debug.msg(2, "AnimationWindow.__init__()")
  88. self.bitmap = wx.EmptyBitmap(1, 1)
  89. self.text = ''
  90. self.parent = parent
  91. BufferedWindow.__init__(self, parent = parent, id = id, style = style)
  92. self.SetBackgroundColour(wx.BLACK)
  93. self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
  94. self.Bind(wx.EVT_SIZE, self.OnSize)
  95. def Draw(self, dc):
  96. """!Draws bitmap."""
  97. Debug.msg(5, "AnimationWindow.Draw()")
  98. dc.Clear() # make sure you clear the bitmap!
  99. dc.DrawBitmap(self.bitmap, x=0, y=0)
  100. dc.DrawText(self.text, 0, 0)
  101. def OnSize(self, event):
  102. Debug.msg(5, "AnimationWindow.OnSize()")
  103. self.DrawBitmap(self.bitmap, self.text)
  104. BufferedWindow.OnSize(self, event)
  105. if event:
  106. event.Skip()
  107. def DrawBitmap(self, bitmap, text):
  108. """!Draws bitmap.
  109. Does not draw the bitmap if it is the same one as last time.
  110. """
  111. if self.bitmap == bitmap:
  112. return
  113. self.bitmap = bitmap
  114. self.text = text
  115. self.UpdateDrawing()
  116. class BitmapProvider(object):
  117. """!Class responsible for loading data and providing bitmaps"""
  118. def __init__(self, frame, bitmapPool, imageWidth=640, imageHeight=480, nprocs=4):
  119. self.datasource = None
  120. self.dataNames = None
  121. self.dataType = None
  122. self.bitmapPool = bitmapPool
  123. self.frame = frame
  124. self.imageWidth = imageWidth # width of the image to render with d.rast or d.vect
  125. self.imageHeight = imageHeight # height of the image to render with d.rast or d.vect
  126. self.nprocs = nprocs # Number of procs to be used for rendering
  127. self.suffix = ''
  128. self.nvizRegion = None
  129. self.mapsLoaded = Signal('mapsLoaded')
  130. def GetDataNames(self):
  131. return self.dataNames
  132. def SetData(self, datasource, dataNames = None, dataType = 'rast',
  133. suffix = '', nvizRegion = None):
  134. """!Sets data.
  135. @param datasource data to load (raster maps, m.nviz.image commands)
  136. @param dataNames data labels (keys)
  137. @param dataType 'rast', 'nviz'
  138. @param nvizRegion region which must be set for m.nviz.image
  139. """
  140. self.datasource = datasource
  141. self.dataType = dataType
  142. self.suffix = suffix
  143. self.nvizRegion = nvizRegion
  144. if dataNames:
  145. self.dataNames = dataNames
  146. else:
  147. self.dataNames = datasource
  148. self.dataNames = [name + self.suffix for name in self.dataNames]
  149. def GetBitmap(self, dataId):
  150. """!Returns bitmap with given key
  151. or 'no data' bitmap if no such key exists.
  152. @param dataId name of bitmap
  153. """
  154. if dataId:
  155. dataId += self.suffix
  156. try:
  157. bitmap = self.bitmapPool[dataId]
  158. except KeyError:
  159. bitmap = self.bitmapPool[None]
  160. return bitmap
  161. def WindowSizeChanged(self, width, height):
  162. """!Sets size when size of related window changes."""
  163. self.imageWidth, self.imageHeight = width, height
  164. def _createNoDataBitmap(self, width, height):
  165. """!Creates 'no data' bitmap.
  166. Used when requested bitmap is not available (loading data was not successful) or
  167. we want to show 'no data' bitmap.
  168. """
  169. bitmap = wx.EmptyBitmap(width, height)
  170. dc = wx.MemoryDC()
  171. dc.SelectObject(bitmap)
  172. dc.Clear()
  173. text = _("No data")
  174. dc.SetFont(wx.Font(pointSize = 40, family = wx.FONTFAMILY_SCRIPT,
  175. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_BOLD))
  176. tw, th = dc.GetTextExtent(text)
  177. dc.DrawText(text, (width-tw)/2, (height-th)/2)
  178. dc.SelectObject(wx.NullBitmap)
  179. return bitmap
  180. def Load(self, force = False):
  181. """!Loads data.
  182. Shows progress dialog.
  183. @param force if True reload all data, otherwise only missing data
  184. """
  185. count, maxLength = self._dryLoad(rasters = self.datasource,
  186. names = self.dataNames, force = force)
  187. progress = None
  188. if self.dataType == 'rast' and count > 5 or \
  189. self.dataType == 'nviz':
  190. progress = wx.ProgressDialog(title = "Loading data",
  191. message = " " * (maxLength + 20), # ?
  192. maximum = count,
  193. parent = self.frame,
  194. style = wx.PD_CAN_ABORT | wx.PD_APP_MODAL |
  195. wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
  196. updateFunction = progress.Update
  197. else:
  198. updateFunction = None
  199. if self.dataType == 'rast' or self.dataType == 'vect':
  200. self._loadMaps(mapType=self.dataType, maps = self.datasource, names = self.dataNames,
  201. force = force, updateFunction = updateFunction)
  202. elif self.dataType == 'nviz':
  203. self._load3D(commands = self.datasource, region = self.nvizRegion, names = self.dataNames,
  204. force = force, updateFunction = updateFunction)
  205. if progress:
  206. progress.Destroy()
  207. self.mapsLoaded.emit()
  208. def Unload(self):
  209. self.datasource = None
  210. self.dataNames = None
  211. self.dataType = None
  212. def _dryLoad(self, rasters, names, force):
  213. """!Tries how many bitmaps will be loaded.
  214. Used for progress dialog.
  215. @param rasters raster maps to be loaded
  216. @param names names used as keys for bitmaps
  217. @param force load everything even though it is already there
  218. """
  219. count = 0
  220. maxLength = 0
  221. for raster, name in zip(rasters, names):
  222. if not(name in self.bitmapPool and force is False):
  223. count += 1
  224. if len(raster) > maxLength:
  225. maxLength = len(raster)
  226. return count, maxLength
  227. def _loadMaps(self, mapType, maps, names, force, updateFunction):
  228. """!Loads rasters/vectors (also from temporal dataset).
  229. Uses d.rast/d.vect and multiprocessing for parallel rendering
  230. @param mapType Must be "rast" or "vect"
  231. @param maps raster or vector maps to be loaded
  232. @param names names used as keys for bitmaps
  233. @param force load everything even though it is already there
  234. @param updateFunction function called for updating progress dialog
  235. """
  236. count = 0
  237. # Variables for parallel rendering
  238. proc_count = 0
  239. proc_list = []
  240. queue_list = []
  241. name_list = []
  242. mapNum = len(maps)
  243. # create no data bitmap
  244. if None not in self.bitmapPool or force:
  245. self.bitmapPool[None] = self._createNoDataBitmap(self.imageWidth, self.imageHeight)
  246. for mapname, name in zip(maps, names):
  247. count += 1
  248. if name in self.bitmapPool and force is False:
  249. continue
  250. # Queue object for interprocess communication
  251. q = Queue()
  252. # The separate render process
  253. p = Process(target=mapRenderProcess, args=(mapType, mapname, self.imageWidth, self.imageHeight, q))
  254. p.start()
  255. queue_list.append(q)
  256. proc_list.append(p)
  257. name_list.append(name)
  258. proc_count += 1
  259. # Wait for all running processes and read/store the created images
  260. if proc_count == self.nprocs or count == mapNum:
  261. for i in range(len(name_list)):
  262. proc_list[i].join()
  263. filename = queue_list[i].get()
  264. # Unfortunately the png files must be read here,
  265. # since the swig wx objects can not be serialized by the Queue object :(
  266. if filename == None:
  267. self.bitmapPool[name_list[i]] = wx.EmptyBitmap(self.imageWidth, self.imageHeight)
  268. else:
  269. self.bitmapPool[name_list[i]] = wx.BitmapFromImage(wx.Image(filename))
  270. os.remove(filename)
  271. proc_count = 0
  272. proc_list = []
  273. queue_list = []
  274. name_list = []
  275. if updateFunction:
  276. keepGoing, skip = updateFunction(count, mapname)
  277. if not keepGoing:
  278. break
  279. def _load3D(self, commands, region, names, force, updateFunction):
  280. """!Load 3D view images using m.nviz.image.
  281. @param commands
  282. @param region
  283. @param names names used as keys for bitmaps
  284. @param force load everything even though it is already there
  285. @param updateFunction function called for updating progress dialog
  286. """
  287. ncols, nrows = self.imageWidth, self.imageHeight
  288. count = 0
  289. format = 'ppm'
  290. tempFile = grass.tempfile(False)
  291. tempFileFormat = tempFile + '.' + format
  292. os.environ['GRASS_REGION'] = grass.region_env(**region)
  293. # create no data bitmap
  294. if None not in self.bitmapPool or force:
  295. self.bitmapPool[None] = self._createNoDataBitmap(ncols, nrows)
  296. for command, name in zip(commands, names):
  297. if name in self.bitmapPool and force is False:
  298. continue
  299. count += 1
  300. # set temporary file
  301. command[1]['output'] = tempFile
  302. # set size
  303. command[1]['size'] = '%d,%d' % (ncols, nrows)
  304. # set format
  305. command[1]['format'] = format
  306. returncode, messages = RunCommand(getErrorMsg = True, prog = command[0], **command[1])
  307. if returncode != 0:
  308. self.bitmapPool[name] = wx.EmptyBitmap(ncols, nrows)
  309. continue
  310. self.bitmapPool[name] = wx.Bitmap(tempFileFormat)
  311. if updateFunction:
  312. keepGoing, skip = updateFunction(count, name)
  313. if not keepGoing:
  314. break
  315. grass.try_remove(tempFileFormat)
  316. os.environ.pop('GRASS_REGION')
  317. def mapRenderProcess(mapType, mapname, width, height, fileQueue):
  318. """!Render raster or vector files as png image and write the
  319. resulting png filename in the provided file queue
  320. @param mapType Must be "rast" or "vect"
  321. @param mapname raster or vector map name to be rendered
  322. @param width Width of the resulting image
  323. @param height Height of the resulting image
  324. @param fileQueue The inter process communication queue storing the file name of the image
  325. """
  326. # temporary file, we use python here to avoid calling g.tempfile for each render process
  327. fileHandler, filename = tempfile.mkstemp(suffix=".png")
  328. os.close(fileHandler)
  329. # Set the environment variables for this process
  330. os.environ['GRASS_WIDTH'] = str(width)
  331. os.environ['GRASS_HEIGHT'] = str(height)
  332. os.environ['GRASS_RENDER_IMMEDIATE'] = "png"
  333. os.environ['GRASS_TRUECOLOR'] = "1"
  334. os.environ['GRASS_TRANSPARENT'] = "1"
  335. os.environ['GRASS_PNGFILE'] = str(filename)
  336. if mapType == "rast":
  337. Debug.msg(1, "Render raster image " + str(filename))
  338. returncode, stdout, messages = read2_command('d.rast', map = mapname)
  339. else:
  340. Debug.msg(1, "Render vector image " + str(filename))
  341. returncode, stdout, messages = read2_command('d.vect', map = mapname)
  342. if returncode != 0:
  343. fileQueue.put(None)
  344. os.remove(filename)
  345. return
  346. fileQueue.put(filename)
  347. class BitmapPool():
  348. """!Class storing bitmaps (emulates dictionary)"""
  349. def __init__(self):
  350. self.bitmaps = {}
  351. def __getitem__(self, key):
  352. return self.bitmaps[key]
  353. def __setitem__(self, key, bitmap):
  354. self.bitmaps[key] = bitmap
  355. def __contains__(self, key):
  356. return key in self.bitmaps
  357. def Clear(self, usedKeys):
  358. """!Removes all bitmaps which are currentlu not used.
  359. @param usedKeys keys which are currently used
  360. """
  361. for key in self.bitmaps.keys():
  362. if key not in usedKeys and key is not None:
  363. del self.bitmaps[key]
  364. def read2_command(*args, **kwargs):
  365. kwargs['stdout'] = grass.PIPE
  366. kwargs['stderr'] = grass.PIPE
  367. ps = grass.start_command(*args, **kwargs)
  368. stdout, stderr = ps.communicate()
  369. return ps.returncode, stdout, stderr