provider.py 31 KB

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