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