Debian Codegraph @

docutils/writers/s5_html/__init__.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # $Id: __init__.py 10136 2025-05-20 15:48:27Z milde $
2 # Authors: Chris Liechti <[email protected]>;
3 # David Goodger <[email protected]>
4 # Copyright: This module has been placed in the public domain.
5
6 """
7 S5/HTML Slideshow Writer.
8 """
9 from __future__ import annotations
10
11 __docformat__ = 'reStructuredText'
12
13 import os
14 import re
15 import sys
16 from pathlib import Path
17
18 import docutils
19 from docutils import frontend, nodes, utils
20 from docutils.writers import html4css1
21
22 themes_dir_path = utils.relative_path(
23 os.path.join(os.getcwd(), 'dummy'),
24 os.path.join(os.path.dirname(__file__), 'themes'))
25
26
27 def find_theme(name):
28 # Where else to look for a theme?
29 # Check working dir? Destination dir? Config dir? Plugins dir?
30 path = os.path.join(themes_dir_path, name)
31 if not os.path.isdir(path):
32 raise docutils.ApplicationError(
33 'Theme directory not found: %r (path: %r)' % (name, path))
34 return path
35
36
37 class Writer(html4css1.Writer):
38
39 settings_spec = html4css1.Writer.settings_spec + (
40 'S5 Slideshow Specific Options',
41 'For the S5/HTML writer, the --no-toc-backlinks option '
42 '(defined in General Docutils Options above) is the default, '
43 'and should not be changed.',
44 (('Specify an installed S5 theme by name. Overrides --theme-url. '
45 'The default theme name is "default". The theme files will be '
46 'copied into a "ui/<theme>" directory, in the same directory as the '
47 'destination file (output HTML). Note that existing theme files '
48 'will not be overwritten (unless --overwrite-theme-files is used).',
49 ['--theme'],
50 {'default': 'default', 'metavar': '<name>',
51 'overrides': 'theme_url'}),
52 ('Specify an S5 theme URL. The destination file (output HTML) will '
53 'link to this theme; nothing will be copied. Overrides --theme.',
54 ['--theme-url'],
55 {'metavar': '<URL>', 'overrides': 'theme'}),
56 ('Allow existing theme files in the ``ui/<theme>`` directory to be '
57 'overwritten. The default is not to overwrite theme files.',
58 ['--overwrite-theme-files'],
59 {'action': 'store_true', 'validator': frontend.validate_boolean}),
60 ('Keep existing theme files in the ``ui/<theme>`` directory; do not '
61 'overwrite any. This is the default.',
62 ['--keep-theme-files'],
63 {'dest': 'overwrite_theme_files', 'action': 'store_false'}),
64 ('Set the initial view mode to "slideshow" [default] or "outline".',
65 ['--view-mode'],
66 {'choices': ['slideshow', 'outline'], 'default': 'slideshow',
67 'metavar': '<mode>'}),
68 ('Normally hide the presentation controls in slideshow mode. '
69 'This is the default.',
70 ['--hidden-controls'],
71 {'action': 'store_true', 'default': True,
72 'validator': frontend.validate_boolean}),
73 ('Always show the presentation controls in slideshow mode. '
74 'The default is to hide the controls.',
75 ['--visible-controls'],
76 {'dest': 'hidden_controls', 'action': 'store_false'}),
77 ('Enable the current slide indicator ("1 / 15"). '
78 'The default is to disable it.',
79 ['--current-slide'],
80 {'action': 'store_true', 'validator': frontend.validate_boolean}),
81 ('Disable the current slide indicator. This is the default.',
82 ['--no-current-slide'],
83 {'dest': 'current_slide', 'action': 'store_false'}),))
84
85 settings_default_overrides = {'toc_backlinks': 0}
86
87 config_section = 's5_html writer'
88 config_section_dependencies = ('writers', 'html writers',
89 'html4css1 writer')
90
91 def __init__(self) -> None:
92 html4css1.Writer.__init__(self)
93 self.translator_class = S5HTMLTranslator
94
95
96 class S5HTMLTranslator(html4css1.HTMLTranslator):
97
98 s5_stylesheet_template = """\
99 <!-- configuration parameters -->
100 <meta name="defaultView" content="%(view_mode)s" />
101 <meta name="controlVis" content="%(control_visibility)s" />
102 <!-- style sheet links -->
103 <script src="%(path)s/slides.js" type="text/javascript"></script>
104 <link rel="stylesheet" href="%(path)s/slides.css"
105 type="text/css" media="projection" id="slideProj" />
106 <link rel="stylesheet" href="%(path)s/outline.css"
107 type="text/css" media="screen" id="outlineStyle" />
108 <link rel="stylesheet" href="%(path)s/print.css"
109 type="text/css" media="print" id="slidePrint" />
110 <link rel="stylesheet" href="%(path)s/opera.css"
111 type="text/css" media="projection" id="operaFix" />\n"""
112 # The script element must go in front of the link elements to
113 # avoid a flash of unstyled content (FOUC), reproducible with
114 # Firefox.
115
116 disable_current_slide = """
117 <style type="text/css">
118 #currentSlide {display: none;}
119 </style>\n"""
120
121 layout_template = """\
122 <div class="layout">
123 <div id="controls"></div>
124 <div id="currentSlide"></div>
125 <div id="header">
126 %(header)s
127 </div>
128 <div id="footer">
129 %(title)s%(footer)s
130 </div>
131 </div>\n"""
132 # <div class="topleft"></div>
133 # <div class="topright"></div>
134 # <div class="bottomleft"></div>
135 # <div class="bottomright"></div>
136
137 default_theme = 'default'
138 """Name of the default theme."""
139
140 base_theme_file = '__base__'
141 """Name of the file containing the name of the base theme."""
142
143 direct_theme_files = (
144 'slides.css', 'outline.css', 'print.css', 'opera.css', 'slides.js')
145 """Names of theme files directly linked to in the output HTML"""
146
147 indirect_theme_files = (
148 's5-core.css', 'framing.css', 'pretty.css')
149 """Names of files used indirectly; imported or used by files in
150 `direct_theme_files`."""
151
152 required_theme_files = indirect_theme_files + direct_theme_files
153 """Names of mandatory theme files."""
154
155 def __init__(self, *args) -> None:
156 html4css1.HTMLTranslator.__init__(self, *args)
157 # insert S5-specific stylesheet and script stuff:
158 self.theme_file_path = None
159 try:
160 self.setup_theme()
161 except docutils.ApplicationError as e:
162 self.document.reporter.warning(e)
163 view_mode = self.document.settings.view_mode
164 control_visibility = ('visible', 'hidden')[self.document.settings
165 .hidden_controls]
166 self.stylesheet.append(self.s5_stylesheet_template
167 % {'path': self.theme_file_path,
168 'view_mode': view_mode,
169 'control_visibility': control_visibility})
170 if not self.document.settings.current_slide:
171 self.stylesheet.append(self.disable_current_slide)
172 self.meta.append('<meta name="version" content="S5 1.1" />\n')
173 self.s5_footer = []
174 self.s5_header = []
175 self.section_count = 0
176 self.theme_files_copied = None
177
178 def setup_theme(self):
179 if self.document.settings.theme:
180 self.copy_theme()
181 elif self.document.settings.theme_url:
182 self.theme_file_path = self.document.settings.theme_url
183 else:
184 raise docutils.ApplicationError(
185 'No theme specified for S5/HTML writer.')
186
187 def copy_theme(self):
188 """
189 Locate & copy theme files.
190
191 A theme may be explicitly based on another theme via a '__base__'
192 file. The default base theme is 'default'. Files are accumulated
193 from the specified theme, any base themes, and 'default'.
194 """
195 settings = self.document.settings
196 path = find_theme(settings.theme)
197 theme_paths = [path]
198 self.theme_files_copied = {}
199 required_files_copied = {}
200 # This is a link (URL) in HTML, so we use "/", not os.sep:
201 self.theme_file_path = 'ui/%s' % settings.theme
202 if not settings.output_path:
203 raise docutils.ApplicationError(
204 'Output path not specified, you may need to copy'
205 ' the S5 theme files "by hand" or set the "--output" option.')
206 dest = os.path.join(
207 os.path.dirname(settings.output_path), 'ui', settings.theme)
208 if not os.path.isdir(dest):
209 os.makedirs(dest)
210 default = False
211 while path:
212 for f in os.listdir(path): # copy all files from each theme
213 if f == self.base_theme_file:
214 continue # ... except the "__base__" file
215 if (self.copy_file(f, path, dest)
216 and f in self.required_theme_files):
217 required_files_copied[f] = True
218 if default:
219 break # "default" theme has no base theme
220 # Find the "__base__" file in theme directory:
221 base_theme_file = os.path.join(path, self.base_theme_file)
222 # If it exists, read it and record the theme path:
223 if os.path.isfile(base_theme_file):
224 with open(base_theme_file, encoding='utf-8') as f:
225 lines = f.readlines()
226 for line in lines:
227 line = line.strip()
228 if line and not line.startswith('#'):
229 path = find_theme(line)
230 if path in theme_paths: # check for duplicates/cycles
231 path = None # if found, use default base
232 else:
233 theme_paths.append(path)
234 break
235 else: # no theme name found
236 path = None # use default base
237 else: # no base theme file found
238 path = None # use default base
239 if not path:
240 path = find_theme(self.default_theme)
241 theme_paths.append(path)
242 default = True
243 if len(required_files_copied) != len(self.required_theme_files):
244 # Some required files weren't found & couldn't be copied.
245 required = list(self.required_theme_files)
246 for f in required_files_copied.keys():
247 required.remove(f)
248 raise docutils.ApplicationError(
249 'Theme files not found: %s'
250 % ', '.join('%r' % f for f in required))
251
252 files_to_skip_pattern = re.compile(r'~$|\.bak$|#$|\.cvsignore$')
253
254 def copy_file(self, name, source_dir, dest_dir):
255 """
256 Copy file `name` from `source_dir` to `dest_dir`.
257 Return True if the file exists in either `source_dir` or `dest_dir`.
258 """
259 source = os.path.join(source_dir, name)
260 dest = os.path.join(dest_dir, name)
261 if dest in self.theme_files_copied:
262 return True
263 else:
264 self.theme_files_copied[dest] = True
265 if os.path.isfile(source):
266 if self.files_to_skip_pattern.search(source):
267 return None
268 settings = self.document.settings
269 if os.path.exists(dest) and not settings.overwrite_theme_files:
270 settings.record_dependencies.add(dest)
271 else:
272 src_data = Path(source).read_bytes()
273 dest_dir = dest_dir.replace(os.sep, '/')
274 Path(dest).write_bytes(src_data.replace(
275 b'ui/default',
276 dest_dir[dest_dir.rfind('ui/'):].encode(
277 sys.getfilesystemencoding())))
278 settings.record_dependencies.add(source)
279 return True
280 if os.path.isfile(dest):
281 return True
282
283 def depart_document(self, node) -> None:
284 self.head_prefix.extend([self.doctype,
285 self.head_prefix_template %
286 {'lang': self.settings.language_code}])
287 self.html_prolog.append(self.doctype)
288 self.head = self.meta[:] + self.head
289 if self.math_header:
290 if self.math_output == 'mathjax':
291 self.head.extend(self.math_header)
292 else:
293 self.stylesheet.extend(self.math_header)
294 # skip content-type meta tag with interpolated charset value:
295 self.html_head.extend(self.head[1:])
296 self.fragment.extend(self.body)
297 # special S5 code up to the next comment line
298 header = ''.join(self.s5_header)
299 footer = ''.join(self.s5_footer)
300 title = ''.join(self.html_title).replace('<h1 class="title">', '<h1>')
301 layout = self.layout_template % {'header': header,
302 'title': title,
303 'footer': footer}
304 self.body_prefix.extend(layout)
305 self.body_prefix.append('<div class="presentation">\n')
306 self.body_prefix.append(
307 self.starttag({'classes': ['slide'], 'ids': ['slide0']}, 'div'))
308 if not self.section_count:
309 self.body.append('</div>\n')
310 #
311 self.body_suffix.insert(0, '</div>\n')
312 self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
313 + self.docinfo + self.body
314 + self.body_suffix[:-1])
315
316 def depart_footer(self, node) -> None:
317 start = self.context.pop()
318 self.s5_footer.append('<h2>')
319 self.s5_footer.extend(self.body[start:])
320 self.s5_footer.append('</h2>')
321 del self.body[start:]
322
323 def depart_header(self, node) -> None:
324 start = self.context.pop()
325 header = ['<div id="header">\n']
326 header.extend(self.body[start:])
327 header.append('\n</div>\n')
328 del self.body[start:]
329 self.s5_header.extend(header)
330
331 def visit_section(self, node) -> None:
332 if not self.section_count:
333 self.body.append('\n</div>\n')
334 self.section_count += 1
335 self.section_level += 1
336 if self.section_level > 1:
337 # dummy for matching div's
338 self.body.append(self.starttag(node, 'div', CLASS='section'))
339 else:
340 self.body.append(self.starttag(node, 'div', CLASS='slide'))
341
342 def visit_subtitle(self, node) -> None:
343 if isinstance(node.parent, nodes.section):
344 level = self.section_level + self.initial_header_level - 1
345 if level == 1:
346 level = 2
347 tag = 'h%s' % level
348 self.body.append(self.starttag(node, tag, ''))
349 self.context.append('</%s>\n' % tag)
350 else:
351 html4css1.HTMLTranslator.visit_subtitle(self, node)
352
353 def visit_title(self, node) -> None:
354 html4css1.HTMLTranslator.visit_title(self, node)