mkdb: fix CheckIsObject return value
[gtk-doc.git] / gtkdoc-mkdb.in
blob8dfeb1dfb073464261488c20dbdd1100d7f0f9f2
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) = @_;
1705     my $is_gtype = 0;
1706     if (&CheckIsObject ($symbol)) {
1707         @TRACE@("Found union gtype: $symbol\n");
1708         $is_gtype = 1;
1709     }
1711     my $id;
1712     my $condition;
1713     if ($is_gtype) {
1714         $id = &CreateValidSGMLID ($symbol . "_union");
1715         $condition = &MakeConditionDescription ($symbol . "_union");
1716     } else {
1717         $id = &CreateValidSGMLID ($symbol);
1718         $condition = &MakeConditionDescription ($symbol);
1719     }
1721     # Determine if it is a simple struct or it also has a typedef.
1722     my $has_typedef = 0;
1723     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1724       $has_typedef = 1;
1725     }
1727     my $synop;
1728     my $desc;
1729     if ($has_typedef) {
1730         # For unions with typedefs we just output the union name.
1731         $synop = &MakeReturnField("") . "<link linkend=\"$id\">$symbol</link>;\n";
1732         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>$symbol</title>\n";
1733     } else {
1734         $synop = &MakeReturnField("union") . "<link linkend=\"$id\">$symbol</link>;\n";
1735         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>union $symbol</title>\n";
1736     }
1738     $desc .= MakeIndexterms($symbol, $id);
1739     $desc .= "\n";
1740     $desc .= OutputSymbolExtraLinks($symbol);
1742     # FIXME: we do more for structs
1743     my $decl_out = &CreateValidSGML ($declaration);
1744     $desc .= "<programlisting>$decl_out</programlisting>\n";
1746     $desc .= &MakeDeprecationNote($symbol);
1748     if (defined ($SymbolDocs{$symbol})) {
1749         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1750     }
1752     # Create a table of fields and descriptions
1754     # FIXME: Inserting &#160's into the produced type declarations here would
1755     #        improve the output in most situations ... except for function
1756     #        members of structs!
1757     my @fields = ParseStructDeclaration($declaration, 0,
1758                                         0, \&MakeXRef,
1759                                         sub {
1760                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1761                                         });
1762     my $params = $SymbolParams{$symbol};
1764     # If no parameters are filled in, we don't generate the description
1765     # table, for backwards compatibility
1767     my $found = 0;
1768     if (defined $params) {
1769         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1770             if ($params->[$i] =~ /\S/) {
1771                 $found = 1;
1772                 last;
1773             }
1774         }
1775     }
1777     if ($found) {
1778         my %field_descrs = @$params;
1779         my $missing_parameters = "";
1780         my $unused_parameters = "";
1782         $desc .= "<variablelist role=\"union\">\n";
1783         while (@fields) {
1784             my $field_name = shift @fields;
1785             my $text = shift @fields;
1786             my $field_descr = $field_descrs{$field_name};
1787             my $param_annotations = "";
1789             $desc .= "<varlistentry><term>$text</term>\n";
1790             if (defined $field_descr) {
1791                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1792                 $field_descr = &ConvertMarkDown($symbol, $field_descr);
1793                 $field_descr .= $param_annotations;
1794                 # trim
1795                 $field_descr =~ s/^(\s|\n)+//msg;
1796                 $field_descr =~ s/(\s|\n)+$//msg;
1797                 $desc .= "<listitem>$field_descr</listitem>\n";
1798                 delete $field_descrs{$field_name};
1799             } else {
1800                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1801                     "Field description for $symbol"."::"."$field_name is missing in source code comment block.");
1802                 if ($missing_parameters ne "") {
1803                     $missing_parameters .= ", ".$field_name;
1804                 } else {
1805                     $missing_parameters = $field_name;
1806                 }
1807                 $desc .= "<listitem />\n";
1808             }
1809             $desc .= "</varlistentry>\n";
1810         }
1811         $desc .= "</variablelist>";
1812         foreach my $field_name (keys %field_descrs) {
1813             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1814                 "Field description for $symbol"."::"."$field_name is not used from source code comment block.");
1815             if ($unused_parameters ne "") {
1816               $unused_parameters .= ", ".$field_name;
1817             } else {
1818                $unused_parameters = $field_name;
1819             }
1820         }
1822         # remember missing/unused parameters (needed in tmpl-free build)
1823         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1824             $AllIncompleteSymbols{$symbol}=$missing_parameters;
1825         }
1826         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1827             $AllUnusedSymbols{$symbol}=$unused_parameters;
1828         }
1829     }
1830     else {
1831         if (scalar(@fields) > 0) {
1832             if (! exists ($AllIncompleteSymbols{$symbol})) {
1833                 $AllIncompleteSymbols{$symbol}="<items>";
1834                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1835                     "Field descriptions for union $symbol are missing in source code comment block.");
1836                 @TRACE@("Remaining union fields: ".@fields.":".join(',',@fields)."\n");
1837             }
1838         }
1839     }
1841     $desc .= OutputSymbolTraits ($symbol);
1842     $desc .= "</refsect2>\n";
1843     return ($synop, $desc);
1847 #############################################################################
1848 # Function    : OutputEnum
1849 # Description : Returns the synopsis and detailed description of a enum.
1850 # Arguments   : $symbol - the enum.
1851 #                $declaration - the declaration of the enum.
1852 #############################################################################
1854 sub OutputEnum {
1855     my ($symbol, $declaration) = @_;
1857     my $is_gtype = 0;
1858     if (&CheckIsObject ($symbol)) {
1859         #print "Found enum gtype: $symbol\n";
1860         $is_gtype = 1;
1861     }
1863     my $id;
1864     my $condition;
1865     if ($is_gtype) {
1866         $id = &CreateValidSGMLID ($symbol . "_enum");
1867         $condition = &MakeConditionDescription ($symbol . "_enum");
1868     } else {
1869         $id = &CreateValidSGMLID ($symbol);
1870         $condition = &MakeConditionDescription ($symbol);
1871     }
1873     my $synop = &MakeReturnField("enum") . "<link linkend=\"$id\">$symbol</link>;\n";
1874     my $desc = "<refsect2 id=\"$id\" role=\"enum\"$condition>\n<title>enum $symbol</title>\n";
1876     $desc .= MakeIndexterms($symbol, $id);
1877     $desc .= "\n";
1878     $desc .= OutputSymbolExtraLinks($symbol);
1880     my $decl_out = "";
1881     my $public = 1;
1882     my $new_declaration = "";
1883     my $decl_line;
1884     my $decl = $declaration;
1886     if ($decl =~ m/^\s*(typedef\s+)?enum\s*\w*\s*(?:\/\*.*\*\/)?\s*{(.*)}\s*\w*\s*;\s*$/s) {
1887         my $has_typedef = defined($1) ? 1 : 0;
1888         my $enum_contents = $2;
1890         foreach $decl_line (split (/\n/, $enum_contents)) {
1891             #print "Enum line: $decl_line\n";
1892             if ($decl_line =~ m%/\*\s*<\s*public\s*>\s*\*/%) {
1893                 $public = 1;
1894             } elsif ($decl_line =~ m%/\*\s*<\s*(private|protected)\s*>\s*\*/%) {
1895                 $public = 0;
1896             } elsif ($public) {
1897                 $new_declaration .= $decl_line . "\n";
1898             }
1899         }
1901         if ($new_declaration) {
1902             # Strip any blank lines off the ends.
1903             $new_declaration =~ s/^\s*\n//;
1904             $new_declaration =~ s/\n\s*$/\n/;
1906             if ($has_typedef) {
1907                 $decl_out = "typedef enum {\n" . $new_declaration
1908                   . "} $symbol;\n";
1909             } else {
1910                 $decl_out = "enum $symbol {\n" . $new_declaration
1911                   . "};\n";
1912             }
1913         }
1914     }
1916     $decl_out = &CreateValidSGML ($decl_out);
1917     $desc .= "<programlisting>$decl_out</programlisting>\n";
1919     $desc .= &MakeDeprecationNote($symbol);
1921     if (defined ($SymbolDocs{$symbol})) {
1922         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1923     }
1925     # Create a table of fields and descriptions
1927     my @fields = ParseEnumDeclaration($declaration);
1928     my $params = $SymbolParams{$symbol};
1930     # If nothing at all is documented log a single summary warning at the end.
1931     # Otherwise, warn about each undocumented item.
1933     my $found = 0;
1934     if (defined $params) {
1935         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1936             if ($params->[$i] =~ /\S/) {
1937                 $found = 1;
1938                 last;
1939             }
1940         }
1941     }
1943     my %field_descrs = (defined $params ? @$params : ());
1944     my $missing_parameters = "";
1945     my $unused_parameters = "";
1947     $desc .= "<variablelist role=\"enum\">\n";
1948     for my $field_name (@fields) {
1949         my $field_descr = $field_descrs{$field_name};
1950         my $param_annotations = "";
1952         $id = &CreateValidSGMLID ($field_name);
1953         $condition = &MakeConditionDescription ($field_name);
1954         $desc .= "<varlistentry id=\"$id\" role=\"constant\"$condition>\n<term><literal>$field_name</literal></term>\n";
1955         if (defined $field_descr) {
1956             ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1957             $field_descr = &ConvertMarkDown($symbol, $field_descr);
1958             $desc .= "<listitem>$field_descr$param_annotations</listitem>\n";
1959             delete $field_descrs{$field_name};
1960         } else {
1961             if ($found) {
1962                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1963                     "Value description for $symbol"."::"."$field_name is missing in source code comment block.");
1964                 if ($missing_parameters ne "") {
1965                     $missing_parameters .= ", ".$field_name;
1966                 } else {
1967                     $missing_parameters = $field_name;
1968                 }
1969             }
1970             $desc .= "<listitem />\n";
1971         }
1972         $desc .= "</varlistentry>\n";
1973     }
1974     $desc .= "</variablelist>";
1975     foreach my $field_name (keys %field_descrs) {
1976         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1977             "Value description for $symbol"."::"."$field_name is not used from source code comment block.");
1978         if ($unused_parameters ne "") {
1979             $unused_parameters .= ", ".$field_name;
1980         } else {
1981             $unused_parameters = $field_name;
1982         }
1983     }
1985     # remember missing/unused parameters (needed in tmpl-free build)
1986     if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1987         $AllIncompleteSymbols{$symbol}=$missing_parameters;
1988     }
1989     if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1990         $AllUnusedSymbols{$symbol}=$unused_parameters;
1991     }
1993     if (!$found) {
1994         if (scalar(@fields) > 0) {
1995             if (! exists ($AllIncompleteSymbols{$symbol})) {
1996                 $AllIncompleteSymbols{$symbol}="<items>";
1997                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1998                     "Value descriptions for $symbol are missing in source code comment block.");
1999             }
2000         }
2001     }
2003     $desc .= OutputSymbolTraits ($symbol);
2004     $desc .= "</refsect2>\n";
2005     return ($synop, $desc);
2009 #############################################################################
2010 # Function    : OutputVariable
2011 # Description : Returns the synopsis and detailed description of a variable.
2012 # Arguments   : $symbol - the extern'ed variable.
2013 #                $declaration - the declaration of the variable.
2014 #############################################################################
2016 sub OutputVariable {
2017     my ($symbol, $declaration) = @_;
2018     my $id = &CreateValidSGMLID ($symbol);
2019     my $condition = &MakeConditionDescription ($symbol);
2020     
2021     @TRACE@("ouputing variable: '$symbol' '$declaration'");
2023     my $synop;
2024     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*;/) {
2025         my $mod1 = defined ($1) ? $1 : "";
2026         my $ptr = defined ($3) ? $3 : "";
2027         my $space = defined ($4) ? $4 : "";
2028         my $mod2 = defined ($5) ? $5 : "";
2029         $synop = &MakeReturnField("extern $mod1$ptr$space$mod2") . "<link linkend=\"$id\">$symbol</link>;\n";
2030     } 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*=/) {
2031         my $mod1 = defined ($1) ? $1 : "";
2032         my $ptr = defined ($3) ? $3 : "";
2033         my $space = defined ($4) ? $4 : "";
2034         my $mod2 = defined ($5) ? $5 : "";
2035         $synop = &MakeReturnField("$mod1$ptr$space$mod2") . "<link linkend=\"$id\">$symbol</link>;\n";
2037     } else {
2038         $synop = &MakeReturnField("extern") . "<link linkend=\"$id\">$symbol</link>;\n";
2039     }
2041     my $desc = "<refsect2 id=\"$id\" role=\"variable\"$condition>\n<title>$symbol</title>\n";
2043     $desc .= MakeIndexterms($symbol, $id);
2044     $desc .= "\n";
2045     $desc .= OutputSymbolExtraLinks($symbol);
2047     my $decl_out = &CreateValidSGML ($declaration);
2048     $desc .= "<programlisting>$decl_out</programlisting>\n";
2050     $desc .= &MakeDeprecationNote($symbol);
2052     if (defined ($SymbolDocs{$symbol})) {
2053         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
2054     }
2055     $desc .= OutputSymbolTraits ($symbol);
2056     $desc .= "</refsect2>\n";
2057     return ($synop, $desc);
2061 #############################################################################
2062 # Function    : OutputFunction
2063 # Description : Returns the synopsis and detailed description of a function.
2064 # Arguments   : $symbol - the function.
2065 #                $declaration - the declaration of the function.
2066 #############################################################################
2068 sub OutputFunction {
2069     my ($symbol, $declaration, $symbol_type) = @_;
2070     my $id = &CreateValidSGMLID ($symbol);
2071     my $condition = &MakeConditionDescription ($symbol);
2073     # Take out the return type     $1                                                                                       $2   $3
2074     $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//;
2075     my $type_modifier = defined($1) ? $1 : "";
2076     my $type = $2;
2077     my $pointer = $3;
2078     # Trim trailing spaces as we are going to pad to $RETURN_TYPE_FIELD_WIDTH below anyway
2079     $pointer =~ s/\s+$//;
2080     my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
2081     my $start = "";
2082     #if ($symbol_type eq 'USER_FUNCTION') {
2083     #    $start = "typedef ";
2084     #}
2086     # We output const rather than G_CONST_RETURN.
2087     $type_modifier =~ s/G_CONST_RETURN/const/g;
2088     $pointer =~ s/G_CONST_RETURN/const/g;
2089     $pointer =~ s/^\s+/ /g;
2091     my $ret_type_len = length ($start) + length ($type_modifier)+ length ($type)
2092         + length ($pointer);
2093     my $ret_type_output;
2094     my $symbol_len;
2095     if ($ret_type_len < $RETURN_TYPE_FIELD_WIDTH) {
2096         $ret_type_output = "$start$type_modifier$xref$pointer"
2097             . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
2098         $symbol_len = 0;
2099     } else {
2100         #$ret_type_output = "$start$type_modifier$xref$pointer\n" . (' ' x $RETURN_TYPE_FIELD_WIDTH);
2102         $ret_type_output = "$start$type_modifier$xref$pointer ";
2103         $symbol_len = $ret_type_len + 1 - $RETURN_TYPE_FIELD_WIDTH;
2104     }
2105     #@TRACE@("$symbol ret type output: [$ret_type_output], $ret_type_len");
2107     $symbol_len += length ($symbol);
2108     my $char1 = my $char2 = my $char3 = "";
2109     if ($symbol_type eq 'USER_FUNCTION') {
2110         $symbol_len += 3;
2111         $char1 = "(";
2112         $char2 = "*";
2113         $char3 = ")";
2114     }
2116     my ($symbol_output, $symbol_desc_output);
2117     if ($symbol_len < $SYMBOL_FIELD_WIDTH) {
2118         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3"
2119             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
2120         $symbol_desc_output = "$char1$char2$symbol$char3"
2121             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
2122     } else {
2123         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3\n"
2124             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
2125         $symbol_desc_output = "$char1$char2$symbol$char3\n"
2126             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
2127     }
2129     my $synop = $ret_type_output . $symbol_output . '(';
2130     my $desc = "<refsect2 id=\"$id\" role=\"function\"$condition>\n<title>${symbol} ()</title>\n";
2132     $desc .= MakeIndexterms($symbol, $id);
2133     $desc .= "\n";
2134     $desc .= OutputSymbolExtraLinks($symbol);
2136     $desc  .= "<programlisting>${ret_type_output}$symbol_desc_output(";
2138     my @fields = ParseFunctionDeclaration($declaration, \&MakeXRef,
2139                                         sub {
2140                                             &tagify($_[0],"parameter");
2141                                         });
2143     for (my $i = 1; $i <= $#fields; $i += 2) {
2144         my $field_name = $fields[$i];
2146         if ($i == 1) {
2147             $synop .= "$field_name";
2148             $desc  .= "$field_name";
2149         } else {
2150             $synop .= ",\n"
2151                 . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
2152                 . " $field_name";
2153             $desc  .= ",\n"
2154                 . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
2155                 . " $field_name";
2156         }
2158     }
2160     $synop .= ");\n";
2161     $desc  .= ");</programlisting>\n";
2163     $desc .= &MakeDeprecationNote($symbol);
2165     my $parameters = &OutputParamDescriptions ("FUNCTION", $symbol, @fields);
2166     my $parameters_output = 0;
2168     if (defined ($SymbolDocs{$symbol})) {
2169         my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
2171         # Try to insert the parameter table at the author's desired position.
2172         # Otherwise we need to tag it onto the end.
2173         # FIXME: document that in the user manual and make it useable for other
2174         # types too
2175         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
2176           $parameters_output = 1;
2177         }
2178         $desc .= $symbol_docs;
2179     }
2181     if ($parameters_output == 0) {
2182         $desc .= $parameters;
2183     }
2185     $desc .= OutputSymbolTraits ($symbol);
2186     $desc .= "</refsect2>\n";
2187     return ($synop, $desc);
2191 #############################################################################
2192 # Function    : OutputParamDescriptions
2193 # Description : Returns the DocBook output describing the parameters of a
2194 #                function, macro or signal handler.
2195 # Arguments   : $symbol_type - 'FUNCTION', 'MACRO' or 'SIGNAL'. Signal
2196 #                  handlers have an implicit user_data parameter last.
2197 #                $symbol - the name of the function/macro being described.
2198 #               @fields - parsed fields from the declaration, used to determine
2199 #                  undocumented/unused entries
2200 #############################################################################
2202 sub OutputParamDescriptions {
2203     my ($symbol_type, $symbol, @fields) = @_;
2204     my $output = "";
2205     my $params = $SymbolParams{$symbol};
2206     my $num_params = 0;
2207     my %field_descrs = ();
2209     if (@fields) {
2210         %field_descrs = @fields;
2211         delete $field_descrs{"void"};
2212         delete $field_descrs{"Returns"};
2213     }
2215     if (defined $params) {
2216         my $returns = "";
2217         my $params_desc = "";
2218         my $missing_parameters = "";
2219         my $unused_parameters = "";
2220         my $j;
2222         for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
2223             my $param_name = $$params[$j];
2224             my $param_desc = $$params[$j + 1];
2225             my $param_annotations = "";
2227             ($param_desc,$param_annotations) = & ExpandAnnotation($symbol, $param_desc);
2228             $param_desc = &ConvertMarkDown($symbol, $param_desc);
2229             $param_desc .= $param_annotations;
2230             # trim
2231             $param_desc =~ s/^(\s|\n)+//msg;
2232             $param_desc =~ s/(\s|\n)+$//msg;
2233             if ($param_name eq "Returns") {
2234                 $returns = "$param_desc";
2235             } elsif ($param_name eq "void") {
2236                 #print "!!!! void in params for $symbol?\n";
2237             } else {
2238                 if (@fields) {
2239                     if (!defined $field_descrs{$param_name}) {
2240                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2241                             "Parameter description for $symbol"."::"."$param_name is not used from source code comment block.");
2242                         if ($unused_parameters ne "") {
2243                           $unused_parameters .= ", ".$param_name;
2244                         } else {
2245                            $unused_parameters = $param_name;
2246                         }
2247                     } else {
2248                         delete $field_descrs{$param_name};
2249                     }
2250                 }
2251                 if($param_desc ne "") {
2252                     $params_desc .= "<varlistentry><term><parameter>$param_name</parameter>&#160;:</term>\n<listitem>$param_desc</listitem></varlistentry>\n";
2253                     $num_params++;
2254                 }
2255             }
2256         }
2257         foreach my $param_name (keys %field_descrs) {
2258             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2259                 "Parameter description for $symbol"."::"."$param_name is missing in source code comment block.");
2260             if ($missing_parameters ne "") {
2261               $missing_parameters .= ", ".$param_name;
2262             } else {
2263                $missing_parameters = $param_name;
2264             }
2265         }
2267         # Signals have an implicit user_data parameter which we describe.
2268         if ($symbol_type eq "SIGNAL") {
2269             $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";
2270         }
2272         # Start a table if we need one.
2273         if ($params_desc || $returns) {
2274             $output .= "<variablelist role=\"params\">\n";
2275             if ($params_desc ne "") {
2276                 #$output .= "<varlistentry><term>Parameters:</term><listitem></listitem></varlistentry>\n";
2277                 $output .= $params_desc;
2278             }
2280             # Output the returns info last
2281             if ($returns) {
2282                 $output .= "<varlistentry><term><emphasis>Returns</emphasis>&#160;:</term><listitem>$returns</listitem></varlistentry>\n";
2283             }
2285             # Finish the table.
2286             $output .= "</variablelist>";
2287         }
2289         # remember missing/unused parameters (needed in tmpl-free build)
2290         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
2291             $AllIncompleteSymbols{$symbol}=$missing_parameters;
2292         }
2293         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
2294             $AllUnusedSymbols{$symbol}=$unused_parameters;
2295         }
2296     }
2297     if (($num_params == 0) && @fields && (scalar(keys(%field_descrs)) > 0)) {
2298         if (! exists ($AllIncompleteSymbols{$symbol})) {
2299             $AllIncompleteSymbols{$symbol}="<parameters>";
2300         }
2301     }
2303     return $output;
2307 #############################################################################
2308 # Function    : ParseStabilityLevel
2309 # Description : Parses a stability level and outputs a warning if it isn't
2310 #               valid.
2311 # Arguments   : $stability - the stability text.
2312 #                $file, $line - context for error message
2313 #                $message - description of where the level is from, to use in
2314 #               any error message.
2315 # Returns     : The parsed stability level string.
2316 #############################################################################
2318 sub ParseStabilityLevel {
2319     my ($stability, $file, $line, $message) = @_;
2321     $stability =~ s/^\s*//;
2322     $stability =~ s/\s*$//;
2323     if ($stability =~ m/^stable$/i) {
2324         $stability = "Stable";
2325     } elsif ($stability =~ m/^unstable$/i) {
2326         $stability = "Unstable";
2327     } elsif ($stability =~ m/^private$/i) {
2328         $stability = "Private";
2329     } else {
2330         &LogWarning ($file, $line, "$message is $stability.".
2331             "It should be one of these: Stable, Unstable, or Private.");
2332     }
2333     return $stability;
2337 #############################################################################
2338 # Function    : OutputSGMLFile
2339 # Description : Outputs the final DocBook file for one section.
2340 # Arguments   : $file - the name of the file.
2341 #               $title - the title from the $MODULE-sections.txt file, which
2342 #                 will be overridden by the title in the template file.
2343 #               $section_id - the SGML id to use for the toplevel tag.
2344 #               $includes - comma-separates list of include files added at top of
2345 #                 synopsis, with '<' '>' around them (if not already enclosed in "").
2346 #               $synopsis - reference to the DocBook for the Synopsis part.
2347 #               $details - reference to the DocBook for the Details part.
2348 #               $signal_synop - reference to the DocBook for the Signal Synopsis part
2349 #               $signal_desc - reference to the DocBook for the Signal Description part
2350 #               $args_synop - reference to the DocBook for the Arg Synopsis part
2351 #               $args_desc - reference to the DocBook for the Arg Description part
2352 #               $hierarchy - reference to the DocBook for the Object Hierarchy part
2353 #               $interfaces - reference to the DocBook for the Interfaces part
2354 #               $implementations - reference to the DocBook for the Known Implementations part
2355 #               $prerequisites - reference to the DocBook for the Prerequisites part
2356 #               $derived - reference to the DocBook for the Derived Interfaces part
2357 #               $file_objects - reference to an array of objects in this file
2358 #############################################################################
2360 sub OutputSGMLFile {
2361     my ($file, $title, $section_id, $includes, $synopsis, $details, $signals_synop, $signals_desc, $args_synop, $args_desc, $hierarchy, $interfaces, $implementations, $prerequisites, $derived, $file_objects) = @_;
2363     #print "Output sgml for file $file with title '$title'\n";
2365     # The edited title overrides the one from the sections file.
2366     my $new_title = $SymbolDocs{"$TMPL_DIR/$file:Title"};
2367     if (defined ($new_title) && $new_title !~ m/^\s*$/) {
2368         $title = $new_title;
2369         #print "Found title: $title\n";
2370     }
2371     my $short_desc = $SymbolDocs{"$TMPL_DIR/$file:Short_Description"};
2372     if (!defined ($short_desc) || $short_desc =~ m/^\s*$/) {
2373         $short_desc = "";
2374     } else {
2375         # Don't use ConvertMarkDown here for now since we don't want blocks
2376         $short_desc = &ExpandAbbreviations("$title:Short_description",
2377                                            $short_desc);
2378         #print "Found short_desc: $short_desc";
2379     }
2380     my $long_desc = $SymbolDocs{"$TMPL_DIR/$file:Long_Description"};
2381     if (!defined ($long_desc) || $long_desc =~ m/^\s*$/) {
2382         $long_desc = "";
2383     } else {
2384         $long_desc = &ConvertMarkDown("$title:Long_description",
2385                                           $long_desc);
2386         #print "Found long_desc: $long_desc";
2387     }
2388     my $see_also = $SymbolDocs{"$TMPL_DIR/$file:See_Also"};
2389     if (!defined ($see_also) || $see_also =~ m%^\s*(<para>)?\s*(</para>)?\s*$%) {
2390         $see_also = "";
2391     } else {
2392         $see_also = &ConvertMarkDown("$title:See_Also", $see_also);
2393         #print "Found see_also: $see_also";
2394     }
2395     if ($see_also) {
2396         $see_also = "<refsect1 id=\"$section_id.see-also\">\n<title>See Also</title>\n$see_also\n</refsect1>\n";
2397     }
2398     my $stability = $SymbolDocs{"$TMPL_DIR/$file:Stability_Level"};
2399     if (!defined ($stability) || $stability =~ m/^\s*$/) {
2400         $stability = "";
2401     } else {
2402         $stability = &ParseStabilityLevel($stability, $file, $., "Section stability level");
2403         #print "Found stability: $stability";
2404     }
2405     if ($stability) {
2406         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$stability, unless otherwise indicated\n</refsect1>\n";
2407     } elsif ($DEFAULT_STABILITY) {
2408         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$DEFAULT_STABILITY, unless otherwise indicated\n</refsect1>\n";
2409     }
2411     my $image = $SymbolDocs{"$TMPL_DIR/$file:Image"};
2412     if (!defined ($image) || $image =~ m/^\s*$/) {
2413       $image = "";
2414     } else {
2415       $image =~ s/^\s*//;
2416       $image =~ s/\s*$//;
2418       my $format;
2420       if ($image =~ /jpe?g$/i) {
2421         $format = "format='JPEG'";
2422       } elsif ($image =~ /png$/i) {
2423         $format = "format='PNG'";
2424       } elsif ($image =~ /svg$/i) {
2425         $format = "format='SVG'";
2426       } else {
2427         $format = "";
2428       }
2430       $image = "  <inlinegraphic fileref='$image' $format/>\n"
2431     }
2433     my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
2434         gmtime (time);
2435     my $month = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))[$mon];
2436     $year += 1900;
2438     my $include_output = "";
2439     my $include;
2440     foreach $include (split (/,/, $includes)) {
2441         if ($include =~ m/^\".+\"$/) {
2442             $include_output .= "#include ${include}\n";
2443         }
2444         else {
2445             $include =~ s/^\s+|\s+$//gs;
2446             $include_output .= "#include &lt;${include}&gt;\n";
2447         }
2448     }
2449     if ($include_output ne '') {
2450         $include_output = "\n$include_output\n";
2451     }
2453     my $extralinks = OutputSectionExtraLinks($title,"Section:$file");
2455     my $old_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT";
2456     my $new_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT.new";
2458     open (OUTPUT, ">$new_sgml_file")
2459         || die "Can't create $new_sgml_file: $!";
2461     my $object_anchors = "";
2462     foreach my $object (@$file_objects) {
2463         next if ($object eq $section_id);
2464         my $id = CreateValidSGMLID($object);
2465         #print "Debug: Adding anchor for $object\n";
2466         $object_anchors .= "<anchor id=\"$id\"$empty_element_end";
2467     }
2469     # We used to output this, but is messes up our UpdateFileIfChanged code
2470     # since it changes every day (and it is only used in the man pages):
2471     # "<refentry id="$section_id" revision="$mday $month $year">"
2473     if ($OUTPUT_FORMAT eq "xml") {
2474         print OUTPUT $doctype_header;
2475     }
2477     print OUTPUT <<EOF;
2478 <refentry id="$section_id">
2479 <refmeta>
2480 <refentrytitle role="top_of_page" id="$section_id.top_of_page">$title</refentrytitle>
2481 <manvolnum>3</manvolnum>
2482 <refmiscinfo>
2483   \U$MODULE\E Library
2484 $image</refmiscinfo>
2485 </refmeta>
2486 <refnamediv>
2487 <refname>$title</refname>
2488 <refpurpose>$short_desc</refpurpose>
2489 </refnamediv>
2490 $stability
2491 <refsynopsisdiv id="$section_id.synopsis" role="synopsis">
2492 <title role="synopsis.title">Synopsis</title>
2493 $object_anchors
2494 <synopsis>$include_output$${synopsis}</synopsis>
2495 </refsynopsisdiv>
2496 $$hierarchy$$prerequisites$$derived$$interfaces$$implementations$$args_synop$$signals_synop
2497 <refsect1 id="$section_id.description" role="desc">
2498 <title role="desc.title">Description</title>
2499 $extralinks$long_desc
2500 </refsect1>
2501 <refsect1 id="$section_id.details" role="details">
2502 <title role="details.title">Details</title>
2503 $$details
2504 </refsect1>
2505 $$args_desc$$signals_desc$see_also
2506 </refentry>
2508     close (OUTPUT);
2510     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2514 #############################################################################
2515 # Function    : OutputExtraFile
2516 # Description : Copies an "extra" DocBook file into the output directory,
2517 #               expanding abbreviations
2518 # Arguments   : $file - the source file.
2519 #############################################################################
2520 sub OutputExtraFile {
2521     my ($file) = @_;
2523     my $basename;
2525     ($basename = $file) =~ s!^.*/!!;
2527     my $old_sgml_file = "$SGML_OUTPUT_DIR/$basename";
2528     my $new_sgml_file = "$SGML_OUTPUT_DIR/$basename.new";
2530     my $contents;
2532     open(EXTRA_FILE, "<$file") || die "Can't open $file";
2534     {
2535         local $/;
2536         $contents = <EXTRA_FILE>;
2537     }
2539     open (OUTPUT, ">$new_sgml_file")
2540         || die "Can't create $new_sgml_file: $!";
2542     print OUTPUT &ExpandAbbreviations ("$basename file", $contents);
2543     close (OUTPUT);
2545     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2547 #############################################################################
2548 # Function    : OutputBook
2549 # Description : Outputs the SGML entities that need to be included into the
2550 #                main SGML file for the module.
2551 # Arguments   : $book_top - the declarations of the entities, which are added
2552 #                  at the top of the main SGML file.
2553 #                $book_bottom - the references to the entities, which are
2554 #                  added in the main SGML file at the desired position.
2555 #############################################################################
2557 sub OutputBook {
2558     my ($book_top, $book_bottom) = @_;
2560     my $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top";
2561     my $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top.new";
2563     open (OUTPUT, ">$new_file")
2564         || die "Can't create $new_file: $!";
2565     print OUTPUT $book_top;
2566     close (OUTPUT);
2568     &UpdateFileIfChanged ($old_file, $new_file, 0);
2571     $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom";
2572     $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom.new";
2574     open (OUTPUT, ">$new_file")
2575         || die "Can't create $new_file: $!";
2576     print OUTPUT $book_bottom;
2577     close (OUTPUT);
2579     &UpdateFileIfChanged ($old_file, $new_file, 0);
2582     # If the main SGML/XML file hasn't been created yet, we create it here.
2583     # The user can tweak it later.
2584     if ($MAIN_SGML_FILE && ! -e $MAIN_SGML_FILE) {
2585       open (OUTPUT, ">$MAIN_SGML_FILE")
2586         || die "Can't create $MAIN_SGML_FILE: $!";
2588       if ($OUTPUT_FORMAT eq "xml") {
2589           print OUTPUT <<EOF;
2590 <?xml version="1.0"?>
2591 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
2592                "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd"
2594   <!ENTITY % local.common.attrib "xmlns:xi  CDATA  #FIXED 'http://www.w3.org/2003/XInclude'">
2596 <book id="index">
2598       } else {
2599         print OUTPUT <<EOF;
2600 <!doctype book PUBLIC "-//Davenport//DTD DocBook V3.0//EN" [
2601 $book_top
2603 <book id="index">
2605       }
2607 print OUTPUT <<EOF;
2608   <bookinfo>
2609     <title>$MODULE Reference Manual</title>
2610     <releaseinfo>
2611       for $MODULE [VERSION].
2612       The latest version of this documentation can be found on-line at
2613       <ulink role="online-location" url="http://[SERVER]/$MODULE/index.html">http://[SERVER]/$MODULE/</ulink>.
2614     </releaseinfo>
2615   </bookinfo>
2617   <chapter>
2618     <title>[Insert title here]</title>
2619     $book_bottom
2620   </chapter>
2622   if (-e $OBJECT_TREE_FILE) {
2623     print OUTPUT <<EOF;
2624   <chapter id="object-tree">
2625     <title>Object Hierarchy</title>
2626      <xi:include href="xml/tree_index.sgml"/>
2627   </chapter>
2629   }
2631 print OUTPUT <<EOF;
2632   <index id="api-index-full">
2633     <title>API Index</title>
2634     <xi:include href="xml/api-index-full.xml"><xi:fallback /></xi:include>
2635   </index>
2636   <index id="deprecated-api-index" role="deprecated">
2637     <title>Index of deprecated API</title>
2638     <xi:include href="xml/api-index-deprecated.xml"><xi:fallback /></xi:include>
2639   </index>
2641   <xi:include href="xml/annotation-glossary.xml"><xi:fallback /></xi:include>
2642 </book>
2645       close (OUTPUT);
2646     }
2650 #############################################################################
2651 # Function    : CreateValidSGML
2652 # Description : This turns any chars which are used in SGML into entities,
2653 #                e.g. '<' into '&lt;'
2654 # Arguments   : $text - the text to turn into proper SGML.
2655 #############################################################################
2657 sub CreateValidSGML {
2658     my ($text) = @_;
2659     $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2660     $text =~ s/</&lt;/g;
2661     $text =~ s/>/&gt;/g;
2662     # browers render single tabs inconsistently
2663     $text =~ s/([^\s])\t([^\s])/$1&#160;$2/g;
2664     return $text;
2667 #############################################################################
2668 # Function    : ConvertSGMLChars
2669 # Description : This is used for text in source code comment blocks, to turn
2670 #               chars which are used in SGML into entities, e.g. '<' into
2671 #               '&lt;'. Depending on $INLINE_MARKUP_MODE, this is done
2672 #               unconditionally or only if the character doesn't seem to be
2673 #               part of an SGML construct (tag or entity reference).
2674 # Arguments   : $text - the text to turn into proper SGML.
2675 #############################################################################
2677 sub ConvertSGMLChars {
2678     my ($symbol, $text) = @_;
2680     if ($INLINE_MARKUP_MODE) {
2681         # For the XML/SGML mode only convert to entities outside CDATA sections.
2682         return &ModifyXMLElements ($text, $symbol,
2683                                    "<!\\[CDATA\\[|<programlisting[^>]*>",
2684                                    \&ConvertSGMLCharsEndTag,
2685                                    \&ConvertSGMLCharsCallback);
2686     } else {
2687         # For the simple non-sgml mode, convert to entities everywhere.
2688         $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2689         $text =~ s/</&lt;/g;
2690         $text =~ s/>/&gt;/g;
2691         return $text;
2692     }
2696 sub ConvertSGMLCharsEndTag {
2697   if ($_[0] eq "<!\[CDATA\[") {
2698     return "]]>";
2699   } else {
2700     return "</programlisting>";
2701   }
2704 sub ConvertSGMLCharsCallback {
2705   my ($text, $symbol, $tag) = @_;
2707   if ($tag =~ m/^<programlisting/) {
2708     # We can handle <programlisting> specially here.
2709     return &ModifyXMLElements ($text, $symbol,
2710                                "<!\\[CDATA\\[",
2711                                \&ConvertSGMLCharsEndTag,
2712                                \&ConvertSGMLCharsCallback2);
2713   } elsif ($tag eq "") {
2714     # If we're not in CDATA convert to entities.
2715     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2716     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2717     # Allow ">" at beginning of string for blockquote markdown
2718     $text =~ s/(?<=[^\w\n"'\/-])>/&gt;/g;
2720     # Handle "#include <xxxxx>"
2721     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2722   }
2724   return $text;
2727 sub ConvertSGMLCharsCallback2 {
2728   my ($text, $symbol, $tag) = @_;
2730   # If we're not in CDATA convert to entities.
2731   # We could handle <programlisting> differently, though I'm not sure it helps.
2732   if ($tag eq "") {
2733     # replace only if its not a tag
2734     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2735     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2736     $text =~ s/(?<![a-zA-Z0-9"'\/-])>/&gt;/g;
2738     # Handle "#include <xxxxx>"
2739     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2740   }
2742   return $text;
2745 #############################################################################
2746 # Function    : ExpandAnnotation
2747 # Description : This turns annotations into acronym tags.
2748 # Arguments   : $symbol - the symbol being documented, for error messages.
2749 #                $text - the text to expand.
2750 #############################################################################
2751 sub ExpandAnnotation {
2752     my ($symbol, $param_desc) = @_;
2753     my $param_annotations = "";
2755     # look for annotations at the start of the comment part
2756     if ($param_desc =~ m%^\s*\((.*?)\):%) {
2757         my @annotations;
2758         my $annotation;
2759         $param_desc = $';
2761         @annotations = split(/\)\s*\(/,$1);
2762         foreach $annotation (@annotations) {
2763             # need to search for the longest key-match in %AnnotationDefinition
2764             my $match_length=0;
2765             my $match_annotation="";
2766             my $annotationdef;
2767             foreach $annotationdef (keys %AnnotationDefinition) {
2768                 if ($annotation =~ m/^$annotationdef/) {
2769                     if (length($annotationdef)>$match_length) {
2770                         $match_length=length($annotationdef);
2771                         $match_annotation=$annotationdef;
2772                     }
2773                 }
2774             }
2775             my $annotation_extra = "";
2776             if ($match_annotation ne "") {
2777                 if ($annotation =~ m%$match_annotation\s+(.*)%) {
2778                     $annotation_extra = " $1";
2779                 }
2780                 $AnnotationsUsed{$match_annotation} = 1;
2781                 $param_annotations .= "[<acronym>$match_annotation</acronym>$annotation_extra]";
2782             }
2783             else {
2784                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2785                     "unknown annotation \"$annotation\" in documentation for $symbol.");
2786                 $param_annotations .= "[$annotation]";
2787             }
2788         }
2789         chomp($param_desc);
2790         $param_desc =~ m/^(.*?)\.*\s*$/s;
2791         $param_desc = "$1. ";
2792     }
2793     if ($param_annotations ne "") {
2794         $param_annotations = "<emphasis role=\"annotation\">$param_annotations</emphasis>";
2795     }
2796     return ($param_desc, $param_annotations);
2799 #############################################################################
2800 # Function    : ExpandAbbreviations
2801 # Description : This turns the abbreviations function(), macro(), @param,
2802 #                %constant, and #symbol into appropriate DocBook markup.
2803 #               CDATA sections and <programlisting> parts are skipped.
2804 # Arguments   : $symbol - the symbol being documented, for error messages.
2805 #                $text - the text to expand.
2806 #############################################################################
2808 sub ExpandAbbreviations {
2809   my ($symbol, $text) = @_;
2811   # Note: This is a fallback and normally done in the markdown parser
2813   # Convert "|[" and "]|" into the start and end of program listing examples.
2814   # Support \[<!-- language="C" --> modifiers
2815   $text =~ s%\|\[<!-- language="([^"]+)" -->%<informalexample><programlisting language="$1"><![CDATA[%g;
2816   $text =~ s%\|\[%<informalexample><programlisting><![CDATA[%g;
2817   $text =~ s%\]\|%]]></programlisting></informalexample>%g;
2819   # keep CDATA unmodified, preserve ulink tags (ideally we preseve all tags
2820   # as such)
2821   return &ModifyXMLElements ($text, $symbol,
2822                              "<!\\[CDATA\\[|<ulink[^>]*>|<programlisting[^>]*>|<!DOCTYPE",
2823                              \&ExpandAbbreviationsEndTag,
2824                              \&ExpandAbbreviationsCallback);
2828 # Returns the end tag (as a regexp) corresponding to the given start tag.
2829 sub ExpandAbbreviationsEndTag {
2830   my ($start_tag) = @_;
2832   if ($start_tag eq "<!\[CDATA\[") {
2833     return "]]>";
2834   } elsif ($start_tag eq "<!DOCTYPE") {
2835     return ">";
2836   } elsif ($start_tag =~ m/<(\w+)/) {
2837     return "</$1>";
2838   }
2841 # Called inside or outside each CDATA or <programlisting> section.
2842 sub ExpandAbbreviationsCallback {
2843   my ($text, $symbol, $tag) = @_;
2845   if ($tag =~ m/^<programlisting/) {
2846     # Handle any embedded CDATA sections.
2847     return &ModifyXMLElements ($text, $symbol,
2848                                "<!\\[CDATA\\[",
2849                                \&ExpandAbbreviationsEndTag,
2850                                \&ExpandAbbreviationsCallback2);
2851   } elsif ($tag eq "") {
2852     # NOTE: this is a fallback. It is normally done by the Markdown parser.
2854     # We are outside any CDATA or <programlisting> sections, so we expand
2855     # any gtk-doc abbreviations.
2857     # Convert '@param()'
2858     # FIXME: we could make those also links ($symbol.$2), but that would be less
2859     # useful as the link target is a few lines up or down
2860     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)/$1<parameter>$2()<\/parameter>/g;
2862     # Convert 'function()' or 'macro()'.
2863     # if there is abc_*_def() we don't want to make a link to _def()
2864     # FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
2865     $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2866     # handle #Object.func()
2867     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2869     # Convert '@param', but not '\@param'.
2870     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)/$1<parameter>$2<\/parameter>/g;
2871     $text =~ s/\\\@/\@/g;
2873     # Convert '%constant', but not '\%constant'.
2874     # Also allow negative numbers, e.g. %-1.
2875     $text =~ s/(\A|[^\\])\%(-?\w+)/$1.&MakeXRef($2, &tagify($2, "literal"));/eg;
2876     $text =~ s/\\\%/\%/g;
2878     # Convert '#symbol', but not '\#symbol'.
2879     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)/$1.&MakeHashXRef($2, "type");/eg;
2880     $text =~ s/\\#/#/g;
2881   }
2883   return $text;
2886 # This is called inside a <programlisting>
2887 sub ExpandAbbreviationsCallback2 {
2888   my ($text, $symbol, $tag) = @_;
2890   if ($tag eq "") {
2891     # We are inside a <programlisting> but outside any CDATA sections,
2892     # so we expand any gtk-doc abbreviations.
2893     # FIXME: why is this different from &ExpandAbbreviationsCallback(),
2894     #        why not just call it
2895     $text =~ s/#(\w+)/&MakeHashXRef($1, "");/eg;
2896   } elsif ($tag eq "<![CDATA[") {
2897     # NOTE: this is a fallback. It is normally done by the Markdown parser.
2898     $text = &ReplaceEntities ($text, $symbol);
2899   }
2901   return $text;
2904 sub MakeHashXRef {
2905     my ($symbol, $tag) = @_;;
2906     my $text = $symbol;
2908     # Check for things like '#include', '#define', and skip them.
2909     if ($PreProcessorDirectives{$symbol}) {
2910       return "#$symbol";
2911     }
2913     # Get rid of special suffixes ('-struct','-enum').
2914     $text =~ s/-struct$//;
2915     $text =~ s/-enum$//;
2917     # If the symbol is in the form "Object::signal", then change the symbol to
2918     # "Object-signal" and use "signal" as the text.
2919     if ($symbol =~ s/::/-/) {
2920       $text = "“$'”";
2921     }
2923     # If the symbol is in the form "Object:property", then change the symbol to
2924     # "Object--property" and use "property" as the text.
2925     if ($symbol =~ s/:/--/) {
2926       $text = "“$'”";
2927     }
2929     if ($tag ne "") {
2930       $text = tagify ($text, $tag);
2931     }
2933     return &MakeXRef($symbol, $text);
2937 #############################################################################
2938 # Function    : ModifyXMLElements
2939 # Description : Looks for given XML element tags within the text, and calls
2940 #               the callback on pieces of text inside & outside those elements.
2941 #               Used for special handling of text inside things like CDATA
2942 #               and <programlisting>.
2943 # Arguments   : $text - the text.
2944 #               $symbol - the symbol currently being documented (only used for
2945 #                      error messages).
2946 #               $start_tag_regexp - the regular expression to match start tags.
2947 #                      e.g. "<!\\[CDATA\\[|<programlisting[^>]*>" to match
2948 #                      CDATA sections or programlisting elements.
2949 #               $end_tag_func - function which is passed the matched start tag
2950 #                      and should return the appropriate end tag string regexp.
2951 #               $callback - callback called with each part of the text. It is
2952 #                      called with a piece of text, the symbol being
2953 #                      documented, and the matched start tag or "" if the text
2954 #                      is outside the XML elements being matched.
2955 #############################################################################
2956 sub ModifyXMLElements {
2957     my ($text, $symbol, $start_tag_regexp, $end_tag_func, $callback) = @_;
2958     my ($before_tag, $start_tag, $end_tag_regexp, $end_tag);
2959     my $result = "";
2961     while ($text =~ m/$start_tag_regexp/s) {
2962       $before_tag = $`; # Prematch for last successful match string
2963       $start_tag = $&;  # Last successful match
2964       $text = $';       # Postmatch for last successful match string
2966       $result .= &$callback ($before_tag, $symbol, "");
2967       $result .= $start_tag;
2969       # get the matching end-tag for current tag
2970       $end_tag_regexp = &$end_tag_func ($start_tag);
2972       if ($text =~ m/$end_tag_regexp/s) {
2973         $before_tag = $`;
2974         $end_tag = $&;
2975         $text = $';
2977         $result .= &$callback ($before_tag, $symbol, $start_tag);
2978         $result .= $end_tag;
2979       } else {
2980         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2981             "Can't find tag end: $end_tag_regexp in docs for: $symbol.");
2982         # Just assume it is all inside the tag.
2983         $result .= &$callback ($text, $symbol, $start_tag);
2984         $text = "";
2985       }
2986     }
2988     # Handle any remaining text outside the tags.
2989     $result .= &$callback ($text, $symbol, "");
2991     return $result;
2994 sub noop {
2995   return $_[0];
2998 # Adds a tag around some text.
2999 # e.g tagify("Text", "literal") => "<literal>Text</literal>".
3000 sub tagify {
3001    my ($text, $elem) = @_;
3002    return "<" . $elem . ">" . $text . "</" . $elem . ">";
3006 #############################################################################
3007 # Function    : MakeXRef
3008 # Description : This returns a cross-reference link to the given symbol.
3009 #                Though it doesn't try to do this for a few standard C types
3010 #                that it        knows won't be in the documentation.
3011 # Arguments   : $symbol - the symbol to try to create a XRef to.
3012 #               $text - text text to put inside the XRef, defaults to $symbol
3013 #############################################################################
3015 sub MakeXRef {
3016     my ($symbol, $text) = ($_[0], $_[1]);
3018     $symbol =~ s/^\s+//;
3019     $symbol =~ s/\s+$//;
3021     if (!defined($text)) {
3022         $text = $symbol;
3024         # Get rid of special suffixes ('-struct','-enum').
3025         $text =~ s/-struct$//;
3026         $text =~ s/-enum$//;
3027     }
3029     if ($symbol =~ m/ /) {
3030         return "$text";
3031     }
3033     #print "Getting type link for $symbol -> $text\n";
3035     my $symbol_id = &CreateValidSGMLID ($symbol);
3036     return "<link linkend=\"$symbol_id\">$text</link>";
3040 #############################################################################
3041 # Function    : MakeIndexterms
3042 # Description : This returns a indexterm elements for the given symbol
3043 # Arguments   : $symbol - the symbol to create indexterms for
3044 #############################################################################
3046 sub MakeIndexterms {
3047   my ($symbol, $id) = @_;
3048   my $terms =  "";
3049   my $sortas = "";
3051   # make the index useful, by ommiting the namespace when sorting
3052   if ($NAME_SPACE ne "") {
3053     if ($symbol =~ m/^$NAME_SPACE\_?(.*)/i) {
3054        $sortas=" sortas=\"$1\"";
3055     }
3056   }
3058   if (exists $Deprecated{$symbol}) {
3059       $terms .= "<indexterm zone=\"$id\" role=\"deprecated\"><primary$sortas>$symbol</primary></indexterm>";
3060       $IndexEntriesDeprecated{$symbol}=$id;
3061       $IndexEntriesFull{$symbol}=$id;
3062   }
3063   if (exists $Since{$symbol}) {
3064      my $since = $Since{$symbol};
3065      $since =~ s/^\s+//;
3066      $since =~ s/\s+$//;
3067      if ($since ne "") {
3068          $terms .= "<indexterm zone=\"$id\" role=\"$since\"><primary$sortas>$symbol</primary></indexterm>";
3069      }
3070      $IndexEntriesSince{$symbol}=$id;
3071      $IndexEntriesFull{$symbol}=$id;
3072   }
3073   if ($terms eq "") {
3074      $terms .= "<indexterm zone=\"$id\"><primary$sortas>$symbol</primary></indexterm>";
3075      $IndexEntriesFull{$symbol}=$id;
3076   }
3078   return $terms;
3081 #############################################################################
3082 # Function    : MakeDeprecationNote
3083 # Description : This returns a deprecation warning for the given symbol.
3084 # Arguments   : $symbol - the symbol to try to create a warning for.
3085 #############################################################################
3087 sub MakeDeprecationNote {
3088     my ($symbol) = $_[0];
3089     my $desc = "";
3090     if (exists $Deprecated{$symbol}) {
3091         my $note;
3093         $desc .= "<warning><para><literal>$symbol</literal> ";
3095         $note = $Deprecated{$symbol};
3097         if ($note =~ /^\s*([0-9\.]+)\s*:?/) {
3098                 $desc .= "has been deprecated since version $1 and should not be used in newly-written code.</para>";
3099         } else {
3100                 $desc .= "is deprecated and should not be used in newly-written code.</para>";
3101         }
3102         $note =~ s/^\s*([0-9\.]+)\s*:?\s*//;
3103         $note =~ s/^\s+//;
3104         $note =~ s/\s+$//;
3105         if ($note ne "") {
3106             $note = &ConvertMarkDown($symbol, $note);
3107             $desc .= " " . $note;
3108         }
3109         $desc .= "</warning>\n";
3110     }
3111     return $desc;
3114 #############################################################################
3115 # Function    : MakeConditionDescription
3116 # Description : This returns a sumary of conditions for the given symbol.
3117 # Arguments   : $symbol - the symbol to try to create the sumary.
3118 #############################################################################
3120 sub MakeConditionDescription {
3121     my ($symbol) = $_[0];
3122     my $desc = "";
3124     if (exists $Deprecated{$symbol}) {
3125         if ($desc ne "") {
3126             $desc .= "|";
3127         }
3129         if ($Deprecated{$symbol} =~ /^\s*(.*?)\s*$/) {
3130                 $desc .= "deprecated:$1";
3131         } else {
3132                 $desc .= "deprecated";
3133         }
3134     }
3136     if (exists $Since{$symbol}) {
3137         if ($desc ne "") {
3138             $desc .= "|";
3139         }
3141         if ($Since{$symbol} =~ /^\s*(.*?)\s*$/) {
3142                 $desc .= "since:$1";
3143         } else {
3144                 $desc .= "since";
3145         }
3146     }
3148     if (exists $StabilityLevel{$symbol}) {
3149         if ($desc ne "") {
3150             $desc .= "|";
3151         }
3152         $desc .= "stability:".$StabilityLevel{$symbol};
3153     }
3155     if ($desc ne "") {
3156         my $cond = $desc;
3157         $cond =~ s/\"/&quot;/g;
3158         $desc=" condition=\"".$cond."\"";
3159         #print "condition for '$symbol' = '$desc'\n";
3160     }
3161     return $desc;
3164 #############################################################################
3165 # Function    : GetHierarchy
3166 # Description : Returns the DocBook output describing the ancestors and
3167 #               immediate children of a GObject subclass. It uses the
3168 #               global @Objects and @ObjectLevels arrays to walk the tree.
3169 # Arguments   : $object - the GtkObject subclass.
3170 #############################################################################
3172 sub GetHierarchy {
3173     my ($object) = @_;
3175     # Find object in the objects array.
3176     my $found = 0;
3177     my @children = ();
3178     my $i;
3179     my $level;
3180     my $j;
3181     for ($i = 0; $i < @Objects; $i++) {
3182         if ($found) {
3183             if ($ObjectLevels[$i] <= $level) {
3184             last;
3185         }
3186             elsif ($ObjectLevels[$i] == $level + 1) {
3187                 push (@children, $Objects[$i]);
3188             }
3189         }
3190         elsif ($Objects[$i] eq $object) {
3191             $found = 1;
3192             $j = $i;
3193             $level = $ObjectLevels[$i];
3194         }
3195     }
3196     if (!$found) {
3197         return "";
3198     }
3200     # Walk up the hierarchy, pushing ancestors onto the ancestors array.
3201     my @ancestors = ();
3202     push (@ancestors, $object);
3203     #print "Level: $level\n";
3204     while ($level > 1) {
3205         $j--;
3206         if ($ObjectLevels[$j] < $level) {
3207             push (@ancestors, $Objects[$j]);
3208             $level = $ObjectLevels[$j];
3209             #print "Level: $level\n";
3210         }
3211     }
3213     # Output the ancestors list, indented and with links.
3214     my $hierarchy = "<synopsis>\n";
3215     $level = 0;
3216     for ($i = $#ancestors; $i >= 0; $i--) {
3217         my $link_text;
3218         # Don't add a link to the current object, i.e. when i == 0.
3219         if ($i > 0) {
3220             my $ancestor_id = &CreateValidSGMLID ($ancestors[$i]);
3221             $link_text = "<link linkend=\"$ancestor_id\">$ancestors[$i]</link>";
3222         } else {
3223             $link_text = "$ancestors[$i]";
3224         }
3225         if ($level == 0) {
3226             $hierarchy .= "  $link_text\n";
3227         } else {
3228 #            $hierarchy .= ' ' x ($level * 6 - 3) . "|\n";
3229             $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
3230         }
3231         $level++;
3232     }
3233     for ($i = 0; $i <= $#children; $i++) {
3234       my $id = &CreateValidSGMLID ($children[$i]);
3235       my $link_text = "<link linkend=\"$id\">$children[$i]</link>";
3236       $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
3237     }
3238     $hierarchy .= "</synopsis>\n";
3240     return $hierarchy;
3244 #############################################################################
3245 # Function    : GetInterfaces
3246 # Description : Returns the DocBook output describing the interfaces
3247 #               implemented by a class. It uses the global %Interfaces hash.
3248 # Arguments   : $object - the GtkObject subclass.
3249 #############################################################################
3251 sub GetInterfaces {
3252     my ($object) = @_;
3253     my $text = "";
3254     my $i;
3256     # Find object in the objects array.
3257     if (exists($Interfaces{$object})) {
3258         my @ifaces = split(' ', $Interfaces{$object});
3259         $text = <<EOF;
3260 <para>
3261 $object implements
3263         for ($i = 0; $i <= $#ifaces; $i++) {
3264             my $id = &CreateValidSGMLID ($ifaces[$i]);
3265             $text .= " <link linkend=\"$id\">$ifaces[$i]</link>";
3266             if ($i < $#ifaces - 1) {
3267                 $text .= ', ';
3268             }
3269             elsif ($i < $#ifaces) {
3270                 $text .= ' and ';
3271             }
3272             else {
3273                 $text .= '.';
3274             }
3275         }
3276         $text .= <<EOF;
3277 </para>
3279     }
3281     return $text;
3284 #############################################################################
3285 # Function    : GetImplementations
3286 # Description : Returns the DocBook output describing the implementations
3287 #               of an interface. It uses the global %Interfaces hash.
3288 # Arguments   : $object - the GtkObject subclass.
3289 #############################################################################
3291 sub GetImplementations {
3292     my ($object) = @_;
3293     my @impls = ();
3294     my $text = "";
3295     my $i;
3296     foreach my $key (keys %Interfaces) {
3297         if ($Interfaces{$key} =~ /\b$object\b/) {
3298             push (@impls, $key);
3299         }
3300     }
3301     if ($#impls >= 0) {
3302         @impls = sort @impls;
3303         $text = <<EOF;
3304 <para>
3305 $object is implemented by
3307         for ($i = 0; $i <= $#impls; $i++) {
3308             my $id = &CreateValidSGMLID ($impls[$i]);
3309             $text .= " <link linkend=\"$id\">$impls[$i]</link>";
3310             if ($i < $#impls - 1) {
3311                 $text .= ', ';
3312             }
3313             elsif ($i < $#impls) {
3314                 $text .= ' and ';
3315             }
3316             else {
3317                 $text .= '.';
3318             }
3319         }
3320         $text .= <<EOF;
3321 </para>
3323     }
3324     return $text;
3328 #############################################################################
3329 # Function    : GetPrerequisites
3330 # Description : Returns the DocBook output describing the prerequisites
3331 #               of an interface. It uses the global %Prerequisites hash.
3332 # Arguments   : $iface - the interface.
3333 #############################################################################
3335 sub GetPrerequisites {
3336     my ($iface) = @_;
3337     my $text = "";
3338     my $i;
3340     if (exists($Prerequisites{$iface})) {
3341         $text = <<EOF;
3342 <para>
3343 $iface requires
3345         my @prereqs = split(' ', $Prerequisites{$iface});
3346         for ($i = 0; $i <= $#prereqs; $i++) {
3347             my $id = &CreateValidSGMLID ($prereqs[$i]);
3348             $text .= " <link linkend=\"$id\">$prereqs[$i]</link>";
3349             if ($i < $#prereqs - 1) {
3350                 $text .= ', ';
3351             }
3352             elsif ($i < $#prereqs) {
3353                 $text .= ' and ';
3354             }
3355             else {
3356                 $text .= '.';
3357             }
3358         }
3359         $text .= <<EOF;
3360 </para>
3362     }
3363     return $text;
3366 #############################################################################
3367 # Function    : GetDerived
3368 # Description : Returns the DocBook output describing the derived interfaces
3369 #               of an interface. It uses the global %Prerequisites hash.
3370 # Arguments   : $iface - the interface.
3371 #############################################################################
3373 sub GetDerived {
3374     my ($iface) = @_;
3375     my $text = "";
3376     my $i;
3378     my @derived = ();
3379     foreach my $key (keys %Prerequisites) {
3380         if ($Prerequisites{$key} =~ /\b$iface\b/) {
3381             push (@derived, $key);
3382         }
3383     }
3384     if ($#derived >= 0) {
3385         @derived = sort @derived;
3386         $text = <<EOF;
3387 <para>
3388 $iface is required by
3390         for ($i = 0; $i <= $#derived; $i++) {
3391             my $id = &CreateValidSGMLID ($derived[$i]);
3392             $text .= " <link linkend=\"$id\">$derived[$i]</link>";
3393             if ($i < $#derived - 1) {
3394                 $text .= ', ';
3395             }
3396             elsif ($i < $#derived) {
3397                 $text .= ' and ';
3398             }
3399             else {
3400                 $text .= '.';
3401             }
3402         }
3403         $text .= <<EOF;
3404 </para>
3406     }
3407     return $text;
3411 #############################################################################
3412 # Function    : GetSignals
3413 # Description : Returns the synopsis and detailed description DocBook output
3414 #                for the signal handlers of a given GtkObject subclass.
3415 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3416 #############################################################################
3418 sub GetSignals {
3419     my ($object) = @_;
3420     my $synop = "";
3421     my $desc = "";
3423     my $i;
3424     for ($i = 0; $i <= $#SignalObjects; $i++) {
3425         if ($SignalObjects[$i] eq $object) {
3426             #print "Found signal: $SignalNames[$i]\n";
3427             my $name = $SignalNames[$i];
3428             my $symbol = "${object}::${name}";
3429             my $id = &CreateValidSGMLID ("$object-$name");
3431             my $pad = ' ' x (46 - length($name));
3432             $synop .= "  “<link linkend=\"$id\">$name</link>”$pad ";
3434             $desc .= "<refsect2 id=\"$id\" role=\"signal\"><title>The <literal>“$name”</literal> signal</title>\n";
3435             $desc .= MakeIndexterms($symbol, $id);
3436             $desc .= "\n";
3437             $desc .= OutputSymbolExtraLinks($symbol);
3439             $desc .= "<programlisting>";
3441             $SignalReturns[$i] =~ m/\s*(const\s+)?(\w+)\s*(\**)/;
3442             my $type_modifier = defined($1) ? $1 : "";
3443             my $type = $2;
3444             my $pointer = $3;
3445             my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
3447             my $ret_type_len = length ($type_modifier) + length ($pointer)
3448                 + length ($type);
3449             my $ret_type_output = "$type_modifier$xref$pointer"
3450                 . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
3452             $desc  .= "${ret_type_output}user_function " . &MakeReturnField("") . " (";
3454             my $sourceparams = $SourceSymbolParams{$symbol};
3455             my @params = split ("\n", $SignalPrototypes[$i]);
3456             my $j;
3457             my $l;
3458             my $type_len = length("gpointer");
3459             my $name_len = length("user_data");
3460             # do two passes, the first one is to calculate padding
3461             for ($l = 0; $l < 2; $l++) {
3462                 for ($j = 0; $j <= $#params; $j++) {
3463                     # allow alphanumerics, '_', '[' & ']' in param names
3464                     if ($params[$j] =~ m/^\s*(\w+)\s*(\**)\s*([\w\[\]]+)\s*$/) {
3465                         $type = $1;
3466                         $pointer = $2;
3467                         if (defined($sourceparams)) {
3468                             $name = $$sourceparams[$PARAM_FIELD_COUNT * $j];
3469                         }
3470                         else {
3471                             $name = $3;
3472                         }
3473                         if (!defined($name)) {
3474                             $name = "arg$j";
3475                         }
3476                         if ($l == 0) {
3477                             if (length($type) + length($pointer) > $type_len) {
3478                                 $type_len = length($type) + length($pointer);
3479                             }
3480                             if (length($name) > $name_len) {
3481                                 $name_len = length($name);
3482                             }
3483                         }
3484                         else {
3485                             $xref = &MakeXRef ($type, &tagify($type, "type"));
3486                             $pad = ' ' x ($type_len - length($type) - length($pointer));
3487                             $desc .= "$xref$pad $pointer$name,\n";
3488                             $desc .= (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
3489                         }
3490                     } else {
3491                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
3492                              "Can't parse arg: $params[$j]\nArgs:$SignalPrototypes[$i]");
3493                     }
3494                 }
3495             }
3496             $xref = &MakeXRef ("gpointer", &tagify("gpointer", "type"));
3497             $pad = ' ' x ($type_len - length("gpointer"));
3498             $desc  .= "$xref$pad user_data)";
3500             my $flags = $SignalFlags[$i];
3501             my $flags_string = "";
3503             if (defined ($flags)) {
3504               if ($flags =~ m/f/) {
3505                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-FIRST:CAPS\"><literal>Run First</literal></link>";
3506               }
3507               elsif ($flags =~ m/l/) {
3508                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-LAST:CAPS\"><literal>Run Last</literal></link>";
3509               }
3510               elsif ($flags =~ m/c/) {
3511                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-CLEANUP:CAPS\"><literal>Cleanup</literal></link>";
3512                 $flags_string = "Cleanup";
3513               }
3514               if ($flags =~ m/r/) {
3515                 if ($flags_string) { $flags_string .= " / "; }
3516                 $flags_string = "<link linkend=\"G-SIGNAL-NO-RECURSE:CAPS\"><literal>No Recursion</literal></link>";
3517               }
3518               if ($flags =~ m/d/) {
3519                 if ($flags_string) { $flags_string .= " / "; }
3520                 $flags_string = "<link linkend=\"G-SIGNAL-DETAILED:CAPS\"><literal>Has Details</literal></link>";
3521               }
3522               if ($flags =~ m/a/) {
3523                 if ($flags_string) { $flags_string .= " / "; }
3524                 $flags_string = "<link linkend=\"G-SIGNAL-ACTION:CAPS\"><literal>Action</literal></link>";
3525               }
3526               if ($flags =~ m/h/) {
3527                 if ($flags_string) { $flags_string .= " / "; }
3528                 $flags_string = "<link linkend=\"G-SIGNAL-NO-HOOKS:CAPS\"><literal>No Hooks</literal></link>";
3529               }
3530             }
3532             if ($flags_string)
3533               {
3534                 $synop .= ": $flags_string\n";
3536                 $pad = ' ' x (5 + $name_len - length("user_data"));
3537                 $desc  .= "$pad : $flags_string</programlisting>\n";
3538               }
3539             else
3540               {
3541                 $synop .= "\n";
3542                 $desc  .= "</programlisting>\n";
3543               }
3545             $desc .= &MakeDeprecationNote($symbol);
3547             my $parameters = &OutputParamDescriptions ("SIGNAL", $symbol);
3548             my $parameters_output = 0;
3550             $AllSymbols{$symbol} = 1;
3551             if (defined ($SymbolDocs{$symbol})) {
3552                 my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
3554                 # Try to insert the parameter table at the author's desired
3555                 # position. Otherwise we need to tag it onto the end.
3556                 if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
3557                   $parameters_output = 1;
3558                 }
3559                 $desc .= $symbol_docs;
3561                 if (!IsEmptyDoc($SymbolDocs{$symbol})) {
3562                     $AllDocumentedSymbols{$symbol} = 1;
3563                 }
3564             }
3566             if ($parameters_output == 0) {
3567                 $desc .= $parameters;
3568               }
3569             $desc .= OutputSymbolTraits ($symbol);
3570             $desc .= "</refsect2>";
3571         }
3572     }
3573     return ($synop, $desc);
3577 #############################################################################
3578 # Function    : GetArgs
3579 # Description : Returns the synopsis and detailed description DocBook output
3580 #                for the Args of a given GtkObject subclass.
3581 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3582 #############################################################################
3584 sub GetArgs {
3585     my ($object) = @_;
3586     my $synop = "";
3587     my $desc = "";
3588     my $child_synop = "";
3589     my $child_desc = "";
3590     my $style_synop = "";
3591     my $style_desc = "";
3593     my $i;
3594     for ($i = 0; $i <= $#ArgObjects; $i++) {
3595         if ($ArgObjects[$i] eq $object) {
3596             #print "Found arg: $ArgNames[$i]\n";
3597             my $name = $ArgNames[$i];
3598             my $flags = $ArgFlags[$i];
3599             my $flags_string = "";
3600             my $kind = "";
3601             my $id_sep = "";
3603             if ($flags =~ m/c/) {
3604                 $kind = "child property";
3605                 $id_sep = "c-";
3606             }
3607             elsif ($flags =~ m/s/) {
3608                 $kind = "style property";
3609                 $id_sep = "s-";
3610             }
3611             else {
3612                 $kind = "property";
3613             }
3615             # Remember only one colon so we don't clash with signals.
3616             my $symbol = "${object}:${name}";
3617             # use two dashes and ev. an extra separator here for the same reason.
3618             my $id = &CreateValidSGMLID ("$object--$id_sep$name");
3620             my $type = $ArgTypes[$i];
3621             my $type_output;
3622             my $range = $ArgRanges[$i];
3623             my $range_output = CreateValidSGML ($range);
3624             my $default = $ArgDefaults[$i];
3625             my $default_output = CreateValidSGML ($default);
3627             if ($type eq "GtkString") {
3628                 $type = "char*";
3629             }
3630             if ($type eq "GtkSignal") {
3631                 $type = "GtkSignalFunc, gpointer";
3632                 $type_output = &MakeXRef ("GtkSignalFunc") . ", "
3633                     . &MakeXRef ("gpointer");
3634             } elsif ($type =~ m/^(\w+)\*$/) {
3635                 $type_output = &MakeXRef ($1, &tagify($1, "type")) . "*";
3636             } else {
3637                 $type_output = &MakeXRef ($type, &tagify($type, "type"));
3638             }
3640             if ($flags =~ m/r/) {
3641                 $flags_string = "Read";
3642             }
3643             if ($flags =~ m/w/) {
3644                 if ($flags_string) { $flags_string .= " / "; }
3645                 $flags_string .= "Write";
3646             }
3647             if ($flags =~ m/x/) {
3648                 if ($flags_string) { $flags_string .= " / "; }
3649                 $flags_string .= "Construct";
3650             }
3651             if ($flags =~ m/X/) {
3652                 if ($flags_string) { $flags_string .= " / "; }
3653                 $flags_string .= "Construct Only";
3654             }
3656             $AllSymbols{$symbol} = 1;
3657             my $blurb;
3658             if (defined($SymbolDocs{$symbol}) &&
3659                 !IsEmptyDoc($SymbolDocs{$symbol})) {
3660                 $blurb = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
3661                 #print ".. [$SymbolDocs{$symbol}][$blurb]\n";
3662                 $AllDocumentedSymbols{$symbol} = 1;
3663             }
3664             else {
3665                 if (!($ArgBlurbs[$i] eq "")) {
3666                     $AllDocumentedSymbols{$symbol} = 1;
3667                 } else {
3668                     # FIXME: print a warning?
3669                     #print ".. no description\n";
3670                 }
3671                 $blurb = "<para>" . &CreateValidSGML ($ArgBlurbs[$i]) . "</para>";
3672             }
3674             my $pad1 = " " x (24 - length ($name));
3675             my $pad2 = " " x (20 - length ($type));
3677             my $arg_synop = "  “<link linkend=\"$id\">$name</link>”$pad1 $type_output $pad2 : $flags_string\n";
3678             my $arg_desc = "<refsect2 id=\"$id\" role=\"property\"><title>The <literal>“$name”</literal> $kind</title>\n";
3679             $arg_desc .= MakeIndexterms($symbol, $id);
3680             $arg_desc .= "\n";
3681             $arg_desc .= OutputSymbolExtraLinks($symbol);
3683             $arg_desc .= "<programlisting>  “$name”$pad1 $type_output $pad2 : $flags_string</programlisting>\n";
3684             $arg_desc .= &MakeDeprecationNote($symbol);
3685             $arg_desc .= $blurb;
3686             if ($range ne "") {
3687                 $arg_desc .= "<para>Allowed values: $range_output</para>\n";
3688             }
3689             if ($default ne "") {
3690                 $arg_desc .= "<para>Default value: $default_output</para>\n";
3691             }
3692             $arg_desc .= OutputSymbolTraits ($symbol);
3693             $arg_desc .= "</refsect2>\n";
3695             if ($flags =~ m/c/) {
3696                 $child_synop .= $arg_synop;
3697                 $child_desc .= $arg_desc;
3698             }
3699             elsif ($flags =~ m/s/) {
3700                 $style_synop .= $arg_synop;
3701                 $style_desc .= $arg_desc;
3702             }
3703             else {
3704                 $synop .= $arg_synop;
3705                 $desc .= $arg_desc;
3706             }
3707         }
3708     }
3709     return ($synop, $child_synop, $style_synop, $desc, $child_desc, $style_desc);
3713 #############################################################################
3714 # Function    : ReadSourceDocumentation
3715 # Description : This reads in the documentation embedded in comment blocks
3716 #                in the source code (for Gnome).
3718 #                Parameter descriptions override any in the template files.
3719 #                Function descriptions are placed before any description from
3720 #                the template files.
3722 #                It recursively descends the source directory looking for .c
3723 #                files and scans them looking for specially-formatted comment
3724 #                blocks.
3726 # Arguments   : $source_dir - the directory to scan.
3727 #############m###############################################################
3729 sub ReadSourceDocumentation {
3730     my ($source_dir) = @_;
3731     my ($file, $dir, @suffix_list, $suffix);
3733     # prepend entries from @SOURCE_DIR
3734     for my $dir (@SOURCE_DIRS) {
3735         # Check if the filename is in the ignore list.
3736         if ($source_dir =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3737             @TRACE@("Skipping source directory: $source_dir");
3738             return;
3739         }
3740     }
3742     @TRACE@("Scanning source directory: $source_dir");
3744     # This array holds any subdirectories found.
3745     my (@subdirs) = ();
3747     @suffix_list = split (/,/, $SOURCE_SUFFIXES);
3749     opendir (SRCDIR, $source_dir)
3750         || die "Can't open source directory $source_dir: $!";
3752     foreach $file (readdir (SRCDIR)) {
3753       if ($file =~ /^\./) {
3754         next;
3755       } elsif (-d "$source_dir/$file") {
3756         push (@subdirs, $file);
3757       } elsif (@suffix_list) {
3758         foreach $suffix (@suffix_list) {
3759           if ($file =~ m/\.\Q${suffix}\E$/) {
3760             &ScanSourceFile ("$source_dir/$file");
3761           }
3762         }
3763       } elsif ($file =~ m/\.[ch]$/) {
3764         &ScanSourceFile ("$source_dir/$file");
3765       }
3766     }
3767     closedir (SRCDIR);
3769     # Now recursively scan the subdirectories.
3770     foreach $dir (@subdirs) {
3771         &ReadSourceDocumentation ("$source_dir/$dir");
3772     }
3776 #############################################################################
3777 # Function    : ScanSourceFile
3778 # Description : Scans one source file looking for specially-formatted comment
3779 #                blocks. Later &MergeSourceDocumentation is used to merge any
3780 #                documentation found with the documentation already read in
3781 #                from the template files.
3783 # Arguments   : $file - the file to scan.
3784 #############################################################################
3786 sub ScanSourceFile {
3787     my ($file) = @_;
3788     my $basename;
3790     # prepend entries from @SOURCE_DIR
3791     for my $dir (@SOURCE_DIRS) {
3792         # Check if the filename is in the ignore list.
3793         if ($file =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3794             @TRACE@("Skipping source file: $file");
3795             return;
3796         }
3797     }
3799     if ($file =~ m/^.*[\/\\]([^\/\\]*)$/) {
3800         $basename = $1;
3801     } else {
3802         &LogWarning ($file, 1, "Can't find basename for this filename.");
3803         $basename = $file;
3804     }
3806     # Check if the basename is in the list of files to ignore.
3807     if ($IGNORE_FILES =~ m/(\s|^)\Q${basename}\E(\s|$)/) {
3808         @TRACE@("Skipping source file: $file");
3809         return;
3810     }
3812     @TRACE@("Scanning source file: $file");
3814     open (SRCFILE, $file)
3815         || die "Can't open $file: $!";
3816     my $in_comment_block = 0;
3817     my $symbol;
3818     my $in_part = "";
3819     my ($description, $return_desc, $return_start, $return_style);
3820     my ($since_desc, $stability_desc, $deprecated_desc);
3821     my $current_param;
3822     my $ignore_broken_returns;
3823     my @params;
3824     while (<SRCFILE>) {
3825         # Look for the start of a comment block.
3826         if (!$in_comment_block) {
3827             if (m%^\s*/\*.*\*/%) {
3828                 #one-line comment - not gtkdoc
3829             } elsif (m%^\s*/\*\*\s%) {
3830                 #print "Found comment block start\n";
3832                 $in_comment_block = 1;
3834                 # Reset all the symbol data.
3835                 $symbol = "";
3836                 $in_part = "";
3837                 $description = "";
3838                 $return_desc = "";
3839                 $return_style = "";
3840                 $since_desc = "";
3841                 $deprecated_desc = "";
3842                 $stability_desc = "";
3843                 $current_param = -1;
3844                 $ignore_broken_returns = 0;
3845                 @params = ();
3846             }
3847             next;
3848         }
3850         # We're in a comment block. Check if we've found the end of it.
3851         if (m%^\s*\*+/%) {
3852             if (!$symbol) {
3853                 # maybe its not even meant to be a gtk-doc comment?
3854                 &LogWarning ($file, $., "Symbol name not found at the start of the comment block.");
3855             } else {
3856                 # Add the return value description onto the end of the params.
3857                 if ($return_desc) {
3858                     push (@params, "Returns");
3859                     push (@params, $return_desc);
3860                     if ($return_style eq 'broken') {
3861                         &LogWarning ($file, $., "Free-form return value description in $symbol. Use `Returns:' to avoid ambiguities.");
3862                     }
3863                 }
3864                 # Convert special SGML characters
3865                 $description = &ConvertSGMLChars ($symbol, $description);
3866                 my $k;
3867                 for ($k = 1; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3868                     $params[$k] = &ConvertSGMLChars ($symbol, $params[$k]);
3869                 }
3871                 # Handle Section docs
3872                 if ($symbol =~ m/SECTION:\s*(.*)/) {
3873                     my $real_symbol=$1;
3874                     my $key;
3876                     if (scalar %KnownSymbols) {
3877                         if ((! defined($KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"})) || $KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"} != 1) {
3878                             &LogWarning ($file, $., "Section $real_symbol is not defined in the $MODULE-sections.txt file.");
3879                         }
3880                     }
3882                     #print "SECTION DOCS found in source for : '$real_symbol'\n";
3883                     $ignore_broken_returns = 1;
3884                     for ($k = 0; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3885                         #print "   '".$params[$k]."'\n";
3886                         $params[$k] = "\L$params[$k]";
3887                         undef $key;
3888                         if ($params[$k] eq "short_description") {
3889                             $key = "$TMPL_DIR/$real_symbol:Short_Description";
3890                         } elsif ($params[$k] eq "see_also") {
3891                             $key = "$TMPL_DIR/$real_symbol:See_Also";
3892                         } elsif ($params[$k] eq "title") {
3893                             $key = "$TMPL_DIR/$real_symbol:Title";
3894                         } elsif ($params[$k] eq "stability") {
3895                             $key = "$TMPL_DIR/$real_symbol:Stability_Level";
3896                         } elsif ($params[$k] eq "section_id") {
3897                             $key = "$TMPL_DIR/$real_symbol:Section_Id";
3898                         } elsif ($params[$k] eq "include") {
3899                             $key = "$TMPL_DIR/$real_symbol:Include";
3900                         } elsif ($params[$k] eq "image") {
3901                             $key = "$TMPL_DIR/$real_symbol:Image";
3902                         }
3903                         if (defined($key)) {
3904                             $SourceSymbolDocs{$key}=$params[$k+1];
3905                             $SourceSymbolSourceFile{$key} = $file;
3906                             $SourceSymbolSourceLine{$key} = $.;
3907                         }
3908                     }
3909                     $SourceSymbolDocs{"$TMPL_DIR/$real_symbol:Long_Description"}=$description;
3910                     $SourceSymbolSourceFile{"$TMPL_DIR/$real_symbol:Long_Description"} = $file;
3911                     $SourceSymbolSourceLine{"$TMPL_DIR/$real_symbol:Long_Description"} = $.;
3912                     #$SourceSymbolTypes{$symbol} = "SECTION";
3913                 } else {
3914                     #print "SYMBOL DOCS found in source for : '$symbol' ",length($description), "\n";
3915                     $SourceSymbolDocs{$symbol} = $description;
3916                     $SourceSymbolParams{$symbol} = [ @params ];
3917                     # FIXME $SourceSymbolTypes{$symbol} = "STRUCT,SIGNAL,ARG,FUNCTION,MACRO";
3918                     #if (defined $DeclarationTypes{$symbol}) {
3919                     #    $SourceSymbolTypes{$symbol} = $DeclarationTypes{$symbol}
3920                     #}
3921                     $SourceSymbolSourceFile{$symbol} = $file;
3922                     $SourceSymbolSourceLine{$symbol} = $.;
3923                 }
3925                 if ($since_desc) {
3926                      ($since_desc, my @extra_lines) = split ("\n", $since_desc);
3927                      $since_desc =~ s/^\s+//;
3928                      $since_desc =~ s/\s+$//;
3929                      #print "Since($symbol) : [$since_desc]\n";
3930                      $Since{$symbol} = &ConvertSGMLChars ($symbol, $since_desc);
3931                      if(scalar @extra_lines) {
3932                          &LogWarning ($file, $., "multi-line since docs found");
3933                      }
3934                 }
3936                 if ($stability_desc) {
3937                     $stability_desc = &ParseStabilityLevel($stability_desc, $file, $., "Stability level for $symbol");
3938                     $StabilityLevel{$symbol} = &ConvertSGMLChars ($symbol, $stability_desc);
3939                 }
3941                 if ($deprecated_desc) {
3942                     if (!exists $Deprecated{$symbol}) {
3943                          # don't warn for signals and properties
3944                          #if ($symbol !~ m/::?(.*)/) {
3945                          if (defined $DeclarationTypes{$symbol}) {
3946                              &LogWarning ($file, $.,
3947                                  "$symbol is deprecated in the inline comments, but no deprecation guards were found around the declaration.".
3948                                  " (See the --deprecated-guards option for gtkdoc-scan.)");
3949                          }
3950                     }
3951                     $Deprecated{$symbol} = &ConvertSGMLChars ($symbol, $deprecated_desc);
3952                 }
3953             }
3955             $in_comment_block = 0;
3956             next;
3957         }
3959         # Get rid of ' * ' at start of every line in the comment block.
3960         s%^\s*\*\s?%%;
3961         # But make sure we don't get rid of the newline at the end.
3962         if (!$_) {
3963             $_ = "\n";
3964         }
3965         #print "DEBUG: scanning :$_";
3967         # If we haven't found the symbol name yet, look for it.
3968         if (!$symbol) {
3969             if (m%^\s*(SECTION:\s*\S+)%) {
3970                 $symbol = $1;
3971                 #print "SECTION DOCS found in source for : '$symbol'\n";
3972                 $ignore_broken_returns = 1;
3973             } elsif (m%^\s*([\w:-]*\w)\s*:?\s*(\([-a-z0-9_ ]+\)\s*)*$%) {
3974                 $symbol = $1;
3975                 #print "SYMBOL DOCS found in source for : '$symbol'\n";
3976             }
3977             next;
3978         }
3980         if ($in_part eq "description") {
3981             # Get rid of 'Description:'
3982             s%^\s*Description:%%;
3983         }
3985         if (m/^\s*(returns:|return\s+value:)/i) {
3986             if ($return_style eq 'broken') {
3987                 $description .= $return_start . $return_desc;
3988             }
3989             $return_start = $1;
3990             if ($return_style eq 'sane') {
3991                 &LogWarning ($file, $., "Multiple Returns for $symbol.");
3992             }
3993             $return_style = 'sane';
3994             $ignore_broken_returns = 1;
3995             $return_desc = $';
3996             $in_part = "return";
3997             next;
3998         } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3999             $return_start = $1;
4000             $return_style = 'broken';
4001             $return_desc = $';
4002             $in_part = "return";
4003             next;
4004         } elsif (m%^\s*since:%i) {
4005             # we're in param section and have not seen the blank line
4006             if($in_part ne "") {
4007               $since_desc = $';
4008               $in_part = "since";
4009               next;
4010             }
4011         } elsif (m%^\s*deprecated:%i) {
4012             # we're in param section and have not seen the blank line
4013             if($in_part ne "") {
4014               $deprecated_desc = $';
4015               $in_part = "deprecated";
4016               next;
4017             }
4018         } elsif (m%^\s*stability:%i) {
4019             $stability_desc = $';
4020             $in_part = "stability";
4021             next;
4022         }
4024         if ($in_part eq "description") {
4025             $description .= $_;
4026             next;
4027         } elsif ($in_part eq "return") {
4028             $return_desc .= $_;
4029             next;
4030         } elsif ($in_part eq "since") {
4031             $since_desc .= $_;
4032             next;
4033         } elsif ($in_part eq "stability") {
4034             $stability_desc .= $_;
4035             next;
4036         } elsif ($in_part eq "deprecated") {
4037             $deprecated_desc .= $_;
4038             next;
4039         }
4041         # We must be in the parameters. Check for the empty line below them.
4042         if (m%^\s*$%) {
4043             $in_part = "description";
4044             next;
4045         }
4047         # Look for a parameter name.
4048         if (m%^\s*@(\S+)\s*:\s*%) {
4049             my $param_name = $1;
4050             my $param_desc = $';
4052             #print "Found parameter: $param_name\n";
4053             # Allow varargs variations
4054             if ($param_name =~ m/^\.\.\.$/) {
4055                 $param_name = "...";
4056             }
4057             if ("\L$param_name" eq "returns") {
4058                 $return_style = 'sane';
4059                 $ignore_broken_returns = 1;
4060             }
4061             @TRACE@("Found param for symbol $symbol : '$param_name'= '$_'");
4063             push (@params, $param_name);
4064             push (@params, $param_desc);
4065             $current_param += $PARAM_FIELD_COUNT;
4066             next;
4067         }
4069         # We must be in the middle of a parameter description, so add it on
4070         # to the last element in @params.
4071         if ($current_param == -1) {
4072             &LogWarning ($file, $., "Parsing comment block file : parameter expected.");
4073         } else {
4074             $params[$#params] .= $_;
4075         }
4076     }
4077     close (SRCFILE);
4080 #############################################################################
4081 # Function    : OutputMissingDocumentation
4082 # Description : Outputs report of documentation coverage to a file
4084 # Arguments   : none
4085 #############################################################################
4087 sub OutputMissingDocumentation {
4088     my $old_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.txt";
4089     my $new_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.new";
4091     my $n_documented = 0;
4092     my $n_incomplete = 0;
4093     my $total = 0;
4094     my $symbol;
4095     my $percent;
4096     my $msg;
4097     my $buffer = "";
4098     my $buffer_deprecated = "";
4099     my $buffer_descriptions = "";
4101     open(UNDOCUMENTED, ">$new_undocumented_file")
4102       || die "Can't create $new_undocumented_file";
4104     foreach $symbol (sort (keys (%AllSymbols))) {
4105         # FIXME: should we print LogWarnings for undocumented stuff?
4106         # DEBUG
4107         #my $ssfile = &GetSymbolSourceFile($symbol);
4108         #my $ssline = &GetSymbolSourceLine($symbol);
4109         #my $location = "defined at " . (defined($ssfile)?$ssfile:"?") . ":" . (defined($ssline)?$ssline:"0") . "\n";
4110         # DEBUG
4111         if ($symbol !~ /:(Title|Long_Description|Short_Description|See_Also|Stability_Level|Include|Section_Id|Image)/) {
4112             $total++;
4113             if (exists ($AllDocumentedSymbols{$symbol})) {
4114                 $n_documented++;
4115                 if (exists ($AllIncompleteSymbols{$symbol})) {
4116                     $n_incomplete++;
4117                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4118                     #$buffer .= "\t0: ".$location;
4119                 }
4120             } elsif (exists $Deprecated{$symbol}) {
4121                 if (exists ($AllIncompleteSymbols{$symbol})) {
4122                     $n_incomplete++;
4123                     $buffer_deprecated .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4124                     #$buffer .= "\t1a: ".$location;
4125                 } else {
4126                     $buffer_deprecated .= $symbol . "\n";
4127                     #$buffer .= "\t1b: ".$location;
4128                 }
4129             } else {
4130                 if (exists ($AllIncompleteSymbols{$symbol})) {
4131                     $n_incomplete++;
4132                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4133                     #$buffer .= "\t2a: ".$location;
4134                 } else {
4135                     $buffer .= $symbol . "\n";
4136                     #$buffer .= "\t2b: ".$location;
4137                 }
4138             }
4139         } elsif ($symbol =~ /:(Long_Description|Short_Description)/) {
4140             $total++;
4141             #my $len1=(exists($SymbolDocs{$symbol}))?length($SymbolDocs{$symbol}):-1;
4142             #my $len2=(exists($AllDocumentedSymbols{$symbol}))?length($AllDocumentedSymbols{$symbol}):-1;
4143             #print "%%%% $symbol : $len1,$len2\n";
4144             if (((exists ($SymbolDocs{$symbol})) && (length ($SymbolDocs{$symbol}) > 0))
4145             || ((exists ($AllDocumentedSymbols{$symbol})) && (length ($AllDocumentedSymbols{$symbol}) > 0))) {
4146               $n_documented++;
4147             } else {
4148               # cut off the leading namespace ($TMPL_DIR)
4149               $symbol =~ m/^.*\/(.*)$/;
4150               $buffer_descriptions .= $1 . "\n";
4151             }
4152         }
4153     }
4155     $buffer .= "\n" . $buffer_deprecated . "\n" . $buffer_descriptions;
4157     if ($total == 0) {
4158       $percent = 100;
4159     } else {
4160       $percent = ($n_documented / $total) * 100.0;
4161     }
4163     printf UNDOCUMENTED "%.0f%% symbol docs coverage.\n", $percent;
4164     print UNDOCUMENTED "$n_documented symbols documented.\n";
4165     print UNDOCUMENTED "$n_incomplete symbols incomplete.\n";
4166     print UNDOCUMENTED ($total - $n_documented) . " not documented.\n\n\n";
4168     print UNDOCUMENTED $buffer;
4169     close (UNDOCUMENTED);
4171     return &UpdateFileIfChanged ($old_undocumented_file, $new_undocumented_file, 0);
4173     printf "%.0f%% symbol docs coverage", $percent;
4174     print "($n_documented symbols documented, $n_incomplete symbols incomplete, " . ($total - $n_documented) . " not documented)\n";
4175     print "See $MODULE-undocumented.txt for a list of missing docs.\nThe doc coverage percentage doesn't include intro sections.\n";
4179 #############################################################################
4180 # Function    : OutputUndeclaredSymbols
4181 # Description : Outputs symbols that are listed in the section file, but not
4182 #               declaration is found in the sources
4184 # Arguments   : none
4185 #############################################################################
4187 sub OutputUndeclaredSymbols {
4188     my $old_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.txt";
4189     my $new_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.new";
4191     open(UNDECLARED, ">$new_undeclared_file")
4192         || die "Can't create $new_undeclared_file";
4194     if (%UndeclaredSymbols) {
4195         print UNDECLARED (join("\n", sort keys %UndeclaredSymbols));
4196         print UNDECLARED "\n";
4197         print "See $MODULE-undeclared.txt for the list of undeclared symbols.\n"
4198     }
4199     close(UNDECLARED);
4201     return &UpdateFileIfChanged ($old_undeclared_file, $new_undeclared_file, 0);
4204 #############################################################################
4205 # Function    : OutputUnusedSymbols
4206 # Description : Outputs symbols that are documented in comments, but not
4207 #               declared in the sources
4209 # Arguments   : none
4210 #############################################################################
4212 sub OutputUnusedSymbols {
4213     my $num_unused = 0;
4214     my $old_unused_file = "$ROOT_DIR/$MODULE-unused.txt";
4215     my $new_unused_file = "$ROOT_DIR/$MODULE-unused.new";
4217     open (UNUSED, ">$new_unused_file")
4218         || die "Can't open $new_unused_file";
4219     my ($symbol);
4220     foreach $symbol (sort keys (%Declarations)) {
4221         if (!defined ($DeclarationOutput{$symbol})) {
4222             print (UNUSED "$symbol\n");
4223             $num_unused++;
4224         }
4225     }
4226     foreach $symbol (sort (keys (%AllUnusedSymbols))) {
4227         print (UNUSED "$symbol(" . $AllUnusedSymbols{$symbol} . ")\n");
4228         $num_unused++;
4229     }
4230     close (UNUSED);
4231     if ($num_unused != 0) {
4232         &LogWarning ($old_unused_file, 1, "$num_unused unused declarations.".
4233             "They should be added to $MODULE-sections.txt in the appropriate place.");
4234     }
4236     return &UpdateFileIfChanged ($old_unused_file, $new_unused_file, 0);
4240 #############################################################################
4241 # Function    : OutputAllSymbols
4242 # Description : Outputs list of all symbols to a file
4244 # Arguments   : none
4245 #############################################################################
4247 sub OutputAllSymbols {
4248      my $n_documented = 0;
4249      my $total = 0;
4250      my $symbol;
4251      my $percent;
4252      my $msg;
4254      open (SYMBOLS, ">$ROOT_DIR/$MODULE-symbols.txt")
4255           || die "Can't create $ROOT_DIR/$MODULE-symbols.txt: $!";
4257      foreach $symbol (sort (keys (%AllSymbols))) {
4258           print SYMBOLS $symbol . "\n";
4259      }
4261      close (SYMBOLS);
4264 #############################################################################
4265 # Function    : OutputSymbolsWithoutSince
4266 # Description : Outputs list of all symbols without a since tag to a file
4268 # Arguments   : none
4269 #############################################################################
4271 sub OutputSymbolsWithoutSince {
4272      my $n_documented = 0;
4273      my $total = 0;
4274      my $symbol;
4275      my $percent;
4276      my $msg;
4278      open (SYMBOLS, ">$ROOT_DIR/$MODULE-nosince.txt")
4279           || die "Can't create $ROOT_DIR/$MODULE-nosince.txt: $!";
4281      foreach $symbol (sort (keys (%SourceSymbolDocs))) {
4282          if (!defined $Since{$symbol}) {
4283              print SYMBOLS $symbol . "\n";
4284          }
4285      }
4287      close (SYMBOLS);
4291 #############################################################################
4292 # Function    : MergeSourceDocumentation
4293 # Description : This merges documentation read from a source file into the
4294 #                documentation read in from a template file.
4296 #                Parameter descriptions override any in the template files.
4297 #                Function descriptions are placed before any description from
4298 #                the template files.
4300 # Arguments   : none
4301 #############################################################################
4303 sub MergeSourceDocumentation {
4304     my $symbol;
4305     my @Symbols;
4307     if (scalar %SymbolDocs) {
4308         @Symbols=keys (%SymbolDocs);
4309         #print "num existing entries: ".(scalar @Symbols)."\n";
4310         #print "  ",$Symbols[0], " ",$Symbols[1],"\n";
4311     }
4312     else {
4313         # filter scanned declarations, with what we suppress from -sections.txt
4314         my %tmp = ();
4315         foreach $symbol (keys (%Declarations)) {
4316             if (defined($KnownSymbols{$symbol}) && $KnownSymbols{$symbol} == 1) {
4317                 $tmp{$symbol}=1;
4318             }
4319         }
4320         # , add the rest from -sections.txt
4321         foreach $symbol (keys (%KnownSymbols)) {
4322             if ($KnownSymbols{$symbol} == 1) {
4323                 $tmp{$symbol}=1;
4324             }
4325         }
4326         # and add whats found in the source
4327         foreach $symbol (keys (%SourceSymbolDocs)) {
4328             $tmp{$symbol}=1;
4329         }
4330         @Symbols = keys (%tmp);
4331         #print "num source entries: ".(scalar @Symbols)."\n";
4332     }
4333     foreach $symbol (@Symbols) {
4334         $AllSymbols{$symbol} = 1;
4336         my $have_tmpl_docs = 0;
4338         ## see if the symbol is documented in template
4339         my $tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4340         my $check_tmpl_doc =$tmpl_doc;
4341         # remove all xml-tags and whitespaces
4342         $check_tmpl_doc =~ s/<.*?>//g;
4343         $check_tmpl_doc =~ s/\s//g;
4344         # anything left ?
4345         if ($check_tmpl_doc ne "") {
4346             $have_tmpl_docs = 1;
4347             #print "## [$check_tmpl_doc]\n";
4348         } else {
4349             # if the docs have just an empty para, don't merge that.
4350             $check_tmpl_doc = $tmpl_doc;
4351             $check_tmpl_doc =~ s/(\s|\n)//msg;
4352             if ($check_tmpl_doc eq "<para></para>") {
4353                $tmpl_doc = "";
4354             }
4355         }
4357         if (exists ($SourceSymbolDocs{$symbol})) {
4358             my $type = $DeclarationTypes {$symbol};
4360             #print "merging [$symbol] from source\n";
4362             my $item = "Parameter";
4363             if (defined ($type)) {
4364                 if ($type eq 'STRUCT') {
4365                     $item = "Field";
4366                 } elsif ($type eq 'ENUM') {
4367                     $item = "Value";
4368                 } elsif ($type eq 'UNION') {
4369                     $item = "Field";
4370                 }
4371             } else {
4372                 $type="SIGNAL";
4373             }
4375             my $src_doc = $SourceSymbolDocs{$symbol};
4376             # remove leading and training whitespaces
4377             $src_doc =~ s/^\s+//;
4378             $src_doc =~ s/\s+$//;
4380             # Don't output warnings for overridden titles as titles are
4381             # automatically generated in the -sections.txt file, and thus they
4382             # are often overridden.
4383             if ($have_tmpl_docs && $symbol !~ m/:Title$/) {
4384                 # check if content is different
4385                 if ($tmpl_doc ne $src_doc) {
4386                     #print "[$tmpl_doc] [$src_doc]\n";
4387                     &LogWarning ($SourceSymbolSourceFile{$symbol}, $SourceSymbolSourceLine{$symbol},
4388                         "Documentation in template ".$SymbolSourceFile{$symbol}.":".$SymbolSourceLine{$symbol}." for $symbol being overridden by inline comments.");
4389                 }
4390             }
4392             if ($src_doc ne "") {
4393                  $AllDocumentedSymbols{$symbol} = 1;
4394             }
4396             # Convert <!--PARAMETERS--> with any blank lines around it to
4397             # a </para> followed by <!--PARAMETERS--> followed by <para>.
4398             $src_doc =~ s%\n+\s*<!--PARAMETERS-->\s*\n+%\n</para>\n<!--PARAMETERS-->\n<para>\n%g;
4400             # Do not add <para> to nothing, it breaks missing docs checks.
4401             my $src_doc_para = "";
4402             if ($src_doc ne "") {
4403                 $src_doc_para = $src_doc;
4404             }
4406             if ($symbol =~ m/$TMPL_DIR\/.+:Long_Description/) {
4407                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4408             } elsif ($symbol =~ m/$TMPL_DIR\/.+:.+/) {
4409                 # For the title/summary/see also section docs we don't want to
4410                 # add any <para> tags.
4411                 $SymbolDocs{$symbol} = "$src_doc"
4412             } else {
4413                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4414             }
4416             # merge parameters
4417             if ($symbol =~ m/.*::.*/) {
4418                 # For signals we prefer the param names from the source docs,
4419                 # since the ones from the templates are likely to contain the
4420                 # artificial argn names which are generated by gtkdoc-scangobj.
4421                 $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4422                 # FIXME: we need to check for empty docs here as well!
4423             } else {
4424                 # The templates contain the definitive parameter names and order,
4425                 # so we will not change that. We only override the actual text.
4426                 my $tmpl_params = $SymbolParams{$symbol};
4427                 if (!defined ($tmpl_params)) {
4428                     #print "No merge needed for $symbol\n";
4429                     $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4430                     #  FIXME: we still like to get the number of params and merge
4431                     #  1) we would noticed that params have been removed/renamed
4432                     #  2) we would catch undocumented params
4433                     #  params are not (yet) exported in -decl.txt so that we
4434                     #  could easily grab them :/
4435                 } else {
4436                     my $params = $SourceSymbolParams{$symbol};
4437                     my $j;
4438                     #print "Merge needed for $symbol, tmpl_params: ",$#$tmpl_params,", source_params: ",$#$params," \n";
4439                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4440                         my $tmpl_param_name = $$tmpl_params[$j];
4442                         # Try to find the param in the source comment documentation.
4443                         my $found = 0;
4444                         my $k;
4445                         #print "  try merge param $tmpl_param_name\n";
4446                         for ($k = 0; $k <= $#$params; $k += $PARAM_FIELD_COUNT) {
4447                             my $param_name = $$params[$k];
4448                             my $param_desc = $$params[$k + 1];
4450                             #print "    test param  $param_name\n";
4451                             # We accept changes in case, since the Gnome source
4452                             # docs contain a lot of these.
4453                             if ("\L$param_name" eq "\L$tmpl_param_name") {
4454                                 $found = 1;
4456                                 # Override the description.
4457                                 $$tmpl_params[$j + 1] = $param_desc;
4459                                 # Set the name to "" to mark it as used.
4460                                 $$params[$k] = "";
4461                                 last;
4462                             }
4463                         }
4465                         # If it looks like the parameters are there, but not
4466                         # in the right place, try to explain a bit better.
4467                         if ((!$found) && ($src_doc =~ m/\@$tmpl_param_name:/)) {
4468                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4469                                 "Parameters for $symbol must start on the line immediately after the function or macro name.");
4470                         }
4471                     }
4473                     # Now we output a warning if parameters have been described which
4474                     # do not exist.
4475                     for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
4476                         my $param_name = $$params[$j];
4477                         if ($param_name) {
4478                             # the template builder cannot detect if a macro returns
4479                             # a result or not
4480                             if(($type eq "MACRO") && ($param_name eq "Returns")) {
4481                                 # FIXME: do we need to add it then to tmpl_params[] ?
4482                                 my $num=$#$tmpl_params;
4483                                 #print "  adding Returns: to macro docs for $symbol.\n";
4484                                 $$tmpl_params[$num+1]="Returns";
4485                                 $$tmpl_params[$num+2]=$$params[$j+1];
4486                                 next;
4487                             }
4488                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4489                                 "$item described in source code comment block but does not exist. $type: $symbol $item: $param_name.");
4490                         }
4491                     }
4492                 }
4493             }
4494         } else {
4495             if ($have_tmpl_docs) {
4496                 $AllDocumentedSymbols{$symbol} = 1;
4497                 #print "merging [$symbol] from template\n";
4498             }
4499             else {
4500                 #print "[$symbol] undocumented\n";
4501             }
4502         }
4504         # if this symbol is documented, check if docs are complete
4505         $check_tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4506         # remove all xml-tags and whitespaces
4507         $check_tmpl_doc =~ s/<.*?>//g;
4508         $check_tmpl_doc =~ s/\s//g;
4509         if ($check_tmpl_doc ne "") {
4510             my $tmpl_params = $SymbolParams{$symbol};
4511             if (defined ($tmpl_params)) {
4512                 my $type = $DeclarationTypes {$symbol};
4514                 my $item = "Parameter";
4515                 if (defined ($type)) {
4516                     if ($type eq 'STRUCT') {
4517                         $item = "Field";
4518                     } elsif ($type eq 'ENUM') {
4519                         $item = "Value";
4520                     } elsif ($type eq 'UNION') {
4521                         $item = "Field";
4522                     }
4523                 } else {
4524                     $type="SIGNAL";
4525                 }
4527                 #print "Check param docs for $symbol, tmpl_params: ",$#$tmpl_params," entries, type=$type\n";
4529                 if ($#$tmpl_params > 0) {
4530                     my $j;
4531                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4532                         # Output a warning if the parameter is empty and
4533                         # remember for stats.
4534                         my $tmpl_param_name = $$tmpl_params[$j];
4535                         my $tmpl_param_desc = $$tmpl_params[$j + 1];
4536                         if ($tmpl_param_name ne "void" && $tmpl_param_desc !~ m/\S/) {
4537                             if (exists ($AllIncompleteSymbols{$symbol})) {
4538                                 $AllIncompleteSymbols{$symbol}.=", ".$tmpl_param_name;
4539                             } else {
4540                                 $AllIncompleteSymbols{$symbol}=$tmpl_param_name;
4541                             }
4542                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4543                                 "$item description for $symbol"."::"."$tmpl_param_name is missing in source code comment block.");
4544                         }
4545                     }
4546                 }
4547                 else {
4548                     if ($#$tmpl_params == 0) {
4549                         $AllIncompleteSymbols{$symbol}="<items>";
4550                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4551                             "$item descriptions for $symbol are missing in source code comment block.");
4552                     }
4553                     # $#$tmpl_params==-1 means we don't know about parameters
4554                     # this unfortunately does not tell if there should be some
4555                 }
4556             }
4557         }
4558    }
4559    #print "num doc entries: ".(scalar %SymbolDocs)."\n";
4562 #############################################################################
4563 # Function    : IsEmptyDoc
4564 # Description : Check if a doc-string is empty. Its also regarded as empty if
4565 #               it only consist of whitespace or e.g. FIXME.
4566 # Arguments   : the doc-string
4567 #############################################################################
4568 sub IsEmptyDoc {
4569     my ($doc) = @_;
4571     if ($doc =~ /^\s*$/) {
4572         return 1;
4573     }
4575     if ($doc =~ /^\s*<para>\s*(FIXME)?\s*<\/para>\s*$/) {
4576         return 1;
4577     }
4579     return 0;
4582 #############################################################################
4583 # Function    : ConvertMarkDown
4584 # Description : Converts mark down syntax to the respective docbook.
4585 #               http://de.wikipedia.org/wiki/Markdown
4586 #               Inspired by the design of ParseDown
4587 #               http://parsedown.org/
4588 #               Copyright (c) 2013 Emanuil Rusev, erusev.com
4589 # Arguments   : the symbol name, the doc-string
4590 #############################################################################
4592 sub ConvertMarkDown {
4593     my ($symbol, $text) = @_;
4595     $text = &MarkDownParse ($text, $symbol);
4597     return $text
4600 # SUPPORTED MARKDOWN
4601 # ==================
4603 # Atx-style Headers
4604 # -----------------
4606 # # Header 1
4608 # ## Header 2 ##
4610 # Setext-style Headers
4611 # --------------------
4613 # Header 1
4614 # ========
4616 # Header 2
4617 # --------
4619 # Ordered (unnested) Lists
4620 # ------------------------
4622 # 1. item 1
4624 # 1. item 2 with loooong
4625 #    description
4627 # 3. item 3
4629 # Note: we require a blank line above the list items
4632 # TODO(ensonic): it would be nice to add id parameters to the refsect2 elements
4634 sub MarkDownParseBlocks {
4635   my ($linesref, $symbol, $context) = @_;
4636   my $line;
4637   my @md_blocks = ();
4638   my $md_block = { type => "" };
4640  OUTER: foreach $line (@$linesref) {
4641     my $first_char = substr ($line, 0, 1);
4642     my $deindented_line;
4644     if ($md_block->{"type"} eq "markup") {
4645       if (!$md_block->{"closed"}) {
4646         if (index ($line, $md_block->{"start"}) != -1) {
4647           $md_block->{"depth"}++;
4648         }
4649         if (index ($line, $md_block->{"end"}) != -1) {
4650           if ($md_block->{"depth"} > 0) {
4651             $md_block->{"depth"}--;
4652           } else {
4653             $md_block->{"closed"} = 1;
4654           }
4655         }
4656         $md_block->{"text"} .= "\n" . $line;
4657         next OUTER;
4658       }
4659     }
4661     $deindented_line = $line;
4662     $deindented_line =~ s/^\s+//;
4664     if ($md_block->{"type"} eq "heading") {
4665       # a heading is ended by any level less than or equal
4666       if ($md_block->{"level"} == 1) {
4667         if ($line =~ /^={4,}[ \t]*$/) {
4668           my $text = pop $md_block->{"lines"};
4669           $md_block->{"interrupted"} = 0;
4670           push @md_blocks, $md_block;
4672           $md_block = { type => "heading",
4673                         text => $text,
4674                         lines => [],
4675                         level => 1 };
4676           next OUTER;
4677         } elsif ($line =~ /^[#][ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4678           $md_block->{"interrupted"} = 0;
4679           push @md_blocks, $md_block;
4681           $md_block = { type => "heading",
4682                         text => $1,
4683                         id => $2,
4684                         lines => [],
4685                         level => 1 };
4686           next OUTER;
4687         } else {
4688           # push lines into the block until the end is reached
4689           push $md_block->{"lines"}, $line;
4690           next OUTER;
4691         }
4692       } else {
4693         if ($line =~ /^[=]{4,}[ \t]*$/) {
4694           my $text = pop $md_block->{"lines"};
4695           $md_block->{"interrupted"} = 0;
4696           push @md_blocks, $md_block;
4698           $md_block = { type => "heading",
4699                         text => $text,
4700                         lines => [],
4701                         level => 1 };
4702           next OUTER;
4703         } elsif ($line =~ /^[-]{4,}[ \t]*$/) {
4704           my $text = pop $md_block->{"lines"};
4705           $md_block->{"interrupted"} = 0;
4706           push @md_blocks, $md_block;
4708           $md_block = { type => "heading",
4709                         text => $text,
4710                         lines => [],
4711                         level => 2 };
4712           next OUTER;
4713         } elsif ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4714           $md_block->{"interrupted"} = 0;
4715           push @md_blocks, $md_block;
4717           $md_block = { type => "heading",
4718                         text => $2,
4719                         id => $3,
4720                         lines => [],
4721                         level => length($1) };
4722           next OUTER;
4723         } else {
4724           # push lines into the block until the end is reached
4725           push $md_block->{"lines"}, $line;
4726           next OUTER;
4727         }
4728       }
4729     } elsif ($md_block->{"type"} eq "code") {
4730       if ($line =~ /^[ \t]*\]\|/) {
4731         push @md_blocks, $md_block;
4732         $md_block = { type => "paragraph",
4733                       text => "",
4734                       lines => [] };
4735       } else {
4736         push $md_block->{"lines"}, $line;
4737       }
4738       next OUTER;
4739     }
4741     if ($deindented_line eq "") {
4742       $md_block->{"interrupted"} = 1;
4743       next;
4744     }
4746     if ($md_block->{"type"} eq "quote") {
4747       if (!$md_block->{"interrupted"}) {
4748         $line =~ s/^[ ]*>[ ]?//;
4749         push $md_block->{"lines"}, $line;
4750         next OUTER;
4751       }
4752     } elsif ($md_block->{"type"} eq "li") {
4753       if ($line =~ /^([ ]{0,3})(\d+[.]|[*+-])[ ](.*)/) {
4754         my $indentation = $1;
4755         if ($md_block->{"indentation"} ne $indentation) {
4756           push $md_block->{"lines"}, $line;
4757         } else {
4758           my $lines = $3;
4759           my $ordered = $md_block->{"ordered"};
4760           $lines =~ s/^[ ]{0,4}//;
4761           $md_block->{"last"} = 0;
4762           push @md_blocks, $md_block;
4763           $md_block = { type => "li",
4764                         ordered => $ordered,
4765                         indentation => $indentation,
4766                         first => 0,
4767                         last => 1,
4768                         lines => [ $lines ] };
4769         }
4770         next OUTER;
4771       }
4773       if ($md_block->{"interrupted"}) {
4774         if ($first_char eq " ") {
4775           push $md_block->{"lines"}, "";
4776           $line =~ s/^[ ]{0,4}//;
4777           push $md_block->{"lines"}, $line;
4778           $md_block->{"interrupted"} = 0;
4779           next OUTER;
4780         }
4781       } else {
4782         $line =~ s/^[ ]{0,4}//;
4783         push $md_block->{"lines"}, $line;
4784         next OUTER;
4785       }
4786     }
4788     # indentation sensitive types
4790     if ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4791       # atx heading (#)
4792       push @md_blocks, $md_block;
4794       $md_block = { type => "heading",
4795                     text => $2,
4796                     id => $3,
4797                     lines => [],
4798                     level => length($1) };
4800       next OUTER;
4801     } elsif ($line =~ /^={4,}[ \t]*$/) {
4802       # setext heading (====)
4804       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4805         push @md_blocks, $md_block;
4806         $md_block->{"type"} = "heading";
4807         $md_block->{"lines"} = [];
4808         $md_block->{"level"} = 1;
4809       }
4811       next OUTER;
4812     } elsif ($line =~ /^-{4,}[ \t]*$/) {
4813       # setext heading (-----)
4815       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4816         push @md_blocks, $md_block;
4817         $md_block->{"type"} = "heading";
4818         $md_block->{"lines"} = [];
4819         $md_block->{"level"} = 2;
4820       }
4822       next OUTER;
4823     } elsif ($line =~ /^[ \t]*\|\[[ ]*(?:<!-- language="([^"]+?)" -->)?/) {
4824       # code
4825       $md_block->{"interrupted"} = 1;
4826       push @md_blocks, $md_block;
4827       $md_block = { type => "code",
4828                     language => $1,
4829                     lines => [] };
4830       next OUTER;
4831     }
4833     # indentation insensitive types
4835     if ($line =~ /^[ ]*<!DOCTYPE/) {
4836       push @md_blocks, $md_block;
4838       $md_block = { type   => "markup",
4839                     text   => $deindented_line,
4840                     start  => "<",
4841                     end    => ">",
4842                     closed => 0,
4843                     depth  => 0 };
4845     } elsif ($line =~ /^[ ]*<\??(\w+)[^>]*([\/\?])?[ \t]*>/) {
4846       # markup, including <?xml version="1.0"?>
4847       my $tag = $1;
4848       my $is_self_closing = defined($2);
4850       if (! $MD_TEXT_LEVEL_ELEMENTS{$tag} && $tag ne "http") {
4851         push @md_blocks, $md_block;
4853         if ($is_self_closing) {
4854           $md_block = { type => "self-closing tag",
4855                         text => $deindented_line };
4856           $is_self_closing = 0;
4857           next OUTER;
4858         }
4860         $md_block = { type   => "markup",
4861                       text   => $deindented_line,
4862                       start  => "<" . $tag . ">",
4863                       end    => "</" . $tag . ">",
4864                       closed => 0,
4865                       depth  => 0 };
4866         if ($deindented_line =~ /<\/$tag>/) {
4867           $md_block->{"closed"} = 1;
4868         }
4869         next OUTER;
4870       }
4871     } elsif ($line =~ /^([ ]*)[*+-][ ](.*)/) {
4872       # li
4873       push @md_blocks, $md_block;
4874       my $lines = $2;
4875       my $indentation = $1;
4876       $lines =~ s/^[ ]{0,4}//;
4877       $md_block = { type => "li",
4878                     ordered => 0,
4879                     indentation => $indentation,
4880                     first => 1,
4881                     last => 1,
4882                     lines => [ $lines ] };
4883       next OUTER;
4884     } elsif ($line =~ /^[ ]*>[ ]?(.*)/) {
4885       push @md_blocks, $md_block;
4886       $md_block = { type => "quote",
4887                     lines => [ $1 ] };
4888       next OUTER;
4889     }
4891     # list item
4893     if ($line =~ /^([ ]{0,4})\d+[.][ ]+(.*)/) {
4894       push @md_blocks, $md_block;
4895       my $lines = $2;
4896       my $indentation = $1;
4897       $lines =~ s/^[ ]{0,4}//;
4899       $md_block = { type => "li",
4900                     ordered => 1,
4901                     indentation => $indentation,
4902                     first => 1,
4903                     last => 1,
4904                     lines => [ $lines ] };
4906       next;
4907     }
4909     # paragraph
4910     if ($md_block->{"type"} eq "paragraph") {
4911       if ($md_block->{"interrupted"}) {
4912         push @md_blocks, $md_block;
4913         $md_block = { type => "paragraph",
4914                       interrupted => 0,
4915                       text => $line };
4916       } else {
4917         $md_block->{"text"} .= "\n" . $line;
4918       }
4919     } else {
4920       push @md_blocks, $md_block;
4921       $md_block = { type => "paragraph",
4922                     text => $line };
4923     }
4924   }
4926   push @md_blocks, $md_block;
4928   shift @md_blocks;
4930   return @md_blocks;
4933 sub MarkDownParseSpanElementsInner {
4934   my ($text, $markersref) = @_;
4935   my $markup = "";
4936   my %markers = map { $_ => 1 } @$markersref;
4938   while ($text ne "") {
4939     my $closest_marker = "";
4940     my $closest_marker_index = 0;
4941     my $closest_marker_position = -1;
4942     my $text_marker = "";
4943     my $i = 0;
4944     my $offset = 0;
4945     my @markers_rest;
4946     my $marker;
4947     my $use;
4949     while ( ($marker, $use) = each %markers ) {
4950       my $marker_position;
4952       if (!$use) {
4953         next;
4954       }
4956       $marker_position = index ($text, $marker);
4958       if ($marker_position < 0) {
4959         $markers{$marker} = 0;
4960         next;
4961       }
4963       if ($closest_marker eq "" || $marker_position < $closest_marker_position) {
4964         $closest_marker = $marker;
4965         $closest_marker_index = $i;
4966         $closest_marker_position = $marker_position;
4967       }
4968     }
4970     if ($closest_marker_position >= 0) {
4971       $text_marker = substr ($text, $closest_marker_position);
4972     }
4974     if ($text_marker eq "") {
4975       $markup .= $text;
4976       $text = "";
4977       next; # last
4978     }
4980     $markup .= substr ($text, 0, $closest_marker_position);
4981     $text = substr ($text, $closest_marker_position);
4982     @markers_rest = map { $markers{$_} ? ($_ eq $closest_marker ? () : $_) : () } keys %markers;
4984     if ($closest_marker eq "![" || $closest_marker eq "[") {
4985       my %element;
4987       if (index ($text, "]") && $text =~ /\[((?:[^][]|(?R))*)\]/) {
4988         my $remaining_text;
4990         %element = ( "!" => (substr ($text, 0, 1) eq "!"),
4991                      "a" => $1 );
4993         $offset = length ($&);
4994         if ($element{"!"}) {
4995           $offset++;
4996         }
4998         $remaining_text = substr ($text, $offset);
4999         if ($remaining_text =~ /^\([ ]*([^)'"]*?)(?:[ ]+['"](.+?)['"])?[ ]*\)/) {
5000           $element{"»"} = $1;
5001           if (defined ($2)) {
5002             $element{"#"} = $2;
5003           }
5004           $offset += length ($&);
5005         } elsif ($remaining_text =~ /^\s*\[([^\]<]*?)\]/) {
5006           $element{"ref"} = $1;
5007           $offset += length ($&);
5008         } else {
5009           undef %element;
5010         }
5011       }
5013       if (%element) {
5014         if ($element{"»"}) {
5015           $element{"»"} =~ s/&/&amp;/g;
5016           $element{"»"} =~ s/</&lt;/g;
5017         }
5018         if ($element{"!"}) {
5019           $markup .= "<inlinemediaobject><imageobject><imagedata fileref=\"" . $element{"»"} . "\"></imagedata></imageobject>";
5021           if (defined ($element{"a"})) {
5022             $markup .= "<textobject><phrase>" . $element{"a"} . "</phrase></textobject>";
5023           }
5025           $markup .= "</inlinemediaobject>";
5026         } elsif ($element{"ref"}) {
5027           $element{"a"} = &MarkDownParseSpanElementsInner ($element{"a"}, \@markers_rest);
5028           $markup .= "<link linkend=\"" . $element{"ref"} . "\"";
5030           if (defined ($element{"#"})) {
5031             # title attribute not supported
5032           }
5034           $markup .= ">" . $element{"a"} . "</link>";
5035         } else {
5036           $element{"a"} = &MarkDownParseSpanElementsInner ($element{"a"}, \@markers_rest);
5037           $markup .= "<ulink url=\"" . $element{"»"} . "\"";
5039           if (defined ($element{"#"})) {
5040             # title attribute not supported
5041           }
5043           $markup .= ">" . $element{"a"} . "</ulink>";
5044         }
5045       } else {
5046         $markup .= $closest_marker;
5047         if ($closest_marker eq "![") {
5048           $offset = 2;
5049         } else {
5050           $offset = 1;
5051         }
5052       }
5053     } elsif ($closest_marker eq "<") {
5054       if ($text =~ /^<(https?:[\/]{2}[^\s]+?)>/i) {
5055         my $element_url = $1;
5056         $element_url =~ s/&/&amp;/g;
5057         $element_url =~ s/</&lt;/g;
5059         $markup .= "<ulink url=\"" . $element_url . "\">" . $element_url . "</ulink>";
5060         $offset = length ($&);
5061       } elsif ($text =~ /^<([A-Za-z0-9._-]+?@[A-Za-z0-9._-]+?)>/) {
5062         $markup .= "<ulink url=\"mailto:" . $1 . "\">" . $1 . "</ulink>";
5063         $offset = length ($&);
5064       } elsif ($text =~ /^<[^>]+?>/) {
5065         $markup .= $&;
5066         $offset = length ($&);
5067       } else {
5068         $markup .= "&lt;";
5069         $offset = 1;
5070       }
5071     } elsif ($closest_marker eq "\\") {
5072       my $special_char = substr ($text, 1, 1);
5073       if ($MD_ESCAPABLE_CHARS{$special_char} ||
5074           $MD_GTK_ESCAPABLE_CHARS{$special_char}) {
5075         $markup .= $special_char;
5076         $offset = 2;
5077       } else {
5078         $markup .= "\\";
5079         $offset = 1;
5080       }
5081     } elsif ($closest_marker eq "`") {
5082       if ($text =~ /^(`+)([^`]+?)\1(?!`)/) {
5083         my $element_text = $2;
5084         $markup .= "<literal>" . $element_text . "</literal>";
5085         $offset = length ($&);
5086       } else {
5087         $markup .= "`";
5088         $offset = 1;
5089       }
5090     } elsif ($closest_marker eq "@") {
5091       # Convert '@param()'
5092       # FIXME: we could make those also links ($symbol.$2), but that would be less
5093       # useful as the link target is a few lines up or down
5094       if ($text =~ /^(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)/) {
5095         $markup .= $1 . "<parameter>" . $2 . "()</parameter>\n";
5096         $offset = length ($&);
5097       } elsif ($text =~ /^(\A|[^\\])\@(\w+((\.|->)\w+)*)/) {
5098         # Convert '@param', but not '\@param'.
5099         $markup .= $1 . "<parameter>" . $2 . "</parameter>\n";
5100         $offset = length ($&);
5101       } elsif ($text =~ /^\\\@/) {
5102         $markup .= "\@";
5103         $offset = length ($&);
5104       } else {
5105         $markup .= "@";
5106         $offset = 1;
5107       }
5108     } elsif ($closest_marker eq "#") {
5109       if ($text =~ /^(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/) {
5110         # handle #Object.func()
5111         $markup .= $1 . &MakeXRef ($2, &tagify ($2 . "()", "function"));
5112         $offset = length ($&);
5113       } elsif ($text =~ /^(\A|[^\\])#([\w\-:\.]+[\w]+)/) {
5114         # Convert '#symbol', but not '\#symbol'.
5115         $markup .= $1 . &MakeHashXRef ($2, "type");
5116         $offset = length ($&);
5117       } elsif ($text =~ /^\\#/) {
5118         $markup .= "#";
5119         $offset = length ($&);
5120       } else {
5121         $markup .= "#";
5122         $offset = 1;
5123       }
5124     } elsif ($closest_marker eq "%") {
5125       if ($text =~ /^(\A|[^\\])\%(-?\w+)/) {
5126         # Convert '%constant', but not '\%constant'.
5127         # Also allow negative numbers, e.g. %-1.
5128         $markup .= $1 . &MakeXRef ($2, &tagify ($2, "literal"));
5129         $offset = length ($&);
5130       } elsif ($text =~ /^\\%/) {
5131         $markup .= "\%";
5132         $offset = length ($&);
5133       } else {
5134         $markup .= "%";
5135         $offset = 1;
5136       }
5137     }
5139     if ($offset > 0) {
5140       $text = substr ($text, $offset);
5141     }
5142   }
5144   return $markup;
5147 sub MarkDownParseSpanElements {
5148   my ($text) = @_;
5149   my @markers = ( "\\", "<", "![", "[", "`", "%", "#", "@" );
5151   $text = &MarkDownParseSpanElementsInner ($text, \@markers);
5153   # Convert 'function()' or 'macro()'.
5154   # if there is abc_*_def() we don't want to make a link to _def()
5155   # FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
5156   $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
5158   return $text;
5161 sub ReplaceEntities {
5162   my ($text, $symbol) = @_;
5163   my $warn = "";
5164   my @entities = ( [ "&lt;", "<" ],
5165                    [ "&gt;", ">" ],
5166                    [ "&ast;", "*" ],
5167                    [ "&num;", "#" ],
5168                    [ "&percnt;", "%"],
5169                    [ "&colon;", ":" ],
5170                    [ "&quot;", "\"" ],
5171                    [ "&apos;", "'" ],
5172                    [ "&nbsp;", " " ],
5173                    [ "&amp;", "&" ] ); # Do this last, or the others get messed up.
5174   my $i;
5176   # Expand entities in <programlisting> even inside CDATA since
5177   # we changed the definition of |[ to add CDATA
5178   for ($i = 0; $i <= $#entities; $i++) {
5179     if ($text =~ s/$entities[$i][0]/$entities[$i][1]/g) {
5180       # don't warn about &ast; since it is expected to be present
5181       # for C-style comments
5182       if ($entities[$i][0] ne "&ast;") {
5183         $warn .= "$entities[$i][0] ";
5184       }
5185     }
5186   }
5188   if ($warn ne "") {
5189     chomp $warn;
5190     &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
5191                  "Deprecated entities found in documentation for $symbol: $warn");
5192   }
5194   return $text;
5197 sub MarkDownOutputDocBook {
5198   my ($blocksref, $symbol, $context) = @_;
5199   my $output = "";
5200   my $block;
5201   my @blocks = @$blocksref;
5203   foreach $block (@blocks) {
5204     my $text;
5205     my $title;
5207     if ($block->{"type"} eq "paragraph") {
5208       $text = &MarkDownParseSpanElements ($block->{"text"});
5210       if ($context eq "li" && $output eq "") {
5211         if ($block->{"interrupted"}) {
5212           $output .= "\n"."<para>".$text."</para>"."\n";
5213         } else {
5214           $output .= $text;
5215           if ($#blocks > 0) {
5216             $output .= "\n";
5217           }
5218         }
5219       } else {
5220         $output .= "<para>".$text."</para>"."\n";
5221       }
5223     } elsif ($block->{"type"} eq "heading") {
5224       my $tag;
5226       $title = &MarkDownParseSpanElements ($block->{"text"});
5228       if ($block->{"level"} == 1) {
5229         $tag = "refsect2";
5230       } else {
5231         $tag = "refsect3";
5232       }
5234       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "heading");
5235       if (defined ($block->{"id"})) {
5236         $output .= "<" . $tag . " id=\"" . $block->{"id"} . "\">";
5237       } else {
5238         $output .= "<" . $tag . ">";
5239       }
5241       $output .= "<title>" . $title . "</title>" . $text . "</" . $tag . ">\n";
5242     } elsif ($block->{"type"} eq "li") {
5243       my $tag = "itemizedlist";
5245       if ($block->{"first"}) {
5246         if ($block->{"ordered"}) {
5247           $tag = "orderedlist";
5248         }
5249         $output .= "<".$tag.">\n";
5250       }
5252       if ($block->{"interrupted"}) {
5253         push $block->{"lines"}, "";
5254       }
5256       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "li");
5257       $output .= "<listitem>".$text."</listitem>\n";
5258       if ($block->{"last"}) {
5259         if ($block->{"ordered"}) {
5260           $tag = "orderedlist";
5261         }
5262         $output .= "</".$tag.">\n";
5263       }
5264     } elsif ($block->{"type"} eq "quote") {
5265       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "quote");
5266       $output .= "<blockquote>\n" . $text . "</blockquote>\n";
5267     } elsif ($block->{"type"} eq "code") {
5268       if ($block->{"language"}) {
5269         $output .= "<informalexample><programlisting language=\"" . $block->{"language"} . "\"><![CDATA[\n";
5270       } else {
5271         $output .= "<informalexample><programlisting><![CDATA[\n";
5272       }
5273       foreach (@{$block->{"lines"}}) {
5274         $output .= &ReplaceEntities ($_, $symbol) . "\n";
5275       }
5276       $output .= "]]></programlisting></informalexample>\n";
5277     } elsif ($block->{"type"} eq "markup") {
5278       $text = &ExpandAbbreviations($symbol, $block->{"text"});
5279       $output .= $text."\n";
5280     } else {
5281       $output .= $block->{"text"}."\n";
5282     }
5283   }
5285   return $output;
5288 sub MarkDownParseLines {
5289   my ($linesref, $symbol, $context) = @_;
5290   my $output;
5291   my @lines = @$linesref;
5292   my @blocks;
5294   @blocks = &MarkDownParseBlocks (\@lines, $symbol, $context);
5295   $output = &MarkDownOutputDocBook (\@blocks, $symbol, $context);
5297   return $output;
5300 sub MarkDownParse {
5301   my ($text, $symbol) = @_;
5302   my @lines;
5304   # take out some variability in line endings
5305   $text =~ s%\r\n%\n%g;
5306   $text =~ s%\r%\n%g;
5308   # split lines
5309   @lines = split("\n", $text);
5310   $text = MarkDownParseLines(\@lines, $symbol, "");
5312   return $text;
5315 #############################################################################
5316 # LIBRARY FUNCTIONS -        These functions are used in both gtkdoc-mkdb and
5317 #                        gtkdoc-mktmpl and should eventually be moved to a
5318 #                        separate library.
5319 #############################################################################
5321 #############################################################################
5322 # Function    : ReadDeclarationsFile
5323 # Description : This reads in a file containing the function/macro/enum etc.
5324 #                declarations.
5326 #                Note that in some cases there are several declarations with
5327 #                the same name, e.g. for conditional macros. In this case we
5328 #                set a flag in the %DeclarationConditional hash so the
5329 #                declaration is not shown in the docs.
5331 #                If a macro and a function have the same name, e.g. for
5332 #                gtk_object_ref, the function declaration takes precedence.
5334 #                Some opaque structs are just declared with 'typedef struct
5335 #                _name name;' in which case the declaration may be empty.
5336 #                The structure may have been found later in the header, so
5337 #                that overrides the empty declaration.
5339 # Arguments   : $file - the declarations file to read
5340 #                $override - if declarations in this file should override
5341 #                        any current declaration.
5342 #############################################################################
5344 sub ReadDeclarationsFile {
5345     my ($file, $override) = @_;
5347     if ($override == 0) {
5348         %Declarations = ();
5349         %DeclarationTypes = ();
5350         %DeclarationConditional = ();
5351         %DeclarationOutput = ();
5352     }
5354     open (INPUT, $file)
5355         || die "Can't open $file: $!";
5356     my $declaration_type = "";
5357     my $declaration_name;
5358     my $declaration;
5359     my $is_deprecated = 0;
5360     while (<INPUT>) {
5361         if (!$declaration_type) {
5362             if (m/^<([^>]+)>/) {
5363                 $declaration_type = $1;
5364                 $declaration_name = "";
5365                 #print "Found declaration: $declaration_type\n";
5366                 $declaration = "";
5367             }
5368         } else {
5369             if (m%^<NAME>(.*)</NAME>%) {
5370                 $declaration_name = $1;
5371             } elsif (m%^<DEPRECATED/>%) {
5372                 $is_deprecated = 1;
5373             } elsif (m%^</$declaration_type>%) {
5374                 #print "Found end of declaration: $declaration_name\n";
5375                 # Check that the declaration has a name
5376                 if ($declaration_name eq "") {
5377                     print "ERROR: $declaration_type has no name $file:$.\n";
5378                 }
5380                 # If the declaration is an empty typedef struct _XXX XXX
5381                 # set the flag to indicate the struct has a typedef.
5382                 if ($declaration_type eq 'STRUCT'
5383                     && $declaration =~ m/^\s*$/) {
5384                     #print "Struct has typedef: $declaration_name\n";
5385                     $StructHasTypedef{$declaration_name} = 1;
5386                 }
5388                 # Check if the symbol is already defined.
5389                 if (defined ($Declarations{$declaration_name})
5390                     && $override == 0) {
5391                     # Function declarations take precedence.
5392                     if ($DeclarationTypes{$declaration_name} eq 'FUNCTION') {
5393                         # Ignore it.
5394                     } elsif ($declaration_type eq 'FUNCTION') {
5395                         if ($is_deprecated) {
5396                             $Deprecated{$declaration_name} = "";
5397                         }
5398                         $Declarations{$declaration_name} = $declaration;
5399                         $DeclarationTypes{$declaration_name} = $declaration_type;
5400                     } elsif ($DeclarationTypes{$declaration_name}
5401                               eq $declaration_type) {
5402                         # If the existing declaration is empty, or is just a
5403                         # forward declaration of a struct, override it.
5404                         if ($declaration_type eq 'STRUCT') {
5405                             if ($Declarations{$declaration_name} =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5406                                 if ($is_deprecated) {
5407                                     $Deprecated{$declaration_name} = "";
5408                                 }
5409                                 $Declarations{$declaration_name} = $declaration;
5410                             } elsif ($declaration =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5411                                 # Ignore an empty or forward declaration.
5412                             } else {
5413                                 &LogWarning ($file, $., "Structure $declaration_name has multiple definitions.");
5414                             }
5415                         } else {
5416                             # set flag in %DeclarationConditional hash for
5417                             # multiply defined macros/typedefs.
5418                             $DeclarationConditional{$declaration_name} = 1;
5419                         }
5420                     } else {
5421                         &LogWarning ($file, $., "$declaration_name has multiple definitions.");
5422                     }
5423                 } else {
5424                     if ($is_deprecated) {
5425                         $Deprecated{$declaration_name} = "";
5426                     }
5427                     $Declarations{$declaration_name} = $declaration;
5428                     $DeclarationTypes{$declaration_name} = $declaration_type;
5429                 }
5431                 $declaration_type = "";
5432                 $is_deprecated = 0;
5433             } else {
5434                 $declaration .= $_;
5435             }
5436         }
5437     }
5438     close (INPUT);
5442 #############################################################################
5443 # Function    : ReadSignalsFile
5444 # Description : This reads in an existing file which contains information on
5445 #                all GTK signals. It creates the arrays @SignalNames and
5446 #                @SignalPrototypes containing info on the signals. The first
5447 #                line of the SignalPrototype is the return type of the signal
5448 #                handler. The remaining lines are the parameters passed to it.
5449 #                The last parameter, "gpointer user_data" is always the same
5450 #                so is not included.
5451 # Arguments   : $file - the file containing the signal handler prototype
5452 #                        information.
5453 #############################################################################
5455 sub ReadSignalsFile {
5456     my ($file) = @_;
5458     my $in_signal = 0;
5459     my $signal_object;
5460     my $signal_name;
5461     my $signal_returns;
5462     my $signal_flags;
5463     my $signal_prototype;
5465     # Reset the signal info.
5466     @SignalObjects = ();
5467     @SignalNames = ();
5468     @SignalReturns = ();
5469     @SignalFlags = ();
5470     @SignalPrototypes = ();
5472     if (! -f $file) {
5473         return;
5474     }
5475     if (!open (INPUT, $file)) {
5476         warn "Can't open $file - skipping signals\n";
5477         return;
5478     }
5479     while (<INPUT>) {
5480         if (!$in_signal) {
5481             if (m/^<SIGNAL>/) {
5482                 $in_signal = 1;
5483                 $signal_object = "";
5484                 $signal_name = "";
5485                 $signal_returns = "";
5486                 $signal_prototype = "";
5487             }
5488         } else {
5489             if (m/^<NAME>(.*)<\/NAME>/) {
5490                 $signal_name = $1;
5491                 if ($signal_name =~ m/^(.*)::(.*)$/) {
5492                     $signal_object = $1;
5493                     ($signal_name = $2) =~ s/_/-/g;
5494                     #print "Found signal: $signal_name\n";
5495                 } else {
5496                     &LogWarning ($file, $., "Invalid signal name: $signal_name.");
5497                 }
5498             } elsif (m/^<RETURNS>(.*)<\/RETURNS>/) {
5499                 $signal_returns = $1;
5500             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5501                 $signal_flags = $1;
5502             } elsif (m%^</SIGNAL>%) {
5503                 #print "Found end of signal: ${signal_object}::${signal_name}\nReturns: ${signal_returns}\n${signal_prototype}";
5504                 push (@SignalObjects, $signal_object);
5505                 push (@SignalNames, $signal_name);
5506                 push (@SignalReturns, $signal_returns);
5507                 push (@SignalFlags, $signal_flags);
5508                 push (@SignalPrototypes, $signal_prototype);
5509                 $in_signal = 0;
5510             } else {
5511                 $signal_prototype .= $_;
5512             }
5513         }
5514     }
5515     close (INPUT);
5519 #############################################################################
5520 # Function    : ReadTemplateFile
5521 # Description : This reads in the manually-edited documentation file
5522 #               corresponding to the file currently being created, so we can
5523 #               insert the documentation at the appropriate places.
5524 #               It outputs %SymbolTypes, %SymbolDocs and %SymbolParams, which
5525 #               is a hash of arrays.
5526 #               NOTE: This function is duplicated in gtkdoc-mktmpl (but
5527 #               slightly different).
5528 # Arguments   : $docsfile - the template file to read in.
5529 #               $skip_unused_params - 1 if the unused parameters should be
5530 #                 skipped.
5531 #############################################################################
5533 sub ReadTemplateFile {
5534     my ($docsfile, $skip_unused_params) = @_;
5536     my $template = "$docsfile.sgml";
5537     if (! -f $template) {
5538         #print "File doesn't exist: $template\n";
5539         return 0;
5540     }
5542     # start with empty hashes, we merge the source comment for each file
5543     # afterwards
5544     %SymbolDocs = ();
5545     %SymbolTypes = ();
5546     %SymbolParams = ();
5548     my $current_type = "";        # Type of symbol being read.
5549     my $current_symbol = "";        # Name of symbol being read.
5550     my $symbol_doc = "";                # Description of symbol being read.
5551     my @params;                        # Parameter names and descriptions of current
5552                                 #   function/macro/function typedef.
5553     my $current_param = -1;        # Index of parameter currently being read.
5554                                 #   Note that the param array contains pairs
5555                                 #   of param name & description.
5556     my $in_unused_params = 0;        # True if we are reading in the unused params.
5557     my $in_deprecated = 0;
5558     my $in_since = 0;
5559     my $in_stability = 0;
5561     open (DOCS, "$template")
5562         || die "Can't open $template: $!";
5564     @TRACE@("reading template $template");
5566     while (<DOCS>) {
5567         if (m/^<!-- ##### ([A-Z_]+) (\S+) ##### -->/) {
5568             my $type = $1;
5569             my $symbol = $2;
5570             if ($symbol eq "Title"
5571                 || $symbol eq "Short_Description"
5572                 || $symbol eq "Long_Description"
5573                 || $symbol eq "See_Also"
5574                 || $symbol eq "Stability_Level"
5575                 || $symbol eq "Include"
5576                 || $symbol eq "Image") {
5578                 $symbol = $docsfile . ":" . $symbol;
5579             }
5581             #print "Found symbol: $symbol\n";
5582             # Remember file and line for the symbol
5583             $SymbolSourceFile{$symbol} = $template;
5584             $SymbolSourceLine{$symbol} = $.;
5586             # Store previous symbol, but remove any trailing blank lines.
5587             if ($current_symbol ne "") {
5588                 $symbol_doc =~ s/\s+$//;
5589                 $SymbolTypes{$current_symbol} = $current_type;
5590                 $SymbolDocs{$current_symbol} = $symbol_doc;
5592                 # Check that the stability level is valid.
5593                 if ($StabilityLevel{$current_symbol}) {
5594                     $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5595                 }
5597                 if ($current_param >= 0) {
5598                     $SymbolParams{$current_symbol} = [ @params ];
5599                 } else {
5600                     # Delete any existing params in case we are overriding a
5601                     # previously read template.
5602                     delete $SymbolParams{$current_symbol};
5603                 }
5604             }
5605             $current_type = $type;
5606             $current_symbol = $symbol;
5607             $current_param = -1;
5608             $in_unused_params = 0;
5609             $in_deprecated = 0;
5610             $in_since = 0;
5611             $in_stability = 0;
5612             $symbol_doc = "";
5613             @params = ();
5615         } elsif (m/^<!-- # Unused Parameters # -->/) {
5616             #print "DEBUG: Found unused parameters\n";
5617             $in_unused_params = 1;
5618             next;
5620         } elsif ($in_unused_params && $skip_unused_params) {
5621             # When outputting the DocBook we skip unused parameters.
5622             #print "DEBUG: Skipping unused param: $_";
5623             next;
5625         } else {
5626             # Check if param found. Need to handle "..." and "format...".
5627             if (s/^\@([\w\.]+):\040?//) {
5628                 my $param_name = $1;
5629                 my $param_desc = $_;
5630                 # Allow variations of 'Returns'
5631                 if ($param_name =~ m/^[Rr]eturns?$/) {
5632                     $param_name = "Returns";
5633                 }
5634                 # Allow varargs variations
5635                 if ($param_name =~ m/^.*\.\.\.$/) {
5636                     $param_name = "...";
5637                 }
5639                 # strip trailing whitespaces and blank lines
5640                 s/\s+\n$/\n/m;
5641                 s/\n+$/\n/sm;
5642                 @TRACE@("Found param for symbol $current_symbol : '$param_name'= '$_'");
5644                 if ($param_name eq "Deprecated") {
5645                     $in_deprecated = 1;
5646                     $Deprecated{$current_symbol} = $_;
5647                 } elsif ($param_name eq "Since") {
5648                     $in_since = 1;
5649                     chomp;
5650                     $Since{$current_symbol} = $_;
5651                 } elsif ($param_name eq "Stability") {
5652                     $in_stability = 1;
5653                     $StabilityLevel{$current_symbol} = $_;
5654                 } else {
5655                     push (@params, $param_name);
5656                     push (@params, $param_desc);
5657                     $current_param += $PARAM_FIELD_COUNT;
5658                 }
5659             } else {
5660                 # strip trailing whitespaces and blank lines
5661                 s/\s+\n$/\n/m;
5662                 s/\n+$/\n/sm;
5664                 if (!m/^\s+$/) {
5665                     if ($in_deprecated) {
5666                         $Deprecated{$current_symbol} .= $_;
5667                     } elsif ($in_since) {
5668                         &LogWarning ($template, $., "multi-line since docs found");
5669                         #$Since{$current_symbol} .= $_;
5670                     } elsif ($in_stability) {
5671                         $StabilityLevel{$current_symbol} .= $_;
5672                     } elsif ($current_param >= 0) {
5673                         $params[$current_param] .= $_;
5674                     } else {
5675                         $symbol_doc .= $_;
5676                     }
5677                 }
5678             }
5679         }
5680     }
5682     # Remember to finish the current symbol doccs.
5683     if ($current_symbol ne "") {
5685         $symbol_doc =~ s/\s+$//;
5686         $SymbolTypes{$current_symbol} = $current_type;
5687         $SymbolDocs{$current_symbol} = $symbol_doc;
5689         # Check that the stability level is valid.
5690         if ($StabilityLevel{$current_symbol}) {
5691             $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5692         }
5694         if ($current_param >= 0) {
5695             $SymbolParams{$current_symbol} = [ @params ];
5696         } else {
5697             # Delete any existing params in case we are overriding a
5698             # previously read template.
5699             delete $SymbolParams{$current_symbol};
5700         }
5701     }
5703     close (DOCS);
5704     return 1;
5708 #############################################################################
5709 # Function    : ReadObjectHierarchy
5710 # Description : This reads in the $MODULE-hierarchy.txt file containing all
5711 #                the GtkObject subclasses described in this module (and their
5712 #                ancestors).
5713 #                It places them in the @Objects array, and places their level
5714 #                in the object hierarchy in the @ObjectLevels array, at the
5715 #                same index. GtkObject, the root object, has a level of 1.
5717 #               FIXME: the version in gtkdoc-mkdb also generates tree_index.sgml
5718 #               as it goes along, this should be split out into a separate
5719 #               function.
5721 # Arguments   : none
5722 #############################################################################
5724 sub ReadObjectHierarchy {
5725     @Objects = ();
5726     @ObjectLevels = ();
5728     if (! -f $OBJECT_TREE_FILE) {
5729         return;
5730     }
5731     if (!open (INPUT, $OBJECT_TREE_FILE)) {
5732         warn "Can't open $OBJECT_TREE_FILE - skipping object tree\n";
5733         return;
5734     }
5736     # FIXME: use $OUTPUT_FORMAT
5737     # my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.$OUTPUT_FORMAT";
5738     my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.sgml";
5739     my $new_tree_index = "$SGML_OUTPUT_DIR/tree_index.new";
5741     open (OUTPUT, ">$new_tree_index")
5742         || die "Can't create $new_tree_index: $!";
5744     if ($OUTPUT_FORMAT eq "xml") {
5745         my $tree_header = $doctype_header;
5747         $tree_header =~ s/<!DOCTYPE \w+/<!DOCTYPE screen/;
5748         print (OUTPUT "$tree_header");
5749     }
5750     print (OUTPUT "<screen>\n");
5752     # Only emit objects if they are supposed to be documented, or if
5753     # they have documented children. To implement this, we maintain a
5754     # stack of pending objects which will be emitted if a documented
5755     # child turns up.
5756     my @pending_objects = ();
5757     my @pending_levels = ();
5758     my $root;
5759     while (<INPUT>) {
5760         if (m/\S+/) {
5761             my $object = $&;
5762             my $level = (length($`)) / 2 + 1;
5763             my $xref = "";
5765             if ($level == 1) {
5766                 $root = $object;
5767             }
5769             while (($#pending_levels >= 0) && ($pending_levels[$#pending_levels] >= $level)) {
5770                 my $pobject = pop(@pending_objects);
5771                 my $plevel = pop(@pending_levels);
5772             }
5774                push (@pending_objects, $object);
5775             push (@pending_levels, $level);
5777             if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
5778                    while ($#pending_levels >= 0) {
5779                     $object = shift @pending_objects;
5780                     $level = shift @pending_levels;
5781                        $xref = &MakeXRef ($object);
5783                      print (OUTPUT ' ' x ($level * 4), "$xref\n");
5784                     push (@Objects, $object);
5785                     push (@ObjectLevels, $level);
5786                     $ObjectRoots{$object} = $root;
5787                 }
5788             }
5789             #else {
5790             #    LogWarning ($OBJECT_TREE_FILE, $., "unknown type $object");
5791             #}
5792         }
5793     }
5794     print (OUTPUT "</screen>\n");
5796     close (INPUT);
5797     close (OUTPUT);
5799     &UpdateFileIfChanged ($old_tree_index, $new_tree_index, 0);
5801     &OutputObjectList;
5804 #############################################################################
5805 # Function    : ReadInterfaces
5806 # Description : This reads in the $MODULE.interfaces file.
5808 # Arguments   : none
5809 #############################################################################
5811 sub ReadInterfaces {
5812     %Interfaces = ();
5814     if (! -f $INTERFACES_FILE) {
5815         return;
5816     }
5817     if (!open (INPUT, $INTERFACES_FILE)) {
5818         warn "Can't open $INTERFACES_FILE - skipping interfaces\n";
5819         return;
5820     }
5822     while (<INPUT>) {
5823        chomp;
5824        my ($object, @ifaces) = split;
5825        if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
5826            my @knownIfaces = ();
5828            # filter out private interfaces, but leave foreign interfaces
5829            foreach my $iface (@ifaces) {
5830                if (!exists($KnownSymbols{$iface}) || $KnownSymbols{$iface} == 1) {
5831                    push (@knownIfaces, $iface);
5832                }
5833              }
5835            $Interfaces{$object} = join(' ', @knownIfaces);
5836        }
5837     }
5838     close (INPUT);
5841 #############################################################################
5842 # Function    : ReadPrerequisites
5843 # Description : This reads in the $MODULE.prerequisites file.
5845 # Arguments   : none
5846 #############################################################################
5848 sub ReadPrerequisites {
5849     %Prerequisites = ();
5851     if (! -f $PREREQUISITES_FILE) {
5852         return;
5853     }
5854     if (!open (INPUT, $PREREQUISITES_FILE)) {
5855         warn "Can't open $PREREQUISITES_FILE - skipping prerequisites\n";
5856         return;
5857     }
5859     while (<INPUT>) {
5860        chomp;
5861        my ($iface, @prereqs) = split;
5862        if (exists($KnownSymbols{$iface}) && $KnownSymbols{$iface} == 1) {
5863            my @knownPrereqs = ();
5865            # filter out private prerequisites, but leave foreign prerequisites
5866            foreach my $prereq (@prereqs) {
5867                if (!exists($KnownSymbols{$prereq}) || $KnownSymbols{$prereq} == 1) {
5868                   push (@knownPrereqs, $prereq);
5869                }
5870            }
5872            $Prerequisites{$iface} = join(' ', @knownPrereqs);
5873        }
5874     }
5875     close (INPUT);
5878 #############################################################################
5879 # Function    : ReadArgsFile
5880 # Description : This reads in an existing file which contains information on
5881 #                all GTK args. It creates the arrays @ArgObjects, @ArgNames,
5882 #                @ArgTypes, @ArgFlags, @ArgNicks and @ArgBlurbs containing info
5883 #               on the args.
5884 # Arguments   : $file - the file containing the arg information.
5885 #############################################################################
5887 sub ReadArgsFile {
5888     my ($file) = @_;
5890     my $in_arg = 0;
5891     my $arg_object;
5892     my $arg_name;
5893     my $arg_type;
5894     my $arg_flags;
5895     my $arg_nick;
5896     my $arg_blurb;
5897     my $arg_default;
5898     my $arg_range;
5900     # Reset the args info.
5901     @ArgObjects = ();
5902     @ArgNames = ();
5903     @ArgTypes = ();
5904     @ArgFlags = ();
5905     @ArgNicks = ();
5906     @ArgBlurbs = ();
5907     @ArgDefaults = ();
5908     @ArgRanges = ();
5910     if (! -f $file) {
5911         return;
5912     }
5913     if (!open (INPUT, $file)) {
5914         warn "Can't open $file - skipping args\n";
5915         return;
5916     }
5917     while (<INPUT>) {
5918         if (!$in_arg) {
5919             if (m/^<ARG>/) {
5920                 $in_arg = 1;
5921                 $arg_object = "";
5922                 $arg_name = "";
5923                 $arg_type = "";
5924                 $arg_flags = "";
5925                 $arg_nick = "";
5926                 $arg_blurb = "";
5927                 $arg_default = "";
5928                 $arg_range = "";
5929             }
5930         } else {
5931             if (m/^<NAME>(.*)<\/NAME>/) {
5932                 $arg_name = $1;
5933                 if ($arg_name =~ m/^(.*)::(.*)$/) {
5934                     $arg_object = $1;
5935                     ($arg_name = $2) =~ s/_/-/g;
5936                     #print "Found arg: $arg_name\n";
5937                 } else {
5938                     &LogWarning ($file, $., "Invalid argument name: $arg_name");
5939                 }
5940             } elsif (m/^<TYPE>(.*)<\/TYPE>/) {
5941                 $arg_type = $1;
5942             } elsif (m/^<RANGE>(.*)<\/RANGE>/) {
5943                 $arg_range = $1;
5944             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5945                 $arg_flags = $1;
5946             } elsif (m/^<NICK>(.*)<\/NICK>/) {
5947                 $arg_nick = $1;
5948             } elsif (m/^<BLURB>(.*)<\/BLURB>/) {
5949                 $arg_blurb = $1;
5950                 if ($arg_blurb eq "(null)") {
5951                   $arg_blurb = "";
5952                   &LogWarning ($file, $., "Property ${arg_object}:${arg_name} has no documentation.");
5953                 }
5954             } elsif (m/^<DEFAULT>(.*)<\/DEFAULT>/) {
5955                 $arg_default = $1;
5956             } elsif (m%^</ARG>%) {
5957                 #print "Found end of arg: ${arg_object}::${arg_name}\n${arg_type} : ${arg_flags}\n";
5958                 push (@ArgObjects, $arg_object);
5959                 push (@ArgNames, $arg_name);
5960                 push (@ArgTypes, $arg_type);
5961                 push (@ArgRanges, $arg_range);
5962                 push (@ArgFlags, $arg_flags);
5963                 push (@ArgNicks, $arg_nick);
5964                 push (@ArgBlurbs, $arg_blurb);
5965                 push (@ArgDefaults, $arg_default);
5966                 $in_arg = 0;
5967             }
5968         }
5969     }
5970     close (INPUT);
5974 #############################################################################
5975 # Function    : CheckIsObject
5976 # Description : Returns 1 if the given name is a GObject or a subclass.
5977 #                It uses the global @Objects array.
5978 #                Note that the @Objects array only contains classes in the
5979 #                current module and their ancestors - not all GObject classes.
5980 # Arguments   : $name - the name to check.
5981 #############################################################################
5983 sub CheckIsObject {
5984     my ($name) = @_;
5985     my $root = $ObjectRoots{$name};
5986     # Let GBoxed pass as an object here to get -struct appended to the id
5987     # and prevent conflicts with sections.
5988     return (defined($root) and $root ne 'GEnum' and $root ne 'GFlags');
5992 #############################################################################
5993 # Function    : MakeReturnField
5994 # Description : Pads a string to $RETURN_TYPE_FIELD_WIDTH.
5995 # Arguments   : $str - the string to pad.
5996 #############################################################################
5998 sub MakeReturnField {
5999     my ($str) = @_;
6001     return $str . (' ' x ($RETURN_TYPE_FIELD_WIDTH - length ($str)));
6004 #############################################################################
6005 # Function    : GetSymbolSourceFile
6006 # Description : Get the filename where the symbol docs where taken from.
6007 # Arguments   : $symbol - the symbol name
6008 #############################################################################
6010 sub GetSymbolSourceFile {
6011     my ($symbol) = @_;
6013     if (defined($SourceSymbolSourceFile{$symbol})) {
6014         return $SourceSymbolSourceFile{$symbol};
6015     } elsif (defined($SymbolSourceFile{$symbol})) {
6016         return $SymbolSourceFile{$symbol};
6017     } else {
6018         return "";
6019     }
6022 #############################################################################
6023 # Function    : GetSymbolSourceLine
6024 # Description : Get the file line where the symbol docs where taken from.
6025 # Arguments   : $symbol - the symbol name
6026 #############################################################################
6028 sub GetSymbolSourceLine {
6029     my ($symbol) = @_;
6031     if (defined($SourceSymbolSourceLine{$symbol})) {
6032         return $SourceSymbolSourceLine{$symbol};
6033     } elsif (defined($SymbolSourceLine{$symbol})) {
6034         return $SymbolSourceLine{$symbol};
6035     } else {
6036         return 0;
6037     }