provider.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. # -*- coding: utf-8 -*-
  2. """!
  3. @package animation.provider
  4. @brief Animation files and bitmaps management
  5. Classes:
  6. - mapwindow::BitmapProvider
  7. - mapwindow::BitmapRenderer
  8. - mapwindow::BitmapComposer
  9. - mapwindow::DictRefCounter
  10. - mapwindow::MapFilesPool
  11. - mapwindow::BitmapPool
  12. - mapwindow::CleanUp
  13. (C) 2013 by the GRASS Development Team
  14. This program is free software under the GNU General Public License
  15. (>=v2). Read the file COPYING that comes with GRASS for details.
  16. @author Anna Petrasova <kratochanna gmail.com>
  17. """
  18. import os
  19. import sys
  20. import wx
  21. import tempfile
  22. from multiprocessing import Process, Queue
  23. if __name__ == '__main__':
  24. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  25. from core.gcmd import RunCommand, GException
  26. from core.settings import UserSettings
  27. from core.debug import Debug
  28. from core.utils import _, CmdToTuple, autoCropImageFromFile
  29. from animation.utils import HashCmd, HashCmds, GetFileFromCmd, GetFileFromCmds
  30. import grass.script.core as gcore
  31. from grass.pydispatch.signal import Signal
  32. class BitmapProvider:
  33. """!Class for management of image files and bitmaps.
  34. There is one instance of this class in the application.
  35. It handles both 2D and 3D animations.
  36. """
  37. def __init__(self, bitmapPool, mapFilesPool, tempDir,
  38. imageWidth=640, imageHeight=480):
  39. self._bitmapPool = bitmapPool
  40. self._mapFilesPool = mapFilesPool
  41. self.imageWidth = imageWidth # width of the image to render with d.rast or d.vect
  42. self.imageHeight = imageHeight # height of the image to render with d.rast or d.vect
  43. self._tempDir = tempDir
  44. self._uniqueCmds = []
  45. self._cmdsForComposition = []
  46. self._opacities = []
  47. self._cmds3D = []
  48. self._regionFor3D = None
  49. self._renderer = BitmapRenderer(self._mapFilesPool, self._tempDir,
  50. self.imageWidth, self.imageHeight)
  51. self._composer = BitmapComposer(self._tempDir, self._mapFilesPool,
  52. self._bitmapPool, self.imageWidth,
  53. self.imageHeight)
  54. self.renderingStarted = Signal('BitmapProvider.renderingStarted')
  55. self.compositionStarted = Signal('BitmapProvider.compositionStarted')
  56. self.renderingContinues = Signal('BitmapProvider.renderingContinues')
  57. self.compositionContinues = Signal('BitmapProvider.compositionContinues')
  58. self.renderingFinished = Signal('BitmapProvider.renderingFinished')
  59. self.compositionFinished = Signal('BitmapProvider.compositionFinished')
  60. self.mapsLoaded = Signal('BitmapProvider.mapsLoaded')
  61. self._renderer.renderingContinues.connect(self.renderingContinues)
  62. self._composer.compositionContinues.connect(self.compositionContinues)
  63. def SetCmds(self, cmdsForComposition, opacities):
  64. """!Sets commands to be rendered with opacity levels.
  65. Applies to 2D mode.
  66. @param cmdsForComposition list of lists of command lists
  67. [[['d.rast', 'map=elev_2001'], ['d.vect', 'map=points']], # g.pnmcomp
  68. [['d.rast', 'map=elev_2002'], ['d.vect', 'map=points']],
  69. ...]
  70. @param opacities list of opacity values
  71. """
  72. Debug.msg(2, "BitmapProvider.SetCmds: {} lists".format(len(cmdsForComposition)))
  73. self._cmdsForComposition.extend(cmdsForComposition)
  74. self._uniqueCmds = self._getUniqueCmds()
  75. self._opacities.extend(opacities)
  76. def SetCmds3D(self, cmds, region):
  77. """!Sets commands for 3D rendering.
  78. @param cmds list of commands m.nviz.image (cmd as a list)
  79. @param region for 3D rendering
  80. """
  81. Debug.msg(2, "BitmapProvider.SetCmds3D: {} commands".format(len(cmds)))
  82. self._cmds3D = cmds
  83. self._regionFor3D = region
  84. def _getUniqueCmds(self):
  85. """!Returns list of unique commands."""
  86. unique = set()
  87. for cmdList in self._cmdsForComposition:
  88. for cmd in cmdList:
  89. unique.add(tuple(cmd))
  90. return list(unique)
  91. def Unload(self):
  92. """!Unloads currently loaded data.
  93. Needs to be called before setting new data.
  94. """
  95. Debug.msg(2, "BitmapProvider.Unload")
  96. if self._cmdsForComposition:
  97. for cmd in self._uniqueCmds:
  98. del self._mapFilesPool[HashCmd(cmd)]
  99. for cmdList in self._cmdsForComposition:
  100. del self._bitmapPool[HashCmds(cmdList)]
  101. self._uniqueCmds = []
  102. self._cmdsForComposition = []
  103. self._opacities = []
  104. if self._cmds3D:
  105. self._cmds3D = []
  106. self._regionFor3D = None
  107. def _dryRender(self, uniqueCmds, force):
  108. """!Determines how many files will be rendered.
  109. @param uniqueCmds list of commands which are to be rendered
  110. @param force if forced rerendering
  111. """
  112. count = 0
  113. for cmd in uniqueCmds:
  114. filename = GetFileFromCmd(self._tempDir, cmd)
  115. if not force and os.path.exists(filename) and \
  116. self._mapFilesPool.GetSize(HashCmd(cmd)) == (self.imageWidth, self.imageHeight):
  117. continue
  118. count += 1
  119. Debug.msg(3, "BitmapProvider._dryRender: {} files to be rendered".format(count))
  120. return count
  121. def _dryCompose(self, cmdLists, force):
  122. """!Determines how many lists of (commands) files
  123. will be composed (with g.pnmcomp).
  124. @param cmdLists list of commands lists which are to be composed
  125. @param force if forced rerendering
  126. """
  127. count = 0
  128. for cmdList in cmdLists:
  129. if not force and HashCmds(cmdList) in self._bitmapPool and \
  130. self._bitmapPool[HashCmds(cmdList)].GetSize() == (self.imageWidth,
  131. self.imageHeight):
  132. continue
  133. count += 1
  134. Debug.msg(2, "BitmapProvider._dryCompose: {} files to be composed".format(count))
  135. return count
  136. def Load(self, force=False, bgcolor=(255, 255, 255), nprocs=4):
  137. """!Loads data, both 2D and 3D. In case of 2D, it creates composites,
  138. even when there is only 1 layer to compose (to be changed for speedup)
  139. @param force if True reload all data, otherwise only missing data
  140. @param bgcolor background color as a tuple of 3 values 0 to 255
  141. @param nprocs number of procs to be used for rendering
  142. """
  143. Debug.msg(2, "BitmapProvider.Load: "
  144. "force={}, bgcolor={}, nprocs={}".format(force, bgcolor, nprocs))
  145. cmds = []
  146. if self._uniqueCmds:
  147. cmds.extend(self._uniqueCmds)
  148. if self._cmds3D:
  149. cmds.extend(self._cmds3D)
  150. count = self._dryRender(cmds, force=force)
  151. self.renderingStarted.emit(count=count)
  152. # create no data bitmap
  153. if None not in self._bitmapPool or force:
  154. self._bitmapPool[None] = createNoDataBitmap(self.imageWidth, self.imageHeight)
  155. ok = self._renderer.Render(cmds, regionFor3D=self._regionFor3D,
  156. bgcolor=bgcolor, force=force, nprocs=nprocs)
  157. self.renderingFinished.emit()
  158. if not ok:
  159. self.mapsLoaded.emit() # what to do here?
  160. return
  161. if self._cmdsForComposition:
  162. count = self._dryCompose(self._cmdsForComposition, force=force)
  163. self.compositionStarted.emit(count=count)
  164. self._composer.Compose(self._cmdsForComposition, self._opacities,
  165. bgcolor=bgcolor, force=force, nprocs=nprocs)
  166. self.compositionFinished.emit()
  167. if self._cmds3D:
  168. for cmd in self._cmds3D:
  169. self._bitmapPool[HashCmd(cmd)] = \
  170. wx.Bitmap(GetFileFromCmd(self._tempDir, cmd))
  171. self.mapsLoaded.emit()
  172. def RequestStopRendering(self):
  173. """!Requests to stop rendering/composition"""
  174. Debug.msg(2, "BitmapProvider.RequestStopRendering")
  175. self._renderer.RequestStopRendering()
  176. self._composer.RequestStopComposing()
  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. try:
  183. bitmap = self._bitmapPool[dataId]
  184. except KeyError:
  185. bitmap = self._bitmapPool[None]
  186. return bitmap
  187. def WindowSizeChanged(self, width, height):
  188. """!Sets size when size of related window changes."""
  189. Debug.msg(5, "BitmapProvider.WindowSizeChanged: w={}, h={}".format(width, height))
  190. self.imageWidth, self.imageHeight = width, height
  191. self._composer.imageWidth = self._renderer.imageWidth = width
  192. self._composer.imageHeight = self._renderer.imageHeight = height
  193. def LoadOverlay(self, cmd):
  194. """!Creates raster legend with d.legend
  195. @param cmd d.legend command as a list
  196. @return bitmap with legend
  197. """
  198. Debug.msg(5, "BitmapProvider.LoadOverlay: cmd={}".format(cmd))
  199. fileHandler, filename = tempfile.mkstemp(suffix=".png")
  200. os.close(fileHandler)
  201. # Set the environment variables for this process
  202. _setEnvironment(self.imageWidth, self.imageHeight, filename,
  203. transparent=True, bgcolor=(0, 0, 0))
  204. Debug.msg(1, "Render raster legend " + str(filename))
  205. cmdTuple = CmdToTuple(cmd)
  206. returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
  207. if returncode == 0:
  208. return wx.BitmapFromImage(autoCropImageFromFile(filename))
  209. else:
  210. os.remove(filename)
  211. raise GException(messages)
  212. class BitmapRenderer:
  213. """!Class which renderes 2D and 3D images to files."""
  214. def __init__(self, mapFilesPool, tempDir,
  215. imageWidth, imageHeight):
  216. self._mapFilesPool = mapFilesPool
  217. self._tempDir = tempDir
  218. self.imageWidth = imageWidth
  219. self.imageHeight = imageHeight
  220. self.renderingContinues = Signal('BitmapRenderer.renderingContinues')
  221. self._stopRendering = False
  222. self._isRendering = False
  223. def Render(self, cmdList, regionFor3D, bgcolor, force, nprocs):
  224. """!Renders all maps and stores files.
  225. @param cmdList list of rendering commands to run
  226. @param regionFor3D region for setting 3D view
  227. @param bgcolor background color as a tuple of 3 values 0 to 255
  228. @param force if True reload all data, otherwise only missing data
  229. @param nprocs number of procs to be used for rendering
  230. """
  231. Debug.msg(3, "BitmapRenderer.Render")
  232. count = 0
  233. # Variables for parallel rendering
  234. proc_count = 0
  235. proc_list = []
  236. queue_list = []
  237. cmd_list = []
  238. filteredCmdList = []
  239. for cmd in cmdList:
  240. filename = GetFileFromCmd(self._tempDir, cmd)
  241. if not force and os.path.exists(filename) and \
  242. self._mapFilesPool.GetSize(HashCmd(cmd)) == (self.imageWidth, self.imageHeight):
  243. # for reference counting
  244. self._mapFilesPool[HashCmd(cmd)] = filename
  245. continue
  246. filteredCmdList.append(cmd)
  247. mapNum = len(filteredCmdList)
  248. stopped = False
  249. self._isRendering = True
  250. for cmd in filteredCmdList:
  251. count += 1
  252. # Queue object for interprocess communication
  253. q = Queue()
  254. # The separate render process
  255. if cmd[0] == 'm.nviz.image':
  256. p = Process(target=self.RenderProcess3D, args=(cmd, regionFor3D, bgcolor, q))
  257. else:
  258. p = Process(target=self.RenderProcess2D, args=(cmd, bgcolor, q))
  259. p.start()
  260. queue_list.append(q)
  261. proc_list.append(p)
  262. cmd_list.append(cmd)
  263. proc_count += 1
  264. # Wait for all running processes and read/store the created images
  265. if proc_count == nprocs or count == mapNum:
  266. for i in range(len(cmd_list)):
  267. proc_list[i].join()
  268. filename = queue_list[i].get()
  269. self._mapFilesPool[HashCmd(cmd_list[i])] = filename
  270. self._mapFilesPool.SetSize(HashCmd(cmd_list[i]),
  271. (self.imageWidth, self.imageHeight))
  272. proc_count = 0
  273. proc_list = []
  274. queue_list = []
  275. cmd_list = []
  276. self.renderingContinues.emit(current=count, text=_("Rendering map layers"))
  277. if self._stopRendering:
  278. self._stopRendering = False
  279. stopped = True
  280. break
  281. self._isRendering = False
  282. return not stopped
  283. def RenderProcess2D(self, cmd, bgcolor, fileQueue):
  284. """!Render raster or vector files as ppm image and write the
  285. resulting ppm filename in the provided file queue
  286. @param cmd d.rast/d.vect command as a list
  287. @param bgcolor background color as a tuple of 3 values 0 to 255
  288. @param fileQueue the inter process communication queue
  289. storing the file name of the image
  290. """
  291. Debug.msg(3, "BitmapRenderer.RenderProcess2D: cmd={}".format(cmd))
  292. filename = GetFileFromCmd(self._tempDir, cmd)
  293. transparency = True
  294. # Set the environment variables for this process
  295. _setEnvironment(self.imageWidth, self.imageHeight, filename,
  296. transparent=transparency, bgcolor=bgcolor)
  297. Debug.msg(1, "Render image to file " + str(filename))
  298. cmdTuple = CmdToTuple(cmd)
  299. returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
  300. if returncode != 0:
  301. gcore.warning("Rendering failed:\n" + messages)
  302. fileQueue.put(None)
  303. os.remove(filename)
  304. return
  305. fileQueue.put(filename)
  306. def RenderProcess3D(self, cmd, region, bgcolor, fileQueue):
  307. """!Renders image with m.nviz.image and writes the
  308. resulting ppm filename in the provided file queue
  309. @param cmd m.nviz.image command as a list
  310. @param bgcolor background color as a tuple of 3 values 0 to 255
  311. @param fileQueue the inter process communication queue
  312. storing the file name of the image
  313. """
  314. Debug.msg(3, "BitmapRenderer.RenderProcess3D: cmd={}".format(cmd))
  315. filename = GetFileFromCmd(self._tempDir, cmd)
  316. os.environ['GRASS_REGION'] = gcore.region_env(**region)
  317. Debug.msg(1, "Render image to file " + str(filename))
  318. cmdTuple = CmdToTuple(cmd)
  319. cmdTuple[1]['output'] = os.path.splitext(filename)[0]
  320. # set size
  321. cmdTuple[1]['size'] = '%d,%d' % (self.imageWidth, self.imageHeight)
  322. # set format
  323. cmdTuple[1]['format'] = 'ppm'
  324. cmdTuple[1]['bgcolor'] = bgcolor = ':'.join([str(part) for part in bgcolor])
  325. returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
  326. if returncode != 0:
  327. gcore.warning("Rendering failed:\n" + messages)
  328. fileQueue.put(None)
  329. os.environ.pop('GRASS_REGION')
  330. return
  331. os.environ.pop('GRASS_REGION')
  332. fileQueue.put(filename)
  333. def RequestStopRendering(self):
  334. """!Requests to stop rendering."""
  335. if self._isRendering:
  336. self._stopRendering = True
  337. class BitmapComposer:
  338. """!Class which handles the composition of image files with g.pnmcomp."""
  339. def __init__(self, tmpDir, mapFilesPool, bitmapPool,
  340. imageWidth, imageHeight):
  341. self._mapFilesPool = mapFilesPool
  342. self._bitmapPool = bitmapPool
  343. self._tmpDir = tmpDir
  344. self.imageWidth = imageWidth
  345. self.imageHeight = imageHeight
  346. self.compositionContinues = Signal('BitmapComposer.composingContinues')
  347. self._stopComposing = False
  348. self._isComposing = False
  349. def Compose(self, cmdLists, opacityList, bgcolor, force, nprocs):
  350. """!Performs the composition of ppm/pgm files.
  351. @param cmdLisst lists of rendering commands lists to compose
  352. @param opacityList list of lists of opacity values
  353. @param bgcolor background color as a tuple of 3 values 0 to 255
  354. @param force if True reload all data, otherwise only missing data
  355. @param nprocs number of procs to be used for rendering
  356. """
  357. Debug.msg(3, "BitmapComposer.Compose")
  358. count = 0
  359. # Variables for parallel rendering
  360. proc_count = 0
  361. proc_list = []
  362. queue_list = []
  363. cmd_lists = []
  364. filteredCmdLists = []
  365. for cmdList in cmdLists:
  366. if not force and HashCmds(cmdList) in self._bitmapPool and \
  367. self._bitmapPool[HashCmds(cmdList)].GetSize() == (self.imageWidth,
  368. self.imageHeight):
  369. # TODO: find a better way than to assign the same to increase the reference
  370. self._bitmapPool[HashCmds(cmdList)] = self._bitmapPool[HashCmds(cmdList)]
  371. continue
  372. filteredCmdLists.append(cmdList)
  373. num = len(filteredCmdLists)
  374. self._isComposing = True
  375. for cmdList in filteredCmdLists:
  376. count += 1
  377. # Queue object for interprocess communication
  378. q = Queue()
  379. # The separate render process
  380. p = Process(target=self.CompositeProcess,
  381. args=(cmdList, opacityList, bgcolor, q))
  382. p.start()
  383. queue_list.append(q)
  384. proc_list.append(p)
  385. cmd_lists.append(cmdList)
  386. proc_count += 1
  387. # Wait for all running processes and read/store the created images
  388. if proc_count == nprocs or count == num:
  389. for i in range(len(cmd_lists)):
  390. proc_list[i].join()
  391. filename = queue_list[i].get()
  392. if filename is None:
  393. self._bitmapPool[HashCmds(cmd_lists[i])] = \
  394. createNoDataBitmap(self.imageWidth, self.imageHeight,
  395. text="Failed to render")
  396. else:
  397. self._bitmapPool[HashCmds(cmd_lists[i])] = \
  398. wx.BitmapFromImage(wx.Image(filename))
  399. os.remove(filename)
  400. proc_count = 0
  401. proc_list = []
  402. queue_list = []
  403. cmd_lists = []
  404. self.compositionContinues.emit(current=count, text=_("Overlaying map layers"))
  405. if self._stopComposing:
  406. self._stopComposing = False
  407. break
  408. self._isComposing = False
  409. def CompositeProcess(self, cmdList, opacities, bgcolor, fileQueue):
  410. """!Performs the composition of image ppm files and writes the
  411. resulting ppm filename in the provided file queue
  412. @param cmdList list of d.rast/d.vect commands
  413. @param opacities list of opacities
  414. @param bgcolor background color as a tuple of 3 values 0 to 255
  415. @param fileQueue the inter process communication queue
  416. storing the file name of the image
  417. """
  418. Debug.msg(3, "BitmapComposer.CompositeProcess")
  419. maps = []
  420. masks = []
  421. for cmd in cmdList:
  422. maps.append(GetFileFromCmd(self._tmpDir, cmd))
  423. masks.append(GetFileFromCmd(self._tmpDir, cmd, 'pgm'))
  424. filename = GetFileFromCmds(self._tmpDir, cmdList)
  425. # Set the environment variables for this process
  426. _setEnvironment(self.imageWidth, self.imageHeight, filename,
  427. transparent=False, bgcolor=bgcolor)
  428. opacities = [str(op / 100.) for op in opacities]
  429. bgcolor = ':'.join([str(part) for part in bgcolor])
  430. returncode, messages = RunCommand('g.pnmcomp',
  431. getErrorMsg=True,
  432. overwrite=True,
  433. input='%s' % ",".join(reversed(maps)),
  434. mask='%s' % ",".join(reversed(masks)),
  435. opacity='%s' % ",".join(reversed(opacities)),
  436. bgcolor=bgcolor,
  437. width=self.imageWidth,
  438. height=self.imageHeight,
  439. output=filename)
  440. if returncode != 0:
  441. gcore.warning("Rendering composite failed:\n" + messages)
  442. fileQueue.put(None)
  443. os.remove(filename)
  444. return
  445. fileQueue.put(filename)
  446. def RequestStopComposing(self):
  447. """!Requests to stop the composition."""
  448. if self._isComposing:
  449. self._stopComposing = True
  450. class DictRefCounter:
  451. """!Base class storing map files/bitmaps (emulates dictionary).
  452. Counts the references to know which files/bitmaps to delete."""
  453. def __init__(self):
  454. self.dictionary = {}
  455. self.referenceCount = {}
  456. def __getitem__(self, key):
  457. return self.dictionary[key]
  458. def __setitem__(self, key, value):
  459. self.dictionary[key] = value
  460. if key not in self.referenceCount:
  461. self.referenceCount[key] = 1
  462. else:
  463. self.referenceCount[key] += 1
  464. Debug.msg(5, 'DictRefCounter.__setitem__: +1 for key {}'.format(key))
  465. def __contains__(self, key):
  466. return key in self.dictionary
  467. def __delitem__(self, key):
  468. self.referenceCount[key] -= 1
  469. Debug.msg(5, 'DictRefCounter.__delitem__: -1 for key {}'.format(key))
  470. def keys(self):
  471. return self.dictionary.keys()
  472. def Clear(self):
  473. """!Clears items which are not needed any more."""
  474. Debug.msg(4, 'DictRefCounter.Clear')
  475. for key in self.dictionary.keys():
  476. if key is not None:
  477. if self.referenceCount[key] <= 0:
  478. del self.dictionary[key]
  479. del self.referenceCount[key]
  480. class MapFilesPool(DictRefCounter):
  481. """!Stores rendered images as files."""
  482. def __init__(self):
  483. DictRefCounter.__init__(self)
  484. self.size = {}
  485. def SetSize(self, key, size):
  486. self.size[key] = size
  487. def GetSize(self, key):
  488. return self.size[key]
  489. def Clear(self):
  490. """!Removes files which are not needed anymore.
  491. Removes both ppm and pgm.
  492. """
  493. Debug.msg(4, 'MapFilesPool.Clear')
  494. for key in self.dictionary.keys():
  495. if self.referenceCount[key] <= 0:
  496. name, ext = os.path.splitext(self.dictionary[key])
  497. os.remove(self.dictionary[key])
  498. if ext == '.ppm':
  499. os.remove(name + '.pgm')
  500. del self.dictionary[key]
  501. del self.referenceCount[key]
  502. del self.size[key]
  503. class BitmapPool(DictRefCounter):
  504. """!Class storing bitmaps (emulates dictionary)"""
  505. def __init__(self):
  506. DictRefCounter.__init__(self)
  507. class CleanUp:
  508. """!Responsible for cleaning up the files."""
  509. def __init__(self, tempDir):
  510. self._tempDir = tempDir
  511. def __call__(self):
  512. import shutil
  513. if os.path.exists(self._tempDir):
  514. try:
  515. shutil.rmtree(self._tempDir)
  516. Debug.msg(5, 'CleanUp: removed directory {}'.format(self._tempDir))
  517. except OSError:
  518. gcore.warning(_("Directory {} not removed.").format(self._tempDir))
  519. def _setEnvironment(width, height, filename, transparent, bgcolor):
  520. """!Sets environmental variables for 2D rendering.
  521. @param width rendering width
  522. @param height rendering height
  523. @param filename file name
  524. @param transparent use transparency
  525. @param bgcolor background color as a tuple of 3 values 0 to 255
  526. """
  527. Debug.msg(5, "_setEnvironment: width={}, height={}, "
  528. "filename={}, transparent={}, bgcolor={}".format(width, height, filename,
  529. transparent, bgcolor))
  530. os.environ['GRASS_WIDTH'] = str(width)
  531. os.environ['GRASS_HEIGHT'] = str(height)
  532. driver = UserSettings.Get(group='display', key='driver', subkey='type')
  533. os.environ['GRASS_RENDER_IMMEDIATE'] = driver
  534. os.environ['GRASS_BACKGROUNDCOLOR'] = '{:02x}{:02x}{:02x}'.format(*bgcolor)
  535. os.environ['GRASS_TRUECOLOR'] = "TRUE"
  536. if transparent:
  537. os.environ['GRASS_TRANSPARENT'] = "TRUE"
  538. else:
  539. os.environ['GRASS_TRANSPARENT'] = "FALSE"
  540. os.environ['GRASS_PNGFILE'] = str(filename)
  541. def createNoDataBitmap(imageWidth, imageHeight, text="No data"):
  542. """!Creates 'no data' bitmap.
  543. Used when requested bitmap is not available (loading data was not successful) or
  544. we want to show 'no data' bitmap.
  545. @param imageWidth image width
  546. @param imageHeight image height
  547. """
  548. Debug.msg(4, "createNoDataBitmap: w={}, h={}, text={}".format(imageWidth,
  549. imageHeight, text))
  550. bitmap = wx.EmptyBitmap(imageWidth, imageHeight)
  551. dc = wx.MemoryDC()
  552. dc.SelectObject(bitmap)
  553. dc.Clear()
  554. text = _(text)
  555. dc.SetFont(wx.Font(pointSize=40, family=wx.FONTFAMILY_SCRIPT,
  556. style=wx.FONTSTYLE_NORMAL, weight=wx.FONTWEIGHT_BOLD))
  557. tw, th = dc.GetTextExtent(text)
  558. dc.DrawText(text, (imageWidth - tw) / 2, (imageHeight - th) / 2)
  559. dc.SelectObject(wx.NullBitmap)
  560. return bitmap
  561. def read2_command(*args, **kwargs):
  562. kwargs['stdout'] = gcore.PIPE
  563. kwargs['stderr'] = gcore.PIPE
  564. ps = gcore.start_command(*args, **kwargs)
  565. stdout, stderr = ps.communicate()
  566. return ps.returncode, stdout, stderr
  567. def test():
  568. import shutil
  569. from core.layerlist import LayerList, Layer
  570. from animation.data import AnimLayer
  571. from animation.utils import layerListToCmdsMatrix
  572. layerList = LayerList()
  573. layer = AnimLayer()
  574. layer.mapType = 'strds'
  575. layer.name = 'JR'
  576. layer.cmd = ['d.rast', 'map=elev_2007_1m']
  577. layerList.AddLayer(layer)
  578. layer = Layer()
  579. layer.mapType = 'vect'
  580. layer.name = 'buildings_2009_approx'
  581. layer.cmd = ['d.vect', 'map=buildings_2009_approx',
  582. 'color=grey']
  583. layer.opacity = 50
  584. layerList.AddLayer(layer)
  585. bPool = BitmapPool()
  586. mapFilesPool = MapFilesPool()
  587. tempDir = '/tmp/test'
  588. if os.path.exists(tempDir):
  589. shutil.rmtree(tempDir)
  590. os.mkdir(tempDir)
  591. # comment this line to keep the directory after prgm ends
  592. # cleanUp = CleanUp(tempDir)
  593. # import atexit
  594. # atexit.register(cleanUp)
  595. prov = BitmapProvider(bPool, mapFilesPool, tempDir,
  596. imageWidth=640, imageHeight=480)
  597. prov.renderingStarted.connect(
  598. lambda count: sys.stdout.write("Total number of maps: {}\n".format(count)))
  599. prov.renderingContinues.connect(
  600. lambda current, text: sys.stdout.write("Current number: {}\n".format(current)))
  601. prov.compositionStarted.connect(
  602. lambda count: sys.stdout.write("Composition: total number of maps: {}\n".format(count)))
  603. prov.compositionContinues.connect(
  604. lambda current, text: sys.stdout.write("Composition: Current number: {}\n".format(current)))
  605. prov.mapsLoaded.connect(
  606. lambda: sys.stdout.write("Maps loading finished\n"))
  607. cmdMatrix = layerListToCmdsMatrix(layerList)
  608. prov.SetCmds(cmdMatrix, [l.opacity for l in layerList])
  609. app = wx.App()
  610. prov.Load(bgcolor=(13, 156, 230), nprocs=4)
  611. for key in bPool.keys():
  612. if key is not None:
  613. bPool[key].SaveFile(os.path.join(tempDir, key + '.png'), wx.BITMAP_TYPE_PNG)
  614. # prov.Unload()
  615. # prov.SetCmds(cmdMatrix, [l.opacity for l in layerList])
  616. # prov.Load(bgcolor=(13, 156, 230))
  617. # prov.Unload()
  618. # newList = LayerList()
  619. # prov.SetCmds(layerListToCmdsMatrix(newList), [l.opacity for l in newList])
  620. # prov.Load()
  621. # prov.Unload()
  622. # mapFilesPool.Clear()
  623. # bPool.Clear()
  624. # print bPool.keys(), mapFilesPool.keys()
  625. if __name__ == '__main__':
  626. test()