Slicer 5.8
Slicer is a multi-platform, free and open source software package for visualization and medical image computing
Loading...
Searching...
No Matches
conf.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2#
3# 3D Slicer documentation build configuration file, created by
4# sphinx-quickstart on Tue Mar 21 03:07:30 2017.
5#
6# This file is execfile()d with the current directory set to its
7# containing dir.
8#
9# Note that not all possible configuration values are present in this
10# autogenerated file.
11#
12# All configuration values have a default; values that are commented out
13# serve to show the default.
14
15# If extensions (or modules to document with autodoc) are in another directory,
16# add these directories to sys.path here. If the directory is relative to the
17# documentation root, use os.path.abspath to make it absolute, like shown here.
18#
19import lxml.etree as ET
20import os
21import re
22import sys
23from datetime import date
24
25sys.path.insert(0, os.path.abspath("../Base/Python"))
26
27
28# -- General configuration ------------------------------------------------
29
30# If your documentation needs a minimal Sphinx version, state it here.
31#
32# needs_sphinx = '1.0'
33
34# Add any Sphinx extension module names here, as strings. They can be
35# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
36# ones.
37extensions = [
38 "sphinx.ext.autodoc",
39 "myst_parser",
40 "sphinx_markdown_tables",
41 "notfound.extension", # Show a better 404 page when an invalid address is entered
42 "sphinx_rtd_theme",
43 "sphinx-jsonschema",
44]
45
46suppress_warnings = [
47 # Since we split the "script_repository.md" into smaller documents combined using
48 # the "include" directive, we ignore warnings like "Document headings start at H2, not H1"
49 "myst.header",
50]
51
52autodoc_mock_imports = [
53 "ctk",
54 "qt",
55 "vtk",
56]
57
58myst_enable_extensions = [
59 "attrs_inline", # Enable parsing of inline attributes (see https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#inline-attributes)
60 "colon_fence", # Allow code fence using ::: (see https://myst-parser.readthedocs.io/en/latest/using/syntax-optional.html#syntax-colon-fence)
61 "dollarmath", # Support syntax for inline and block math using `$...$` and `$$...$$`
62 # (see https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#dollar-delimited-math)
63 "linkify", # Allow automatic creation of links from URLs (it is sufficient to write https://google.com instead of <https://google.com>)
64]
65
66# Auto-generate header anchors up to level 6, so that it can be referenced like [](file.md#header-anchor).
67# (see https://myst-parser.readthedocs.io/en/latest/using/syntax-optional.html#auto-generated-header-anchors)
68myst_heading_anchors = 6
69
70# Allow display (block) math with equation label syntax
71myst_dmath_allow_labels = True
72
73
74def _extract_slicer_xy_version(slicer_src_dir):
75 """
76 Given a Slicer source director, extract <major>.<minor> version
77 from top-level `CMakeLists.txt`.
78
79 Return a dictionary containing `major` and `minor` version components as strings
80 """
81 slicer_src_dir = os.path.abspath(slicer_src_dir)
82 version_patterns = {
83 part: re.compile(rf'set\‍(Slicer_VERSION_{part.upper()} "(\d+)"\‍)')
84 for part in ["major", "minor"]
85 }
86 version_parts = {}
87
88 # Parse the CMakeLists.txt file to extract version components.
89 cmakelists_path = os.path.join(slicer_src_dir, "CMakeLists.txt")
90 with open(cmakelists_path) as cmake_file:
91 for line in cmake_file:
92 for part, pattern in version_patterns.items():
93 match = pattern.match(line.strip())
94 if match is not None:
95 version_parts[part] = match.group(1)
96 if len(version_parts) == len(version_patterns ):
97 break
98
99 if len(version_parts) != len(version_patterns):
100 raise ValueError(f"Failed to extract version from {cmakelists_path}")
101
102 return version_parts
103
104
106 """
107 Determine the Doxygen documentation version to use based on the Slicer version.
108
109 Return Doxygen version identifier (`v<major>.<minor>` for Stable, `main` for Preview)
110 """
111
112 slicer_repo_dir = os.path.dirname(os.path.dirname(__file__))
113 version_parts = _extract_slicer_xy_version(slicer_repo_dir)
114
115 # Determine the documentation branch based on the minor version parity.
116 is_even = int(version_parts["minor"]) % 2 == 0
117 return "v{major}.{minor}".format(**version_parts) if is_even else "main"
118
119
120# Construct the custom URL scheme for Slicer Doxygen documentation links.
121slicerapidocs_url_scheme = "https://apidocs.slicer.org/" + _get_apidocs_doxygen_version() + "/{{path}}#{{fragment}}"
122print(f"Slicer API documentation URL scheme: {slicerapidocs_url_scheme}")
123
124
125# Register custom URL schemes for Markdown processing.
126# These schemes allow linking to external and Slicer-specific resources dynamically.
127myst_url_schemes = {
128 "http": None,
129 "https": None,
130 "mailto": None,
131 "ftp": None,
132 "slicerapidocs": slicerapidocs_url_scheme,
133}
134
135#
136# Add any paths that contain templates here, relative to this directory.
137templates_path = ["_templates"]
138
139# The suffix(es) of source filenames.
140# You can specify multiple suffix as a list of string:
141#
142source_suffix = [".rst", ".md"]
143
144# The master toctree document.
145master_doc = "index"
146
147# General information about the project.
148project = "3D Slicer"
149copyright = f"{date.today().year}, Slicer Community"
150author = "Slicer Community"
151
152# The version info for the project you're documenting, acts as replacement for
153# |version| and |release|, also used in various other places throughout the
154# built documents.
155#
156# The short X.Y version.
157version = ""
158# The full version, including alpha/beta/rc tags.
159release = ""
160
161# List of patterns, relative to source directory, that match files and
162# directories to ignore when looking for source files.
163# This patterns also effect to html_static_path and html_extra_path
164exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "_moduledescriptions"]
165
166# Set EXCLUDE_DEVELOPER_GUIDE=True environment variable to exclude developer guide.
167# It is useful for quicker documentation generation while eiditing user manual.
168if os.environ.get("EXCLUDE_API_REFERENCE", False) == "True":
169 print("API reference is excluded from documentation.")
170 exclude_patterns.append("developer_guide/vtkTeem.rst")
171 exclude_patterns.append("developer_guide/vtkAddon.rst")
172 exclude_patterns.append("developer_guide/vtkITK.rst")
173 exclude_patterns.append("developer_guide/slicer.rst")
174 exclude_patterns.append("developer_guide/mrml.rst")
175
176# sphinx-notfound-page
177# https://github.com/readthedocs/sphinx-notfound-page
178notfound_context = {
179 "title": "Page Not Found",
180 "body": """
181<h1>Page Not Found</h1>
182<p>Sorry, we couldn't find that page.</p>
183<p>Try using the search box or go to the homepage.</p>
184""",
185}
186
187# The name of the Pygments (syntax highlighting) style to use.
188pygments_style = "sphinx"
189
190# If true, `todo` and `todoList` produce output, else they produce nothing.
191todo_include_todos = False
192
193# A string of reStructuredText that will be included at the beginning of every source file that is read.
194rst_prolog = open("global.rst.in").read()
195
196# If given, this must be the name of an image file (path relative to the configuration directory) that is the logo of the docs.
197# It is placed at the top of the sidebar; its width should therefore not exceed 200 pixels
198html_logo = "_static/images/3D-Slicer-Mark.png"
199
200# -- Options for HTML output ----------------------------------------------
201
202# The theme to use for HTML and HTML Help pages. See the documentation for
203# a list of builtin themes.
204#
205html_theme = "sphinx_rtd_theme"
206
207# Theme options are theme-specific and customize the look and feel of a theme
208# further. For a list of options available for each theme, see the
209# documentation.
210#
211html_theme_options = {
212 # Toc options
213 "includehidden": False,
214}
215
216html_context = {
217 # Enable the "Edit in GitHub link within the header of each page.
218 "display_github": True,
219 # Set the following variables to generate the resulting github URL for each page.
220 # Format Template: https://{{ github_host|default("github.com") }}/{{ github_user }}/{{ github_repo }}
221 # /blob/{{ github_version }}{{ conf_py_path }}{{ pagename }}{{ suffix }}
222 "github_user": "slicer",
223 "github_repo": "slicer",
224 "github_version": "main",
225 "conf_py_path": "/Docs/",
226}
227
228# Add any paths that contain custom static files (such as style sheets) here,
229# relative to this directory. They are copied after the builtin static files,
230# so a file named "default.css" will overwrite the builtin "default.css".
231html_static_path = ["_static"]
232
233# These paths are either relative to html_static_path
234# or fully qualified paths (eg. https://...)
235html_css_files = [
236 "css/custom.css",
237]
238
239# -- Options for HTMLHelp output ------------------------------------------
240
241# Output file base name for HTML help builder.
242htmlhelp_basename = "3DSlicerdoc"
243
244
245# -- Options for LaTeX output ---------------------------------------------
246
247latex_elements = {
248 # The paper size ('letterpaper' or 'a4paper').
249 #
250 # 'papersize': 'letterpaper',
251 # The font size ('10pt', '11pt' or '12pt').
252 #
253 # 'pointsize': '10pt',
254 # Additional stuff for the LaTeX preamble.
255 #
256 # 'preamble': '',
257 # Latex figure (float) alignment
258 #
259 # 'figure_align': 'htbp',
260}
261
262# Grouping the document tree into LaTeX files. List of tuples
263# (source start file, target name, title,
264# author, documentclass [howto, manual, or own class]).
265latex_documents = [
266 (master_doc, "3DSlicer.tex", "3D Slicer Documentation",
267 "Slicer Community", "manual"),
268]
269
270
271# -- Options for manual page output ---------------------------------------
272
273# One entry per manual page. List of tuples
274# (source start file, name, description, authors, manual section).
275man_pages = [
276 (master_doc, "3Dslicer", "3D Slicer Documentation",
277 [author], 1),
278]
279
280
281# -- Options for Texinfo output -------------------------------------------
282
283# Grouping the document tree into Texinfo files. List of tuples
284# (source start file, target name, title, author,
285# dir menu entry, description, category)
286texinfo_documents = [
287 (master_doc, "3DSlicer", "3D Slicer Documentation",
288 author, "3DSlicer", "One line description of project.",
289 "Miscellaneous"),
290]
291
292# -- Convert CLI module descriptions into markdown files ----------------
293
294# Each CLI module descriptor XML file is converted to two markdown files
295# in _moduledescriptions subfolder: *Overview.md and *Parameters.md.
296# Overview file contains the module title and description.
297# Parameters file contains detailed description of module inputs and
298# outputs, contributors, and acknowledgements.
299#
300# These md files are included at the top and bottom of each CLI module
301# documentation file (user_guide\modules\*.md). Custom content, such as
302# tutorials, screenshots, etc. can be added in between these includes.
303#
304# A copy of all CLI module descriptor XML files for modules that are
305# not part of the Slicer repository (e.g., BRAINS toolkit) are stored in
306# _extracli subfolder. Content of this folder must be updated manually
307# whenever they are updated in the original location. The process could
308# be automated with some effort, but since these bundled libraries do
309# not change frequently, manual update takes less work overall.
310
311
312# Documentation root folder (folder of this script).
313docsfolder = os.path.dirname(__file__)
314
315# List of folders that contain CLI module descriptor XML files.
316inputpaths = [
317 os.path.join(docsfolder, "../Modules/CLI"),
318 os.path.join(docsfolder, "_extracli"),
319]
320
321# List of modules to be excluded from documentation generation
322# (for example, testing modules only).
323excludenames = [
324 "CLIROITest.xml",
325 "TestGridTransformRegistration.xml",
326 "DiffusionTensorTest.xml",
327]
328
329# Output folder that contains all generated markdown files.
330outpath = os.path.join(docsfolder, "_moduledescriptions")
331os.makedirs(outpath, exist_ok=True)
332with open(os.path.join(outpath, "_readme_.txt"), "w") as descriptionfile:
333 descriptionfile.write("Content of this folder is automatically generated by Docs/conf.py from CLI module descriptor XML files\n")
334 descriptionfile.write("during documentation build. The folder can be deleted because it is automatically regenerated when needed.")
335
336
337def _generatemd(dom, docsfolder, outpath, xslt, suffix):
338 """Helper function to create markdown file from CLI module description XML file using XSLT"""
339 xsltpath = os.path.join(docsfolder, xslt)
340 transform = ET.XSLT(ET.parse(xsltpath))
341 content = str(transform(dom))
342 with open(os.path.join(outpath, os.path.splitext(name)[0] + suffix + ".md"), "w", encoding="utf8") as outfile:
343 outfile.write(content)
344
345
346for inputpath in inputpaths:
347 for root, dirs, files in os.walk(inputpath):
348 for name in files:
349 if name in excludenames:
350 continue
351 if name.endswith(".xml"):
352 print(f"Generating CLI module documentation from {name}")
353 dom = ET.parse(os.path.join(root, name))
354 _generatemd(dom, docsfolder, outpath, "cli_module_overview_to_md.xsl", "Overview")
355 _generatemd(dom, docsfolder, outpath, "cli_module_parameters_to_md.xsl", "Parameters")
_get_apidocs_doxygen_version()
Definition conf.py:105
_extract_slicer_xy_version(slicer_src_dir)
Definition conf.py:74