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