1#!/usr/bin/env python3
 2
 3"""Embed a static image into a report."""
 4
 5
 6
 7from collections import OrderedDict
 8
 9from chart.common.path import Path
10from chart.project import settings
11from chart.reports.widget import Widget
12from chart.common.exceptions import ConfigError
13
14
15class PictureWidget(Widget):
16    """Import a static image from the local filesystem into the current report.
17    The file is copied over and becomes part of the .zip file.
18    """
19
20    name = 'picture'
21
22    image = 'widgets/picture.jpeg'
23    thumbnail = 'widgets/picture_sm.jpeg'
24
25    options = OrderedDict([
26            ('filename', {'type': 'string'})])
27
28    url = 'http://tctrac/projects/chart/wiki/PictureWidget'
29
30    def __str__(self):
31        return 'PictureWidget({filename})'.format(filename=self.config['filename'])
32
33    def html(self, document):
34        """Final rendering pass."""
35        c = self.config
36
37        filename = Path(c['filename'])
38
39        if filename.is_absolute():
40            filename = filename.expand()
41            if not filename.exists():
42                raise ConfigError('Filename {path} not found'.format(path=filename))
43
44        elif settings.REPORT_TEMPLATE_DIR.child(filename).exists():
45            # filename relative to reports directory
46            # logging.debug('Detected picture in report directory')
47            filename = settings.REPORT_TEMPLATE_DIR.child(filename)
48
49        else:
50            raise ConfigError('Cannot find picture {name}'.format(name=filename))
51
52        # filename is now the absolute path of the image to be imported
53
54        # test for pictures in the reports directory
55        # if the file already exists in the output directory clear it
56        if Path(filename.name).exists():
57            Path(filename.name).unlink()
58
59        filename.copy(filename.name)
60        # TBD: make filename unique
61        document.aux_files.append(filename.name)
62        document.html.write('<img src=\'{filename}\'/>\n'.format(
63                filename=filename.name))