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