summaryrefslogtreecommitdiff
path: root/ishtar_common/utils_secretary.py
blob: 15fb69a2d787b3baa2c8749cfd301c4d88893552 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from secretary import Renderer
from PIL import Image
import re


RE_UNITS = re.compile("([.0-9]+)([a-z]+)")


def parse_value_unit(value):
    m = RE_UNITS.match(value)
    if not m:
        return None, None
    value, unit = m.groups()
    value = float(value)
    return value, unit


class IshtarSecretaryRenderer(Renderer):
    def __init__(self, *args, **kwargs):
        super(IshtarSecretaryRenderer, self).__init__(*args, **kwargs)
        self.media_callback = self.ishtar_media_loader
        # self.environment.filters['pad'] = pad_string

    def ishtar_media_loader(self, media, *args, **kwargs):
        image_file, mime = self.fs_loader(media, *args, **kwargs)
        if "width" in kwargs:
            kwargs['frame_attrs']['svg:width'] = kwargs["width"]
        if "height" in kwargs:
            kwargs['frame_attrs']['svg:height'] = kwargs["height"]
        if "keep_ratio" in args:
            image = Image.open(image_file.name)
            width, width_unit = parse_value_unit(
                kwargs['frame_attrs']['svg:width'])
            height, height_unit = parse_value_unit(
                kwargs['frame_attrs']['svg:height'])
            if "height" not in kwargs and width:
                new_height = width * image.height / image.width
                kwargs['frame_attrs']['svg:height'] = "{}{}".format(
                    new_height, width_unit
                )
            if "width" not in kwargs and height:
                new_width = height * image.width / image.height
                kwargs['frame_attrs']['svg:width'] = "{}{}".format(
                    new_width, height_unit
                )
        return image_file, mime