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