Debian Codegraph @

docutils/parsers/rst/directives/images.py

raw symbols SCIP
1 # $Id: images.py 10102 2025-04-23 15:54:44Z milde $
2 # Author: David Goodger <[email protected]>
3 # Copyright: This module has been placed in the public domain.
4
5 """
6 Directives for figures and simple images.
7 """
8
9 __docformat__ = 'reStructuredText'
10
11 from urllib.request import url2pathname
12
13 try: # check for the Python Imaging Library
14 import PIL.Image
15 except ImportError:
16 try: # sometimes PIL modules are put in PYTHONPATH's root
17 import Image
18 class PIL: pass # noqa:E701 dummy wrapper
19 PIL.Image = Image
20 except ImportError:
21 PIL = None
22
23 from docutils import nodes
24 from docutils.nodes import fully_normalize_name, whitespace_normalize_name
25 from docutils.parsers.rst import Directive
26 from docutils.parsers.rst import directives, states
27 from docutils.parsers.rst.roles import normalize_options
28
29
30 class Image(Directive):
31
32 align_h_values = ('left', 'center', 'right')
33 align_v_values = ('top', 'middle', 'bottom')
34 align_values = align_v_values + align_h_values
35 loading_values = ('embed', 'link', 'lazy')
36
37 def align(argument):
38 # This is not callable as `self.align()`. We cannot make it a
39 # staticmethod because we're saving an unbound method in
40 # option_spec below.
41 return directives.choice(argument, Image.align_values)
42
43 def loading(argument):
44 # This is not callable as `self.loading()` (see above).
45 return directives.choice(argument, Image.loading_values)
46
47 required_arguments = 1
48 optional_arguments = 0
49 final_argument_whitespace = True
50 option_spec = {'alt': directives.unchanged,
51 'height': directives.length_or_unitless,
52 'width': directives.length_or_percentage_or_unitless,
53 'scale': directives.percentage,
54 'align': align,
55 'target': directives.unchanged_required,
56 'loading': loading,
57 'class': directives.class_option,
58 'name': directives.unchanged}
59
60 def run(self):
61 if 'align' in self.options:
62 if isinstance(self.state, states.SubstitutionDef):
63 # Check for align_v_values.
64 if self.options['align'] not in self.align_v_values:
65 raise self.error(
66 'Error in "%s" directive: "%s" is not a valid value '
67 'for the "align" option within a substitution '
68 'definition. Valid values for "align" are: "%s".'
69 % (self.name, self.options['align'],
70 '", "'.join(self.align_v_values)))
71 elif self.options['align'] not in self.align_h_values:
72 raise self.error(
73 'Error in "%s" directive: "%s" is not a valid value for '
74 'the "align" option. Valid values for "align" are: "%s".'
75 % (self.name, self.options['align'],
76 '", "'.join(self.align_h_values)))
77 messages = []
78 reference = directives.uri(self.arguments[0])
79 self.options['uri'] = reference
80 reference_node = None
81 if 'target' in self.options:
82 block = states.escape2null(
83 self.options['target']).splitlines()
84 block = list(block)
85 target_type, data = self.state.parse_target(
86 block, self.block_text, self.lineno)
87 if target_type == 'refuri':
88 reference_node = nodes.reference(refuri=data)
89 elif target_type == 'refname':
90 reference_node = nodes.reference(
91 refname=fully_normalize_name(data),
92 name=whitespace_normalize_name(data))
93 reference_node.indirect_reference_name = data
94 self.state.document.note_refname(reference_node)
95 else: # malformed target
96 messages.append(data) # data is a system message
97 del self.options['target']
98 options = normalize_options(self.options)
99 image_node = nodes.image(self.block_text, **options)
100 (image_node.source,
101 image_node.line) = self.state_machine.get_source_and_line(self.lineno)
102 self.add_name(image_node)
103 if reference_node:
104 reference_node += image_node
105 return messages + [reference_node]
106 else:
107 return messages + [image_node]
108
109
110 class Figure(Image):
111
112 def align(argument):
113 return directives.choice(argument, Figure.align_h_values)
114
115 def figwidth_value(argument):
116 if argument.lower() == 'image':
117 return 'image'
118 else:
119 return directives.length_or_percentage_or_unitless(argument, 'px')
120
121 option_spec = Image.option_spec.copy()
122
123 option_spec['figwidth'] = figwidth_value
124 option_spec['figclass'] = directives.class_option
125 option_spec['figname'] = directives.unchanged
126 option_spec['align'] = align
127 has_content = True
128
129 def run(self):
130 figwidth = self.options.pop('figwidth', None)
131 figclasses = self.options.pop('figclass', None)
132 figname = self.options.pop('figname', None)
133 align = self.options.pop('align', None)
134 (image_node,) = Image.run(self)
135 if isinstance(image_node, nodes.system_message):
136 return [image_node]
137 figure_node = nodes.figure('', image_node)
138 (figure_node.source, figure_node.line
139 ) = self.state_machine.get_source_and_line(self.lineno)
140 if figwidth == 'image':
141 if PIL and self.state.document.settings.file_insertion_enabled:
142 imagepath = url2pathname(image_node['uri'])
143 try:
144 with PIL.Image.open(imagepath) as img:
145 figure_node['width'] = '%dpx' % img.size[0]
146 except (OSError, UnicodeEncodeError):
147 pass # TODO: warn/info?
148 else:
149 self.state.document.settings.record_dependencies.add(
150 imagepath.replace('\\', '/'))
151 elif figwidth is not None:
152 figure_node['width'] = figwidth
153 if figclasses:
154 figure_node['classes'] += figclasses
155 if figname:
156 figure_node['names'].append(nodes.fully_normalize_name(figname))
157 self.state.document.note_explicit_target(figure_node, figure_node)
158 if align:
159 figure_node['align'] = align
160 if self.content:
161 # optional caption (single paragraph or empty comment)
162 # + optional legend (arbitrary body elements).
163 node = nodes.Element() # anonymous container for parsing
164 self.state.nested_parse(self.content, self.content_offset, node)
165 for i, child in enumerate(node):
166 # skip temporary nodes that will be removed by transforms
167 if isinstance(child, (nodes.target, nodes.pending)):
168 figure_node += child
169 continue
170 if isinstance(child, nodes.paragraph):
171 caption = nodes.caption(child.rawsource, '',
172 *child.children)
173 caption.source = child.source
174 caption.line = child.line
175 figure_node += caption
176 break
177 if isinstance(child, nodes.comment) and len(child) == 0:
178 break
179 error = self.reporter.error(
180 'Figure caption must be a paragraph or empty comment.',
181 nodes.literal_block(self.block_text, self.block_text),
182 line=self.lineno)
183 return [figure_node, error]
184 if len(node) > i+1:
185 figure_node += nodes.legend('', *node[i+1:])
186 return [figure_node]