diff --git a/Wrapping/Generators/Doc/doxy2swig.py b/Wrapping/Generators/Doc/doxy2swig.py index 122fe1fbd95..4f32510e336 100755 --- a/Wrapping/Generators/Doc/doxy2swig.py +++ b/Wrapping/Generators/Doc/doxy2swig.py @@ -218,7 +218,7 @@ def do_compounddef(self, node): for n in names: if n in first: self.parse(first[n]) - self.add_text(['";', "\n"]) + self.end_docstring() for n in node.childNodes: if n not in first.values(): self.parse(n) @@ -290,7 +290,10 @@ def do_memberdef(self, node): for n in node.childNodes: if n not in first.values(): self.parse(n) - self.add_text(['";', "\n"]) + self.end_docstring() + + def end_docstring(self): + self.add_text(['";', "\n"]) def do_definition(self, node): data = node.firstChild.data diff --git a/Wrapping/Generators/Doc/itk_doxy2swig.py b/Wrapping/Generators/Doc/itk_doxy2swig.py index 6f42ce6607a..ce73f52f9ae 100755 --- a/Wrapping/Generators/Doc/itk_doxy2swig.py +++ b/Wrapping/Generators/Doc/itk_doxy2swig.py @@ -12,6 +12,47 @@ import glob from doxy2swig import * from io import StringIO +from xml.dom import minidom + +CITE_REFID_PREFIX = "citelist_1CITEREF_" +_bibliographies = {} + + +def _plain_text(node): + if node.nodeType == node.TEXT_NODE: + return node.data + if node.nodeType != node.ELEMENT_NODE: + return "" + if node.tagName == "nonbreakablespace": + return " " + if node.tagName in ("ndash", "mdash"): + return "-" + text = "".join(_plain_text(n) for n in node.childNodes) + if node.tagName == "ulink": + text += f" ({node.getAttribute('url')})" + return text + + +def _bibliography(xml_dir): + """Map citation refids to the entries of Doxygen's citelist.xml.""" + if xml_dir not in _bibliographies: + entries = {} + citelist = os.path.join(xml_dir, "citelist.xml") + if os.path.isfile(citelist): + doc = minidom.parse(citelist) + for variablelist in doc.getElementsByTagName("variablelist"): + refid = None + for child in variablelist.childNodes: + if child.nodeType != child.ELEMENT_NODE: + continue + if child.tagName == "varlistentry": + anchors = child.getElementsByTagName("anchor") + refid = anchors[0].getAttribute("id") if anchors else None + elif child.tagName == "listitem" and refid: + entries[refid] = " ".join(_plain_text(child).split()) + refid = None + _bibliographies[xml_dir] = entries + return _bibliographies[xml_dir] class itkDoxy2SWIG(Doxy2SWIG): @@ -19,6 +60,30 @@ def __init__(self, src, cpp_name="", swig_name=""): Doxy2SWIG.__init__(self, src) self.cpp_name = cpp_name self.swig_name = swig_name + self.citations = [] + + def do_ref(self, node): + refid = node.getAttribute("refid") + if not refid.startswith(CITE_REFID_PREFIX): + Doxy2SWIG.do_ref(self, node) + return + # Doxygen's [N] labels only index its own bibliography page, and + # without bibtex Doxygen writes the key instead. + self.add_text(" " + refid[len(CITE_REFID_PREFIX) :]) + if refid not in self.citations: + self.citations.append(refid) + + def end_docstring(self): + bibliography = _bibliography(self.my_dir) + references = [r for r in self.citations if r in bibliography] + if references: + self.add_text(["\n", "\n", "References:", "\n"]) + for refid in references: + entry = f"{refid[len(CITE_REFID_PREFIX) :]}: {bibliography[refid]}" + entry = entry.replace("\\", r"\\\\").replace('"', r"\"") + self.add_text(["\n", entry, "\n"]) + self.citations = [] + Doxy2SWIG.end_docstring(self) def write_to_file(self, file): if self.multi: @@ -93,7 +158,7 @@ def do_memberdef(self, node): # restore the old self.pieces self.pieces = pieces_backup else: - self.add_text(['";', "\n"]) + self.end_docstring() def d2s_dir(in_dir_name, out_swig_i): @@ -117,9 +182,14 @@ def d2s_dir(in_dir_name, out_swig_i): output.write(tpl.replace("@[{(]})@", swig_name)) else: print(f"Warning: {xfn} does not exist. Ignore it.", file=sys.stderr) + text = output.getvalue() + # An unchanged file keeps its timestamp, so the build skips SWIG for it. + if os.path.isfile(out_swig_i): + with open(out_swig_i, encoding="utf-8") as f: + if f.read() == text: + return with open(out_swig_i, "w", encoding="utf-8") as f: - f.write(output.getvalue()) - f.close() + f.write(text) def main(in_dir_name, out_swig_i): diff --git a/Wrapping/Generators/Python/Tests/CMakeLists.txt b/Wrapping/Generators/Python/Tests/CMakeLists.txt index 4f6f3419ca5..273b6da5e38 100644 --- a/Wrapping/Generators/Python/Tests/CMakeLists.txt +++ b/Wrapping/Generators/Python/Tests/CMakeLists.txt @@ -333,3 +333,10 @@ itk_python_add_test( ${CMAKE_CURRENT_SOURCE_DIR}/pyi_generator_merge_test.py ${CMAKE_CURRENT_SOURCE_DIR}/../itk/pyi_generator.py ) + +itk_python_add_test( + NAME PythonDoxy2SwigCitationTest + COMMAND + ${CMAKE_CURRENT_SOURCE_DIR}/doxy2swig_citation_test.py + ${CMAKE_CURRENT_SOURCE_DIR}/../../Doc +) diff --git a/Wrapping/Generators/Python/Tests/doxy2swig_citation_test.py b/Wrapping/Generators/Python/Tests/doxy2swig_citation_test.py new file mode 100644 index 00000000000..04f5c3cd1e6 --- /dev/null +++ b/Wrapping/Generators/Python/Tests/doxy2swig_citation_test.py @@ -0,0 +1,79 @@ +# ========================================================================== +# +# Copyright NumFOCUS +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================== + +# Usage: doxy2swig_citation_test.py + +import os +import sys +import tempfile + +sys.path.insert(0, sys.argv[1]) +from itk_doxy2swig import d2s_dir + +REF = '[{}]' +CLASS_XML = ( + '' + "itk::Foo" + f"See {REF.format('smith2000', 1)}, {REF.format('doe2001', 2)} " + f"and again {REF.format('smith2000', 1)}." + "" +) +CITELIST_XML = ( + "" + '[1]' + "A. Smith. Title. 2000." + '[2]' + "B. Doe. Other. 2001." + "" +) + + +def convert(xml_dir, citelist): + """Convert CLASS_XML in xml_dir and return the output path and its words.""" + files = {"classitk_1_1Foo.xml": CLASS_XML} + if citelist: + files["citelist.xml"] = CITELIST_XML + files["itkFoo.conf"] = ( + os.path.join(xml_dir, "classitk_1_1Foo.xml") + "\titk::Foo\titkFoo\n" + ) + for name, text in files.items(): + with open(os.path.join(xml_dir, name), "w", encoding="utf-8") as f: + f.write(text) + out = os.path.join(xml_dir, "itkFoo_doc.i") + d2s_dir(os.path.join(xml_dir, "itkFoo.conf"), out) + with open(out, encoding="utf-8") as f: + return out, " ".join(f.read().split()) + + +with tempfile.TemporaryDirectory() as with_bib, tempfile.TemporaryDirectory() as no_bib: + out, text = convert(with_bib, citelist=True) + assert "See smith2000, doe2001 and again smith2000." in text, text + assert "[1]" not in text, text + references = ( + "References: smith2000: A. Smith. Title. 2000. doe2001: B. Doe. Other. 2001." + ) + assert f'{references} ";' in text, text + + # Unchanged output keeps its timestamp, so SWIG does not rerun. + os.utime(out, (1e9, 1e9)) + convert(with_bib, citelist=True) + assert os.path.getmtime(out) == 1e9 + + _, text = convert(no_bib, citelist=False) + assert "See smith2000, doe2001 and again smith2000." in text, text + assert "References:" not in text, text diff --git a/Wrapping/macro_files/itk_auto_load_submodules.cmake b/Wrapping/macro_files/itk_auto_load_submodules.cmake index d825aa51472..23fe7b09429 100644 --- a/Wrapping/macro_files/itk_auto_load_submodules.cmake +++ b/Wrapping/macro_files/itk_auto_load_submodules.cmake @@ -306,11 +306,14 @@ function(generate_wrap_doc) COMMAND ${Python3_EXECUTABLE} ${_itk_doxy2swig_py} ${_doxy2swig_config_file} ${swig_doc_interface_file} - #DEPENDS ${ITK_WRAP_DOC_DOXYGEN_XML_FILES} ${_doxy2swig_config_file} ${_itk_doxy2swig_py} + # The target orders the Doxygen run; its stamp file reruns this command + # whenever Doxygen regenerates the XML. DEPENDS ${WRAPPER_LIBRARY_NAME}Doxygen + ${CMAKE_CURRENT_BINARY_DIR}/${WRAPPER_LIBRARY_NAME}Doxygen.stamp ${_doxy2swig_config_file} ${_itk_doxy2swig_py} + ${ITK_WRAP_DOC_SOURCE_DIR}/doxy2swig.py # COMMENT "-- Wrapping library ${_each_submodule_this_module}: Generating swig interface for inline documentation." ) endfunction()