Debian Codegraph @

kapidox/generator.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # SPDX-FileCopyrightText: 2014 Alex Merry <[email protected]>
4 # SPDX-FileCopyrightText: 2014 Aurélien Gâteau <[email protected]>
5 # SPDX-FileCopyrightText: 2014 Alex Turbov <[email protected]>
6 # SPDX-FileCopyrightText: 2016 Olivier Churlaud <[email protected]>
7 #
8 # SPDX-License-Identifier: BSD-2-Clause
9
10 import codecs
11 import datetime
12 import os
13 import logging
14 from os import environ
15 import shutil
16 import subprocess
17 import tempfile
18 import sys
19 import pathlib
20 from typing import Any, Dict
21 import xml.etree.ElementTree as ET
22 import re
23 import glob
24 from pathlib import Path
25
26 import jinja2
27
28 from urllib.parse import urljoin
29
30 import xml.etree.ElementTree as xmlET
31 import json
32
33 from jinja2.environment import Template
34
35 from kapidox import utils
36 try:
37 from kapidox import depdiagram
38 DEPDIAGRAM_AVAILABLE = True
39 except ImportError:
40 DEPDIAGRAM_AVAILABLE = False
41
42 from .doxyfilewriter import DoxyfileWriter
43
44
45 # @package kapidox.generator
46 #
47 # The generator
48
49 __all__ = (
50 "Context",
51 "generate_apidocs",
52 "search_for_tagfiles",
53 "WARN_LOGFILE",
54 "build_classmap",
55 "postprocess",
56 "create_dirs",
57 "create_jinja_environment",
58 )
59
60 WARN_LOGFILE = 'doxygen-warnings.log'
61
62 HTML_SUBDIR = 'html'
63
64
65 class Context(object):
66 """
67 Holds parameters used by the various functions of the generator
68 """
69 __slots__ = (
70 # Names
71 'modulename',
72 'fancyname',
73 'title',
74 'fwinfo',
75 # KApidox files
76 'doxdatadir',
77 'resourcedir',
78 # Input
79 'srcdir',
80 'tagfiles',
81 'dependency_diagram',
82 'copyright',
83 'is_qdoc',
84 # Output
85 'outputdir',
86 'htmldir',
87 'tagfile',
88 # Output options
89 'man_pages',
90 'qhp',
91 # Binaries
92 'doxygen',
93 'qhelpgenerator',
94 )
95
96 def __init__(self, args, **kwargs):
97 # Names
98 self.title = args.title
99 # KApidox files
100 self.doxdatadir = args.doxdatadir
101 # Output options
102 self.man_pages = args.man_pages
103 self.qhp = args.qhp
104 # Binaries
105 self.doxygen = args.doxygen
106 self.qhelpgenerator = args.qhelpgenerator
107
108 for key in self.__slots__:
109 if not hasattr(self, key):
110 setattr(self, key, kwargs.get(key))
111
112
113 def create_jinja_environment(doxdatadir):
114 loader = jinja2.FileSystemLoader(os.path.join(doxdatadir, 'templates'))
115 return jinja2.Environment(loader=loader)
116
117
118 def process_toplevel_html_file(outputfile, doxdatadir, products, title, qch_enabled=False):
119
120 def sort_product(product):
121 print(product.fancyname)
122 if product.fancyname == "The KDE Frameworks":
123 return 'aa'
124 if product.fancyname == "KDE PIM":
125 return 'ab'
126 return product.fancyname.lower()
127
128 products.sort(key=sort_product)
129 mapping = {
130 'resources': './resources',
131 # steal the doxygen css from one of the frameworks
132 # this means that all the doxygen-provided images etc. will be found
133 'title': title,
134 'qch': qch_enabled,
135 'breadcrumbs': {
136 'entries': [
137 {
138 'href': './index.html',
139 'text': 'KDE API Reference'
140 }
141 ]
142 },
143 'product_list': products,
144 }
145 tmpl = create_jinja_environment(doxdatadir).get_template('frontpage.html')
146 with codecs.open(outputfile, 'w', 'utf-8') as outf:
147 outf.write(tmpl.render(mapping))
148
149 tmpl2 = create_jinja_environment(doxdatadir).get_template('search.html')
150 search_output = "search.html"
151 with codecs.open(search_output, 'w', 'utf-8') as outf:
152 outf.write(tmpl2.render(mapping))
153
154
155 def process_subgroup_html_files(outputfile, doxdatadir, groups, available_platforms, title, qch_enabled=False):
156
157 for group in groups:
158 mapping = {
159 'resources': '../resources',
160 'title': title,
161 'qch': qch_enabled,
162 'breadcrumbs': {
163 'entries': [
164 {
165 'href': '../index.html',
166 'text': 'KDE API Reference'
167 },
168 {
169 'href': './index.html',
170 'text': group.fancyname
171 }
172 ]
173 },
174 'group': group,
175 'available_platforms': sorted(available_platforms),
176 }
177
178 if not os.path.isdir(group.name):
179 os.mkdir(group.name)
180 outputfile = group.name + '/index.html'
181 tmpl = create_jinja_environment(doxdatadir).get_template('subgroup.html')
182 with codecs.open(outputfile, 'w', 'utf-8') as outf:
183 outf.write(tmpl.render(mapping))
184
185 tmpl2 = create_jinja_environment(doxdatadir).get_template('search.html')
186 search_output = group.name + "/search.html"
187 with codecs.open(search_output, 'w', 'utf-8') as outf:
188 outf.write(tmpl2.render(mapping))
189
190
191 def create_dirs(ctx):
192 ctx.htmldir = os.path.join(ctx.outputdir, HTML_SUBDIR)
193 ctx.tagfile = os.path.join(ctx.htmldir, ctx.fwinfo.fancyname + '.tags')
194
195 if not os.path.exists(ctx.outputdir):
196 os.makedirs(ctx.outputdir)
197
198 if os.path.exists(ctx.htmldir):
199 # If we have files left there from a previous run but which are no
200 # longer generated (for example because a C++ class has been removed)
201 # then postprocess will fail because the left-over file has already been
202 # processed. To avoid that, we delete the html dir.
203 shutil.rmtree(ctx.htmldir)
204 os.makedirs(ctx.htmldir)
205
206
207 def load_template(path):
208 # Set errors to 'ignore' because we don't want weird characters in Doxygen
209 # output (for example source code listing) to cause a failure
210 content = codecs.open(path, encoding='utf-8', errors='ignore').read()
211 try:
212 return jinja2.Template(content)
213 except jinja2.exceptions.TemplateSyntaxError:
214 logging.error(f"Failed to parse template {path}")
215 raise
216
217
218 def find_tagfiles(docdir, doclink=None, flattenlinks=False, exclude=None, _depth=0):
219 """Find Doxygen-generated tag files in a directory.
220
221 The tag files must have the extension .tags, and must be in the listed
222 directory, a subdirectory or a subdirectory named html of a subdirectory.
223
224 Args:
225 docdir: (string) the directory to search.
226 doclink: (string) the path or URL to use when creating the
227 documentation links; if None, this will default to
228 docdir. (optional, default None)
229 flattenlinks: (bool) if True, generated links will assume all the html
230 files are directly under doclink; else the html files are
231 assumed to be at the same relative location to doclink as
232 the tag file is to docdir; ignored if doclink is not set.
233 (optional, default False)
234
235 Returns:
236 A list of pairs of (tag_file,link_path).
237 """
238
239 if not os.path.isdir(docdir):
240 return []
241
242 if doclink is None:
243 doclink = docdir
244 flattenlinks = False
245
246 def smartjoin(pathorurl1, *args):
247 """Join paths or URLS
248
249 It figures out which it is from whether the first contains a "://"
250 """
251 if '://' in pathorurl1:
252 if not pathorurl1.endswith('/'):
253 pathorurl1 += '/'
254 return urljoin(pathorurl1, *args)
255 else:
256 return os.path.join(pathorurl1, *args)
257
258 def nestedlink(subdir):
259 if flattenlinks:
260 return doclink
261 else:
262 return smartjoin(doclink, subdir)
263
264 tagfiles = []
265
266 entries = os.listdir(docdir)
267 for e in entries:
268 if e == exclude:
269 continue
270 path = os.path.join(docdir, e)
271 if os.path.isfile(path) and e.endswith('.tags'):
272 tagfiles.append((path, doclink))
273 elif (_depth == 0 or (_depth == 1 and e == 'html')) and os.path.isdir(path):
274 tagfiles += find_tagfiles(path, nestedlink(e),
275 flattenlinks=flattenlinks,
276 _depth=_depth+1,
277 exclude=exclude)
278
279 return tagfiles
280
281
282 def search_for_tagfiles(suggestion=None, doclink=None, flattenlinks=False, searchpaths=[], exclude=None):
283 """Find Doxygen-generated tag files
284
285 See the find_tagfiles documentation for how the search is carried out in
286 each directory; this just allows a list of directories to be searched.
287
288 At least one of docdir or searchpaths must be given for it to find anything.
289
290 Args:
291 suggestion: the first place to look (will complain if there are no
292 documentation tag files there)
293 doclink: the path or URL to use when creating the documentation
294 links; if None, this will default to docdir
295 flattenlinks: if this is True, generated links will assume all the html
296 files are directly under doclink; if False (the default),
297 the html files are assumed to be at the same relative
298 location to doclink as the tag file is to docdir; ignored
299 if doclink is not set
300 searchpaths: other places to look for documentation tag files
301
302 Returns:
303 A list of pairs of (tag_file,link_path)
304 """
305
306 if suggestion is not None:
307 if not os.path.isdir(suggestion):
308 logging.warning(suggestion + " is not a directory")
309 else:
310 tagfiles = find_tagfiles(suggestion, doclink, flattenlinks, exclude)
311 if len(tagfiles) == 0:
312 logging.warning(suggestion + " does not contain any tag files")
313 else:
314 return tagfiles
315
316 for d in searchpaths:
317 tagfiles = find_tagfiles(d, doclink, flattenlinks, exclude)
318 if len(tagfiles) > 0:
319 logging.info("Documentation tag files found at " + d)
320 return tagfiles
321
322 return []
323
324
325 def menu_items(htmldir, modulename):
326 """Menu items for standard Doxygen files
327
328 Looks for a set of standard Doxygen files (like namespaces.html) and
329 provides menu text for those it finds in htmldir.
330
331 Args:
332 htmldir: (string) the directory the HTML files are contained in.
333 modulename: (string) the name of the library
334
335 Returns:
336 A list of maps with 'text' and 'href' keys.
337 """
338 entries = [
339 {'text': 'Main Page', 'href': 'index.html'},
340 {'text': 'Namespace List', 'href': 'namespaces.html'},
341 {'text': 'Namespace Members', 'href': 'namespacemembers.html'},
342 {'text': 'Alphabetical List', 'href': 'classes.html'},
343 {'text': 'Class List', 'href': 'annotated.html'},
344 {'text': 'Class Hierarchy', 'href': 'hierarchy.html'},
345 {'text': 'File List', 'href': 'files.html'},
346 {'text': 'File Members', 'href': 'globals.html'},
347 {'text': 'Modules', 'href': 'modules.html'},
348 {'text': 'Directories', 'href': 'dirs.html'},
349 {'text': 'Dependencies', 'href': modulename + '-dependencies.html'},
350 {'text': 'Related Pages', 'href': 'pages.html'},
351 ]
352 # NOTE In Python 3 filter() builtin returns an iterable, but not a list
353 # type, so explicit conversion is here!
354 return list(filter(
355 lambda e: os.path.isfile(os.path.join(htmldir, e['href'])),
356 entries))
357
358
359 def parse_dox_html(stream):
360 """Parse the HTML files produced by Doxygen, extract the key/value block we
361 add through header.html and return a dict ready for the Jinja template.
362
363 The HTML files produced by Doxygen with our custom header and footer files
364 look like this:
365
366 @code
367 <!--
368 key1: value1
369 key2: value2
370 ...
371 -->
372 <html>
373 <head>
374 ...
375 </head>
376 <body>
377 ...
378 </body>
379 </html>
380 @endcode
381
382 The parser fills the dict from the top key/value block, and add the content
383 of the body to the dict using the "content" key.
384
385 We do not use an XML parser because the HTML file might not be well-formed,
386 for example if the documentation contains raw HTML.
387
388 The key/value block is kept in a comment so that it does not appear in Qt
389 Compressed Help output, which is not post processed by us.
390 """
391 dct = {}
392 body = []
393
394 def parse_key_value_block(line):
395 if line == "<!--":
396 return parse_key_value_block
397 if line == "-->":
398 return skip_head
399 if line.startswith("<!DOCTYPE html"):
400 return skip_head
401 key, value = line.split(': ', 1)
402 dct[key] = value
403 return parse_key_value_block
404
405 def skip_head(line):
406 if line == "<body>":
407 return extract_body
408 else:
409 return skip_head
410
411 def extract_body(line):
412 if line == "</body>":
413 return None
414 body.append(line)
415 return extract_body
416
417 parser = parse_key_value_block
418 while parser is not None:
419 line = stream.readline().rstrip()
420 parser = parser(line)
421
422 dct['content'] = '\n'.join(body)
423 return dct
424
425
426 def postprocess_internal_qdoc(htmldir: str, tmpl: Template, env: Dict[str, Any]):
427 """Substitute text in HTML files
428
429 Performs text substitutions on each line in each .html file in a directory.
430
431 Args:
432 htmldir: (string) the directory containing the .html files.
433 mapping: (dict) a dict of mappings.
434
435 """
436 for path in glob.glob(os.path.join(htmldir, "*.html")):
437 newpath = f"{path}.new"
438
439 txt = Path(path).read_text()
440 env['docs'] = txt.partition('body')[2].partition('</body>')[0]
441
442 with codecs.open(newpath, 'w', 'utf-8') as outf:
443 try:
444 html = tmpl.render(env)
445 except BaseException:
446 logging.error(f"Postprocessing {path} failed")
447 raise
448
449 outf.write(html)
450
451 os.remove(path)
452 os.rename(newpath, path)
453
454
455 def postprocess_internal(htmldir, tmpl, mapping):
456 """Substitute text in HTML files
457
458 Performs text substitutions on each line in each .html file in a directory.
459
460 Args:
461 htmldir: (string) the directory containing the .html files.
462 mapping: (dict) a dict of mappings.
463
464 """
465 for name in os.listdir(htmldir):
466 if name.endswith('.html'):
467 path = os.path.join(htmldir, name)
468 newpath = path + '.new'
469
470 if name != 'classes.html' and name.startswith('class'):
471 mapping['classname'] = name[5:-5].split('_1_1')[-1]
472 mapping['fullname'] = name[5:-5].replace('_1_1', '::')
473 elif name.startswith('namespace') and name != 'namespaces.html' and not name.startswith('namespacemembers'):
474 mapping['classname'] = None
475 mapping['fullname'] = name[9:-5].replace('_1_1', '::')
476 else:
477 mapping['classname'] = None
478 mapping['fullname'] = None
479
480 with codecs.open(path, 'r', 'utf-8', errors='ignore') as f:
481 mapping['dox'] = parse_dox_html(f)
482
483 with codecs.open(newpath, 'w', 'utf-8') as outf:
484 try:
485 html = tmpl.render(mapping)
486 except Exception:
487 logging.error(f"postprocessing {path} failed")
488 raise
489 outf.write(html)
490 os.remove(path)
491 os.rename(newpath, path)
492
493
494 def build_classmap(tagfile):
495 """Parses a tagfile to get a map from classes to files
496
497 Args:
498 tagfile: the Doxygen-generated tagfile to parse.
499
500 Returns:
501 A list of maps (keys: classname and filename).
502 """
503 import xml.etree.ElementTree as ET
504 tree = ET.parse(tagfile)
505 tagfile_root = tree.getroot()
506 mapping = []
507 for compound in tagfile_root:
508 kind = compound.get('kind')
509 if kind == 'class' or kind == 'namespace':
510 name_el = compound.find('name')
511 filename_el = compound.find('filename')
512 mapping.append({'classname': name_el.text,
513 'filename': filename_el.text})
514 return mapping
515
516
517 def generate_dependencies_page(tmp_dir, doxdatadir, modulename, dependency_diagram):
518 """Create `modulename`-dependencies.md in `tmp_dir`"""
519 template_path = os.path.join(doxdatadir, 'dependencies.md.tmpl')
520 out_path = os.path.join(tmp_dir, modulename + '-dependencies.md')
521 tmpl = load_template(template_path)
522 with codecs.open(out_path, 'w', 'utf-8') as outf:
523 txt = tmpl.render({
524 'modulename': modulename,
525 'diagramname': os.path.basename(dependency_diagram),
526 })
527 outf.write(txt)
528 return out_path
529
530
531 def generate_apidocs_qdoc(ctx: Context, tmp_dir: str, doxyfile_entries=None, keep_temp_dirs=False):
532 absolute = pathlib.Path(os.path.join(ctx.outputdir, 'html')).absolute()
533
534 environ['KAPIDOX_DIR'] = ctx.doxdatadir
535
536 logging.info(f'Running QDoc (qdoc {ctx.fwinfo.path}/.qdocconf --outputdir={absolute}')
537 ret = subprocess.call(['qdoc', ctx.fwinfo.path + "/.qdocconf", f"--outputdir={absolute}"])
538 if ret != 0:
539 raise Exception("QDoc exited with a non-zero status code")
540
541
542 def generate_apidocs(ctx: Context, tmp_dir, doxyfile_entries=None, keep_temp_dirs=False):
543 """Generate the API documentation for a single directory"""
544
545 if ctx.is_qdoc:
546 return generate_apidocs_qdoc(ctx, tmp_dir, doxyfile_entries, keep_temp_dirs)
547
548 def find_src_subdir(dirlist, deeper_subd=None):
549 returnlist = []
550 for d in dirlist:
551 pth = os.path.join(ctx.fwinfo.path, d)
552 if deeper_subd is not None:
553 pth = os.path.join(pth, deeper_subd)
554 if os.path.isdir(pth) or os.path.isfile(pth):
555 returnlist.append(pth)
556 else:
557 pass # We drop it
558 return returnlist
559
560 input_list = []
561 if os.path.isfile(ctx.fwinfo.path + "/Mainpage.dox"):
562 input_list.append(ctx.fwinfo.path + "/Mainpage.dox")
563 elif os.path.isfile(ctx.fwinfo.path + "/README.md"):
564 input_list.append(ctx.fwinfo.path + "/README.md")
565
566 input_list.extend(find_src_subdir(ctx.fwinfo.srcdirs))
567 input_list.extend(find_src_subdir(ctx.fwinfo.docdir))
568 image_path_list = []
569
570 if ctx.dependency_diagram:
571 input_list.append(generate_dependencies_page(tmp_dir,
572 ctx.doxdatadir,
573 ctx.modulename,
574 ctx.dependency_diagram))
575 image_path_list.append(ctx.dependency_diagram)
576
577 doxyfile_path = os.path.join(tmp_dir, 'Doxyfile')
578 with codecs.open(doxyfile_path, 'w', 'utf-8') as doxyfile:
579 # Global defaults
580 with codecs.open(os.path.join(ctx.doxdatadir, 'Doxyfile.global'),
581 'r', 'utf-8') as f:
582 for line in f:
583 doxyfile.write(line)
584
585 writer = DoxyfileWriter(doxyfile)
586 writer.write_entry('PROJECT_NAME', ctx.fancyname)
587 # FIXME: can we get the project version from CMake? No from GIT TAGS!
588
589 # Input locations
590 image_path_list.extend(find_src_subdir(ctx.fwinfo.docdir, 'pics'))
591 writer.write_entries(
592 INPUT=input_list,
593 DOTFILE_DIRS=find_src_subdir(ctx.fwinfo.docdir, 'dot'),
594 EXAMPLE_PATH=find_src_subdir(ctx.fwinfo.exampledirs),
595 IMAGE_PATH=image_path_list)
596
597 # Other input settings
598 writer.write_entry('TAGFILES', [f + '=' + loc for f, loc in ctx.tagfiles])
599
600 # Output locations
601 writer.write_entries(
602 OUTPUT_DIRECTORY=ctx.outputdir,
603 GENERATE_TAGFILE=ctx.tagfile,
604 HTML_OUTPUT=HTML_SUBDIR,
605 WARN_LOGFILE=os.path.join(ctx.outputdir, WARN_LOGFILE))
606
607 # Other output settings
608 writer.write_entries(
609 HTML_HEADER=ctx.doxdatadir + '/header.html',
610 HTML_FOOTER=ctx.doxdatadir + '/footer.html'
611 )
612
613 # Set a layout so that properties are first
614 writer.write_entries(
615 LAYOUT_FILE=ctx.doxdatadir + '/DoxygenLayout.xml'
616 )
617
618 # Always write these, even if QHP is disabled, in case Doxygen.local
619 # overrides it
620 writer.write_entries(
621 QHP_VIRTUAL_FOLDER=ctx.modulename,
622 QHP_NAMESPACE="org.kde." + ctx.modulename,
623 QHG_LOCATION=ctx.qhelpgenerator)
624
625 writer.write_entries(
626 GENERATE_MAN=ctx.man_pages,
627 GENERATE_QHP=ctx.qhp)
628
629 if doxyfile_entries:
630 writer.write_entries(**doxyfile_entries)
631
632 # Module-specific overrides
633 if find_src_subdir(ctx.fwinfo.docdir):
634 localdoxyfile = os.path.join(find_src_subdir(ctx.fwinfo.docdir)[0], 'Doxyfile.local')
635 if os.path.isfile(localdoxyfile):
636 with codecs.open(localdoxyfile, 'r', 'utf-8') as f:
637 for line in f:
638 doxyfile.write(line)
639
640 logging.info('Running Doxygen')
641 subprocess.call([ctx.doxygen, doxyfile_path])
642
643
644 def generate_diagram(png_path, fancyname, dot_files, tmp_dir):
645 """Generate a dependency diagram for a framework.
646 """
647 def run_cmd(cmd, **kwargs):
648 try:
649 subprocess.check_call(cmd, **kwargs)
650 except subprocess.CalledProcessError as exc:
651 logging.error(f'Command {exc.cmd} failed with error code {exc.returncode}.')
652 return False
653 return True
654
655 logging.info('Generating dependency diagram')
656 dot_path = os.path.join(tmp_dir, fancyname + '.dot')
657
658 with open(dot_path, 'w') as f:
659 with_qt = False
660 ok = depdiagram.generate(f, dot_files, framework=fancyname,
661 with_qt=with_qt)
662 if not ok:
663 logging.error('Generating diagram failed')
664 return False
665
666 logging.info('- Simplifying diagram')
667 simplified_dot_path = os.path.join(tmp_dir, fancyname + '-simplified.dot')
668 with open(simplified_dot_path, 'w') as f:
669 if not run_cmd(['tred', dot_path], stdout=f):
670 return False
671
672 logging.info('- Generating diagram png')
673 if not run_cmd(['dot', '-Tpng', '-o' + png_path, simplified_dot_path]):
674 return False
675
676 # These os.unlink() calls are not in a 'finally' block on purpose.
677 # Keeping the dot files around makes it possible to inspect their content
678 # when running with the --keep-temp-dirs option. If generation fails and
679 # --keep-temp-dirs is not set, the files will be removed when the program
680 # ends because they were created in `tmp_dir`.
681 os.unlink(dot_path)
682 os.unlink(simplified_dot_path)
683 return True
684
685
686 def create_fw_context(args, lib, tagfiles, copyright=''):
687
688 # There is one more level for groups
689 if lib.part_of_group:
690 corrected_tagfiles = []
691 for k in range(len(tagfiles)):
692 # tagfiles are tuples like:
693 # ('/usr/share/doc/qt/KF5Completion.tags', '/usr/share/doc/qt')
694 # ('/where/the/tagfile/is/Name.tags', '/where/the/root/folder/is')
695 if tagfiles[k][1].startswith("http://") or tagfiles[k][1].startswith("https://"):
696 corrected_tagfiles.append(tagfiles[k])
697 else:
698 corrected_tagfiles.append((tagfiles[k][0], '../' + tagfiles[k][1]))
699 else:
700 corrected_tagfiles = tagfiles
701
702 return Context(args,
703 # Names
704 modulename=lib.name,
705 fancyname=lib.fancyname,
706 fwinfo=lib,
707 # KApidox files
708 resourcedir=('../../../resources' if lib.part_of_group
709 else '../../resources'),
710 # Input
711 copyright=copyright,
712 tagfiles=corrected_tagfiles,
713 dependency_diagram=lib.dependency_diagram,
714 # Output
715 outputdir=lib.outputdir,
716 is_qdoc=lib.metainfo['qdoc'],
717 )
718
719
720 def gen_fw_apidocs(ctx, tmp_base_dir):
721 create_dirs(ctx)
722 # tmp_dir is deleted when tmp_base_dir is
723 tmp_dir = tempfile.mkdtemp(prefix=ctx.modulename + '-', dir=tmp_base_dir)
724 generate_apidocs(ctx, tmp_dir,
725 doxyfile_entries=dict(WARN_IF_UNDOCUMENTED=True)
726 )
727
728
729 def create_fw_tagfile_tuple(lib):
730 tagfile = os.path.abspath(
731 os.path.join(
732 lib.outputdir,
733 'html',
734 lib.fancyname+'.tags'))
735 if lib.part_of_group:
736 prefix = '../../'
737 else:
738 prefix = '../../'
739 return tagfile, prefix + lib.outputdir + '/html/'
740
741
742 def finish_fw_apidocs_doxygen(ctx: Context, env: Dict[str, Any]):
743 tmpl = create_jinja_environment(ctx.doxdatadir).get_template('library.html')
744 postprocess_internal(ctx.htmldir, tmpl, env)
745
746 tmpl2 = create_jinja_environment(ctx.doxdatadir).get_template('search.html')
747 search_output = ctx.fwinfo.outputdir + "/html/search.html"
748 with codecs.open(search_output, 'w', 'utf-8') as outf:
749 outf.write(tmpl2.render(env))
750
751
752 def finish_fw_apidocs_qdoc(ctx: Context, env: Dict[str, Any]):
753 tmpl = create_jinja_environment(ctx.doxdatadir).get_template('qdoc-wrapper.html')
754 postprocess_internal_qdoc(ctx.htmldir, tmpl, env)
755
756
757 def gen_template_environment(ctx: Context) -> Dict[str, Any]:
758 classmap = build_classmap(ctx.tagfile)
759
760 entries = [{
761 'href': '../../index.html',
762 'text': 'KDE API Reference'
763 }]
764
765 if ctx.fwinfo.part_of_group:
766 entries[0]['href'] = '../' + entries[0]['href']
767 entries.append({'href': '../../index.html', 'text': ctx.fwinfo.product.fancyname })
768
769 entries.append({'href': 'index.html', 'text': ctx.fancyname })
770
771 mapping = {
772 'qch': ctx.qhp,
773 'doxygencss': 'doxygen.css',
774 'resources': ctx.resourcedir,
775 'title': ctx.title,
776 'fwinfo': ctx.fwinfo,
777 'copyright': f"1996-{datetime.date.today().year} The KDE developers",
778 'doxygen_menu': {'entries': menu_items(ctx.htmldir, ctx.modulename)},
779 'class_map': {'classes': classmap},
780 'kapidox_version': utils.get_kapidox_version(),
781 'breadcrumbs': {
782 'entries': entries
783 },
784 }
785
786 return mapping
787
788
789 def finish_fw_apidocs(ctx: Context):
790 env = gen_template_environment(ctx)
791
792 if ctx.is_qdoc:
793 logging.info('Postprocessing QtDoc...')
794
795 finish_fw_apidocs_qdoc(ctx, env)
796
797 else:
798 logging.info('Postprocessing Doxygen...')
799
800 finish_fw_apidocs_doxygen(ctx, env)
801
802
803 def indexer(lib):
804 """ Create json index from xml
805 <add>
806 <doc>
807 <field name="type">source</field>
808 <field name="name">kcmodule.cpp</field>
809 <field name="url">kcmodule_8cpp_source.html#l00001</field>
810 <field name="keywords"></field>
811 <field name="text"></field>
812 </doc>
813 </add>
814 """
815
816 doclist = []
817 tree = xmlET.parse(lib.outputdir + '/searchdata.xml')
818 for doc_child in tree.getroot():
819 field = {}
820 for child in doc_child:
821 if child.attrib['name'] == "type":
822 if child.text == 'source':
823 field = None
824 break # We go to next <doc>
825 field['type'] = child.text
826 elif child.attrib['name'] == "name":
827 field['name'] = child.text
828 elif child.attrib['name'] == "url":
829 field['url'] = child.text
830 elif child.attrib['name'] == "keywords":
831 field['keyword'] = child.text
832 elif child.attrib['name'] == "text":
833 field['text'] = "" if child.text is None else child.text
834 if field is not None:
835 doclist.append(field)
836
837 indexdic = {
838 'name': lib.name,
839 'fancyname': lib.fancyname,
840 'docfields': doclist
841 }
842
843 with open(lib.outputdir + '/html/searchdata.json', 'w') as f:
844 for chunk in json.JSONEncoder().iterencode(indexdic):
845 f.write(chunk)
846
847
848 def create_product_index(product):
849 doclist = []
850 for lib in product.libraries:
851 with open(lib.outputdir+'/html/searchdata.json', 'r') as f:
852 libindex = json.load(f)
853 for item in libindex['docfields']:
854 if lib.part_of_group:
855 item['url'] = lib.name.lower() + '/html/' + item['url']
856 else:
857 item['url'] = 'html/' + item['url']
858 doclist.append(libindex)
859
860 indexdic = {
861 'name': product.name,
862 'fancyname': product.fancyname,
863 'libraries': doclist
864 }
865
866 with open(product.outputdir + '/searchdata.json', 'w') as f:
867 for chunk in json.JSONEncoder().iterencode(indexdic):
868 f.write(chunk)
869
870
871 def create_global_index(products):
872 doclist = []
873 for product in products:
874 if product.metainfo['qdoc']:
875 continue
876
877 with open(product.outputdir+'/searchdata.json', 'r') as f:
878 prodindex = json.load(f)
879 for proditem in prodindex['libraries']:
880 for item in proditem['docfields']:
881 item['url'] = os.path.join(product.name, item['url'])
882 doclist.append(prodindex)
883
884 indexdic = {
885 'all': doclist
886 }
887 with open('searchdata.json', 'w') as f:
888 for chunk in json.JSONEncoder().iterencode(indexdic):
889 f.write(chunk)
890
891
892 def create_qch(products, tagfiles):
893 tag_root = "QtHelpProject"
894 tag_files = "files"
895 tag_filter_section = "filterSection"
896 tag_keywords = "keywords"
897 tag_toc = "toc"
898 for product in products:
899 tree_out = ET.ElementTree(ET.Element(tag_root))
900 root_out = tree_out.getroot()
901 root_out.set("version", "1.0")
902 namespace = ET.SubElement(root_out, "namespace")
903 namespace.text = "org.kde." + product.name
904 virtual_folder = ET.SubElement(root_out, "virtualFolder")
905 virtual_folder.text = product.name
906 filter_section = ET.SubElement(root_out, tag_filter_section)
907 filter_attribute = ET.SubElement(filter_section, "filterAttribute")
908 filter_attribute.text = "doxygen"
909 toc = ET.SubElement(filter_section, "toc")
910 keywords = ET.SubElement(filter_section, tag_keywords)
911 if len(product.libraries) > 0:
912 if product.libraries[0].part_of_group:
913 product_index_section = ET.SubElement(toc, "section", {'ref': product.name + "/index.html", 'title': product.fancyname})
914 files = ET.SubElement(filter_section, tag_files)
915
916 for lib in sorted(product.libraries, key=lambda lib: lib.name):
917 tree = ET.parse(lib.outputdir + '/html/index.qhp')
918 root = tree.getroot()
919 for child in root.findall(".//*[@ref]"):
920 if lib.part_of_group:
921 child.attrib['ref'] = lib.name + "/html/" + child.attrib['ref']
922 else:
923 child.attrib['ref'] = "html/" + child.attrib['ref']
924 child.attrib['ref'] = product.name + '/' + child.attrib['ref']
925
926 for child in root.find(".//"+tag_toc):
927 if lib.part_of_group:
928 product_index_section.append(child)
929 else:
930 toc.append(child)
931
932 for child in root.find(".//keywords"):
933 keywords.append(child)
934
935 resources = [
936 "*.json",
937 product.name + "/*.json",
938 "resources/css/*.css",
939 "resources/3rd-party/bootstrap/css/*.css",
940 "resources/3rd-party/jquery/jquery-3.1.0.min.js",
941 "resources/*.svg",
942 "resources/js/*.js",
943 "resources/icons/*",
944 ]
945 if product.part_of_group:
946 resources.extend([
947 product.name + "/*.html",
948 product.name + "/" + lib.name + "/html/*.html",
949 product.name + "/" + lib.name + "/html/*.png",
950 product.name + "/" + lib.name + "/html/*.css",
951 product.name + "/" + lib.name + "/html/*.js",
952 product.name + "/" + lib.name + "/html/*.json"
953 ])
954
955 else:
956 resources.extend([
957 product.name + "/html/*.html",
958 product.name + "/html/*.png",
959 product.name + "/html/*.css",
960 product.name + "/html/*.js"
961 ])
962
963 for resource in resources:
964 file_elem = ET.SubElement(files, "file")
965 file_elem.text = resource
966
967 if not os.path.isdir('qch'):
968 os.mkdir('qch')
969
970 name = product.name+".qhp"
971 outname = product.name+".qch"
972 tree_out.write(name, encoding="utf-8", xml_declaration=True)
973
974 # On many distributions, qhelpgenerator from Qt5 is suffixed with
975 # "-qt5". Look for it first, and fall back to unsuffixed one if
976 # not found.
977 qhelpgenerator = shutil.which("qhelpgenerator-qt5")
978
979 if qhelpgenerator is None:
980 qhelpgenerator = "qhelpgenerator"
981
982 subprocess.call([qhelpgenerator, name, '-o', 'qch/'+outname])
983 os.remove(name)