mapwindow.py 19 KB

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