New MarkDown parser
[gtk-doc.git] / gtkdoc-mkdb.in
blob31e227bf97f901dcfea7e0d273321c05660dd087
1 #!@PERL@ -w
2 # -*- cperl -*-
4 # gtk-doc - GTK DocBook documentation generator.
5 # Copyright (C) 1998  Damon Chaplin
6 #               2007,2008,2009  Stefan Kost
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 #############################################################################
24 # Script      : gtkdoc-mkdb
25 # Description : This creates the DocBook files from the edited templates.
26 #############################################################################
28 use warnings;
29 use strict;
30 use Getopt::Long;
32 push @INC, '@PACKAGE_DATA_DIR@';
33 require "gtkdoc-common.pl";
35 # Options
37 # name of documentation module
38 my $MODULE;
39 my $TMPL_DIR;
40 my $SGML_OUTPUT_DIR;
41 my @SOURCE_DIRS;
42 my $SOURCE_SUFFIXES = "";
43 my $IGNORE_FILES = "";
44 my $PRINT_VERSION;
45 my $PRINT_HELP;
46 my $MAIN_SGML_FILE;
47 my $EXPAND_CONTENT_FILES = "";
48 my $INLINE_MARKUP_MODE;
49 my $DEFAULT_STABILITY;
50 my $DEFAULT_INCLUDES;
51 my $OUTPUT_FORMAT;
52 my $NAME_SPACE = "";
53 my $OUTPUT_ALL_SYMBOLS;
54 my $OUTPUT_SYMBOLS_WITHOUT_SINCE;
56 my %optctl = ('module' => \$MODULE,
57               'source-dir' => \@SOURCE_DIRS,
58               'source-suffixes' => \$SOURCE_SUFFIXES,
59               'ignore-files' => \$IGNORE_FILES,
60               'output-dir' => \$SGML_OUTPUT_DIR,
61               'tmpl-dir' => \$TMPL_DIR,
62               'version' => \$PRINT_VERSION,
63               'help' => \$PRINT_HELP,
64               'main-sgml-file' => \$MAIN_SGML_FILE,
65               'expand-content-files' => \$EXPAND_CONTENT_FILES,
66               'sgml-mode' => \$INLINE_MARKUP_MODE,
67               'xml-mode' => \$INLINE_MARKUP_MODE,
68               'default-stability' => \$DEFAULT_STABILITY,
69               'default-includes' => \$DEFAULT_INCLUDES,
70               'output-format' => \$OUTPUT_FORMAT,
71               'name-space' => \$NAME_SPACE,
72               'outputallsymbols' => \$OUTPUT_ALL_SYMBOLS,
73               'outputsymbolswithoutsince' => \$OUTPUT_SYMBOLS_WITHOUT_SINCE
74               );
75 GetOptions(\%optctl, "module=s", "source-dir:s", "source-suffixes:s",
76     "ignore-files:s", "output-dir:s", "tmpl-dir:s", "version", "outputallsymbols",
77     "outputsymbolswithoutsince",
78     "expand-content-files:s", "main-sgml-file:s", "extra-db-files:s", "help",
79     "sgml-mode", "xml-mode", "default-stability:s", "default-includes:s",
80     "output-format:s", "name-space:s");
82 if ($PRINT_VERSION) {
83     print "@VERSION@\n";
84     exit 0;
87 if (!$MODULE) {
88     $PRINT_HELP = 1;
91 if ($DEFAULT_STABILITY && $DEFAULT_STABILITY ne "Stable"
92     && $DEFAULT_STABILITY ne "Private" && $DEFAULT_STABILITY ne "Unstable") {
93     $PRINT_HELP = 1;
96 if ($PRINT_HELP) {
97     print <<EOF;
98 gtkdoc-mkdb version @VERSION@ - generate docbook files
100 --module=MODULE_NAME       Name of the doc module being parsed
101 --source-dir=DIRNAME       Directories which contain inline reference material
102 --source-suffixes=SUFFIXES Suffixes of source files to scan, comma-separated
103 --ignore-files=FILES       Files or directories which should not be scanned
104                            May be used more than once for multiple directories
105 --output-dir=DIRNAME       Directory to put the generated DocBook files in
106 --tmpl-dir=DIRNAME         Directory in which template files may be found
107 --main-sgml-file=FILE      File containing the toplevel DocBook file.
108 --expand-content-files=FILES Extra DocBook files to expand abbreviations in.
109 --output-format=FORMAT     Format to use for the generated docbook, XML or SGML.
110 --{xml,sgml}-mode          Allow DocBook markup in inline documentation.
111 --default-stability=LEVEL  Specify default stability Level. Valid values are
112                            Stable, Unstable, or Private.
113 --default-includes=FILENAMES Specify default includes for section Synopsis
114 --name-space=NS            Omit namespace in index.
115 --version                  Print the version of this program
116 --help                     Print this help
118     exit 0;
121 my ($empty_element_end, $doctype_header);
123 # autodetect output format
124 if (! defined($OUTPUT_FORMAT) || ($OUTPUT_FORMAT eq "")) {
125     if (!$MAIN_SGML_FILE) {
126         if (-e "${MODULE}-docs.xml") {
127             $OUTPUT_FORMAT = "xml";
128         } else {
129             $OUTPUT_FORMAT = "sgml";
130         }
131     } else {
132         if ($MAIN_SGML_FILE =~ m/.*\.(.*ml)$/i) {
133             $OUTPUT_FORMAT = lc($1);
134         }
135     }
137 } else {
138     $OUTPUT_FORMAT = lc($OUTPUT_FORMAT);
141 #print "DEBUG: output-format: [$OUTPUT_FORMAT]\n";
143 if ($OUTPUT_FORMAT eq "xml") {
144     if (!$MAIN_SGML_FILE) {
145         # backwards compatibility
146         if (-e "${MODULE}-docs.sgml") {
147             $MAIN_SGML_FILE = "${MODULE}-docs.sgml";
148         } else {
149             $MAIN_SGML_FILE = "${MODULE}-docs.xml";
150         }
151     }
152     $empty_element_end = "/>";
154     if (-e $MAIN_SGML_FILE) {
155         open(INPUT, "<$MAIN_SGML_FILE") || die "Can't open $MAIN_SGML_FILE";
156         $doctype_header = "";
157         while (<INPUT>) {
158             if (/^\s*<(book|chapter|article)/) {
159                 # check that the top-level tag or the doctype decl contain the xinclude namespace decl
160                 if (($_ !~ m/http:\/\/www.w3.org\/200[13]\/XInclude/) && ($doctype_header !~ m/http:\/\/www.w3.org\/200[13]\/XInclude/m)) {
161                     $doctype_header = "";
162                 }
163                 last;
164             }
165             $doctype_header .= $_;
166         }
167         close(INPUT);
168         $doctype_header =~ s/<!DOCTYPE \w+/<!DOCTYPE refentry/;
169         # if there are SYSTEM ENTITIES here, we should prepend "../" to the path
170         # FIXME: not sure if we can do this now, as people already work-around the problem
171         # $doctype_header =~ s#<!ENTITY % ([a-zA-Z-]+) SYSTEM \"([^/][a-zA-Z./]+)\">#<!ENTITY % $1 SYSTEM \"../$2\">#g;
172     } else {
173         $doctype_header =
174 "<?xml version=\"1.0\"?>\n" .
175 "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.3//EN\"\n" .
176 "               \"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd\"\n" .
177 "[\n" .
178 "  <!ENTITY % local.common.attrib \"xmlns:xi  CDATA  #FIXED 'http://www.w3.org/2003/XInclude'\">\n" .
179 "]>\n";
180     }
181 } else {
182     if (!$MAIN_SGML_FILE) {
183         $MAIN_SGML_FILE = "${MODULE}-docs.sgml";
184     }
185     $empty_element_end = ">";
186     $doctype_header = "";
189 my $ROOT_DIR = ".";
191 # All the files are written in subdirectories beneath here.
192 $TMPL_DIR = $TMPL_DIR ? $TMPL_DIR : "$ROOT_DIR/tmpl";
194 # This is where we put all the DocBook output.
195 $SGML_OUTPUT_DIR = $SGML_OUTPUT_DIR ? $SGML_OUTPUT_DIR : "$ROOT_DIR/$OUTPUT_FORMAT";
197 # This file contains the object hierarchy.
198 my $OBJECT_TREE_FILE = "$ROOT_DIR/$MODULE.hierarchy";
200 # This file contains the interfaces.
201 my $INTERFACES_FILE = "$ROOT_DIR/$MODULE.interfaces";
203 # This file contains the prerequisites.
204 my $PREREQUISITES_FILE = "$ROOT_DIR/$MODULE.prerequisites";
206 # This file contains signal arguments and names.
207 my $SIGNALS_FILE = "$ROOT_DIR/$MODULE.signals";
209 # The file containing Arg information.
210 my $ARGS_FILE = "$ROOT_DIR/$MODULE.args";
212 # These global arrays store information on signals. Each signal has an entry
213 # in each of these arrays at the same index, like a multi-dimensional array.
214 my @SignalObjects;        # The GtkObject which emits the signal.
215 my @SignalNames;        # The signal name.
216 my @SignalReturns;        # The return type.
217 my @SignalFlags;        # Flags for the signal
218 my @SignalPrototypes;        # The rest of the prototype of the signal handler.
220 # These global arrays store information on Args. Each Arg has an entry
221 # in each of these arrays at the same index, like a multi-dimensional array.
222 my @ArgObjects;                # The GtkObject which has the Arg.
223 my @ArgNames;                # The Arg name.
224 my @ArgTypes;                # The Arg type - gint, GtkArrowType etc.
225 my @ArgFlags;                # How the Arg can be used - readable/writable etc.
226 my @ArgNicks;                # The nickname of the Arg.
227 my @ArgBlurbs;          # Docstring of the Arg.
228 my @ArgDefaults;        # Default value of the Arg.
229 my @ArgRanges;                # The range of the Arg type
230 # These global hashes store declaration info keyed on a symbol name.
231 my %Declarations;
232 my %DeclarationTypes;
233 my %DeclarationConditional;
234 my %DeclarationOutput;
235 my %Deprecated;
236 my %Since;
237 my %StabilityLevel;
238 my %StructHasTypedef;
240 # These global hashes store the existing documentation.
241 my %SymbolDocs;
242 my %SymbolTypes;
243 my %SymbolParams;
244 my %SymbolSourceFile;
245 my %SymbolSourceLine;
247 # These global hashes store documentation scanned from the source files.
248 my %SourceSymbolDocs;
249 my %SourceSymbolParams;
250 my %SourceSymbolSourceFile;
251 my %SourceSymbolSourceLine;
253 # all documentation goes in here, so we can do coverage analysis
254 my %AllSymbols;
255 my %AllIncompleteSymbols;
256 my %AllUnusedSymbols;
257 my %AllDocumentedSymbols;
259 # Undeclared yet documented symbols
260 my %UndeclaredSymbols;
262 # These global arrays store GObject, subclasses and the hierarchy (also of
263 # non-object derived types).
264 my @Objects;
265 my @ObjectLevels;
266 my %ObjectRoots;
268 my %Interfaces;
269 my %Prerequisites;
271 # holds the symbols which are mentioned in $MODULE-sections.txt and in which
272 # section they are defined
273 my %KnownSymbols;
274 my %SymbolSection;
275 my %SymbolSectionId;
277 # collects index entries
278 my %IndexEntriesFull;
279 my %IndexEntriesSince;
280 my %IndexEntriesDeprecated;
282 # Standard C preprocessor directives, which we ignore for '#' abbreviations.
283 my %PreProcessorDirectives;
284 $PreProcessorDirectives{"assert"} = 1;
285 $PreProcessorDirectives{"define"} = 1;
286 $PreProcessorDirectives{"elif"} = 1;
287 $PreProcessorDirectives{"else"} = 1;
288 $PreProcessorDirectives{"endif"} = 1;
289 $PreProcessorDirectives{"error"} = 1;
290 $PreProcessorDirectives{"if"} = 1;
291 $PreProcessorDirectives{"ifdef"} = 1;
292 $PreProcessorDirectives{"ifndef"} = 1;
293 $PreProcessorDirectives{"include"} = 1;
294 $PreProcessorDirectives{"line"} = 1;
295 $PreProcessorDirectives{"pragma"} = 1;
296 $PreProcessorDirectives{"unassert"} = 1;
297 $PreProcessorDirectives{"undef"} = 1;
298 $PreProcessorDirectives{"warning"} = 1;
300 # remember used annotation (to write minimal glossary)
301 my %AnnotationsUsed;
303 # the annotations are defined at:
304 # https://live.gnome.org/GObjectIntrospection/Annotations
305 my %AnnotationDefinition = (
306     'allow-none' => "NULL is ok, both for passing and for returning.",
307     'array' => "Parameter points to an array of items.",
308     'attribute' => "Deprecated free-form custom annotation, replaced by (attributes) annotation.",
309     'attributes' => "Free-form key-value pairs.",
310     'closure' => "This parameter is a 'user_data', for callbacks; many bindings can pass NULL here.",
311     'constructor' => "This symbol is a constructor, not a static method.",
312     'destroy' => "This parameter is a 'destroy_data', for callbacks.",
313     'default' => "Default parameter value (for in case the <acronym>shadows</acronym>-to function has less parameters).",
314     'element-type' => "Generics and defining elements of containers and arrays.",
315     'error-domains' => "Typed errors. Similar to throws in Java.",
316     'foreign' => "This is a foreign struct.",
317     'get-value-func' => "The specified function is used to convert a struct from a GValue, must be a GTypeInstance.",
318     'in' => "Parameter for input. Default is <acronym>transfer none</acronym>.",
319     'inout' => "Parameter for input and for returning results. Default is <acronym>transfer full</acronym>.",
320     'in-out' => "Parameter for input and for returning results. Default is <acronym>transfer full</acronym>.",
321     'method' => "This is a method",
322     'not-error' => "A GError parameter is not to be handled like a normal GError.",
323     'out' => "Parameter for returning results. Default is <acronym>transfer full</acronym>.",
324     'out caller-allocates' => "Out parameter, where caller must allocate storage.",
325     'out callee-allocates' => "Out parameter, where caller must allocate storage.",
326     'ref-func' => "The specified function is used to ref a struct, must be a GTypeInstance.",
327     'rename-to' => "Rename the original symbol's name to SYMBOL.",
328     'scope call' => "The callback is valid only during the call to the method.",
329     'scope async' => "The callback is valid until first called.",
330     'scope notified' => "The callback is valid until the GDestroyNotify argument is called.",
331     'set-value-func' => "The specified function is used to convert from a struct to a GValue, must be a GTypeInstance.",
332     'skip' => "Exposed in C code, not necessarily available in other languages.",
333     'transfer container' => "Free data container after the code is done.",
334     'transfer floating' => "Alias for <acronym>transfer none</acronym>, used for objects with floating refs.",
335     'transfer full' => "Free data after the code is done.",
336     'transfer none' => "Don't free data after the code is done.",
337     'type' => "Override the parsed C type with given type.",
338     'unref-func' => "The specified function is used to unref a struct, must be a GTypeInstance.",
339     'virtual' => "This is the invoker for a virtual method.",
340     'value' => "The specified value overrides the evaluated value of the constant."
343 # Create the root DocBook output directory if it doens't exist.
344 if (! -e $SGML_OUTPUT_DIR) {
345     mkdir ("$SGML_OUTPUT_DIR", 0777)
346         || die "Can't create directory: $SGML_OUTPUT_DIR";
349 # Function and other declaration output settings.
350 my $RETURN_TYPE_FIELD_WIDTH = 20;
351 my $SYMBOL_FIELD_WIDTH = 36;
352 my $SIGNAL_FIELD_WIDTH = 16;
353 my $PARAM_FIELD_COUNT = 2;
355 &ReadKnownSymbols ("$ROOT_DIR/$MODULE-sections.txt");
356 &ReadSignalsFile ($SIGNALS_FILE);
357 &ReadArgsFile ($ARGS_FILE);
358 &ReadObjectHierarchy;
359 &ReadInterfaces;
360 &ReadPrerequisites;
362 &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-decl.txt", 0);
363 if (-f "$ROOT_DIR/$MODULE-overrides.txt") {
364     &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-overrides.txt", 1);
367 for my $dir (@SOURCE_DIRS) {
368     &ReadSourceDocumentation ($dir);
371 my $changed = &OutputSGML ("$ROOT_DIR/$MODULE-sections.txt");
373 # If any of the DocBook SGML files have changed, update the timestamp file (so
374 # it can be used for Makefile dependencies).
375 if ($changed || ! -e "$ROOT_DIR/sgml.stamp") {
377     # try to detect the common prefix
378     # GtkWidget, GTK_WIDGET, gtk_widget -> gtk
379     if ($NAME_SPACE eq "") {
380         $NAME_SPACE="";
381         my $pos=0;
382         my $ratio=0.0;
383         do {
384             my %prefix;
385             my $letter="";
386             foreach my $symbol (keys(%IndexEntriesFull)) {
387                 if(($NAME_SPACE eq "") || $symbol =~ /^$NAME_SPACE/i) {
388                     if (length($symbol)>$pos) {
389                         $letter=substr($symbol,$pos,1);
390                         # stop prefix scanning
391                         if ($letter eq "_") {
392                             # stop on "_"
393                             last;
394                         }
395                         # Should we also stop on a uppercase char, if last was lowercase
396                         #   GtkWidget, if we have the 'W' and had the 't' before
397                         # or should we count upper and lowercase, and stop one 2nd uppercase, if we already had a lowercase
398                         #   GtkWidget, the 'W' would be the 2nd uppercase and with 't','k' we had lowercase chars before
399                         # need to recound each time as this is per symbol
400                         $prefix{uc($letter)}++;
401                     }
402                 }
403             }
404             if ($letter ne "" && $letter ne "_") {
405                 my $maxletter="";
406                 my $maxsymbols=0;
407                 foreach $letter (keys(%prefix)) {
408                     #print "$letter: $prefix{$letter}.\n";
409                     if ($prefix{$letter}>$maxsymbols) {
410                         $maxletter=$letter;
411                         $maxsymbols=$prefix{$letter};
412                     }
413                 }
414                 $ratio = scalar(keys(%IndexEntriesFull)) / $prefix{$maxletter};
415                 #print "most symbols start with $maxletter, that is ". (100 * $ratio) ." %\n";
416                 if ($ratio > 0.9) {
417                     # do another round
418                     $NAME_SPACE .= $maxletter;
419                 }
420                 $pos++;
421             }
422             else {
423                 $ratio=0.0;
424             }
425         } while ($ratio > 0.9);
426         #print "most symbols start with $NAME_SPACE\n";
427     }
429     &OutputIndexFull;
430     &OutputDeprecatedIndex;
431     &OutputSinceIndexes;
432     &OutputAnnotationGlossary;
434     open (TIMESTAMP, ">$ROOT_DIR/sgml.stamp")
435         || die "Can't create $ROOT_DIR/sgml.stamp: $!";
436     print (TIMESTAMP "timestamp");
437     close (TIMESTAMP);
440 #############################################################################
441 # Function    : OutputObjectList
442 # Description : This outputs the alphabetical list of objects, in a columned
443 #                table.
444 #               FIXME: Currently this also outputs ancestor objects
445 #                which may not actually be in this module.
446 # Arguments   : none
447 #############################################################################
449 sub OutputObjectList {
450     my $cols = 3;
452     # FIXME: use $OUTPUT_FORMAT
453     # my $old_object_index = "$SGML_OUTPUT_DIR/object_index.$OUTPUT_FORMAT";
454     my $old_object_index = "$SGML_OUTPUT_DIR/object_index.sgml";
455     my $new_object_index = "$SGML_OUTPUT_DIR/object_index.new";
457     open (OUTPUT, ">$new_object_index")
458         || die "Can't create $new_object_index: $!";
460     if ($OUTPUT_FORMAT eq "xml") {
461         my $header = $doctype_header;
463         $header =~ s/<!DOCTYPE \w+/<!DOCTYPE informaltable/;
464         print (OUTPUT "$header");
465     }
467     print (OUTPUT <<EOF);
468 <informaltable pgwide="1" frame="none">
469 <tgroup cols="$cols">
470 <colspec colwidth="1*"${empty_element_end}
471 <colspec colwidth="1*"${empty_element_end}
472 <colspec colwidth="1*"${empty_element_end}
473 <tbody>
476     my $count = 0;
477     my $object;
478     foreach $object (sort (@Objects)) {
479         my $xref = &MakeXRef ($object);
480         if ($count % $cols == 0) { print (OUTPUT "<row>\n"); }
481         print (OUTPUT "<entry>$xref</entry>\n");
482         if ($count % $cols == ($cols - 1)) { print (OUTPUT "</row>\n"); }
483         $count++;
484     }
485     if ($count == 0) {
486         # emit an empty row, since empty tables are invalid
487         print (OUTPUT "<row><entry> </entry></row>\n");
488     }
489     else {
490         if ($count % $cols > 0) {
491             print (OUTPUT "</row>\n");
492         }
493     }
495     print (OUTPUT <<EOF);
496 </tbody></tgroup></informaltable>
498     close (OUTPUT);
500     &UpdateFileIfChanged ($old_object_index, $new_object_index, 0);
503 #############################################################################
504 # Function    : TrimTextBlock
505 # Description : Trims extra whitespace. Empty lines inside a block are
506 #                preserved.
507 # Arguments   : $desc - the text block to trim. May contain newlines.
508 #############################################################################
510 sub TrimTextBlock {
511   my ($desc) = @_;
512   
513   # strip leading spaces on the block
514   $desc =~ s/^\s+//s;
515   # strip trailing spaces on every line
516   $desc =~ s/\s+$/\n/mg;
517   
518   return $desc;
522 #############################################################################
523 # Function    : OutputSGML
524 # Description : This collects the output for each section of the docs, and
525 #                outputs each file when the end of the section is found.
526 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
527 #                the functions/macros/structs etc. being documented, organised
528 #                into sections and subsections.
529 #############################################################################
531 sub OutputSGML {
532     my ($file) = @_;
534     #print "Reading: $file\n";
535     open (INPUT, $file)
536         || die "Can't open $file: $!";
537     my $filename = "";
538     my $book_top = "";
539     my $book_bottom = "";
540     my $includes = (defined $DEFAULT_INCLUDES) ? $DEFAULT_INCLUDES : "";
541     my $section_includes = "";
542     my $in_section = 0;
543     my $title = "";
544     my $section_id = "";
545     my $subsection = "";
546     my $synopsis;
547     my $details;
548     my $num_symbols;
549     my $changed = 0;
550     my $signals_synop = "";
551     my $signals_desc = "";
552     my $args_synop = "";
553     my $child_args_synop = "";
554     my $style_args_synop = "";
555     my $args_desc = "";
556     my $child_args_desc = "";
557     my $style_args_desc = "";
558     my $hierarchy = "";
559     my $interfaces = "";
560     my $implementations = "";
561     my $prerequisites = "";
562     my $derived = "";
563     my @file_objects = ();
564     my %templates = ();
565     my %symbol_def_line = ();
567     # merge the source docs, in case there are no templates
568     &MergeSourceDocumentation;
570     while (<INPUT>) {
571         if (m/^#/) {
572             next;
574         } elsif (m/^<SECTION>/) {
575             $synopsis = "";
576             $details = "";
577             $num_symbols = 0;
578             $in_section = 1;
579             @file_objects = ();
580             %symbol_def_line = ();
582         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
583             $synopsis .= "\n";
584             $subsection = $1;
586         } elsif (m/^<SUBSECTION>/) {
588         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
589             $title = $1;
590             #print "Section: $title\n";
592             # We don't want warnings if object & class structs aren't used.
593             $DeclarationOutput{$title} = 1;
594             $DeclarationOutput{"${title}Class"} = 1;
595             $DeclarationOutput{"${title}Iface"} = 1;
596             $DeclarationOutput{"${title}Interface"} = 1;
598         } elsif (m/^<FILE>(.*)<\/FILE>/) {
599             $filename = $1;
600             if (! defined $templates{$filename}) {
601                if (&ReadTemplateFile ("$TMPL_DIR/$filename", 1)) {
602                    &MergeSourceDocumentation;
603                    $templates{$filename}=$.;
604                }
605             } else {
606                 &LogWarning ($file, $., "Double <FILE>$filename</FILE> entry. ".
607                     "Previous occurrence on line ".$templates{$filename}.".");
608             }
609             if (($title eq "") and (defined $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"})) {
610                 $title = $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"};
611                  # Remove trailing blanks
612                 $title =~ s/\s+$//;
613            }
615         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
616             if ($in_section) {
617                 $section_includes = $1;
618             } else {
619                 if (defined $DEFAULT_INCLUDES) {
620                     &LogWarning ($file, $., "Default <INCLUDE> being overridden by command line option.");
621                 }
622                 else {
623                     $includes = $1;
624                 }
625             }
627         } elsif (m/^<\/SECTION>/) {
628             #print "End of section: $title\n";
629             if ($num_symbols > 0) {
630                 # collect documents
631                 if ($OUTPUT_FORMAT eq "xml") {
632                     $book_bottom .= "    <xi:include href=\"xml/$filename.xml\"/>\n";
633                 } else {
634                     $book_top.="<!ENTITY $section_id SYSTEM \"sgml/$filename.sgml\">\n";
635                     $book_bottom .= "    &$section_id;\n";
636                 }
638                 if (defined ($SourceSymbolDocs{"$TMPL_DIR/$filename:Include"})) {
639                     if ($section_includes) {
640                         &LogWarning ($file, $., "Section <INCLUDE> being overridden by inline comments.");
641                     }
642                     $section_includes = $SourceSymbolDocs{"$TMPL_DIR/$filename:Include"};
643                 }
644                 if ($section_includes eq "") {
645                     $section_includes = $includes;
646                 }
648                  $signals_synop =~ s/^\n*//g;
649                  $signals_synop =~ s/\n+$/\n/g;
650                 if ($signals_synop ne '') {
651                     $signals_synop = <<EOF;
652 <refsect1 id="$section_id.signals" role="signal_proto">
653 <title role="signal_proto.title">Signals</title>
654 <synopsis>
655 ${signals_synop}</synopsis>
656 </refsect1>
658                      $signals_desc = TrimTextBlock($signals_desc);
659                     $signals_desc  = <<EOF;
660 <refsect1 id="$section_id.signal-details" role="signals">
661 <title role="signals.title">Signal Details</title>
662 $signals_desc
663 </refsect1>
665                 }
667                  $args_synop =~ s/^\n*//g;
668                  $args_synop =~ s/\n+$/\n/g;
669                 if ($args_synop ne '') {
670                     $args_synop = <<EOF;
671 <refsect1 id="$section_id.properties" role="properties">
672 <title role="properties.title">Properties</title>
673 <synopsis>
674 ${args_synop}</synopsis>
675 </refsect1>
677                      $args_desc = TrimTextBlock($args_desc);
678                     $args_desc  = <<EOF;
679 <refsect1 id="$section_id.property-details" role="property_details">
680 <title role="property_details.title">Property Details</title>
681 $args_desc
682 </refsect1>
684                 }
686                  $child_args_synop =~ s/^\n*//g;
687                  $child_args_synop =~ s/\n+$/\n/g;
688                 if ($child_args_synop ne '') {
689                     $args_synop .= <<EOF;
690 <refsect1 id="$section_id.child-properties" role="child_properties">
691 <title role="child_properties.title">Child Properties</title>
692 <synopsis>
693 ${child_args_synop}</synopsis>
694 </refsect1>
696                      $child_args_desc = TrimTextBlock($child_args_desc);
697                      $args_desc .= <<EOF;
698 <refsect1 id="$section_id.child-property-details" role="child_property_details">
699 <title role="child_property_details.title">Child Property Details</title>
700 $child_args_desc
701 </refsect1>
703                 }
705                  $style_args_synop =~ s/^\n*//g;
706                  $style_args_synop =~ s/\n+$/\n/g;
707                 if ($style_args_synop ne '') {
708                     $args_synop .= <<EOF;
709 <refsect1 id="$section_id.style-properties" role="style_properties">
710 <title role="style_properties.title">Style Properties</title>
711 <synopsis>
712 ${style_args_synop}</synopsis>
713 </refsect1>
715                      $style_args_desc = TrimTextBlock($style_args_desc);
716                     $args_desc .= <<EOF;
717 <refsect1 id="$section_id.style-property-details" role="style_properties_details">
718 <title role="style_properties_details.title">Style Property Details</title>
719 $style_args_desc
720 </refsect1>
722                 }
724                  $hierarchy = TrimTextBlock($hierarchy);
725                 if ($hierarchy ne "") {
726                     $hierarchy = <<EOF;
727 <refsect1 id="$section_id.object-hierarchy" role="object_hierarchy">
728 <title role="object_hierarchy.title">Object Hierarchy</title>
729 $hierarchy
730 </refsect1>
732                 }
734                  $interfaces =~ TrimTextBlock($interfaces);
735                 if ($interfaces ne "") {
736                     $interfaces = <<EOF;
737 <refsect1 id="$section_id.implemented-interfaces" role="impl_interfaces">
738 <title role="impl_interfaces.title">Implemented Interfaces</title>
739 $interfaces
740 </refsect1>
742                 }
744                  $implementations = TrimTextBlock($implementations);
745                 if ($implementations ne "") {
746                     $implementations = <<EOF;
747 <refsect1 id="$section_id.implementations" role="implementations">
748 <title role="implementations.title">Known Implementations</title>
749 $implementations
750 </refsect1>
752                 }
754                  $prerequisites = TrimTextBlock($prerequisites);
755                 if ($prerequisites ne "") {
756                     $prerequisites = <<EOF;
757 <refsect1 id="$section_id.prerequisites" role="prerequisites">
758 <title role="prerequisites.title">Prerequisites</title>
759 $prerequisites
760 </refsect1>
762                 }
764                  $derived = TrimTextBlock($derived);
765                 if ($derived ne "") {
766                     $derived = <<EOF;
767 <refsect1 id="$section_id.derived-interfaces" role="derived_interfaces">
768 <title role="derived_interfaces.title">Known Derived Interfaces</title>
769 $derived
770 </refsect1>
772                 }
774                 $synopsis =~ s/^\n*//g;
775                 $synopsis =~ s/\n+$/\n/g;
776                 my $file_changed = &OutputSGMLFile ($filename, $title, $section_id,
777                                                     $section_includes,
778                                                     \$synopsis, \$details,
779                                                     \$signals_synop, \$signals_desc,
780                                                     \$args_synop, \$args_desc,
781                                                     \$hierarchy, \$interfaces,
782                                                     \$implementations,
783                                                     \$prerequisites, \$derived,
784                                                     \@file_objects);
785                 if ($file_changed) {
786                     $changed = 1;
787                 }
788             }
789             $title = "";
790             $section_id = "";
791             $subsection = "";
792             $in_section = 0;
793             $section_includes = "";
794             $signals_synop = "";
795             $signals_desc = "";
796             $args_synop = "";
797             $child_args_synop = "";
798             $style_args_synop = "";
799             $args_desc = "";
800             $child_args_desc = "";
801             $style_args_desc = "";
802             $hierarchy = "";
803              $interfaces = "";
804              $implementations = "";
805             $prerequisites = "";
806             $derived = "";
808         } elsif (m/^(\S+)/) {
809             my $symbol = $1;
810             #print "  Symbol: $symbol\n";
812             # check for duplicate entries
813             if (! defined $symbol_def_line{$symbol}) {
814                 my $declaration = $Declarations{$symbol};
815                 if (defined ($declaration)) {
816                     # We don't want standard macros/functions of GObjects,
817                     # or private declarations.
818                     if ($subsection ne "Standard" && $subsection ne "Private") {
819                         if (&CheckIsObject ($symbol)) {
820                             push @file_objects, $symbol;
821                         }
822                         my ($synop, $desc) = &OutputDeclaration ($symbol,
823                                                                  $declaration);
824                         my ($sig_synop, $sig_desc) = &GetSignals ($symbol);
825                         my ($arg_synop, $child_arg_synop, $style_arg_synop,
826                             $arg_desc, $child_arg_desc, $style_arg_desc) = &GetArgs ($symbol);
827                         my $hier = &GetHierarchy ($symbol);
828                         my $ifaces = &GetInterfaces ($symbol);
829                         my $impls = &GetImplementations ($symbol);
830                         my $prereqs = &GetPrerequisites ($symbol);
831                         my $der = &GetDerived ($symbol);
832                         $synopsis .= $synop;
833                         $details .= $desc;
834                         $signals_synop .= $sig_synop;
835                         $signals_desc .= $sig_desc;
836                         $args_synop .= $arg_synop;
837                         $child_args_synop .= $child_arg_synop;
838                         $style_args_synop .= $style_arg_synop;
839                         $args_desc .= $arg_desc;
840                         $child_args_desc .= $child_arg_desc;
841                         $style_args_desc .= $style_arg_desc;
842                         $hierarchy .= $hier;
843                         $interfaces .= $ifaces;
844                         $implementations .= $impls;
845                         $prerequisites .= $prereqs;
846                         $derived .= $der;
847                     }
849                     # Note that the declaration has been output.
850                     $DeclarationOutput{$symbol} = 1;
851                 } elsif ($subsection ne "Standard" && $subsection ne "Private") {
852                     $UndeclaredSymbols{$symbol} = 1;
853                     &LogWarning ($file, $., "No declaration found for $symbol.");
854                 }
855                 $num_symbols++;
856                 $symbol_def_line{$symbol}=$.;
858                 if ($section_id eq "") {
859                     if($title eq "" && $filename eq "") {
860                         &LogWarning ($file, $., "Section has no title and no file.");
861                     }
862                     # FIXME: one of those would be enough
863                     # filename should be an internal detail for gtk-doc
864                     if ($title eq "") {
865                         $title = $filename;
866                     } elsif ($filename eq "") {
867                         $filename = $title;
868                     }
869                     $filename =~ s/\s/_/g;
871                     $section_id = $SourceSymbolDocs{"$TMPL_DIR/$filename:Section_Id"};
872                     if (defined ($section_id) && $section_id !~ m/^\s*$/) {
873                         # Remove trailing blanks and use as is
874                         $section_id =~ s/\s+$//;
875                     } elsif (&CheckIsObject ($title)) {
876                         # GObjects use their class name as the ID.
877                         $section_id = &CreateValidSGMLID ($title);
878                     } else {
879                         $section_id = &CreateValidSGMLID ("$MODULE-$title");
880                     }
881                 }
882                 $SymbolSection{$symbol}=$title;
883                 $SymbolSectionId{$symbol}=$section_id;
884             }
885             else {
886                 &LogWarning ($file, $., "Double symbol entry for $symbol. ".
887                     "Previous occurrence on line ".$symbol_def_line{$symbol}.".");
888             }
889         }
890     }
891     close (INPUT);
893     &OutputMissingDocumentation;
894     &OutputUndeclaredSymbols;
895     &OutputUnusedSymbols;
897     if ($OUTPUT_ALL_SYMBOLS) {
898         &OutputAllSymbols;
899     }
900     if ($OUTPUT_SYMBOLS_WITHOUT_SINCE) {
901         &OutputSymbolsWithoutSince;
902     }
904     for $filename (split (' ', $EXPAND_CONTENT_FILES)) {
905         my $file_changed = &OutputExtraFile ($filename);
906         if ($file_changed) {
907             $changed = 1;
908         }
909     }
911     &OutputBook ($book_top, $book_bottom);
913     return $changed;
916 #############################################################################
917 # Function    : OutputIndex
918 # Description : This writes an indexlist that can be included into the main-
919 #               document into an <index> tag.
920 #############################################################################
922 sub OutputIndex {
923     my ($basename, $apiindexref ) = @_;
924     my %apiindex = %{$apiindexref};
925     my $old_index = "$SGML_OUTPUT_DIR/$basename.xml";
926     my $new_index = "$SGML_OUTPUT_DIR/$basename.new";
927     my $lastletter = " ";
928     my $divopen = 0;
929     my $symbol;
930     my $short_symbol;
932     open (OUTPUT, ">$new_index")
933         || die "Can't create $new_index";
935     my $header = $doctype_header;
936     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE indexdiv/;
938     print (OUTPUT "$header<indexdiv>\n");
940     #print "generate $basename index (".%apiindex." entries)\n";
942     # do a case insensitive sort while chopping off the prefix
943     foreach my $hash (
944         sort { $$a{criteria} cmp $$b{criteria} }
945         map { my $x = uc($_); $x =~ s/^$NAME_SPACE\_?(.*)/$1/i; { criteria => $x, original => $_, short => $1 } }
946         keys %apiindex) {
948         $symbol = $$hash{original};
949         if (defined($$hash{short})) {
950             $short_symbol = $$hash{short};
951         } else {
952             $short_symbol = $symbol;
953         }
955         # generate a short symbol description
956         my $symbol_desc = "";
957         my $symbol_section = "";
958         my $symbol_section_id = "";
959         my $symbol_type = "";
960         if (defined($DeclarationTypes{$symbol})) {
961           $symbol_type = lc($DeclarationTypes{$symbol});
962         }
963         if ($symbol_type eq "") {
964             #print "trying symbol $symbol\n";
965             if ($symbol =~ m/(.*)::(.*)/) {
966                 my $oname = $1;
967                 my $osym = $2;
968                 my $i;
969                 #print "  trying object signal ${oname}:$osym in ".$#SignalNames." signals\n";
970                 for ($i = 0; $i <= $#SignalNames; $i++) {
971                     if ($SignalNames[$i] eq $osym) {
972                         $symbol_type = "object signal";
973                         if (defined($SymbolSection{$oname})) {
974                            $symbol_section = $SymbolSection{$oname};
975                            $symbol_section_id = $SymbolSectionId{$oname};
976                         }
977                         last;
978                     }
979                 }
980             } elsif ($symbol =~ m/(.*):(.*)/) {
981                 my $oname = $1;
982                 my $osym = $2;
983                 my $i;
984                 #print "  trying object property ${oname}::$osym in ".$#ArgNames." properties\n";
985                 for ($i = 0; $i <= $#ArgNames; $i++) {
986                     #print "    ".$ArgNames[$i]."\n";
987                     if ($ArgNames[$i] eq $osym) {
988                         $symbol_type = "object property";
989                         if (defined($SymbolSection{$oname})) {
990                            $symbol_section = $SymbolSection{$oname};
991                            $symbol_section_id = $SymbolSectionId{$oname};
992                         }
993                         last;
994                     }
995                 }
996             }
997         } else {
998            if (defined($SymbolSection{$symbol})) {
999                $symbol_section = $SymbolSection{$symbol};
1000                $symbol_section_id = $SymbolSectionId{$symbol};
1001            }
1002         }
1003         if ($symbol_type ne "") {
1004            $symbol_desc=", $symbol_type";
1005            if ($symbol_section ne "") {
1006                $symbol_desc.=" in <link linkend=\"$symbol_section_id\">$symbol_section</link>";
1007                #$symbol_desc.=" in ". &ExpandAbbreviations($symbol, "#$symbol_section");
1008            }
1009         }
1011         my $curletter = uc(substr($short_symbol,0,1));
1012         my $id = $apiindex{$symbol};
1014         #print "  add symbol $symbol with $id to index in section $curletter\n";
1016         if ($curletter ne $lastletter) {
1017             $lastletter = $curletter;
1019             if ($divopen == 1) {
1020                 print (OUTPUT "</indexdiv>\n");
1021             }
1022             print (OUTPUT "<indexdiv><title>$curletter</title>\n");
1023             $divopen = 1;
1024         }
1026         print (OUTPUT <<EOF);
1027 <indexentry><primaryie linkends="$id"><link linkend="$id">$symbol</link>$symbol_desc</primaryie></indexentry>
1029     }
1031     if ($divopen == 1) {
1032         print (OUTPUT "</indexdiv>\n");
1033     }
1034     print (OUTPUT "</indexdiv>\n");
1035     close (OUTPUT);
1037     &UpdateFileIfChanged ($old_index, $new_index, 0);
1041 #############################################################################
1042 # Function    : OutputIndexFull
1043 # Description : This writes the full api indexlist that can be included into the
1044 #               main document into an <index> tag.
1045 #############################################################################
1047 sub OutputIndexFull {
1048     &OutputIndex ("api-index-full", \%IndexEntriesFull);
1052 #############################################################################
1053 # Function    : OutputDeprecatedIndex
1054 # Description : This writes the deprecated api indexlist that can be included
1055 #               into the main document into an <index> tag.
1056 #############################################################################
1058 sub OutputDeprecatedIndex {
1059     &OutputIndex ("api-index-deprecated", \%IndexEntriesDeprecated);
1063 #############################################################################
1064 # Function    : OutputSinceIndexes
1065 # Description : This writes the 'since' api indexlists that can be included into
1066 #               the main document into an <index> tag.
1067 #############################################################################
1069 sub OutputSinceIndexes {
1070     my @sinces = keys %{{ map { $_ => 1 } values %Since }};
1072     foreach my $version (@sinces) {
1073         #print "Since : [$version]\n";
1074         # TODO make filtered hash
1075         #my %index = grep { $Since{$_} eq $version } %IndexEntriesSince;
1076         my %index = map { $_ => $IndexEntriesSince{$_} } grep { $Since{$_} eq $version } keys %IndexEntriesSince;
1078         &OutputIndex ("api-index-$version", \%index);
1079     }
1082 #############################################################################
1083 # Function    : OutputAnnotationGlossary
1084 # Description : This writes a glossary of the used annotation terms into a
1085 #               separate glossary file that can be included into the main
1086 #               document.
1087 #############################################################################
1089 sub OutputAnnotationGlossary {
1090     my $old_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.xml";
1091     my $new_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.new";
1092     my $lastletter = " ";
1093     my $divopen = 0;
1095     # if there are no annotations used return
1096     return if (! keys(%AnnotationsUsed));
1098     # add acronyms that are referenced from acronym text
1099 rerun:
1100     foreach my $annotation (keys(%AnnotationsUsed)) {
1101         if(defined($AnnotationDefinition{$annotation})) {
1102             if($AnnotationDefinition{$annotation} =~ m/<acronym>([\w ]+)<\/acronym>/) {
1103                 if (!exists($AnnotationsUsed{$1})) {
1104                     $AnnotationsUsed{$1} = 1;
1105                     goto rerun;
1106                 }
1107             }
1108         }
1109     }
1111     open (OUTPUT, ">$new_glossary")
1112         || die "Can't create $new_glossary";
1114     my $header = $doctype_header;
1115     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE glossary/;
1117     print (OUTPUT  <<EOF);
1118 $header
1119 <glossary id="annotation-glossary">
1120   <title>Annotation Glossary</title>
1123     foreach my $annotation (sort(keys(%AnnotationsUsed))) {
1124         if(defined($AnnotationDefinition{$annotation})) {
1125             my $def = $AnnotationDefinition{$annotation};
1126             my $curletter = uc(substr($annotation,0,1));
1128             if ($curletter ne $lastletter) {
1129                 $lastletter = $curletter;
1131                 if ($divopen == 1) {
1132                     print (OUTPUT "</glossdiv>\n");
1133                 }
1134                 print (OUTPUT "<glossdiv><title>$curletter</title>\n");
1135                 $divopen = 1;
1136             }
1137             print (OUTPUT <<EOF);
1138     <glossentry>
1139       <glossterm><anchor id="annotation-glossterm-$annotation"/>$annotation</glossterm>
1140       <glossdef>
1141         <para>$def</para>
1142       </glossdef>
1143     </glossentry>
1145         }
1146     }
1148     if ($divopen == 1) {
1149         print (OUTPUT "</glossdiv>\n");
1150     }
1151     print (OUTPUT "</glossary>\n");
1152     close (OUTPUT);
1154     &UpdateFileIfChanged ($old_glossary, $new_glossary, 0);
1157 #############################################################################
1158 # Function    : ReadKnownSymbols
1159 # Description : This collects the names of non-private symbols from the
1160 #               $MODULE-sections.txt file.
1161 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
1162 #                the functions/macros/structs etc. being documented, organised
1163 #                into sections and subsections.
1164 #############################################################################
1166 sub ReadKnownSymbols {
1167     my ($file) = @_;
1169     my $subsection = "";
1171     #print "Reading: $file\n";
1172     open (INPUT, $file)
1173         || die "Can't open $file: $!";
1175     while (<INPUT>) {
1176         if (m/^#/) {
1177             next;
1179         } elsif (m/^<SECTION>/) {
1180             $subsection = "";
1182         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
1183             $subsection = $1;
1185         } elsif (m/^<SUBSECTION>/) {
1186             next;
1188         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
1189             next;
1191         } elsif (m/^<FILE>(.*)<\/FILE>/) {
1192             $KnownSymbols{"$TMPL_DIR/$1:Long_Description"} = 1;
1193             $KnownSymbols{"$TMPL_DIR/$1:Short_Description"} = 1;
1194             next;
1196         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
1197             next;
1199         } elsif (m/^<\/SECTION>/) {
1200             next;
1202         } elsif (m/^(\S+)/) {
1203             my $symbol = $1;
1205             if ($subsection ne "Standard" && $subsection ne "Private") {
1206                 $KnownSymbols{$symbol} = 1;
1207             }
1208             else {
1209                 $KnownSymbols{$symbol} = 0;
1210             }
1211         }
1212     }
1213     close (INPUT);
1217 #############################################################################
1218 # Function    : OutputDeclaration
1219 # Description : Returns the synopsis and detailed description DocBook
1220 #                describing one function/macro etc.
1221 # Arguments   : $symbol - the name of the function/macro begin described.
1222 #                $declaration - the declaration of the function/macro.
1223 #############################################################################
1225 sub OutputDeclaration {
1226     my ($symbol, $declaration) = @_;
1228     my $type = $DeclarationTypes {$symbol};
1229     if ($type eq 'MACRO') {
1230         return &OutputMacro ($symbol, $declaration);
1231     } elsif ($type eq 'TYPEDEF') {
1232         return &OutputTypedef ($symbol, $declaration);
1233     } elsif ($type eq 'STRUCT') {
1234         return &OutputStruct ($symbol, $declaration);
1235     } elsif ($type eq 'ENUM') {
1236         return &OutputEnum ($symbol, $declaration);
1237     } elsif ($type eq 'UNION') {
1238         return &OutputUnion ($symbol, $declaration);
1239     } elsif ($type eq 'VARIABLE') {
1240         return &OutputVariable ($symbol, $declaration);
1241     } elsif ($type eq 'FUNCTION') {
1242         return &OutputFunction ($symbol, $declaration, $type);
1243     } elsif ($type eq 'USER_FUNCTION') {
1244         return &OutputFunction ($symbol, $declaration, $type);
1245     } else {
1246         die "Unknown symbol type";
1247     }
1251 #############################################################################
1252 # Function    : OutputSymbolTraits
1253 # Description : Returns the Since and StabilityLevel paragraphs for a symbol.
1254 # Arguments   : $symbol - the name of the function/macro begin described.
1255 #############################################################################
1257 sub OutputSymbolTraits {
1258     my ($symbol) = @_;
1259     my $desc = "";
1261     if (exists $Since{$symbol}) {
1262         $desc .= "<para role=\"since\">Since $Since{$symbol}</para>";
1263     }
1264     if (exists $StabilityLevel{$symbol}) {
1265         $desc .= "<para role=\"stability\">Stability Level: $StabilityLevel{$symbol}</para>";
1266     }
1267     return $desc;
1270 #############################################################################
1271 # Function    : Outpu{Symbol,Section}ExtraLinks
1272 # Description : Returns extralinks for the symbol (if enabled).
1273 # Arguments   : $symbol - the name of the function/macro begin described.
1274 #############################################################################
1276 sub uri_escape {
1277     my $text = $_[0];
1278     return undef unless defined $text;
1280     # Build a char to hex map
1281     my %escapes = ();
1282     for (0..255) {
1283             $escapes{chr($_)} = sprintf("%%%02X", $_);
1284     }
1286     # Default unsafe characters.  RFC 2732 ^(uric - reserved)
1287     $text =~ s/([^A-Za-z0-9\-_.!~*'()])/$escapes{$1}/g;
1289     return $text;
1292 sub OutputSymbolExtraLinks {
1293     my ($symbol) = @_;
1294     my $desc = "";
1296     if (0) { # NEW FEATURE: needs configurability
1297     my $sstr = &uri_escape($symbol);
1298     my $mstr = &uri_escape($MODULE);
1299     $desc .= <<EOF;
1300 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1301 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$sstr">edit documentation</ulink>
1303     }
1304     return $desc;
1307 sub OutputSectionExtraLinks {
1308     my ($symbol,$docsymbol) = @_;
1309     my $desc = "";
1311     if (0) { # NEW FEATURE: needs configurability
1312     my $sstr = &uri_escape($symbol);
1313     my $mstr = &uri_escape($MODULE);
1314     my $dsstr = &uri_escape($docsymbol);
1315     $desc .= <<EOF;
1316 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1317 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$dsstr">edit documentation</ulink>
1319     }
1320     return $desc;
1324 #############################################################################
1325 # Function    : OutputMacro
1326 # Description : Returns the synopsis and detailed description of a macro.
1327 # Arguments   : $symbol - the macro.
1328 #                $declaration - the declaration of the macro.
1329 #############################################################################
1331 sub OutputMacro {
1332     my ($symbol, $declaration) = @_;
1333     my $id = &CreateValidSGMLID ($symbol);
1334     my $condition = &MakeConditionDescription ($symbol);
1335     my $synop = &MakeReturnField("#define") . "<link linkend=\"$id\">$symbol</link>";
1336     my $desc;
1338     my @fields = ParseMacroDeclaration($declaration, \&CreateValidSGML);
1339     my $title = $symbol . (@fields ? "()" : "");
1341     $desc = "<refsect2 id=\"$id\" role=\"macro\"$condition>\n<title>$title</title>\n";
1342     $desc .= MakeIndexterms($symbol, $id);
1343     $desc .= "\n";
1344     $desc .= OutputSymbolExtraLinks($symbol);
1346     if (@fields) {
1347         if (length ($symbol) < $SYMBOL_FIELD_WIDTH) {
1348             $synop .= (' ' x ($SYMBOL_FIELD_WIDTH - length ($symbol)));
1349         }
1351         $synop .= "(";
1352         for (my $i = 1; $i <= $#fields; $i += 2) {
1353             my $field_name = $fields[$i];
1355             if ($i == 1) {
1356                 $synop .= "$field_name";
1357             } else {
1358                 $synop .= ",\n"
1359                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1360                     . " $field_name";
1361             }
1362         }
1363         $synop .= ")";
1364     }
1365     $synop .= "\n";
1367     # Don't output the macro definition if is is a conditional macro or it
1368     # looks like a function, i.e. starts with "g_" or "_?gnome_", or it is
1369     # longer than 2 lines, otherwise we get lots of complicated macros like
1370     # g_assert.
1371     if (!defined ($DeclarationConditional{$symbol}) && ($symbol !~ m/^g_/)
1372         && ($symbol !~ m/^_?gnome_/) && (($declaration =~ tr/\n//) < 2)) {
1373         my $decl_out = &CreateValidSGML ($declaration);
1374         $desc .= "<programlisting>$decl_out</programlisting>\n";
1375     } else {
1376         $desc .= "<programlisting>" . &MakeReturnField("#define") . "$symbol";
1377         if ($declaration =~ m/^\s*#\s*define\s+\w+(\([^\)]*\))/) {
1378             my $args = $1;
1379             my $pad = ' ' x ($RETURN_TYPE_FIELD_WIDTH - length ("#define "));
1380             # Align each line so that if should all line up OK.
1381             $args =~ s/\n/\n$pad/gm;
1382             $desc .= &CreateValidSGML ($args);
1383         }
1384         $desc .= "</programlisting>\n";
1385     }
1387     $desc .= &MakeDeprecationNote($symbol);
1389     my $parameters = &OutputParamDescriptions ("MACRO", $symbol, @fields);
1390     my $parameters_output = 0;
1392     if (defined ($SymbolDocs{$symbol})) {
1393         my $symbol_docs = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1395         # Try to insert the parameter table at the author's desired position.
1396         # Otherwise we need to tag it onto the end.
1397         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
1398           $parameters_output = 1;
1399         }
1400         $desc .= $symbol_docs;
1401     }
1403     if ($parameters_output == 0) {
1404         $desc .= $parameters;
1405     }
1407     $desc .= OutputSymbolTraits ($symbol);
1408     $desc .= "</refsect2>\n";
1409     return ($synop, $desc);
1413 #############################################################################
1414 # Function    : OutputTypedef
1415 # Description : Returns the synopsis and detailed description of a typedef.
1416 # Arguments   : $symbol - the typedef.
1417 #                $declaration - the declaration of the typedef,
1418 #                  e.g. 'typedef unsigned int guint;'
1419 #############################################################################
1421 sub OutputTypedef {
1422     my ($symbol, $declaration) = @_;
1423     my $id = &CreateValidSGMLID ($symbol);
1424     my $condition = &MakeConditionDescription ($symbol);
1425     my $synop = &MakeReturnField("typedef") . "<link linkend=\"$id\">$symbol</link>;\n";
1426     my $desc = "<refsect2 id=\"$id\" role=\"typedef\"$condition>\n<title>$symbol</title>\n";
1428     $desc .= MakeIndexterms($symbol, $id);
1429     $desc .= "\n";
1430     $desc .= OutputSymbolExtraLinks($symbol);
1432     if (!defined ($DeclarationConditional{$symbol})) {
1433         my $decl_out = &CreateValidSGML ($declaration);
1434         $desc .= "<programlisting>$decl_out</programlisting>\n";
1435     }
1437     $desc .= &MakeDeprecationNote($symbol);
1439     if (defined ($SymbolDocs{$symbol})) {
1440         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1441     }
1442     $desc .= OutputSymbolTraits ($symbol);
1443     $desc .= "</refsect2>\n";
1444     return ($synop, $desc);
1448 #############################################################################
1449 # Function    : OutputStruct
1450 # Description : Returns the synopsis and detailed description of a struct.
1451 #                We check if it is a object struct, and if so we only output
1452 #                parts of it that are noted as public fields.
1453 #                We also use a different SGML ID for object structs, since the
1454 #                original ID is used for the entire RefEntry.
1455 # Arguments   : $symbol - the struct.
1456 #                $declaration - the declaration of the struct.
1457 #############################################################################
1459 sub OutputStruct {
1460     my ($symbol, $declaration) = @_;
1462     my $is_gtype = 0;
1463     my $default_to_public = 1;
1464     if (&CheckIsObject ($symbol)) {
1465         #print "Found struct gtype: $symbol\n";
1466         $is_gtype = 1;
1467         $default_to_public = $ObjectRoots{$symbol} eq 'GBoxed';
1468     }
1470     my $id;
1471     my $condition;
1472     if ($is_gtype) {
1473         $id = &CreateValidSGMLID ($symbol . "_struct");
1474         $condition = &MakeConditionDescription ($symbol . "_struct");
1475     } else {
1476         $id = &CreateValidSGMLID ($symbol);
1477         $condition = &MakeConditionDescription ($symbol);
1478     }
1480     # Determine if it is a simple struct or it also has a typedef.
1481     my $has_typedef = 0;
1482     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1483       $has_typedef = 1;
1484     }
1486     my $synop;
1487     my $desc;
1488     if ($has_typedef) {
1489         # For structs with typedefs we just output the struct name.
1490         $synop = &MakeReturnField("") . "<link linkend=\"$id\">$symbol</link>;\n";
1491         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>$symbol</title>\n";
1492     } else {
1493         $synop = &MakeReturnField("struct") . "<link linkend=\"$id\">$symbol</link>;\n";
1494         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>struct $symbol</title>\n";
1495     }
1497     $desc .= MakeIndexterms($symbol, $id);
1498     $desc .= "\n";
1499     $desc .= OutputSymbolExtraLinks($symbol);
1501     # Form a pretty-printed, private-data-removed form of the declaration
1503     my $decl_out = "";
1504     if ($declaration =~ m/^\s*$/) {
1505         #print "Found opaque struct: $symbol\n";
1506         $decl_out = "typedef struct _$symbol $symbol;";
1507     } elsif ($declaration =~ m/^\s*struct\s+\w+\s*;\s*$/) {
1508         #print "Found opaque struct: $symbol\n";
1509         $decl_out = "struct $symbol;";
1510     } else {
1511         my $public = $default_to_public;
1512         my $new_declaration = "";
1513         my $decl_line;
1514         my $decl = $declaration;
1516         if ($decl =~ m/^\s*(typedef\s+)?struct\s*\w*\s*(?:\/\*.*\*\/)?\s*{(.*)}\s*\w*\s*;\s*$/s) {
1517             my $struct_contents = $2;
1519             foreach $decl_line (split (/\n/, $struct_contents)) {
1520                 #print "Struct line: $decl_line\n";
1521                 if ($decl_line =~ m%/\*\s*<\s*public\s*>\s*\*/%) {
1522                     $public = 1;
1523                 } elsif ($decl_line =~ m%/\*\s*<\s*(private|protected)\s*>\s*\*/%) {
1524                     $public = 0;
1525                 } elsif ($public) {
1526                     $new_declaration .= $decl_line . "\n";
1527                 }
1528             }
1530             if ($new_declaration) {
1531                 # Strip any blank lines off the ends.
1532                 $new_declaration =~ s/^\s*\n//;
1533                 $new_declaration =~ s/\n\s*$/\n/;
1535                 if ($has_typedef) {
1536                     $decl_out = "typedef struct {\n" . $new_declaration
1537                       . "} $symbol;\n";
1538                 } else {
1539                     $decl_out = "struct $symbol {\n" . $new_declaration
1540                       . "};\n";
1541                 }
1542             }
1543         } else {
1544             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1545                 "Couldn't parse struct:\n$declaration");
1546         }
1548         # If we couldn't parse the struct or it was all private, output an
1549         # empty struct declaration.
1550         if ($decl_out eq "") {
1551             if ($has_typedef) {
1552                 $decl_out = "typedef struct _$symbol $symbol;";
1553             } else {
1554                 $decl_out = "struct $symbol;";
1555             }
1556         }
1557     }
1559     $decl_out = &CreateValidSGML ($decl_out);
1560     $desc .= "<programlisting>$decl_out</programlisting>\n";
1562     $desc .= &MakeDeprecationNote($symbol);
1564     if (defined ($SymbolDocs{$symbol})) {
1565         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1566     }
1568     # Create a table of fields and descriptions
1570     # FIXME: Inserting &#160's into the produced type declarations here would
1571     #        improve the output in most situations ... except for function
1572     #        members of structs!
1573     my @fields = ParseStructDeclaration($declaration, !$default_to_public,
1574                                         0, \&MakeXRef,
1575                                         sub {
1576                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1577                                         });
1578     my $params = $SymbolParams{$symbol};
1580     # If no parameters are filled in, we don't generate the description
1581     # table, for backwards compatibility.
1583     my $found = 0;
1584     if (defined $params) {
1585         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1586             if ($params->[$i] =~ /\S/) {
1587                 $found = 1;
1588                 last;
1589             }
1590         }
1591     }
1593     if ($found) {
1594         my %field_descrs = @$params;
1595         my $missing_parameters = "";
1596         my $unused_parameters = "";
1598         $desc .= "<variablelist role=\"struct\">\n";
1599         while (@fields) {
1600             my $field_name = shift @fields;
1601             my $text = shift @fields;
1602             my $field_descr = $field_descrs{$field_name};
1603             my $param_annotations = "";
1605             $desc .= "<varlistentry><term>$text</term>\n";
1606             if (defined $field_descr) {
1607                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1608                 $field_descr = &ExpandAbbreviations($symbol, $field_descr);
1609                 $field_descr .= $param_annotations;
1610                 # trim
1611                 $field_descr =~ s/^(\s|\n)+//msg;
1612                 $field_descr =~ s/(\s|\n)+$//msg;
1613                 $desc .= "<listitem><simpara>$field_descr</simpara></listitem>\n";
1614                 delete $field_descrs{$field_name};
1615             } else {
1616                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1617                     "Field description for $symbol"."::"."$field_name is missing in source code comment block.");
1618                 if ($missing_parameters ne "") {
1619                   $missing_parameters .= ", ".$field_name;
1620                 } else {
1621                     $missing_parameters = $field_name;
1622                 }
1623                 $desc .= "<listitem />\n";
1624             }
1625             $desc .= "</varlistentry>\n";
1626         }
1627         $desc .= "</variablelist>";
1628         foreach my $field_name (keys %field_descrs) {
1629             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1630                 "Field description for $symbol"."::"."$field_name is not used from source code comment block.");
1631             if ($unused_parameters ne "") {
1632               $unused_parameters .= ", ".$field_name;
1633             } else {
1634                $unused_parameters = $field_name;
1635             }
1636         }
1638         # remember missing/unused parameters (needed in tmpl-free build)
1639         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1640             $AllIncompleteSymbols{$symbol}=$missing_parameters;
1641         }
1642         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1643             $AllUnusedSymbols{$symbol}=$unused_parameters;
1644         }
1645     }
1646     else {
1647         if (scalar(@fields) > 0) {
1648             if (! exists ($AllIncompleteSymbols{$symbol})) {
1649                 $AllIncompleteSymbols{$symbol}="<items>";
1650                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1651                     "Field descriptions for struct $symbol are missing in source code comment block.");
1652                 @TRACE@("Remaining structs fields: ".@fields.":".join(',',@fields)."\n");
1653             }
1654         }
1655     }
1657     $desc .= OutputSymbolTraits ($symbol);
1658     $desc .= "</refsect2>\n";
1659     return ($synop, $desc);
1663 #############################################################################
1664 # Function    : OutputUnion
1665 # Description : Returns the synopsis and detailed description of a union.
1666 # Arguments   : $symbol - the union.
1667 #                $declaration - the declaration of the union.
1668 #############################################################################
1670 sub OutputUnion {
1671     my ($symbol, $declaration) = @_;
1672     my $id = &CreateValidSGMLID ($symbol);
1673     my $condition = &MakeConditionDescription ($symbol);
1675     # Determine if it is a simple struct or it also has a typedef.
1676     my $has_typedef = 0;
1677     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1678       $has_typedef = 1;
1679     }
1681     my $synop;
1682     my $desc;
1683     if ($has_typedef) {
1684         # For unions with typedefs we just output the union name.
1685         $synop = &MakeReturnField("") . "<link linkend=\"$id\">$symbol</link>;\n";
1686         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>$symbol</title>\n";
1687     } else {
1688         $synop = &MakeReturnField("union") . "<link linkend=\"$id\">$symbol</link>;\n";
1689         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>union $symbol</title>\n";
1690     }
1692     $desc .= MakeIndexterms($symbol, $id);
1693     $desc .= "\n";
1694     $desc .= OutputSymbolExtraLinks($symbol);
1696     # FIXME: we do more for structs
1697     my $decl_out = &CreateValidSGML ($declaration);
1698     $desc .= "<programlisting>$decl_out</programlisting>\n";
1700     $desc .= &MakeDeprecationNote($symbol);
1702     if (defined ($SymbolDocs{$symbol})) {
1703         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1704     }
1706     # Create a table of fields and descriptions
1708     # FIXME: Inserting &#160's into the produced type declarations here would
1709     #        improve the output in most situations ... except for function
1710     #        members of structs!
1711     my @fields = ParseStructDeclaration($declaration, 0,
1712                                         0, \&MakeXRef,
1713                                         sub {
1714                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1715                                         });
1716     my $params = $SymbolParams{$symbol};
1718     # If no parameters are filled in, we don't generate the description
1719     # table, for backwards compatibility
1721     my $found = 0;
1722     if (defined $params) {
1723         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1724             if ($params->[$i] =~ /\S/) {
1725                 $found = 1;
1726                 last;
1727             }
1728         }
1729     }
1731     if ($found) {
1732         my %field_descrs = @$params;
1733         my $missing_parameters = "";
1734         my $unused_parameters = "";
1736         $desc .= "<variablelist role=\"union\">\n";
1737         while (@fields) {
1738             my $field_name = shift @fields;
1739             my $text = shift @fields;
1740             my $field_descr = $field_descrs{$field_name};
1741             my $param_annotations = "";
1743             $desc .= "<varlistentry><term>$text</term>\n";
1744             if (defined $field_descr) {
1745                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1746                 $field_descr = &ExpandAbbreviations($symbol, $field_descr);
1747                 $field_descr .= $param_annotations;
1748                 # trim
1749                 $field_descr =~ s/^(\s|\n)+//msg;
1750                 $field_descr =~ s/(\s|\n)+$//msg;
1751                 $desc .= "<listitem><simpara>$field_descr</simpara></listitem>\n";
1752                 delete $field_descrs{$field_name};
1753             } else {
1754                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1755                     "Field description for $symbol"."::"."$field_name is missing in source code comment block.");
1756                 if ($missing_parameters ne "") {
1757                     $missing_parameters .= ", ".$field_name;
1758                 } else {
1759                     $missing_parameters = $field_name;
1760                 }
1761                 $desc .= "<listitem />\n";
1762             }
1763             $desc .= "</varlistentry>\n";
1764         }
1765         $desc .= "</variablelist>";
1766         foreach my $field_name (keys %field_descrs) {
1767             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1768                 "Field description for $symbol"."::"."$field_name is not used from source code comment block.");
1769             if ($unused_parameters ne "") {
1770               $unused_parameters .= ", ".$field_name;
1771             } else {
1772                $unused_parameters = $field_name;
1773             }
1774         }
1776         # remember missing/unused parameters (needed in tmpl-free build)
1777         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1778             $AllIncompleteSymbols{$symbol}=$missing_parameters;
1779         }
1780         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1781             $AllUnusedSymbols{$symbol}=$unused_parameters;
1782         }
1783     }
1784     else {
1785         if (scalar(@fields) > 0) {
1786             if (! exists ($AllIncompleteSymbols{$symbol})) {
1787                 $AllIncompleteSymbols{$symbol}="<items>";
1788                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1789                     "Field descriptions for union $symbol are missing in source code comment block.");
1790                 @TRACE@("Remaining union fields: ".@fields.":".join(',',@fields)."\n");
1791             }
1792         }
1793     }
1795     $desc .= OutputSymbolTraits ($symbol);
1796     $desc .= "</refsect2>\n";
1797     return ($synop, $desc);
1801 #############################################################################
1802 # Function    : OutputEnum
1803 # Description : Returns the synopsis and detailed description of a enum.
1804 # Arguments   : $symbol - the enum.
1805 #                $declaration - the declaration of the enum.
1806 #############################################################################
1808 sub OutputEnum {
1809     my ($symbol, $declaration) = @_;
1811     my $is_gtype = 0;
1812     if (&CheckIsObject ($symbol)) {
1813         #print "Found enum gtype: $symbol\n";
1814         $is_gtype = 1;
1815     }
1817     my $id;
1818     my $condition;
1819     if ($is_gtype) {
1820         $id = &CreateValidSGMLID ($symbol . "_enum");
1821         $condition = &MakeConditionDescription ($symbol . "_enum");
1822     } else {
1823         $id = &CreateValidSGMLID ($symbol);
1824         $condition = &MakeConditionDescription ($symbol);
1825     }
1827     my $synop = &MakeReturnField("enum") . "<link linkend=\"$id\">$symbol</link>;\n";
1828     my $desc = "<refsect2 id=\"$id\" role=\"enum\"$condition>\n<title>enum $symbol</title>\n";
1830     $desc .= MakeIndexterms($symbol, $id);
1831     $desc .= "\n";
1832     $desc .= OutputSymbolExtraLinks($symbol);
1834     my $decl_out = "";
1835     my $public = 1;
1836     my $new_declaration = "";
1837     my $decl_line;
1838     my $decl = $declaration;
1840     if ($decl =~ m/^\s*(typedef\s+)?enum\s*\w*\s*(?:\/\*.*\*\/)?\s*{(.*)}\s*\w*\s*;\s*$/s) {
1841         my $has_typedef = defined($1) ? 1 : 0;
1842         my $enum_contents = $2;
1844         foreach $decl_line (split (/\n/, $enum_contents)) {
1845             #print "Enum line: $decl_line\n";
1846             if ($decl_line =~ m%/\*\s*<\s*public\s*>\s*\*/%) {
1847                 $public = 1;
1848             } elsif ($decl_line =~ m%/\*\s*<\s*(private|protected)\s*>\s*\*/%) {
1849                 $public = 0;
1850             } elsif ($public) {
1851                 $new_declaration .= $decl_line . "\n";
1852             }
1853         }
1855         if ($new_declaration) {
1856             # Strip any blank lines off the ends.
1857             $new_declaration =~ s/^\s*\n//;
1858             $new_declaration =~ s/\n\s*$/\n/;
1860             if ($has_typedef) {
1861                 $decl_out = "typedef enum {\n" . $new_declaration
1862                   . "} $symbol;\n";
1863             } else {
1864                 $decl_out = "enum $symbol {\n" . $new_declaration
1865                   . "};\n";
1866             }
1867         }
1868     }
1870     $decl_out = &CreateValidSGML ($decl_out);
1871     $desc .= "<programlisting>$decl_out</programlisting>\n";
1873     $desc .= &MakeDeprecationNote($symbol);
1875     if (defined ($SymbolDocs{$symbol})) {
1876         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1877     }
1879     # Create a table of fields and descriptions
1881     my @fields = ParseEnumDeclaration($declaration);
1882     my $params = $SymbolParams{$symbol};
1884     # If nothing at all is documented log a single summary warning at the end.
1885     # Otherwise, warn about each undocumented item.
1887     my $found = 0;
1888     if (defined $params) {
1889         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1890             if ($params->[$i] =~ /\S/) {
1891                 $found = 1;
1892                 last;
1893             }
1894         }
1895     }
1897     my %field_descrs = (defined $params ? @$params : ());
1898     my $missing_parameters = "";
1899     my $unused_parameters = "";
1901     $desc .= "<variablelist role=\"enum\">\n";
1902     for my $field_name (@fields) {
1903         my $field_descr = $field_descrs{$field_name};
1904         my $param_annotations = "";
1906         $id = &CreateValidSGMLID ($field_name);
1907         $condition = &MakeConditionDescription ($field_name);
1908         $desc .= "<varlistentry id=\"$id\" role=\"constant\"$condition>\n<term><literal>$field_name</literal></term>\n";
1909         if (defined $field_descr) {
1910             ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1911             $field_descr = &ExpandAbbreviations($symbol, $field_descr);
1912             $desc .= "<listitem><simpara>$field_descr$param_annotations</simpara></listitem>\n";
1913             delete $field_descrs{$field_name};
1914         } else {
1915             if ($found) {
1916                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1917                     "Value description for $symbol"."::"."$field_name is missing in source code comment block.");
1918                 if ($missing_parameters ne "") {
1919                     $missing_parameters .= ", ".$field_name;
1920                 } else {
1921                     $missing_parameters = $field_name;
1922                 }
1923             }
1924             $desc .= "<listitem />\n";
1925         }
1926         $desc .= "</varlistentry>\n";
1927     }
1928     $desc .= "</variablelist>";
1929     foreach my $field_name (keys %field_descrs) {
1930         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1931             "Value description for $symbol"."::"."$field_name is not used from source code comment block.");
1932         if ($unused_parameters ne "") {
1933             $unused_parameters .= ", ".$field_name;
1934         } else {
1935             $unused_parameters = $field_name;
1936         }
1937     }
1939     # remember missing/unused parameters (needed in tmpl-free build)
1940     if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1941         $AllIncompleteSymbols{$symbol}=$missing_parameters;
1942     }
1943     if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1944         $AllUnusedSymbols{$symbol}=$unused_parameters;
1945     }
1947     if (!$found) {
1948         if (scalar(@fields) > 0) {
1949             if (! exists ($AllIncompleteSymbols{$symbol})) {
1950                 $AllIncompleteSymbols{$symbol}="<items>";
1951                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1952                     "Value descriptions for $symbol are missing in source code comment block.");
1953             }
1954         }
1955     }
1957     $desc .= OutputSymbolTraits ($symbol);
1958     $desc .= "</refsect2>\n";
1959     return ($synop, $desc);
1963 #############################################################################
1964 # Function    : OutputVariable
1965 # Description : Returns the synopsis and detailed description of a variable.
1966 # Arguments   : $symbol - the extern'ed variable.
1967 #                $declaration - the declaration of the variable.
1968 #############################################################################
1970 sub OutputVariable {
1971     my ($symbol, $declaration) = @_;
1972     my $id = &CreateValidSGMLID ($symbol);
1973     my $condition = &MakeConditionDescription ($symbol);
1974     
1975     @TRACE@("ouputing variable: '$symbol' '$declaration'");
1977     my $synop;
1978     if ($declaration =~ m/^\s*extern\s+((const\s+|signed\s+|unsigned\s+|long\s+|short\s+)*\w+)(\s+\*+|\*+|\s)(\s*)(const\s+)*([A-Za-z]\w*)\s*;/) {
1979         my $mod1 = defined ($1) ? $1 : "";
1980         my $ptr = defined ($3) ? $3 : "";
1981         my $space = defined ($4) ? $4 : "";
1982         my $mod2 = defined ($5) ? $5 : "";
1983         $synop = &MakeReturnField("extern $mod1$ptr$space$mod2") . "<link linkend=\"$id\">$symbol</link>;\n";
1984     } elsif ($declaration =~ m/^\s*((const\s+|signed\s+|unsigned\s+|long\s+|short\s+)*\w+)(\s+\*+|\*+|\s)(\s*)(const\s+)*([A-Za-z]\w*)\s*=/) {
1985         my $mod1 = defined ($1) ? $1 : "";
1986         my $ptr = defined ($3) ? $3 : "";
1987         my $space = defined ($4) ? $4 : "";
1988         my $mod2 = defined ($5) ? $5 : "";
1989         $synop = &MakeReturnField("$mod1$ptr$space$mod2") . "<link linkend=\"$id\">$symbol</link>;\n";
1991     } else {
1992         $synop = &MakeReturnField("extern") . "<link linkend=\"$id\">$symbol</link>;\n";
1993     }
1995     my $desc = "<refsect2 id=\"$id\" role=\"variable\"$condition>\n<title>$symbol</title>\n";
1997     $desc .= MakeIndexterms($symbol, $id);
1998     $desc .= "\n";
1999     $desc .= OutputSymbolExtraLinks($symbol);
2001     my $decl_out = &CreateValidSGML ($declaration);
2002     $desc .= "<programlisting>$decl_out</programlisting>\n";
2004     $desc .= &MakeDeprecationNote($symbol);
2006     if (defined ($SymbolDocs{$symbol})) {
2007         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
2008     }
2009     $desc .= OutputSymbolTraits ($symbol);
2010     $desc .= "</refsect2>\n";
2011     return ($synop, $desc);
2015 #############################################################################
2016 # Function    : OutputFunction
2017 # Description : Returns the synopsis and detailed description of a function.
2018 # Arguments   : $symbol - the function.
2019 #                $declaration - the declaration of the function.
2020 #############################################################################
2022 sub OutputFunction {
2023     my ($symbol, $declaration, $symbol_type) = @_;
2024     my $id = &CreateValidSGMLID ($symbol);
2025     my $condition = &MakeConditionDescription ($symbol);
2027     # Take out the return type     $1                                                                                       $2   $3
2028     $declaration =~ s/<RETURNS>\s*((?:const\s+|G_CONST_RETURN\s+|signed\s+|unsigned\s+|long\s+|short\s+|struct\s+|enum\s+)*)(\w+)(\s*\**\s*(?:const|G_CONST_RETURN)?\s*\**\s*(?:restrict)?\s*)<\/RETURNS>\n//;
2029     my $type_modifier = defined($1) ? $1 : "";
2030     my $type = $2;
2031     my $pointer = $3;
2032     # Trim trailing spaces as we are going to pad to $RETURN_TYPE_FIELD_WIDTH below anyway
2033     $pointer =~ s/\s+$//;
2034     my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
2035     my $start = "";
2036     #if ($symbol_type eq 'USER_FUNCTION') {
2037     #    $start = "typedef ";
2038     #}
2040     # We output const rather than G_CONST_RETURN.
2041     $type_modifier =~ s/G_CONST_RETURN/const/g;
2042     $pointer =~ s/G_CONST_RETURN/const/g;
2043     $pointer =~ s/^\s+/ /g;
2045     my $ret_type_len = length ($start) + length ($type_modifier)+ length ($type)
2046         + length ($pointer);
2047     my $ret_type_output;
2048     my $symbol_len;
2049     if ($ret_type_len < $RETURN_TYPE_FIELD_WIDTH) {
2050         $ret_type_output = "$start$type_modifier$xref$pointer"
2051             . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
2052         $symbol_len = 0;
2053     } else {
2054         #$ret_type_output = "$start$type_modifier$xref$pointer\n" . (' ' x $RETURN_TYPE_FIELD_WIDTH);
2056         $ret_type_output = "$start$type_modifier$xref$pointer ";
2057         $symbol_len = $ret_type_len + 1 - $RETURN_TYPE_FIELD_WIDTH;
2058     }
2059     #@TRACE@("$symbol ret type output: [$ret_type_output], $ret_type_len");
2061     $symbol_len += length ($symbol);
2062     my $char1 = my $char2 = my $char3 = "";
2063     if ($symbol_type eq 'USER_FUNCTION') {
2064         $symbol_len += 3;
2065         $char1 = "(";
2066         $char2 = "*";
2067         $char3 = ")";
2068     }
2070     my ($symbol_output, $symbol_desc_output);
2071     if ($symbol_len < $SYMBOL_FIELD_WIDTH) {
2072         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3"
2073             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
2074         $symbol_desc_output = "$char1$char2$symbol$char3"
2075             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
2076     } else {
2077         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3\n"
2078             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
2079         $symbol_desc_output = "$char1$char2$symbol$char3\n"
2080             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
2081     }
2083     my $synop = $ret_type_output . $symbol_output . '(';
2084     my $desc = "<refsect2 id=\"$id\" role=\"function\"$condition>\n<title>${symbol} ()</title>\n";
2086     $desc .= MakeIndexterms($symbol, $id);
2087     $desc .= "\n";
2088     $desc .= OutputSymbolExtraLinks($symbol);
2090     $desc  .= "<programlisting>${ret_type_output}$symbol_desc_output(";
2092     my @fields = ParseFunctionDeclaration($declaration, \&MakeXRef,
2093                                         sub {
2094                                             &tagify($_[0],"parameter");
2095                                         });
2097     for (my $i = 1; $i <= $#fields; $i += 2) {
2098         my $field_name = $fields[$i];
2100         if ($i == 1) {
2101             $synop .= "$field_name";
2102             $desc  .= "$field_name";
2103         } else {
2104             $synop .= ",\n"
2105                 . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
2106                 . " $field_name";
2107             $desc  .= ",\n"
2108                 . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
2109                 . " $field_name";
2110         }
2112     }
2114     $synop .= ");\n";
2115     $desc  .= ");</programlisting>\n";
2117     $desc .= &MakeDeprecationNote($symbol);
2119     my $parameters = &OutputParamDescriptions ("FUNCTION", $symbol, @fields);
2120     my $parameters_output = 0;
2122     if (defined ($SymbolDocs{$symbol})) {
2123         my $symbol_docs = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
2125         # Try to insert the parameter table at the author's desired position.
2126         # Otherwise we need to tag it onto the end.
2127         # FIXME: document that in the user manual and make it useable for other
2128         # types too
2129         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
2130           $parameters_output = 1;
2131         }
2132         $desc .= $symbol_docs;
2133     }
2135     if ($parameters_output == 0) {
2136         $desc .= $parameters;
2137     }
2139     $desc .= OutputSymbolTraits ($symbol);
2140     $desc .= "</refsect2>\n";
2141     return ($synop, $desc);
2145 #############################################################################
2146 # Function    : OutputParamDescriptions
2147 # Description : Returns the DocBook output describing the parameters of a
2148 #                function, macro or signal handler.
2149 # Arguments   : $symbol_type - 'FUNCTION', 'MACRO' or 'SIGNAL'. Signal
2150 #                  handlers have an implicit user_data parameter last.
2151 #                $symbol - the name of the function/macro being described.
2152 #               @fields - parsed fields from the declaration, used to determine
2153 #                  undocumented/unused entries
2154 #############################################################################
2156 sub OutputParamDescriptions {
2157     my ($symbol_type, $symbol, @fields) = @_;
2158     my $output = "";
2159     my $params = $SymbolParams{$symbol};
2160     my $num_params = 0;
2161     my %field_descrs = ();
2163     if (@fields) {
2164         %field_descrs = @fields;
2165         delete $field_descrs{"void"};
2166         delete $field_descrs{"Returns"};
2167     }
2169     if (defined $params) {
2170         my $returns = "";
2171         my $params_desc = "";
2172         my $missing_parameters = "";
2173         my $unused_parameters = "";
2174         my $j;
2176         for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
2177             my $param_name = $$params[$j];
2178             my $param_desc = $$params[$j + 1];
2179             my $param_annotations = "";
2181             ($param_desc,$param_annotations) = & ExpandAnnotation($symbol, $param_desc);
2182             $param_desc = &ExpandAbbreviations($symbol, $param_desc);
2183             $param_desc .= $param_annotations;
2184             # trim
2185             $param_desc =~ s/^(\s|\n)+//msg;
2186             $param_desc =~ s/(\s|\n)+$//msg;
2187             if ($param_name eq "Returns") {
2188                 $returns = "$param_desc";
2189             } elsif ($param_name eq "void") {
2190                 #print "!!!! void in params for $symbol?\n";
2191             } else {
2192                 if (@fields) {
2193                     if (!defined $field_descrs{$param_name}) {
2194                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2195                             "Parameter description for $symbol"."::"."$param_name is not used from source code comment block.");
2196                         if ($unused_parameters ne "") {
2197                           $unused_parameters .= ", ".$param_name;
2198                         } else {
2199                            $unused_parameters = $param_name;
2200                         }
2201                     } else {
2202                         delete $field_descrs{$param_name};
2203                     }
2204                 }
2205                 if($param_desc ne "") {
2206                     $params_desc .= "<varlistentry><term><parameter>$param_name</parameter>&#160;:</term>\n<listitem><simpara>$param_desc</simpara></listitem></varlistentry>\n";
2207                     $num_params++;
2208                 }
2209             }
2210         }
2211         foreach my $param_name (keys %field_descrs) {
2212             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2213                 "Parameter description for $symbol"."::"."$param_name is missing in source code comment block.");
2214             if ($missing_parameters ne "") {
2215               $missing_parameters .= ", ".$param_name;
2216             } else {
2217                $missing_parameters = $param_name;
2218             }
2219         }
2221         # Signals have an implicit user_data parameter which we describe.
2222         if ($symbol_type eq "SIGNAL") {
2223             $params_desc .= "<varlistentry><term><parameter>user_data</parameter>&#160;:</term>\n<listitem><simpara>user data set when the signal handler was connected.</simpara></listitem></varlistentry>\n";
2224         }
2226         # Start a table if we need one.
2227         if ($params_desc || $returns) {
2228             $output .= "<variablelist role=\"params\">\n";
2229             if ($params_desc ne "") {
2230                 #$output .= "<varlistentry><term>Parameters:</term><listitem></listitem></varlistentry>\n";
2231                 $output .= $params_desc;
2232             }
2234             # Output the returns info last
2235             if ($returns) {
2236                 $output .= "<varlistentry><term><emphasis>Returns</emphasis>&#160;:</term><listitem><simpara>$returns</simpara></listitem></varlistentry>\n";
2237             }
2239             # Finish the table.
2240             $output .= "</variablelist>";
2241         }
2243         # remember missing/unused parameters (needed in tmpl-free build)
2244         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
2245             $AllIncompleteSymbols{$symbol}=$missing_parameters;
2246         }
2247         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
2248             $AllUnusedSymbols{$symbol}=$unused_parameters;
2249         }
2250     }
2251     if (($num_params == 0) && @fields && (scalar(keys(%field_descrs)) > 0)) {
2252         if (! exists ($AllIncompleteSymbols{$symbol})) {
2253             $AllIncompleteSymbols{$symbol}="<parameters>";
2254         }
2255     }
2257     return $output;
2261 #############################################################################
2262 # Function    : ParseStabilityLevel
2263 # Description : Parses a stability level and outputs a warning if it isn't
2264 #               valid.
2265 # Arguments   : $stability - the stability text.
2266 #                $file, $line - context for error message
2267 #                $message - description of where the level is from, to use in
2268 #               any error message.
2269 # Returns     : The parsed stability level string.
2270 #############################################################################
2272 sub ParseStabilityLevel {
2273     my ($stability, $file, $line, $message) = @_;
2275     $stability =~ s/^\s*//;
2276     $stability =~ s/\s*$//;
2277     if ($stability =~ m/^stable$/i) {
2278         $stability = "Stable";
2279     } elsif ($stability =~ m/^unstable$/i) {
2280         $stability = "Unstable";
2281     } elsif ($stability =~ m/^private$/i) {
2282         $stability = "Private";
2283     } else {
2284         &LogWarning ($file, $line, "$message is $stability.".
2285             "It should be one of these: Stable, Unstable, or Private.");
2286     }
2287     return $stability;
2291 #############################################################################
2292 # Function    : OutputSGMLFile
2293 # Description : Outputs the final DocBook file for one section.
2294 # Arguments   : $file - the name of the file.
2295 #               $title - the title from the $MODULE-sections.txt file, which
2296 #                 will be overridden by the title in the template file.
2297 #               $section_id - the SGML id to use for the toplevel tag.
2298 #               $includes - comma-separates list of include files added at top of
2299 #                 synopsis, with '<' '>' around them (if not already enclosed in "").
2300 #               $synopsis - reference to the DocBook for the Synopsis part.
2301 #               $details - reference to the DocBook for the Details part.
2302 #               $signal_synop - reference to the DocBook for the Signal Synopsis part
2303 #               $signal_desc - reference to the DocBook for the Signal Description part
2304 #               $args_synop - reference to the DocBook for the Arg Synopsis part
2305 #               $args_desc - reference to the DocBook for the Arg Description part
2306 #               $hierarchy - reference to the DocBook for the Object Hierarchy part
2307 #               $interfaces - reference to the DocBook for the Interfaces part
2308 #               $implementations - reference to the DocBook for the Known Implementations part
2309 #               $prerequisites - reference to the DocBook for the Prerequisites part
2310 #               $derived - reference to the DocBook for the Derived Interfaces part
2311 #               $file_objects - reference to an array of objects in this file
2312 #############################################################################
2314 sub OutputSGMLFile {
2315     my ($file, $title, $section_id, $includes, $synopsis, $details, $signals_synop, $signals_desc, $args_synop, $args_desc, $hierarchy, $interfaces, $implementations, $prerequisites, $derived, $file_objects) = @_;
2317     #print "Output sgml for file $file with title '$title'\n";
2319     # The edited title overrides the one from the sections file.
2320     my $new_title = $SymbolDocs{"$TMPL_DIR/$file:Title"};
2321     if (defined ($new_title) && $new_title !~ m/^\s*$/) {
2322         $title = $new_title;
2323         #print "Found title: $title\n";
2324     }
2325     my $short_desc = $SymbolDocs{"$TMPL_DIR/$file:Short_Description"};
2326     if (!defined ($short_desc) || $short_desc =~ m/^\s*$/) {
2327         $short_desc = "";
2328     } else {
2329         $short_desc = &ExpandAbbreviations("$title:Short_description",
2330                                            $short_desc);
2331         #print "Found short_desc: $short_desc";
2332     }
2333     my $long_desc = $SymbolDocs{"$TMPL_DIR/$file:Long_Description"};
2334     if (!defined ($long_desc) || $long_desc =~ m/^\s*$/) {
2335         $long_desc = "";
2336     } else {
2337         $long_desc = &ExpandAbbreviations("$title:Long_description",
2338                                           $long_desc);
2339         #print "Found long_desc: $long_desc";
2340     }
2341     my $see_also = $SymbolDocs{"$TMPL_DIR/$file:See_Also"};
2342     if (!defined ($see_also) || $see_also =~ m%^\s*(<para>)?\s*(</para>)?\s*$%) {
2343         $see_also = "";
2344     } else {
2345         $see_also = &ExpandAbbreviations("$title:See_Also", $see_also);
2346         #print "Found see_also: $see_also";
2347     }
2348     if ($see_also) {
2349         $see_also = "<refsect1 id=\"$section_id.see-also\">\n<title>See Also</title>\n$see_also\n</refsect1>\n";
2350     }
2351     my $stability = $SymbolDocs{"$TMPL_DIR/$file:Stability_Level"};
2352     if (!defined ($stability) || $stability =~ m/^\s*$/) {
2353         $stability = "";
2354     } else {
2355         $stability = &ParseStabilityLevel($stability, $file, $., "Section stability level");
2356         #print "Found stability: $stability";
2357     }
2358     if ($stability) {
2359         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$stability, unless otherwise indicated\n</refsect1>\n";
2360     } elsif ($DEFAULT_STABILITY) {
2361         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$DEFAULT_STABILITY, unless otherwise indicated\n</refsect1>\n";
2362     }
2364     my $image = $SymbolDocs{"$TMPL_DIR/$file:Image"};
2365     if (!defined ($image) || $image =~ m/^\s*$/) {
2366       $image = "";
2367     } else {
2368       $image =~ s/^\s*//;
2369       $image =~ s/\s*$//;
2371       my $format;
2373       if ($image =~ /jpe?g$/i) {
2374         $format = "format='JPEG'";
2375       } elsif ($image =~ /png$/i) {
2376         $format = "format='PNG'";
2377       } elsif ($image =~ /svg$/i) {
2378         $format = "format='SVG'";
2379       } else {
2380         $format = "";
2381       }
2383       $image = "  <inlinegraphic fileref='$image' $format/>\n"
2384     }
2386     my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
2387         gmtime (time);
2388     my $month = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))[$mon];
2389     $year += 1900;
2391     my $include_output = "";
2392     my $include;
2393     foreach $include (split (/,/, $includes)) {
2394         if ($include =~ m/^\".+\"$/) {
2395             $include_output .= "#include ${include}\n";
2396         }
2397         else {
2398             $include =~ s/^\s+|\s+$//gs;
2399             $include_output .= "#include &lt;${include}&gt;\n";
2400         }
2401     }
2402     if ($include_output ne '') {
2403         $include_output = "\n$include_output\n";
2404     }
2406     my $extralinks = OutputSectionExtraLinks($title,"Section:$file");
2408     my $old_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT";
2409     my $new_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT.new";
2411     open (OUTPUT, ">$new_sgml_file")
2412         || die "Can't create $new_sgml_file: $!";
2414     my $object_anchors = "";
2415     foreach my $object (@$file_objects) {
2416         next if ($object eq $section_id);
2417         my $id = CreateValidSGMLID($object);
2418         #print "Debug: Adding anchor for $object\n";
2419         $object_anchors .= "<anchor id=\"$id\"$empty_element_end";
2420     }
2422     # We used to output this, but is messes up our UpdateFileIfChanged code
2423     # since it changes every day (and it is only used in the man pages):
2424     # "<refentry id="$section_id" revision="$mday $month $year">"
2426     if ($OUTPUT_FORMAT eq "xml") {
2427         print OUTPUT $doctype_header;
2428     }
2430     print OUTPUT <<EOF;
2431 <refentry id="$section_id">
2432 <refmeta>
2433 <refentrytitle role="top_of_page" id="$section_id.top_of_page">$title</refentrytitle>
2434 <manvolnum>3</manvolnum>
2435 <refmiscinfo>
2436   \U$MODULE\E Library
2437 $image</refmiscinfo>
2438 </refmeta>
2439 <refnamediv>
2440 <refname>$title</refname>
2441 <refpurpose>$short_desc</refpurpose>
2442 </refnamediv>
2443 $stability
2444 <refsynopsisdiv id="$section_id.synopsis" role="synopsis">
2445 <title role="synopsis.title">Synopsis</title>
2446 $object_anchors
2447 <synopsis>$include_output$${synopsis}</synopsis>
2448 </refsynopsisdiv>
2449 $$hierarchy$$prerequisites$$derived$$interfaces$$implementations$$args_synop$$signals_synop
2450 <refsect1 id="$section_id.description" role="desc">
2451 <title role="desc.title">Description</title>
2452 $extralinks$long_desc
2453 </refsect1>
2454 <refsect1 id="$section_id.details" role="details">
2455 <title role="details.title">Details</title>
2456 $$details
2457 </refsect1>
2458 $$args_desc$$signals_desc$see_also
2459 </refentry>
2461     close (OUTPUT);
2463     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2467 #############################################################################
2468 # Function    : OutputExtraFile
2469 # Description : Copies an "extra" DocBook file into the output directory,
2470 #               expanding abbreviations
2471 # Arguments   : $file - the source file.
2472 #############################################################################
2473 sub OutputExtraFile {
2474     my ($file) = @_;
2476     my $basename;
2478     ($basename = $file) =~ s!^.*/!!;
2480     my $old_sgml_file = "$SGML_OUTPUT_DIR/$basename";
2481     my $new_sgml_file = "$SGML_OUTPUT_DIR/$basename.new";
2483     my $contents;
2485     open(EXTRA_FILE, "<$file") || die "Can't open $file";
2487     {
2488         local $/;
2489         $contents = <EXTRA_FILE>;
2490     }
2492     open (OUTPUT, ">$new_sgml_file")
2493         || die "Can't create $new_sgml_file: $!";
2495     print OUTPUT &ExpandAbbreviations ("$basename file", $contents);
2496     close (OUTPUT);
2498     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2500 #############################################################################
2501 # Function    : OutputBook
2502 # Description : Outputs the SGML entities that need to be included into the
2503 #                main SGML file for the module.
2504 # Arguments   : $book_top - the declarations of the entities, which are added
2505 #                  at the top of the main SGML file.
2506 #                $book_bottom - the references to the entities, which are
2507 #                  added in the main SGML file at the desired position.
2508 #############################################################################
2510 sub OutputBook {
2511     my ($book_top, $book_bottom) = @_;
2513     my $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top";
2514     my $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top.new";
2516     open (OUTPUT, ">$new_file")
2517         || die "Can't create $new_file: $!";
2518     print OUTPUT $book_top;
2519     close (OUTPUT);
2521     &UpdateFileIfChanged ($old_file, $new_file, 0);
2524     $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom";
2525     $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom.new";
2527     open (OUTPUT, ">$new_file")
2528         || die "Can't create $new_file: $!";
2529     print OUTPUT $book_bottom;
2530     close (OUTPUT);
2532     &UpdateFileIfChanged ($old_file, $new_file, 0);
2535     # If the main SGML/XML file hasn't been created yet, we create it here.
2536     # The user can tweak it later.
2537     if ($MAIN_SGML_FILE && ! -e $MAIN_SGML_FILE) {
2538       open (OUTPUT, ">$MAIN_SGML_FILE")
2539         || die "Can't create $MAIN_SGML_FILE: $!";
2541       if ($OUTPUT_FORMAT eq "xml") {
2542           print OUTPUT <<EOF;
2543 <?xml version="1.0"?>
2544 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
2545                "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd"
2547   <!ENTITY % local.common.attrib "xmlns:xi  CDATA  #FIXED 'http://www.w3.org/2003/XInclude'">
2549 <book id="index">
2551       } else {
2552         print OUTPUT <<EOF;
2553 <!doctype book PUBLIC "-//Davenport//DTD DocBook V3.0//EN" [
2554 $book_top
2556 <book id="index">
2558       }
2560 print OUTPUT <<EOF;
2561   <bookinfo>
2562     <title>$MODULE Reference Manual</title>
2563     <releaseinfo>
2564       for $MODULE [VERSION].
2565       The latest version of this documentation can be found on-line at
2566       <ulink role="online-location" url="http://[SERVER]/$MODULE/index.html">http://[SERVER]/$MODULE/</ulink>.
2567     </releaseinfo>
2568   </bookinfo>
2570   <chapter>
2571     <title>[Insert title here]</title>
2572     $book_bottom
2573   </chapter>
2575   if (-e $OBJECT_TREE_FILE) {
2576     print OUTPUT <<EOF;
2577   <chapter id="object-tree">
2578     <title>Object Hierarchy</title>
2579      <xi:include href="xml/tree_index.sgml"/>
2580   </chapter>
2582   }
2584 print OUTPUT <<EOF;
2585   <index id="api-index-full">
2586     <title>API Index</title>
2587     <xi:include href="xml/api-index-full.xml"><xi:fallback /></xi:include>
2588   </index>
2589   <index id="deprecated-api-index" role="deprecated">
2590     <title>Index of deprecated API</title>
2591     <xi:include href="xml/api-index-deprecated.xml"><xi:fallback /></xi:include>
2592   </index>
2594   <xi:include href="xml/annotation-glossary.xml"><xi:fallback /></xi:include>
2595 </book>
2598       close (OUTPUT);
2599     }
2603 #############################################################################
2604 # Function    : CreateValidSGML
2605 # Description : This turns any chars which are used in SGML into entities,
2606 #                e.g. '<' into '&lt;'
2607 # Arguments   : $text - the text to turn into proper SGML.
2608 #############################################################################
2610 sub CreateValidSGML {
2611     my ($text) = @_;
2612     $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2613     $text =~ s/</&lt;/g;
2614     $text =~ s/>/&gt;/g;
2615     # browers render single tabs inconsistently
2616     $text =~ s/([^\s])\t([^\s])/$1&#160;$2/g;
2617     return $text;
2620 #############################################################################
2621 # Function    : ConvertSGMLChars
2622 # Description : This is used for text in source code comment blocks, to turn
2623 #               chars which are used in SGML into entities, e.g. '<' into
2624 #               '&lt;'. Depending on $INLINE_MARKUP_MODE, this is done
2625 #               unconditionally or only if the character doesn't seem to be
2626 #               part of an SGML construct (tag or entity reference).
2627 # Arguments   : $text - the text to turn into proper SGML.
2628 #############################################################################
2630 sub ConvertSGMLChars {
2631     my ($symbol, $text) = @_;
2633     if ($INLINE_MARKUP_MODE) {
2634         # For the XML/SGML mode only convert to entities outside CDATA sections.
2635         return &ModifyXMLElements ($text, $symbol,
2636                                    "<!\\[CDATA\\[|<programlisting[^>]*>",
2637                                    \&ConvertSGMLCharsEndTag,
2638                                    \&ConvertSGMLCharsCallback);
2639     } else {
2640         # For the simple non-sgml mode, convert to entities everywhere.
2641         $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2642         $text =~ s/</&lt;/g;
2643         $text =~ s/>/&gt;/g;
2644         return $text;
2645     }
2649 sub ConvertSGMLCharsEndTag {
2650   if ($_[0] eq "<!\[CDATA\[") {
2651     return "]]>";
2652   } else {
2653     return "</programlisting>";
2654   }
2657 sub ConvertSGMLCharsCallback {
2658   my ($text, $symbol, $tag) = @_;
2660   if ($tag =~ m/^<programlisting/) {
2661     # We can handle <programlisting> specially here.
2662     return &ModifyXMLElements ($text, $symbol,
2663                                "<!\\[CDATA\\[",
2664                                \&ConvertSGMLCharsEndTag,
2665                                \&ConvertSGMLCharsCallback2);
2666   } elsif ($tag eq "") {
2667     # If we're not in CDATA convert to entities.
2668     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2669     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2670     $text =~ s/(?<![a-zA-Z0-9"'\/-])>/&gt;/g;
2672     # Handle "#include <xxxxx>"
2673     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2674   }
2676   return $text;
2679 sub ConvertSGMLCharsCallback2 {
2680   my ($text, $symbol, $tag) = @_;
2682   # If we're not in CDATA convert to entities.
2683   # We could handle <programlisting> differently, though I'm not sure it helps.
2684   if ($tag eq "") {
2685     # replace only if its not a tag
2686     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2687     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2688     $text =~ s/(?<![a-zA-Z0-9"'\/-])>/&gt;/g;
2690     # Handle "#include <xxxxx>"
2691     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2692   }
2694   return $text;
2697 #############################################################################
2698 # Function    : ExpandAnnotation
2699 # Description : This turns annotations into acronym tags.
2700 # Arguments   : $symbol - the symbol being documented, for error messages.
2701 #                $text - the text to expand.
2702 #############################################################################
2703 sub ExpandAnnotation {
2704     my ($symbol, $param_desc) = @_;
2705     my $param_annotations = "";
2707     # look for annotations at the start of the comment part
2708     if ($param_desc =~ m%^\s*\((.*?)\):%) {
2709         my @annotations;
2710         my $annotation;
2711         $param_desc = $';
2713         @annotations = split(/\)\s*\(/,$1);
2714         foreach $annotation (@annotations) {
2715             # need to search for the longest key-match in %AnnotationDefinition
2716             my $match_length=0;
2717             my $match_annotation="";
2718             my $annotationdef;
2719             foreach $annotationdef (keys %AnnotationDefinition) {
2720                 if ($annotation =~ m/^$annotationdef/) {
2721                     if (length($annotationdef)>$match_length) {
2722                         $match_length=length($annotationdef);
2723                         $match_annotation=$annotationdef;
2724                     }
2725                 }
2726             }
2727             my $annotation_extra = "";
2728             if ($match_annotation ne "") {
2729                 if ($annotation =~ m%$match_annotation\s+(.*)%) {
2730                     $annotation_extra = " $1";
2731                 }
2732                 $AnnotationsUsed{$match_annotation} = 1;
2733                 $param_annotations .= "[<acronym>$match_annotation</acronym>$annotation_extra]";
2734             }
2735             else {
2736                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2737                     "unknown annotation \"$annotation\" in documentation for $symbol.");
2738                 $param_annotations .= "[$annotation]";
2739             }
2740         }
2741         chomp($param_desc);
2742         $param_desc =~ m/^(.*?)\.*\s*$/s;
2743         $param_desc = "$1. ";
2744     }
2745     if ($param_annotations ne "") {
2746         $param_annotations = "<emphasis role=\"annotation\">$param_annotations</emphasis>";
2747     }
2748     return ($param_desc, $param_annotations);
2751 #############################################################################
2752 # Function    : ExpandAbbreviations
2753 # Description : This turns the abbreviations function(), macro(), @param,
2754 #                %constant, and #symbol into appropriate DocBook markup.
2755 #               CDATA sections and <programlisting> parts are skipped.
2756 # Arguments   : $symbol - the symbol being documented, for error messages.
2757 #                $text - the text to expand.
2758 #############################################################################
2760 sub ExpandAbbreviations {
2761   my ($symbol, $text) = @_;
2763   # Convert "|[" and "]|" into the start and end of program listing examples.
2764   # Support \[<!-- language="C" --> modifiers
2765   $text =~ s%\|\[<!-- language="([^"]+)" -->%<informalexample><programlisting language="$1"><![CDATA[%g;
2766   $text =~ s%\|\[%<informalexample><programlisting><![CDATA[%g;
2767   $text =~ s%\]\|%]]></programlisting></informalexample>%g;
2769   # keep CDATA unmodified, preserve ulink tags (ideally we preseve all tags
2770   # as such)
2771   return &ModifyXMLElements ($text, $symbol,
2772                              "<!\\[CDATA\\[|<ulink[^>]*>|<programlisting[^>]*>|<!DOCTYPE",
2773                              \&ExpandAbbreviationsEndTag,
2774                              \&ExpandAbbreviationsCallback);
2778 # Returns the end tag (as a regexp) corresponding to the given start tag.
2779 sub ExpandAbbreviationsEndTag {
2780   my ($start_tag) = @_;
2782   if ($start_tag eq "<!\[CDATA\[") {
2783     return "]]>";
2784   } elsif ($start_tag eq "<!DOCTYPE") {
2785     return ">";
2786   } elsif ($start_tag =~ m/<(\w+)/) {
2787     return "</$1>";
2788   }
2791 # Called inside or outside each CDATA or <programlisting> section.
2792 sub ExpandAbbreviationsCallback {
2793   my ($text, $symbol, $tag) = @_;
2795   if ($tag =~ m/^<programlisting/) {
2796     # Handle any embedded CDATA sections.
2797     return &ModifyXMLElements ($text, $symbol,
2798                                "<!\\[CDATA\\[",
2799                                \&ExpandAbbreviationsEndTag,
2800                                \&ExpandAbbreviationsCallback2);
2801   } elsif ($tag eq "") {
2802     # We are outside any CDATA or <programlisting> sections, so we expand
2803     # any gtk-doc abbreviations.
2805     # Convert '@param()'
2806     # FIXME: we could make those also links ($symbol.$2), but that would be less
2807     # useful as the link target is a few lines up or down
2808     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)/$1<parameter>$2()<\/parameter>/g;
2810     # Convert 'function()' or 'macro()'.
2811     # if there is abc_*_def() we don't want to make a link to _def()
2812     # FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
2813     $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2814     # handle #Object.func()
2815     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2817     # Convert '@param', but not '\@param'.
2818     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)/$1<parameter>$2<\/parameter>/g;
2819     $text =~ s/\\\@/\@/g;
2821     # Convert '%constant', but not '\%constant'.
2822     # Also allow negative numbers, e.g. %-1.
2823     $text =~ s/(\A|[^\\])\%(-?\w+)/$1.&MakeXRef($2, &tagify($2, "literal"));/eg;
2824     $text =~ s/\\\%/\%/g;
2826     # Convert '#symbol', but not '\#symbol'.
2827     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)/$1.&MakeHashXRef($2, "type");/eg;
2828     $text =~ s/\\#/#/g;
2830     # Expand urls
2831     # FIXME: should we skip urls that are already tagged? (e.g. <literal>http://...</literal>)
2832     # this is apparently also called for markup and not just for plain text
2833     # disable for now.
2834     #$text =~ s%(http|https|ftp)://(.*?)((?:\s|,|\)|\]|\<|\.\s))%<ulink url="$1://$2">$2</ulink>$3%g;
2836     # TODO: optionally check all words from $text against internal symbols and
2837     # warn if those could be xreffed, but miss a %,# or ()
2838   }
2840   return $text;
2843 # This is called inside a <programlisting>
2844 sub ExpandAbbreviationsCallback2 {
2845   my ($text, $symbol, $tag) = @_;
2847   if ($tag eq "") {
2848     # We are inside a <programlisting> but outside any CDATA sections,
2849     # so we expand any gtk-doc abbreviations.
2850     # FIXME: why is this different from &ExpandAbbreviationsCallback(),
2851     #        why not just call it
2852     $text =~ s/#(\w+)/&MakeHashXRef($1, "");/eg;
2853   } elsif ($tag eq "<![CDATA[") {
2854     my $warn = "";
2855     my @entities = ( [ "&lt;", "<" ],
2856                      [ "&gt;", ">" ],
2857                      [ "&ast;", "*" ],
2858                      [ "&num;", "#" ],
2859                      [ "&percnt;", "%"],
2860                      [ "&colon;", ":" ],
2861                      [ "&quot;", "\"" ],
2862                      [ "&apos;", "'" ],
2863                      [ "&nbsp;", " " ],
2864                      [ "&amp;", "&" ] ); # Do this last, or the others get messed up.
2865     my $i;
2867     # Expand entities in <programlisting> even inside CDATA since
2868     # we changed the definition of |[ to add CDATA
2869     for ($i = 0; $i <= $#entities; $i++) {
2870       if ($text =~ s/$entities[$i][0]/$entities[$i][1]/g) {
2871         # don't warn about &ast; since it is expected to be present
2872         # for C-style comments
2873         if ($entities[$i][0] ne "&ast;") {
2874           $warn .= "$entities[$i][0] ";
2875         }
2876       }
2877     }
2879     if ($warn ne "") {
2880       chomp $warn;
2881       &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2882                    "Deprecated entities found in documentation for $symbol: $warn");
2883     }
2885   }
2887   return $text;
2890 sub MakeHashXRef {
2891     my ($symbol, $tag) = @_;;
2892     my $text = $symbol;
2894     # Check for things like '#include', '#define', and skip them.
2895     if ($PreProcessorDirectives{$symbol}) {
2896       return "#$symbol";
2897     }
2899     # Get rid of special suffixes ('-struct','-enum').
2900     $text =~ s/-struct$//;
2901     $text =~ s/-enum$//;
2903     # If the symbol is in the form "Object::signal", then change the symbol to
2904     # "Object-signal" and use "signal" as the text.
2905     if ($symbol =~ s/::/-/) {
2906       $text = "\"$'\"";
2907     }
2909     # If the symbol is in the form "Object:property", then change the symbol to
2910     # "Object--property" and use "property" as the text.
2911     if ($symbol =~ s/:/--/) {
2912       $text = "\"$'\"";
2913     }
2915     if ($tag ne "") {
2916       $text = tagify ($text, $tag);
2917     }
2919     return &MakeXRef($symbol, $text);
2923 #############################################################################
2924 # Function    : ModifyXMLElements
2925 # Description : Looks for given XML element tags within the text, and calls
2926 #               the callback on pieces of text inside & outside those elements.
2927 #               Used for special handling of text inside things like CDATA
2928 #               and <programlisting>.
2929 # Arguments   : $text - the text.
2930 #               $symbol - the symbol currently being documented (only used for
2931 #                      error messages).
2932 #               $start_tag_regexp - the regular expression to match start tags.
2933 #                      e.g. "<!\\[CDATA\\[|<programlisting[^>]*>" to match
2934 #                      CDATA sections or programlisting elements.
2935 #               $end_tag_func - function which is passed the matched start tag
2936 #                      and should return the appropriate end tag string regexp.
2937 #               $callback - callback called with each part of the text. It is
2938 #                      called with a piece of text, the symbol being
2939 #                      documented, and the matched start tag or "" if the text
2940 #                      is outside the XML elements being matched.
2941 #############################################################################
2942 sub ModifyXMLElements {
2943     my ($text, $symbol, $start_tag_regexp, $end_tag_func, $callback) = @_;
2944     my ($before_tag, $start_tag, $end_tag_regexp, $end_tag);
2945     my $result = "";
2947     while ($text =~ m/$start_tag_regexp/s) {
2948       $before_tag = $`; # Prematch for last successful match string
2949       $start_tag = $&;  # Last successful match
2950       $text = $';       # Postmatch for last successful match string
2952       $result .= &$callback ($before_tag, $symbol, "");
2953       $result .= $start_tag;
2955       # get the matching end-tag for current tag
2956       $end_tag_regexp = &$end_tag_func ($start_tag);
2958       if ($text =~ m/$end_tag_regexp/s) {
2959         $before_tag = $`;
2960         $end_tag = $&;
2961         $text = $';
2963         $result .= &$callback ($before_tag, $symbol, $start_tag);
2964         $result .= $end_tag;
2965       } else {
2966         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2967             "Can't find tag end: $end_tag_regexp in docs for: $symbol.");
2968         # Just assume it is all inside the tag.
2969         $result .= &$callback ($text, $symbol, $start_tag);
2970         $text = "";
2971       }
2972     }
2974     # Handle any remaining text outside the tags.
2975     $result .= &$callback ($text, $symbol, "");
2977     return $result;
2980 sub noop {
2981   return $_[0];
2984 # Adds a tag around some text.
2985 # e.g tagify("Text", "literal") => "<literal>Text</literal>".
2986 sub tagify {
2987    my ($text, $elem) = @_;
2988    return "<" . $elem . ">" . $text . "</" . $elem . ">";
2992 #############################################################################
2993 # Function    : MakeXRef
2994 # Description : This returns a cross-reference link to the given symbol.
2995 #                Though it doesn't try to do this for a few standard C types
2996 #                that it        knows won't be in the documentation.
2997 # Arguments   : $symbol - the symbol to try to create a XRef to.
2998 #               $text - text text to put inside the XRef, defaults to $symbol
2999 #############################################################################
3001 sub MakeXRef {
3002     my ($symbol, $text) = ($_[0], $_[1]);
3004     $symbol =~ s/^\s+//;
3005     $symbol =~ s/\s+$//;
3007     if (!defined($text)) {
3008         $text = $symbol;
3010         # Get rid of special suffixes ('-struct','-enum').
3011         $text =~ s/-struct$//;
3012         $text =~ s/-enum$//;
3013     }
3015     if ($symbol =~ m/ /) {
3016         return "$text";
3017     }
3019     #print "Getting type link for $symbol -> $text\n";
3021     my $symbol_id = &CreateValidSGMLID ($symbol);
3022     return "<link linkend=\"$symbol_id\">$text</link>";
3026 #############################################################################
3027 # Function    : MakeIndexterms
3028 # Description : This returns a indexterm elements for the given symbol
3029 # Arguments   : $symbol - the symbol to create indexterms for
3030 #############################################################################
3032 sub MakeIndexterms {
3033   my ($symbol, $id) = @_;
3034   my $terms =  "";
3035   my $sortas = "";
3037   # make the index useful, by ommiting the namespace when sorting
3038   if ($NAME_SPACE ne "") {
3039     if ($symbol =~ m/^$NAME_SPACE\_?(.*)/i) {
3040        $sortas=" sortas=\"$1\"";
3041     }
3042   }
3044   if (exists $Deprecated{$symbol}) {
3045       $terms .= "<indexterm zone=\"$id\" role=\"deprecated\"><primary$sortas>$symbol</primary></indexterm>";
3046       $IndexEntriesDeprecated{$symbol}=$id;
3047       $IndexEntriesFull{$symbol}=$id;
3048   }
3049   if (exists $Since{$symbol}) {
3050      my $since = $Since{$symbol};
3051      $since =~ s/^\s+//;
3052      $since =~ s/\s+$//;
3053      if ($since ne "") {
3054          $terms .= "<indexterm zone=\"$id\" role=\"$since\"><primary$sortas>$symbol</primary></indexterm>";
3055      }
3056      $IndexEntriesSince{$symbol}=$id;
3057      $IndexEntriesFull{$symbol}=$id;
3058   }
3059   if ($terms eq "") {
3060      $terms .= "<indexterm zone=\"$id\"><primary$sortas>$symbol</primary></indexterm>";
3061      $IndexEntriesFull{$symbol}=$id;
3062   }
3064   return $terms;
3067 #############################################################################
3068 # Function    : MakeDeprecationNote
3069 # Description : This returns a deprecation warning for the given symbol.
3070 # Arguments   : $symbol - the symbol to try to create a warning for.
3071 #############################################################################
3073 sub MakeDeprecationNote {
3074     my ($symbol) = $_[0];
3075     my $desc = "";
3076     my $note = "";
3077     if (exists $Deprecated{$symbol}) {
3078         $desc .= "<warning>";
3080         if ($Deprecated{$symbol} =~ /^\s*([0-9\.]+)\s*:/) {
3081                 $desc .= "<para><literal>$symbol</literal> has been deprecated since version $1 and should not be used in newly-written code.";
3082         } else {
3083                 $desc .= "<para><literal>$symbol</literal> is deprecated and should not be used in newly-written code.";
3084         }
3085         if ($Deprecated{$symbol} ne "") {
3086             $note = &ExpandAbbreviations($symbol, $Deprecated{$symbol});
3087             $note =~ s/^\s*([0-9\.]+)\s*:\s*//;
3088             $note =~ s/^\s+//;
3089             $note =~ s/\s+$//;
3090             $note =~ s%\n{2,}%\n</para>\n<para>\n%g;
3091             $desc .= " " . $note;
3092         }
3093         $desc .= "</para></warning>\n";
3094     }
3095     return $desc;
3098 #############################################################################
3099 # Function    : MakeConditionDescription
3100 # Description : This returns a sumary of conditions for the given symbol.
3101 # Arguments   : $symbol - the symbol to try to create the sumary.
3102 #############################################################################
3104 sub MakeConditionDescription {
3105     my ($symbol) = $_[0];
3106     my $desc = "";
3108     if (exists $Deprecated{$symbol}) {
3109         if ($desc ne "") {
3110             $desc .= "|";
3111         }
3113         if ($Deprecated{$symbol} =~ /^\s*(.*?)\s*$/) {
3114                 $desc .= "deprecated:$1";
3115         } else {
3116                 $desc .= "deprecated";
3117         }
3118     }
3120     if (exists $Since{$symbol}) {
3121         if ($desc ne "") {
3122             $desc .= "|";
3123         }
3125         if ($Since{$symbol} =~ /^\s*(.*?)\s*$/) {
3126                 $desc .= "since:$1";
3127         } else {
3128                 $desc .= "since";
3129         }
3130     }
3132     if (exists $StabilityLevel{$symbol}) {
3133         if ($desc ne "") {
3134             $desc .= "|";
3135         }
3136         $desc .= "stability:".$StabilityLevel{$symbol};
3137     }
3139     if ($desc ne "") {
3140         my $cond = $desc;
3141         $cond =~ s/\"/&quot;/g;
3142         $desc=" condition=\"".$cond."\"";
3143         #print "condition for '$symbol' = '$desc'\n";
3144     }
3145     return $desc;
3148 #############################################################################
3149 # Function    : GetHierarchy
3150 # Description : Returns the DocBook output describing the ancestors and
3151 #               immediate children of a GObject subclass. It uses the
3152 #               global @Objects and @ObjectLevels arrays to walk the tree.
3153 # Arguments   : $object - the GtkObject subclass.
3154 #############################################################################
3156 sub GetHierarchy {
3157     my ($object) = @_;
3159     # Find object in the objects array.
3160     my $found = 0;
3161     my @children = ();
3162     my $i;
3163     my $level;
3164     my $j;
3165     for ($i = 0; $i < @Objects; $i++) {
3166         if ($found) {
3167             if ($ObjectLevels[$i] <= $level) {
3168             last;
3169         }
3170             elsif ($ObjectLevels[$i] == $level + 1) {
3171                 push (@children, $Objects[$i]);
3172             }
3173         }
3174         elsif ($Objects[$i] eq $object) {
3175             $found = 1;
3176             $j = $i;
3177             $level = $ObjectLevels[$i];
3178         }
3179     }
3180     if (!$found) {
3181         return "";
3182     }
3184     # Walk up the hierarchy, pushing ancestors onto the ancestors array.
3185     my @ancestors = ();
3186     push (@ancestors, $object);
3187     #print "Level: $level\n";
3188     while ($level > 1) {
3189         $j--;
3190         if ($ObjectLevels[$j] < $level) {
3191             push (@ancestors, $Objects[$j]);
3192             $level = $ObjectLevels[$j];
3193             #print "Level: $level\n";
3194         }
3195     }
3197     # Output the ancestors list, indented and with links.
3198     my $hierarchy = "<synopsis>\n";
3199     $level = 0;
3200     for ($i = $#ancestors; $i >= 0; $i--) {
3201         my $link_text;
3202         # Don't add a link to the current object, i.e. when i == 0.
3203         if ($i > 0) {
3204             my $ancestor_id = &CreateValidSGMLID ($ancestors[$i]);
3205             $link_text = "<link linkend=\"$ancestor_id\">$ancestors[$i]</link>";
3206         } else {
3207             $link_text = "$ancestors[$i]";
3208         }
3209         if ($level == 0) {
3210             $hierarchy .= "  $link_text\n";
3211         } else {
3212 #            $hierarchy .= ' ' x ($level * 6 - 3) . "|\n";
3213             $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
3214         }
3215         $level++;
3216     }
3217     for ($i = 0; $i <= $#children; $i++) {
3218       my $id = &CreateValidSGMLID ($children[$i]);
3219       my $link_text = "<link linkend=\"$id\">$children[$i]</link>";
3220       $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
3221     }
3222     $hierarchy .= "</synopsis>\n";
3224     return $hierarchy;
3228 #############################################################################
3229 # Function    : GetInterfaces
3230 # Description : Returns the DocBook output describing the interfaces
3231 #               implemented by a class. It uses the global %Interfaces hash.
3232 # Arguments   : $object - the GtkObject subclass.
3233 #############################################################################
3235 sub GetInterfaces {
3236     my ($object) = @_;
3237     my $text = "";
3238     my $i;
3240     # Find object in the objects array.
3241     if (exists($Interfaces{$object})) {
3242         my @ifaces = split(' ', $Interfaces{$object});
3243         $text = <<EOF;
3244 <para>
3245 $object implements
3247         for ($i = 0; $i <= $#ifaces; $i++) {
3248             my $id = &CreateValidSGMLID ($ifaces[$i]);
3249             $text .= " <link linkend=\"$id\">$ifaces[$i]</link>";
3250             if ($i < $#ifaces - 1) {
3251                 $text .= ', ';
3252             }
3253             elsif ($i < $#ifaces) {
3254                 $text .= ' and ';
3255             }
3256             else {
3257                 $text .= '.';
3258             }
3259         }
3260         $text .= <<EOF;
3261 </para>
3263     }
3265     return $text;
3268 #############################################################################
3269 # Function    : GetImplementations
3270 # Description : Returns the DocBook output describing the implementations
3271 #               of an interface. It uses the global %Interfaces hash.
3272 # Arguments   : $object - the GtkObject subclass.
3273 #############################################################################
3275 sub GetImplementations {
3276     my ($object) = @_;
3277     my @impls = ();
3278     my $text = "";
3279     my $i;
3280     foreach my $key (keys %Interfaces) {
3281         if ($Interfaces{$key} =~ /\b$object\b/) {
3282             push (@impls, $key);
3283         }
3284     }
3285     if ($#impls >= 0) {
3286         @impls = sort @impls;
3287         $text = <<EOF;
3288 <para>
3289 $object is implemented by
3291         for ($i = 0; $i <= $#impls; $i++) {
3292             my $id = &CreateValidSGMLID ($impls[$i]);
3293             $text .= " <link linkend=\"$id\">$impls[$i]</link>";
3294             if ($i < $#impls - 1) {
3295                 $text .= ', ';
3296             }
3297             elsif ($i < $#impls) {
3298                 $text .= ' and ';
3299             }
3300             else {
3301                 $text .= '.';
3302             }
3303         }
3304         $text .= <<EOF;
3305 </para>
3307     }
3308     return $text;
3312 #############################################################################
3313 # Function    : GetPrerequisites
3314 # Description : Returns the DocBook output describing the prerequisites
3315 #               of an interface. It uses the global %Prerequisites hash.
3316 # Arguments   : $iface - the interface.
3317 #############################################################################
3319 sub GetPrerequisites {
3320     my ($iface) = @_;
3321     my $text = "";
3322     my $i;
3324     if (exists($Prerequisites{$iface})) {
3325         $text = <<EOF;
3326 <para>
3327 $iface requires
3329         my @prereqs = split(' ', $Prerequisites{$iface});
3330         for ($i = 0; $i <= $#prereqs; $i++) {
3331             my $id = &CreateValidSGMLID ($prereqs[$i]);
3332             $text .= " <link linkend=\"$id\">$prereqs[$i]</link>";
3333             if ($i < $#prereqs - 1) {
3334                 $text .= ', ';
3335             }
3336             elsif ($i < $#prereqs) {
3337                 $text .= ' and ';
3338             }
3339             else {
3340                 $text .= '.';
3341             }
3342         }
3343         $text .= <<EOF;
3344 </para>
3346     }
3347     return $text;
3350 #############################################################################
3351 # Function    : GetDerived
3352 # Description : Returns the DocBook output describing the derived interfaces
3353 #               of an interface. It uses the global %Prerequisites hash.
3354 # Arguments   : $iface - the interface.
3355 #############################################################################
3357 sub GetDerived {
3358     my ($iface) = @_;
3359     my $text = "";
3360     my $i;
3362     my @derived = ();
3363     foreach my $key (keys %Prerequisites) {
3364         if ($Prerequisites{$key} =~ /\b$iface\b/) {
3365             push (@derived, $key);
3366         }
3367     }
3368     if ($#derived >= 0) {
3369         @derived = sort @derived;
3370         $text = <<EOF;
3371 <para>
3372 $iface is required by
3374         for ($i = 0; $i <= $#derived; $i++) {
3375             my $id = &CreateValidSGMLID ($derived[$i]);
3376             $text .= " <link linkend=\"$id\">$derived[$i]</link>";
3377             if ($i < $#derived - 1) {
3378                 $text .= ', ';
3379             }
3380             elsif ($i < $#derived) {
3381                 $text .= ' and ';
3382             }
3383             else {
3384                 $text .= '.';
3385             }
3386         }
3387         $text .= <<EOF;
3388 </para>
3390     }
3391     return $text;
3395 #############################################################################
3396 # Function    : GetSignals
3397 # Description : Returns the synopsis and detailed description DocBook output
3398 #                for the signal handlers of a given GtkObject subclass.
3399 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3400 #############################################################################
3402 sub GetSignals {
3403     my ($object) = @_;
3404     my $synop = "";
3405     my $desc = "";
3407     my $i;
3408     for ($i = 0; $i <= $#SignalObjects; $i++) {
3409         if ($SignalObjects[$i] eq $object) {
3410             #print "Found signal: $SignalNames[$i]\n";
3411             my $name = $SignalNames[$i];
3412             my $symbol = "${object}::${name}";
3413             my $id = &CreateValidSGMLID ("$object-$name");
3415             my $pad = ' ' x (46 - length($name));
3416             $synop .= "  &quot;<link linkend=\"$id\">$name</link>&quot;$pad ";
3418             $desc .= "<refsect2 id=\"$id\" role=\"signal\"><title>The <literal>&quot;$name&quot;</literal> signal</title>\n";
3419             $desc .= MakeIndexterms($symbol, $id);
3420             $desc .= "\n";
3421             $desc .= OutputSymbolExtraLinks($symbol);
3423             $desc .= "<programlisting>";
3425             $SignalReturns[$i] =~ m/\s*(const\s+)?(\w+)\s*(\**)/;
3426             my $type_modifier = defined($1) ? $1 : "";
3427             my $type = $2;
3428             my $pointer = $3;
3429             my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
3431             my $ret_type_len = length ($type_modifier) + length ($pointer)
3432                 + length ($type);
3433             my $ret_type_output = "$type_modifier$xref$pointer"
3434                 . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
3436             $desc  .= "${ret_type_output}user_function " . &MakeReturnField("") . " (";
3438             my $sourceparams = $SourceSymbolParams{$symbol};
3439             my @params = split ("\n", $SignalPrototypes[$i]);
3440             my $j;
3441             my $l;
3442             my $type_len = length("gpointer");
3443             my $name_len = length("user_data");
3444             # do two passes, the first one is to calculate padding
3445             for ($l = 0; $l < 2; $l++) {
3446                 for ($j = 0; $j <= $#params; $j++) {
3447                     # allow alphanumerics, '_', '[' & ']' in param names
3448                     if ($params[$j] =~ m/^\s*(\w+)\s*(\**)\s*([\w\[\]]+)\s*$/) {
3449                         $type = $1;
3450                         $pointer = $2;
3451                         if (defined($sourceparams)) {
3452                             $name = $$sourceparams[$PARAM_FIELD_COUNT * $j];
3453                         }
3454                         else {
3455                             $name = $3;
3456                         }
3457                         if (!defined($name)) {
3458                             $name = "arg$j";
3459                         }
3460                         if ($l == 0) {
3461                             if (length($type) + length($pointer) > $type_len) {
3462                                 $type_len = length($type) + length($pointer);
3463                             }
3464                             if (length($name) > $name_len) {
3465                                 $name_len = length($name);
3466                             }
3467                         }
3468                         else {
3469                             $xref = &MakeXRef ($type, &tagify($type, "type"));
3470                             $pad = ' ' x ($type_len - length($type) - length($pointer));
3471                             $desc .= "$xref$pad $pointer$name,\n";
3472                             $desc .= (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
3473                         }
3474                     } else {
3475                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
3476                              "Can't parse arg: $params[$j]\nArgs:$SignalPrototypes[$i]");
3477                     }
3478                 }
3479             }
3480             $xref = &MakeXRef ("gpointer", &tagify("gpointer", "type"));
3481             $pad = ' ' x ($type_len - length("gpointer"));
3482             $desc  .= "$xref$pad user_data)";
3484             my $flags = $SignalFlags[$i];
3485             my $flags_string = "";
3487             if (defined ($flags)) {
3488               if ($flags =~ m/f/) {
3489                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-FIRST:CAPS\"><literal>Run First</literal></link>";
3490               }
3491               elsif ($flags =~ m/l/) {
3492                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-LAST:CAPS\"><literal>Run Last</literal></link>";
3493               }
3494               elsif ($flags =~ m/c/) {
3495                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-CLEANUP:CAPS\"><literal>Cleanup</literal></link>";
3496                 $flags_string = "Cleanup";
3497               }
3498               if ($flags =~ m/r/) {
3499                 if ($flags_string) { $flags_string .= " / "; }
3500                 $flags_string = "<link linkend=\"G-SIGNAL-NO-RECURSE:CAPS\"><literal>No Recursion</literal></link>";
3501               }
3502               if ($flags =~ m/d/) {
3503                 if ($flags_string) { $flags_string .= " / "; }
3504                 $flags_string = "<link linkend=\"G-SIGNAL-DETAILED:CAPS\"><literal>Has Details</literal></link>";
3505               }
3506               if ($flags =~ m/a/) {
3507                 if ($flags_string) { $flags_string .= " / "; }
3508                 $flags_string = "<link linkend=\"G-SIGNAL-ACTION:CAPS\"><literal>Action</literal></link>";
3509               }
3510               if ($flags =~ m/h/) {
3511                 if ($flags_string) { $flags_string .= " / "; }
3512                 $flags_string = "<link linkend=\"G-SIGNAL-NO-HOOKS:CAPS\"><literal>No Hooks</literal></link>";
3513               }
3514             }
3516             if ($flags_string)
3517               {
3518                 $synop .= ": $flags_string\n";
3520                 $pad = ' ' x (5 + $name_len - length("user_data"));
3521                 $desc  .= "$pad : $flags_string</programlisting>\n";
3522               }
3523             else
3524               {
3525                 $synop .= "\n";
3526                 $desc  .= "</programlisting>\n";
3527               }
3529             $desc .= &MakeDeprecationNote($symbol);
3531             my $parameters = &OutputParamDescriptions ("SIGNAL", $symbol);
3532             my $parameters_output = 0;
3534             $AllSymbols{$symbol} = 1;
3535             if (defined ($SymbolDocs{$symbol})) {
3536                 my $symbol_docs = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
3538                 # Try to insert the parameter table at the author's desired
3539                 # position. Otherwise we need to tag it onto the end.
3540                 if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
3541                   $parameters_output = 1;
3542                 }
3543                 $desc .= $symbol_docs;
3545                 if (!IsEmptyDoc($SymbolDocs{$symbol})) {
3546                     $AllDocumentedSymbols{$symbol} = 1;
3547                 }
3548             }
3550             if ($parameters_output == 0) {
3551                 $desc .= $parameters;
3552               }
3553             $desc .= OutputSymbolTraits ($symbol);
3554             $desc .= "</refsect2>";
3555         }
3556     }
3557     return ($synop, $desc);
3561 #############################################################################
3562 # Function    : GetArgs
3563 # Description : Returns the synopsis and detailed description DocBook output
3564 #                for the Args of a given GtkObject subclass.
3565 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3566 #############################################################################
3568 sub GetArgs {
3569     my ($object) = @_;
3570     my $synop = "";
3571     my $desc = "";
3572     my $child_synop = "";
3573     my $child_desc = "";
3574     my $style_synop = "";
3575     my $style_desc = "";
3577     my $i;
3578     for ($i = 0; $i <= $#ArgObjects; $i++) {
3579         if ($ArgObjects[$i] eq $object) {
3580             #print "Found arg: $ArgNames[$i]\n";
3581             my $name = $ArgNames[$i];
3582             my $flags = $ArgFlags[$i];
3583             my $flags_string = "";
3584             my $kind = "";
3585             my $id_sep = "";
3587             if ($flags =~ m/c/) {
3588                 $kind = "child property";
3589                 $id_sep = "c-";
3590             }
3591             elsif ($flags =~ m/s/) {
3592                 $kind = "style property";
3593                 $id_sep = "s-";
3594             }
3595             else {
3596                 $kind = "property";
3597             }
3599             # Remember only one colon so we don't clash with signals.
3600             my $symbol = "${object}:${name}";
3601             # use two dashes and ev. an extra separator here for the same reason.
3602             my $id = &CreateValidSGMLID ("$object--$id_sep$name");
3604             my $type = $ArgTypes[$i];
3605             my $type_output;
3606             my $range = $ArgRanges[$i];
3607             my $range_output = CreateValidSGML ($range);
3608             my $default = $ArgDefaults[$i];
3609             my $default_output = CreateValidSGML ($default);
3611             if ($type eq "GtkString") {
3612                 $type = "char*";
3613             }
3614             if ($type eq "GtkSignal") {
3615                 $type = "GtkSignalFunc, gpointer";
3616                 $type_output = &MakeXRef ("GtkSignalFunc") . ", "
3617                     . &MakeXRef ("gpointer");
3618             } elsif ($type =~ m/^(\w+)\*$/) {
3619                 $type_output = &MakeXRef ($1, &tagify($1, "type")) . "*";
3620             } else {
3621                 $type_output = &MakeXRef ($type, &tagify($type, "type"));
3622             }
3624             if ($flags =~ m/r/) {
3625                 $flags_string = "Read";
3626             }
3627             if ($flags =~ m/w/) {
3628                 if ($flags_string) { $flags_string .= " / "; }
3629                 $flags_string .= "Write";
3630             }
3631             if ($flags =~ m/x/) {
3632                 if ($flags_string) { $flags_string .= " / "; }
3633                 $flags_string .= "Construct";
3634             }
3635             if ($flags =~ m/X/) {
3636                 if ($flags_string) { $flags_string .= " / "; }
3637                 $flags_string .= "Construct Only";
3638             }
3640             $AllSymbols{$symbol} = 1;
3641             my $blurb;
3642             if (defined($SymbolDocs{$symbol}) &&
3643                 !IsEmptyDoc($SymbolDocs{$symbol})) {
3644                 $blurb = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
3645                 #print ".. [$SymbolDocs{$symbol}][$blurb]\n";
3646                 $AllDocumentedSymbols{$symbol} = 1;
3647             }
3648             else {
3649                 if (!($ArgBlurbs[$i] eq "")) {
3650                     $AllDocumentedSymbols{$symbol} = 1;
3651                 } else {
3652                     # FIXME: print a warning?
3653                     #print ".. no description\n";
3654                 }
3655                 $blurb = "<para>" . &CreateValidSGML ($ArgBlurbs[$i]) . "</para>";
3656             }
3658             my $pad1 = " " x (24 - length ($name));
3659             my $pad2 = " " x (20 - length ($type));
3661              my $arg_synop = "  &quot;<link linkend=\"$id\">$name</link>&quot;$pad1 $type_output $pad2 : $flags_string\n";
3662             my $arg_desc = "<refsect2 id=\"$id\" role=\"property\"><title>The <literal>&quot;$name&quot;</literal> $kind</title>\n";
3663             $arg_desc .= MakeIndexterms($symbol, $id);
3664             $arg_desc .= "\n";
3665             $arg_desc .= OutputSymbolExtraLinks($symbol);
3667             $arg_desc .= "<programlisting>  &quot;$name&quot;$pad1 $type_output $pad2 : $flags_string</programlisting>\n";
3668             $arg_desc .= &MakeDeprecationNote($symbol);
3669             $arg_desc .= $blurb;
3670             if ($range ne "") {
3671                 $arg_desc .= "<para>Allowed values: $range_output</para>\n";
3672             }
3673             if ($default ne "") {
3674                 $arg_desc .= "<para>Default value: $default_output</para>\n";
3675             }
3676             $arg_desc .= OutputSymbolTraits ($symbol);
3677             $arg_desc .= "</refsect2>\n";
3679             if ($flags =~ m/c/) {
3680                 $child_synop .= $arg_synop;
3681                 $child_desc .= $arg_desc;
3682             }
3683             elsif ($flags =~ m/s/) {
3684                 $style_synop .= $arg_synop;
3685                 $style_desc .= $arg_desc;
3686             }
3687             else {
3688                 $synop .= $arg_synop;
3689                 $desc .= $arg_desc;
3690             }
3691         }
3692     }
3693     return ($synop, $child_synop, $style_synop, $desc, $child_desc, $style_desc);
3697 #############################################################################
3698 # Function    : ReadSourceDocumentation
3699 # Description : This reads in the documentation embedded in comment blocks
3700 #                in the source code (for Gnome).
3702 #                Parameter descriptions override any in the template files.
3703 #                Function descriptions are placed before any description from
3704 #                the template files.
3706 #                It recursively descends the source directory looking for .c
3707 #                files and scans them looking for specially-formatted comment
3708 #                blocks.
3710 # Arguments   : $source_dir - the directory to scan.
3711 #############m###############################################################
3713 sub ReadSourceDocumentation {
3714     my ($source_dir) = @_;
3715     my ($file, $dir, @suffix_list, $suffix);
3717     # prepend entries from @SOURCE_DIR
3718     for my $dir (@SOURCE_DIRS) {
3719         # Check if the filename is in the ignore list.
3720         if ($source_dir =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3721             @TRACE@("Skipping source directory: $source_dir");
3722             return;
3723         }
3724     }
3726     @TRACE@("Scanning source directory: $source_dir");
3728     # This array holds any subdirectories found.
3729     my (@subdirs) = ();
3731     @suffix_list = split (/,/, $SOURCE_SUFFIXES);
3733     opendir (SRCDIR, $source_dir)
3734         || die "Can't open source directory $source_dir: $!";
3736     foreach $file (readdir (SRCDIR)) {
3737       if ($file =~ /^\./) {
3738         next;
3739       } elsif (-d "$source_dir/$file") {
3740         push (@subdirs, $file);
3741       } elsif (@suffix_list) {
3742         foreach $suffix (@suffix_list) {
3743           if ($file =~ m/\.\Q${suffix}\E$/) {
3744             &ScanSourceFile ("$source_dir/$file");
3745           }
3746         }
3747       } elsif ($file =~ m/\.[ch]$/) {
3748         &ScanSourceFile ("$source_dir/$file");
3749       }
3750     }
3751     closedir (SRCDIR);
3753     # Now recursively scan the subdirectories.
3754     foreach $dir (@subdirs) {
3755         &ReadSourceDocumentation ("$source_dir/$dir");
3756     }
3760 #############################################################################
3761 # Function    : ScanSourceFile
3762 # Description : Scans one source file looking for specially-formatted comment
3763 #                blocks. Later &MergeSourceDocumentation is used to merge any
3764 #                documentation found with the documentation already read in
3765 #                from the template files.
3767 # Arguments   : $file - the file to scan.
3768 #############################################################################
3770 sub ScanSourceFile {
3771     my ($file) = @_;
3772     my $basename;
3774     # prepend entries from @SOURCE_DIR
3775     for my $dir (@SOURCE_DIRS) {
3776         # Check if the filename is in the ignore list.
3777         if ($file =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3778             @TRACE@("Skipping source file: $file");
3779             return;
3780         }
3781     }
3783     if ($file =~ m/^.*[\/\\]([^\/\\]*)$/) {
3784         $basename = $1;
3785     } else {
3786         &LogWarning ($file, 1, "Can't find basename for this filename.");
3787         $basename = $file;
3788     }
3790     # Check if the basename is in the list of files to ignore.
3791     if ($IGNORE_FILES =~ m/(\s|^)\Q${basename}\E(\s|$)/) {
3792         @TRACE@("Skipping source file: $file");
3793         return;
3794     }
3796     @TRACE@("Scanning source file: $file");
3798     open (SRCFILE, $file)
3799         || die "Can't open $file: $!";
3800     my $in_comment_block = 0;
3801     my $symbol;
3802     my $in_part = "";
3803     my ($description, $return_desc, $return_start, $return_style);
3804     my ($since_desc, $stability_desc, $deprecated_desc);
3805     my $current_param;
3806     my $ignore_broken_returns;
3807     my @params;
3808     while (<SRCFILE>) {
3809         # Look for the start of a comment block.
3810         if (!$in_comment_block) {
3811             if (m%^\s*/\*.*\*/%) {
3812                 #one-line comment - not gtkdoc
3813             } elsif (m%^\s*/\*\*\s%) {
3814                 #print "Found comment block start\n";
3816                 $in_comment_block = 1;
3818                 # Reset all the symbol data.
3819                 $symbol = "";
3820                 $in_part = "";
3821                 $description = "";
3822                 $return_desc = "";
3823                 $return_style = "";
3824                 $since_desc = "";
3825                 $deprecated_desc = "";
3826                 $stability_desc = "";
3827                 $current_param = -1;
3828                 $ignore_broken_returns = 0;
3829                 @params = ();
3830             }
3831             next;
3832         }
3834         # We're in a comment block. Check if we've found the end of it.
3835         if (m%^\s*\*+/%) {
3836             if (!$symbol) {
3837                 # maybe its not even meant to be a gtk-doc comment?
3838                 &LogWarning ($file, $., "Symbol name not found at the start of the comment block.");
3839             } else {
3840                 # Add the return value description onto the end of the params.
3841                 if ($return_desc) {
3842                     push (@params, "Returns");
3843                     push (@params, $return_desc);
3844                     if ($return_style eq 'broken') {
3845                         &LogWarning ($file, $., "Free-form return value description in $symbol. Use `Returns:' to avoid ambiguities.");
3846                     }
3847                 }
3848                 # Convert special SGML characters
3849                 $description = &ConvertSGMLChars ($symbol, $description);
3850                 my $k;
3851                 for ($k = 1; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3852                     $params[$k] = &ConvertSGMLChars ($symbol, $params[$k]);
3853                 }
3855                 # Handle Section docs
3856                 if ($symbol =~ m/SECTION:\s*(.*)/) {
3857                     my $real_symbol=$1;
3858                     my $key;
3860                     if (scalar %KnownSymbols) {
3861                         if ((! defined($KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"})) || $KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"} != 1) {
3862                             &LogWarning ($file, $., "Section $real_symbol is not defined in the $MODULE-sections.txt file.");
3863                         }
3864                     }
3866                     #print "SECTION DOCS found in source for : '$real_symbol'\n";
3867                     $ignore_broken_returns = 1;
3868                     for ($k = 0; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3869                         #print "   '".$params[$k]."'\n";
3870                         $params[$k] = "\L$params[$k]";
3871                         undef $key;
3872                         if ($params[$k] eq "short_description") {
3873                             $key = "$TMPL_DIR/$real_symbol:Short_Description";
3874                         } elsif ($params[$k] eq "see_also") {
3875                             $key = "$TMPL_DIR/$real_symbol:See_Also";
3876                         } elsif ($params[$k] eq "title") {
3877                             $key = "$TMPL_DIR/$real_symbol:Title";
3878                         } elsif ($params[$k] eq "stability") {
3879                             $key = "$TMPL_DIR/$real_symbol:Stability_Level";
3880                         } elsif ($params[$k] eq "section_id") {
3881                             $key = "$TMPL_DIR/$real_symbol:Section_Id";
3882                         } elsif ($params[$k] eq "include") {
3883                             $key = "$TMPL_DIR/$real_symbol:Include";
3884                         } elsif ($params[$k] eq "image") {
3885                             $key = "$TMPL_DIR/$real_symbol:Image";
3886                         }
3887                         if (defined($key)) {
3888                             $SourceSymbolDocs{$key}=$params[$k+1];
3889                             $SourceSymbolSourceFile{$key} = $file;
3890                             $SourceSymbolSourceLine{$key} = $.;
3891                         }
3892                     }
3893                     $SourceSymbolDocs{"$TMPL_DIR/$real_symbol:Long_Description"}=$description;
3894                     $SourceSymbolSourceFile{"$TMPL_DIR/$real_symbol:Long_Description"} = $file;
3895                     $SourceSymbolSourceLine{"$TMPL_DIR/$real_symbol:Long_Description"} = $.;
3896                     #$SourceSymbolTypes{$symbol} = "SECTION";
3897                 } else {
3898                     #print "SYMBOL DOCS found in source for : '$symbol' ",length($description), "\n";
3899                     $SourceSymbolDocs{$symbol} = $description;
3900                     $SourceSymbolParams{$symbol} = [ @params ];
3901                     # FIXME $SourceSymbolTypes{$symbol} = "STRUCT,SIGNAL,ARG,FUNCTION,MACRO";
3902                     #if (defined $DeclarationTypes{$symbol}) {
3903                     #    $SourceSymbolTypes{$symbol} = $DeclarationTypes{$symbol}
3904                     #}
3905                     $SourceSymbolSourceFile{$symbol} = $file;
3906                     $SourceSymbolSourceLine{$symbol} = $.;
3907                 }
3909                 if ($since_desc) {
3910                      ($since_desc, my @extra_lines) = split ("\n", $since_desc);
3911                      $since_desc =~ s/^\s+//;
3912                      $since_desc =~ s/\s+$//;
3913                      #print "Since($symbol) : [$since_desc]\n";
3914                      $Since{$symbol} = &ConvertSGMLChars ($symbol, $since_desc);
3915                      if(scalar @extra_lines) {
3916                          &LogWarning ($file, $., "multi-line since docs found");
3917                      }
3918                 }
3920                 if ($stability_desc) {
3921                     $stability_desc = &ParseStabilityLevel($stability_desc, $file, $., "Stability level for $symbol");
3922                     $StabilityLevel{$symbol} = &ConvertSGMLChars ($symbol, $stability_desc);
3923                 }
3925                 if ($deprecated_desc) {
3926                     if (!exists $Deprecated{$symbol}) {
3927                          # don't warn for signals and properties
3928                          #if ($symbol !~ m/::?(.*)/) {
3929                          if (defined $DeclarationTypes{$symbol}) {
3930                              &LogWarning ($file, $.,
3931                                  "$symbol is deprecated in the inline comments, but no deprecation guards were found around the declaration.".
3932                                  " (See the --deprecated-guards option for gtkdoc-scan.)");
3933                          }
3934                     }
3935                     $Deprecated{$symbol} = &ConvertSGMLChars ($symbol, $deprecated_desc);
3936                 }
3937             }
3939             $in_comment_block = 0;
3940             next;
3941         }
3943         # Get rid of ' * ' at start of every line in the comment block.
3944         s%^\s*\*\s?%%;
3945         # But make sure we don't get rid of the newline at the end.
3946         if (!$_) {
3947             $_ = "\n";
3948         }
3949         #print "DEBUG: scanning :$_";
3951         # If we haven't found the symbol name yet, look for it.
3952         if (!$symbol) {
3953             if (m%^\s*(SECTION:\s*\S+)%) {
3954                 $symbol = $1;
3955                 #print "SECTION DOCS found in source for : '$symbol'\n";
3956                 $ignore_broken_returns = 1;
3957             } elsif (m%^\s*([\w:-]*\w)\s*:?\s*(\([-a-z0-9_ ]+\)\s*)*$%) {
3958                 $symbol = $1;
3959                 #print "SYMBOL DOCS found in source for : '$symbol'\n";
3960             }
3961             next;
3962         }
3964         if ($in_part eq "description") {
3965             # Get rid of 'Description:'
3966             s%^\s*Description:%%;
3967         }
3969         if (m/^\s*(returns:|return\s+value:)/i) {
3970             if ($return_style eq 'broken') {
3971                 $description .= $return_start . $return_desc;
3972             }
3973             $return_start = $1;
3974             if ($return_style eq 'sane') {
3975                 &LogWarning ($file, $., "Multiple Returns for $symbol.");
3976             }
3977             $return_style = 'sane';
3978             $ignore_broken_returns = 1;
3979             $return_desc = $';
3980             $in_part = "return";
3981             next;
3982         } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3983             $return_start = $1;
3984             $return_style = 'broken';
3985             $return_desc = $';
3986             $in_part = "return";
3987             next;
3988         } elsif (m%^\s*since:%i) {
3989             # we're in param section and have not seen the blank line
3990             if($in_part ne "") {
3991               $since_desc = $';
3992               $in_part = "since";
3993               next;
3994             }
3995         } elsif (m%^\s*deprecated:%i) {
3996             # we're in param section and have not seen the blank line
3997             if($in_part ne "") {
3998               $deprecated_desc = $';
3999               $in_part = "deprecated";
4000               next;
4001             }
4002         } elsif (m%^\s*stability:%i) {
4003             $stability_desc = $';
4004             $in_part = "stability";
4005             next;
4006         }
4008         if ($in_part eq "description") {
4009             $description .= $_;
4010             next;
4011         } elsif ($in_part eq "return") {
4012             $return_desc .= $_;
4013             next;
4014         } elsif ($in_part eq "since") {
4015             $since_desc .= $_;
4016             next;
4017         } elsif ($in_part eq "stability") {
4018             $stability_desc .= $_;
4019             next;
4020         } elsif ($in_part eq "deprecated") {
4021             $deprecated_desc .= $_;
4022             next;
4023         }
4025         # We must be in the parameters. Check for the empty line below them.
4026         if (m%^\s*$%) {
4027             $in_part = "description";
4028             next;
4029         }
4031         # Look for a parameter name.
4032         if (m%^\s*@(\S+)\s*:\s*%) {
4033             my $param_name = $1;
4034             my $param_desc = $';
4036             #print "Found parameter: $param_name\n";
4037             # Allow varargs variations
4038             if ($param_name =~ m/^\.\.\.$/) {
4039                 $param_name = "...";
4040             }
4041             if ("\L$param_name" eq "returns") {
4042                 $return_style = 'sane';
4043                 $ignore_broken_returns = 1;
4044             }
4045             @TRACE@("Found param for symbol $symbol : '$param_name'= '$_'");
4047             push (@params, $param_name);
4048             push (@params, $param_desc);
4049             $current_param += $PARAM_FIELD_COUNT;
4050             next;
4051         }
4053         # We must be in the middle of a parameter description, so add it on
4054         # to the last element in @params.
4055         if ($current_param == -1) {
4056             &LogWarning ($file, $., "Parsing comment block file : parameter expected.");
4057         } else {
4058             $params[$#params] .= $_;
4059         }
4060     }
4061     close (SRCFILE);
4064 #############################################################################
4065 # Function    : OutputMissingDocumentation
4066 # Description : Outputs report of documentation coverage to a file
4068 # Arguments   : none
4069 #############################################################################
4071 sub OutputMissingDocumentation {
4072     my $old_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.txt";
4073     my $new_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.new";
4075     my $n_documented = 0;
4076     my $n_incomplete = 0;
4077     my $total = 0;
4078     my $symbol;
4079     my $percent;
4080     my $msg;
4081     my $buffer = "";
4082     my $buffer_deprecated = "";
4083     my $buffer_descriptions = "";
4085     open(UNDOCUMENTED, ">$new_undocumented_file")
4086       || die "Can't create $new_undocumented_file";
4088     foreach $symbol (sort (keys (%AllSymbols))) {
4089         # FIXME: should we print LogWarnings for undocumented stuff?
4090         # DEBUG
4091         #my $ssfile = &GetSymbolSourceFile($symbol);
4092         #my $ssline = &GetSymbolSourceLine($symbol);
4093         #my $location = "defined at " . (defined($ssfile)?$ssfile:"?") . ":" . (defined($ssline)?$ssline:"0") . "\n";
4094         # DEBUG
4095         if ($symbol !~ /:(Title|Long_Description|Short_Description|See_Also|Stability_Level|Include|Section_Id|Image)/) {
4096             $total++;
4097             if (exists ($AllDocumentedSymbols{$symbol})) {
4098                 $n_documented++;
4099                 if (exists ($AllIncompleteSymbols{$symbol})) {
4100                     $n_incomplete++;
4101                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4102                     #$buffer .= "\t0: ".$location;
4103                 }
4104             } elsif (exists $Deprecated{$symbol}) {
4105                 if (exists ($AllIncompleteSymbols{$symbol})) {
4106                     $n_incomplete++;
4107                     $buffer_deprecated .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4108                     #$buffer .= "\t1a: ".$location;
4109                 } else {
4110                     $buffer_deprecated .= $symbol . "\n";
4111                     #$buffer .= "\t1b: ".$location;
4112                 }
4113             } else {
4114                 if (exists ($AllIncompleteSymbols{$symbol})) {
4115                     $n_incomplete++;
4116                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4117                     #$buffer .= "\t2a: ".$location;
4118                 } else {
4119                     $buffer .= $symbol . "\n";
4120                     #$buffer .= "\t2b: ".$location;
4121                 }
4122             }
4123         } elsif ($symbol =~ /:(Long_Description|Short_Description)/) {
4124             $total++;
4125             #my $len1=(exists($SymbolDocs{$symbol}))?length($SymbolDocs{$symbol}):-1;
4126             #my $len2=(exists($AllDocumentedSymbols{$symbol}))?length($AllDocumentedSymbols{$symbol}):-1;
4127             #print "%%%% $symbol : $len1,$len2\n";
4128             if (((exists ($SymbolDocs{$symbol})) && (length ($SymbolDocs{$symbol}) > 0))
4129             || ((exists ($AllDocumentedSymbols{$symbol})) && (length ($AllDocumentedSymbols{$symbol}) > 0))) {
4130               $n_documented++;
4131             } else {
4132               # cut off the leading namespace ($TMPL_DIR)
4133               $symbol =~ m/^.*\/(.*)$/;
4134               $buffer_descriptions .= $1 . "\n";
4135             }
4136         }
4137     }
4139     $buffer .= "\n" . $buffer_deprecated . "\n" . $buffer_descriptions;
4141     if ($total == 0) {
4142       $percent = 100;
4143     } else {
4144       $percent = ($n_documented / $total) * 100.0;
4145     }
4147     printf UNDOCUMENTED "%.0f%% symbol docs coverage.\n", $percent;
4148     print UNDOCUMENTED "$n_documented symbols documented.\n";
4149     print UNDOCUMENTED "$n_incomplete symbols incomplete.\n";
4150     print UNDOCUMENTED ($total - $n_documented) . " not documented.\n\n\n";
4152     print UNDOCUMENTED $buffer;
4153     close (UNDOCUMENTED);
4155     return &UpdateFileIfChanged ($old_undocumented_file, $new_undocumented_file, 0);
4157     printf "%.0f%% symbol docs coverage", $percent;
4158     print "($n_documented symbols documented, $n_incomplete symbols incomplete, " . ($total - $n_documented) . " not documented)\n";
4159     print "See $MODULE-undocumented.txt for a list of missing docs.\nThe doc coverage percentage doesn't include intro sections.\n";
4163 #############################################################################
4164 # Function    : OutputUndeclaredSymbols
4165 # Description : Outputs symbols that are listed in the section file, but not
4166 #               declaration is found in the sources
4168 # Arguments   : none
4169 #############################################################################
4171 sub OutputUndeclaredSymbols {
4172     my $old_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.txt";
4173     my $new_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.new";
4175     open(UNDECLARED, ">$new_undeclared_file")
4176         || die "Can't create $new_undeclared_file";
4178     if (%UndeclaredSymbols) {
4179         print UNDECLARED (join("\n", sort keys %UndeclaredSymbols));
4180         print UNDECLARED "\n";
4181         print "See $MODULE-undeclared.txt for the list of undeclared symbols.\n"
4182     }
4183     close(UNDECLARED);
4185     return &UpdateFileIfChanged ($old_undeclared_file, $new_undeclared_file, 0);
4188 #############################################################################
4189 # Function    : OutputUnusedSymbols
4190 # Description : Outputs symbols that are documented in comments, but not
4191 #               declared in the sources
4193 # Arguments   : none
4194 #############################################################################
4196 sub OutputUnusedSymbols {
4197     my $num_unused = 0;
4198     my $old_unused_file = "$ROOT_DIR/$MODULE-unused.txt";
4199     my $new_unused_file = "$ROOT_DIR/$MODULE-unused.new";
4201     open (UNUSED, ">$new_unused_file")
4202         || die "Can't open $new_unused_file";
4203     my ($symbol);
4204     foreach $symbol (sort keys (%Declarations)) {
4205         if (!defined ($DeclarationOutput{$symbol})) {
4206             print (UNUSED "$symbol\n");
4207             $num_unused++;
4208         }
4209     }
4210     foreach $symbol (sort (keys (%AllUnusedSymbols))) {
4211         print (UNUSED "$symbol(" . $AllUnusedSymbols{$symbol} . ")\n");
4212         $num_unused++;
4213     }
4214     close (UNUSED);
4215     if ($num_unused != 0) {
4216         &LogWarning ($old_unused_file, 1, "$num_unused unused declarations.".
4217             "They should be added to $MODULE-sections.txt in the appropriate place.");
4218     }
4220     return &UpdateFileIfChanged ($old_unused_file, $new_unused_file, 0);
4224 #############################################################################
4225 # Function    : OutputAllSymbols
4226 # Description : Outputs list of all symbols to a file
4228 # Arguments   : none
4229 #############################################################################
4231 sub OutputAllSymbols {
4232      my $n_documented = 0;
4233      my $total = 0;
4234      my $symbol;
4235      my $percent;
4236      my $msg;
4238      open (SYMBOLS, ">$ROOT_DIR/$MODULE-symbols.txt")
4239           || die "Can't create $ROOT_DIR/$MODULE-symbols.txt: $!";
4241      foreach $symbol (sort (keys (%AllSymbols))) {
4242           print SYMBOLS $symbol . "\n";
4243      }
4245      close (SYMBOLS);
4248 #############################################################################
4249 # Function    : OutputSymbolsWithoutSince
4250 # Description : Outputs list of all symbols without a since tag to a file
4252 # Arguments   : none
4253 #############################################################################
4255 sub OutputSymbolsWithoutSince {
4256      my $n_documented = 0;
4257      my $total = 0;
4258      my $symbol;
4259      my $percent;
4260      my $msg;
4262      open (SYMBOLS, ">$ROOT_DIR/$MODULE-nosince.txt")
4263           || die "Can't create $ROOT_DIR/$MODULE-nosince.txt: $!";
4265      foreach $symbol (sort (keys (%SourceSymbolDocs))) {
4266          if (!defined $Since{$symbol}) {
4267              print SYMBOLS $symbol . "\n";
4268          }
4269      }
4271      close (SYMBOLS);
4275 #############################################################################
4276 # Function    : MergeSourceDocumentation
4277 # Description : This merges documentation read from a source file into the
4278 #                documentation read in from a template file.
4280 #                Parameter descriptions override any in the template files.
4281 #                Function descriptions are placed before any description from
4282 #                the template files.
4284 # Arguments   : none
4285 #############################################################################
4287 sub MergeSourceDocumentation {
4288     my $symbol;
4289     my @Symbols;
4291     if (scalar %SymbolDocs) {
4292         @Symbols=keys (%SymbolDocs);
4293         #print "num existing entries: ".(scalar @Symbols)."\n";
4294         #print "  ",$Symbols[0], " ",$Symbols[1],"\n";
4295     }
4296     else {
4297         # filter scanned declarations, with what we suppress from -sections.txt
4298         my %tmp = ();
4299         foreach $symbol (keys (%Declarations)) {
4300             if (defined($KnownSymbols{$symbol}) && $KnownSymbols{$symbol} == 1) {
4301                 $tmp{$symbol}=1;
4302             }
4303         }
4304         # , add the rest from -sections.txt
4305         foreach $symbol (keys (%KnownSymbols)) {
4306             if ($KnownSymbols{$symbol} == 1) {
4307                 $tmp{$symbol}=1;
4308             }
4309         }
4310         # and add whats found in the source
4311         foreach $symbol (keys (%SourceSymbolDocs)) {
4312             $tmp{$symbol}=1;
4313         }
4314         @Symbols = keys (%tmp);
4315         #print "num source entries: ".(scalar @Symbols)."\n";
4316     }
4317     foreach $symbol (@Symbols) {
4318         $AllSymbols{$symbol} = 1;
4320         my $have_tmpl_docs = 0;
4322         ## see if the symbol is documented in template
4323         my $tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4324         my $check_tmpl_doc =$tmpl_doc;
4325         # remove all xml-tags and whitespaces
4326         $check_tmpl_doc =~ s/<.*?>//g;
4327         $check_tmpl_doc =~ s/\s//g;
4328         # anything left ?
4329         if ($check_tmpl_doc ne "") {
4330             $have_tmpl_docs = 1;
4331             #print "## [$check_tmpl_doc]\n";
4332         } else {
4333             # if the docs have just an empty para, don't merge that.
4334             $check_tmpl_doc = $tmpl_doc;
4335             $check_tmpl_doc =~ s/(\s|\n)//msg;
4336             if ($check_tmpl_doc eq "<para></para>") {
4337                $tmpl_doc = "";
4338             }
4339         }
4341         if (exists ($SourceSymbolDocs{$symbol})) {
4342             my $type = $DeclarationTypes {$symbol};
4344             #print "merging [$symbol] from source\n";
4346             my $item = "Parameter";
4347             if (defined ($type)) {
4348                 if ($type eq 'STRUCT') {
4349                     $item = "Field";
4350                 } elsif ($type eq 'ENUM') {
4351                     $item = "Value";
4352                 } elsif ($type eq 'UNION') {
4353                     $item = "Field";
4354                 }
4355             } else {
4356                 $type="SIGNAL";
4357             }
4359             my $src_doc = $SourceSymbolDocs{$symbol};
4360             # remove leading and training whitespaces
4361             $src_doc =~ s/^\s+//;
4362             $src_doc =~ s/\s+$//;
4364             # Don't output warnings for overridden titles as titles are
4365             # automatically generated in the -sections.txt file, and thus they
4366             # are often overridden.
4367             if ($have_tmpl_docs && $symbol !~ m/:Title$/) {
4368                 # check if content is different
4369                 if ($tmpl_doc ne $src_doc) {
4370                     #print "[$tmpl_doc] [$src_doc]\n";
4371                     &LogWarning ($SourceSymbolSourceFile{$symbol}, $SourceSymbolSourceLine{$symbol},
4372                         "Documentation in template ".$SymbolSourceFile{$symbol}.":".$SymbolSourceLine{$symbol}." for $symbol being overridden by inline comments.");
4373                 }
4374             }
4376             if ($src_doc ne "") {
4377                  $AllDocumentedSymbols{$symbol} = 1;
4378             }
4380             # Convert <!--PARAMETERS--> with any blank lines around it to
4381             # a </para> followed by <!--PARAMETERS--> followed by <para>.
4382             $src_doc =~ s%\n+\s*<!--PARAMETERS-->\s*\n+%\n</para>\n<!--PARAMETERS-->\n<para>\n%g;
4384             # Do not add <para> to nothing, it breaks missing docs checks.
4385             my $src_doc_para = "";
4386             if ($src_doc ne "") {
4387                 # Expand markdown (and do paragraphs)
4388                 $src_doc_para = &ConvertMarkDown ($src_doc, $symbol);
4389                 ## fixup xml markup
4390                 # FIXME: this is questionable, as we can't make assumtions on the content really
4391                 #$src_doc_para =~ s%^<para>\n(<refsect[1-9])%$1%gms;
4392                 #$src_doc_para =~ s%^<para>\n<para>%<para>%gms;
4393                 #$src_doc_para =~ s%(</refsect[1-9]>)\n</para>$%$1%gms;
4394                 #print "$symbol : [$src_doc][$src_doc_para]\n";
4395             }
4397             if ($symbol =~ m/$TMPL_DIR\/.+:Long_Description/) {
4398                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4399             } elsif ($symbol =~ m/$TMPL_DIR\/.+:.+/) {
4400                 # For the title/summary/see also section docs we don't want to
4401                 # add any <para> tags.
4402                 $SymbolDocs{$symbol} = "$src_doc"
4403             } else {
4404                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4405             }
4407             # merge parameters
4408             if ($symbol =~ m/.*::.*/) {
4409                 # For signals we prefer the param names from the source docs,
4410                 # since the ones from the templates are likely to contain the
4411                 # artificial argn names which are generated by gtkdoc-scangobj.
4412                 $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4413                 # FIXME: we need to check for empty docs here as well!
4414             } else {
4415                 # The templates contain the definitive parameter names and order,
4416                 # so we will not change that. We only override the actual text.
4417                 my $tmpl_params = $SymbolParams{$symbol};
4418                 if (!defined ($tmpl_params)) {
4419                     #print "No merge needed for $symbol\n";
4420                     $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4421                     #  FIXME: we still like to get the number of params and merge
4422                     #  1) we would noticed that params have been removed/renamed
4423                     #  2) we would catch undocumented params
4424                     #  params are not (yet) exported in -decl.txt so that we
4425                     #  could easily grab them :/
4426                 } else {
4427                     my $params = $SourceSymbolParams{$symbol};
4428                     my $j;
4429                     #print "Merge needed for $symbol, tmpl_params: ",$#$tmpl_params,", source_params: ",$#$params," \n";
4430                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4431                         my $tmpl_param_name = $$tmpl_params[$j];
4433                         # Try to find the param in the source comment documentation.
4434                         my $found = 0;
4435                         my $k;
4436                         #print "  try merge param $tmpl_param_name\n";
4437                         for ($k = 0; $k <= $#$params; $k += $PARAM_FIELD_COUNT) {
4438                             my $param_name = $$params[$k];
4439                             my $param_desc = $$params[$k + 1];
4441                             #print "    test param  $param_name\n";
4442                             # We accept changes in case, since the Gnome source
4443                             # docs contain a lot of these.
4444                             if ("\L$param_name" eq "\L$tmpl_param_name") {
4445                                 $found = 1;
4447                                 # Override the description.
4448                                 $$tmpl_params[$j + 1] = $param_desc;
4450                                 # Set the name to "" to mark it as used.
4451                                 $$params[$k] = "";
4452                                 last;
4453                             }
4454                         }
4456                         # If it looks like the parameters are there, but not
4457                         # in the right place, try to explain a bit better.
4458                         if ((!$found) && ($src_doc =~ m/\@$tmpl_param_name:/)) {
4459                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4460                                 "Parameters for $symbol must start on the line immediately after the function or macro name.");
4461                         }
4462                     }
4464                     # Now we output a warning if parameters have been described which
4465                     # do not exist.
4466                     for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
4467                         my $param_name = $$params[$j];
4468                         if ($param_name) {
4469                             # the template builder cannot detect if a macro returns
4470                             # a result or not
4471                             if(($type eq "MACRO") && ($param_name eq "Returns")) {
4472                                 # FIXME: do we need to add it then to tmpl_params[] ?
4473                                 my $num=$#$tmpl_params;
4474                                 #print "  adding Returns: to macro docs for $symbol.\n";
4475                                 $$tmpl_params[$num+1]="Returns";
4476                                 $$tmpl_params[$num+2]=$$params[$j+1];
4477                                 next;
4478                             }
4479                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4480                                 "$item described in source code comment block but does not exist. $type: $symbol $item: $param_name.");
4481                         }
4482                     }
4483                 }
4484             }
4485         } else {
4486             if ($have_tmpl_docs) {
4487                 $AllDocumentedSymbols{$symbol} = 1;
4488                 #print "merging [$symbol] from template\n";
4489             }
4490             else {
4491                 #print "[$symbol] undocumented\n";
4492             }
4493         }
4495         # if this symbol is documented, check if docs are complete
4496         $check_tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4497         # remove all xml-tags and whitespaces
4498         $check_tmpl_doc =~ s/<.*?>//g;
4499         $check_tmpl_doc =~ s/\s//g;
4500         if ($check_tmpl_doc ne "") {
4501             my $tmpl_params = $SymbolParams{$symbol};
4502             if (defined ($tmpl_params)) {
4503                 my $type = $DeclarationTypes {$symbol};
4505                 my $item = "Parameter";
4506                 if (defined ($type)) {
4507                     if ($type eq 'STRUCT') {
4508                         $item = "Field";
4509                     } elsif ($type eq 'ENUM') {
4510                         $item = "Value";
4511                     } elsif ($type eq 'UNION') {
4512                         $item = "Field";
4513                     }
4514                 } else {
4515                     $type="SIGNAL";
4516                 }
4518                 #print "Check param docs for $symbol, tmpl_params: ",$#$tmpl_params," entries, type=$type\n";
4520                 if ($#$tmpl_params > 0) {
4521                     my $j;
4522                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4523                         # Output a warning if the parameter is empty and
4524                         # remember for stats.
4525                         my $tmpl_param_name = $$tmpl_params[$j];
4526                         my $tmpl_param_desc = $$tmpl_params[$j + 1];
4527                         if ($tmpl_param_name ne "void" && $tmpl_param_desc !~ m/\S/) {
4528                             if (exists ($AllIncompleteSymbols{$symbol})) {
4529                                 $AllIncompleteSymbols{$symbol}.=", ".$tmpl_param_name;
4530                             } else {
4531                                 $AllIncompleteSymbols{$symbol}=$tmpl_param_name;
4532                             }
4533                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4534                                 "$item description for $symbol"."::"."$tmpl_param_name is missing in source code comment block.");
4535                         }
4536                     }
4537                 }
4538                 else {
4539                     if ($#$tmpl_params == 0) {
4540                         $AllIncompleteSymbols{$symbol}="<items>";
4541                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4542                             "$item descriptions for $symbol are missing in source code comment block.");
4543                     }
4544                     # $#$tmpl_params==-1 means we don't know about parameters
4545                     # this unfortunately does not tell if there should be some
4546                 }
4547             }
4548         }
4549    }
4550    #print "num doc entries: ".(scalar %SymbolDocs)."\n";
4553 #############################################################################
4554 # Function    : IsEmptyDoc
4555 # Description : Check if a doc-string is empty. Its also regarded as empty if
4556 #               it only consist of whitespace or e.g. FIXME.
4557 # Arguments   : the doc-string
4558 #############################################################################
4559 sub IsEmptyDoc {
4560     my ($doc) = @_;
4562     if ($doc =~ /^\s*$/) {
4563         return 1;
4564     }
4566     if ($doc =~ /^\s*<para>\s*(FIXME)?\s*<\/para>\s*$/) {
4567         return 1;
4568     }
4570     return 0;
4573 #############################################################################
4574 # Function    : ConvertMarkDown
4575 # Description : Converts mark down syntax to the respective docbook.
4576 #               http://de.wikipedia.org/wiki/Markdown
4577 #               Inspired by the design of ParseDown
4578 #               http://parsedown.org/
4579 #               Copyright (c) 2013 Emanuil Rusev, erusev.com
4580 # Arguments   : the doc-string, the symbol name
4581 #############################################################################
4583 sub ConvertMarkDown {
4584     my ($text, $symbol) = @_;
4586     $text = &MarkDownParse ($text);
4588     return $text
4591 # SUPPORTED MARKDOWN
4592 # ==================
4594 # Atx-style Headers
4595 # -----------------
4597 # # Header 1
4599 # ## Header 2 ##
4601 # Setext-style Headers
4602 # --------------------
4604 # Header 1
4605 # ========
4607 # Header 2
4608 # --------
4610 # Ordered (unnested) Lists
4611 # ------------------------
4613 # 1. item 1
4615 # 1. item 2 with loooong
4616 #    description
4618 # 3. item 3
4620 # Note: we require a blank line above the list items
4623 # TODO(ensonic): it would be nice to add id parameters to the refsect2 elements
4625 sub MarkDownParseBlocks {
4626   my ($linesref, $context) = @_;
4627   my $line;
4628   my @md_blocks = ();
4629   my $md_block = { type => "" };
4631  OUTER: foreach $line (@$linesref) {
4632     my $first_char = substr ($line, 0, 1);
4633     my $deindented_line = $line;
4634     $deindented_line =~ s/^\s+//;
4636     if ($md_block->{"type"} eq "heading") {
4637       # a heading is ended by any level less than or equal
4638       if ($md_block->{"level"} == 1) {
4639         if ($line =~ /^={4,}[ \t]*$/) {
4640           my $text = pop $md_block->{"lines"};
4641           $md_block->{"interrupted"} = 0;
4642           push @md_blocks, $md_block;
4644           $md_block = { type => "heading",
4645                         text => $text,
4646                         lines => [],
4647                         level => 1 };
4648           next OUTER;
4649         } elsif ($line =~ /^[#][ \t]+(.+?)[ \t]*[#]*\s*$/) {
4650           $md_block->{"interrupted"} = 0;
4651           push @md_blocks, $md_block;
4653           $md_block = { type => "heading",
4654                         text => $1,
4655                         lines => [],
4656                         level => 1 };
4657           next OUTER;
4658         } else {
4659           # push lines into the block until the end is reached
4660           push $md_block->{"lines"}, $line;
4661           next OUTER;
4662         }
4663       } else {
4664         if ($line =~ /^[=]{4,}[ \t]*$/) {
4665           my $text = pop $md_block->{"lines"};
4666           $md_block->{"interrupted"} = 0;
4667           push @md_blocks, $md_block;
4669           $md_block = { type => "heading",
4670                         text => $text,
4671                         lines => [],
4672                         level => 1 };
4673           next OUTER;
4674         } elsif ($line =~ /^[-]{4,}[ \t]*$/) {
4675           my $text = pop $md_block->{"lines"};
4676           $md_block->{"interrupted"} = 0;
4677           push @md_blocks, $md_block;
4679           $md_block = { type => "heading",
4680                         text => $text,
4681                         lines => [],
4682                         level => 2 };
4683           next OUTER;
4684         } elsif ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*\s*$/) {
4685           $md_block->{"interrupted"} = 0;
4686           push @md_blocks, $md_block;
4688           $md_block = { type => "heading",
4689                         text => $2,
4690                         lines => [],
4691                         level => length($1) };
4692           next OUTER;
4693         } else {
4694           # push lines into the block until the end is reached
4695           push $md_block->{"lines"}, $line;
4696           next OUTER;
4697         }
4698       }
4699     } elsif ($md_block->{"type"} eq "code") {
4700       push $md_block->{"lines"}, $line;
4701       if ($line =~ /^[ \t]*\]\|/) {
4702         push @md_blocks, $md_block;
4703         $md_block = { type => "paragraph",
4704                       text => "",
4705                       lines => [] };
4706       }
4707       next OUTER;
4708     }
4710     if ($deindented_line eq "") {
4711       $md_block->{"interrupted"} = 1;
4712       next;
4713     }
4715     if ($md_block->{"type"} eq "li") {
4716       if ($line =~ /^([ ]{0,3})(\d+[.]|[*+-])[ ](.*)/) {
4717         my $indentation = $1;
4718         if ($md_block->{"indentation"} ne $indentation) {
4719           push $md_block->{"lines"}, $line;
4720         } else {
4721           my $lines = $3;
4722           my $ordered = $md_block->{"ordered"};
4723           $lines =~ s/^[ ]{0,4}//;
4724           $md_block->{"last"} = 0;
4725           push @md_blocks, $md_block;
4726           $md_block = { type => "li",
4727                         ordered => $ordered,
4728                         indentation => $indentation,
4729                         first => 0,
4730                         last => 1,
4731                         lines => [ $lines ] };
4732         }
4733         next OUTER;
4734       }
4736       if ($md_block->{"interrupted"}) {
4737         if ($first_char eq " ") {
4738           push $md_block->{"lines"}, "";
4739           $line =~ s/^[ ]{0,4}//;
4740           push $md_block->{"lines"}, $line;
4741           $md_block->{"interrupted"} = 0;
4742           next OUTER;
4743         }
4744       } else {
4745         $line =~ s/^[ ]{0,4}//;
4746         push $md_block->{"lines"}, $line;
4747         next OUTER;
4748       }
4749     }
4751     # indentation sensitive types
4753     if ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*\s*$/) {
4754       # atx heading (#)
4755       push @md_blocks, $md_block;
4757       $md_block = { type => "heading",
4758                     text => $2,
4759                     lines => [],
4760                     level => length($1) };
4762       next OUTER;
4763     } elsif ($line =~ /^={4,}[ \t]*$/) {
4764       # setext heading (====)
4766       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4767         push @md_blocks, $md_block;
4768         $md_block->{"type"} = "heading";
4769         $md_block->{"lines"} = [];
4770         $md_block->{"level"} = 1;
4771       }
4773       next OUTER;
4774     } elsif ($line =~ /^-{4,}[ \t]*$/) {
4775       # setext heading (-----)
4777       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4778         push @md_blocks, $md_block;
4779         $md_block->{"type"} = "heading";
4780         $md_block->{"lines"} = [];
4781         $md_block->{"level"} = 2;
4782       }
4784       next OUTER;
4785     } elsif ($line =~ /^[ \t]*\|\[/) {
4786       # code
4787       $md_block->{"interrupted"} = 1;
4788       push @md_blocks, $md_block;
4790       $md_block = { type => "code",
4791                     lines => [ $line ] };
4792       next OUTER;
4793     }
4795     # indentation insensitive types
4797     if ($line =~ /^([ ]*)[*+-][ ](.*)/) {
4798       # li
4799       push @md_blocks, $md_block;
4800       my $lines = $2;
4801       my $indentation = $1;
4802       $lines =~ s/^[ ]{0,4}//;
4803       $md_block = { type => "li",
4804                     ordered => 0,
4805                     indentation => $indentation,
4806                     first => 1,
4807                     last => 1,
4808                     lines => [ $lines ] };
4809       next OUTER;
4810     }
4812     # list item
4814     if ($line =~ /^([ ]{0,4})\d+[.][ ]+(.*)/) {
4815       push @md_blocks, $md_block;
4816       my $lines = $2;
4817       my $indentation = $1;
4818       $lines =~ s/^[ ]{0,4}//;
4820       $md_block = { type => "li",
4821                     ordered => 1,
4822                     indentation => $indentation,
4823                     first => 1,
4824                     last => 1,
4825                     lines => [ $lines ] };
4827       next;
4828     }
4830     # paragraph
4831     if ($md_block->{"type"} eq "paragraph") {
4832       if ($md_block->{"interrupted"}) {
4833         push @md_blocks, $md_block;
4834         $md_block = { type => "paragraph",
4835                       interrupted => 0,
4836                       text => $line };
4837       } else {
4838         $md_block->{"text"} .= "\n" . $line;
4839       }
4840     } else {
4841       push @md_blocks, $md_block;
4842       $md_block = { type => "paragraph",
4843                     text => $line };
4844     }
4845   }
4847   push @md_blocks, $md_block;
4849   shift @md_blocks;
4851   return @md_blocks;
4854 sub MarkDownParseSpanElements {
4855   my ($text) = @_;
4857   return $text;
4860 sub MarkDownOutputDocBook {
4861   my ($blocksref, $context) = @_;
4862   my $output = "";
4863   my $block;
4864   my @blocks = @$blocksref;
4866   foreach $block (@blocks) {
4867     my $text;
4868     my $title;
4870     if ($block->{"type"} eq "paragraph") {
4871       $text = &MarkDownParseSpanElements ($block->{"text"});
4873       if ($context eq "li" && $output eq "") {
4874         if ($block->{"interrupted"}) {
4875           $output .= "\n"."<para>".$text."</para>"."\n";
4876         } else {
4877           $output .= $text;
4878           if ($#blocks > 0) {
4879             $output .= "\n";
4880           }
4881         }
4882       } else {
4883         $output .= "<para>".$text."</para>"."\n";
4884       }
4886     } elsif ($block->{"type"} eq "heading") {
4887       my $tag;
4889       $title = &MarkDownParseSpanElements ($block->{"text"});
4890       if ($block->{"level"} == 1) {
4891         $tag = "refsect2";
4892       } else {
4893         $tag = "refsect3";
4894       }
4896       $text = &MarkDownParseLines ($block->{"lines"}, "heading");
4897       $output .= "<".$tag."><title>".$title."</title>".$text."</".$tag.">\n";
4899     } elsif ($block->{"type"} eq "li") {
4900       my $tag = "itemizedlist";
4902       if ($block->{"first"}) {
4903         if ($block->{"ordered"}) {
4904           $tag = "orderedlist";
4905         }
4906         $output .= "<".$tag.">\n";
4907       }
4909       if ($block->{"interrupted"}) {
4910         push $block->{"lines"}, "";
4911       }
4913       $text = &MarkDownParseLines ($block->{"lines"}, "li");
4914       $output .= "<listitem>".$text."</listitem>\n";
4915       if ($block->{"last"}) {
4916         if ($block->{"ordered"}) {
4917           $tag = "orderedlist";
4918         }
4919         $output .= "</".$tag.">\n";
4920       }
4921     } elsif ($block->{"type"} eq "code") {
4922       foreach (@{$block->{"lines"}}) {
4923         $output .= $_ . "\n";
4924       }
4925     } else {
4926       $output .= $block->{"text"}."\n";
4927     }
4928   }
4930   return $output;
4933 sub MarkDownParseLines {
4934   my ($linesref, $context) = @_;
4935   my $output;
4936   my @lines = @$linesref;
4937   my @blocks;
4939   @blocks = &MarkDownParseBlocks (\@lines, $context);
4940   $output = &MarkDownOutputDocBook (\@blocks, $context);
4942   return $output;
4945 sub MarkDownParse {
4946   my ($text) = @_;
4947   my @lines;
4949   # take out some variability in line endings
4950   $text =~ s%\r\n%\n%g;
4951   $text =~ s%\r%\n%g;
4953   # split lines
4954   @lines = split("\n", $text);
4955   $text = MarkDownParseLines(\@lines, "");
4957   return $text;
4960 sub ConvertMarkDownCallback {
4961   my ($text, $symbol, $tag) = @_;
4963   # If we're not in CDATA or a <programlisting> we convert blank lines so
4964   # they start a new <para>.
4965   if ($tag eq "") {
4966     $text = &MarkDownParse ($text);
4967   }
4969   return $text;
4973 #############################################################################
4974 # LIBRARY FUNCTIONS -        These functions are used in both gtkdoc-mkdb and
4975 #                        gtkdoc-mktmpl and should eventually be moved to a
4976 #                        separate library.
4977 #############################################################################
4979 #############################################################################
4980 # Function    : ReadDeclarationsFile
4981 # Description : This reads in a file containing the function/macro/enum etc.
4982 #                declarations.
4984 #                Note that in some cases there are several declarations with
4985 #                the same name, e.g. for conditional macros. In this case we
4986 #                set a flag in the %DeclarationConditional hash so the
4987 #                declaration is not shown in the docs.
4989 #                If a macro and a function have the same name, e.g. for
4990 #                gtk_object_ref, the function declaration takes precedence.
4992 #                Some opaque structs are just declared with 'typedef struct
4993 #                _name name;' in which case the declaration may be empty.
4994 #                The structure may have been found later in the header, so
4995 #                that overrides the empty declaration.
4997 # Arguments   : $file - the declarations file to read
4998 #                $override - if declarations in this file should override
4999 #                        any current declaration.
5000 #############################################################################
5002 sub ReadDeclarationsFile {
5003     my ($file, $override) = @_;
5005     if ($override == 0) {
5006         %Declarations = ();
5007         %DeclarationTypes = ();
5008         %DeclarationConditional = ();
5009         %DeclarationOutput = ();
5010     }
5012     open (INPUT, $file)
5013         || die "Can't open $file: $!";
5014     my $declaration_type = "";
5015     my $declaration_name;
5016     my $declaration;
5017     my $is_deprecated = 0;
5018     while (<INPUT>) {
5019         if (!$declaration_type) {
5020             if (m/^<([^>]+)>/) {
5021                 $declaration_type = $1;
5022                 $declaration_name = "";
5023                 #print "Found declaration: $declaration_type\n";
5024                 $declaration = "";
5025             }
5026         } else {
5027             if (m%^<NAME>(.*)</NAME>%) {
5028                 $declaration_name = $1;
5029             } elsif (m%^<DEPRECATED/>%) {
5030                 $is_deprecated = 1;
5031             } elsif (m%^</$declaration_type>%) {
5032                 #print "Found end of declaration: $declaration_name\n";
5033                 # Check that the declaration has a name
5034                 if ($declaration_name eq "") {
5035                     print "ERROR: $declaration_type has no name $file:$.\n";
5036                 }
5038                 # If the declaration is an empty typedef struct _XXX XXX
5039                 # set the flag to indicate the struct has a typedef.
5040                 if ($declaration_type eq 'STRUCT'
5041                     && $declaration =~ m/^\s*$/) {
5042                     #print "Struct has typedef: $declaration_name\n";
5043                     $StructHasTypedef{$declaration_name} = 1;
5044                 }
5046                 # Check if the symbol is already defined.
5047                 if (defined ($Declarations{$declaration_name})
5048                     && $override == 0) {
5049                     # Function declarations take precedence.
5050                     if ($DeclarationTypes{$declaration_name} eq 'FUNCTION') {
5051                         # Ignore it.
5052                     } elsif ($declaration_type eq 'FUNCTION') {
5053                         if ($is_deprecated) {
5054                             $Deprecated{$declaration_name} = "";
5055                         }
5056                         $Declarations{$declaration_name} = $declaration;
5057                         $DeclarationTypes{$declaration_name} = $declaration_type;
5058                     } elsif ($DeclarationTypes{$declaration_name}
5059                               eq $declaration_type) {
5060                         # If the existing declaration is empty, or is just a
5061                         # forward declaration of a struct, override it.
5062                         if ($declaration_type eq 'STRUCT') {
5063                             if ($Declarations{$declaration_name} =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5064                                 if ($is_deprecated) {
5065                                     $Deprecated{$declaration_name} = "";
5066                                 }
5067                                 $Declarations{$declaration_name} = $declaration;
5068                             } elsif ($declaration =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5069                                 # Ignore an empty or forward declaration.
5070                             } else {
5071                                 &LogWarning ($file, $., "Structure $declaration_name has multiple definitions.");
5072                             }
5073                         } else {
5074                             # set flag in %DeclarationConditional hash for
5075                             # multiply defined macros/typedefs.
5076                             $DeclarationConditional{$declaration_name} = 1;
5077                         }
5078                     } else {
5079                         &LogWarning ($file, $., "$declaration_name has multiple definitions.");
5080                     }
5081                 } else {
5082                     if ($is_deprecated) {
5083                         $Deprecated{$declaration_name} = "";
5084                     }
5085                     $Declarations{$declaration_name} = $declaration;
5086                     $DeclarationTypes{$declaration_name} = $declaration_type;
5087                 }
5089                 $declaration_type = "";
5090                 $is_deprecated = 0;
5091             } else {
5092                 $declaration .= $_;
5093             }
5094         }
5095     }
5096     close (INPUT);
5100 #############################################################################
5101 # Function    : ReadSignalsFile
5102 # Description : This reads in an existing file which contains information on
5103 #                all GTK signals. It creates the arrays @SignalNames and
5104 #                @SignalPrototypes containing info on the signals. The first
5105 #                line of the SignalPrototype is the return type of the signal
5106 #                handler. The remaining lines are the parameters passed to it.
5107 #                The last parameter, "gpointer user_data" is always the same
5108 #                so is not included.
5109 # Arguments   : $file - the file containing the signal handler prototype
5110 #                        information.
5111 #############################################################################
5113 sub ReadSignalsFile {
5114     my ($file) = @_;
5116     my $in_signal = 0;
5117     my $signal_object;
5118     my $signal_name;
5119     my $signal_returns;
5120     my $signal_flags;
5121     my $signal_prototype;
5123     # Reset the signal info.
5124     @SignalObjects = ();
5125     @SignalNames = ();
5126     @SignalReturns = ();
5127     @SignalFlags = ();
5128     @SignalPrototypes = ();
5130     if (! -f $file) {
5131         return;
5132     }
5133     if (!open (INPUT, $file)) {
5134         warn "Can't open $file - skipping signals\n";
5135         return;
5136     }
5137     while (<INPUT>) {
5138         if (!$in_signal) {
5139             if (m/^<SIGNAL>/) {
5140                 $in_signal = 1;
5141                 $signal_object = "";
5142                 $signal_name = "";
5143                 $signal_returns = "";
5144                 $signal_prototype = "";
5145             }
5146         } else {
5147             if (m/^<NAME>(.*)<\/NAME>/) {
5148                 $signal_name = $1;
5149                 if ($signal_name =~ m/^(.*)::(.*)$/) {
5150                     $signal_object = $1;
5151                     ($signal_name = $2) =~ s/_/-/g;
5152                     #print "Found signal: $signal_name\n";
5153                 } else {
5154                     &LogWarning ($file, $., "Invalid signal name: $signal_name.");
5155                 }
5156             } elsif (m/^<RETURNS>(.*)<\/RETURNS>/) {
5157                 $signal_returns = $1;
5158             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5159                 $signal_flags = $1;
5160             } elsif (m%^</SIGNAL>%) {
5161                 #print "Found end of signal: ${signal_object}::${signal_name}\nReturns: ${signal_returns}\n${signal_prototype}";
5162                 push (@SignalObjects, $signal_object);
5163                 push (@SignalNames, $signal_name);
5164                 push (@SignalReturns, $signal_returns);
5165                 push (@SignalFlags, $signal_flags);
5166                 push (@SignalPrototypes, $signal_prototype);
5167                 $in_signal = 0;
5168             } else {
5169                 $signal_prototype .= $_;
5170             }
5171         }
5172     }
5173     close (INPUT);
5177 #############################################################################
5178 # Function    : ReadTemplateFile
5179 # Description : This reads in the manually-edited documentation file
5180 #               corresponding to the file currently being created, so we can
5181 #               insert the documentation at the appropriate places.
5182 #               It outputs %SymbolTypes, %SymbolDocs and %SymbolParams, which
5183 #               is a hash of arrays.
5184 #               NOTE: This function is duplicated in gtkdoc-mktmpl (but
5185 #               slightly different).
5186 # Arguments   : $docsfile - the template file to read in.
5187 #               $skip_unused_params - 1 if the unused parameters should be
5188 #                 skipped.
5189 #############################################################################
5191 sub ReadTemplateFile {
5192     my ($docsfile, $skip_unused_params) = @_;
5194     my $template = "$docsfile.sgml";
5195     if (! -f $template) {
5196         #print "File doesn't exist: $template\n";
5197         return 0;
5198     }
5200     # start with empty hashes, we merge the source comment for each file
5201     # afterwards
5202     %SymbolDocs = ();
5203     %SymbolTypes = ();
5204     %SymbolParams = ();
5206     my $current_type = "";        # Type of symbol being read.
5207     my $current_symbol = "";        # Name of symbol being read.
5208     my $symbol_doc = "";                # Description of symbol being read.
5209     my @params;                        # Parameter names and descriptions of current
5210                                 #   function/macro/function typedef.
5211     my $current_param = -1;        # Index of parameter currently being read.
5212                                 #   Note that the param array contains pairs
5213                                 #   of param name & description.
5214     my $in_unused_params = 0;        # True if we are reading in the unused params.
5215     my $in_deprecated = 0;
5216     my $in_since = 0;
5217     my $in_stability = 0;
5219     open (DOCS, "$template")
5220         || die "Can't open $template: $!";
5222     @TRACE@("reading template $template");
5224     while (<DOCS>) {
5225         if (m/^<!-- ##### ([A-Z_]+) (\S+) ##### -->/) {
5226             my $type = $1;
5227             my $symbol = $2;
5228             if ($symbol eq "Title"
5229                 || $symbol eq "Short_Description"
5230                 || $symbol eq "Long_Description"
5231                 || $symbol eq "See_Also"
5232                 || $symbol eq "Stability_Level"
5233                 || $symbol eq "Include"
5234                 || $symbol eq "Image") {
5236                 $symbol = $docsfile . ":" . $symbol;
5237             }
5239             #print "Found symbol: $symbol\n";
5240             # Remember file and line for the symbol
5241             $SymbolSourceFile{$symbol} = $template;
5242             $SymbolSourceLine{$symbol} = $.;
5244             # Store previous symbol, but remove any trailing blank lines.
5245             if ($current_symbol ne "") {
5246                 $symbol_doc =~ s/\s+$//;
5247                 $SymbolTypes{$current_symbol} = $current_type;
5248                 $SymbolDocs{$current_symbol} = $symbol_doc;
5250                 # Check that the stability level is valid.
5251                 if ($StabilityLevel{$current_symbol}) {
5252                     $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5253                 }
5255                 if ($current_param >= 0) {
5256                     $SymbolParams{$current_symbol} = [ @params ];
5257                 } else {
5258                     # Delete any existing params in case we are overriding a
5259                     # previously read template.
5260                     delete $SymbolParams{$current_symbol};
5261                 }
5262             }
5263             $current_type = $type;
5264             $current_symbol = $symbol;
5265             $current_param = -1;
5266             $in_unused_params = 0;
5267             $in_deprecated = 0;
5268             $in_since = 0;
5269             $in_stability = 0;
5270             $symbol_doc = "";
5271             @params = ();
5273         } elsif (m/^<!-- # Unused Parameters # -->/) {
5274             #print "DEBUG: Found unused parameters\n";
5275             $in_unused_params = 1;
5276             next;
5278         } elsif ($in_unused_params && $skip_unused_params) {
5279             # When outputting the DocBook we skip unused parameters.
5280             #print "DEBUG: Skipping unused param: $_";
5281             next;
5283         } else {
5284             # Check if param found. Need to handle "..." and "format...".
5285             if (s/^\@([\w\.]+):\040?//) {
5286                 my $param_name = $1;
5287                 my $param_desc = $_;
5288                 # Allow variations of 'Returns'
5289                 if ($param_name =~ m/^[Rr]eturns?$/) {
5290                     $param_name = "Returns";
5291                 }
5292                 # Allow varargs variations
5293                 if ($param_name =~ m/^.*\.\.\.$/) {
5294                     $param_name = "...";
5295                 }
5297                 # strip trailing whitespaces and blank lines
5298                 s/\s+\n$/\n/m;
5299                 s/\n+$/\n/sm;
5300                 @TRACE@("Found param for symbol $current_symbol : '$param_name'= '$_'");
5302                 if ($param_name eq "Deprecated") {
5303                     $in_deprecated = 1;
5304                     $Deprecated{$current_symbol} = $_;
5305                 } elsif ($param_name eq "Since") {
5306                     $in_since = 1;
5307                     chomp;
5308                     $Since{$current_symbol} = $_;
5309                 } elsif ($param_name eq "Stability") {
5310                     $in_stability = 1;
5311                     $StabilityLevel{$current_symbol} = $_;
5312                 } else {
5313                     push (@params, $param_name);
5314                     push (@params, $param_desc);
5315                     $current_param += $PARAM_FIELD_COUNT;
5316                 }
5317             } else {
5318                 # strip trailing whitespaces and blank lines
5319                 s/\s+\n$/\n/m;
5320                 s/\n+$/\n/sm;
5322                 if (!m/^\s+$/) {
5323                     if ($in_deprecated) {
5324                         $Deprecated{$current_symbol} .= $_;
5325                     } elsif ($in_since) {
5326                         &LogWarning ($template, $., "multi-line since docs found");
5327                         #$Since{$current_symbol} .= $_;
5328                     } elsif ($in_stability) {
5329                         $StabilityLevel{$current_symbol} .= $_;
5330                     } elsif ($current_param >= 0) {
5331                         $params[$current_param] .= $_;
5332                     } else {
5333                         $symbol_doc .= $_;
5334                     }
5335                 }
5336             }
5337         }
5338     }
5340     # Remember to finish the current symbol doccs.
5341     if ($current_symbol ne "") {
5343         $symbol_doc =~ s/\s+$//;
5344         $SymbolTypes{$current_symbol} = $current_type;
5345         $SymbolDocs{$current_symbol} = $symbol_doc;
5347         # Check that the stability level is valid.
5348         if ($StabilityLevel{$current_symbol}) {
5349             $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5350         }
5352         if ($current_param >= 0) {
5353             $SymbolParams{$current_symbol} = [ @params ];
5354         } else {
5355             # Delete any existing params in case we are overriding a
5356             # previously read template.
5357             delete $SymbolParams{$current_symbol};
5358         }
5359     }
5361     close (DOCS);
5362     return 1;
5366 #############################################################################
5367 # Function    : ReadObjectHierarchy
5368 # Description : This reads in the $MODULE-hierarchy.txt file containing all
5369 #                the GtkObject subclasses described in this module (and their
5370 #                ancestors).
5371 #                It places them in the @Objects array, and places their level
5372 #                in the object hierarchy in the @ObjectLevels array, at the
5373 #                same index. GtkObject, the root object, has a level of 1.
5375 #               FIXME: the version in gtkdoc-mkdb also generates tree_index.sgml
5376 #               as it goes along, this should be split out into a separate
5377 #               function.
5379 # Arguments   : none
5380 #############################################################################
5382 sub ReadObjectHierarchy {
5383     @Objects = ();
5384     @ObjectLevels = ();
5386     if (! -f $OBJECT_TREE_FILE) {
5387         return;
5388     }
5389     if (!open (INPUT, $OBJECT_TREE_FILE)) {
5390         warn "Can't open $OBJECT_TREE_FILE - skipping object tree\n";
5391         return;
5392     }
5394     # FIXME: use $OUTPUT_FORMAT
5395     # my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.$OUTPUT_FORMAT";
5396     my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.sgml";
5397     my $new_tree_index = "$SGML_OUTPUT_DIR/tree_index.new";
5399     open (OUTPUT, ">$new_tree_index")
5400         || die "Can't create $new_tree_index: $!";
5402     if ($OUTPUT_FORMAT eq "xml") {
5403         my $tree_header = $doctype_header;
5405         $tree_header =~ s/<!DOCTYPE \w+/<!DOCTYPE screen/;
5406         print (OUTPUT "$tree_header");
5407     }
5408     print (OUTPUT "<screen>\n");
5410     # Only emit objects if they are supposed to be documented, or if
5411     # they have documented children. To implement this, we maintain a
5412     # stack of pending objects which will be emitted if a documented
5413     # child turns up.
5414     my @pending_objects = ();
5415     my @pending_levels = ();
5416     my $root;
5417     while (<INPUT>) {
5418         if (m/\S+/) {
5419             my $object = $&;
5420             my $level = (length($`)) / 2 + 1;
5421             my $xref = "";
5423             if ($level == 1) {
5424                 $root = $object;
5425             }
5427             while (($#pending_levels >= 0) && ($pending_levels[$#pending_levels] >= $level)) {
5428                 my $pobject = pop(@pending_objects);
5429                 my $plevel = pop(@pending_levels);
5430             }
5432                push (@pending_objects, $object);
5433             push (@pending_levels, $level);
5435             if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
5436                    while ($#pending_levels >= 0) {
5437                     $object = shift @pending_objects;
5438                     $level = shift @pending_levels;
5439                        $xref = &MakeXRef ($object);
5441                      print (OUTPUT ' ' x ($level * 4), "$xref\n");
5442                     push (@Objects, $object);
5443                     push (@ObjectLevels, $level);
5444                     $ObjectRoots{$object} = $root;
5445                 }
5446             }
5447             #else {
5448             #    LogWarning ($OBJECT_TREE_FILE, $., "unknown type $object");
5449             #}
5450         }
5451     }
5452     print (OUTPUT "</screen>\n");
5454     close (INPUT);
5455     close (OUTPUT);
5457     &UpdateFileIfChanged ($old_tree_index, $new_tree_index, 0);
5459     &OutputObjectList;
5462 #############################################################################
5463 # Function    : ReadInterfaces
5464 # Description : This reads in the $MODULE.interfaces file.
5466 # Arguments   : none
5467 #############################################################################
5469 sub ReadInterfaces {
5470     %Interfaces = ();
5472     if (! -f $INTERFACES_FILE) {
5473         return;
5474     }
5475     if (!open (INPUT, $INTERFACES_FILE)) {
5476         warn "Can't open $INTERFACES_FILE - skipping interfaces\n";
5477         return;
5478     }
5480     while (<INPUT>) {
5481        chomp;
5482        my ($object, @ifaces) = split;
5483        if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
5484            my @knownIfaces = ();
5486            # filter out private interfaces, but leave foreign interfaces
5487            foreach my $iface (@ifaces) {
5488                if (!exists($KnownSymbols{$iface}) || $KnownSymbols{$iface} == 1) {
5489                    push (@knownIfaces, $iface);
5490                }
5491              }
5493            $Interfaces{$object} = join(' ', @knownIfaces);
5494        }
5495     }
5496     close (INPUT);
5499 #############################################################################
5500 # Function    : ReadPrerequisites
5501 # Description : This reads in the $MODULE.prerequisites file.
5503 # Arguments   : none
5504 #############################################################################
5506 sub ReadPrerequisites {
5507     %Prerequisites = ();
5509     if (! -f $PREREQUISITES_FILE) {
5510         return;
5511     }
5512     if (!open (INPUT, $PREREQUISITES_FILE)) {
5513         warn "Can't open $PREREQUISITES_FILE - skipping prerequisites\n";
5514         return;
5515     }
5517     while (<INPUT>) {
5518        chomp;
5519        my ($iface, @prereqs) = split;
5520        if (exists($KnownSymbols{$iface}) && $KnownSymbols{$iface} == 1) {
5521            my @knownPrereqs = ();
5523            # filter out private prerequisites, but leave foreign prerequisites
5524            foreach my $prereq (@prereqs) {
5525                if (!exists($KnownSymbols{$prereq}) || $KnownSymbols{$prereq} == 1) {
5526                   push (@knownPrereqs, $prereq);
5527                }
5528            }
5530            $Prerequisites{$iface} = join(' ', @knownPrereqs);
5531        }
5532     }
5533     close (INPUT);
5536 #############################################################################
5537 # Function    : ReadArgsFile
5538 # Description : This reads in an existing file which contains information on
5539 #                all GTK args. It creates the arrays @ArgObjects, @ArgNames,
5540 #                @ArgTypes, @ArgFlags, @ArgNicks and @ArgBlurbs containing info
5541 #               on the args.
5542 # Arguments   : $file - the file containing the arg information.
5543 #############################################################################
5545 sub ReadArgsFile {
5546     my ($file) = @_;
5548     my $in_arg = 0;
5549     my $arg_object;
5550     my $arg_name;
5551     my $arg_type;
5552     my $arg_flags;
5553     my $arg_nick;
5554     my $arg_blurb;
5555     my $arg_default;
5556     my $arg_range;
5558     # Reset the args info.
5559     @ArgObjects = ();
5560     @ArgNames = ();
5561     @ArgTypes = ();
5562     @ArgFlags = ();
5563     @ArgNicks = ();
5564     @ArgBlurbs = ();
5565     @ArgDefaults = ();
5566     @ArgRanges = ();
5568     if (! -f $file) {
5569         return;
5570     }
5571     if (!open (INPUT, $file)) {
5572         warn "Can't open $file - skipping args\n";
5573         return;
5574     }
5575     while (<INPUT>) {
5576         if (!$in_arg) {
5577             if (m/^<ARG>/) {
5578                 $in_arg = 1;
5579                 $arg_object = "";
5580                 $arg_name = "";
5581                 $arg_type = "";
5582                 $arg_flags = "";
5583                 $arg_nick = "";
5584                 $arg_blurb = "";
5585                 $arg_default = "";
5586                 $arg_range = "";
5587             }
5588         } else {
5589             if (m/^<NAME>(.*)<\/NAME>/) {
5590                 $arg_name = $1;
5591                 if ($arg_name =~ m/^(.*)::(.*)$/) {
5592                     $arg_object = $1;
5593                     ($arg_name = $2) =~ s/_/-/g;
5594                     #print "Found arg: $arg_name\n";
5595                 } else {
5596                     &LogWarning ($file, $., "Invalid argument name: $arg_name");
5597                 }
5598             } elsif (m/^<TYPE>(.*)<\/TYPE>/) {
5599                 $arg_type = $1;
5600             } elsif (m/^<RANGE>(.*)<\/RANGE>/) {
5601                 $arg_range = $1;
5602             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5603                 $arg_flags = $1;
5604             } elsif (m/^<NICK>(.*)<\/NICK>/) {
5605                 $arg_nick = $1;
5606             } elsif (m/^<BLURB>(.*)<\/BLURB>/) {
5607                 $arg_blurb = $1;
5608                 if ($arg_blurb eq "(null)") {
5609                   $arg_blurb = "";
5610                   &LogWarning ($file, $., "Property ${arg_object}:${arg_name} has no documentation.");
5611                 }
5612             } elsif (m/^<DEFAULT>(.*)<\/DEFAULT>/) {
5613                 $arg_default = $1;
5614             } elsif (m%^</ARG>%) {
5615                 #print "Found end of arg: ${arg_object}::${arg_name}\n${arg_type} : ${arg_flags}\n";
5616                 push (@ArgObjects, $arg_object);
5617                 push (@ArgNames, $arg_name);
5618                 push (@ArgTypes, $arg_type);
5619                 push (@ArgRanges, $arg_range);
5620                 push (@ArgFlags, $arg_flags);
5621                 push (@ArgNicks, $arg_nick);
5622                 push (@ArgBlurbs, $arg_blurb);
5623                 push (@ArgDefaults, $arg_default);
5624                 $in_arg = 0;
5625             }
5626         }
5627     }
5628     close (INPUT);
5632 #############################################################################
5633 # Function    : CheckIsObject
5634 # Description : Returns 1 if the given name is a GObject or a subclass.
5635 #                It uses the global @Objects array.
5636 #                Note that the @Objects array only contains classes in the
5637 #                current module and their ancestors - not all GObject classes.
5638 # Arguments   : $name - the name to check.
5639 #############################################################################
5641 sub CheckIsObject {
5642     my ($name) = @_;
5643     my $root = $ObjectRoots{$name};
5644     # Let GBoxed pass as an object here to get -struct appended to the id
5645     # and prevent conflicts with sections.
5646     return defined($root) and $root ne 'GEnum' and $root ne 'GFlags';
5650 #############################################################################
5651 # Function    : MakeReturnField
5652 # Description : Pads a string to $RETURN_TYPE_FIELD_WIDTH.
5653 # Arguments   : $str - the string to pad.
5654 #############################################################################
5656 sub MakeReturnField {
5657     my ($str) = @_;
5659     return $str . (' ' x ($RETURN_TYPE_FIELD_WIDTH - length ($str)));
5662 #############################################################################
5663 # Function    : GetSymbolSourceFile
5664 # Description : Get the filename where the symbol docs where taken from.
5665 # Arguments   : $symbol - the symbol name
5666 #############################################################################
5668 sub GetSymbolSourceFile {
5669     my ($symbol) = @_;
5671     if (defined($SourceSymbolSourceFile{$symbol})) {
5672         return $SourceSymbolSourceFile{$symbol};
5673     } elsif (defined($SymbolSourceFile{$symbol})) {
5674         return $SymbolSourceFile{$symbol};
5675     } else {
5676         return "";
5677     }
5680 #############################################################################
5681 # Function    : GetSymbolSourceLine
5682 # Description : Get the file line where the symbol docs where taken from.
5683 # Arguments   : $symbol - the symbol name
5684 #############################################################################
5686 sub GetSymbolSourceLine {
5687     my ($symbol) = @_;
5689     if (defined($SourceSymbolSourceLine{$symbol})) {
5690         return $SourceSymbolSourceLine{$symbol};
5691     } elsif (defined($SymbolSourceLine{$symbol})) {
5692         return $SymbolSourceLine{$symbol};
5693     } else {
5694         return 0;
5695     }