Fix deprecation version without message
[gtk-doc.git] / gtkdoc-mkdb.in
blobaa34f08663aaba13cc37222d88869fd33f8e97db
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 # Elements to consider non-block items in MarkDown parsing
344 my %MD_TEXT_LEVEL_ELEMENTS = ( "literal" => 1,
345                                "emphasis" => 1,
346                                "envar" => 1,
347                                "filename" => 1,
348                                "firstterm" => 1,
349                                "function" => 1,
350                                "manvolnum" => 1,
351                                "option" => 1,
352                                "replaceable" => 1,
353                                "structname" => 1,
354                                "title" => 1,
355                                "varname" => 1 );
356 my %MD_ESCAPABLE_CHARS = ( "\\" => 1,
357                            "`" => 1,
358                            "*" => 1,
359                            "_" => 1,
360                            "{" => 1,
361                            "}" => 1,
362                            "[" => 1,
363                            "]" => 1,
364                            "(" => 1,
365                            ")" => 1,
366                            ">" => 1,
367                            "#" => 1,
368                            "+" => 1,
369                            "-" => 1,
370                            "." => 1,
371                            "!" => 1 );
372 my %MD_GTK_ESCAPABLE_CHARS = ( "@" => 1,
373                                "%" => 1 );
375 # Create the root DocBook output directory if it doens't exist.
376 if (! -e $SGML_OUTPUT_DIR) {
377     mkdir ("$SGML_OUTPUT_DIR", 0777)
378         || die "Can't create directory: $SGML_OUTPUT_DIR";
381 # Function and other declaration output settings.
382 my $RETURN_TYPE_FIELD_WIDTH = 20;
383 my $SYMBOL_FIELD_WIDTH = 36;
384 my $SIGNAL_FIELD_WIDTH = 16;
385 my $PARAM_FIELD_COUNT = 2;
387 &ReadKnownSymbols ("$ROOT_DIR/$MODULE-sections.txt");
388 &ReadSignalsFile ($SIGNALS_FILE);
389 &ReadArgsFile ($ARGS_FILE);
390 &ReadObjectHierarchy;
391 &ReadInterfaces;
392 &ReadPrerequisites;
394 &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-decl.txt", 0);
395 if (-f "$ROOT_DIR/$MODULE-overrides.txt") {
396     &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-overrides.txt", 1);
399 for my $dir (@SOURCE_DIRS) {
400     &ReadSourceDocumentation ($dir);
403 my $changed = &OutputSGML ("$ROOT_DIR/$MODULE-sections.txt");
405 # If any of the DocBook SGML files have changed, update the timestamp file (so
406 # it can be used for Makefile dependencies).
407 if ($changed || ! -e "$ROOT_DIR/sgml.stamp") {
409     # try to detect the common prefix
410     # GtkWidget, GTK_WIDGET, gtk_widget -> gtk
411     if ($NAME_SPACE eq "") {
412         $NAME_SPACE="";
413         my $pos=0;
414         my $ratio=0.0;
415         do {
416             my %prefix;
417             my $letter="";
418             foreach my $symbol (keys(%IndexEntriesFull)) {
419                 if(($NAME_SPACE eq "") || $symbol =~ /^$NAME_SPACE/i) {
420                     if (length($symbol)>$pos) {
421                         $letter=substr($symbol,$pos,1);
422                         # stop prefix scanning
423                         if ($letter eq "_") {
424                             # stop on "_"
425                             last;
426                         }
427                         # Should we also stop on a uppercase char, if last was lowercase
428                         #   GtkWidget, if we have the 'W' and had the 't' before
429                         # or should we count upper and lowercase, and stop one 2nd uppercase, if we already had a lowercase
430                         #   GtkWidget, the 'W' would be the 2nd uppercase and with 't','k' we had lowercase chars before
431                         # need to recound each time as this is per symbol
432                         $prefix{uc($letter)}++;
433                     }
434                 }
435             }
436             if ($letter ne "" && $letter ne "_") {
437                 my $maxletter="";
438                 my $maxsymbols=0;
439                 foreach $letter (keys(%prefix)) {
440                     #print "$letter: $prefix{$letter}.\n";
441                     if ($prefix{$letter}>$maxsymbols) {
442                         $maxletter=$letter;
443                         $maxsymbols=$prefix{$letter};
444                     }
445                 }
446                 $ratio = scalar(keys(%IndexEntriesFull)) / $prefix{$maxletter};
447                 #print "most symbols start with $maxletter, that is ". (100 * $ratio) ." %\n";
448                 if ($ratio > 0.9) {
449                     # do another round
450                     $NAME_SPACE .= $maxletter;
451                 }
452                 $pos++;
453             }
454             else {
455                 $ratio=0.0;
456             }
457         } while ($ratio > 0.9);
458         #print "most symbols start with $NAME_SPACE\n";
459     }
461     &OutputIndexFull;
462     &OutputDeprecatedIndex;
463     &OutputSinceIndexes;
464     &OutputAnnotationGlossary;
466     open (TIMESTAMP, ">$ROOT_DIR/sgml.stamp")
467         || die "Can't create $ROOT_DIR/sgml.stamp: $!";
468     print (TIMESTAMP "timestamp");
469     close (TIMESTAMP);
472 #############################################################################
473 # Function    : OutputObjectList
474 # Description : This outputs the alphabetical list of objects, in a columned
475 #                table.
476 #               FIXME: Currently this also outputs ancestor objects
477 #                which may not actually be in this module.
478 # Arguments   : none
479 #############################################################################
481 sub OutputObjectList {
482     my $cols = 3;
484     # FIXME: use $OUTPUT_FORMAT
485     # my $old_object_index = "$SGML_OUTPUT_DIR/object_index.$OUTPUT_FORMAT";
486     my $old_object_index = "$SGML_OUTPUT_DIR/object_index.sgml";
487     my $new_object_index = "$SGML_OUTPUT_DIR/object_index.new";
489     open (OUTPUT, ">$new_object_index")
490         || die "Can't create $new_object_index: $!";
492     if ($OUTPUT_FORMAT eq "xml") {
493         my $header = $doctype_header;
495         $header =~ s/<!DOCTYPE \w+/<!DOCTYPE informaltable/;
496         print (OUTPUT "$header");
497     }
499     print (OUTPUT <<EOF);
500 <informaltable pgwide="1" frame="none">
501 <tgroup cols="$cols">
502 <colspec colwidth="1*"${empty_element_end}
503 <colspec colwidth="1*"${empty_element_end}
504 <colspec colwidth="1*"${empty_element_end}
505 <tbody>
508     my $count = 0;
509     my $object;
510     foreach $object (sort (@Objects)) {
511         my $xref = &MakeXRef ($object);
512         if ($count % $cols == 0) { print (OUTPUT "<row>\n"); }
513         print (OUTPUT "<entry>$xref</entry>\n");
514         if ($count % $cols == ($cols - 1)) { print (OUTPUT "</row>\n"); }
515         $count++;
516     }
517     if ($count == 0) {
518         # emit an empty row, since empty tables are invalid
519         print (OUTPUT "<row><entry> </entry></row>\n");
520     }
521     else {
522         if ($count % $cols > 0) {
523             print (OUTPUT "</row>\n");
524         }
525     }
527     print (OUTPUT <<EOF);
528 </tbody></tgroup></informaltable>
530     close (OUTPUT);
532     &UpdateFileIfChanged ($old_object_index, $new_object_index, 0);
535 #############################################################################
536 # Function    : TrimTextBlock
537 # Description : Trims extra whitespace. Empty lines inside a block are
538 #                preserved.
539 # Arguments   : $desc - the text block to trim. May contain newlines.
540 #############################################################################
542 sub TrimTextBlock {
543   my ($desc) = @_;
544   
545   # strip leading spaces on the block
546   $desc =~ s/^\s+//s;
547   # strip trailing spaces on every line
548   $desc =~ s/\s+$/\n/mg;
549   
550   return $desc;
554 #############################################################################
555 # Function    : OutputSGML
556 # Description : This collects the output for each section of the docs, and
557 #                outputs each file when the end of the section is found.
558 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
559 #                the functions/macros/structs etc. being documented, organised
560 #                into sections and subsections.
561 #############################################################################
563 sub OutputSGML {
564     my ($file) = @_;
566     #print "Reading: $file\n";
567     open (INPUT, $file)
568         || die "Can't open $file: $!";
569     my $filename = "";
570     my $book_top = "";
571     my $book_bottom = "";
572     my $includes = (defined $DEFAULT_INCLUDES) ? $DEFAULT_INCLUDES : "";
573     my $section_includes = "";
574     my $in_section = 0;
575     my $title = "";
576     my $section_id = "";
577     my $subsection = "";
578     my $synopsis;
579     my $details;
580     my $num_symbols;
581     my $changed = 0;
582     my $signals_synop = "";
583     my $signals_desc = "";
584     my $args_synop = "";
585     my $child_args_synop = "";
586     my $style_args_synop = "";
587     my $args_desc = "";
588     my $child_args_desc = "";
589     my $style_args_desc = "";
590     my $hierarchy = "";
591     my $interfaces = "";
592     my $implementations = "";
593     my $prerequisites = "";
594     my $derived = "";
595     my @file_objects = ();
596     my %templates = ();
597     my %symbol_def_line = ();
599     # merge the source docs, in case there are no templates
600     &MergeSourceDocumentation;
602     while (<INPUT>) {
603         if (m/^#/) {
604             next;
606         } elsif (m/^<SECTION>/) {
607             $synopsis = "";
608             $details = "";
609             $num_symbols = 0;
610             $in_section = 1;
611             @file_objects = ();
612             %symbol_def_line = ();
614         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
615             $synopsis .= "\n";
616             $subsection = $1;
618         } elsif (m/^<SUBSECTION>/) {
620         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
621             $title = $1;
622             #print "Section: $title\n";
624             # We don't want warnings if object & class structs aren't used.
625             $DeclarationOutput{$title} = 1;
626             $DeclarationOutput{"${title}Class"} = 1;
627             $DeclarationOutput{"${title}Iface"} = 1;
628             $DeclarationOutput{"${title}Interface"} = 1;
630         } elsif (m/^<FILE>(.*)<\/FILE>/) {
631             $filename = $1;
632             if (! defined $templates{$filename}) {
633                if (&ReadTemplateFile ("$TMPL_DIR/$filename", 1)) {
634                    &MergeSourceDocumentation;
635                    $templates{$filename}=$.;
636                }
637             } else {
638                 &LogWarning ($file, $., "Double <FILE>$filename</FILE> entry. ".
639                     "Previous occurrence on line ".$templates{$filename}.".");
640             }
641             if (($title eq "") and (defined $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"})) {
642                 $title = $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"};
643                  # Remove trailing blanks
644                 $title =~ s/\s+$//;
645            }
647         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
648             if ($in_section) {
649                 $section_includes = $1;
650             } else {
651                 if (defined $DEFAULT_INCLUDES) {
652                     &LogWarning ($file, $., "Default <INCLUDE> being overridden by command line option.");
653                 }
654                 else {
655                     $includes = $1;
656                 }
657             }
659         } elsif (m/^<\/SECTION>/) {
660             #print "End of section: $title\n";
661             if ($num_symbols > 0) {
662                 # collect documents
663                 if ($OUTPUT_FORMAT eq "xml") {
664                     $book_bottom .= "    <xi:include href=\"xml/$filename.xml\"/>\n";
665                 } else {
666                     $book_top.="<!ENTITY $section_id SYSTEM \"sgml/$filename.sgml\">\n";
667                     $book_bottom .= "    &$section_id;\n";
668                 }
670                 if (defined ($SourceSymbolDocs{"$TMPL_DIR/$filename:Include"})) {
671                     if ($section_includes) {
672                         &LogWarning ($file, $., "Section <INCLUDE> being overridden by inline comments.");
673                     }
674                     $section_includes = $SourceSymbolDocs{"$TMPL_DIR/$filename:Include"};
675                 }
676                 if ($section_includes eq "") {
677                     $section_includes = $includes;
678                 }
680                  $signals_synop =~ s/^\n*//g;
681                  $signals_synop =~ s/\n+$/\n/g;
682                 if ($signals_synop ne '') {
683                     $signals_synop = <<EOF;
684 <refsect1 id="$section_id.signals" role="signal_proto">
685 <title role="signal_proto.title">Signals</title>
686 <synopsis>
687 ${signals_synop}</synopsis>
688 </refsect1>
690                      $signals_desc = TrimTextBlock($signals_desc);
691                     $signals_desc  = <<EOF;
692 <refsect1 id="$section_id.signal-details" role="signals">
693 <title role="signals.title">Signal Details</title>
694 $signals_desc
695 </refsect1>
697                 }
699                  $args_synop =~ s/^\n*//g;
700                  $args_synop =~ s/\n+$/\n/g;
701                 if ($args_synop ne '') {
702                     $args_synop = <<EOF;
703 <refsect1 id="$section_id.properties" role="properties">
704 <title role="properties.title">Properties</title>
705 <synopsis>
706 ${args_synop}</synopsis>
707 </refsect1>
709                      $args_desc = TrimTextBlock($args_desc);
710                     $args_desc  = <<EOF;
711 <refsect1 id="$section_id.property-details" role="property_details">
712 <title role="property_details.title">Property Details</title>
713 $args_desc
714 </refsect1>
716                 }
718                  $child_args_synop =~ s/^\n*//g;
719                  $child_args_synop =~ s/\n+$/\n/g;
720                 if ($child_args_synop ne '') {
721                     $args_synop .= <<EOF;
722 <refsect1 id="$section_id.child-properties" role="child_properties">
723 <title role="child_properties.title">Child Properties</title>
724 <synopsis>
725 ${child_args_synop}</synopsis>
726 </refsect1>
728                      $child_args_desc = TrimTextBlock($child_args_desc);
729                      $args_desc .= <<EOF;
730 <refsect1 id="$section_id.child-property-details" role="child_property_details">
731 <title role="child_property_details.title">Child Property Details</title>
732 $child_args_desc
733 </refsect1>
735                 }
737                  $style_args_synop =~ s/^\n*//g;
738                  $style_args_synop =~ s/\n+$/\n/g;
739                 if ($style_args_synop ne '') {
740                     $args_synop .= <<EOF;
741 <refsect1 id="$section_id.style-properties" role="style_properties">
742 <title role="style_properties.title">Style Properties</title>
743 <synopsis>
744 ${style_args_synop}</synopsis>
745 </refsect1>
747                      $style_args_desc = TrimTextBlock($style_args_desc);
748                     $args_desc .= <<EOF;
749 <refsect1 id="$section_id.style-property-details" role="style_properties_details">
750 <title role="style_properties_details.title">Style Property Details</title>
751 $style_args_desc
752 </refsect1>
754                 }
756                  $hierarchy = TrimTextBlock($hierarchy);
757                 if ($hierarchy ne "") {
758                     $hierarchy = <<EOF;
759 <refsect1 id="$section_id.object-hierarchy" role="object_hierarchy">
760 <title role="object_hierarchy.title">Object Hierarchy</title>
761 $hierarchy
762 </refsect1>
764                 }
766                  $interfaces =~ TrimTextBlock($interfaces);
767                 if ($interfaces ne "") {
768                     $interfaces = <<EOF;
769 <refsect1 id="$section_id.implemented-interfaces" role="impl_interfaces">
770 <title role="impl_interfaces.title">Implemented Interfaces</title>
771 $interfaces
772 </refsect1>
774                 }
776                  $implementations = TrimTextBlock($implementations);
777                 if ($implementations ne "") {
778                     $implementations = <<EOF;
779 <refsect1 id="$section_id.implementations" role="implementations">
780 <title role="implementations.title">Known Implementations</title>
781 $implementations
782 </refsect1>
784                 }
786                  $prerequisites = TrimTextBlock($prerequisites);
787                 if ($prerequisites ne "") {
788                     $prerequisites = <<EOF;
789 <refsect1 id="$section_id.prerequisites" role="prerequisites">
790 <title role="prerequisites.title">Prerequisites</title>
791 $prerequisites
792 </refsect1>
794                 }
796                  $derived = TrimTextBlock($derived);
797                 if ($derived ne "") {
798                     $derived = <<EOF;
799 <refsect1 id="$section_id.derived-interfaces" role="derived_interfaces">
800 <title role="derived_interfaces.title">Known Derived Interfaces</title>
801 $derived
802 </refsect1>
804                 }
806                 $synopsis =~ s/^\n*//g;
807                 $synopsis =~ s/\n+$/\n/g;
808                 my $file_changed = &OutputSGMLFile ($filename, $title, $section_id,
809                                                     $section_includes,
810                                                     \$synopsis, \$details,
811                                                     \$signals_synop, \$signals_desc,
812                                                     \$args_synop, \$args_desc,
813                                                     \$hierarchy, \$interfaces,
814                                                     \$implementations,
815                                                     \$prerequisites, \$derived,
816                                                     \@file_objects);
817                 if ($file_changed) {
818                     $changed = 1;
819                 }
820             }
821             $title = "";
822             $section_id = "";
823             $subsection = "";
824             $in_section = 0;
825             $section_includes = "";
826             $signals_synop = "";
827             $signals_desc = "";
828             $args_synop = "";
829             $child_args_synop = "";
830             $style_args_synop = "";
831             $args_desc = "";
832             $child_args_desc = "";
833             $style_args_desc = "";
834             $hierarchy = "";
835              $interfaces = "";
836              $implementations = "";
837             $prerequisites = "";
838             $derived = "";
840         } elsif (m/^(\S+)/) {
841             my $symbol = $1;
842             #print "  Symbol: $symbol\n";
844             # check for duplicate entries
845             if (! defined $symbol_def_line{$symbol}) {
846                 my $declaration = $Declarations{$symbol};
847                 if (defined ($declaration)) {
848                     # We don't want standard macros/functions of GObjects,
849                     # or private declarations.
850                     if ($subsection ne "Standard" && $subsection ne "Private") {
851                         if (&CheckIsObject ($symbol)) {
852                             push @file_objects, $symbol;
853                         }
854                         my ($synop, $desc) = &OutputDeclaration ($symbol,
855                                                                  $declaration);
856                         my ($sig_synop, $sig_desc) = &GetSignals ($symbol);
857                         my ($arg_synop, $child_arg_synop, $style_arg_synop,
858                             $arg_desc, $child_arg_desc, $style_arg_desc) = &GetArgs ($symbol);
859                         my $hier = &GetHierarchy ($symbol);
860                         my $ifaces = &GetInterfaces ($symbol);
861                         my $impls = &GetImplementations ($symbol);
862                         my $prereqs = &GetPrerequisites ($symbol);
863                         my $der = &GetDerived ($symbol);
864                         $synopsis .= $synop;
865                         $details .= $desc;
866                         $signals_synop .= $sig_synop;
867                         $signals_desc .= $sig_desc;
868                         $args_synop .= $arg_synop;
869                         $child_args_synop .= $child_arg_synop;
870                         $style_args_synop .= $style_arg_synop;
871                         $args_desc .= $arg_desc;
872                         $child_args_desc .= $child_arg_desc;
873                         $style_args_desc .= $style_arg_desc;
874                         $hierarchy .= $hier;
875                         $interfaces .= $ifaces;
876                         $implementations .= $impls;
877                         $prerequisites .= $prereqs;
878                         $derived .= $der;
879                     }
881                     # Note that the declaration has been output.
882                     $DeclarationOutput{$symbol} = 1;
883                 } elsif ($subsection ne "Standard" && $subsection ne "Private") {
884                     $UndeclaredSymbols{$symbol} = 1;
885                     &LogWarning ($file, $., "No declaration found for $symbol.");
886                 }
887                 $num_symbols++;
888                 $symbol_def_line{$symbol}=$.;
890                 if ($section_id eq "") {
891                     if($title eq "" && $filename eq "") {
892                         &LogWarning ($file, $., "Section has no title and no file.");
893                     }
894                     # FIXME: one of those would be enough
895                     # filename should be an internal detail for gtk-doc
896                     if ($title eq "") {
897                         $title = $filename;
898                     } elsif ($filename eq "") {
899                         $filename = $title;
900                     }
901                     $filename =~ s/\s/_/g;
903                     $section_id = $SourceSymbolDocs{"$TMPL_DIR/$filename:Section_Id"};
904                     if (defined ($section_id) && $section_id !~ m/^\s*$/) {
905                         # Remove trailing blanks and use as is
906                         $section_id =~ s/\s+$//;
907                     } elsif (&CheckIsObject ($title)) {
908                         # GObjects use their class name as the ID.
909                         $section_id = &CreateValidSGMLID ($title);
910                     } else {
911                         $section_id = &CreateValidSGMLID ("$MODULE-$title");
912                     }
913                 }
914                 $SymbolSection{$symbol}=$title;
915                 $SymbolSectionId{$symbol}=$section_id;
916             }
917             else {
918                 &LogWarning ($file, $., "Double symbol entry for $symbol. ".
919                     "Previous occurrence on line ".$symbol_def_line{$symbol}.".");
920             }
921         }
922     }
923     close (INPUT);
925     &OutputMissingDocumentation;
926     &OutputUndeclaredSymbols;
927     &OutputUnusedSymbols;
929     if ($OUTPUT_ALL_SYMBOLS) {
930         &OutputAllSymbols;
931     }
932     if ($OUTPUT_SYMBOLS_WITHOUT_SINCE) {
933         &OutputSymbolsWithoutSince;
934     }
936     for $filename (split (' ', $EXPAND_CONTENT_FILES)) {
937         my $file_changed = &OutputExtraFile ($filename);
938         if ($file_changed) {
939             $changed = 1;
940         }
941     }
943     &OutputBook ($book_top, $book_bottom);
945     return $changed;
948 #############################################################################
949 # Function    : OutputIndex
950 # Description : This writes an indexlist that can be included into the main-
951 #               document into an <index> tag.
952 #############################################################################
954 sub OutputIndex {
955     my ($basename, $apiindexref ) = @_;
956     my %apiindex = %{$apiindexref};
957     my $old_index = "$SGML_OUTPUT_DIR/$basename.xml";
958     my $new_index = "$SGML_OUTPUT_DIR/$basename.new";
959     my $lastletter = " ";
960     my $divopen = 0;
961     my $symbol;
962     my $short_symbol;
964     open (OUTPUT, ">$new_index")
965         || die "Can't create $new_index";
967     my $header = $doctype_header;
968     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE indexdiv/;
970     print (OUTPUT "$header<indexdiv>\n");
972     #print "generate $basename index (".%apiindex." entries)\n";
974     # do a case insensitive sort while chopping off the prefix
975     foreach my $hash (
976         sort { $$a{criteria} cmp $$b{criteria} }
977         map { my $x = uc($_); $x =~ s/^$NAME_SPACE\_?(.*)/$1/i; { criteria => $x, original => $_, short => $1 } }
978         keys %apiindex) {
980         $symbol = $$hash{original};
981         if (defined($$hash{short})) {
982             $short_symbol = $$hash{short};
983         } else {
984             $short_symbol = $symbol;
985         }
987         # generate a short symbol description
988         my $symbol_desc = "";
989         my $symbol_section = "";
990         my $symbol_section_id = "";
991         my $symbol_type = "";
992         if (defined($DeclarationTypes{$symbol})) {
993           $symbol_type = lc($DeclarationTypes{$symbol});
994         }
995         if ($symbol_type eq "") {
996             #print "trying symbol $symbol\n";
997             if ($symbol =~ m/(.*)::(.*)/) {
998                 my $oname = $1;
999                 my $osym = $2;
1000                 my $i;
1001                 #print "  trying object signal ${oname}:$osym in ".$#SignalNames." signals\n";
1002                 for ($i = 0; $i <= $#SignalNames; $i++) {
1003                     if ($SignalNames[$i] eq $osym) {
1004                         $symbol_type = "object signal";
1005                         if (defined($SymbolSection{$oname})) {
1006                            $symbol_section = $SymbolSection{$oname};
1007                            $symbol_section_id = $SymbolSectionId{$oname};
1008                         }
1009                         last;
1010                     }
1011                 }
1012             } elsif ($symbol =~ m/(.*):(.*)/) {
1013                 my $oname = $1;
1014                 my $osym = $2;
1015                 my $i;
1016                 #print "  trying object property ${oname}::$osym in ".$#ArgNames." properties\n";
1017                 for ($i = 0; $i <= $#ArgNames; $i++) {
1018                     #print "    ".$ArgNames[$i]."\n";
1019                     if ($ArgNames[$i] eq $osym) {
1020                         $symbol_type = "object property";
1021                         if (defined($SymbolSection{$oname})) {
1022                            $symbol_section = $SymbolSection{$oname};
1023                            $symbol_section_id = $SymbolSectionId{$oname};
1024                         }
1025                         last;
1026                     }
1027                 }
1028             }
1029         } else {
1030            if (defined($SymbolSection{$symbol})) {
1031                $symbol_section = $SymbolSection{$symbol};
1032                $symbol_section_id = $SymbolSectionId{$symbol};
1033            }
1034         }
1035         if ($symbol_type ne "") {
1036            $symbol_desc=", $symbol_type";
1037            if ($symbol_section ne "") {
1038                $symbol_desc.=" in <link linkend=\"$symbol_section_id\">$symbol_section</link>";
1039                #$symbol_desc.=" in ". &ExpandAbbreviations($symbol, "#$symbol_section");
1040            }
1041         }
1043         my $curletter = uc(substr($short_symbol,0,1));
1044         my $id = $apiindex{$symbol};
1046         #print "  add symbol $symbol with $id to index in section $curletter\n";
1048         if ($curletter ne $lastletter) {
1049             $lastletter = $curletter;
1051             if ($divopen == 1) {
1052                 print (OUTPUT "</indexdiv>\n");
1053             }
1054             print (OUTPUT "<indexdiv><title>$curletter</title>\n");
1055             $divopen = 1;
1056         }
1058         print (OUTPUT <<EOF);
1059 <indexentry><primaryie linkends="$id"><link linkend="$id">$symbol</link>$symbol_desc</primaryie></indexentry>
1061     }
1063     if ($divopen == 1) {
1064         print (OUTPUT "</indexdiv>\n");
1065     }
1066     print (OUTPUT "</indexdiv>\n");
1067     close (OUTPUT);
1069     &UpdateFileIfChanged ($old_index, $new_index, 0);
1073 #############################################################################
1074 # Function    : OutputIndexFull
1075 # Description : This writes the full api indexlist that can be included into the
1076 #               main document into an <index> tag.
1077 #############################################################################
1079 sub OutputIndexFull {
1080     &OutputIndex ("api-index-full", \%IndexEntriesFull);
1084 #############################################################################
1085 # Function    : OutputDeprecatedIndex
1086 # Description : This writes the deprecated api indexlist that can be included
1087 #               into the main document into an <index> tag.
1088 #############################################################################
1090 sub OutputDeprecatedIndex {
1091     &OutputIndex ("api-index-deprecated", \%IndexEntriesDeprecated);
1095 #############################################################################
1096 # Function    : OutputSinceIndexes
1097 # Description : This writes the 'since' api indexlists that can be included into
1098 #               the main document into an <index> tag.
1099 #############################################################################
1101 sub OutputSinceIndexes {
1102     my @sinces = keys %{{ map { $_ => 1 } values %Since }};
1104     foreach my $version (@sinces) {
1105         #print "Since : [$version]\n";
1106         # TODO make filtered hash
1107         #my %index = grep { $Since{$_} eq $version } %IndexEntriesSince;
1108         my %index = map { $_ => $IndexEntriesSince{$_} } grep { $Since{$_} eq $version } keys %IndexEntriesSince;
1110         &OutputIndex ("api-index-$version", \%index);
1111     }
1114 #############################################################################
1115 # Function    : OutputAnnotationGlossary
1116 # Description : This writes a glossary of the used annotation terms into a
1117 #               separate glossary file that can be included into the main
1118 #               document.
1119 #############################################################################
1121 sub OutputAnnotationGlossary {
1122     my $old_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.xml";
1123     my $new_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.new";
1124     my $lastletter = " ";
1125     my $divopen = 0;
1127     # if there are no annotations used return
1128     return if (! keys(%AnnotationsUsed));
1130     # add acronyms that are referenced from acronym text
1131 rerun:
1132     foreach my $annotation (keys(%AnnotationsUsed)) {
1133         if(defined($AnnotationDefinition{$annotation})) {
1134             if($AnnotationDefinition{$annotation} =~ m/<acronym>([\w ]+)<\/acronym>/) {
1135                 if (!exists($AnnotationsUsed{$1})) {
1136                     $AnnotationsUsed{$1} = 1;
1137                     goto rerun;
1138                 }
1139             }
1140         }
1141     }
1143     open (OUTPUT, ">$new_glossary")
1144         || die "Can't create $new_glossary";
1146     my $header = $doctype_header;
1147     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE glossary/;
1149     print (OUTPUT  <<EOF);
1150 $header
1151 <glossary id="annotation-glossary">
1152   <title>Annotation Glossary</title>
1155     foreach my $annotation (sort(keys(%AnnotationsUsed))) {
1156         if(defined($AnnotationDefinition{$annotation})) {
1157             my $def = $AnnotationDefinition{$annotation};
1158             my $curletter = uc(substr($annotation,0,1));
1160             if ($curletter ne $lastletter) {
1161                 $lastletter = $curletter;
1163                 if ($divopen == 1) {
1164                     print (OUTPUT "</glossdiv>\n");
1165                 }
1166                 print (OUTPUT "<glossdiv><title>$curletter</title>\n");
1167                 $divopen = 1;
1168             }
1169             print (OUTPUT <<EOF);
1170     <glossentry>
1171       <glossterm><anchor id="annotation-glossterm-$annotation"/>$annotation</glossterm>
1172       <glossdef>
1173         <para>$def</para>
1174       </glossdef>
1175     </glossentry>
1177         }
1178     }
1180     if ($divopen == 1) {
1181         print (OUTPUT "</glossdiv>\n");
1182     }
1183     print (OUTPUT "</glossary>\n");
1184     close (OUTPUT);
1186     &UpdateFileIfChanged ($old_glossary, $new_glossary, 0);
1189 #############################################################################
1190 # Function    : ReadKnownSymbols
1191 # Description : This collects the names of non-private symbols from the
1192 #               $MODULE-sections.txt file.
1193 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
1194 #                the functions/macros/structs etc. being documented, organised
1195 #                into sections and subsections.
1196 #############################################################################
1198 sub ReadKnownSymbols {
1199     my ($file) = @_;
1201     my $subsection = "";
1203     #print "Reading: $file\n";
1204     open (INPUT, $file)
1205         || die "Can't open $file: $!";
1207     while (<INPUT>) {
1208         if (m/^#/) {
1209             next;
1211         } elsif (m/^<SECTION>/) {
1212             $subsection = "";
1214         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
1215             $subsection = $1;
1217         } elsif (m/^<SUBSECTION>/) {
1218             next;
1220         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
1221             next;
1223         } elsif (m/^<FILE>(.*)<\/FILE>/) {
1224             $KnownSymbols{"$TMPL_DIR/$1:Long_Description"} = 1;
1225             $KnownSymbols{"$TMPL_DIR/$1:Short_Description"} = 1;
1226             next;
1228         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
1229             next;
1231         } elsif (m/^<\/SECTION>/) {
1232             next;
1234         } elsif (m/^(\S+)/) {
1235             my $symbol = $1;
1237             if ($subsection ne "Standard" && $subsection ne "Private") {
1238                 $KnownSymbols{$symbol} = 1;
1239             }
1240             else {
1241                 $KnownSymbols{$symbol} = 0;
1242             }
1243         }
1244     }
1245     close (INPUT);
1249 #############################################################################
1250 # Function    : OutputDeclaration
1251 # Description : Returns the synopsis and detailed description DocBook
1252 #                describing one function/macro etc.
1253 # Arguments   : $symbol - the name of the function/macro begin described.
1254 #                $declaration - the declaration of the function/macro.
1255 #############################################################################
1257 sub OutputDeclaration {
1258     my ($symbol, $declaration) = @_;
1260     my $type = $DeclarationTypes {$symbol};
1261     if ($type eq 'MACRO') {
1262         return &OutputMacro ($symbol, $declaration);
1263     } elsif ($type eq 'TYPEDEF') {
1264         return &OutputTypedef ($symbol, $declaration);
1265     } elsif ($type eq 'STRUCT') {
1266         return &OutputStruct ($symbol, $declaration);
1267     } elsif ($type eq 'ENUM') {
1268         return &OutputEnum ($symbol, $declaration);
1269     } elsif ($type eq 'UNION') {
1270         return &OutputUnion ($symbol, $declaration);
1271     } elsif ($type eq 'VARIABLE') {
1272         return &OutputVariable ($symbol, $declaration);
1273     } elsif ($type eq 'FUNCTION') {
1274         return &OutputFunction ($symbol, $declaration, $type);
1275     } elsif ($type eq 'USER_FUNCTION') {
1276         return &OutputFunction ($symbol, $declaration, $type);
1277     } else {
1278         die "Unknown symbol type";
1279     }
1283 #############################################################################
1284 # Function    : OutputSymbolTraits
1285 # Description : Returns the Since and StabilityLevel paragraphs for a symbol.
1286 # Arguments   : $symbol - the name of the function/macro begin described.
1287 #############################################################################
1289 sub OutputSymbolTraits {
1290     my ($symbol) = @_;
1291     my $desc = "";
1293     if (exists $Since{$symbol}) {
1294         $desc .= "<para role=\"since\">Since $Since{$symbol}</para>";
1295     }
1296     if (exists $StabilityLevel{$symbol}) {
1297         $desc .= "<para role=\"stability\">Stability Level: $StabilityLevel{$symbol}</para>";
1298     }
1299     return $desc;
1302 #############################################################################
1303 # Function    : Outpu{Symbol,Section}ExtraLinks
1304 # Description : Returns extralinks for the symbol (if enabled).
1305 # Arguments   : $symbol - the name of the function/macro begin described.
1306 #############################################################################
1308 sub uri_escape {
1309     my $text = $_[0];
1310     return undef unless defined $text;
1312     # Build a char to hex map
1313     my %escapes = ();
1314     for (0..255) {
1315             $escapes{chr($_)} = sprintf("%%%02X", $_);
1316     }
1318     # Default unsafe characters.  RFC 2732 ^(uric - reserved)
1319     $text =~ s/([^A-Za-z0-9\-_.!~*'()])/$escapes{$1}/g;
1321     return $text;
1324 sub OutputSymbolExtraLinks {
1325     my ($symbol) = @_;
1326     my $desc = "";
1328     if (0) { # NEW FEATURE: needs configurability
1329     my $sstr = &uri_escape($symbol);
1330     my $mstr = &uri_escape($MODULE);
1331     $desc .= <<EOF;
1332 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1333 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$sstr">edit documentation</ulink>
1335     }
1336     return $desc;
1339 sub OutputSectionExtraLinks {
1340     my ($symbol,$docsymbol) = @_;
1341     my $desc = "";
1343     if (0) { # NEW FEATURE: needs configurability
1344     my $sstr = &uri_escape($symbol);
1345     my $mstr = &uri_escape($MODULE);
1346     my $dsstr = &uri_escape($docsymbol);
1347     $desc .= <<EOF;
1348 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1349 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$dsstr">edit documentation</ulink>
1351     }
1352     return $desc;
1356 #############################################################################
1357 # Function    : OutputMacro
1358 # Description : Returns the synopsis and detailed description of a macro.
1359 # Arguments   : $symbol - the macro.
1360 #                $declaration - the declaration of the macro.
1361 #############################################################################
1363 sub OutputMacro {
1364     my ($symbol, $declaration) = @_;
1365     my $id = &CreateValidSGMLID ($symbol);
1366     my $condition = &MakeConditionDescription ($symbol);
1367     my $synop = &MakeReturnField("#define") . "<link linkend=\"$id\">$symbol</link>";
1368     my $desc;
1370     my @fields = ParseMacroDeclaration($declaration, \&CreateValidSGML);
1371     my $title = $symbol . (@fields ? "()" : "");
1373     $desc = "<refsect2 id=\"$id\" role=\"macro\"$condition>\n<title>$title</title>\n";
1374     $desc .= MakeIndexterms($symbol, $id);
1375     $desc .= "\n";
1376     $desc .= OutputSymbolExtraLinks($symbol);
1378     if (@fields) {
1379         if (length ($symbol) < $SYMBOL_FIELD_WIDTH) {
1380             $synop .= (' ' x ($SYMBOL_FIELD_WIDTH - length ($symbol)));
1381         }
1383         $synop .= "(";
1384         for (my $i = 1; $i <= $#fields; $i += 2) {
1385             my $field_name = $fields[$i];
1387             if ($i == 1) {
1388                 $synop .= "$field_name";
1389             } else {
1390                 $synop .= ",\n"
1391                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1392                     . " $field_name";
1393             }
1394         }
1395         $synop .= ")";
1396     }
1397     $synop .= "\n";
1399     # Don't output the macro definition if is is a conditional macro or it
1400     # looks like a function, i.e. starts with "g_" or "_?gnome_", or it is
1401     # longer than 2 lines, otherwise we get lots of complicated macros like
1402     # g_assert.
1403     if (!defined ($DeclarationConditional{$symbol}) && ($symbol !~ m/^g_/)
1404         && ($symbol !~ m/^_?gnome_/) && (($declaration =~ tr/\n//) < 2)) {
1405         my $decl_out = &CreateValidSGML ($declaration);
1406         $desc .= "<programlisting>$decl_out</programlisting>\n";
1407     } else {
1408         $desc .= "<programlisting>" . &MakeReturnField("#define") . "$symbol";
1409         if ($declaration =~ m/^\s*#\s*define\s+\w+(\([^\)]*\))/) {
1410             my $args = $1;
1411             my $pad = ' ' x ($RETURN_TYPE_FIELD_WIDTH - length ("#define "));
1412             # Align each line so that if should all line up OK.
1413             $args =~ s/\n/\n$pad/gm;
1414             $desc .= &CreateValidSGML ($args);
1415         }
1416         $desc .= "</programlisting>\n";
1417     }
1419     $desc .= &MakeDeprecationNote($symbol);
1421     my $parameters = &OutputParamDescriptions ("MACRO", $symbol, @fields);
1422     my $parameters_output = 0;
1424     if (defined ($SymbolDocs{$symbol})) {
1425         my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1427         # Try to insert the parameter table at the author's desired position.
1428         # Otherwise we need to tag it onto the end.
1429         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
1430           $parameters_output = 1;
1431         }
1432         $desc .= $symbol_docs;
1433     }
1435     if ($parameters_output == 0) {
1436         $desc .= $parameters;
1437     }
1439     $desc .= OutputSymbolTraits ($symbol);
1440     $desc .= "</refsect2>\n";
1441     return ($synop, $desc);
1445 #############################################################################
1446 # Function    : OutputTypedef
1447 # Description : Returns the synopsis and detailed description of a typedef.
1448 # Arguments   : $symbol - the typedef.
1449 #                $declaration - the declaration of the typedef,
1450 #                  e.g. 'typedef unsigned int guint;'
1451 #############################################################################
1453 sub OutputTypedef {
1454     my ($symbol, $declaration) = @_;
1455     my $id = &CreateValidSGMLID ($symbol);
1456     my $condition = &MakeConditionDescription ($symbol);
1457     my $synop = &MakeReturnField("typedef") . "<link linkend=\"$id\">$symbol</link>;\n";
1458     my $desc = "<refsect2 id=\"$id\" role=\"typedef\"$condition>\n<title>$symbol</title>\n";
1460     $desc .= MakeIndexterms($symbol, $id);
1461     $desc .= "\n";
1462     $desc .= OutputSymbolExtraLinks($symbol);
1464     if (!defined ($DeclarationConditional{$symbol})) {
1465         my $decl_out = &CreateValidSGML ($declaration);
1466         $desc .= "<programlisting>$decl_out</programlisting>\n";
1467     }
1469     $desc .= &MakeDeprecationNote($symbol);
1471     if (defined ($SymbolDocs{$symbol})) {
1472         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1473     }
1474     $desc .= OutputSymbolTraits ($symbol);
1475     $desc .= "</refsect2>\n";
1476     return ($synop, $desc);
1480 #############################################################################
1481 # Function    : OutputStruct
1482 # Description : Returns the synopsis and detailed description of a struct.
1483 #                We check if it is a object struct, and if so we only output
1484 #                parts of it that are noted as public fields.
1485 #                We also use a different SGML ID for object structs, since the
1486 #                original ID is used for the entire RefEntry.
1487 # Arguments   : $symbol - the struct.
1488 #                $declaration - the declaration of the struct.
1489 #############################################################################
1491 sub OutputStruct {
1492     my ($symbol, $declaration) = @_;
1494     my $is_gtype = 0;
1495     my $default_to_public = 1;
1496     if (&CheckIsObject ($symbol)) {
1497         #print "Found struct gtype: $symbol\n";
1498         $is_gtype = 1;
1499         $default_to_public = $ObjectRoots{$symbol} eq 'GBoxed';
1500     }
1502     my $id;
1503     my $condition;
1504     if ($is_gtype) {
1505         $id = &CreateValidSGMLID ($symbol . "_struct");
1506         $condition = &MakeConditionDescription ($symbol . "_struct");
1507     } else {
1508         $id = &CreateValidSGMLID ($symbol);
1509         $condition = &MakeConditionDescription ($symbol);
1510     }
1512     # Determine if it is a simple struct or it also has a typedef.
1513     my $has_typedef = 0;
1514     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1515       $has_typedef = 1;
1516     }
1518     my $synop;
1519     my $desc;
1520     if ($has_typedef) {
1521         # For structs with typedefs we just output the struct name.
1522         $synop = &MakeReturnField("") . "<link linkend=\"$id\">$symbol</link>;\n";
1523         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>$symbol</title>\n";
1524     } else {
1525         $synop = &MakeReturnField("struct") . "<link linkend=\"$id\">$symbol</link>;\n";
1526         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>struct $symbol</title>\n";
1527     }
1529     $desc .= MakeIndexterms($symbol, $id);
1530     $desc .= "\n";
1531     $desc .= OutputSymbolExtraLinks($symbol);
1533     # Form a pretty-printed, private-data-removed form of the declaration
1535     my $decl_out = "";
1536     if ($declaration =~ m/^\s*$/) {
1537         #print "Found opaque struct: $symbol\n";
1538         $decl_out = "typedef struct _$symbol $symbol;";
1539     } elsif ($declaration =~ m/^\s*struct\s+\w+\s*;\s*$/) {
1540         #print "Found opaque struct: $symbol\n";
1541         $decl_out = "struct $symbol;";
1542     } else {
1543         my $public = $default_to_public;
1544         my $new_declaration = "";
1545         my $decl_line;
1546         my $decl = $declaration;
1548         if ($decl =~ m/^\s*(typedef\s+)?struct\s*\w*\s*(?:\/\*.*\*\/)?\s*{(.*)}\s*\w*\s*;\s*$/s) {
1549             my $struct_contents = $2;
1551             foreach $decl_line (split (/\n/, $struct_contents)) {
1552                 #print "Struct line: $decl_line\n";
1553                 if ($decl_line =~ m%/\*\s*<\s*public\s*>\s*\*/%) {
1554                     $public = 1;
1555                 } elsif ($decl_line =~ m%/\*\s*<\s*(private|protected)\s*>\s*\*/%) {
1556                     $public = 0;
1557                 } elsif ($public) {
1558                     $new_declaration .= $decl_line . "\n";
1559                 }
1560             }
1562             if ($new_declaration) {
1563                 # Strip any blank lines off the ends.
1564                 $new_declaration =~ s/^\s*\n//;
1565                 $new_declaration =~ s/\n\s*$/\n/;
1567                 if ($has_typedef) {
1568                     $decl_out = "typedef struct {\n" . $new_declaration
1569                       . "} $symbol;\n";
1570                 } else {
1571                     $decl_out = "struct $symbol {\n" . $new_declaration
1572                       . "};\n";
1573                 }
1574             }
1575         } else {
1576             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1577                 "Couldn't parse struct:\n$declaration");
1578         }
1580         # If we couldn't parse the struct or it was all private, output an
1581         # empty struct declaration.
1582         if ($decl_out eq "") {
1583             if ($has_typedef) {
1584                 $decl_out = "typedef struct _$symbol $symbol;";
1585             } else {
1586                 $decl_out = "struct $symbol;";
1587             }
1588         }
1589     }
1591     $decl_out = &CreateValidSGML ($decl_out);
1592     $desc .= "<programlisting>$decl_out</programlisting>\n";
1594     $desc .= &MakeDeprecationNote($symbol);
1596     if (defined ($SymbolDocs{$symbol})) {
1597         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1598     }
1600     # Create a table of fields and descriptions
1602     # FIXME: Inserting &#160's into the produced type declarations here would
1603     #        improve the output in most situations ... except for function
1604     #        members of structs!
1605     my @fields = ParseStructDeclaration($declaration, !$default_to_public,
1606                                         0, \&MakeXRef,
1607                                         sub {
1608                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1609                                         });
1610     my $params = $SymbolParams{$symbol};
1612     # If no parameters are filled in, we don't generate the description
1613     # table, for backwards compatibility.
1615     my $found = 0;
1616     if (defined $params) {
1617         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1618             if ($params->[$i] =~ /\S/) {
1619                 $found = 1;
1620                 last;
1621             }
1622         }
1623     }
1625     if ($found) {
1626         my %field_descrs = @$params;
1627         my $missing_parameters = "";
1628         my $unused_parameters = "";
1630         $desc .= "<variablelist role=\"struct\">\n";
1631         while (@fields) {
1632             my $field_name = shift @fields;
1633             my $text = shift @fields;
1634             my $field_descr = $field_descrs{$field_name};
1635             my $param_annotations = "";
1637             $desc .= "<varlistentry><term>$text</term>\n";
1638             if (defined $field_descr) {
1639                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1640                 $field_descr = &ConvertMarkDown($symbol, $field_descr);
1641                 $field_descr .= $param_annotations;
1642                 # trim
1643                 $field_descr =~ s/^(\s|\n)+//msg;
1644                 $field_descr =~ s/(\s|\n)+$//msg;
1645                 $desc .= "<listitem>$field_descr</listitem>\n";
1646                 delete $field_descrs{$field_name};
1647             } else {
1648                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1649                     "Field description for $symbol"."::"."$field_name is missing in source code comment block.");
1650                 if ($missing_parameters ne "") {
1651                   $missing_parameters .= ", ".$field_name;
1652                 } else {
1653                     $missing_parameters = $field_name;
1654                 }
1655                 $desc .= "<listitem />\n";
1656             }
1657             $desc .= "</varlistentry>\n";
1658         }
1659         $desc .= "</variablelist>";
1660         foreach my $field_name (keys %field_descrs) {
1661             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1662                 "Field description for $symbol"."::"."$field_name is not used from source code comment block.");
1663             if ($unused_parameters ne "") {
1664               $unused_parameters .= ", ".$field_name;
1665             } else {
1666                $unused_parameters = $field_name;
1667             }
1668         }
1670         # remember missing/unused parameters (needed in tmpl-free build)
1671         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1672             $AllIncompleteSymbols{$symbol}=$missing_parameters;
1673         }
1674         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1675             $AllUnusedSymbols{$symbol}=$unused_parameters;
1676         }
1677     }
1678     else {
1679         if (scalar(@fields) > 0) {
1680             if (! exists ($AllIncompleteSymbols{$symbol})) {
1681                 $AllIncompleteSymbols{$symbol}="<items>";
1682                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1683                     "Field descriptions for struct $symbol are missing in source code comment block.");
1684                 @TRACE@("Remaining structs fields: ".@fields.":".join(',',@fields)."\n");
1685             }
1686         }
1687     }
1689     $desc .= OutputSymbolTraits ($symbol);
1690     $desc .= "</refsect2>\n";
1691     return ($synop, $desc);
1695 #############################################################################
1696 # Function    : OutputUnion
1697 # Description : Returns the synopsis and detailed description of a union.
1698 # Arguments   : $symbol - the union.
1699 #                $declaration - the declaration of the union.
1700 #############################################################################
1702 sub OutputUnion {
1703     my ($symbol, $declaration) = @_;
1704     my $id = &CreateValidSGMLID ($symbol);
1705     my $condition = &MakeConditionDescription ($symbol);
1707     # Determine if it is a simple struct or it also has a typedef.
1708     my $has_typedef = 0;
1709     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1710       $has_typedef = 1;
1711     }
1713     my $synop;
1714     my $desc;
1715     if ($has_typedef) {
1716         # For unions with typedefs we just output the union name.
1717         $synop = &MakeReturnField("") . "<link linkend=\"$id\">$symbol</link>;\n";
1718         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>$symbol</title>\n";
1719     } else {
1720         $synop = &MakeReturnField("union") . "<link linkend=\"$id\">$symbol</link>;\n";
1721         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>union $symbol</title>\n";
1722     }
1724     $desc .= MakeIndexterms($symbol, $id);
1725     $desc .= "\n";
1726     $desc .= OutputSymbolExtraLinks($symbol);
1728     # FIXME: we do more for structs
1729     my $decl_out = &CreateValidSGML ($declaration);
1730     $desc .= "<programlisting>$decl_out</programlisting>\n";
1732     $desc .= &MakeDeprecationNote($symbol);
1734     if (defined ($SymbolDocs{$symbol})) {
1735         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1736     }
1738     # Create a table of fields and descriptions
1740     # FIXME: Inserting &#160's into the produced type declarations here would
1741     #        improve the output in most situations ... except for function
1742     #        members of structs!
1743     my @fields = ParseStructDeclaration($declaration, 0,
1744                                         0, \&MakeXRef,
1745                                         sub {
1746                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1747                                         });
1748     my $params = $SymbolParams{$symbol};
1750     # If no parameters are filled in, we don't generate the description
1751     # table, for backwards compatibility
1753     my $found = 0;
1754     if (defined $params) {
1755         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1756             if ($params->[$i] =~ /\S/) {
1757                 $found = 1;
1758                 last;
1759             }
1760         }
1761     }
1763     if ($found) {
1764         my %field_descrs = @$params;
1765         my $missing_parameters = "";
1766         my $unused_parameters = "";
1768         $desc .= "<variablelist role=\"union\">\n";
1769         while (@fields) {
1770             my $field_name = shift @fields;
1771             my $text = shift @fields;
1772             my $field_descr = $field_descrs{$field_name};
1773             my $param_annotations = "";
1775             $desc .= "<varlistentry><term>$text</term>\n";
1776             if (defined $field_descr) {
1777                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1778                 $field_descr = &ConvertMarkDown($symbol, $field_descr);
1779                 $field_descr .= $param_annotations;
1780                 # trim
1781                 $field_descr =~ s/^(\s|\n)+//msg;
1782                 $field_descr =~ s/(\s|\n)+$//msg;
1783                 $desc .= "<listitem>$field_descr</listitem>\n";
1784                 delete $field_descrs{$field_name};
1785             } else {
1786                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1787                     "Field description for $symbol"."::"."$field_name is missing in source code comment block.");
1788                 if ($missing_parameters ne "") {
1789                     $missing_parameters .= ", ".$field_name;
1790                 } else {
1791                     $missing_parameters = $field_name;
1792                 }
1793                 $desc .= "<listitem />\n";
1794             }
1795             $desc .= "</varlistentry>\n";
1796         }
1797         $desc .= "</variablelist>";
1798         foreach my $field_name (keys %field_descrs) {
1799             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1800                 "Field description for $symbol"."::"."$field_name is not used from source code comment block.");
1801             if ($unused_parameters ne "") {
1802               $unused_parameters .= ", ".$field_name;
1803             } else {
1804                $unused_parameters = $field_name;
1805             }
1806         }
1808         # remember missing/unused parameters (needed in tmpl-free build)
1809         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1810             $AllIncompleteSymbols{$symbol}=$missing_parameters;
1811         }
1812         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1813             $AllUnusedSymbols{$symbol}=$unused_parameters;
1814         }
1815     }
1816     else {
1817         if (scalar(@fields) > 0) {
1818             if (! exists ($AllIncompleteSymbols{$symbol})) {
1819                 $AllIncompleteSymbols{$symbol}="<items>";
1820                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1821                     "Field descriptions for union $symbol are missing in source code comment block.");
1822                 @TRACE@("Remaining union fields: ".@fields.":".join(',',@fields)."\n");
1823             }
1824         }
1825     }
1827     $desc .= OutputSymbolTraits ($symbol);
1828     $desc .= "</refsect2>\n";
1829     return ($synop, $desc);
1833 #############################################################################
1834 # Function    : OutputEnum
1835 # Description : Returns the synopsis and detailed description of a enum.
1836 # Arguments   : $symbol - the enum.
1837 #                $declaration - the declaration of the enum.
1838 #############################################################################
1840 sub OutputEnum {
1841     my ($symbol, $declaration) = @_;
1843     my $is_gtype = 0;
1844     if (&CheckIsObject ($symbol)) {
1845         #print "Found enum gtype: $symbol\n";
1846         $is_gtype = 1;
1847     }
1849     my $id;
1850     my $condition;
1851     if ($is_gtype) {
1852         $id = &CreateValidSGMLID ($symbol . "_enum");
1853         $condition = &MakeConditionDescription ($symbol . "_enum");
1854     } else {
1855         $id = &CreateValidSGMLID ($symbol);
1856         $condition = &MakeConditionDescription ($symbol);
1857     }
1859     my $synop = &MakeReturnField("enum") . "<link linkend=\"$id\">$symbol</link>;\n";
1860     my $desc = "<refsect2 id=\"$id\" role=\"enum\"$condition>\n<title>enum $symbol</title>\n";
1862     $desc .= MakeIndexterms($symbol, $id);
1863     $desc .= "\n";
1864     $desc .= OutputSymbolExtraLinks($symbol);
1866     my $decl_out = "";
1867     my $public = 1;
1868     my $new_declaration = "";
1869     my $decl_line;
1870     my $decl = $declaration;
1872     if ($decl =~ m/^\s*(typedef\s+)?enum\s*\w*\s*(?:\/\*.*\*\/)?\s*{(.*)}\s*\w*\s*;\s*$/s) {
1873         my $has_typedef = defined($1) ? 1 : 0;
1874         my $enum_contents = $2;
1876         foreach $decl_line (split (/\n/, $enum_contents)) {
1877             #print "Enum line: $decl_line\n";
1878             if ($decl_line =~ m%/\*\s*<\s*public\s*>\s*\*/%) {
1879                 $public = 1;
1880             } elsif ($decl_line =~ m%/\*\s*<\s*(private|protected)\s*>\s*\*/%) {
1881                 $public = 0;
1882             } elsif ($public) {
1883                 $new_declaration .= $decl_line . "\n";
1884             }
1885         }
1887         if ($new_declaration) {
1888             # Strip any blank lines off the ends.
1889             $new_declaration =~ s/^\s*\n//;
1890             $new_declaration =~ s/\n\s*$/\n/;
1892             if ($has_typedef) {
1893                 $decl_out = "typedef enum {\n" . $new_declaration
1894                   . "} $symbol;\n";
1895             } else {
1896                 $decl_out = "enum $symbol {\n" . $new_declaration
1897                   . "};\n";
1898             }
1899         }
1900     }
1902     $decl_out = &CreateValidSGML ($decl_out);
1903     $desc .= "<programlisting>$decl_out</programlisting>\n";
1905     $desc .= &MakeDeprecationNote($symbol);
1907     if (defined ($SymbolDocs{$symbol})) {
1908         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1909     }
1911     # Create a table of fields and descriptions
1913     my @fields = ParseEnumDeclaration($declaration);
1914     my $params = $SymbolParams{$symbol};
1916     # If nothing at all is documented log a single summary warning at the end.
1917     # Otherwise, warn about each undocumented item.
1919     my $found = 0;
1920     if (defined $params) {
1921         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1922             if ($params->[$i] =~ /\S/) {
1923                 $found = 1;
1924                 last;
1925             }
1926         }
1927     }
1929     my %field_descrs = (defined $params ? @$params : ());
1930     my $missing_parameters = "";
1931     my $unused_parameters = "";
1933     $desc .= "<variablelist role=\"enum\">\n";
1934     for my $field_name (@fields) {
1935         my $field_descr = $field_descrs{$field_name};
1936         my $param_annotations = "";
1938         $id = &CreateValidSGMLID ($field_name);
1939         $condition = &MakeConditionDescription ($field_name);
1940         $desc .= "<varlistentry id=\"$id\" role=\"constant\"$condition>\n<term><literal>$field_name</literal></term>\n";
1941         if (defined $field_descr) {
1942             ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1943             $field_descr = &ConvertMarkDown($symbol, $field_descr);
1944             $desc .= "<listitem>$field_descr$param_annotations</listitem>\n";
1945             delete $field_descrs{$field_name};
1946         } else {
1947             if ($found) {
1948                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1949                     "Value description for $symbol"."::"."$field_name is missing in source code comment block.");
1950                 if ($missing_parameters ne "") {
1951                     $missing_parameters .= ", ".$field_name;
1952                 } else {
1953                     $missing_parameters = $field_name;
1954                 }
1955             }
1956             $desc .= "<listitem />\n";
1957         }
1958         $desc .= "</varlistentry>\n";
1959     }
1960     $desc .= "</variablelist>";
1961     foreach my $field_name (keys %field_descrs) {
1962         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1963             "Value description for $symbol"."::"."$field_name is not used from source code comment block.");
1964         if ($unused_parameters ne "") {
1965             $unused_parameters .= ", ".$field_name;
1966         } else {
1967             $unused_parameters = $field_name;
1968         }
1969     }
1971     # remember missing/unused parameters (needed in tmpl-free build)
1972     if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1973         $AllIncompleteSymbols{$symbol}=$missing_parameters;
1974     }
1975     if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1976         $AllUnusedSymbols{$symbol}=$unused_parameters;
1977     }
1979     if (!$found) {
1980         if (scalar(@fields) > 0) {
1981             if (! exists ($AllIncompleteSymbols{$symbol})) {
1982                 $AllIncompleteSymbols{$symbol}="<items>";
1983                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1984                     "Value descriptions for $symbol are missing in source code comment block.");
1985             }
1986         }
1987     }
1989     $desc .= OutputSymbolTraits ($symbol);
1990     $desc .= "</refsect2>\n";
1991     return ($synop, $desc);
1995 #############################################################################
1996 # Function    : OutputVariable
1997 # Description : Returns the synopsis and detailed description of a variable.
1998 # Arguments   : $symbol - the extern'ed variable.
1999 #                $declaration - the declaration of the variable.
2000 #############################################################################
2002 sub OutputVariable {
2003     my ($symbol, $declaration) = @_;
2004     my $id = &CreateValidSGMLID ($symbol);
2005     my $condition = &MakeConditionDescription ($symbol);
2006     
2007     @TRACE@("ouputing variable: '$symbol' '$declaration'");
2009     my $synop;
2010     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*;/) {
2011         my $mod1 = defined ($1) ? $1 : "";
2012         my $ptr = defined ($3) ? $3 : "";
2013         my $space = defined ($4) ? $4 : "";
2014         my $mod2 = defined ($5) ? $5 : "";
2015         $synop = &MakeReturnField("extern $mod1$ptr$space$mod2") . "<link linkend=\"$id\">$symbol</link>;\n";
2016     } 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*=/) {
2017         my $mod1 = defined ($1) ? $1 : "";
2018         my $ptr = defined ($3) ? $3 : "";
2019         my $space = defined ($4) ? $4 : "";
2020         my $mod2 = defined ($5) ? $5 : "";
2021         $synop = &MakeReturnField("$mod1$ptr$space$mod2") . "<link linkend=\"$id\">$symbol</link>;\n";
2023     } else {
2024         $synop = &MakeReturnField("extern") . "<link linkend=\"$id\">$symbol</link>;\n";
2025     }
2027     my $desc = "<refsect2 id=\"$id\" role=\"variable\"$condition>\n<title>$symbol</title>\n";
2029     $desc .= MakeIndexterms($symbol, $id);
2030     $desc .= "\n";
2031     $desc .= OutputSymbolExtraLinks($symbol);
2033     my $decl_out = &CreateValidSGML ($declaration);
2034     $desc .= "<programlisting>$decl_out</programlisting>\n";
2036     $desc .= &MakeDeprecationNote($symbol);
2038     if (defined ($SymbolDocs{$symbol})) {
2039         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
2040     }
2041     $desc .= OutputSymbolTraits ($symbol);
2042     $desc .= "</refsect2>\n";
2043     return ($synop, $desc);
2047 #############################################################################
2048 # Function    : OutputFunction
2049 # Description : Returns the synopsis and detailed description of a function.
2050 # Arguments   : $symbol - the function.
2051 #                $declaration - the declaration of the function.
2052 #############################################################################
2054 sub OutputFunction {
2055     my ($symbol, $declaration, $symbol_type) = @_;
2056     my $id = &CreateValidSGMLID ($symbol);
2057     my $condition = &MakeConditionDescription ($symbol);
2059     # Take out the return type     $1                                                                                       $2   $3
2060     $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//;
2061     my $type_modifier = defined($1) ? $1 : "";
2062     my $type = $2;
2063     my $pointer = $3;
2064     # Trim trailing spaces as we are going to pad to $RETURN_TYPE_FIELD_WIDTH below anyway
2065     $pointer =~ s/\s+$//;
2066     my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
2067     my $start = "";
2068     #if ($symbol_type eq 'USER_FUNCTION') {
2069     #    $start = "typedef ";
2070     #}
2072     # We output const rather than G_CONST_RETURN.
2073     $type_modifier =~ s/G_CONST_RETURN/const/g;
2074     $pointer =~ s/G_CONST_RETURN/const/g;
2075     $pointer =~ s/^\s+/ /g;
2077     my $ret_type_len = length ($start) + length ($type_modifier)+ length ($type)
2078         + length ($pointer);
2079     my $ret_type_output;
2080     my $symbol_len;
2081     if ($ret_type_len < $RETURN_TYPE_FIELD_WIDTH) {
2082         $ret_type_output = "$start$type_modifier$xref$pointer"
2083             . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
2084         $symbol_len = 0;
2085     } else {
2086         #$ret_type_output = "$start$type_modifier$xref$pointer\n" . (' ' x $RETURN_TYPE_FIELD_WIDTH);
2088         $ret_type_output = "$start$type_modifier$xref$pointer ";
2089         $symbol_len = $ret_type_len + 1 - $RETURN_TYPE_FIELD_WIDTH;
2090     }
2091     #@TRACE@("$symbol ret type output: [$ret_type_output], $ret_type_len");
2093     $symbol_len += length ($symbol);
2094     my $char1 = my $char2 = my $char3 = "";
2095     if ($symbol_type eq 'USER_FUNCTION') {
2096         $symbol_len += 3;
2097         $char1 = "(";
2098         $char2 = "*";
2099         $char3 = ")";
2100     }
2102     my ($symbol_output, $symbol_desc_output);
2103     if ($symbol_len < $SYMBOL_FIELD_WIDTH) {
2104         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3"
2105             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
2106         $symbol_desc_output = "$char1$char2$symbol$char3"
2107             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
2108     } else {
2109         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3\n"
2110             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
2111         $symbol_desc_output = "$char1$char2$symbol$char3\n"
2112             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
2113     }
2115     my $synop = $ret_type_output . $symbol_output . '(';
2116     my $desc = "<refsect2 id=\"$id\" role=\"function\"$condition>\n<title>${symbol} ()</title>\n";
2118     $desc .= MakeIndexterms($symbol, $id);
2119     $desc .= "\n";
2120     $desc .= OutputSymbolExtraLinks($symbol);
2122     $desc  .= "<programlisting>${ret_type_output}$symbol_desc_output(";
2124     my @fields = ParseFunctionDeclaration($declaration, \&MakeXRef,
2125                                         sub {
2126                                             &tagify($_[0],"parameter");
2127                                         });
2129     for (my $i = 1; $i <= $#fields; $i += 2) {
2130         my $field_name = $fields[$i];
2132         if ($i == 1) {
2133             $synop .= "$field_name";
2134             $desc  .= "$field_name";
2135         } else {
2136             $synop .= ",\n"
2137                 . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
2138                 . " $field_name";
2139             $desc  .= ",\n"
2140                 . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
2141                 . " $field_name";
2142         }
2144     }
2146     $synop .= ");\n";
2147     $desc  .= ");</programlisting>\n";
2149     $desc .= &MakeDeprecationNote($symbol);
2151     my $parameters = &OutputParamDescriptions ("FUNCTION", $symbol, @fields);
2152     my $parameters_output = 0;
2154     if (defined ($SymbolDocs{$symbol})) {
2155         my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
2157         # Try to insert the parameter table at the author's desired position.
2158         # Otherwise we need to tag it onto the end.
2159         # FIXME: document that in the user manual and make it useable for other
2160         # types too
2161         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
2162           $parameters_output = 1;
2163         }
2164         $desc .= $symbol_docs;
2165     }
2167     if ($parameters_output == 0) {
2168         $desc .= $parameters;
2169     }
2171     $desc .= OutputSymbolTraits ($symbol);
2172     $desc .= "</refsect2>\n";
2173     return ($synop, $desc);
2177 #############################################################################
2178 # Function    : OutputParamDescriptions
2179 # Description : Returns the DocBook output describing the parameters of a
2180 #                function, macro or signal handler.
2181 # Arguments   : $symbol_type - 'FUNCTION', 'MACRO' or 'SIGNAL'. Signal
2182 #                  handlers have an implicit user_data parameter last.
2183 #                $symbol - the name of the function/macro being described.
2184 #               @fields - parsed fields from the declaration, used to determine
2185 #                  undocumented/unused entries
2186 #############################################################################
2188 sub OutputParamDescriptions {
2189     my ($symbol_type, $symbol, @fields) = @_;
2190     my $output = "";
2191     my $params = $SymbolParams{$symbol};
2192     my $num_params = 0;
2193     my %field_descrs = ();
2195     if (@fields) {
2196         %field_descrs = @fields;
2197         delete $field_descrs{"void"};
2198         delete $field_descrs{"Returns"};
2199     }
2201     if (defined $params) {
2202         my $returns = "";
2203         my $params_desc = "";
2204         my $missing_parameters = "";
2205         my $unused_parameters = "";
2206         my $j;
2208         for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
2209             my $param_name = $$params[$j];
2210             my $param_desc = $$params[$j + 1];
2211             my $param_annotations = "";
2213             ($param_desc,$param_annotations) = & ExpandAnnotation($symbol, $param_desc);
2214             $param_desc = &ConvertMarkDown($symbol, $param_desc);
2215             $param_desc .= $param_annotations;
2216             # trim
2217             $param_desc =~ s/^(\s|\n)+//msg;
2218             $param_desc =~ s/(\s|\n)+$//msg;
2219             if ($param_name eq "Returns") {
2220                 $returns = "$param_desc";
2221             } elsif ($param_name eq "void") {
2222                 #print "!!!! void in params for $symbol?\n";
2223             } else {
2224                 if (@fields) {
2225                     if (!defined $field_descrs{$param_name}) {
2226                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2227                             "Parameter description for $symbol"."::"."$param_name is not used from source code comment block.");
2228                         if ($unused_parameters ne "") {
2229                           $unused_parameters .= ", ".$param_name;
2230                         } else {
2231                            $unused_parameters = $param_name;
2232                         }
2233                     } else {
2234                         delete $field_descrs{$param_name};
2235                     }
2236                 }
2237                 if($param_desc ne "") {
2238                     $params_desc .= "<varlistentry><term><parameter>$param_name</parameter>&#160;:</term>\n<listitem>$param_desc</listitem></varlistentry>\n";
2239                     $num_params++;
2240                 }
2241             }
2242         }
2243         foreach my $param_name (keys %field_descrs) {
2244             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2245                 "Parameter description for $symbol"."::"."$param_name is missing in source code comment block.");
2246             if ($missing_parameters ne "") {
2247               $missing_parameters .= ", ".$param_name;
2248             } else {
2249                $missing_parameters = $param_name;
2250             }
2251         }
2253         # Signals have an implicit user_data parameter which we describe.
2254         if ($symbol_type eq "SIGNAL") {
2255             $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";
2256         }
2258         # Start a table if we need one.
2259         if ($params_desc || $returns) {
2260             $output .= "<variablelist role=\"params\">\n";
2261             if ($params_desc ne "") {
2262                 #$output .= "<varlistentry><term>Parameters:</term><listitem></listitem></varlistentry>\n";
2263                 $output .= $params_desc;
2264             }
2266             # Output the returns info last
2267             if ($returns) {
2268                 $output .= "<varlistentry><term><emphasis>Returns</emphasis>&#160;:</term><listitem>$returns</listitem></varlistentry>\n";
2269             }
2271             # Finish the table.
2272             $output .= "</variablelist>";
2273         }
2275         # remember missing/unused parameters (needed in tmpl-free build)
2276         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
2277             $AllIncompleteSymbols{$symbol}=$missing_parameters;
2278         }
2279         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
2280             $AllUnusedSymbols{$symbol}=$unused_parameters;
2281         }
2282     }
2283     if (($num_params == 0) && @fields && (scalar(keys(%field_descrs)) > 0)) {
2284         if (! exists ($AllIncompleteSymbols{$symbol})) {
2285             $AllIncompleteSymbols{$symbol}="<parameters>";
2286         }
2287     }
2289     return $output;
2293 #############################################################################
2294 # Function    : ParseStabilityLevel
2295 # Description : Parses a stability level and outputs a warning if it isn't
2296 #               valid.
2297 # Arguments   : $stability - the stability text.
2298 #                $file, $line - context for error message
2299 #                $message - description of where the level is from, to use in
2300 #               any error message.
2301 # Returns     : The parsed stability level string.
2302 #############################################################################
2304 sub ParseStabilityLevel {
2305     my ($stability, $file, $line, $message) = @_;
2307     $stability =~ s/^\s*//;
2308     $stability =~ s/\s*$//;
2309     if ($stability =~ m/^stable$/i) {
2310         $stability = "Stable";
2311     } elsif ($stability =~ m/^unstable$/i) {
2312         $stability = "Unstable";
2313     } elsif ($stability =~ m/^private$/i) {
2314         $stability = "Private";
2315     } else {
2316         &LogWarning ($file, $line, "$message is $stability.".
2317             "It should be one of these: Stable, Unstable, or Private.");
2318     }
2319     return $stability;
2323 #############################################################################
2324 # Function    : OutputSGMLFile
2325 # Description : Outputs the final DocBook file for one section.
2326 # Arguments   : $file - the name of the file.
2327 #               $title - the title from the $MODULE-sections.txt file, which
2328 #                 will be overridden by the title in the template file.
2329 #               $section_id - the SGML id to use for the toplevel tag.
2330 #               $includes - comma-separates list of include files added at top of
2331 #                 synopsis, with '<' '>' around them (if not already enclosed in "").
2332 #               $synopsis - reference to the DocBook for the Synopsis part.
2333 #               $details - reference to the DocBook for the Details part.
2334 #               $signal_synop - reference to the DocBook for the Signal Synopsis part
2335 #               $signal_desc - reference to the DocBook for the Signal Description part
2336 #               $args_synop - reference to the DocBook for the Arg Synopsis part
2337 #               $args_desc - reference to the DocBook for the Arg Description part
2338 #               $hierarchy - reference to the DocBook for the Object Hierarchy part
2339 #               $interfaces - reference to the DocBook for the Interfaces part
2340 #               $implementations - reference to the DocBook for the Known Implementations part
2341 #               $prerequisites - reference to the DocBook for the Prerequisites part
2342 #               $derived - reference to the DocBook for the Derived Interfaces part
2343 #               $file_objects - reference to an array of objects in this file
2344 #############################################################################
2346 sub OutputSGMLFile {
2347     my ($file, $title, $section_id, $includes, $synopsis, $details, $signals_synop, $signals_desc, $args_synop, $args_desc, $hierarchy, $interfaces, $implementations, $prerequisites, $derived, $file_objects) = @_;
2349     #print "Output sgml for file $file with title '$title'\n";
2351     # The edited title overrides the one from the sections file.
2352     my $new_title = $SymbolDocs{"$TMPL_DIR/$file:Title"};
2353     if (defined ($new_title) && $new_title !~ m/^\s*$/) {
2354         $title = $new_title;
2355         #print "Found title: $title\n";
2356     }
2357     my $short_desc = $SymbolDocs{"$TMPL_DIR/$file:Short_Description"};
2358     if (!defined ($short_desc) || $short_desc =~ m/^\s*$/) {
2359         $short_desc = "";
2360     } else {
2361         # Don't use ConvertMarkDown here for now since we don't want blocks
2362         $short_desc = &ExpandAbbreviations("$title:Short_description",
2363                                            $short_desc);
2364         #print "Found short_desc: $short_desc";
2365     }
2366     my $long_desc = $SymbolDocs{"$TMPL_DIR/$file:Long_Description"};
2367     if (!defined ($long_desc) || $long_desc =~ m/^\s*$/) {
2368         $long_desc = "";
2369     } else {
2370         $long_desc = &ConvertMarkDown("$title:Long_description",
2371                                           $long_desc);
2372         #print "Found long_desc: $long_desc";
2373     }
2374     my $see_also = $SymbolDocs{"$TMPL_DIR/$file:See_Also"};
2375     if (!defined ($see_also) || $see_also =~ m%^\s*(<para>)?\s*(</para>)?\s*$%) {
2376         $see_also = "";
2377     } else {
2378         $see_also = &ConvertMarkDown("$title:See_Also", $see_also);
2379         #print "Found see_also: $see_also";
2380     }
2381     if ($see_also) {
2382         $see_also = "<refsect1 id=\"$section_id.see-also\">\n<title>See Also</title>\n$see_also\n</refsect1>\n";
2383     }
2384     my $stability = $SymbolDocs{"$TMPL_DIR/$file:Stability_Level"};
2385     if (!defined ($stability) || $stability =~ m/^\s*$/) {
2386         $stability = "";
2387     } else {
2388         $stability = &ParseStabilityLevel($stability, $file, $., "Section stability level");
2389         #print "Found stability: $stability";
2390     }
2391     if ($stability) {
2392         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$stability, unless otherwise indicated\n</refsect1>\n";
2393     } elsif ($DEFAULT_STABILITY) {
2394         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$DEFAULT_STABILITY, unless otherwise indicated\n</refsect1>\n";
2395     }
2397     my $image = $SymbolDocs{"$TMPL_DIR/$file:Image"};
2398     if (!defined ($image) || $image =~ m/^\s*$/) {
2399       $image = "";
2400     } else {
2401       $image =~ s/^\s*//;
2402       $image =~ s/\s*$//;
2404       my $format;
2406       if ($image =~ /jpe?g$/i) {
2407         $format = "format='JPEG'";
2408       } elsif ($image =~ /png$/i) {
2409         $format = "format='PNG'";
2410       } elsif ($image =~ /svg$/i) {
2411         $format = "format='SVG'";
2412       } else {
2413         $format = "";
2414       }
2416       $image = "  <inlinegraphic fileref='$image' $format/>\n"
2417     }
2419     my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
2420         gmtime (time);
2421     my $month = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))[$mon];
2422     $year += 1900;
2424     my $include_output = "";
2425     my $include;
2426     foreach $include (split (/,/, $includes)) {
2427         if ($include =~ m/^\".+\"$/) {
2428             $include_output .= "#include ${include}\n";
2429         }
2430         else {
2431             $include =~ s/^\s+|\s+$//gs;
2432             $include_output .= "#include &lt;${include}&gt;\n";
2433         }
2434     }
2435     if ($include_output ne '') {
2436         $include_output = "\n$include_output\n";
2437     }
2439     my $extralinks = OutputSectionExtraLinks($title,"Section:$file");
2441     my $old_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT";
2442     my $new_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT.new";
2444     open (OUTPUT, ">$new_sgml_file")
2445         || die "Can't create $new_sgml_file: $!";
2447     my $object_anchors = "";
2448     foreach my $object (@$file_objects) {
2449         next if ($object eq $section_id);
2450         my $id = CreateValidSGMLID($object);
2451         #print "Debug: Adding anchor for $object\n";
2452         $object_anchors .= "<anchor id=\"$id\"$empty_element_end";
2453     }
2455     # We used to output this, but is messes up our UpdateFileIfChanged code
2456     # since it changes every day (and it is only used in the man pages):
2457     # "<refentry id="$section_id" revision="$mday $month $year">"
2459     if ($OUTPUT_FORMAT eq "xml") {
2460         print OUTPUT $doctype_header;
2461     }
2463     print OUTPUT <<EOF;
2464 <refentry id="$section_id">
2465 <refmeta>
2466 <refentrytitle role="top_of_page" id="$section_id.top_of_page">$title</refentrytitle>
2467 <manvolnum>3</manvolnum>
2468 <refmiscinfo>
2469   \U$MODULE\E Library
2470 $image</refmiscinfo>
2471 </refmeta>
2472 <refnamediv>
2473 <refname>$title</refname>
2474 <refpurpose>$short_desc</refpurpose>
2475 </refnamediv>
2476 $stability
2477 <refsynopsisdiv id="$section_id.synopsis" role="synopsis">
2478 <title role="synopsis.title">Synopsis</title>
2479 $object_anchors
2480 <synopsis>$include_output$${synopsis}</synopsis>
2481 </refsynopsisdiv>
2482 $$hierarchy$$prerequisites$$derived$$interfaces$$implementations$$args_synop$$signals_synop
2483 <refsect1 id="$section_id.description" role="desc">
2484 <title role="desc.title">Description</title>
2485 $extralinks$long_desc
2486 </refsect1>
2487 <refsect1 id="$section_id.details" role="details">
2488 <title role="details.title">Details</title>
2489 $$details
2490 </refsect1>
2491 $$args_desc$$signals_desc$see_also
2492 </refentry>
2494     close (OUTPUT);
2496     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2500 #############################################################################
2501 # Function    : OutputExtraFile
2502 # Description : Copies an "extra" DocBook file into the output directory,
2503 #               expanding abbreviations
2504 # Arguments   : $file - the source file.
2505 #############################################################################
2506 sub OutputExtraFile {
2507     my ($file) = @_;
2509     my $basename;
2511     ($basename = $file) =~ s!^.*/!!;
2513     my $old_sgml_file = "$SGML_OUTPUT_DIR/$basename";
2514     my $new_sgml_file = "$SGML_OUTPUT_DIR/$basename.new";
2516     my $contents;
2518     open(EXTRA_FILE, "<$file") || die "Can't open $file";
2520     {
2521         local $/;
2522         $contents = <EXTRA_FILE>;
2523     }
2525     open (OUTPUT, ">$new_sgml_file")
2526         || die "Can't create $new_sgml_file: $!";
2528     print OUTPUT &ExpandAbbreviations ("$basename file", $contents);
2529     close (OUTPUT);
2531     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2533 #############################################################################
2534 # Function    : OutputBook
2535 # Description : Outputs the SGML entities that need to be included into the
2536 #                main SGML file for the module.
2537 # Arguments   : $book_top - the declarations of the entities, which are added
2538 #                  at the top of the main SGML file.
2539 #                $book_bottom - the references to the entities, which are
2540 #                  added in the main SGML file at the desired position.
2541 #############################################################################
2543 sub OutputBook {
2544     my ($book_top, $book_bottom) = @_;
2546     my $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top";
2547     my $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top.new";
2549     open (OUTPUT, ">$new_file")
2550         || die "Can't create $new_file: $!";
2551     print OUTPUT $book_top;
2552     close (OUTPUT);
2554     &UpdateFileIfChanged ($old_file, $new_file, 0);
2557     $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom";
2558     $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom.new";
2560     open (OUTPUT, ">$new_file")
2561         || die "Can't create $new_file: $!";
2562     print OUTPUT $book_bottom;
2563     close (OUTPUT);
2565     &UpdateFileIfChanged ($old_file, $new_file, 0);
2568     # If the main SGML/XML file hasn't been created yet, we create it here.
2569     # The user can tweak it later.
2570     if ($MAIN_SGML_FILE && ! -e $MAIN_SGML_FILE) {
2571       open (OUTPUT, ">$MAIN_SGML_FILE")
2572         || die "Can't create $MAIN_SGML_FILE: $!";
2574       if ($OUTPUT_FORMAT eq "xml") {
2575           print OUTPUT <<EOF;
2576 <?xml version="1.0"?>
2577 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
2578                "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd"
2580   <!ENTITY % local.common.attrib "xmlns:xi  CDATA  #FIXED 'http://www.w3.org/2003/XInclude'">
2582 <book id="index">
2584       } else {
2585         print OUTPUT <<EOF;
2586 <!doctype book PUBLIC "-//Davenport//DTD DocBook V3.0//EN" [
2587 $book_top
2589 <book id="index">
2591       }
2593 print OUTPUT <<EOF;
2594   <bookinfo>
2595     <title>$MODULE Reference Manual</title>
2596     <releaseinfo>
2597       for $MODULE [VERSION].
2598       The latest version of this documentation can be found on-line at
2599       <ulink role="online-location" url="http://[SERVER]/$MODULE/index.html">http://[SERVER]/$MODULE/</ulink>.
2600     </releaseinfo>
2601   </bookinfo>
2603   <chapter>
2604     <title>[Insert title here]</title>
2605     $book_bottom
2606   </chapter>
2608   if (-e $OBJECT_TREE_FILE) {
2609     print OUTPUT <<EOF;
2610   <chapter id="object-tree">
2611     <title>Object Hierarchy</title>
2612      <xi:include href="xml/tree_index.sgml"/>
2613   </chapter>
2615   }
2617 print OUTPUT <<EOF;
2618   <index id="api-index-full">
2619     <title>API Index</title>
2620     <xi:include href="xml/api-index-full.xml"><xi:fallback /></xi:include>
2621   </index>
2622   <index id="deprecated-api-index" role="deprecated">
2623     <title>Index of deprecated API</title>
2624     <xi:include href="xml/api-index-deprecated.xml"><xi:fallback /></xi:include>
2625   </index>
2627   <xi:include href="xml/annotation-glossary.xml"><xi:fallback /></xi:include>
2628 </book>
2631       close (OUTPUT);
2632     }
2636 #############################################################################
2637 # Function    : CreateValidSGML
2638 # Description : This turns any chars which are used in SGML into entities,
2639 #                e.g. '<' into '&lt;'
2640 # Arguments   : $text - the text to turn into proper SGML.
2641 #############################################################################
2643 sub CreateValidSGML {
2644     my ($text) = @_;
2645     $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2646     $text =~ s/</&lt;/g;
2647     $text =~ s/>/&gt;/g;
2648     # browers render single tabs inconsistently
2649     $text =~ s/([^\s])\t([^\s])/$1&#160;$2/g;
2650     return $text;
2653 #############################################################################
2654 # Function    : ConvertSGMLChars
2655 # Description : This is used for text in source code comment blocks, to turn
2656 #               chars which are used in SGML into entities, e.g. '<' into
2657 #               '&lt;'. Depending on $INLINE_MARKUP_MODE, this is done
2658 #               unconditionally or only if the character doesn't seem to be
2659 #               part of an SGML construct (tag or entity reference).
2660 # Arguments   : $text - the text to turn into proper SGML.
2661 #############################################################################
2663 sub ConvertSGMLChars {
2664     my ($symbol, $text) = @_;
2666     if ($INLINE_MARKUP_MODE) {
2667         # For the XML/SGML mode only convert to entities outside CDATA sections.
2668         return &ModifyXMLElements ($text, $symbol,
2669                                    "<!\\[CDATA\\[|<programlisting[^>]*>",
2670                                    \&ConvertSGMLCharsEndTag,
2671                                    \&ConvertSGMLCharsCallback);
2672     } else {
2673         # For the simple non-sgml mode, convert to entities everywhere.
2674         $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2675         $text =~ s/</&lt;/g;
2676         $text =~ s/>/&gt;/g;
2677         return $text;
2678     }
2682 sub ConvertSGMLCharsEndTag {
2683   if ($_[0] eq "<!\[CDATA\[") {
2684     return "]]>";
2685   } else {
2686     return "</programlisting>";
2687   }
2690 sub ConvertSGMLCharsCallback {
2691   my ($text, $symbol, $tag) = @_;
2693   if ($tag =~ m/^<programlisting/) {
2694     # We can handle <programlisting> specially here.
2695     return &ModifyXMLElements ($text, $symbol,
2696                                "<!\\[CDATA\\[",
2697                                \&ConvertSGMLCharsEndTag,
2698                                \&ConvertSGMLCharsCallback2);
2699   } elsif ($tag eq "") {
2700     # If we're not in CDATA convert to entities.
2701     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2702     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2703     # Allow ">" at beginning of string for blockquote markdown
2704     $text =~ s/(?<=[^\w\n"'\/-])>/&gt;/g;
2706     # Handle "#include <xxxxx>"
2707     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2708   }
2710   return $text;
2713 sub ConvertSGMLCharsCallback2 {
2714   my ($text, $symbol, $tag) = @_;
2716   # If we're not in CDATA convert to entities.
2717   # We could handle <programlisting> differently, though I'm not sure it helps.
2718   if ($tag eq "") {
2719     # replace only if its not a tag
2720     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2721     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2722     $text =~ s/(?<![a-zA-Z0-9"'\/-])>/&gt;/g;
2724     # Handle "#include <xxxxx>"
2725     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2726   }
2728   return $text;
2731 #############################################################################
2732 # Function    : ExpandAnnotation
2733 # Description : This turns annotations into acronym tags.
2734 # Arguments   : $symbol - the symbol being documented, for error messages.
2735 #                $text - the text to expand.
2736 #############################################################################
2737 sub ExpandAnnotation {
2738     my ($symbol, $param_desc) = @_;
2739     my $param_annotations = "";
2741     # look for annotations at the start of the comment part
2742     if ($param_desc =~ m%^\s*\((.*?)\):%) {
2743         my @annotations;
2744         my $annotation;
2745         $param_desc = $';
2747         @annotations = split(/\)\s*\(/,$1);
2748         foreach $annotation (@annotations) {
2749             # need to search for the longest key-match in %AnnotationDefinition
2750             my $match_length=0;
2751             my $match_annotation="";
2752             my $annotationdef;
2753             foreach $annotationdef (keys %AnnotationDefinition) {
2754                 if ($annotation =~ m/^$annotationdef/) {
2755                     if (length($annotationdef)>$match_length) {
2756                         $match_length=length($annotationdef);
2757                         $match_annotation=$annotationdef;
2758                     }
2759                 }
2760             }
2761             my $annotation_extra = "";
2762             if ($match_annotation ne "") {
2763                 if ($annotation =~ m%$match_annotation\s+(.*)%) {
2764                     $annotation_extra = " $1";
2765                 }
2766                 $AnnotationsUsed{$match_annotation} = 1;
2767                 $param_annotations .= "[<acronym>$match_annotation</acronym>$annotation_extra]";
2768             }
2769             else {
2770                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2771                     "unknown annotation \"$annotation\" in documentation for $symbol.");
2772                 $param_annotations .= "[$annotation]";
2773             }
2774         }
2775         chomp($param_desc);
2776         $param_desc =~ m/^(.*?)\.*\s*$/s;
2777         $param_desc = "$1. ";
2778     }
2779     if ($param_annotations ne "") {
2780         $param_annotations = "<emphasis role=\"annotation\">$param_annotations</emphasis>";
2781     }
2782     return ($param_desc, $param_annotations);
2785 #############################################################################
2786 # Function    : ExpandAbbreviations
2787 # Description : This turns the abbreviations function(), macro(), @param,
2788 #                %constant, and #symbol into appropriate DocBook markup.
2789 #               CDATA sections and <programlisting> parts are skipped.
2790 # Arguments   : $symbol - the symbol being documented, for error messages.
2791 #                $text - the text to expand.
2792 #############################################################################
2794 sub ExpandAbbreviations {
2795   my ($symbol, $text) = @_;
2797   # Note: This is a fallback and normally done in the markdown parser
2799   # Convert "|[" and "]|" into the start and end of program listing examples.
2800   # Support \[<!-- language="C" --> modifiers
2801   $text =~ s%\|\[<!-- language="([^"]+)" -->%<informalexample><programlisting language="$1"><![CDATA[%g;
2802   $text =~ s%\|\[%<informalexample><programlisting><![CDATA[%g;
2803   $text =~ s%\]\|%]]></programlisting></informalexample>%g;
2805   # keep CDATA unmodified, preserve ulink tags (ideally we preseve all tags
2806   # as such)
2807   return &ModifyXMLElements ($text, $symbol,
2808                              "<!\\[CDATA\\[|<ulink[^>]*>|<programlisting[^>]*>|<!DOCTYPE",
2809                              \&ExpandAbbreviationsEndTag,
2810                              \&ExpandAbbreviationsCallback);
2814 # Returns the end tag (as a regexp) corresponding to the given start tag.
2815 sub ExpandAbbreviationsEndTag {
2816   my ($start_tag) = @_;
2818   if ($start_tag eq "<!\[CDATA\[") {
2819     return "]]>";
2820   } elsif ($start_tag eq "<!DOCTYPE") {
2821     return ">";
2822   } elsif ($start_tag =~ m/<(\w+)/) {
2823     return "</$1>";
2824   }
2827 # Called inside or outside each CDATA or <programlisting> section.
2828 sub ExpandAbbreviationsCallback {
2829   my ($text, $symbol, $tag) = @_;
2831   if ($tag =~ m/^<programlisting/) {
2832     # Handle any embedded CDATA sections.
2833     return &ModifyXMLElements ($text, $symbol,
2834                                "<!\\[CDATA\\[",
2835                                \&ExpandAbbreviationsEndTag,
2836                                \&ExpandAbbreviationsCallback2);
2837   } elsif ($tag eq "") {
2838     # NOTE: this is a fallback. It is normally done by the Markdown parser.
2840     # We are outside any CDATA or <programlisting> sections, so we expand
2841     # any gtk-doc abbreviations.
2843     # Convert '@param()'
2844     # FIXME: we could make those also links ($symbol.$2), but that would be less
2845     # useful as the link target is a few lines up or down
2846     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)/$1<parameter>$2()<\/parameter>/g;
2848     # Convert 'function()' or 'macro()'.
2849     # if there is abc_*_def() we don't want to make a link to _def()
2850     # FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
2851     $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2852     # handle #Object.func()
2853     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2855     # Convert '@param', but not '\@param'.
2856     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)/$1<parameter>$2<\/parameter>/g;
2857     $text =~ s/\\\@/\@/g;
2859     # Convert '%constant', but not '\%constant'.
2860     # Also allow negative numbers, e.g. %-1.
2861     $text =~ s/(\A|[^\\])\%(-?\w+)/$1.&MakeXRef($2, &tagify($2, "literal"));/eg;
2862     $text =~ s/\\\%/\%/g;
2864     # Convert '#symbol', but not '\#symbol'.
2865     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)/$1.&MakeHashXRef($2, "type");/eg;
2866     $text =~ s/\\#/#/g;
2867   }
2869   return $text;
2872 # This is called inside a <programlisting>
2873 sub ExpandAbbreviationsCallback2 {
2874   my ($text, $symbol, $tag) = @_;
2876   if ($tag eq "") {
2877     # We are inside a <programlisting> but outside any CDATA sections,
2878     # so we expand any gtk-doc abbreviations.
2879     # FIXME: why is this different from &ExpandAbbreviationsCallback(),
2880     #        why not just call it
2881     $text =~ s/#(\w+)/&MakeHashXRef($1, "");/eg;
2882   } elsif ($tag eq "<![CDATA[") {
2883     # NOTE: this is a fallback. It is normally done by the Markdown parser.
2884     $text = &ReplaceEntities ($text, $symbol);
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     if (exists $Deprecated{$symbol}) {
3077         my $note;
3079         $desc .= "<warning><para><literal>$symbol</literal> ";
3081         $note = $Deprecated{$symbol};
3083         if ($note =~ /^\s*([0-9\.]+)\s*:?/) {
3084                 $desc .= "has been deprecated since version $1 and should not be used in newly-written code.</para>";
3085         } else {
3086                 $desc .= "is deprecated and should not be used in newly-written code.</para>";
3087         }
3088         $note =~ s/^\s*([0-9\.]+)\s*:?\s*//;
3089         $note =~ s/^\s+//;
3090         $note =~ s/\s+$//;
3091         if ($note ne "") {
3092             $note = &ConvertMarkDown($symbol, $note);
3093             $desc .= " " . $note;
3094         }
3095         $desc .= "</warning>\n";
3096     }
3097     return $desc;
3100 #############################################################################
3101 # Function    : MakeConditionDescription
3102 # Description : This returns a sumary of conditions for the given symbol.
3103 # Arguments   : $symbol - the symbol to try to create the sumary.
3104 #############################################################################
3106 sub MakeConditionDescription {
3107     my ($symbol) = $_[0];
3108     my $desc = "";
3110     if (exists $Deprecated{$symbol}) {
3111         if ($desc ne "") {
3112             $desc .= "|";
3113         }
3115         if ($Deprecated{$symbol} =~ /^\s*(.*?)\s*$/) {
3116                 $desc .= "deprecated:$1";
3117         } else {
3118                 $desc .= "deprecated";
3119         }
3120     }
3122     if (exists $Since{$symbol}) {
3123         if ($desc ne "") {
3124             $desc .= "|";
3125         }
3127         if ($Since{$symbol} =~ /^\s*(.*?)\s*$/) {
3128                 $desc .= "since:$1";
3129         } else {
3130                 $desc .= "since";
3131         }
3132     }
3134     if (exists $StabilityLevel{$symbol}) {
3135         if ($desc ne "") {
3136             $desc .= "|";
3137         }
3138         $desc .= "stability:".$StabilityLevel{$symbol};
3139     }
3141     if ($desc ne "") {
3142         my $cond = $desc;
3143         $cond =~ s/\"/&quot;/g;
3144         $desc=" condition=\"".$cond."\"";
3145         #print "condition for '$symbol' = '$desc'\n";
3146     }
3147     return $desc;
3150 #############################################################################
3151 # Function    : GetHierarchy
3152 # Description : Returns the DocBook output describing the ancestors and
3153 #               immediate children of a GObject subclass. It uses the
3154 #               global @Objects and @ObjectLevels arrays to walk the tree.
3155 # Arguments   : $object - the GtkObject subclass.
3156 #############################################################################
3158 sub GetHierarchy {
3159     my ($object) = @_;
3161     # Find object in the objects array.
3162     my $found = 0;
3163     my @children = ();
3164     my $i;
3165     my $level;
3166     my $j;
3167     for ($i = 0; $i < @Objects; $i++) {
3168         if ($found) {
3169             if ($ObjectLevels[$i] <= $level) {
3170             last;
3171         }
3172             elsif ($ObjectLevels[$i] == $level + 1) {
3173                 push (@children, $Objects[$i]);
3174             }
3175         }
3176         elsif ($Objects[$i] eq $object) {
3177             $found = 1;
3178             $j = $i;
3179             $level = $ObjectLevels[$i];
3180         }
3181     }
3182     if (!$found) {
3183         return "";
3184     }
3186     # Walk up the hierarchy, pushing ancestors onto the ancestors array.
3187     my @ancestors = ();
3188     push (@ancestors, $object);
3189     #print "Level: $level\n";
3190     while ($level > 1) {
3191         $j--;
3192         if ($ObjectLevels[$j] < $level) {
3193             push (@ancestors, $Objects[$j]);
3194             $level = $ObjectLevels[$j];
3195             #print "Level: $level\n";
3196         }
3197     }
3199     # Output the ancestors list, indented and with links.
3200     my $hierarchy = "<synopsis>\n";
3201     $level = 0;
3202     for ($i = $#ancestors; $i >= 0; $i--) {
3203         my $link_text;
3204         # Don't add a link to the current object, i.e. when i == 0.
3205         if ($i > 0) {
3206             my $ancestor_id = &CreateValidSGMLID ($ancestors[$i]);
3207             $link_text = "<link linkend=\"$ancestor_id\">$ancestors[$i]</link>";
3208         } else {
3209             $link_text = "$ancestors[$i]";
3210         }
3211         if ($level == 0) {
3212             $hierarchy .= "  $link_text\n";
3213         } else {
3214 #            $hierarchy .= ' ' x ($level * 6 - 3) . "|\n";
3215             $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
3216         }
3217         $level++;
3218     }
3219     for ($i = 0; $i <= $#children; $i++) {
3220       my $id = &CreateValidSGMLID ($children[$i]);
3221       my $link_text = "<link linkend=\"$id\">$children[$i]</link>";
3222       $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
3223     }
3224     $hierarchy .= "</synopsis>\n";
3226     return $hierarchy;
3230 #############################################################################
3231 # Function    : GetInterfaces
3232 # Description : Returns the DocBook output describing the interfaces
3233 #               implemented by a class. It uses the global %Interfaces hash.
3234 # Arguments   : $object - the GtkObject subclass.
3235 #############################################################################
3237 sub GetInterfaces {
3238     my ($object) = @_;
3239     my $text = "";
3240     my $i;
3242     # Find object in the objects array.
3243     if (exists($Interfaces{$object})) {
3244         my @ifaces = split(' ', $Interfaces{$object});
3245         $text = <<EOF;
3246 <para>
3247 $object implements
3249         for ($i = 0; $i <= $#ifaces; $i++) {
3250             my $id = &CreateValidSGMLID ($ifaces[$i]);
3251             $text .= " <link linkend=\"$id\">$ifaces[$i]</link>";
3252             if ($i < $#ifaces - 1) {
3253                 $text .= ', ';
3254             }
3255             elsif ($i < $#ifaces) {
3256                 $text .= ' and ';
3257             }
3258             else {
3259                 $text .= '.';
3260             }
3261         }
3262         $text .= <<EOF;
3263 </para>
3265     }
3267     return $text;
3270 #############################################################################
3271 # Function    : GetImplementations
3272 # Description : Returns the DocBook output describing the implementations
3273 #               of an interface. It uses the global %Interfaces hash.
3274 # Arguments   : $object - the GtkObject subclass.
3275 #############################################################################
3277 sub GetImplementations {
3278     my ($object) = @_;
3279     my @impls = ();
3280     my $text = "";
3281     my $i;
3282     foreach my $key (keys %Interfaces) {
3283         if ($Interfaces{$key} =~ /\b$object\b/) {
3284             push (@impls, $key);
3285         }
3286     }
3287     if ($#impls >= 0) {
3288         @impls = sort @impls;
3289         $text = <<EOF;
3290 <para>
3291 $object is implemented by
3293         for ($i = 0; $i <= $#impls; $i++) {
3294             my $id = &CreateValidSGMLID ($impls[$i]);
3295             $text .= " <link linkend=\"$id\">$impls[$i]</link>";
3296             if ($i < $#impls - 1) {
3297                 $text .= ', ';
3298             }
3299             elsif ($i < $#impls) {
3300                 $text .= ' and ';
3301             }
3302             else {
3303                 $text .= '.';
3304             }
3305         }
3306         $text .= <<EOF;
3307 </para>
3309     }
3310     return $text;
3314 #############################################################################
3315 # Function    : GetPrerequisites
3316 # Description : Returns the DocBook output describing the prerequisites
3317 #               of an interface. It uses the global %Prerequisites hash.
3318 # Arguments   : $iface - the interface.
3319 #############################################################################
3321 sub GetPrerequisites {
3322     my ($iface) = @_;
3323     my $text = "";
3324     my $i;
3326     if (exists($Prerequisites{$iface})) {
3327         $text = <<EOF;
3328 <para>
3329 $iface requires
3331         my @prereqs = split(' ', $Prerequisites{$iface});
3332         for ($i = 0; $i <= $#prereqs; $i++) {
3333             my $id = &CreateValidSGMLID ($prereqs[$i]);
3334             $text .= " <link linkend=\"$id\">$prereqs[$i]</link>";
3335             if ($i < $#prereqs - 1) {
3336                 $text .= ', ';
3337             }
3338             elsif ($i < $#prereqs) {
3339                 $text .= ' and ';
3340             }
3341             else {
3342                 $text .= '.';
3343             }
3344         }
3345         $text .= <<EOF;
3346 </para>
3348     }
3349     return $text;
3352 #############################################################################
3353 # Function    : GetDerived
3354 # Description : Returns the DocBook output describing the derived interfaces
3355 #               of an interface. It uses the global %Prerequisites hash.
3356 # Arguments   : $iface - the interface.
3357 #############################################################################
3359 sub GetDerived {
3360     my ($iface) = @_;
3361     my $text = "";
3362     my $i;
3364     my @derived = ();
3365     foreach my $key (keys %Prerequisites) {
3366         if ($Prerequisites{$key} =~ /\b$iface\b/) {
3367             push (@derived, $key);
3368         }
3369     }
3370     if ($#derived >= 0) {
3371         @derived = sort @derived;
3372         $text = <<EOF;
3373 <para>
3374 $iface is required by
3376         for ($i = 0; $i <= $#derived; $i++) {
3377             my $id = &CreateValidSGMLID ($derived[$i]);
3378             $text .= " <link linkend=\"$id\">$derived[$i]</link>";
3379             if ($i < $#derived - 1) {
3380                 $text .= ', ';
3381             }
3382             elsif ($i < $#derived) {
3383                 $text .= ' and ';
3384             }
3385             else {
3386                 $text .= '.';
3387             }
3388         }
3389         $text .= <<EOF;
3390 </para>
3392     }
3393     return $text;
3397 #############################################################################
3398 # Function    : GetSignals
3399 # Description : Returns the synopsis and detailed description DocBook output
3400 #                for the signal handlers of a given GtkObject subclass.
3401 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3402 #############################################################################
3404 sub GetSignals {
3405     my ($object) = @_;
3406     my $synop = "";
3407     my $desc = "";
3409     my $i;
3410     for ($i = 0; $i <= $#SignalObjects; $i++) {
3411         if ($SignalObjects[$i] eq $object) {
3412             #print "Found signal: $SignalNames[$i]\n";
3413             my $name = $SignalNames[$i];
3414             my $symbol = "${object}::${name}";
3415             my $id = &CreateValidSGMLID ("$object-$name");
3417             my $pad = ' ' x (46 - length($name));
3418             $synop .= "  &quot;<link linkend=\"$id\">$name</link>&quot;$pad ";
3420             $desc .= "<refsect2 id=\"$id\" role=\"signal\"><title>The <literal>&quot;$name&quot;</literal> signal</title>\n";
3421             $desc .= MakeIndexterms($symbol, $id);
3422             $desc .= "\n";
3423             $desc .= OutputSymbolExtraLinks($symbol);
3425             $desc .= "<programlisting>";
3427             $SignalReturns[$i] =~ m/\s*(const\s+)?(\w+)\s*(\**)/;
3428             my $type_modifier = defined($1) ? $1 : "";
3429             my $type = $2;
3430             my $pointer = $3;
3431             my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
3433             my $ret_type_len = length ($type_modifier) + length ($pointer)
3434                 + length ($type);
3435             my $ret_type_output = "$type_modifier$xref$pointer"
3436                 . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
3438             $desc  .= "${ret_type_output}user_function " . &MakeReturnField("") . " (";
3440             my $sourceparams = $SourceSymbolParams{$symbol};
3441             my @params = split ("\n", $SignalPrototypes[$i]);
3442             my $j;
3443             my $l;
3444             my $type_len = length("gpointer");
3445             my $name_len = length("user_data");
3446             # do two passes, the first one is to calculate padding
3447             for ($l = 0; $l < 2; $l++) {
3448                 for ($j = 0; $j <= $#params; $j++) {
3449                     # allow alphanumerics, '_', '[' & ']' in param names
3450                     if ($params[$j] =~ m/^\s*(\w+)\s*(\**)\s*([\w\[\]]+)\s*$/) {
3451                         $type = $1;
3452                         $pointer = $2;
3453                         if (defined($sourceparams)) {
3454                             $name = $$sourceparams[$PARAM_FIELD_COUNT * $j];
3455                         }
3456                         else {
3457                             $name = $3;
3458                         }
3459                         if (!defined($name)) {
3460                             $name = "arg$j";
3461                         }
3462                         if ($l == 0) {
3463                             if (length($type) + length($pointer) > $type_len) {
3464                                 $type_len = length($type) + length($pointer);
3465                             }
3466                             if (length($name) > $name_len) {
3467                                 $name_len = length($name);
3468                             }
3469                         }
3470                         else {
3471                             $xref = &MakeXRef ($type, &tagify($type, "type"));
3472                             $pad = ' ' x ($type_len - length($type) - length($pointer));
3473                             $desc .= "$xref$pad $pointer$name,\n";
3474                             $desc .= (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
3475                         }
3476                     } else {
3477                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
3478                              "Can't parse arg: $params[$j]\nArgs:$SignalPrototypes[$i]");
3479                     }
3480                 }
3481             }
3482             $xref = &MakeXRef ("gpointer", &tagify("gpointer", "type"));
3483             $pad = ' ' x ($type_len - length("gpointer"));
3484             $desc  .= "$xref$pad user_data)";
3486             my $flags = $SignalFlags[$i];
3487             my $flags_string = "";
3489             if (defined ($flags)) {
3490               if ($flags =~ m/f/) {
3491                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-FIRST:CAPS\"><literal>Run First</literal></link>";
3492               }
3493               elsif ($flags =~ m/l/) {
3494                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-LAST:CAPS\"><literal>Run Last</literal></link>";
3495               }
3496               elsif ($flags =~ m/c/) {
3497                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-CLEANUP:CAPS\"><literal>Cleanup</literal></link>";
3498                 $flags_string = "Cleanup";
3499               }
3500               if ($flags =~ m/r/) {
3501                 if ($flags_string) { $flags_string .= " / "; }
3502                 $flags_string = "<link linkend=\"G-SIGNAL-NO-RECURSE:CAPS\"><literal>No Recursion</literal></link>";
3503               }
3504               if ($flags =~ m/d/) {
3505                 if ($flags_string) { $flags_string .= " / "; }
3506                 $flags_string = "<link linkend=\"G-SIGNAL-DETAILED:CAPS\"><literal>Has Details</literal></link>";
3507               }
3508               if ($flags =~ m/a/) {
3509                 if ($flags_string) { $flags_string .= " / "; }
3510                 $flags_string = "<link linkend=\"G-SIGNAL-ACTION:CAPS\"><literal>Action</literal></link>";
3511               }
3512               if ($flags =~ m/h/) {
3513                 if ($flags_string) { $flags_string .= " / "; }
3514                 $flags_string = "<link linkend=\"G-SIGNAL-NO-HOOKS:CAPS\"><literal>No Hooks</literal></link>";
3515               }
3516             }
3518             if ($flags_string)
3519               {
3520                 $synop .= ": $flags_string\n";
3522                 $pad = ' ' x (5 + $name_len - length("user_data"));
3523                 $desc  .= "$pad : $flags_string</programlisting>\n";
3524               }
3525             else
3526               {
3527                 $synop .= "\n";
3528                 $desc  .= "</programlisting>\n";
3529               }
3531             $desc .= &MakeDeprecationNote($symbol);
3533             my $parameters = &OutputParamDescriptions ("SIGNAL", $symbol);
3534             my $parameters_output = 0;
3536             $AllSymbols{$symbol} = 1;
3537             if (defined ($SymbolDocs{$symbol})) {
3538                 my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
3540                 # Try to insert the parameter table at the author's desired
3541                 # position. Otherwise we need to tag it onto the end.
3542                 if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
3543                   $parameters_output = 1;
3544                 }
3545                 $desc .= $symbol_docs;
3547                 if (!IsEmptyDoc($SymbolDocs{$symbol})) {
3548                     $AllDocumentedSymbols{$symbol} = 1;
3549                 }
3550             }
3552             if ($parameters_output == 0) {
3553                 $desc .= $parameters;
3554               }
3555             $desc .= OutputSymbolTraits ($symbol);
3556             $desc .= "</refsect2>";
3557         }
3558     }
3559     return ($synop, $desc);
3563 #############################################################################
3564 # Function    : GetArgs
3565 # Description : Returns the synopsis and detailed description DocBook output
3566 #                for the Args of a given GtkObject subclass.
3567 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3568 #############################################################################
3570 sub GetArgs {
3571     my ($object) = @_;
3572     my $synop = "";
3573     my $desc = "";
3574     my $child_synop = "";
3575     my $child_desc = "";
3576     my $style_synop = "";
3577     my $style_desc = "";
3579     my $i;
3580     for ($i = 0; $i <= $#ArgObjects; $i++) {
3581         if ($ArgObjects[$i] eq $object) {
3582             #print "Found arg: $ArgNames[$i]\n";
3583             my $name = $ArgNames[$i];
3584             my $flags = $ArgFlags[$i];
3585             my $flags_string = "";
3586             my $kind = "";
3587             my $id_sep = "";
3589             if ($flags =~ m/c/) {
3590                 $kind = "child property";
3591                 $id_sep = "c-";
3592             }
3593             elsif ($flags =~ m/s/) {
3594                 $kind = "style property";
3595                 $id_sep = "s-";
3596             }
3597             else {
3598                 $kind = "property";
3599             }
3601             # Remember only one colon so we don't clash with signals.
3602             my $symbol = "${object}:${name}";
3603             # use two dashes and ev. an extra separator here for the same reason.
3604             my $id = &CreateValidSGMLID ("$object--$id_sep$name");
3606             my $type = $ArgTypes[$i];
3607             my $type_output;
3608             my $range = $ArgRanges[$i];
3609             my $range_output = CreateValidSGML ($range);
3610             my $default = $ArgDefaults[$i];
3611             my $default_output = CreateValidSGML ($default);
3613             if ($type eq "GtkString") {
3614                 $type = "char*";
3615             }
3616             if ($type eq "GtkSignal") {
3617                 $type = "GtkSignalFunc, gpointer";
3618                 $type_output = &MakeXRef ("GtkSignalFunc") . ", "
3619                     . &MakeXRef ("gpointer");
3620             } elsif ($type =~ m/^(\w+)\*$/) {
3621                 $type_output = &MakeXRef ($1, &tagify($1, "type")) . "*";
3622             } else {
3623                 $type_output = &MakeXRef ($type, &tagify($type, "type"));
3624             }
3626             if ($flags =~ m/r/) {
3627                 $flags_string = "Read";
3628             }
3629             if ($flags =~ m/w/) {
3630                 if ($flags_string) { $flags_string .= " / "; }
3631                 $flags_string .= "Write";
3632             }
3633             if ($flags =~ m/x/) {
3634                 if ($flags_string) { $flags_string .= " / "; }
3635                 $flags_string .= "Construct";
3636             }
3637             if ($flags =~ m/X/) {
3638                 if ($flags_string) { $flags_string .= " / "; }
3639                 $flags_string .= "Construct Only";
3640             }
3642             $AllSymbols{$symbol} = 1;
3643             my $blurb;
3644             if (defined($SymbolDocs{$symbol}) &&
3645                 !IsEmptyDoc($SymbolDocs{$symbol})) {
3646                 $blurb = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
3647                 #print ".. [$SymbolDocs{$symbol}][$blurb]\n";
3648                 $AllDocumentedSymbols{$symbol} = 1;
3649             }
3650             else {
3651                 if (!($ArgBlurbs[$i] eq "")) {
3652                     $AllDocumentedSymbols{$symbol} = 1;
3653                 } else {
3654                     # FIXME: print a warning?
3655                     #print ".. no description\n";
3656                 }
3657                 $blurb = "<para>" . &CreateValidSGML ($ArgBlurbs[$i]) . "</para>";
3658             }
3660             my $pad1 = " " x (24 - length ($name));
3661             my $pad2 = " " x (20 - length ($type));
3663              my $arg_synop = "  &quot;<link linkend=\"$id\">$name</link>&quot;$pad1 $type_output $pad2 : $flags_string\n";
3664             my $arg_desc = "<refsect2 id=\"$id\" role=\"property\"><title>The <literal>&quot;$name&quot;</literal> $kind</title>\n";
3665             $arg_desc .= MakeIndexterms($symbol, $id);
3666             $arg_desc .= "\n";
3667             $arg_desc .= OutputSymbolExtraLinks($symbol);
3669             $arg_desc .= "<programlisting>  &quot;$name&quot;$pad1 $type_output $pad2 : $flags_string</programlisting>\n";
3670             $arg_desc .= &MakeDeprecationNote($symbol);
3671             $arg_desc .= $blurb;
3672             if ($range ne "") {
3673                 $arg_desc .= "<para>Allowed values: $range_output</para>\n";
3674             }
3675             if ($default ne "") {
3676                 $arg_desc .= "<para>Default value: $default_output</para>\n";
3677             }
3678             $arg_desc .= OutputSymbolTraits ($symbol);
3679             $arg_desc .= "</refsect2>\n";
3681             if ($flags =~ m/c/) {
3682                 $child_synop .= $arg_synop;
3683                 $child_desc .= $arg_desc;
3684             }
3685             elsif ($flags =~ m/s/) {
3686                 $style_synop .= $arg_synop;
3687                 $style_desc .= $arg_desc;
3688             }
3689             else {
3690                 $synop .= $arg_synop;
3691                 $desc .= $arg_desc;
3692             }
3693         }
3694     }
3695     return ($synop, $child_synop, $style_synop, $desc, $child_desc, $style_desc);
3699 #############################################################################
3700 # Function    : ReadSourceDocumentation
3701 # Description : This reads in the documentation embedded in comment blocks
3702 #                in the source code (for Gnome).
3704 #                Parameter descriptions override any in the template files.
3705 #                Function descriptions are placed before any description from
3706 #                the template files.
3708 #                It recursively descends the source directory looking for .c
3709 #                files and scans them looking for specially-formatted comment
3710 #                blocks.
3712 # Arguments   : $source_dir - the directory to scan.
3713 #############m###############################################################
3715 sub ReadSourceDocumentation {
3716     my ($source_dir) = @_;
3717     my ($file, $dir, @suffix_list, $suffix);
3719     # prepend entries from @SOURCE_DIR
3720     for my $dir (@SOURCE_DIRS) {
3721         # Check if the filename is in the ignore list.
3722         if ($source_dir =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3723             @TRACE@("Skipping source directory: $source_dir");
3724             return;
3725         }
3726     }
3728     @TRACE@("Scanning source directory: $source_dir");
3730     # This array holds any subdirectories found.
3731     my (@subdirs) = ();
3733     @suffix_list = split (/,/, $SOURCE_SUFFIXES);
3735     opendir (SRCDIR, $source_dir)
3736         || die "Can't open source directory $source_dir: $!";
3738     foreach $file (readdir (SRCDIR)) {
3739       if ($file =~ /^\./) {
3740         next;
3741       } elsif (-d "$source_dir/$file") {
3742         push (@subdirs, $file);
3743       } elsif (@suffix_list) {
3744         foreach $suffix (@suffix_list) {
3745           if ($file =~ m/\.\Q${suffix}\E$/) {
3746             &ScanSourceFile ("$source_dir/$file");
3747           }
3748         }
3749       } elsif ($file =~ m/\.[ch]$/) {
3750         &ScanSourceFile ("$source_dir/$file");
3751       }
3752     }
3753     closedir (SRCDIR);
3755     # Now recursively scan the subdirectories.
3756     foreach $dir (@subdirs) {
3757         &ReadSourceDocumentation ("$source_dir/$dir");
3758     }
3762 #############################################################################
3763 # Function    : ScanSourceFile
3764 # Description : Scans one source file looking for specially-formatted comment
3765 #                blocks. Later &MergeSourceDocumentation is used to merge any
3766 #                documentation found with the documentation already read in
3767 #                from the template files.
3769 # Arguments   : $file - the file to scan.
3770 #############################################################################
3772 sub ScanSourceFile {
3773     my ($file) = @_;
3774     my $basename;
3776     # prepend entries from @SOURCE_DIR
3777     for my $dir (@SOURCE_DIRS) {
3778         # Check if the filename is in the ignore list.
3779         if ($file =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3780             @TRACE@("Skipping source file: $file");
3781             return;
3782         }
3783     }
3785     if ($file =~ m/^.*[\/\\]([^\/\\]*)$/) {
3786         $basename = $1;
3787     } else {
3788         &LogWarning ($file, 1, "Can't find basename for this filename.");
3789         $basename = $file;
3790     }
3792     # Check if the basename is in the list of files to ignore.
3793     if ($IGNORE_FILES =~ m/(\s|^)\Q${basename}\E(\s|$)/) {
3794         @TRACE@("Skipping source file: $file");
3795         return;
3796     }
3798     @TRACE@("Scanning source file: $file");
3800     open (SRCFILE, $file)
3801         || die "Can't open $file: $!";
3802     my $in_comment_block = 0;
3803     my $symbol;
3804     my $in_part = "";
3805     my ($description, $return_desc, $return_start, $return_style);
3806     my ($since_desc, $stability_desc, $deprecated_desc);
3807     my $current_param;
3808     my $ignore_broken_returns;
3809     my @params;
3810     while (<SRCFILE>) {
3811         # Look for the start of a comment block.
3812         if (!$in_comment_block) {
3813             if (m%^\s*/\*.*\*/%) {
3814                 #one-line comment - not gtkdoc
3815             } elsif (m%^\s*/\*\*\s%) {
3816                 #print "Found comment block start\n";
3818                 $in_comment_block = 1;
3820                 # Reset all the symbol data.
3821                 $symbol = "";
3822                 $in_part = "";
3823                 $description = "";
3824                 $return_desc = "";
3825                 $return_style = "";
3826                 $since_desc = "";
3827                 $deprecated_desc = "";
3828                 $stability_desc = "";
3829                 $current_param = -1;
3830                 $ignore_broken_returns = 0;
3831                 @params = ();
3832             }
3833             next;
3834         }
3836         # We're in a comment block. Check if we've found the end of it.
3837         if (m%^\s*\*+/%) {
3838             if (!$symbol) {
3839                 # maybe its not even meant to be a gtk-doc comment?
3840                 &LogWarning ($file, $., "Symbol name not found at the start of the comment block.");
3841             } else {
3842                 # Add the return value description onto the end of the params.
3843                 if ($return_desc) {
3844                     push (@params, "Returns");
3845                     push (@params, $return_desc);
3846                     if ($return_style eq 'broken') {
3847                         &LogWarning ($file, $., "Free-form return value description in $symbol. Use `Returns:' to avoid ambiguities.");
3848                     }
3849                 }
3850                 # Convert special SGML characters
3851                 $description = &ConvertSGMLChars ($symbol, $description);
3852                 my $k;
3853                 for ($k = 1; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3854                     $params[$k] = &ConvertSGMLChars ($symbol, $params[$k]);
3855                 }
3857                 # Handle Section docs
3858                 if ($symbol =~ m/SECTION:\s*(.*)/) {
3859                     my $real_symbol=$1;
3860                     my $key;
3862                     if (scalar %KnownSymbols) {
3863                         if ((! defined($KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"})) || $KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"} != 1) {
3864                             &LogWarning ($file, $., "Section $real_symbol is not defined in the $MODULE-sections.txt file.");
3865                         }
3866                     }
3868                     #print "SECTION DOCS found in source for : '$real_symbol'\n";
3869                     $ignore_broken_returns = 1;
3870                     for ($k = 0; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3871                         #print "   '".$params[$k]."'\n";
3872                         $params[$k] = "\L$params[$k]";
3873                         undef $key;
3874                         if ($params[$k] eq "short_description") {
3875                             $key = "$TMPL_DIR/$real_symbol:Short_Description";
3876                         } elsif ($params[$k] eq "see_also") {
3877                             $key = "$TMPL_DIR/$real_symbol:See_Also";
3878                         } elsif ($params[$k] eq "title") {
3879                             $key = "$TMPL_DIR/$real_symbol:Title";
3880                         } elsif ($params[$k] eq "stability") {
3881                             $key = "$TMPL_DIR/$real_symbol:Stability_Level";
3882                         } elsif ($params[$k] eq "section_id") {
3883                             $key = "$TMPL_DIR/$real_symbol:Section_Id";
3884                         } elsif ($params[$k] eq "include") {
3885                             $key = "$TMPL_DIR/$real_symbol:Include";
3886                         } elsif ($params[$k] eq "image") {
3887                             $key = "$TMPL_DIR/$real_symbol:Image";
3888                         }
3889                         if (defined($key)) {
3890                             $SourceSymbolDocs{$key}=$params[$k+1];
3891                             $SourceSymbolSourceFile{$key} = $file;
3892                             $SourceSymbolSourceLine{$key} = $.;
3893                         }
3894                     }
3895                     $SourceSymbolDocs{"$TMPL_DIR/$real_symbol:Long_Description"}=$description;
3896                     $SourceSymbolSourceFile{"$TMPL_DIR/$real_symbol:Long_Description"} = $file;
3897                     $SourceSymbolSourceLine{"$TMPL_DIR/$real_symbol:Long_Description"} = $.;
3898                     #$SourceSymbolTypes{$symbol} = "SECTION";
3899                 } else {
3900                     #print "SYMBOL DOCS found in source for : '$symbol' ",length($description), "\n";
3901                     $SourceSymbolDocs{$symbol} = $description;
3902                     $SourceSymbolParams{$symbol} = [ @params ];
3903                     # FIXME $SourceSymbolTypes{$symbol} = "STRUCT,SIGNAL,ARG,FUNCTION,MACRO";
3904                     #if (defined $DeclarationTypes{$symbol}) {
3905                     #    $SourceSymbolTypes{$symbol} = $DeclarationTypes{$symbol}
3906                     #}
3907                     $SourceSymbolSourceFile{$symbol} = $file;
3908                     $SourceSymbolSourceLine{$symbol} = $.;
3909                 }
3911                 if ($since_desc) {
3912                      ($since_desc, my @extra_lines) = split ("\n", $since_desc);
3913                      $since_desc =~ s/^\s+//;
3914                      $since_desc =~ s/\s+$//;
3915                      #print "Since($symbol) : [$since_desc]\n";
3916                      $Since{$symbol} = &ConvertSGMLChars ($symbol, $since_desc);
3917                      if(scalar @extra_lines) {
3918                          &LogWarning ($file, $., "multi-line since docs found");
3919                      }
3920                 }
3922                 if ($stability_desc) {
3923                     $stability_desc = &ParseStabilityLevel($stability_desc, $file, $., "Stability level for $symbol");
3924                     $StabilityLevel{$symbol} = &ConvertSGMLChars ($symbol, $stability_desc);
3925                 }
3927                 if ($deprecated_desc) {
3928                     if (!exists $Deprecated{$symbol}) {
3929                          # don't warn for signals and properties
3930                          #if ($symbol !~ m/::?(.*)/) {
3931                          if (defined $DeclarationTypes{$symbol}) {
3932                              &LogWarning ($file, $.,
3933                                  "$symbol is deprecated in the inline comments, but no deprecation guards were found around the declaration.".
3934                                  " (See the --deprecated-guards option for gtkdoc-scan.)");
3935                          }
3936                     }
3937                     $Deprecated{$symbol} = &ConvertSGMLChars ($symbol, $deprecated_desc);
3938                 }
3939             }
3941             $in_comment_block = 0;
3942             next;
3943         }
3945         # Get rid of ' * ' at start of every line in the comment block.
3946         s%^\s*\*\s?%%;
3947         # But make sure we don't get rid of the newline at the end.
3948         if (!$_) {
3949             $_ = "\n";
3950         }
3951         #print "DEBUG: scanning :$_";
3953         # If we haven't found the symbol name yet, look for it.
3954         if (!$symbol) {
3955             if (m%^\s*(SECTION:\s*\S+)%) {
3956                 $symbol = $1;
3957                 #print "SECTION DOCS found in source for : '$symbol'\n";
3958                 $ignore_broken_returns = 1;
3959             } elsif (m%^\s*([\w:-]*\w)\s*:?\s*(\([-a-z0-9_ ]+\)\s*)*$%) {
3960                 $symbol = $1;
3961                 #print "SYMBOL DOCS found in source for : '$symbol'\n";
3962             }
3963             next;
3964         }
3966         if ($in_part eq "description") {
3967             # Get rid of 'Description:'
3968             s%^\s*Description:%%;
3969         }
3971         if (m/^\s*(returns:|return\s+value:)/i) {
3972             if ($return_style eq 'broken') {
3973                 $description .= $return_start . $return_desc;
3974             }
3975             $return_start = $1;
3976             if ($return_style eq 'sane') {
3977                 &LogWarning ($file, $., "Multiple Returns for $symbol.");
3978             }
3979             $return_style = 'sane';
3980             $ignore_broken_returns = 1;
3981             $return_desc = $';
3982             $in_part = "return";
3983             next;
3984         } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3985             $return_start = $1;
3986             $return_style = 'broken';
3987             $return_desc = $';
3988             $in_part = "return";
3989             next;
3990         } elsif (m%^\s*since:%i) {
3991             # we're in param section and have not seen the blank line
3992             if($in_part ne "") {
3993               $since_desc = $';
3994               $in_part = "since";
3995               next;
3996             }
3997         } elsif (m%^\s*deprecated:%i) {
3998             # we're in param section and have not seen the blank line
3999             if($in_part ne "") {
4000               $deprecated_desc = $';
4001               $in_part = "deprecated";
4002               next;
4003             }
4004         } elsif (m%^\s*stability:%i) {
4005             $stability_desc = $';
4006             $in_part = "stability";
4007             next;
4008         }
4010         if ($in_part eq "description") {
4011             $description .= $_;
4012             next;
4013         } elsif ($in_part eq "return") {
4014             $return_desc .= $_;
4015             next;
4016         } elsif ($in_part eq "since") {
4017             $since_desc .= $_;
4018             next;
4019         } elsif ($in_part eq "stability") {
4020             $stability_desc .= $_;
4021             next;
4022         } elsif ($in_part eq "deprecated") {
4023             $deprecated_desc .= $_;
4024             next;
4025         }
4027         # We must be in the parameters. Check for the empty line below them.
4028         if (m%^\s*$%) {
4029             $in_part = "description";
4030             next;
4031         }
4033         # Look for a parameter name.
4034         if (m%^\s*@(\S+)\s*:\s*%) {
4035             my $param_name = $1;
4036             my $param_desc = $';
4038             #print "Found parameter: $param_name\n";
4039             # Allow varargs variations
4040             if ($param_name =~ m/^\.\.\.$/) {
4041                 $param_name = "...";
4042             }
4043             if ("\L$param_name" eq "returns") {
4044                 $return_style = 'sane';
4045                 $ignore_broken_returns = 1;
4046             }
4047             @TRACE@("Found param for symbol $symbol : '$param_name'= '$_'");
4049             push (@params, $param_name);
4050             push (@params, $param_desc);
4051             $current_param += $PARAM_FIELD_COUNT;
4052             next;
4053         }
4055         # We must be in the middle of a parameter description, so add it on
4056         # to the last element in @params.
4057         if ($current_param == -1) {
4058             &LogWarning ($file, $., "Parsing comment block file : parameter expected.");
4059         } else {
4060             $params[$#params] .= $_;
4061         }
4062     }
4063     close (SRCFILE);
4066 #############################################################################
4067 # Function    : OutputMissingDocumentation
4068 # Description : Outputs report of documentation coverage to a file
4070 # Arguments   : none
4071 #############################################################################
4073 sub OutputMissingDocumentation {
4074     my $old_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.txt";
4075     my $new_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.new";
4077     my $n_documented = 0;
4078     my $n_incomplete = 0;
4079     my $total = 0;
4080     my $symbol;
4081     my $percent;
4082     my $msg;
4083     my $buffer = "";
4084     my $buffer_deprecated = "";
4085     my $buffer_descriptions = "";
4087     open(UNDOCUMENTED, ">$new_undocumented_file")
4088       || die "Can't create $new_undocumented_file";
4090     foreach $symbol (sort (keys (%AllSymbols))) {
4091         # FIXME: should we print LogWarnings for undocumented stuff?
4092         # DEBUG
4093         #my $ssfile = &GetSymbolSourceFile($symbol);
4094         #my $ssline = &GetSymbolSourceLine($symbol);
4095         #my $location = "defined at " . (defined($ssfile)?$ssfile:"?") . ":" . (defined($ssline)?$ssline:"0") . "\n";
4096         # DEBUG
4097         if ($symbol !~ /:(Title|Long_Description|Short_Description|See_Also|Stability_Level|Include|Section_Id|Image)/) {
4098             $total++;
4099             if (exists ($AllDocumentedSymbols{$symbol})) {
4100                 $n_documented++;
4101                 if (exists ($AllIncompleteSymbols{$symbol})) {
4102                     $n_incomplete++;
4103                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4104                     #$buffer .= "\t0: ".$location;
4105                 }
4106             } elsif (exists $Deprecated{$symbol}) {
4107                 if (exists ($AllIncompleteSymbols{$symbol})) {
4108                     $n_incomplete++;
4109                     $buffer_deprecated .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4110                     #$buffer .= "\t1a: ".$location;
4111                 } else {
4112                     $buffer_deprecated .= $symbol . "\n";
4113                     #$buffer .= "\t1b: ".$location;
4114                 }
4115             } else {
4116                 if (exists ($AllIncompleteSymbols{$symbol})) {
4117                     $n_incomplete++;
4118                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4119                     #$buffer .= "\t2a: ".$location;
4120                 } else {
4121                     $buffer .= $symbol . "\n";
4122                     #$buffer .= "\t2b: ".$location;
4123                 }
4124             }
4125         } elsif ($symbol =~ /:(Long_Description|Short_Description)/) {
4126             $total++;
4127             #my $len1=(exists($SymbolDocs{$symbol}))?length($SymbolDocs{$symbol}):-1;
4128             #my $len2=(exists($AllDocumentedSymbols{$symbol}))?length($AllDocumentedSymbols{$symbol}):-1;
4129             #print "%%%% $symbol : $len1,$len2\n";
4130             if (((exists ($SymbolDocs{$symbol})) && (length ($SymbolDocs{$symbol}) > 0))
4131             || ((exists ($AllDocumentedSymbols{$symbol})) && (length ($AllDocumentedSymbols{$symbol}) > 0))) {
4132               $n_documented++;
4133             } else {
4134               # cut off the leading namespace ($TMPL_DIR)
4135               $symbol =~ m/^.*\/(.*)$/;
4136               $buffer_descriptions .= $1 . "\n";
4137             }
4138         }
4139     }
4141     $buffer .= "\n" . $buffer_deprecated . "\n" . $buffer_descriptions;
4143     if ($total == 0) {
4144       $percent = 100;
4145     } else {
4146       $percent = ($n_documented / $total) * 100.0;
4147     }
4149     printf UNDOCUMENTED "%.0f%% symbol docs coverage.\n", $percent;
4150     print UNDOCUMENTED "$n_documented symbols documented.\n";
4151     print UNDOCUMENTED "$n_incomplete symbols incomplete.\n";
4152     print UNDOCUMENTED ($total - $n_documented) . " not documented.\n\n\n";
4154     print UNDOCUMENTED $buffer;
4155     close (UNDOCUMENTED);
4157     return &UpdateFileIfChanged ($old_undocumented_file, $new_undocumented_file, 0);
4159     printf "%.0f%% symbol docs coverage", $percent;
4160     print "($n_documented symbols documented, $n_incomplete symbols incomplete, " . ($total - $n_documented) . " not documented)\n";
4161     print "See $MODULE-undocumented.txt for a list of missing docs.\nThe doc coverage percentage doesn't include intro sections.\n";
4165 #############################################################################
4166 # Function    : OutputUndeclaredSymbols
4167 # Description : Outputs symbols that are listed in the section file, but not
4168 #               declaration is found in the sources
4170 # Arguments   : none
4171 #############################################################################
4173 sub OutputUndeclaredSymbols {
4174     my $old_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.txt";
4175     my $new_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.new";
4177     open(UNDECLARED, ">$new_undeclared_file")
4178         || die "Can't create $new_undeclared_file";
4180     if (%UndeclaredSymbols) {
4181         print UNDECLARED (join("\n", sort keys %UndeclaredSymbols));
4182         print UNDECLARED "\n";
4183         print "See $MODULE-undeclared.txt for the list of undeclared symbols.\n"
4184     }
4185     close(UNDECLARED);
4187     return &UpdateFileIfChanged ($old_undeclared_file, $new_undeclared_file, 0);
4190 #############################################################################
4191 # Function    : OutputUnusedSymbols
4192 # Description : Outputs symbols that are documented in comments, but not
4193 #               declared in the sources
4195 # Arguments   : none
4196 #############################################################################
4198 sub OutputUnusedSymbols {
4199     my $num_unused = 0;
4200     my $old_unused_file = "$ROOT_DIR/$MODULE-unused.txt";
4201     my $new_unused_file = "$ROOT_DIR/$MODULE-unused.new";
4203     open (UNUSED, ">$new_unused_file")
4204         || die "Can't open $new_unused_file";
4205     my ($symbol);
4206     foreach $symbol (sort keys (%Declarations)) {
4207         if (!defined ($DeclarationOutput{$symbol})) {
4208             print (UNUSED "$symbol\n");
4209             $num_unused++;
4210         }
4211     }
4212     foreach $symbol (sort (keys (%AllUnusedSymbols))) {
4213         print (UNUSED "$symbol(" . $AllUnusedSymbols{$symbol} . ")\n");
4214         $num_unused++;
4215     }
4216     close (UNUSED);
4217     if ($num_unused != 0) {
4218         &LogWarning ($old_unused_file, 1, "$num_unused unused declarations.".
4219             "They should be added to $MODULE-sections.txt in the appropriate place.");
4220     }
4222     return &UpdateFileIfChanged ($old_unused_file, $new_unused_file, 0);
4226 #############################################################################
4227 # Function    : OutputAllSymbols
4228 # Description : Outputs list of all symbols to a file
4230 # Arguments   : none
4231 #############################################################################
4233 sub OutputAllSymbols {
4234      my $n_documented = 0;
4235      my $total = 0;
4236      my $symbol;
4237      my $percent;
4238      my $msg;
4240      open (SYMBOLS, ">$ROOT_DIR/$MODULE-symbols.txt")
4241           || die "Can't create $ROOT_DIR/$MODULE-symbols.txt: $!";
4243      foreach $symbol (sort (keys (%AllSymbols))) {
4244           print SYMBOLS $symbol . "\n";
4245      }
4247      close (SYMBOLS);
4250 #############################################################################
4251 # Function    : OutputSymbolsWithoutSince
4252 # Description : Outputs list of all symbols without a since tag to a file
4254 # Arguments   : none
4255 #############################################################################
4257 sub OutputSymbolsWithoutSince {
4258      my $n_documented = 0;
4259      my $total = 0;
4260      my $symbol;
4261      my $percent;
4262      my $msg;
4264      open (SYMBOLS, ">$ROOT_DIR/$MODULE-nosince.txt")
4265           || die "Can't create $ROOT_DIR/$MODULE-nosince.txt: $!";
4267      foreach $symbol (sort (keys (%SourceSymbolDocs))) {
4268          if (!defined $Since{$symbol}) {
4269              print SYMBOLS $symbol . "\n";
4270          }
4271      }
4273      close (SYMBOLS);
4277 #############################################################################
4278 # Function    : MergeSourceDocumentation
4279 # Description : This merges documentation read from a source file into the
4280 #                documentation read in from a template file.
4282 #                Parameter descriptions override any in the template files.
4283 #                Function descriptions are placed before any description from
4284 #                the template files.
4286 # Arguments   : none
4287 #############################################################################
4289 sub MergeSourceDocumentation {
4290     my $symbol;
4291     my @Symbols;
4293     if (scalar %SymbolDocs) {
4294         @Symbols=keys (%SymbolDocs);
4295         #print "num existing entries: ".(scalar @Symbols)."\n";
4296         #print "  ",$Symbols[0], " ",$Symbols[1],"\n";
4297     }
4298     else {
4299         # filter scanned declarations, with what we suppress from -sections.txt
4300         my %tmp = ();
4301         foreach $symbol (keys (%Declarations)) {
4302             if (defined($KnownSymbols{$symbol}) && $KnownSymbols{$symbol} == 1) {
4303                 $tmp{$symbol}=1;
4304             }
4305         }
4306         # , add the rest from -sections.txt
4307         foreach $symbol (keys (%KnownSymbols)) {
4308             if ($KnownSymbols{$symbol} == 1) {
4309                 $tmp{$symbol}=1;
4310             }
4311         }
4312         # and add whats found in the source
4313         foreach $symbol (keys (%SourceSymbolDocs)) {
4314             $tmp{$symbol}=1;
4315         }
4316         @Symbols = keys (%tmp);
4317         #print "num source entries: ".(scalar @Symbols)."\n";
4318     }
4319     foreach $symbol (@Symbols) {
4320         $AllSymbols{$symbol} = 1;
4322         my $have_tmpl_docs = 0;
4324         ## see if the symbol is documented in template
4325         my $tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4326         my $check_tmpl_doc =$tmpl_doc;
4327         # remove all xml-tags and whitespaces
4328         $check_tmpl_doc =~ s/<.*?>//g;
4329         $check_tmpl_doc =~ s/\s//g;
4330         # anything left ?
4331         if ($check_tmpl_doc ne "") {
4332             $have_tmpl_docs = 1;
4333             #print "## [$check_tmpl_doc]\n";
4334         } else {
4335             # if the docs have just an empty para, don't merge that.
4336             $check_tmpl_doc = $tmpl_doc;
4337             $check_tmpl_doc =~ s/(\s|\n)//msg;
4338             if ($check_tmpl_doc eq "<para></para>") {
4339                $tmpl_doc = "";
4340             }
4341         }
4343         if (exists ($SourceSymbolDocs{$symbol})) {
4344             my $type = $DeclarationTypes {$symbol};
4346             #print "merging [$symbol] from source\n";
4348             my $item = "Parameter";
4349             if (defined ($type)) {
4350                 if ($type eq 'STRUCT') {
4351                     $item = "Field";
4352                 } elsif ($type eq 'ENUM') {
4353                     $item = "Value";
4354                 } elsif ($type eq 'UNION') {
4355                     $item = "Field";
4356                 }
4357             } else {
4358                 $type="SIGNAL";
4359             }
4361             my $src_doc = $SourceSymbolDocs{$symbol};
4362             # remove leading and training whitespaces
4363             $src_doc =~ s/^\s+//;
4364             $src_doc =~ s/\s+$//;
4366             # Don't output warnings for overridden titles as titles are
4367             # automatically generated in the -sections.txt file, and thus they
4368             # are often overridden.
4369             if ($have_tmpl_docs && $symbol !~ m/:Title$/) {
4370                 # check if content is different
4371                 if ($tmpl_doc ne $src_doc) {
4372                     #print "[$tmpl_doc] [$src_doc]\n";
4373                     &LogWarning ($SourceSymbolSourceFile{$symbol}, $SourceSymbolSourceLine{$symbol},
4374                         "Documentation in template ".$SymbolSourceFile{$symbol}.":".$SymbolSourceLine{$symbol}." for $symbol being overridden by inline comments.");
4375                 }
4376             }
4378             if ($src_doc ne "") {
4379                  $AllDocumentedSymbols{$symbol} = 1;
4380             }
4382             # Convert <!--PARAMETERS--> with any blank lines around it to
4383             # a </para> followed by <!--PARAMETERS--> followed by <para>.
4384             $src_doc =~ s%\n+\s*<!--PARAMETERS-->\s*\n+%\n</para>\n<!--PARAMETERS-->\n<para>\n%g;
4386             # Do not add <para> to nothing, it breaks missing docs checks.
4387             my $src_doc_para = "";
4388             if ($src_doc ne "") {
4389                 $src_doc_para = $src_doc;
4390             }
4392             if ($symbol =~ m/$TMPL_DIR\/.+:Long_Description/) {
4393                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4394             } elsif ($symbol =~ m/$TMPL_DIR\/.+:.+/) {
4395                 # For the title/summary/see also section docs we don't want to
4396                 # add any <para> tags.
4397                 $SymbolDocs{$symbol} = "$src_doc"
4398             } else {
4399                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4400             }
4402             # merge parameters
4403             if ($symbol =~ m/.*::.*/) {
4404                 # For signals we prefer the param names from the source docs,
4405                 # since the ones from the templates are likely to contain the
4406                 # artificial argn names which are generated by gtkdoc-scangobj.
4407                 $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4408                 # FIXME: we need to check for empty docs here as well!
4409             } else {
4410                 # The templates contain the definitive parameter names and order,
4411                 # so we will not change that. We only override the actual text.
4412                 my $tmpl_params = $SymbolParams{$symbol};
4413                 if (!defined ($tmpl_params)) {
4414                     #print "No merge needed for $symbol\n";
4415                     $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4416                     #  FIXME: we still like to get the number of params and merge
4417                     #  1) we would noticed that params have been removed/renamed
4418                     #  2) we would catch undocumented params
4419                     #  params are not (yet) exported in -decl.txt so that we
4420                     #  could easily grab them :/
4421                 } else {
4422                     my $params = $SourceSymbolParams{$symbol};
4423                     my $j;
4424                     #print "Merge needed for $symbol, tmpl_params: ",$#$tmpl_params,", source_params: ",$#$params," \n";
4425                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4426                         my $tmpl_param_name = $$tmpl_params[$j];
4428                         # Try to find the param in the source comment documentation.
4429                         my $found = 0;
4430                         my $k;
4431                         #print "  try merge param $tmpl_param_name\n";
4432                         for ($k = 0; $k <= $#$params; $k += $PARAM_FIELD_COUNT) {
4433                             my $param_name = $$params[$k];
4434                             my $param_desc = $$params[$k + 1];
4436                             #print "    test param  $param_name\n";
4437                             # We accept changes in case, since the Gnome source
4438                             # docs contain a lot of these.
4439                             if ("\L$param_name" eq "\L$tmpl_param_name") {
4440                                 $found = 1;
4442                                 # Override the description.
4443                                 $$tmpl_params[$j + 1] = $param_desc;
4445                                 # Set the name to "" to mark it as used.
4446                                 $$params[$k] = "";
4447                                 last;
4448                             }
4449                         }
4451                         # If it looks like the parameters are there, but not
4452                         # in the right place, try to explain a bit better.
4453                         if ((!$found) && ($src_doc =~ m/\@$tmpl_param_name:/)) {
4454                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4455                                 "Parameters for $symbol must start on the line immediately after the function or macro name.");
4456                         }
4457                     }
4459                     # Now we output a warning if parameters have been described which
4460                     # do not exist.
4461                     for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
4462                         my $param_name = $$params[$j];
4463                         if ($param_name) {
4464                             # the template builder cannot detect if a macro returns
4465                             # a result or not
4466                             if(($type eq "MACRO") && ($param_name eq "Returns")) {
4467                                 # FIXME: do we need to add it then to tmpl_params[] ?
4468                                 my $num=$#$tmpl_params;
4469                                 #print "  adding Returns: to macro docs for $symbol.\n";
4470                                 $$tmpl_params[$num+1]="Returns";
4471                                 $$tmpl_params[$num+2]=$$params[$j+1];
4472                                 next;
4473                             }
4474                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4475                                 "$item described in source code comment block but does not exist. $type: $symbol $item: $param_name.");
4476                         }
4477                     }
4478                 }
4479             }
4480         } else {
4481             if ($have_tmpl_docs) {
4482                 $AllDocumentedSymbols{$symbol} = 1;
4483                 #print "merging [$symbol] from template\n";
4484             }
4485             else {
4486                 #print "[$symbol] undocumented\n";
4487             }
4488         }
4490         # if this symbol is documented, check if docs are complete
4491         $check_tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4492         # remove all xml-tags and whitespaces
4493         $check_tmpl_doc =~ s/<.*?>//g;
4494         $check_tmpl_doc =~ s/\s//g;
4495         if ($check_tmpl_doc ne "") {
4496             my $tmpl_params = $SymbolParams{$symbol};
4497             if (defined ($tmpl_params)) {
4498                 my $type = $DeclarationTypes {$symbol};
4500                 my $item = "Parameter";
4501                 if (defined ($type)) {
4502                     if ($type eq 'STRUCT') {
4503                         $item = "Field";
4504                     } elsif ($type eq 'ENUM') {
4505                         $item = "Value";
4506                     } elsif ($type eq 'UNION') {
4507                         $item = "Field";
4508                     }
4509                 } else {
4510                     $type="SIGNAL";
4511                 }
4513                 #print "Check param docs for $symbol, tmpl_params: ",$#$tmpl_params," entries, type=$type\n";
4515                 if ($#$tmpl_params > 0) {
4516                     my $j;
4517                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4518                         # Output a warning if the parameter is empty and
4519                         # remember for stats.
4520                         my $tmpl_param_name = $$tmpl_params[$j];
4521                         my $tmpl_param_desc = $$tmpl_params[$j + 1];
4522                         if ($tmpl_param_name ne "void" && $tmpl_param_desc !~ m/\S/) {
4523                             if (exists ($AllIncompleteSymbols{$symbol})) {
4524                                 $AllIncompleteSymbols{$symbol}.=", ".$tmpl_param_name;
4525                             } else {
4526                                 $AllIncompleteSymbols{$symbol}=$tmpl_param_name;
4527                             }
4528                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4529                                 "$item description for $symbol"."::"."$tmpl_param_name is missing in source code comment block.");
4530                         }
4531                     }
4532                 }
4533                 else {
4534                     if ($#$tmpl_params == 0) {
4535                         $AllIncompleteSymbols{$symbol}="<items>";
4536                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4537                             "$item descriptions for $symbol are missing in source code comment block.");
4538                     }
4539                     # $#$tmpl_params==-1 means we don't know about parameters
4540                     # this unfortunately does not tell if there should be some
4541                 }
4542             }
4543         }
4544    }
4545    #print "num doc entries: ".(scalar %SymbolDocs)."\n";
4548 #############################################################################
4549 # Function    : IsEmptyDoc
4550 # Description : Check if a doc-string is empty. Its also regarded as empty if
4551 #               it only consist of whitespace or e.g. FIXME.
4552 # Arguments   : the doc-string
4553 #############################################################################
4554 sub IsEmptyDoc {
4555     my ($doc) = @_;
4557     if ($doc =~ /^\s*$/) {
4558         return 1;
4559     }
4561     if ($doc =~ /^\s*<para>\s*(FIXME)?\s*<\/para>\s*$/) {
4562         return 1;
4563     }
4565     return 0;
4568 #############################################################################
4569 # Function    : ConvertMarkDown
4570 # Description : Converts mark down syntax to the respective docbook.
4571 #               http://de.wikipedia.org/wiki/Markdown
4572 #               Inspired by the design of ParseDown
4573 #               http://parsedown.org/
4574 #               Copyright (c) 2013 Emanuil Rusev, erusev.com
4575 # Arguments   : the symbol name, the doc-string
4576 #############################################################################
4578 sub ConvertMarkDown {
4579     my ($symbol, $text) = @_;
4581     $text = &MarkDownParse ($text, $symbol);
4583     return $text
4586 # SUPPORTED MARKDOWN
4587 # ==================
4589 # Atx-style Headers
4590 # -----------------
4592 # # Header 1
4594 # ## Header 2 ##
4596 # Setext-style Headers
4597 # --------------------
4599 # Header 1
4600 # ========
4602 # Header 2
4603 # --------
4605 # Ordered (unnested) Lists
4606 # ------------------------
4608 # 1. item 1
4610 # 1. item 2 with loooong
4611 #    description
4613 # 3. item 3
4615 # Note: we require a blank line above the list items
4618 # TODO(ensonic): it would be nice to add id parameters to the refsect2 elements
4620 sub MarkDownParseBlocks {
4621   my ($linesref, $symbol, $context) = @_;
4622   my $line;
4623   my @md_blocks = ();
4624   my $md_block = { type => "" };
4626  OUTER: foreach $line (@$linesref) {
4627     my $first_char = substr ($line, 0, 1);
4628     my $deindented_line;
4630     if ($md_block->{"type"} eq "markup") {
4631       if (!$md_block->{"closed"}) {
4632         if (index ($line, $md_block->{"start"}) != -1) {
4633           $md_block->{"depth"}++;
4634         }
4635         if (index ($line, $md_block->{"end"}) != -1) {
4636           if ($md_block->{"depth"} > 0) {
4637             $md_block->{"depth"}--;
4638           } else {
4639             $md_block->{"closed"} = 1;
4640           }
4641         }
4642         $md_block->{"text"} .= "\n" . $line;
4643         next OUTER;
4644       }
4645     }
4647     $deindented_line = $line;
4648     $deindented_line =~ s/^\s+//;
4650     if ($md_block->{"type"} eq "heading") {
4651       # a heading is ended by any level less than or equal
4652       if ($md_block->{"level"} == 1) {
4653         if ($line =~ /^={4,}[ \t]*$/) {
4654           my $text = pop $md_block->{"lines"};
4655           $md_block->{"interrupted"} = 0;
4656           push @md_blocks, $md_block;
4658           $md_block = { type => "heading",
4659                         text => $text,
4660                         lines => [],
4661                         level => 1 };
4662           next OUTER;
4663         } elsif ($line =~ /^[#][ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4664           $md_block->{"interrupted"} = 0;
4665           push @md_blocks, $md_block;
4667           $md_block = { type => "heading",
4668                         text => $1,
4669                         id => $2,
4670                         lines => [],
4671                         level => 1 };
4672           next OUTER;
4673         } else {
4674           # push lines into the block until the end is reached
4675           push $md_block->{"lines"}, $line;
4676           next OUTER;
4677         }
4678       } else {
4679         if ($line =~ /^[=]{4,}[ \t]*$/) {
4680           my $text = pop $md_block->{"lines"};
4681           $md_block->{"interrupted"} = 0;
4682           push @md_blocks, $md_block;
4684           $md_block = { type => "heading",
4685                         text => $text,
4686                         lines => [],
4687                         level => 1 };
4688           next OUTER;
4689         } elsif ($line =~ /^[-]{4,}[ \t]*$/) {
4690           my $text = pop $md_block->{"lines"};
4691           $md_block->{"interrupted"} = 0;
4692           push @md_blocks, $md_block;
4694           $md_block = { type => "heading",
4695                         text => $text,
4696                         lines => [],
4697                         level => 2 };
4698           next OUTER;
4699         } elsif ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4700           $md_block->{"interrupted"} = 0;
4701           push @md_blocks, $md_block;
4703           $md_block = { type => "heading",
4704                         text => $2,
4705                         id => $3,
4706                         lines => [],
4707                         level => length($1) };
4708           next OUTER;
4709         } else {
4710           # push lines into the block until the end is reached
4711           push $md_block->{"lines"}, $line;
4712           next OUTER;
4713         }
4714       }
4715     } elsif ($md_block->{"type"} eq "code") {
4716       if ($line =~ /^[ \t]*\]\|/) {
4717         push @md_blocks, $md_block;
4718         $md_block = { type => "paragraph",
4719                       text => "",
4720                       lines => [] };
4721       } else {
4722         push $md_block->{"lines"}, $line;
4723       }
4724       next OUTER;
4725     }
4727     if ($deindented_line eq "") {
4728       $md_block->{"interrupted"} = 1;
4729       next;
4730     }
4732     if ($md_block->{"type"} eq "quote") {
4733       if (!$md_block->{"interrupted"}) {
4734         $line =~ s/^[ ]*>[ ]?//;
4735         push $md_block->{"lines"}, $line;
4736         next OUTER;
4737       }
4738     } elsif ($md_block->{"type"} eq "li") {
4739       if ($line =~ /^([ ]{0,3})(\d+[.]|[*+-])[ ](.*)/) {
4740         my $indentation = $1;
4741         if ($md_block->{"indentation"} ne $indentation) {
4742           push $md_block->{"lines"}, $line;
4743         } else {
4744           my $lines = $3;
4745           my $ordered = $md_block->{"ordered"};
4746           $lines =~ s/^[ ]{0,4}//;
4747           $md_block->{"last"} = 0;
4748           push @md_blocks, $md_block;
4749           $md_block = { type => "li",
4750                         ordered => $ordered,
4751                         indentation => $indentation,
4752                         first => 0,
4753                         last => 1,
4754                         lines => [ $lines ] };
4755         }
4756         next OUTER;
4757       }
4759       if ($md_block->{"interrupted"}) {
4760         if ($first_char eq " ") {
4761           push $md_block->{"lines"}, "";
4762           $line =~ s/^[ ]{0,4}//;
4763           push $md_block->{"lines"}, $line;
4764           $md_block->{"interrupted"} = 0;
4765           next OUTER;
4766         }
4767       } else {
4768         $line =~ s/^[ ]{0,4}//;
4769         push $md_block->{"lines"}, $line;
4770         next OUTER;
4771       }
4772     }
4774     # indentation sensitive types
4776     if ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4777       # atx heading (#)
4778       push @md_blocks, $md_block;
4780       $md_block = { type => "heading",
4781                     text => $2,
4782                     id => $3,
4783                     lines => [],
4784                     level => length($1) };
4786       next OUTER;
4787     } elsif ($line =~ /^={4,}[ \t]*$/) {
4788       # setext heading (====)
4790       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4791         push @md_blocks, $md_block;
4792         $md_block->{"type"} = "heading";
4793         $md_block->{"lines"} = [];
4794         $md_block->{"level"} = 1;
4795       }
4797       next OUTER;
4798     } elsif ($line =~ /^-{4,}[ \t]*$/) {
4799       # setext heading (-----)
4801       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4802         push @md_blocks, $md_block;
4803         $md_block->{"type"} = "heading";
4804         $md_block->{"lines"} = [];
4805         $md_block->{"level"} = 2;
4806       }
4808       next OUTER;
4809     } elsif ($line =~ /^[ \t]*\|\[[ ]*(?:<!-- language="([^"]+?)" -->)?/) {
4810       # code
4811       $md_block->{"interrupted"} = 1;
4812       push @md_blocks, $md_block;
4813       $md_block = { type => "code",
4814                     language => $1,
4815                     lines => [] };
4816       next OUTER;
4817     }
4819     # indentation insensitive types
4821     if ($line =~ /^[ ]*<!DOCTYPE/) {
4822       push @md_blocks, $md_block;
4824       $md_block = { type   => "markup",
4825                     text   => $deindented_line,
4826                     start  => "<",
4827                     end    => ">",
4828                     closed => 0,
4829                     depth  => 0 };
4831     } elsif ($line =~ /^[ ]*<\??(\w+)[^>]*([\/\?])?[ \t]*>/) {
4832       # markup, including <?xml version="1.0"?>
4833       my $tag = $1;
4834       my $is_self_closing = defined($2);
4836       if (! $MD_TEXT_LEVEL_ELEMENTS{$tag}) {
4837         push @md_blocks, $md_block;
4839         if ($is_self_closing) {
4840           $md_block = { type => "self-closing tag",
4841                         text => $deindented_line };
4842           $is_self_closing = 0;
4843           next OUTER;
4844         }
4846         $md_block = { type   => "markup",
4847                       text   => $deindented_line,
4848                       start  => "<" . $tag . ">",
4849                       end    => "</" . $tag . ">",
4850                       closed => 0,
4851                       depth  => 0 };
4852         if ($deindented_line =~ /<\/$tag>/) {
4853           $md_block->{"closed"} = 1;
4854         }
4855         next OUTER;
4856       }
4857     } elsif ($line =~ /^([ ]*)[*+-][ ](.*)/) {
4858       # li
4859       push @md_blocks, $md_block;
4860       my $lines = $2;
4861       my $indentation = $1;
4862       $lines =~ s/^[ ]{0,4}//;
4863       $md_block = { type => "li",
4864                     ordered => 0,
4865                     indentation => $indentation,
4866                     first => 1,
4867                     last => 1,
4868                     lines => [ $lines ] };
4869       next OUTER;
4870     } elsif ($line =~ /^[ ]*>[ ]?(.*)/) {
4871       push @md_blocks, $md_block;
4872       $md_block = { type => "quote",
4873                     lines => [ $1 ] };
4874       next OUTER;
4875     }
4877     # list item
4879     if ($line =~ /^([ ]{0,4})\d+[.][ ]+(.*)/) {
4880       push @md_blocks, $md_block;
4881       my $lines = $2;
4882       my $indentation = $1;
4883       $lines =~ s/^[ ]{0,4}//;
4885       $md_block = { type => "li",
4886                     ordered => 1,
4887                     indentation => $indentation,
4888                     first => 1,
4889                     last => 1,
4890                     lines => [ $lines ] };
4892       next;
4893     }
4895     # paragraph
4896     if ($md_block->{"type"} eq "paragraph") {
4897       if ($md_block->{"interrupted"}) {
4898         push @md_blocks, $md_block;
4899         $md_block = { type => "paragraph",
4900                       interrupted => 0,
4901                       text => $line };
4902       } else {
4903         $md_block->{"text"} .= "\n" . $line;
4904       }
4905     } else {
4906       push @md_blocks, $md_block;
4907       $md_block = { type => "paragraph",
4908                     text => $line };
4909     }
4910   }
4912   push @md_blocks, $md_block;
4914   shift @md_blocks;
4916   return @md_blocks;
4919 sub MarkDownParseSpanElementsInner {
4920   my ($text, $markersref) = @_;
4921   my $markup = "";
4922   my %markers = map { $_ => 1 } @$markersref;
4924   while ($text ne "") {
4925     my $closest_marker = "";
4926     my $closest_marker_index = 0;
4927     my $closest_marker_position = -1;
4928     my $text_marker = "";
4929     my $i = 0;
4930     my $offset = 0;
4931     my @markers_rest;
4932     my $marker;
4933     my $use;
4935     while ( ($marker, $use) = each %markers ) {
4936       my $marker_position;
4938       if (!$use) {
4939         next;
4940       }
4942       $marker_position = index ($text, $marker);
4944       if ($marker_position < 0) {
4945         $markers{$marker} = 0;
4946         next;
4947       }
4949       if ($closest_marker eq "" || $marker_position < $closest_marker_position) {
4950         $closest_marker = $marker;
4951         $closest_marker_index = $i;
4952         $closest_marker_position = $marker_position;
4953       }
4954     }
4956     if ($closest_marker_position >= 0) {
4957       $text_marker = substr ($text, $closest_marker_position);
4958     }
4960     if ($text_marker eq "") {
4961       $markup .= $text;
4962       $text = "";
4963       next; # last
4964     }
4966     $markup .= substr ($text, 0, $closest_marker_position);
4967     $text = substr ($text, $closest_marker_position);
4968     @markers_rest = map { $markers{$_} ? ($_ eq $closest_marker ? () : $_) : () } keys %markers;
4970     if ($closest_marker eq "![" || $closest_marker eq "[") {
4971       my %element;
4973       if (index ($text, "]") && $text =~ /\[((?:[^][]|(?R))*)\]/) {
4974         my $remaining_text;
4976         %element = ( "!" => (substr ($text, 0, 1) eq "!"),
4977                      "a" => $1 );
4979         $offset = length ($&);
4980         if ($element{"!"}) {
4981           $offset++;
4982         }
4984         $remaining_text = substr ($text, $offset);
4985         if ($remaining_text =~ /^\([ ]*([^)'"]*?)(?:[ ]+['"](.+?)['"])?[ ]*\)/) {
4986           $element{"»"} = $1;
4987           if (defined ($2)) {
4988             $element{"#"} = $2;
4989           }
4990           $offset += length ($&);
4991         } else {
4992           undef %element;
4993         }
4994       }
4996       if (%element) {
4997         $element{"»"} =~ s/&/&amp;/g;
4998         $element{"»"} =~ s/</&lt;/g;
4999         if ($element{"!"}) {
5000           $markup .= "<inlinemediaobject><imageobject><imagedata fileref=\"" . $element{"»"} . "\"></imagedata></imageobject>";
5002           if (defined ($element{"a"})) {
5003             $markup .= "<textobject><phrase>" . $element{"a"} . "</phrase></textobject>";
5004           }
5006           $markup .= "</inlinemediaobject>";
5007         } else {
5008           $element{"a"} = &MarkDownParseSpanElementsInner ($element{"a"}, \@markers_rest);
5009           $markup .= "<ulink url=\"" . $element{"»"} . "\"";
5011           if (defined ($element{"#"})) {
5012             # title attribute not supported
5013           }
5015           $markup .= ">" . $element{"a"} . "</ulink>";
5016         }
5017       } else {
5018         $markup .= $closest_marker;
5019         if ($closest_marker eq "![") {
5020           $offset = 2;
5021         } else {
5022           $offset = 1;
5023         }
5024       }
5025     } elsif ($closest_marker eq "<") {
5026       if ($text =~ /^<(https?:[\/]{2}[^\s]+?)>/i) {
5027         my $element_url = $1;
5028         $element_url =~ s/&/&amp;/g;
5029         $element_url =~ s/</&lt;/g;
5031         $markup .= "<ulink url=\"" . $element_url . "\">" . $element_url . "</ulink>";
5032         $offset = length ($&);
5033       } elsif ($text =~ /^<([A-Za-z0-9._-]+?@[A-Za-z0-9._-]+?)>/) {
5034         $markup .= "<ulink url=\"mailto:" . $1 . "\">" . $1 . "</ulink>";
5035         $offset = length ($&);
5036       } elsif ($text =~ /^<[^>]+?>/) {
5037         $markup .= $&;
5038         $offset = length ($&);
5039       } else {
5040         $markup .= "&lt;";
5041         $offset = 1;
5042       }
5043     } elsif ($closest_marker eq "\\") {
5044       my $special_char = substr ($text, 1, 1);
5045       if ($MD_ESCAPABLE_CHARS{$special_char} ||
5046           $MD_GTK_ESCAPABLE_CHARS{$special_char}) {
5047         $markup .= $special_char;
5048         $offset = 2;
5049       } else {
5050         $markup .= "\\";
5051         $offset = 1;
5052       }
5053     } elsif ($closest_marker eq "`") {
5054       if ($text =~ /^(`+)([^`]+?)\1(?!`)/) {
5055         my $element_text = $2;
5056         $markup .= "<literal>" . $element_text . "</literal>";
5057         $offset = length ($&);
5058       } else {
5059         $markup .= "`";
5060         $offset = 1;
5061       }
5062     } elsif ($closest_marker eq "@") {
5063       # Convert '@param()'
5064       # FIXME: we could make those also links ($symbol.$2), but that would be less
5065       # useful as the link target is a few lines up or down
5066       if ($text =~ /^(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)/) {
5067         $markup .= $1 . "<parameter>" . $2 . "()</parameter>\n";
5068         $offset = length ($&);
5069       } elsif ($text =~ /^(\A|[^\\])\@(\w+((\.|->)\w+)*)/) {
5070         # Convert '@param', but not '\@param'.
5071         $markup .= $1 . "<parameter>" . $2 . "</parameter>\n";
5072         $offset = length ($&);
5073       } elsif ($text =~ /^\\\@/) {
5074         $markup .= "\@";
5075         $offset = length ($&);
5076       } else {
5077         $markup .= "@";
5078         $offset = 1;
5079       }
5080     } elsif ($closest_marker eq "#") {
5081       if ($text =~ /^(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/) {
5082         # handle #Object.func()
5083         $markup .= $1 . &MakeXRef ($2, &tagify ($2 . "()", "function"));
5084         $offset = length ($&);
5085       } elsif ($text =~ /^(\A|[^\\])#([\w\-:\.]+[\w]+)/) {
5086         # Convert '#symbol', but not '\#symbol'.
5087         $markup .= $1 . &MakeHashXRef ($2, "type");
5088         $offset = length ($&);
5089       } elsif ($text =~ /^\\#/) {
5090         $markup .= "#";
5091         $offset = length ($&);
5092       } else {
5093         $markup .= "#";
5094         $offset = 1;
5095       }
5096     } elsif ($closest_marker eq "%") {
5097       if ($text =~ /^(\A|[^\\])\%(-?\w+)/) {
5098         # Convert '%constant', but not '\%constant'.
5099         # Also allow negative numbers, e.g. %-1.
5100         $markup .= $1 . &MakeXRef ($2, &tagify ($2, "literal"));
5101         $offset = length ($&);
5102       } elsif ($text =~ /^\\%/) {
5103         $markup .= "\%";
5104         $offset = length ($&);
5105       } else {
5106         $markup .= "%";
5107         $offset = 1;
5108       }
5109     }
5111     if ($offset > 0) {
5112       $text = substr ($text, $offset);
5113     }
5114   }
5116   return $markup;
5119 sub MarkDownParseSpanElements {
5120   my ($text) = @_;
5121   my @markers = ( "\\", "<", "![", "[", "`", "%", "#", "@" );
5123   $text = &MarkDownParseSpanElementsInner ($text, \@markers);
5125   # Convert 'function()' or 'macro()'.
5126   # if there is abc_*_def() we don't want to make a link to _def()
5127   # FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
5128   $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
5130   return $text;
5133 sub ReplaceEntities {
5134   my ($text, $symbol) = @_;
5135   my $warn = "";
5136   my @entities = ( [ "&lt;", "<" ],
5137                    [ "&gt;", ">" ],
5138                    [ "&ast;", "*" ],
5139                    [ "&num;", "#" ],
5140                    [ "&percnt;", "%"],
5141                    [ "&colon;", ":" ],
5142                    [ "&quot;", "\"" ],
5143                    [ "&apos;", "'" ],
5144                    [ "&nbsp;", " " ],
5145                    [ "&amp;", "&" ] ); # Do this last, or the others get messed up.
5146   my $i;
5148   # Expand entities in <programlisting> even inside CDATA since
5149   # we changed the definition of |[ to add CDATA
5150   for ($i = 0; $i <= $#entities; $i++) {
5151     if ($text =~ s/$entities[$i][0]/$entities[$i][1]/g) {
5152       # don't warn about &ast; since it is expected to be present
5153       # for C-style comments
5154       if ($entities[$i][0] ne "&ast;") {
5155         $warn .= "$entities[$i][0] ";
5156       }
5157     }
5158   }
5160   if ($warn ne "") {
5161     chomp $warn;
5162     &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
5163                  "Deprecated entities found in documentation for $symbol: $warn");
5164   }
5166   return $text;
5169 sub MarkDownOutputDocBook {
5170   my ($blocksref, $symbol, $context) = @_;
5171   my $output = "";
5172   my $block;
5173   my @blocks = @$blocksref;
5175   foreach $block (@blocks) {
5176     my $text;
5177     my $title;
5179     if ($block->{"type"} eq "paragraph") {
5180       $text = &MarkDownParseSpanElements ($block->{"text"});
5182       if ($context eq "li" && $output eq "") {
5183         if ($block->{"interrupted"}) {
5184           $output .= "\n"."<para>".$text."</para>"."\n";
5185         } else {
5186           $output .= $text;
5187           if ($#blocks > 0) {
5188             $output .= "\n";
5189           }
5190         }
5191       } else {
5192         $output .= "<para>".$text."</para>"."\n";
5193       }
5195     } elsif ($block->{"type"} eq "heading") {
5196       my $tag;
5198       $title = &MarkDownParseSpanElements ($block->{"text"});
5200       if ($block->{"level"} == 1) {
5201         $tag = "refsect2";
5202       } else {
5203         $tag = "refsect3";
5204       }
5206       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "heading");
5207       if (defined ($block->{"id"})) {
5208         $output .= "<" . $tag . " id=\"" . $block->{"id"} . "\">";
5209       } else {
5210         $output .= "<" . $tag . ">";
5211       }
5213       $output .= "<title>" . $title . "</title>" . $text . "</" . $tag . ">\n";
5214     } elsif ($block->{"type"} eq "li") {
5215       my $tag = "itemizedlist";
5217       if ($block->{"first"}) {
5218         if ($block->{"ordered"}) {
5219           $tag = "orderedlist";
5220         }
5221         $output .= "<".$tag.">\n";
5222       }
5224       if ($block->{"interrupted"}) {
5225         push $block->{"lines"}, "";
5226       }
5228       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "li");
5229       $output .= "<listitem>".$text."</listitem>\n";
5230       if ($block->{"last"}) {
5231         if ($block->{"ordered"}) {
5232           $tag = "orderedlist";
5233         }
5234         $output .= "</".$tag.">\n";
5235       }
5236     } elsif ($block->{"type"} eq "quote") {
5237       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "quote");
5238       $output .= "<blockquote>\n" . $text . "</blockquote>\n";
5239     } elsif ($block->{"type"} eq "code") {
5240       if ($block->{"language"}) {
5241         $output .= "<informalexample><programlisting language=\"" . $block->{"language"} . "\"><![CDATA[\n";
5242       } else {
5243         $output .= "<informalexample><programlisting><![CDATA[\n";
5244       }
5245       foreach (@{$block->{"lines"}}) {
5246         $output .= &ReplaceEntities ($_, $symbol) . "\n";
5247       }
5248       $output .= "]]></programlisting></informalexample>\n";
5249     } elsif ($block->{"type"} eq "markup") {
5250       $text = &ExpandAbbreviations($symbol, $block->{"text"});
5251       $output .= $text."\n";
5252     } else {
5253       $output .= $block->{"text"}."\n";
5254     }
5255   }
5257   return $output;
5260 sub MarkDownParseLines {
5261   my ($linesref, $symbol, $context) = @_;
5262   my $output;
5263   my @lines = @$linesref;
5264   my @blocks;
5266   @blocks = &MarkDownParseBlocks (\@lines, $symbol, $context);
5267   $output = &MarkDownOutputDocBook (\@blocks, $symbol, $context);
5269   return $output;
5272 sub MarkDownParse {
5273   my ($text, $symbol) = @_;
5274   my @lines;
5276   # take out some variability in line endings
5277   $text =~ s%\r\n%\n%g;
5278   $text =~ s%\r%\n%g;
5280   # split lines
5281   @lines = split("\n", $text);
5282   $text = MarkDownParseLines(\@lines, $symbol, "");
5284   return $text;
5287 #############################################################################
5288 # LIBRARY FUNCTIONS -        These functions are used in both gtkdoc-mkdb and
5289 #                        gtkdoc-mktmpl and should eventually be moved to a
5290 #                        separate library.
5291 #############################################################################
5293 #############################################################################
5294 # Function    : ReadDeclarationsFile
5295 # Description : This reads in a file containing the function/macro/enum etc.
5296 #                declarations.
5298 #                Note that in some cases there are several declarations with
5299 #                the same name, e.g. for conditional macros. In this case we
5300 #                set a flag in the %DeclarationConditional hash so the
5301 #                declaration is not shown in the docs.
5303 #                If a macro and a function have the same name, e.g. for
5304 #                gtk_object_ref, the function declaration takes precedence.
5306 #                Some opaque structs are just declared with 'typedef struct
5307 #                _name name;' in which case the declaration may be empty.
5308 #                The structure may have been found later in the header, so
5309 #                that overrides the empty declaration.
5311 # Arguments   : $file - the declarations file to read
5312 #                $override - if declarations in this file should override
5313 #                        any current declaration.
5314 #############################################################################
5316 sub ReadDeclarationsFile {
5317     my ($file, $override) = @_;
5319     if ($override == 0) {
5320         %Declarations = ();
5321         %DeclarationTypes = ();
5322         %DeclarationConditional = ();
5323         %DeclarationOutput = ();
5324     }
5326     open (INPUT, $file)
5327         || die "Can't open $file: $!";
5328     my $declaration_type = "";
5329     my $declaration_name;
5330     my $declaration;
5331     my $is_deprecated = 0;
5332     while (<INPUT>) {
5333         if (!$declaration_type) {
5334             if (m/^<([^>]+)>/) {
5335                 $declaration_type = $1;
5336                 $declaration_name = "";
5337                 #print "Found declaration: $declaration_type\n";
5338                 $declaration = "";
5339             }
5340         } else {
5341             if (m%^<NAME>(.*)</NAME>%) {
5342                 $declaration_name = $1;
5343             } elsif (m%^<DEPRECATED/>%) {
5344                 $is_deprecated = 1;
5345             } elsif (m%^</$declaration_type>%) {
5346                 #print "Found end of declaration: $declaration_name\n";
5347                 # Check that the declaration has a name
5348                 if ($declaration_name eq "") {
5349                     print "ERROR: $declaration_type has no name $file:$.\n";
5350                 }
5352                 # If the declaration is an empty typedef struct _XXX XXX
5353                 # set the flag to indicate the struct has a typedef.
5354                 if ($declaration_type eq 'STRUCT'
5355                     && $declaration =~ m/^\s*$/) {
5356                     #print "Struct has typedef: $declaration_name\n";
5357                     $StructHasTypedef{$declaration_name} = 1;
5358                 }
5360                 # Check if the symbol is already defined.
5361                 if (defined ($Declarations{$declaration_name})
5362                     && $override == 0) {
5363                     # Function declarations take precedence.
5364                     if ($DeclarationTypes{$declaration_name} eq 'FUNCTION') {
5365                         # Ignore it.
5366                     } elsif ($declaration_type eq 'FUNCTION') {
5367                         if ($is_deprecated) {
5368                             $Deprecated{$declaration_name} = "";
5369                         }
5370                         $Declarations{$declaration_name} = $declaration;
5371                         $DeclarationTypes{$declaration_name} = $declaration_type;
5372                     } elsif ($DeclarationTypes{$declaration_name}
5373                               eq $declaration_type) {
5374                         # If the existing declaration is empty, or is just a
5375                         # forward declaration of a struct, override it.
5376                         if ($declaration_type eq 'STRUCT') {
5377                             if ($Declarations{$declaration_name} =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5378                                 if ($is_deprecated) {
5379                                     $Deprecated{$declaration_name} = "";
5380                                 }
5381                                 $Declarations{$declaration_name} = $declaration;
5382                             } elsif ($declaration =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5383                                 # Ignore an empty or forward declaration.
5384                             } else {
5385                                 &LogWarning ($file, $., "Structure $declaration_name has multiple definitions.");
5386                             }
5387                         } else {
5388                             # set flag in %DeclarationConditional hash for
5389                             # multiply defined macros/typedefs.
5390                             $DeclarationConditional{$declaration_name} = 1;
5391                         }
5392                     } else {
5393                         &LogWarning ($file, $., "$declaration_name has multiple definitions.");
5394                     }
5395                 } else {
5396                     if ($is_deprecated) {
5397                         $Deprecated{$declaration_name} = "";
5398                     }
5399                     $Declarations{$declaration_name} = $declaration;
5400                     $DeclarationTypes{$declaration_name} = $declaration_type;
5401                 }
5403                 $declaration_type = "";
5404                 $is_deprecated = 0;
5405             } else {
5406                 $declaration .= $_;
5407             }
5408         }
5409     }
5410     close (INPUT);
5414 #############################################################################
5415 # Function    : ReadSignalsFile
5416 # Description : This reads in an existing file which contains information on
5417 #                all GTK signals. It creates the arrays @SignalNames and
5418 #                @SignalPrototypes containing info on the signals. The first
5419 #                line of the SignalPrototype is the return type of the signal
5420 #                handler. The remaining lines are the parameters passed to it.
5421 #                The last parameter, "gpointer user_data" is always the same
5422 #                so is not included.
5423 # Arguments   : $file - the file containing the signal handler prototype
5424 #                        information.
5425 #############################################################################
5427 sub ReadSignalsFile {
5428     my ($file) = @_;
5430     my $in_signal = 0;
5431     my $signal_object;
5432     my $signal_name;
5433     my $signal_returns;
5434     my $signal_flags;
5435     my $signal_prototype;
5437     # Reset the signal info.
5438     @SignalObjects = ();
5439     @SignalNames = ();
5440     @SignalReturns = ();
5441     @SignalFlags = ();
5442     @SignalPrototypes = ();
5444     if (! -f $file) {
5445         return;
5446     }
5447     if (!open (INPUT, $file)) {
5448         warn "Can't open $file - skipping signals\n";
5449         return;
5450     }
5451     while (<INPUT>) {
5452         if (!$in_signal) {
5453             if (m/^<SIGNAL>/) {
5454                 $in_signal = 1;
5455                 $signal_object = "";
5456                 $signal_name = "";
5457                 $signal_returns = "";
5458                 $signal_prototype = "";
5459             }
5460         } else {
5461             if (m/^<NAME>(.*)<\/NAME>/) {
5462                 $signal_name = $1;
5463                 if ($signal_name =~ m/^(.*)::(.*)$/) {
5464                     $signal_object = $1;
5465                     ($signal_name = $2) =~ s/_/-/g;
5466                     #print "Found signal: $signal_name\n";
5467                 } else {
5468                     &LogWarning ($file, $., "Invalid signal name: $signal_name.");
5469                 }
5470             } elsif (m/^<RETURNS>(.*)<\/RETURNS>/) {
5471                 $signal_returns = $1;
5472             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5473                 $signal_flags = $1;
5474             } elsif (m%^</SIGNAL>%) {
5475                 #print "Found end of signal: ${signal_object}::${signal_name}\nReturns: ${signal_returns}\n${signal_prototype}";
5476                 push (@SignalObjects, $signal_object);
5477                 push (@SignalNames, $signal_name);
5478                 push (@SignalReturns, $signal_returns);
5479                 push (@SignalFlags, $signal_flags);
5480                 push (@SignalPrototypes, $signal_prototype);
5481                 $in_signal = 0;
5482             } else {
5483                 $signal_prototype .= $_;
5484             }
5485         }
5486     }
5487     close (INPUT);
5491 #############################################################################
5492 # Function    : ReadTemplateFile
5493 # Description : This reads in the manually-edited documentation file
5494 #               corresponding to the file currently being created, so we can
5495 #               insert the documentation at the appropriate places.
5496 #               It outputs %SymbolTypes, %SymbolDocs and %SymbolParams, which
5497 #               is a hash of arrays.
5498 #               NOTE: This function is duplicated in gtkdoc-mktmpl (but
5499 #               slightly different).
5500 # Arguments   : $docsfile - the template file to read in.
5501 #               $skip_unused_params - 1 if the unused parameters should be
5502 #                 skipped.
5503 #############################################################################
5505 sub ReadTemplateFile {
5506     my ($docsfile, $skip_unused_params) = @_;
5508     my $template = "$docsfile.sgml";
5509     if (! -f $template) {
5510         #print "File doesn't exist: $template\n";
5511         return 0;
5512     }
5514     # start with empty hashes, we merge the source comment for each file
5515     # afterwards
5516     %SymbolDocs = ();
5517     %SymbolTypes = ();
5518     %SymbolParams = ();
5520     my $current_type = "";        # Type of symbol being read.
5521     my $current_symbol = "";        # Name of symbol being read.
5522     my $symbol_doc = "";                # Description of symbol being read.
5523     my @params;                        # Parameter names and descriptions of current
5524                                 #   function/macro/function typedef.
5525     my $current_param = -1;        # Index of parameter currently being read.
5526                                 #   Note that the param array contains pairs
5527                                 #   of param name & description.
5528     my $in_unused_params = 0;        # True if we are reading in the unused params.
5529     my $in_deprecated = 0;
5530     my $in_since = 0;
5531     my $in_stability = 0;
5533     open (DOCS, "$template")
5534         || die "Can't open $template: $!";
5536     @TRACE@("reading template $template");
5538     while (<DOCS>) {
5539         if (m/^<!-- ##### ([A-Z_]+) (\S+) ##### -->/) {
5540             my $type = $1;
5541             my $symbol = $2;
5542             if ($symbol eq "Title"
5543                 || $symbol eq "Short_Description"
5544                 || $symbol eq "Long_Description"
5545                 || $symbol eq "See_Also"
5546                 || $symbol eq "Stability_Level"
5547                 || $symbol eq "Include"
5548                 || $symbol eq "Image") {
5550                 $symbol = $docsfile . ":" . $symbol;
5551             }
5553             #print "Found symbol: $symbol\n";
5554             # Remember file and line for the symbol
5555             $SymbolSourceFile{$symbol} = $template;
5556             $SymbolSourceLine{$symbol} = $.;
5558             # Store previous symbol, but remove any trailing blank lines.
5559             if ($current_symbol ne "") {
5560                 $symbol_doc =~ s/\s+$//;
5561                 $SymbolTypes{$current_symbol} = $current_type;
5562                 $SymbolDocs{$current_symbol} = $symbol_doc;
5564                 # Check that the stability level is valid.
5565                 if ($StabilityLevel{$current_symbol}) {
5566                     $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5567                 }
5569                 if ($current_param >= 0) {
5570                     $SymbolParams{$current_symbol} = [ @params ];
5571                 } else {
5572                     # Delete any existing params in case we are overriding a
5573                     # previously read template.
5574                     delete $SymbolParams{$current_symbol};
5575                 }
5576             }
5577             $current_type = $type;
5578             $current_symbol = $symbol;
5579             $current_param = -1;
5580             $in_unused_params = 0;
5581             $in_deprecated = 0;
5582             $in_since = 0;
5583             $in_stability = 0;
5584             $symbol_doc = "";
5585             @params = ();
5587         } elsif (m/^<!-- # Unused Parameters # -->/) {
5588             #print "DEBUG: Found unused parameters\n";
5589             $in_unused_params = 1;
5590             next;
5592         } elsif ($in_unused_params && $skip_unused_params) {
5593             # When outputting the DocBook we skip unused parameters.
5594             #print "DEBUG: Skipping unused param: $_";
5595             next;
5597         } else {
5598             # Check if param found. Need to handle "..." and "format...".
5599             if (s/^\@([\w\.]+):\040?//) {
5600                 my $param_name = $1;
5601                 my $param_desc = $_;
5602                 # Allow variations of 'Returns'
5603                 if ($param_name =~ m/^[Rr]eturns?$/) {
5604                     $param_name = "Returns";
5605                 }
5606                 # Allow varargs variations
5607                 if ($param_name =~ m/^.*\.\.\.$/) {
5608                     $param_name = "...";
5609                 }
5611                 # strip trailing whitespaces and blank lines
5612                 s/\s+\n$/\n/m;
5613                 s/\n+$/\n/sm;
5614                 @TRACE@("Found param for symbol $current_symbol : '$param_name'= '$_'");
5616                 if ($param_name eq "Deprecated") {
5617                     $in_deprecated = 1;
5618                     $Deprecated{$current_symbol} = $_;
5619                 } elsif ($param_name eq "Since") {
5620                     $in_since = 1;
5621                     chomp;
5622                     $Since{$current_symbol} = $_;
5623                 } elsif ($param_name eq "Stability") {
5624                     $in_stability = 1;
5625                     $StabilityLevel{$current_symbol} = $_;
5626                 } else {
5627                     push (@params, $param_name);
5628                     push (@params, $param_desc);
5629                     $current_param += $PARAM_FIELD_COUNT;
5630                 }
5631             } else {
5632                 # strip trailing whitespaces and blank lines
5633                 s/\s+\n$/\n/m;
5634                 s/\n+$/\n/sm;
5636                 if (!m/^\s+$/) {
5637                     if ($in_deprecated) {
5638                         $Deprecated{$current_symbol} .= $_;
5639                     } elsif ($in_since) {
5640                         &LogWarning ($template, $., "multi-line since docs found");
5641                         #$Since{$current_symbol} .= $_;
5642                     } elsif ($in_stability) {
5643                         $StabilityLevel{$current_symbol} .= $_;
5644                     } elsif ($current_param >= 0) {
5645                         $params[$current_param] .= $_;
5646                     } else {
5647                         $symbol_doc .= $_;
5648                     }
5649                 }
5650             }
5651         }
5652     }
5654     # Remember to finish the current symbol doccs.
5655     if ($current_symbol ne "") {
5657         $symbol_doc =~ s/\s+$//;
5658         $SymbolTypes{$current_symbol} = $current_type;
5659         $SymbolDocs{$current_symbol} = $symbol_doc;
5661         # Check that the stability level is valid.
5662         if ($StabilityLevel{$current_symbol}) {
5663             $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5664         }
5666         if ($current_param >= 0) {
5667             $SymbolParams{$current_symbol} = [ @params ];
5668         } else {
5669             # Delete any existing params in case we are overriding a
5670             # previously read template.
5671             delete $SymbolParams{$current_symbol};
5672         }
5673     }
5675     close (DOCS);
5676     return 1;
5680 #############################################################################
5681 # Function    : ReadObjectHierarchy
5682 # Description : This reads in the $MODULE-hierarchy.txt file containing all
5683 #                the GtkObject subclasses described in this module (and their
5684 #                ancestors).
5685 #                It places them in the @Objects array, and places their level
5686 #                in the object hierarchy in the @ObjectLevels array, at the
5687 #                same index. GtkObject, the root object, has a level of 1.
5689 #               FIXME: the version in gtkdoc-mkdb also generates tree_index.sgml
5690 #               as it goes along, this should be split out into a separate
5691 #               function.
5693 # Arguments   : none
5694 #############################################################################
5696 sub ReadObjectHierarchy {
5697     @Objects = ();
5698     @ObjectLevels = ();
5700     if (! -f $OBJECT_TREE_FILE) {
5701         return;
5702     }
5703     if (!open (INPUT, $OBJECT_TREE_FILE)) {
5704         warn "Can't open $OBJECT_TREE_FILE - skipping object tree\n";
5705         return;
5706     }
5708     # FIXME: use $OUTPUT_FORMAT
5709     # my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.$OUTPUT_FORMAT";
5710     my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.sgml";
5711     my $new_tree_index = "$SGML_OUTPUT_DIR/tree_index.new";
5713     open (OUTPUT, ">$new_tree_index")
5714         || die "Can't create $new_tree_index: $!";
5716     if ($OUTPUT_FORMAT eq "xml") {
5717         my $tree_header = $doctype_header;
5719         $tree_header =~ s/<!DOCTYPE \w+/<!DOCTYPE screen/;
5720         print (OUTPUT "$tree_header");
5721     }
5722     print (OUTPUT "<screen>\n");
5724     # Only emit objects if they are supposed to be documented, or if
5725     # they have documented children. To implement this, we maintain a
5726     # stack of pending objects which will be emitted if a documented
5727     # child turns up.
5728     my @pending_objects = ();
5729     my @pending_levels = ();
5730     my $root;
5731     while (<INPUT>) {
5732         if (m/\S+/) {
5733             my $object = $&;
5734             my $level = (length($`)) / 2 + 1;
5735             my $xref = "";
5737             if ($level == 1) {
5738                 $root = $object;
5739             }
5741             while (($#pending_levels >= 0) && ($pending_levels[$#pending_levels] >= $level)) {
5742                 my $pobject = pop(@pending_objects);
5743                 my $plevel = pop(@pending_levels);
5744             }
5746                push (@pending_objects, $object);
5747             push (@pending_levels, $level);
5749             if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
5750                    while ($#pending_levels >= 0) {
5751                     $object = shift @pending_objects;
5752                     $level = shift @pending_levels;
5753                        $xref = &MakeXRef ($object);
5755                      print (OUTPUT ' ' x ($level * 4), "$xref\n");
5756                     push (@Objects, $object);
5757                     push (@ObjectLevels, $level);
5758                     $ObjectRoots{$object} = $root;
5759                 }
5760             }
5761             #else {
5762             #    LogWarning ($OBJECT_TREE_FILE, $., "unknown type $object");
5763             #}
5764         }
5765     }
5766     print (OUTPUT "</screen>\n");
5768     close (INPUT);
5769     close (OUTPUT);
5771     &UpdateFileIfChanged ($old_tree_index, $new_tree_index, 0);
5773     &OutputObjectList;
5776 #############################################################################
5777 # Function    : ReadInterfaces
5778 # Description : This reads in the $MODULE.interfaces file.
5780 # Arguments   : none
5781 #############################################################################
5783 sub ReadInterfaces {
5784     %Interfaces = ();
5786     if (! -f $INTERFACES_FILE) {
5787         return;
5788     }
5789     if (!open (INPUT, $INTERFACES_FILE)) {
5790         warn "Can't open $INTERFACES_FILE - skipping interfaces\n";
5791         return;
5792     }
5794     while (<INPUT>) {
5795        chomp;
5796        my ($object, @ifaces) = split;
5797        if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
5798            my @knownIfaces = ();
5800            # filter out private interfaces, but leave foreign interfaces
5801            foreach my $iface (@ifaces) {
5802                if (!exists($KnownSymbols{$iface}) || $KnownSymbols{$iface} == 1) {
5803                    push (@knownIfaces, $iface);
5804                }
5805              }
5807            $Interfaces{$object} = join(' ', @knownIfaces);
5808        }
5809     }
5810     close (INPUT);
5813 #############################################################################
5814 # Function    : ReadPrerequisites
5815 # Description : This reads in the $MODULE.prerequisites file.
5817 # Arguments   : none
5818 #############################################################################
5820 sub ReadPrerequisites {
5821     %Prerequisites = ();
5823     if (! -f $PREREQUISITES_FILE) {
5824         return;
5825     }
5826     if (!open (INPUT, $PREREQUISITES_FILE)) {
5827         warn "Can't open $PREREQUISITES_FILE - skipping prerequisites\n";
5828         return;
5829     }
5831     while (<INPUT>) {
5832        chomp;
5833        my ($iface, @prereqs) = split;
5834        if (exists($KnownSymbols{$iface}) && $KnownSymbols{$iface} == 1) {
5835            my @knownPrereqs = ();
5837            # filter out private prerequisites, but leave foreign prerequisites
5838            foreach my $prereq (@prereqs) {
5839                if (!exists($KnownSymbols{$prereq}) || $KnownSymbols{$prereq} == 1) {
5840                   push (@knownPrereqs, $prereq);
5841                }
5842            }
5844            $Prerequisites{$iface} = join(' ', @knownPrereqs);
5845        }
5846     }
5847     close (INPUT);
5850 #############################################################################
5851 # Function    : ReadArgsFile
5852 # Description : This reads in an existing file which contains information on
5853 #                all GTK args. It creates the arrays @ArgObjects, @ArgNames,
5854 #                @ArgTypes, @ArgFlags, @ArgNicks and @ArgBlurbs containing info
5855 #               on the args.
5856 # Arguments   : $file - the file containing the arg information.
5857 #############################################################################
5859 sub ReadArgsFile {
5860     my ($file) = @_;
5862     my $in_arg = 0;
5863     my $arg_object;
5864     my $arg_name;
5865     my $arg_type;
5866     my $arg_flags;
5867     my $arg_nick;
5868     my $arg_blurb;
5869     my $arg_default;
5870     my $arg_range;
5872     # Reset the args info.
5873     @ArgObjects = ();
5874     @ArgNames = ();
5875     @ArgTypes = ();
5876     @ArgFlags = ();
5877     @ArgNicks = ();
5878     @ArgBlurbs = ();
5879     @ArgDefaults = ();
5880     @ArgRanges = ();
5882     if (! -f $file) {
5883         return;
5884     }
5885     if (!open (INPUT, $file)) {
5886         warn "Can't open $file - skipping args\n";
5887         return;
5888     }
5889     while (<INPUT>) {
5890         if (!$in_arg) {
5891             if (m/^<ARG>/) {
5892                 $in_arg = 1;
5893                 $arg_object = "";
5894                 $arg_name = "";
5895                 $arg_type = "";
5896                 $arg_flags = "";
5897                 $arg_nick = "";
5898                 $arg_blurb = "";
5899                 $arg_default = "";
5900                 $arg_range = "";
5901             }
5902         } else {
5903             if (m/^<NAME>(.*)<\/NAME>/) {
5904                 $arg_name = $1;
5905                 if ($arg_name =~ m/^(.*)::(.*)$/) {
5906                     $arg_object = $1;
5907                     ($arg_name = $2) =~ s/_/-/g;
5908                     #print "Found arg: $arg_name\n";
5909                 } else {
5910                     &LogWarning ($file, $., "Invalid argument name: $arg_name");
5911                 }
5912             } elsif (m/^<TYPE>(.*)<\/TYPE>/) {
5913                 $arg_type = $1;
5914             } elsif (m/^<RANGE>(.*)<\/RANGE>/) {
5915                 $arg_range = $1;
5916             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5917                 $arg_flags = $1;
5918             } elsif (m/^<NICK>(.*)<\/NICK>/) {
5919                 $arg_nick = $1;
5920             } elsif (m/^<BLURB>(.*)<\/BLURB>/) {
5921                 $arg_blurb = $1;
5922                 if ($arg_blurb eq "(null)") {
5923                   $arg_blurb = "";
5924                   &LogWarning ($file, $., "Property ${arg_object}:${arg_name} has no documentation.");
5925                 }
5926             } elsif (m/^<DEFAULT>(.*)<\/DEFAULT>/) {
5927                 $arg_default = $1;
5928             } elsif (m%^</ARG>%) {
5929                 #print "Found end of arg: ${arg_object}::${arg_name}\n${arg_type} : ${arg_flags}\n";
5930                 push (@ArgObjects, $arg_object);
5931                 push (@ArgNames, $arg_name);
5932                 push (@ArgTypes, $arg_type);
5933                 push (@ArgRanges, $arg_range);
5934                 push (@ArgFlags, $arg_flags);
5935                 push (@ArgNicks, $arg_nick);
5936                 push (@ArgBlurbs, $arg_blurb);
5937                 push (@ArgDefaults, $arg_default);
5938                 $in_arg = 0;
5939             }
5940         }
5941     }
5942     close (INPUT);
5946 #############################################################################
5947 # Function    : CheckIsObject
5948 # Description : Returns 1 if the given name is a GObject or a subclass.
5949 #                It uses the global @Objects array.
5950 #                Note that the @Objects array only contains classes in the
5951 #                current module and their ancestors - not all GObject classes.
5952 # Arguments   : $name - the name to check.
5953 #############################################################################
5955 sub CheckIsObject {
5956     my ($name) = @_;
5957     my $root = $ObjectRoots{$name};
5958     # Let GBoxed pass as an object here to get -struct appended to the id
5959     # and prevent conflicts with sections.
5960     return defined($root) and $root ne 'GEnum' and $root ne 'GFlags';
5964 #############################################################################
5965 # Function    : MakeReturnField
5966 # Description : Pads a string to $RETURN_TYPE_FIELD_WIDTH.
5967 # Arguments   : $str - the string to pad.
5968 #############################################################################
5970 sub MakeReturnField {
5971     my ($str) = @_;
5973     return $str . (' ' x ($RETURN_TYPE_FIELD_WIDTH - length ($str)));
5976 #############################################################################
5977 # Function    : GetSymbolSourceFile
5978 # Description : Get the filename where the symbol docs where taken from.
5979 # Arguments   : $symbol - the symbol name
5980 #############################################################################
5982 sub GetSymbolSourceFile {
5983     my ($symbol) = @_;
5985     if (defined($SourceSymbolSourceFile{$symbol})) {
5986         return $SourceSymbolSourceFile{$symbol};
5987     } elsif (defined($SymbolSourceFile{$symbol})) {
5988         return $SymbolSourceFile{$symbol};
5989     } else {
5990         return "";
5991     }
5994 #############################################################################
5995 # Function    : GetSymbolSourceLine
5996 # Description : Get the file line where the symbol docs where taken from.
5997 # Arguments   : $symbol - the symbol name
5998 #############################################################################
6000 sub GetSymbolSourceLine {
6001     my ($symbol) = @_;
6003     if (defined($SourceSymbolSourceLine{$symbol})) {
6004         return $SourceSymbolSourceLine{$symbol};
6005     } elsif (defined($SymbolSourceLine{$symbol})) {
6006         return $SymbolSourceLine{$symbol};
6007     } else {
6008         return 0;
6009     }