forked from sphinx-gallery/sphinx-gallery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
directives.py
295 lines (227 loc) · 8.94 KB
/
directives.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
Custom Sphinx directives
========================
"""
import os
from pathlib import PurePosixPath
import shutil
from docutils import nodes
from docutils import statemachine
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst.directives import images
from sphinx.errors import ExtensionError
class MiniGallery(Directive):
"""
Custom directive to insert a mini-gallery
The required argument is one or more fully qualified names of objects,
separated by spaces. The mini-gallery will be the subset of gallery
examples that make use of that object (from that specific namespace).
Options:
* `add-heading` adds a heading to the mini-gallery. If an argument is
provided, it uses that text for the heading. Otherwise, it uses
default text.
* `heading-level` specifies the heading level of the heading as a single
character. If omitted, the default heading level is `'^'`.
"""
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'add-heading': directives.unchanged,
'heading-level': directives.single_char_or_unicode}
def run(self):
# Respect the same disabling options as the `raw` directive
if (not self.state.document.settings.raw_enabled
or not self.state.document.settings.file_insertion_enabled):
raise self.warning(f'"{self.name}" directive disabled.')
# Retrieve the backreferences directory
config = self.state.document.settings.env.config
backreferences_dir = config.sphinx_gallery_conf['backreferences_dir']
# Parse the argument into the individual objects
obj_list = self.arguments[0].split()
lines = []
# Add a heading if requested
if 'add-heading' in self.options:
heading = self.options['add-heading']
if heading == "":
if len(obj_list) == 1:
heading = f'Examples using ``{obj_list[0]}``'
else:
heading = 'Examples using one of multiple objects'
lines.append(heading)
heading_level = self.options.get('heading-level', '^')
lines.append(heading_level * len(heading))
def has_backrefs(obj):
src_dir = config.sphinx_gallery_conf['src_dir']
path = os.path.join(src_dir, backreferences_dir,
f'{obj}.examples')
return os.path.isfile(path) and os.path.getsize(path) > 0
if not any(has_backrefs(obj) for obj in obj_list):
return []
# Insert the backreferences file(s) using the `include` directive.
# This already includes the opening <div class="sphx-glr-thumbnails">
# and its closing </div>.
for obj in obj_list:
path = os.path.join('/', # Sphinx treats this as the source dir
backreferences_dir,
f'{obj}.examples')
# Always remove the heading from the file
lines.append(f"""\
.. include:: {path}
:start-after: start-sphx-glr-thumbnails""")
# Parse the assembly of `include` and `raw` directives
text = '\n'.join(lines)
include_lines = statemachine.string2lines(text,
convert_whitespace=True)
self.state_machine.insert_input(include_lines, path)
return []
"""
Image sg for responsive images
"""
class imgsgnode(nodes.General, nodes.Element):
pass
def directive_boolean(value):
if not value.strip():
raise ValueError("No argument provided but required")
if value.lower().strip() in ["yes", "1", 1, "true", "ok"]:
return True
elif value.lower().strip() in ['no', '0', 0, 'false', 'none']:
return False
else:
raise ValueError("Please use one of: yes, true, no, false. "
"Do not use `{}` as boolean.".format(value))
class ImageSg(images.Image):
"""
Implements a directive to allow an optional hidpi image. Meant to be
used with the `image_srcset` configuration option.
e.g.::
.. image-sg:: /plot_types/basic/images/sphx_glr_bar_001.png
:alt: bar
:srcset: /plot_types/basic/images/sphx_glr_bar_001.png,
/plot_types/basic/images/sphx_glr_bar_001_2_00x.png 2.00x
:class: sphx-glr-single-img
The resulting html is::
<img src="sphx_glr_bar_001_hidpi.png"
srcset="_images/sphx_glr_bar_001.png,
_images/sphx_glr_bar_001_2_00x.png 2x",
alt="bar"
class="sphx-glr-single-img" />
"""
has_content = False
required_arguments = 1
optional_arguments = 3
final_argument_whitespace = False
option_spec = {
'srcset': directives.unchanged,
'class': directives.class_option,
'alt': directives.unchanged,
}
def run(self):
image_node = imgsgnode()
imagenm = self.arguments[0]
image_node['alt'] = self.options.get('alt', '')
image_node['class'] = self.options.get('class', None)
# we would like uri to be the highest dpi version so that
# latex etc will use that. But for now, lets just make
# imagenm
image_node['uri'] = imagenm
image_node['srcset'] = self.options.get('srcset', None)
return [image_node]
def _parse_srcset(st):
""" parse st"""
entries = st.split(',')
srcset = {}
for entry in entries:
spl = entry.strip().split(' ')
if len(spl) == 1:
srcset[0] = spl[0]
elif len(spl) == 2:
mult = spl[1][:-1]
srcset[float(mult)] = spl[0]
else:
raise ExtensionError('srcset argument "{entry}" is invalid.')
return srcset
def visit_imgsg_html(self, node):
if node['srcset'] is None:
self.visit_image(node)
return
imagedir, srcset = _copy_images(self, node)
# /doc/examples/subd/plot_1.rst
docsource = self.document['source']
# /doc/
# make sure to add the trailing slash:
srctop = os.path.join(self.builder.srcdir, '')
# examples/subd/plot_1.rst
relsource = os.path.relpath(docsource, srctop)
# /doc/build/html
desttop = os.path.join(self.builder.outdir, '')
# /doc/build/html/examples/subd
dest = os.path.join(desttop, relsource)
# ../../_images/ for dirhtml and ../_images/ for html
imagerel = os.path.relpath(imagedir, os.path.dirname(dest))
if self.builder.name == "dirhtml":
imagerel = os.path.join('..', imagerel, '')
else: # html
imagerel = os.path.join(imagerel, '')
if '\\' in imagerel:
imagerel = imagerel.replace('\\', '/')
# make srcset str. Need to change all the prefixes!
srcsetst = ''
for mult in srcset:
nm = os.path.basename(srcset[mult][1:])
# ../../_images/plot_1_2_0x.png
relpath = imagerel+nm
srcsetst += f'{relpath}'
if mult == 0:
srcsetst += ', '
else:
srcsetst += f' {mult:1.2f}x, '
# trim trailing comma and space...
srcsetst = srcsetst[:-2]
# make uri also be relative...
nm = os.path.basename(node['uri'][1:])
uri = imagerel + nm
alt = node['alt']
if node['class'] is not None:
classst = node['class'][0]
classst = f'class = "{classst}"'
else:
classst = ''
html_block = (f'<img src="{uri}" srcset="{srcsetst}" alt="{alt}"' +
f' {classst}/>')
self.body.append(html_block)
def visit_imgsg_latex(self, node):
if node['srcset'] is not None:
imagedir, srcset = _copy_images(self, node)
maxmult = -1
# choose the highest res version for latex:
for key in srcset.keys():
maxmult = max(maxmult, key)
node['uri'] = str(PurePosixPath(srcset[maxmult]).name)
self.visit_image(node)
def _copy_images(self, node):
srcset = _parse_srcset(node['srcset'])
# where the sources are. i.e. myproj/source
srctop = self.builder.srcdir
# copy image from source to imagedir. This is
# *probably* supposed to be done by a builder but...
# ie myproj/build/html/_images
imagedir = os.path.join(self.builder.imagedir, '')
imagedir = PurePosixPath(self.builder.outdir, imagedir)
os.makedirs(imagedir, exist_ok=True)
# copy all the sources to the imagedir:
for mult in srcset:
abspath = PurePosixPath(srctop, srcset[mult][1:])
shutil.copyfile(abspath, imagedir / abspath.name)
return imagedir, srcset
def depart_imgsg_html(self, node):
pass
def visit_sg_other(self, node):
if node['uri'][0] == '/':
node['uri'] = node['uri'][1:]
self.visit_image(node)
def depart_imgsg_latex(self, node):
self.depart_image(node)
def imagesg_addnode(app):
app.add_node(imgsgnode,
html=(visit_imgsg_html, depart_imgsg_html),
latex=(visit_imgsg_latex, depart_imgsg_latex))