Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / trace-viewer / third_party / tvcm / tvcm / style_sheet.py
1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4 import base64
5 import os
6 import re
7
8 class Image(object):
9   def __init__(self, resource):
10     self.resource = resource
11     self.aliases = []
12
13   @property
14   def relative_path(self):
15     return self.resource.relative_path
16
17   @property
18   def absolute_path(self):
19     return self.resource.absolute_path
20
21   @property
22   def contents(self):
23     return self.resource.contents
24
25 class StyleSheet(object):
26   """Represents a stylesheet resource referenced by a module via the
27   base.requireStylesheet(xxx) directive."""
28   def __init__(self, loader, name, resource):
29     self.loader = loader
30     self.name = name
31     self.resource = resource
32     self._images = None
33
34   @property
35   def filename(self):
36     return self.resource.absolute_path
37
38   @property
39   def contents(self):
40     return self.resource.contents
41
42   def __repr__(self):
43     return "StyleSheet(%s)" % self.name
44
45   @property
46   def images(self):
47     if self._images != None:
48       return self._images
49     self.load()
50     return self._images
51
52   @property
53   def contents_with_inlined_images(self):
54     images_by_url = {}
55     for i in self.images:
56       for a in i.aliases:
57         images_by_url[a] = i
58
59     def InlineUrl(m):
60       url = m.group('url')
61       image = images_by_url[url]
62
63       ext = os.path.splitext(image.absolute_path)[1]
64       data = base64.standard_b64encode(image.contents)
65
66       return "url(data:image/%s;base64,%s)" % (ext[1:], data)
67
68     # I'm assuming we only have url()'s associated with images
69     return re.sub('url\((?P<quote>"|\'|)(?P<url>[^"\'()]*)(?P=quote)\)',
70                   lambda m: InlineUrl(m),
71                   self.contents)
72
73
74   def load(self):
75     matches = re.findall(
76       'url\((?:["|\']?)([^"\'()]*)(?:["|\']?)\)',
77       self.contents)
78
79     module_dirname = os.path.dirname(self.resource.absolute_path)
80     def resolve_url(url):
81       if os.path.isabs(url):
82         raise module.DepsException('URL references must be relative')
83       # URLS are relative to this module's directory
84       abs_path = os.path.abspath(os.path.join(module_dirname, url))
85       image = self.loader.load_image(abs_path)
86       image.aliases.append(url)
87       return image
88
89     self._images = [resolve_url(x) for x in matches]