Debian Codegraph @

pyvista/ext/viewer_directive.py

raw
1 """Viewer directive module."""
2
3 from __future__ import annotations
4
5 import os
6 from pathlib import Path
7 import shutil
8
9 from docutils import nodes
10 from docutils.parsers.rst import Directive
11 from docutils.utils import relative_path # pragma: no cover
12 from sphinx.util import logging
13 from trame_vtk.tools.vtksz2html import HTML_VIEWER_PATH
14
15 logger = logging.getLogger(__name__)
16
17
18 def is_path_relative_to(path, other):
19 """Path.is_relative_to was introduced in Python 3.9 [1].
20
21 Provide a replacement that works for all supported versions
22
23 [1] https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.is_relative_to.
24 """
25 return path.is_relative_to(other)
26
27
28 class OfflineViewerDirective(Directive):
29 required_arguments = 1
30 optional_arguments = 0
31 final_argument_whitespace = True
32 has_content = True
33
34 def run(self): # pragma: no cover
35 source_dir = Path(self.state.document.settings.env.app.srcdir)
36 output_dir = Path(self.state.document.settings.env.app.outdir)
37 # _build directory
38 build_dir = Path(self.state.document.settings.env.app.outdir).parent
39
40 # this is the path passed to 'offlineviewer:: <path>` directive
41 source_file = str(Path(self.state.document.current_source).parent / self.arguments[0])
42 source_file = Path(source_file).absolute().resolve()
43 if not Path(source_file).is_file():
44 logger.warning(f'Source file {source_file} does not exist.')
45 return []
46
47 # copy viewer HTML to _static
48 static_path = Path(output_dir) / '_static'
49 static_path.mkdir(exist_ok=True)
50 if not Path(static_path, Path(HTML_VIEWER_PATH).name).exists():
51 shutil.copy(HTML_VIEWER_PATH, static_path)
52
53 # calculate the scene asset path relative to the build directory and
54 # recreate the directory structure under output_dir/_images. This
55 # avoids overriding files with the same name e.g. index-x_yy_zz.vtksz will
56 # be generated by any index.rst file and we have a number of them.
57 # Example:
58 # source_file ${HOME}/pyvista/pyvista/doc/_build/plot_directive/getting-started/index-2_00_00.vtksz # noqa:E501
59 # dest_partial_path: plot_directive/getting-started
60 # dest_path: ${HOME}/pyvista/pyvista/doc/_build/html/_images/plot_directive/getting-started/index-2_00_00.vtksz # noqa: E501
61
62 if is_path_relative_to(source_file, build_dir):
63 dest_partial_path = Path(source_file.parent).relative_to(build_dir)
64 elif is_path_relative_to(source_file, source_dir):
65 dest_partial_path = Path(source_file.parent).relative_to(source_dir)
66 else:
67 logger.warning(
68 f'Source file {source_file} is not a subpath of either the build directory of the '
69 f'source directory. Cannot extract base path',
70 )
71 return []
72
73 dest_path = Path(output_dir).joinpath('_images').joinpath(dest_partial_path)
74 dest_path.mkdir(parents=True, exist_ok=True)
75 dest_file = dest_path.joinpath(source_file.name).resolve()
76 if source_file != dest_file:
77 try:
78 shutil.copy(source_file, dest_file)
79 except Exception as e: # noqa: BLE001
80 logger.warning(f'Failed to copy file from {source_file} to {dest_file}: {e}')
81
82 # Compute the relative path of the current source to the source directory,
83 # which is the same as the relative path of the '_static' directory to the
84 # generated HTML file.
85 relpath_to_source_root = relative_path(self.state.document.current_source, source_dir)
86 rel_viewer_path = (
87 Path() / relpath_to_source_root / '_static' / Path(HTML_VIEWER_PATH).name
88 ).as_posix()
89 rel_asset_path = Path(os.path.relpath(dest_file, static_path)).as_posix()
90 html = (
91 f"<iframe src='{rel_viewer_path}?fileURL={rel_asset_path}' "
92 "width='100%%' height='400px' frameborder='0'></iframe>"
93 )
94
95 raw_node = nodes.raw('', html, format='html')
96
97 return [raw_node]
98
99
100 def setup(app):
101 app.add_directive('offlineviewer', OfflineViewerDirective)
102
103 return {
104 'version': '0.1',
105 'parallel_read_safe': True,
106 'parallel_write_safe': True,
107 }