Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(197)

Side by Side Diff: grit/gather/chrome_html.py

Issue 10386189: Add chrome_html gatherer, which inlines html and automatically generates image set… (Closed) Base URL: http://git.chromium.org/external/grit-i18n.git@master
Patch Set: Add chrome_html_unittest to test_suite_all. Created 8 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « grit/format/html_inline.py ('k') | grit/gather/chrome_html_unittest.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 """Prepares a Chrome HTML file by inlining resources and adding references to
7 high DPI resources.
8
9 This is a small gatherer that takes a HTML file, looks for src attributes
10 and inlines the specified file, producing one HTML file with no external
11 dependencies. It recursively inlines the included files. When inlining CSS
12 image files this script also checks for the existence of high DPI versions
13 of the inlined file including those on relevant platforms.
14 """
15
16 import os
17 import re
18 import sys
19 import types
20 import base64
21 import mimetypes
22
23 from grit.gather import interface
24 from grit.format import html_inline
25 from grit import lazy_re
26 from grit import util
27
28
29 # Matches a chrome theme source URL.
30 _THEME_SOURCE = lazy_re.compile('chrome://theme/IDR_[A-Z0-9_]*')
31 # Matches CSS image urls with the capture group 'filename'.
32 _CSS_IMAGE_URLS = lazy_re.compile(
33 '(?P<attribute>content|background|[\w-]*-image):[ ]*' +
34 'url\((?:\'|\")(?P<filename>[^"\'\)\(]*)(?:\'|\")')
35
36
37 def InsertImageSet(
38 src_match, base_path, scale_factors, distribution):
39 """Regex replace function which inserts -webkit-image-set.
40
41 Takes a regex match for url('path'). If the file is local, checks for
42 files of the same name in folders corresponding to the supported scale
43 factors. If the file is from a chrome://theme/ source, inserts the
44 supported @Nx scale factor request. In either case inserts a
45 -webkit-image-set rule to fetch the appropriate image for the current
46 scale factor.
47
48 Args:
49 src_match: regex match object from _CSS_IMAGE_URLS
50 base_path: path to look for relative file paths in
51 scale_factors: a list of the supported scale factors (i.e. ['2x'])
52 distribution: string that should replace %DISTRIBUTION%.
53
54 Returns:
55 string
56 """
57 filename = src_match.group('filename')
58 attr = src_match.group('attribute')
59 prefix = src_match.string[src_match.start():src_match.start('filename')-1]
60
61 # Any matches for which a chrome URL handler will serve all scale factors
62 # can simply request all scale factors.
63 if _THEME_SOURCE.match(filename):
64 images = ["url(\"%s\") %s" % (filename, '1x')]
65 for sc in scale_factors:
66 images.append("url(\"%s@%s\") %s" % (filename, sc, sc))
67 return "%s: -webkit-image-set(%s" % (attr, ', '.join(images))
68
69 if filename.find(':') != -1:
70 # filename is probably a URL, which we don't want to bother inlining
71 return src_match.group(0)
72
73 filename = filename.replace('%DISTRIBUTION%', distribution)
74 filepath = os.path.join(base_path, filename)
75 images = ["url(\"%s\") %s" % (filename, '1x')]
76
77 for sc in scale_factors:
78 # Check for existence of file and add to image set.
79 scale_path = os.path.split(os.path.join(base_path, filename))
80 scale_image_path = os.path.join(scale_path[0], sc, scale_path[1])
81 if os.path.isfile(scale_image_path):
82 # CSS always uses forward slashed paths.
83 scale_image_name = re.sub('(?P<path>(.*/)?)(?P<file>[^/]*)',
84 '\\g<path>' + sc + '/\\g<file>',
85 filename)
86 images.append("url(\"%s\") %s" % (scale_image_name, sc))
87 return "%s: -webkit-image-set(%s" % (attr, ', '.join(images))
88
89 def InsertImageSets(
90 filepath, text, scale_factors, distribution):
91 """Helper function that adds references to external images available in any of
92 scale_factors in CSS backgrounds."""
93 # Add high DPI urls for css attributes: content, background,
94 # or *-image.
95 return _CSS_IMAGE_URLS.sub(
96 lambda m: InsertImageSet(m, filepath, scale_factors, distribution),
97 text).decode('utf-8').encode('ascii', 'ignore')
98
99
100 class ChromeHtml(interface.GathererBase):
101 """Represents an HTML document processed for Chrome WebUI.
102
103 HTML documents used in Chrome WebUI have local resources inlined and
104 automatically insert references to high DPI assets used in CSS properties
105 with the use of the -webkit-image-set value. This does not generate any
106 translateable messages and instead generates a single DataPack resource.
107 """
108
109 def __init__(self, html):
110 """Creates a new object that represents the file 'html'.
111 Args:
112 html: 'filename.html'
113 """
114 super(type(self), self).__init__()
115 self.filename_ = html
116 self.inlined_text_ = None
117 # 1x resources are implicitly already in the source and do not need to be
118 # added.
119 self.scale_factors_ = []
120
121 def SetDefines(self, defines):
122 if 'scale_factors' in defines:
123 self.scale_factors_ = defines['scale_factors'].split(',')
124
125 def GetText(self):
126 """Returns inlined text of the HTML document."""
127 return self.inlined_text_
128
129 def GetData(self, lang, encoding):
130 """Returns inlined text of the HTML document."""
131 return self.inlined_text_
132
133 def Translate(self, lang, pseudo_if_not_available=True,
134 skeleton_gatherer=None, fallback_to_english=False):
135 """Returns this document translated."""
136 return self.inlined_text_
137
138 def Parse(self):
139 """Parses and inlines the represented file."""
140 self.inlined_text_ = html_inline.InlineToString(self.filename_, None,
141 rewrite_function=lambda fp, t, d: InsertImageSets(
142 fp, t, self.scale_factors_, d))
143
144 @staticmethod
145 def FromFile(html, extkey=None, encoding = 'utf-8'):
146 """Creates a ChromeHtml object for the contents of 'html'. Returns a new
147 ChromeHtml object.
148
149 Args:
150 html: file('') | 'filename.html'
151 extkey: ignored
152 encoding: 'utf-8' (encoding is ignored)
153
154 Return:
155 ChromeHtml(text_of_file)
156 """
157 if not isinstance(html, types.StringTypes):
158 html = html.name
159
160 return ChromeHtml(html)
OLDNEW
« no previous file with comments | « grit/format/html_inline.py ('k') | grit/gather/chrome_html_unittest.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698