parsing: have simillar support for unions like we have for structs
[gtk-doc.git] / gtkdoc-mkdb.in
blob5cc6f62e1714e77c870379a71f99969b11f7adfc
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 strict;
29 use Getopt::Long;
31 push @INC, '@PACKAGE_DATA_DIR@';
32 require "gtkdoc-common.pl";
34 # Options
36 # name of documentation module
37 my $MODULE;
38 my $TMPL_DIR;
39 my $SGML_OUTPUT_DIR;
40 my @SOURCE_DIRS;
41 my $SOURCE_SUFFIXES = "";
42 my $IGNORE_FILES = "";
43 my $PRINT_VERSION;
44 my $PRINT_HELP;
45 my $MAIN_SGML_FILE;
46 my $EXPAND_CONTENT_FILES = "";
47 my $SGML_MODE;
48 my $DEFAULT_STABILITY;
49 my $DEFAULT_INCLUDES;
50 my $OUTPUT_FORMAT;
51 my $NAME_SPACE = "";
52 my $OUTPUT_ALL_SYMBOLS;
53 my $OUTPUT_SYMBOLS_WITHOUT_SINCE;
55 my %optctl = ('module' => \$MODULE,
56               'source-dir' => \@SOURCE_DIRS,
57               'source-suffixes' => \$SOURCE_SUFFIXES,
58               'ignore-files' => \$IGNORE_FILES,
59               'output-dir' => \$SGML_OUTPUT_DIR,
60               'tmpl-dir' => \$TMPL_DIR,
61               'version' => \$PRINT_VERSION,
62               'help' => \$PRINT_HELP,
63               'main-sgml-file' => \$MAIN_SGML_FILE,
64               'expand-content-files' => \$EXPAND_CONTENT_FILES,
65               'sgml-mode' => \$SGML_MODE,
66               'default-stability' => \$DEFAULT_STABILITY,
67               'default-includes' => \$DEFAULT_INCLUDES,
68               'output-format' => \$OUTPUT_FORMAT,
69               'name-space' => \$NAME_SPACE,
70               'outputallsymbols' => \$OUTPUT_ALL_SYMBOLS,
71               'outputsymbolswithoutsince' => \$OUTPUT_SYMBOLS_WITHOUT_SINCE
72               );
73 GetOptions(\%optctl, "module=s", "source-dir:s", "source-suffixes:s", 
74     "ignore-files:s", "output-dir:s", "tmpl-dir:s", "version", "outputallsymbols",
75     "outputsymbolswithoutsince",
76     "expand-content-files:s", "main-sgml-file:s", "extra-db-files:s", "help",
77     "sgml-mode", "default-stability:s", "default-includes:s", "output-format:s",
78     "name-space:s");
80 if ($PRINT_VERSION) {
81     print "@VERSION@\n";
82     exit 0;
85 if (!$MODULE) {
86     $PRINT_HELP = 1;
89 if ($DEFAULT_STABILITY && $DEFAULT_STABILITY ne "Stable"
90     && $DEFAULT_STABILITY ne "Private" && $DEFAULT_STABILITY ne "Unstable") {
91     $PRINT_HELP = 1;
94 if ($PRINT_HELP) {
95     print <<EOF;
96 gtkdoc-mkdb version @VERSION@ - generate docbook files
98 --module=MODULE_NAME       Name of the doc module being parsed
99 --source-dir=DIRNAME       Directories which contain inline reference material
100 --source-suffixes=SUFFIXES Suffixes of source files to scan, comma-separated
101 --ignore-files=FILES       Files or directories which should not be scanned
102                            May be used more than once for multiple directories
103 --output-dir=DIRNAME       Directory to put the generated DocBook files in
104 --tmpl-dir=DIRNAME         Directory in which template files may be found
105 --main-sgml-file=FILE      File containing the toplevel DocBook file.
106 --expand-content-files=FILES Extra DocBook files to expand abbreviations in.
107 --output-format=FORMAT     Format to use for the generated docbook, XML or SGML.
108 --sgml-mode                Allow DocBook markup in inline documentation.
109 --default-stability=LEVEL  Specify default stability Level. Valid values are
110                            Stable, Unstable, or Private.
111 --default-includes=FILENAMES Specify default includes for section Synopsis
112 --name-space=NS            Omit namespace in index.
113 --version                  Print the version of this program
114 --help                     Print this help
116     exit 0;
119 my ($empty_element_end, $doctype_header);
121 if (lc($OUTPUT_FORMAT) eq "xml") {
122     if (!$MAIN_SGML_FILE) {
123         # backwards compatibility
124         if (-e "${MODULE}-docs.sgml") {
125             $MAIN_SGML_FILE="${MODULE}-docs.sgml";
126         } else {
127             $MAIN_SGML_FILE="${MODULE}-docs.xml";
128         }
129     }
130     $OUTPUT_FORMAT = "xml";
131     $empty_element_end = "/>";
133     if (-e $MAIN_SGML_FILE) {
134         open(INPUT, "<$MAIN_SGML_FILE") || die "Can't open $MAIN_SGML_FILE";
135         $doctype_header = "";
136         while (<INPUT>) {
137             if (/^\s*<(book|chapter|article)/) {
138                 if ($_ !~ m/http:\/\/www.w3.org\/200[13]\/XInclude/) {
139                     $doctype_header = "";
140                 }
141                 last;
142             }
143             $doctype_header .= $_;
144         }
145         close(INPUT);
146     } else {
147         $doctype_header =
148 "<?xml version=\"1.0\"?>\n" .
149 "<!DOCTYPE book PUBLIC \"-//OASIS//DTD DocBook XML V4.3//EN\"\n" .
150 "               \"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd\">\n";
151     }
152     $doctype_header =~ s/<!DOCTYPE \w+/<!DOCTYPE refentry/;
153 } else {
154     if (!$MAIN_SGML_FILE) {
155         $MAIN_SGML_FILE="${MODULE}-docs.sgml";
156     }
157     $OUTPUT_FORMAT = "sgml";
158     $doctype_header = "";
159     $empty_element_end = ">";
162 my $ROOT_DIR = ".";
164 # All the files are written in subdirectories beneath here.
165 $TMPL_DIR = $TMPL_DIR ? $TMPL_DIR : "$ROOT_DIR/tmpl";
167 # This is where we put all the DocBook output.
168 $SGML_OUTPUT_DIR = $SGML_OUTPUT_DIR ? $SGML_OUTPUT_DIR : "$ROOT_DIR/$OUTPUT_FORMAT";
170 # This file contains the object hierarchy.
171 my $OBJECT_TREE_FILE = "$ROOT_DIR/$MODULE.hierarchy";
173 # This file contains the interfaces.
174 my $INTERFACES_FILE = "$ROOT_DIR/$MODULE.interfaces";
176 # This file contains the prerequisites.
177 my $PREREQUISITES_FILE = "$ROOT_DIR/$MODULE.prerequisites";
179 # This file contains signal arguments and names.
180 my $SIGNALS_FILE = "$ROOT_DIR/$MODULE.signals";
182 # The file containing Arg information.
183 my $ARGS_FILE = "$ROOT_DIR/$MODULE.args";
185 # These global arrays store information on signals. Each signal has an entry
186 # in each of these arrays at the same index, like a multi-dimensional array.
187 my @SignalObjects;      # The GtkObject which emits the signal.
188 my @SignalNames;        # The signal name.
189 my @SignalReturns;      # The return type.
190 my @SignalFlags;        # Flags for the signal
191 my @SignalPrototypes;   # The rest of the prototype of the signal handler.
193 # These global arrays store information on Args. Each Arg has an entry
194 # in each of these arrays at the same index, like a multi-dimensional array.
195 my @ArgObjects;         # The GtkObject which has the Arg.
196 my @ArgNames;           # The Arg name.
197 my @ArgTypes;           # The Arg type - gint, GtkArrowType etc.
198 my @ArgFlags;           # How the Arg can be used - readable/writable etc.
199 my @ArgNicks;           # The nickname of the Arg.
200 my @ArgBlurbs;          # Docstring of the Arg.
201 my @ArgDefaults;        # Default value of the Arg.
202 my @ArgRanges;          # The range of the Arg type
203 # These global hashes store declaration info keyed on a symbol name.
204 my %Declarations;
205 my %DeclarationTypes;
206 my %DeclarationConditional;
207 my %DeclarationOutput;
208 my %Deprecated;
209 my %Since;
210 my %StabilityLevel;
211 my %StructHasTypedef;
213 # These global hashes store the existing documentation.
214 my %SymbolDocs;
215 my %SymbolTypes;
216 my %SymbolParams;
217 my %SymbolSourceFile;
218 my %SymbolSourceLine;
220 # These global hashes store documentation scanned from the source files.
221 my %SourceSymbolDocs;
222 my %SourceSymbolParams;
223 my %SourceSymbolSourceFile;
224 my %SourceSymbolSourceLine;
226 # all documentation goes in here, so we can do coverage analysis
227 my %AllSymbols;
228 my %AllIncompleteSymbols;
229 my %AllDocumentedSymbols;
231 # Undeclared yet documented symbols
232 my %UndeclaredSymbols;
234 # These global arrays store GObject, subclasses and the hierarchy.
235 my @Objects;
236 my @ObjectLevels;
238 my %Interfaces;
239 my %Prerequisites;
241 # holds the symbols which are mentioned in $MODULE-sections.txt and in which
242 # section they are defined
243 my %KnownSymbols;
244 my %SymbolSection;
246 # collects index entries
247 my %IndexEntriesFull;
248 my %IndexEntriesSince;
249 my %IndexEntriesDeprecated;
251 # Standard C preprocessor directives, which we ignore for '#' abbreviations.
252 my %PreProcessorDirectives;
253 $PreProcessorDirectives{"assert"} = 1;
254 $PreProcessorDirectives{"define"} = 1;
255 $PreProcessorDirectives{"elif"} = 1;
256 $PreProcessorDirectives{"else"} = 1;
257 $PreProcessorDirectives{"endif"} = 1;
258 $PreProcessorDirectives{"error"} = 1;
259 $PreProcessorDirectives{"if"} = 1;
260 $PreProcessorDirectives{"ifdef"} = 1;
261 $PreProcessorDirectives{"ifndef"} = 1;
262 $PreProcessorDirectives{"include"} = 1;
263 $PreProcessorDirectives{"line"} = 1;
264 $PreProcessorDirectives{"pragma"} = 1;
265 $PreProcessorDirectives{"unassert"} = 1;
266 $PreProcessorDirectives{"undef"} = 1;
267 $PreProcessorDirectives{"warning"} = 1;
269 # remember used annotation (to write minimal glossary)
270 my %AnnotationsUsed;
272 my %AnnotationDefinition = (
273     'allow-none' => "NULL is ok, both for passing and for returning.",
274     'array' => "Parameter points to an array of items.",
275     'default' => "Default parameter value (for in case the <acronym>shadows</acronym>-to function has less parameters).",
276     'element-type' => "Generics and defining elements of containers and arrays.",
277     'error-domains' => "Typed errors. Similar to throws in Java.",
278     'in' => "Parameter for input. Default is <acronym>transfer none</acronym>.",
279     'inout' => "Parameter for input and for returning results. Default is <acronym>transfer full</acronym>.",
280     'in-out' => "Parameter for input and for returning results. Default is <acronym>transfer full</acronym>.",
281     'not-error' => "A GError parameter is not to be handled like a normal GError.",
282     'out' => "Parameter for returning results. Default is <acronym>transfer full</acronym>.",
283     'transfer container' => "Free data container after the code is done.",
284     'transfer full' => "Free data after the code is done.",
285     'transfer none' => "Don't free data after the code is done."
288 # Create the root DocBook output directory if it doens't exist.
289 if (! -e $SGML_OUTPUT_DIR) {
290     mkdir ("$SGML_OUTPUT_DIR", 0777)
291         || die "Can't create directory: $SGML_OUTPUT_DIR";
294 # Function and other declaration output settings.
295 my $RETURN_TYPE_FIELD_WIDTH = 20;
296 my $SYMBOL_FIELD_WIDTH = 36;
297 my $SIGNAL_FIELD_WIDTH = 16;
298 my $PARAM_FIELD_COUNT = 2;
300 &ReadKnownSymbols ("$ROOT_DIR/$MODULE-sections.txt");
301 &ReadSignalsFile ($SIGNALS_FILE);
302 &ReadArgsFile ($ARGS_FILE);
303 &ReadObjectHierarchy;
304 &ReadInterfaces;
305 &ReadPrerequisites;
307 &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-decl.txt", 0);
308 if (-f "$ROOT_DIR/$MODULE-overrides.txt") {
309     &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-overrides.txt", 1);
312 for my $dir (@SOURCE_DIRS) {
313     &ReadSourceDocumentation ($dir);
316 my $changed = &OutputSGML ("$ROOT_DIR/$MODULE-sections.txt");
318 # If any of the DocBook SGML files have changed, update the timestamp file (so
319 # it can be used for Makefile dependencies).
320 if ($changed || ! -e "$ROOT_DIR/sgml.stamp") {
322     # try to detect the common prefix
323     # GtkWidget, GTK_WIDGET, gtk_widget -> gtk
324     if ($NAME_SPACE eq "") {
325         $NAME_SPACE="";
326         my $pos=0;
327         my $ratio=0.0;
328         do {
329             my %prefix;
330             my $letter="";
331             foreach my $symbol (keys(%IndexEntriesFull)) {
332                 if(($NAME_SPACE eq "") || $symbol =~ /^$NAME_SPACE/i) {
333                     if (length($symbol)>$pos) {
334                         $letter=substr($symbol,$pos,1);
335                         # stop prefix scanning
336                         if ($letter eq "_") {
337                             # stop on "_"
338                             last;
339                         }
340                         # Should we also stop on a uppercase char, if last was lowercase
341                         #   GtkWidget, if we have the 'W' and had the 't' before
342                         # or should we count upper and lowercase, and stop one 2nd uppercase, if we already had a lowercase
343                         #   GtkWidget, the 'W' would be the 2nd uppercase and with 't','k' we had lowercase chars before
344                         # need to recound each time as this is per symbol
345                         $prefix{uc($letter)}++;
346                     }
347                 }
348             }
349             if ($letter ne "" && $letter ne "_") {
350                 my $maxletter="";
351                 my $maxsymbols=0;
352                 foreach $letter (keys(%prefix)) {
353                     #print "$letter: $prefix{$letter}.\n";
354                     if ($prefix{$letter}>$maxsymbols) {
355                         $maxletter=$letter;
356                         $maxsymbols=$prefix{$letter};
357                     }
358                 }
359                 $ratio = scalar(keys(%IndexEntriesFull)) / $prefix{$maxletter};
360                 #print "most symbols start with $maxletter, that is ". (100 * $ratio) ." %\n";
361                 if ($ratio > 0.9) {
362                     # do another round
363                     $NAME_SPACE .= $maxletter;
364                 }
365                 $pos++;
366             }
367             else {
368                 $ratio=0.0;
369             }
370         } while ($ratio > 0.9);
371         #print "most symbols start with $NAME_SPACE\n";
372     }
374     &OutputIndexFull;
375     &OutputDeprecatedIndex;
376     &OutputSinceIndexes;
377     &OutputAnnotationGlossary;
379     open (TIMESTAMP, ">$ROOT_DIR/sgml.stamp")
380         || die "Can't create $ROOT_DIR/sgml.stamp: $!";
381     print (TIMESTAMP "timestamp");
382     close (TIMESTAMP);
385 #############################################################################
386 # Function    : OutputObjectList
387 # Description : This outputs the alphabetical list of objects, in a columned
388 #               table.
389 #               FIXME: Currently this also outputs ancestor objects
390 #               which may not actually be in this module.
391 # Arguments   : none
392 #############################################################################
394 sub OutputObjectList {
395     my $cols = 3;
396     
397     # FIXME: use $OUTPUT_FORMAT
398     # my $old_object_index = "$SGML_OUTPUT_DIR/object_index.$OUTPUT_FORMAT";
399     my $old_object_index = "$SGML_OUTPUT_DIR/object_index.sgml";
400     my $new_object_index = "$SGML_OUTPUT_DIR/object_index.new";
402     open (OUTPUT, ">$new_object_index")
403         || die "Can't create $new_object_index: $!";
405     if (lc($OUTPUT_FORMAT) eq "xml") {
406         my $header = $doctype_header;
408         $header =~ s/<!DOCTYPE \w+/<!DOCTYPE informaltable/;
409         print (OUTPUT "$header");
410     }
412     print (OUTPUT <<EOF);
413 <informaltable pgwide="1" frame="none">
414 <tgroup cols="$cols">
415 <colspec colwidth="1*"${empty_element_end}
416 <colspec colwidth="1*"${empty_element_end}
417 <colspec colwidth="1*"${empty_element_end}
418 <tbody>
421     my $count = 0;
422     my $object;
423     foreach $object (sort (@Objects)) {
424         my $xref = &MakeXRef ($object);
425         if ($count % $cols == 0) { print (OUTPUT "<row>\n"); }
426         print (OUTPUT "<entry>$xref</entry>\n");
427         if ($count % $cols == ($cols - 1)) { print (OUTPUT "</row>\n"); }
428         $count++;
429     }
430     if ($count == 0) {
431         # emit an empty row, since empty tables are invalid
432         print (OUTPUT "<row><entry> </entry></row>\n");
433     }
434     else {
435         print (OUTPUT "</row>\n");
436     }
438     print (OUTPUT <<EOF);
439 </tbody></tgroup></informaltable>
441     close (OUTPUT);
443     &UpdateFileIfChanged ($old_object_index, $new_object_index, 0);
447 #############################################################################
448 # Function    : OutputSGML
449 # Description : This collects the output for each section of the docs, and
450 #               outputs each file when the end of the section is found.
451 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
452 #               the functions/macros/structs etc. being documented, organised
453 #               into sections and subsections.
454 #############################################################################
456 sub OutputSGML {
457     my ($file) = @_;
459     #print "Reading: $file\n";
460     open (INPUT, $file)
461         || die "Can't open $file: $!";
462     my $filename = "";
463     my $book_top = "";
464     my $book_bottom = "";
465     my $includes = (defined $DEFAULT_INCLUDES) ? $DEFAULT_INCLUDES : "";
466     my $section_includes = "";
467     my $in_section = 0;
468     my $title = "";
469     my $subsection = "";
470     my $synopsis;
471     my $details;
472     my $num_symbols;
473     my $changed = 0;
474     my $signals_synop = "";
475     my $signals_desc = "";
476     my $args_synop = "";
477     my $child_args_synop = "";
478     my $style_args_synop = "";
479     my $args_desc = "";
480     my $child_args_desc = "";
481     my $style_args_desc = "";
482     my $hierarchy = "";
483     my $interfaces = "";
484     my $implementations = "";
485     my $prerequisites = "";
486     my $derived = "";
487     my @file_objects = ();
488     my %templates = ();
489     my %symbol_def_line = ();
491     # merge the source docs, in case there are no templates
492     &MergeSourceDocumentation;
494     while (<INPUT>) {
495         if (m/^#/) {
496             next;
498         } elsif (m/^<SECTION>/) {
499             $synopsis = "";
500             $details = "";
501             $num_symbols = 0;
502             $in_section = 1;
503             @file_objects = ();
504             %symbol_def_line = ();
506         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
507             $synopsis .= "\n";
508             $subsection = $1;
510         } elsif (m/^<SUBSECTION>/) {
512         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
513             $title = $1;
514             #print "Section: $title\n";
516             # We don't want warnings if object & class structs aren't used.
517             $DeclarationOutput{$title} = 1;
518             $DeclarationOutput{"${title}Class"} = 1;
519             $DeclarationOutput{"${title}Iface"} = 1;
520             $DeclarationOutput{"${title}Interface"} = 1;
522         } elsif (m/^<FILE>(.*)<\/FILE>/) {
523             $filename = $1;
524             if (! defined $templates{$filename}) {
525                if (&ReadTemplateFile ("$TMPL_DIR/$filename", 1)) {
526                    &MergeSourceDocumentation;
527                    $templates{$filename}=$.;
528                }
529             } else {
530                 &LogWarning ($file, $., "Double <FILE>$filename</FILE> entry. ".
531                     "Previous occurrence on line ".$templates{$filename}.".");
532             }
533             if (($title eq "") and (defined $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"})) {
534                 $title = $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"};
535                 # Remove trailing blanks
536                 $title =~ s/\s+$//;
537            }
539         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
540             if ($in_section) {
541                 $section_includes = $1;
542             } else {
543                 if (defined $DEFAULT_INCLUDES) {
544                     &LogWarning ($file, $., "Default <INCLUDE> being overridden by command line option.");
545                 }
546                 else {
547                     $includes = $1;
548                 }
549             }
551         } elsif (m/^<\/SECTION>/) {
552             if($title eq "" && $filename eq "") {
553                 &LogWarning ($file, $., "Section has no title and no file.");
554             }
555             # FIXME: one of those would be enough
556             if ($title eq "") {
557                 $title = $filename;
558             }
559             if ($filename eq "") {
560                 $filename = $title;
561             }
562             #print "End of section: $title\n";
564             $filename =~ s/\s/_/g;
566             my $section_id = $SourceSymbolDocs{"$TMPL_DIR/$filename:Section_Id"};
567             if (defined ($section_id) && $section_id !~ m/^\s*$/) {
568                 # Remove trailing blanks and use as is
569                 $section_id =~ s/\s+$//;
570             } elsif (&CheckIsObject ($title)) {
571                 # GtkObjects use their class name as the ID.
572                 $section_id = &CreateValidSGMLID ($title);
573             } else {
574                 $section_id = &CreateValidSGMLID ("$MODULE-$title");
575             }
577             if ($num_symbols > 0) {
578                 # collect documents
579                 if (lc($OUTPUT_FORMAT) eq "xml") {
580                     $book_bottom .= "    <xi:include href=\"xml/$filename.xml\"/>\n";
581                 } else {
582                     $book_top.="<!ENTITY $section_id SYSTEM \"sgml/$filename.sgml\">\n";
583                     $book_bottom .= "    &$section_id;\n";
584                 }
586                 if (defined ($SourceSymbolDocs{"$TMPL_DIR/$filename:Include"})) {
587                     if ($section_includes) {
588                         &LogWarning ($file, $., "Section <INCLUDE> being overridden by inline comments.");
589                     }
590                     $section_includes = $SourceSymbolDocs{"$TMPL_DIR/$filename:Include"};
591                 }
592                 if ($section_includes eq "") {
593                     $section_includes = $includes;
594                 }
596                  $signals_synop =~ s/^\n*//g;
597                  $signals_synop =~ s/\n+$/\n/g;
598                 if ($signals_synop ne '') {
599                     $signals_synop = <<EOF;
600 <refsect1 id="$section_id.signals" role="signal_proto">
601 <title role="signal_proto.title">Signals</title>
602 <synopsis>
603 ${signals_synop}</synopsis>
604 </refsect1>
606                      $signals_desc =~ s/^\n*//g;
607                      $signals_desc =~ s/\n+$/\n/g;
608                      $signals_desc =~ s/(\s|\n)+$//ms;
609                     $signals_desc  = <<EOF;
610 <refsect1 id="$section_id.signal-details" role="signals">
611 <title role="signals.title">Signal Details</title>
612 $signals_desc
613 </refsect1>
615                 }
617                  $args_synop =~ s/^\n*//g;
618                  $args_synop =~ s/\n+$/\n/g;
619                 if ($args_synop ne '') {
620                     $args_synop = <<EOF;
621 <refsect1 id="$section_id.properties" role="properties">
622 <title role="properties.title">Properties</title>
623 <synopsis>
624 ${args_synop}</synopsis>
625 </refsect1>
627                      $args_desc =~ s/^\n*//g;
628                      $args_desc =~ s/\n+$/\n/g;
629                      $args_desc =~ s/(\s|\n)+$//ms;
630                     $args_desc  = <<EOF;
631 <refsect1 id="$section_id.property-details" role="property_details">
632 <title role="property_details.title">Property Details</title>
633 $args_desc
634 </refsect1>
636                 }
638                  $child_args_synop =~ s/^\n*//g;
639                  $child_args_synop =~ s/\n+$/\n/g;
640                 if ($child_args_synop ne '') {
641                     $args_synop .= <<EOF;
642 <refsect1 id="$section_id.child-properties" role="child_properties">
643 <title role="child_properties.title">Child Properties</title>
644 <synopsis>
645 ${child_args_synop}</synopsis>
646 </refsect1>
648                      $child_args_desc =~ s/^\n*//g;
649                      $child_args_desc =~ s/\n+$/\n/g;
650                      $child_args_desc =~ s/(\s|\n)+$//ms;
651                     $args_desc .= <<EOF;
652 <refsect1 id="$section_id.child-property-details" role="child_property_details">
653 <title role="child_property_details.title">Child Property Details</title>
654 $child_args_desc
655 </refsect1>
657                 }
659                  $style_args_synop =~ s/^\n*//g;
660                  $style_args_synop =~ s/\n+$/\n/g;
661                 if ($style_args_synop ne '') {
662                     $args_synop .= <<EOF;
663 <refsect1 id="$section_id.style-properties" role="style_properties">
664 <title role="style_properties.title">Style Properties</title>
665 <synopsis>
666 ${style_args_synop}</synopsis>
667 </refsect1>
669                      $style_args_desc =~ s/^\n*//g;
670                      $style_args_desc =~ s/\n+$/\n/g;
671                      $style_args_desc =~ s/(\s|\n)+$//ms;
672                     $args_desc .= <<EOF;
673 <refsect1 id="$section_id.style-property-details" role="style_properties_details">
674 <title role="style_properties_details.title">Style Property Details</title>
675 $style_args_desc
676 </refsect1>
678                 }
680                  $hierarchy =~ s/^\n*//g;
681                  $hierarchy =~ s/\n+$/\n/g;
682                  $hierarchy =~ s/(\s|\n)+$//ms;
683                 if ($hierarchy ne "") {
684                     $hierarchy = <<EOF;
685 <refsect1 id="$section_id.object-hierarchy" role="object_hierarchy">
686 <title role="object_hierarchy.title">Object Hierarchy</title>
687 $hierarchy
688 </refsect1>
690                 }
692                  $interfaces =~ s/^\n*//g;
693                  $interfaces =~ s/\n+$/\n/g;
694                  $interfaces =~ s/(\s|\n)+$//ms;
695                 if ($interfaces ne "") {
696                     $interfaces = <<EOF;
697 <refsect1 id="$section_id.implemented-interfaces" role="impl_interfaces">
698 <title role="impl_interfaces.title">Implemented Interfaces</title>
699 $interfaces
700 </refsect1>
702                 }
704                  $implementations =~ s/^\n*//g;
705                  $implementations =~ s/\n+$/\n/g;
706                  $implementations =~ s/(\s|\n)+$//ms;
707                 if ($implementations ne "") {
708                     $implementations = <<EOF;
709 <refsect1 id="$section_id.implementations" role="implementations">
710 <title role="implementations.title">Known Implementations</title>
711 $implementations
712 </refsect1>
714                 }
716                  $prerequisites =~ s/^\n*//g;
717                  $prerequisites =~ s/\n+$/\n/g;
718                  $prerequisites =~ s/(\s|\n)+$//ms;
719                 if ($prerequisites ne "") {
720                     $prerequisites = <<EOF;
721 <refsect1 id="$section_id.prerequisites" role="prerequisites">
722 <title role="prerequisites.title">Prerequisites</title>
723 $prerequisites
724 </refsect1>
726                 }
728                  $derived =~ s/^\n*//g;
729                  $derived =~ s/\n+$/\n/g;
730                  $derived =~ s/(\s|\n)+$//ms;
731                 if ($derived ne "") {
732                     $derived = <<EOF;
733 <refsect1 id="$section_id.derived-interfaces" role="derived_interfaces">
734 <title role="derived_interfaces.title">Known Derived Interfaces</title>
735 $derived
736 </refsect1>
738                 }
740                 $synopsis =~ s/^\n*//g;
741                 $synopsis =~ s/\n+$/\n/g;
742                 my $file_changed = &OutputSGMLFile ($filename, $title, $section_id,
743                                                     $section_includes,
744                                                     \$synopsis, \$details,
745                                                     \$signals_synop, \$signals_desc,
746                                                     \$args_synop, \$args_desc,
747                                                     \$hierarchy, \$interfaces,
748                                                     \$implementations,
749                                                     \$prerequisites, \$derived,
750                                                     \@file_objects);
751                 if ($file_changed) {
752                     $changed = 1;
753                 }
754             }
755             $title = "";
756             $subsection = "";
757             $in_section = 0;
758             $section_includes = "";
759             $signals_synop = "";
760             $signals_desc = "";
761             $args_synop = "";
762             $child_args_synop = "";
763             $style_args_synop = "";
764             $args_desc = "";
765             $child_args_desc = "";
766             $style_args_desc = "";
767             $hierarchy = "";
768             $interfaces = "";
769             $implementations = "";
770             $prerequisites = "";
771             $derived = "";
773         } elsif (m/^(\S+)/) {
774             my $symbol = $1;
775             #print "  Symbol: $symbol\n";
777             # check for duplicate entries
778             if (! defined $symbol_def_line{$symbol}) {
779                 my $declaration = $Declarations{$symbol};
780                 if (defined ($declaration)) {
781                     # We don't want standard macros/functions of GtkObjects,
782                     # or private declarations.
783                     if ($subsection ne "Standard" && $subsection ne "Private") {
784                         if (&CheckIsObject ($symbol)) {
785                             push @file_objects, $symbol;
786                         }
787                         my ($synop, $desc) = &OutputDeclaration ($symbol,
788                                                                  $declaration);
789                         my ($sig_synop, $sig_desc) = &GetSignals ($symbol);
790                         my ($arg_synop, $child_arg_synop, $style_arg_synop,
791                             $arg_desc, $child_arg_desc, $style_arg_desc) = &GetArgs ($symbol);
792                         my $hier = &GetHierarchy ($symbol);
793                         my $ifaces = &GetInterfaces ($symbol);
794                         my $impls = &GetImplementations ($symbol);
795                         my $prereqs = &GetPrerequisites ($symbol);
796                         my $der = &GetDerived ($symbol);
797                         $synopsis .= $synop;
798                         $details .= $desc;
799                         $signals_synop .= $sig_synop;
800                         $signals_desc .= $sig_desc;
801                         $args_synop .= $arg_synop;
802                         $child_args_synop .= $child_arg_synop;
803                         $style_args_synop .= $style_arg_synop;
804                         $args_desc .= $arg_desc;
805                         $child_args_desc .= $child_arg_desc;
806                         $style_args_desc .= $style_arg_desc;
807                         $hierarchy .= $hier;
808                         $interfaces .= $ifaces;
809                         $implementations .= $impls;
810                         $prerequisites .= $prereqs;
811                         $derived .= $der;
812                     }
813     
814                     # Note that the declaration has been output.
815                     $DeclarationOutput{$symbol} = 1;
816                 } elsif ($subsection ne "Standard" && $subsection ne "Private") {
817                     $UndeclaredSymbols{$symbol} = 1;
818                     &LogWarning ($file, $., "No declaration found for $symbol.");
819                 }
820                 $num_symbols++;
821                 $symbol_def_line{$symbol}=$.;
823                 $SymbolSection{$symbol}=$title;
824             }
825             else {
826                 &LogWarning ($file, $., "Double symbol entry for $symbol. ".
827                     "Previous occurrence on line ".$symbol_def_line{$symbol}.".");
828             }
829         }
830     }
831     close (INPUT);
833     &OutputMissingDocumentation;
834     &OutputUndeclaredSymbols;
836     if ($OUTPUT_ALL_SYMBOLS) {
837         &OutputAllSymbols;
838     }
839     if ($OUTPUT_SYMBOLS_WITHOUT_SINCE) {
840         &OutputSymbolsWithoutSince;
841     }
843     for $filename (split (' ', $EXPAND_CONTENT_FILES)) {
844         my $file_changed = &OutputExtraFile ($filename);
845         if ($file_changed) {
846             $changed = 1;
847         }
848     }
850     &OutputBook ($book_top, $book_bottom);
852     return $changed;
855 #############################################################################
856 # Function    : OutputIndex
857 # Description : This writes an indexlist that can be included into the main-
858 #               document into an <index> tag.
859 #############################################################################
861 sub OutputIndex {
862     my ($basename, $apiindexref ) = @_;
863     my %apiindex = %{$apiindexref};
864     my $old_index = "$SGML_OUTPUT_DIR/$basename.xml";
865     my $new_index = "$SGML_OUTPUT_DIR/$basename.new";
866     my $lastletter = " ";
867     my $divopen = 0;
868     my $symbol;
869     my $short_symbol;
871     open (OUTPUT, ">$new_index")
872         || die "Can't create $new_index";
874     my $header = $doctype_header;
875     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE indexdiv/;
877     print (OUTPUT "$header<indexdiv>\n");
879     #print "generate $basename index (".%apiindex." entries)\n";
880     
881     # do a case insensitive sort while chopping off the prefix
882     foreach my $hash (
883         sort { $$a{criteria} cmp $$b{criteria} }
884         map { my $x = uc($_); $x =~ s/^$NAME_SPACE\_?(.*)/$1/i; { criteria => $x, original => $_, short => $1 } } 
885         keys %apiindex) {
887         $symbol = $$hash{original};
888         if (defined($$hash{short})) {
889             $short_symbol = $$hash{short};
890         } else {
891             $short_symbol = $symbol;
892         }
894         # generate a short symbol description
895         my $symbol_desc = "";
896         my $symbol_section = "";
897         my $symbol_type = lc($DeclarationTypes{$symbol});
898         if ($symbol_type eq "") {
899             #print "trying symbol $symbol\n";
900             if ($symbol =~ m/(.*)::(.*)/) {
901                 my $oname = $1;
902                 my $osym = $2;
903                 my $i;
904                 #print "  trying object signal ${oname}:$osym in ".$#SignalNames." signals\n";
905                 for ($i = 0; $i <= $#SignalNames; $i++) {
906                     if ($SignalNames[$i] eq $osym) {
907                         $symbol_type = "object signal";
908                         if (defined($SymbolSection{$oname})) {
909                            $symbol_section = $SymbolSection{$oname};
910                         }
911                         last;
912                     }
913                 }
914             } elsif ($symbol =~ m/(.*):(.*)/) {
915                 my $oname = $1;
916                 my $osym = $2;
917                 my $i;
918                 #print "  trying object property ${oname}::$osym in ".$#ArgNames." properties\n";
919                 for ($i = 0; $i <= $#ArgNames; $i++) {
920                     #print "    ".$ArgNames[$i]."\n";
921                     if ($ArgNames[$i] eq $osym) {
922                         $symbol_type = "object property";
923                         if (defined($SymbolSection{$oname})) {
924                            $symbol_section = $SymbolSection{$oname};
925                         }
926                         last;
927                     }
928                 }
929             }
930         } else {
931            if (defined($SymbolSection{$symbol})) {
932                $symbol_section = $SymbolSection{$symbol};
933            }
934         }
935         if ($symbol_type ne "") {
936            $symbol_desc=", $symbol_type";
937            if ($symbol_section ne "") {
938                $symbol_desc.=" in ". &ExpandAbbreviations($symbol, "#$symbol_section");
939            }
940         }
942         my $curletter = uc(substr($short_symbol,0,1));
943         my $id = $apiindex{$symbol};
945         #print "  add symbol $symbol with $id to index in section $curletter\n";
947         if ($curletter ne $lastletter) {
948             $lastletter = $curletter;
950             if ($divopen == 1) {
951                 print (OUTPUT "</indexdiv>\n");
952             }
953             print (OUTPUT "<indexdiv><title>$curletter</title>\n");
954             $divopen = 1;
955         }
957         print (OUTPUT <<EOF);
958 <indexentry><primaryie linkends="$id"><link linkend="$id">$symbol</link>$symbol_desc</primaryie></indexentry>
960     }
962     if ($divopen == 1) {
963         print (OUTPUT "</indexdiv>\n");
964     }
965     print (OUTPUT "</indexdiv>\n");
966     close (OUTPUT);
968     &UpdateFileIfChanged ($old_index, $new_index, 0);
972 #############################################################################
973 # Function    : OutputIndexFull
974 # Description : This writes the full api indexlist that can be included into the
975 #               main document into an <index> tag.
976 #############################################################################
978 sub OutputIndexFull {
979     &OutputIndex ("api-index-full", \%IndexEntriesFull);
983 #############################################################################
984 # Function    : OutputDeprecatedIndex
985 # Description : This writes the deprecated api indexlist that can be included
986 #               into the main document into an <index> tag.
987 #############################################################################
989 sub OutputDeprecatedIndex {
990     &OutputIndex ("api-index-deprecated", \%IndexEntriesDeprecated);
994 #############################################################################
995 # Function    : OutputSinceIndexes
996 # Description : This writes the 'since' api indexlists that can be included into
997 #               the main document into an <index> tag.
998 #############################################################################
1000 sub OutputSinceIndexes {
1001     my @sinces = keys %{{ map { $_ => 1 } values %Since }};
1003     foreach my $version (@sinces) {
1004         #print "Since : [$version]\n";
1005         # todo make filtered hash
1006         #my %index = grep { $Since{$_} eq $version } %IndexEntriesSince;
1007         my %index = map { $_ => $IndexEntriesSince{$_} } grep { $Since{$_} eq $version } keys %IndexEntriesSince;
1009         &OutputIndex ("api-index-$version", \%index);
1010     }
1013 #############################################################################
1014 # Function    : OutputAnnotationGlossary
1015 # Description : This writes a glossary of the used annotation terms into a
1016 #               separate glossary file that can be included into the main
1017 #               document.
1018 #############################################################################
1020 sub OutputAnnotationGlossary {
1021     my $old_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.xml";
1022     my $new_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.new";
1023     my $lastletter = " ";
1024     my $divopen = 0;
1026     # if there are no annotations used return
1027     return if (! keys(%AnnotationsUsed));
1029     # add acronyms that are referenced from acronym text
1030 rerun:
1031     foreach my $annotation (keys(%AnnotationsUsed)) {
1032         if($AnnotationDefinition{$annotation} =~ m/<acronym>([\w ]+)<\/acronym>/) {
1033             if (!exists($AnnotationsUsed{$1})) {
1034                 $AnnotationsUsed{$1} = 1;
1035                 goto rerun;
1036             }
1037         }
1038     }
1040     open (OUTPUT, ">$new_glossary")
1041         || die "Can't create $new_glossary";
1043     my $header = $doctype_header;
1044     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE glossary/;
1046     print (OUTPUT  <<EOF);
1047 $header
1048 <glossary id="annotation-glossary">
1049   <title>Annotation Glossary</title>
1052     foreach my $annotation (keys(%AnnotationsUsed)) {
1053         my $def = $AnnotationDefinition{$annotation};
1054         my $curletter = uc(substr($annotation,0,1));
1056         if ($curletter ne $lastletter) {
1057             $lastletter = $curletter;
1058       
1059             if ($divopen == 1) {
1060                 print (OUTPUT "</glossdiv>\n");
1061             }
1062             print (OUTPUT "<glossdiv><title>$curletter</title>\n");
1063             $divopen = 1;
1064         }
1065         print (OUTPUT <<EOF);
1066     <glossentry>
1067       <glossterm><anchor id="annotation-glossterm-$annotation"/>$annotation</glossterm>
1068       <glossdef>
1069         <para>$def</para>
1070       </glossdef>
1071     </glossentry>
1073     }
1075     if ($divopen == 1) {
1076         print (OUTPUT "</glossdiv>\n");
1077     }
1078     print (OUTPUT "</glossary>\n");
1079     close (OUTPUT);
1081     &UpdateFileIfChanged ($old_glossary, $new_glossary, 0);
1084 #############################################################################
1085 # Function    : ReadKnownSymbols
1086 # Description : This collects the names of non-private symbols from the
1087 #               $MODULE-sections.txt file.
1088 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
1089 #               the functions/macros/structs etc. being documented, organised
1090 #               into sections and subsections.
1091 #############################################################################
1093 sub ReadKnownSymbols {
1094     my ($file) = @_;
1096     my $subsection = "";
1098     #print "Reading: $file\n";
1099     open (INPUT, $file)
1100         || die "Can't open $file: $!";
1102     while (<INPUT>) {
1103         if (m/^#/) {
1104             next;
1106         } elsif (m/^<SECTION>/) {
1107             $subsection = "";
1109         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
1110             $subsection = $1;
1112         } elsif (m/^<SUBSECTION>/) {
1113             next;
1115         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
1116             next;
1118         } elsif (m/^<FILE>(.*)<\/FILE>/) {
1119             $KnownSymbols{"$TMPL_DIR/$1:Long_Description"} = 1;
1120             $KnownSymbols{"$TMPL_DIR/$1:Short_Description"} = 1;
1121             next;
1123         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
1124             next;
1126         } elsif (m/^<\/SECTION>/) {
1127             next;
1129         } elsif (m/^(\S+)/) {
1130             my $symbol = $1;
1132             if ($subsection ne "Standard" && $subsection ne "Private") {
1133                 $KnownSymbols{$symbol} = 1;
1134             }
1135             else {
1136                 $KnownSymbols{$symbol} = 0;
1137             }
1138         }
1139     }
1140     close (INPUT);
1144 #############################################################################
1145 # Function    : OutputDeclaration
1146 # Description : Returns the synopsis and detailed description DocBook
1147 #               describing one function/macro etc.
1148 # Arguments   : $symbol - the name of the function/macro begin described.
1149 #               $declaration - the declaration of the function/macro.
1150 #############################################################################
1152 sub OutputDeclaration {
1153     my ($symbol, $declaration) = @_;
1155     my $type = $DeclarationTypes {$symbol};
1156     if ($type eq 'MACRO') {
1157         return &OutputMacro ($symbol, $declaration);
1158     } elsif ($type eq 'TYPEDEF') {
1159         return &OutputTypedef ($symbol, $declaration);
1160     } elsif ($type eq 'STRUCT') {
1161         return &OutputStruct ($symbol, $declaration);
1162     } elsif ($type eq 'ENUM') {
1163         return &OutputEnum ($symbol, $declaration);
1164     } elsif ($type eq 'UNION') {
1165         return &OutputUnion ($symbol, $declaration);
1166     } elsif ($type eq 'VARIABLE') {
1167         return &OutputVariable ($symbol, $declaration);
1168     } elsif ($type eq 'FUNCTION') {
1169         return &OutputFunction ($symbol, $declaration, $type);
1170     } elsif ($type eq 'USER_FUNCTION') {
1171         return &OutputFunction ($symbol, $declaration, $type);
1172     } else {
1173         die "Unknown symbol type";
1174     }
1178 #############################################################################
1179 # Function    : OutputSymbolTraits
1180 # Description : Returns the Since and StabilityLevel paragraphs for a symbol.
1181 # Arguments   : $symbol - the name of the function/macro begin described.
1182 #############################################################################
1184 sub OutputSymbolTraits {
1185     my ($symbol) = @_;
1186     my $desc = "";
1188     if (exists $Since{$symbol}) {
1189         $desc .= "<para role=\"since\">Since $Since{$symbol}</para>";
1190     }
1191     if (exists $StabilityLevel{$symbol}) {
1192         $desc .= "<para role=\"stability\">Stability Level: $StabilityLevel{$symbol}</para>";
1193     }
1194     return $desc;
1197 #############################################################################
1198 # Function    : Outpu{Symbol,Section}ExtraLinks
1199 # Description : Returns extralinks for the symbol (if enabled).
1200 # Arguments   : $symbol - the name of the function/macro begin described.
1201 #############################################################################
1203 sub uri_escape {
1204     my $text = $_[0];
1205     return undef unless defined $text;
1207     # Build a char to hex map
1208     my %escapes = ();
1209     for (0..255) {
1210             $escapes{chr($_)} = sprintf("%%%02X", $_);
1211     }
1213     # Default unsafe characters.  RFC 2732 ^(uric - reserved)
1214     $text =~ s/([^A-Za-z0-9\-_.!~*'()])/$escapes{$1}/g;
1216     return $text;
1219 sub OutputSymbolExtraLinks {
1220     my ($symbol) = @_;
1221     my $desc = "";
1223     if (0) { # NEW FEATURE: needs configurability
1224     my $sstr = &uri_escape($symbol);
1225     my $mstr = &uri_escape($MODULE);
1226     $desc .= <<EOF;
1227 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1228 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$sstr">edit documentation</ulink>
1230     }
1231     return $desc;
1234 sub OutputSectionExtraLinks {
1235     my ($symbol,$docsymbol) = @_;
1236     my $desc = "";
1238     if (0) { # NEW FEATURE: needs configurability
1239     my $sstr = &uri_escape($symbol);
1240     my $mstr = &uri_escape($MODULE);
1241     my $dsstr = &uri_escape($docsymbol);
1242     $desc .= <<EOF;
1243 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1244 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$dsstr">edit documentation</ulink>
1246     }
1247     return $desc;
1251 #############################################################################
1252 # Function    : OutputMacro
1253 # Description : Returns the synopsis and detailed description of a macro.
1254 # Arguments   : $symbol - the macro.
1255 #               $declaration - the declaration of the macro.
1256 #############################################################################
1258 sub OutputMacro {
1259     my ($symbol, $declaration) = @_;
1260     my $id = &CreateValidSGMLID ($symbol);
1261     my $condition = &MakeConditionDescription ($symbol);
1262     my $synop = &MakeReturnField("#define") . "<link linkend=\"$id\">$symbol</link>";
1263     my $desc;
1264     my $padding = "";
1265     my $args = "";
1266     my $pad;
1268     if ($declaration =~ m/^\s*#\s*define(\s+)\w+(\([^\)]*\))/) {
1269         $padding = $1;
1270         $args = $2;
1272         if (length ($symbol) < $SYMBOL_FIELD_WIDTH) {
1273             $synop .= (' ' x ($SYMBOL_FIELD_WIDTH - length ($symbol)));
1274         }
1276         # Try to align all the lines of args correctly.
1277         $pad = ' ' x ($RETURN_TYPE_FIELD_WIDTH + $SYMBOL_FIELD_WIDTH + 1);
1278         my $args_padded = $args;
1279         $args_padded =~ s/ *\\\n */\n$pad/gm;
1280         $synop .= &CreateValidSGML ($args_padded);
1281     }
1282     $synop .= "\n";
1284     my $title = $symbol . ($args ? "()" : "");
1285     $desc = "<refsect2 id=\"$id\" role=\"macro\"$condition>\n<title>$title</title>\n";
1286     $desc .= MakeIndexterms($symbol, $id);
1287     $desc .= "\n";
1288     $desc .= OutputSymbolExtraLinks($symbol);
1290     # Don't output the macro definition if is is a conditional macro or it
1291     # looks like a function, i.e. starts with "g_" or "_?gnome_", or it is
1292     # longer than 2 lines, otherwise we get lots of complicated macros like
1293     # g_assert.
1294     if (!defined ($DeclarationConditional{$symbol}) && ($symbol !~ m/^g_/)
1295         && ($symbol !~ m/^_?gnome_/) && (($declaration =~ tr/\n//) < 2)) {
1296         my $decl_out = &CreateValidSGML ($declaration);
1297         $desc .= "<programlisting>$decl_out</programlisting>\n";
1298     } else {
1299         $desc .= "<programlisting>" . &MakeReturnField("#define") . "$symbol";
1300         # Align each line so that if should all line up OK.
1301         $pad = ' ' x ($RETURN_TYPE_FIELD_WIDTH - length ("#define "));
1302         $args =~ s/\n/\n$pad/gm;
1303         $desc .= &CreateValidSGML ($args);
1304         $desc .= "</programlisting>\n";
1305     }
1307     $desc .= &MakeDeprecationNote($symbol);
1309     my $parameters = &OutputParamDescriptions ("MACRO", $symbol);
1310     my $parameters_output = 0;
1312     if (defined ($SymbolDocs{$symbol})) {
1313         my $symbol_docs = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1315         # Try to insert the parameter table at the author's desired position.
1316         # Otherwise we need to tag it onto the end.
1317         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
1318           $parameters_output = 1;
1319         }
1320         $desc .= $symbol_docs;
1321     }
1323     if ($parameters_output == 0) {
1324         $desc .= $parameters;
1325     }
1327     $desc .= OutputSymbolTraits ($symbol);
1328     $desc .= "</refsect2>\n";
1329     return ($synop, $desc);
1333 #############################################################################
1334 # Function    : OutputTypedef
1335 # Description : Returns the synopsis and detailed description of a typedef.
1336 # Arguments   : $symbol - the typedef.
1337 #               $declaration - the declaration of the typedef,
1338 #                 e.g. 'typedef unsigned int guint;'
1339 #############################################################################
1341 sub OutputTypedef {
1342     my ($symbol, $declaration) = @_;
1343     my $id = &CreateValidSGMLID ($symbol);
1344     my $condition = &MakeConditionDescription ($symbol);
1345     my $synop = &MakeReturnField("typedef") . "<link linkend=\"$id\">$symbol</link>;\n";
1346     my $desc = "<refsect2 id=\"$id\" role=\"typedef\"$condition>\n<title>$symbol</title>\n";
1348     $desc .= MakeIndexterms($symbol, $id);
1349     $desc .= "\n";
1350     $desc .= OutputSymbolExtraLinks($symbol);
1352     if (!defined ($DeclarationConditional{$symbol})) {
1353         my $decl_out = &CreateValidSGML ($declaration);
1354         $desc .= "<programlisting>$decl_out</programlisting>\n";
1355     }
1357     $desc .= &MakeDeprecationNote($symbol);
1359     if (defined ($SymbolDocs{$symbol})) {
1360         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1361     }
1362     $desc .= OutputSymbolTraits ($symbol);
1363     $desc .= "</refsect2>\n";
1364     return ($synop, $desc);
1368 #############################################################################
1369 # Function    : OutputStruct
1370 # Description : Returns the synopsis and detailed description of a struct.
1371 #               We check if it is a widget struct, and if so we only output
1372 #               parts of it that are noted as public fields.
1373 #               We also use a different SGML ID for widget structs, since the
1374 #               original ID is used for the entire RefEntry.
1375 # Arguments   : $symbol - the struct.
1376 #               $declaration - the declaration of the struct.
1377 #############################################################################
1379 sub OutputStruct {
1380     my ($symbol, $declaration) = @_;
1382     my $is_widget_struct = 0;
1383     my $default_to_public = 1;
1384     if (&CheckIsObject ($symbol)) {
1385     #print "Found widget struct: $symbol\n";
1386     $is_widget_struct = 1;
1387         $default_to_public = 0;
1388     }
1390     my $id;
1391     my $condition;
1392     if ($is_widget_struct) {
1393         $id = &CreateValidSGMLID ($symbol . "_struct");
1394         $condition = &MakeConditionDescription ($symbol . "_struct");
1395     } else {
1396         $id = &CreateValidSGMLID ($symbol);
1397         $condition = &MakeConditionDescription ($symbol);
1398     }
1400     # Determine if it is a simple struct or it also has a typedef.
1401     my $has_typedef = 0;
1402     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1403       $has_typedef = 1;
1404     }
1406     my $synop;
1407     my $desc;
1408     if ($has_typedef) {
1409         # For structs with typedefs we just output the struct name.
1410         $synop = &MakeReturnField("") . "<link linkend=\"$id\">$symbol</link>;\n";
1411         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>$symbol</title>\n";
1412     } else {
1413         $synop = &MakeReturnField("struct") . "<link linkend=\"$id\">$symbol</link>;\n";
1414         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>struct $symbol</title>\n";
1415     }
1417     $desc .= MakeIndexterms($symbol, $id);
1418     $desc .= "\n";
1419     $desc .= OutputSymbolExtraLinks($symbol);
1421     # Form a pretty-printed, private-data-removed form of the declaration
1423     my $decl_out = "";
1424     if ($declaration =~ m/^\s*$/) {
1425         #print "Found opaque struct: $symbol\n";
1426         $decl_out = "typedef struct _$symbol $symbol;";
1427     } elsif ($declaration =~ m/^\s*struct\s+\w+\s*;\s*$/) {
1428         #print "Found opaque struct: $symbol\n";
1429         $decl_out = "struct $symbol;";
1430     } else {
1431         my $public = $default_to_public;
1432         my $new_declaration = "";
1433         my $decl_line;
1434         my $decl = $declaration;
1436         if ($decl =~ m/^\s*(typedef\s+)?struct\s*\w*\s*(?:\/\*.*\*\/)?\s*{(.*)}\s*\w*\s*;\s*$/s) {
1437             my $struct_contents = $2;
1439             foreach $decl_line (split (/\n/, $struct_contents)) {
1440                 #print "Struct line: $decl_line\n";
1441                 if ($decl_line =~ m%/\*\s*<\s*public\s*>\s*\*/%) {
1442                     $public = 1;
1443                 } elsif ($decl_line =~ m%/\*\s*<\s*(private|protected)\s*>\s*\*/%) {
1444                     $public = 0;
1445                 } elsif ($public) {
1446                     $new_declaration .= $decl_line . "\n";
1447                 }
1448             }
1450             if ($new_declaration) {
1451                 # Strip any blank lines off the ends.
1452                 $new_declaration =~ s/^\s*\n//;
1453                 $new_declaration =~ s/\n\s*$/\n/;
1455                 if ($has_typedef) {
1456                     $decl_out = "typedef struct {\n" . $new_declaration
1457                       . "} $symbol;\n";
1458                 } else {
1459                     $decl_out = "struct $symbol {\n" . $new_declaration
1460                       . "};\n";
1461                 }
1462             }
1463         } else {
1464             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1465                 "Couldn't parse struct:\n$declaration");
1466         }
1468         # If we couldn't parse the struct or it was all private, output an
1469         # empty struct declaration.
1470         if ($decl_out eq "") {
1471             if ($has_typedef) {
1472                 $decl_out = "typedef struct _$symbol $symbol;";
1473             } else {
1474                 $decl_out = "struct $symbol;";
1475             }
1476         }
1477     }
1479     $decl_out = &CreateValidSGML ($decl_out);
1480     $desc .= "<programlisting>$decl_out</programlisting>\n";
1482     $desc .= &MakeDeprecationNote($symbol);
1484     if (defined ($SymbolDocs{$symbol})) {
1485         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1486     }
1488     # Create a table of fields and descriptions
1490     # FIXME: Inserting &#160's into the produced type declarations here would
1491     #        improve the output in most situations ... except for function
1492     #        members of structs!
1493     my @fields = ParseStructDeclaration($declaration, !$default_to_public,
1494                                         0, \&MakeXRef,
1495                                         sub {
1496                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1497                                         });
1498     my $params = $SymbolParams{$symbol};
1500     # If no parameters are filled in, we don't generate the description
1501     # table, for backwards compatibility
1503     my $found = 0;
1504     if (defined $params) {
1505         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1506             if ($params->[$i] =~ /\S/) {
1507                 $found = 1;
1508                 last;
1509             }
1510         }
1511     }
1513     if ($found) {
1514         my %field_descrs = @$params;
1516             $desc .= <<EOF;
1517 <variablelist role="struct">
1519         while (@fields) {
1520             my $field_name = shift @fields;
1521             my $text = shift @fields;
1522             my $field_descr = $field_descrs{$field_name};
1523             my $param_annotations = "";
1525             $desc .= "<varlistentry><term>$text</term>\n";
1526             if (defined $field_descr) {
1527                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1528                 $field_descr = &ExpandAbbreviations($symbol, $field_descr);
1529                 $desc .= "<listitem><simpara>$field_descr$param_annotations</simpara></listitem>\n";
1530             } else {
1531                 $desc .= "<listitem><simpara /></listitem>\n";
1532             }
1533             $desc .= "</varlistentry>\n";
1534         }
1536         $desc .= "</variablelist>";
1537     }
1538     $desc .= OutputSymbolTraits ($symbol);
1539     $desc .= "</refsect2>\n";
1540     return ($synop, $desc);
1544 #############################################################################
1545 # Function    : OutputEnum
1546 # Description : Returns the synopsis and detailed description of a enum.
1547 # Arguments   : $symbol - the enum.
1548 #               $declaration - the declaration of the enum.
1549 #############################################################################
1551 sub OutputEnum {
1552     my ($symbol, $declaration) = @_;
1553     my $id = &CreateValidSGMLID ($symbol);
1554     my $condition = &MakeConditionDescription ($symbol);
1555     my $synop = &MakeReturnField("enum") . "<link linkend=\"$id\">$symbol</link>;\n";
1556     my $desc = "<refsect2 id=\"$id\" role=\"enum\"$condition>\n<title>enum $symbol</title>\n";
1558     $desc .= MakeIndexterms($symbol, $id);
1559     $desc .= "\n";
1560     $desc .= OutputSymbolExtraLinks($symbol);
1562     my $decl_out = &CreateValidSGML ($declaration);
1563     $desc .= "<programlisting>$decl_out</programlisting>\n";
1565     $desc .= &MakeDeprecationNote($symbol);
1567     if (defined ($SymbolDocs{$symbol})) {
1568         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1569     }
1571     # Create a table of fields and descriptions
1573     my @members = ParseEnumDeclaration($declaration);
1574     my $params = $SymbolParams{$symbol};
1576     # If no parameters are filled in, we don't generate the description
1577     # table, for backwards compatibility
1579     my $found = 0;
1580     if (defined $params) {
1581         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1582             if ($params->[$i] =~ /\S/) {
1583                 $found = 1;
1584                 last;
1585             }
1586         }
1587     }
1589     if ($found) {
1590         my %member_descrs = @$params;
1592             $desc .= <<EOF;
1593 <variablelist role="enum">
1595         for my $member_name (@members) {
1596             my $member_descr = $member_descrs{$member_name};
1597             my $param_annotations = "";
1599             $id = &CreateValidSGMLID ($member_name);
1600             $condition = &MakeConditionDescription ($member_name);
1601             $desc .= "<varlistentry id=\"$id\" role=\"constant\"$condition>\n<term><literal>$member_name</literal></term>\n";
1602             if (defined $member_descr) {
1603                 ($member_descr,$param_annotations) = &ExpandAnnotation($symbol, $member_descr);
1604                 $member_descr = &ExpandAbbreviations($symbol, $member_descr);
1605                 $desc .= "<listitem><simpara>$member_descr$param_annotations</simpara></listitem>\n";
1606             } else {
1607                 $desc .= "<listitem></listitem>\n";
1608             }
1609             $desc .= "</varlistentry>\n";
1610         }
1612         $desc .= "</variablelist>";
1613     }
1615     $desc .= OutputSymbolTraits ($symbol);
1616     $desc .= "</refsect2>\n";
1617     return ($synop, $desc);
1621 #############################################################################
1622 # Function    : OutputUnion
1623 # Description : Returns the synopsis and detailed description of a union.
1624 # Arguments   : $symbol - the union.
1625 #               $declaration - the declaration of the union.
1626 #############################################################################
1628 sub OutputUnion {
1629     my ($symbol, $declaration) = @_;
1630     my $id = &CreateValidSGMLID ($symbol);
1631     my $condition = &MakeConditionDescription ($symbol);
1633     # Determine if it is a simple struct or it also has a typedef.
1634     my $has_typedef = 0;
1635     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1636       $has_typedef = 1;
1637     }
1639     my $synop;
1640     my $desc;
1641     if ($has_typedef) {
1642         # For unions with typedefs we just output the union name.
1643         $synop = &MakeReturnField("") . "<link linkend=\"$id\">$symbol</link>;\n";
1644         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>$symbol</title>\n";
1645     } else {
1646         $synop = &MakeReturnField("union") . "<link linkend=\"$id\">$symbol</link>;\n";
1647         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>union $symbol</title>\n";
1648     }
1650     $desc .= MakeIndexterms($symbol, $id);
1651     $desc .= "\n";
1652     $desc .= OutputSymbolExtraLinks($symbol);
1654     # FIXME: we do more for structs
1655     my $decl_out = &CreateValidSGML ($declaration);
1656     $desc .= "<programlisting>$decl_out</programlisting>\n";
1658     $desc .= &MakeDeprecationNote($symbol);
1660     if (defined ($SymbolDocs{$symbol})) {
1661         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1662     }
1664     # Create a table of fields and descriptions
1666     # FIXME: Inserting &#160's into the produced type declarations here would
1667     #        improve the output in most situations ... except for function
1668     #        members of structs!
1669     my @fields = ParseStructDeclaration($declaration, 0,
1670                                         0, \&MakeXRef,
1671                                         sub {
1672                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1673                                         });
1674     my $params = $SymbolParams{$symbol};
1676     # If no parameters are filled in, we don't generate the description
1677     # table, for backwards compatibility
1679     my $found = 0;
1680     if (defined $params) {
1681         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1682             if ($params->[$i] =~ /\S/) {
1683                 $found = 1;
1684                 last;
1685             }
1686         }
1687     }
1689     if ($found) {
1690         my %field_descrs = @$params;
1692             $desc .= <<EOF;
1693 <variablelist role="struct">
1695         while (@fields) {
1696             my $field_name = shift @fields;
1697             my $text = shift @fields;
1698             my $field_descr = $field_descrs{$field_name};
1699             my $param_annotations = "";
1701             $desc .= "<varlistentry><term>$text</term>\n";
1702             if (defined $field_descr) {
1703                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1704                 $field_descr = &ExpandAbbreviations($symbol, $field_descr);
1705                 $desc .= "<listitem><simpara>$field_descr$param_annotations</simpara></listitem>\n";
1706             } else {
1707                 $desc .= "<listitem><simpara /></listitem>\n";
1708             }
1709             $desc .= "</varlistentry>\n";
1710         }
1712         $desc .= "</variablelist>";
1713     }
1714     $desc .= OutputSymbolTraits ($symbol);
1715     $desc .= "</refsect2>\n";
1716     return ($synop, $desc);
1720 #############################################################################
1721 # Function    : OutputVariable
1722 # Description : Returns the synopsis and detailed description of a variable.
1723 # Arguments   : $symbol - the extern'ed variable.
1724 #               $declaration - the declaration of the variable.
1725 #############################################################################
1727 sub OutputVariable {
1728     my ($symbol, $declaration) = @_;
1729     my $id = &CreateValidSGMLID ($symbol);
1730     my $condition = &MakeConditionDescription ($symbol);
1732     my $synop;
1733     if ($declaration =~ m/^\s*extern\s+((const\s+|unsigned\s+)*\w+)(\s+\*+|\*+|\s)(\s*)([A-Za-z]\w*)\s*;/) {
1734         my $mod = defined ($1) ? $1 : "";
1735         my $ptr = defined ($3) ? $3 : "";
1736         my $space = defined ($4) ? $4 : "";
1737         $synop = &MakeReturnField("extern") . "$mod$ptr$space<link linkend=\"$id\">$symbol</link>;\n";
1739     } else {
1740         $synop = &MakeReturnField("extern") . "<link linkend=\"$id\">$symbol</link>;\n";
1741     }
1743     my $desc = "<refsect2 id=\"$id\" role=\"variable\"$condition>\n<title>$symbol</title>\n";
1745     $desc .= MakeIndexterms($symbol, $id);
1746     $desc .= "\n";
1747     $desc .= OutputSymbolExtraLinks($symbol);
1749     my $decl_out = &CreateValidSGML ($declaration);
1750     $desc .= "<programlisting>$decl_out</programlisting>\n";
1752     $desc .= &MakeDeprecationNote($symbol);
1754     if (defined ($SymbolDocs{$symbol})) {
1755         $desc .= &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1756     }
1757     $desc .= OutputSymbolTraits ($symbol);
1758     $desc .= "</refsect2>\n";
1759     return ($synop, $desc);
1763 #############################################################################
1764 # Function    : OutputFunction
1765 # Description : Returns the synopsis and detailed description of a function.
1766 # Arguments   : $symbol - the function.
1767 #               $declaration - the declaration of the function.
1768 #############################################################################
1770 sub OutputFunction {
1771     my ($symbol, $declaration, $symbol_type) = @_;
1772     my $id = &CreateValidSGMLID ($symbol);
1773     my $condition = &MakeConditionDescription ($symbol);
1775     # Take out the return type     $1                                                                           $3   $4
1776     $declaration =~ s/<RETURNS>\s*((const\s+|G_CONST_RETURN\s+|unsigned\s+|long\s+|short\s+|struct\s+|enum\s+)*)(\w+)(\s*\**\s*(const|G_CONST_RETURN)?\s*\**\s*(restrict)?\s*)<\/RETURNS>\n//;
1777     my $type_modifier = defined($1) ? $1 : "";
1778     my $type = $3;
1779     my $pointer = $4;
1780     #print "$symbol pointer is $pointer\n";
1781     my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
1782     my $start = "";
1783     #if ($symbol_type eq 'USER_FUNCTION') {
1784     #    $start = "typedef ";
1785     #}
1787     # We output const rather than G_CONST_RETURN.
1788     $type_modifier =~ s/G_CONST_RETURN/const/g;
1789     $pointer =~ s/G_CONST_RETURN/const/g;
1790     $pointer =~ s/^\s+/ /g;
1792     my $ret_type_len = length ($start) + length ($type_modifier)
1793         + length ($pointer) + length ($type);
1794     my $ret_type_output;
1795     my $symbol_len;
1796     if ($ret_type_len < $RETURN_TYPE_FIELD_WIDTH) {
1797         $ret_type_output = "$start$type_modifier$xref$pointer"
1798             . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
1799         $symbol_len = 0;
1800     } else {
1801 #       $ret_type_output = "$start$type_modifier$xref$pointer\n"
1802 #           . (' ' x $RETURN_TYPE_FIELD_WIDTH);
1804         $ret_type_output = "$start$type_modifier$xref$pointer ";
1805         $symbol_len = $ret_type_len + 1 - $RETURN_TYPE_FIELD_WIDTH;
1806     }
1808     $symbol_len += length ($symbol);
1809     my $char1 = my $char2 = my $char3 = "";
1810     if ($symbol_type eq 'USER_FUNCTION') {
1811         $symbol_len += 3;
1812         $char1 = "(";
1813         $char2 = "*";
1814         $char3 = ")";
1815     }
1817     my ($symbol_output, $symbol_desc_output);
1818     if ($symbol_len < $SYMBOL_FIELD_WIDTH) {
1819         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3"
1820             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
1821         $symbol_desc_output = "$char1$char2$symbol$char3"
1822             . (' ' x ($SYMBOL_FIELD_WIDTH - $symbol_len));
1823     } else {
1824         $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3\n"
1825             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
1826         $symbol_desc_output = "$char1$char2$symbol$char3\n"
1827             . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
1828     }
1830     my $synop = $ret_type_output . $symbol_output . '(';
1831     my $desc = "<refsect2 id=\"$id\" role=\"function\"$condition>\n<title>${symbol} ()</title>\n";
1833     $desc .= MakeIndexterms($symbol, $id);
1834     $desc .= "\n";
1835     $desc .= OutputSymbolExtraLinks($symbol);
1837     $desc  .= "<programlisting>${ret_type_output}$symbol_desc_output(";
1839     my $param_num = 0;
1840     while ($declaration ne "") {
1841         #print "$declaration";
1843         if ($declaration =~ s/^[\s,]+//) {
1844             # skip whitespace and commas
1845             next;
1847         } elsif ($declaration =~ s/^void\s*[,\n]//) {
1848             $synop .= "void";
1849             $desc  .= "void";
1851         } elsif ($declaration =~ s/^...\s*[,\n]//) {
1852             if ($param_num == 0) {
1853                 $synop .= "...";
1854                 $desc  .= "...";
1855             } else {
1856                 $synop .= ",\n"
1857                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1858                     . " ...";
1859                 $desc  .= ",\n"
1860                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1861                     . " ...";
1862             }
1864         # allow alphanumerics, '_', '[' & ']' in param names
1865         # Try to match a standard parameter (keep in sync with gtkdoc-mktmpl)
1866         #                                $1                                                                                                                                    $2                             $3                                                           $4       $5
1867         } elsif ($declaration =~ s/^\s*((?:G_CONST_RETURN|G_GNUC_UNUSED|unsigned long|unsigned short|signed long|signed short|unsigned|signed|long|short|volatile|const)\s+)*((?:struct\b|enum\b)?\s*\w+)\s*((?:(?:const\b|restrict\b)?\s*\*?\s*(?:const\b|restrict\b)?\s*)*)(\w+)?\s*((?:\[\S*\])*)\s*[,\n]//) {
1868             my $pre     = defined($1) ? $1 : "";
1869             my $type    = $2;
1870             my $ptr     = defined($3) ? $3 : "";
1871             my $name    = defined($4) ? $4 : "";
1872             my $array   = defined($5) ? $5 : "";
1874             $pre  =~ s/\s+/ /g;
1875             $type =~ s/\s+/ /g;
1876             $ptr  =~ s/\s+/ /g;
1877             $ptr  =~ s/\s+$//;
1878             if ($ptr && $ptr !~ m/\*$/) { $ptr .= " "; }
1880             #print "$symbol: '$pre' '$type' '$ptr' '$name' '$array'\n";
1882             if (($name eq "") && $pre =~ m/^((un)?signed .*)\s?/ ) {
1883                 $name = $type;
1884                 $type = "$1";
1885                 $pre = "";
1886             }
1888             my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
1889             my $label   = "$pre$xref $ptr$name$array";
1891             #print "$symbol: '$pre' '$type' '$ptr' '$name' '$array'\n";
1893             if ($param_num == 0) {
1894                 $synop .= "$label";
1895                 $desc  .= "$label";
1896             } else {
1897                 $synop .= ",\n"
1898                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1899                     . " $label";
1900                 $desc  .= ",\n"
1901                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1902                     . " $label";
1903             }
1905         # Try to match parameters which are functions (keep in sync with gtkdoc-mktmpl)
1906         #                              $1                                       $2          $3      $4                        $5                    $7             $8
1907         } elsif ($declaration =~ s/^(const\s+|G_CONST_RETURN\s+|unsigned\s+)*(struct\s+)?(\w+)\s*(\**)\s*(?:restrict\b)?\s*(const\s+)?\(\s*\*+\s*(\w+)\s*\)\s*\(([^)]*)\)\s*[,\n]//) {
1908             my $mod1 = defined($1) ? $1 : "";
1909             if (defined($2)) { $mod1 .= $2; }
1910             my $type = $3;
1911             my $ptr1 = $4;
1912             my $mod2 = defined($5) ? $5 : "";
1913             my $func_ptr = $6;
1914             my $name = $7;
1915             my $func_params = defined($8) ? $8 : "";
1916             
1917             #if (!defined($type)) { print "## no type\n"; };
1918             #if (!defined($ptr1)) { print "## no ptr1\n"; };
1919             #if (!defined($func_ptr)) { print "## no func_ptr\n"; };
1920             #if (!defined($name)) { print "## no name\n"; };
1922             if ($ptr1 && $ptr1 !~ m/\*$/) { $ptr1 .= " "; }
1923             $func_ptr  =~ s/\s+//g;
1924             my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
1925             my $label = "$mod1$xref$ptr1$mod2 ($func_ptr$name) ($func_params)";
1927             #print "Type: [$mod1][$xref][$ptr1][$mod2] ([$func_ptr][$name]) ($func_params)\n";
1928             if ($param_num == 0) {
1929                 $synop .= "$label";
1930                 $desc  .= "$label";
1931             } else {
1932                 $synop .= ",\n"
1933                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1934                     . " $label";
1935                 $desc  .= ",\n"
1936                     . (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH))
1937                     . " $label";
1938             }
1940         } else {
1941             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1942                 "Can't parse args for function $symbol: $declaration");
1943             last;
1944         }
1945         $param_num++;
1946     }
1947     $synop .= ");\n";
1948     $desc  .= ");</programlisting>\n";
1950     $desc .= &MakeDeprecationNote($symbol);
1952     my $parameters = &OutputParamDescriptions ("FUNCTION", $symbol);
1953     my $parameters_output = 0;
1955     if (defined ($SymbolDocs{$symbol})) {
1956         my $symbol_docs = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
1958         # Try to insert the parameter table at the author's desired position.
1959         # Otherwise we need to tag it onto the end.
1960         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
1961           $parameters_output = 1;
1962         }
1963         $desc .= $symbol_docs;
1964     }
1966     if ($parameters_output == 0) {
1967         $desc .= $parameters;
1968     }
1970     $desc .= OutputSymbolTraits ($symbol);
1971     $desc .= "</refsect2>\n";
1972     return ($synop, $desc);
1976 #############################################################################
1977 # Function    : OutputParamDescriptions
1978 # Description : Returns the DocBook output describing the parameters of a
1979 #               function, macro or signal handler.
1980 # Arguments   : $symbol_type - 'FUNCTION', 'MACRO' or 'SIGNAL'. Signal
1981 #                 handlers have an implicit user_data parameter last.
1982 #               $symbol - the name of the function/macro being described.
1983 #############################################################################
1985 sub OutputParamDescriptions {
1986     my ($symbol_type, $symbol) = @_;
1987     my $output = "";
1988     if (defined ($SymbolParams{$symbol})) {
1989         my $returns = "";
1990         my $params = $SymbolParams{$symbol};
1991         my $params_desc = "";
1992         my $j;
1993         for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
1994             my $param_name = $$params[$j];
1995             my $param_desc = $$params[$j + 1];
1996             my $param_annotations = "";
1998             ($param_desc,$param_annotations) = & ExpandAnnotation($symbol, $param_desc);
1999             $param_desc = &ExpandAbbreviations($symbol, $param_desc);
2000             if ($param_name eq "Returns") {
2001                 $returns = "$param_desc$param_annotations";
2002             } else {
2003                 if ($param_name eq "Varargs") {
2004                     $param_name = "...";
2005                 }
2006                 $params_desc .= "<varlistentry><term><parameter>$param_name</parameter>&#160;:</term>\n<listitem><simpara>$param_desc$param_annotations</simpara></listitem></varlistentry>\n";
2007             }
2008         }
2010         # Signals have an implicit user_data parameter which we describe.
2011         if ($symbol_type eq "SIGNAL") {
2012             $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";
2013         }
2015         # Start a table if we need one.
2016         if ($params_desc || $returns) {
2017             $output .= "<variablelist role=\"params\">\n";
2018             if ($params_desc ne "") {
2019                 #$output .= "<varlistentry><term>Parameters:</term><listitem></listitem></varlistentry>\n";
2020                 $output .= $params_desc;
2021             }
2023             # Output the returns info last.
2024             if ($returns) {
2025                 $output .= "<varlistentry><term><emphasis>Returns</emphasis>&#160;:</term><listitem><simpara>$returns</simpara></listitem></varlistentry>\n";
2026             }
2028             # Finish the table.
2029             $output .= "</variablelist>";
2030         }
2031     }
2032     return $output;
2036 #############################################################################
2037 # Function    : ParseStabilityLevel
2038 # Description : Parses a stability level and outputs a warning if it isn't
2039 #               valid.
2040 # Arguments   : $stability - the stability text.
2041 #               $file, $line - context for error message
2042 #               $message - description of where the level is from, to use in
2043 #               any error message.
2044 # Returns     : The parsed stability level string.
2045 #############################################################################
2047 sub ParseStabilityLevel {
2048     my ($stability, $file, $line, $message) = @_;
2050     $stability =~ s/^\s*//;
2051     $stability =~ s/\s*$//;
2052     if ($stability =~ m/^stable$/i) {
2053         $stability = "Stable";
2054     } elsif ($stability =~ m/^unstable$/i) {
2055         $stability = "Unstable";
2056     } elsif ($stability =~ m/^private$/i) {
2057         $stability = "Private";
2058     } else {
2059         &LogWarning ($file, $line, "$message is $stability.".
2060             "It should be one of these: Stable, Unstable, or Private.");
2061     }
2062     return $stability;
2066 #############################################################################
2067 # Function    : OutputSGMLFile
2068 # Description : Outputs the final DocBook file for one section.
2069 # Arguments   : $file - the name of the file.
2070 #               $title - the title from the $MODULE-sections.txt file, which
2071 #                 will be overridden by the title in the template file.
2072 #               $section_id - the SGML id to use for the toplevel tag.
2073 #               $includes - comma-separates list of include files added at top
2074 #                 of synopsis, with '<' '>' around them (if not already enclosed in "").
2075 #               $synopsis - reference to the DocBook for the Synopsis part.
2076 #               $details - reference to the DocBook for the Details part.
2077 #               $signal_synop - reference to the DocBook for the Signal Synopsis part
2078 #               $signal_desc - reference to the DocBook for the Signal Description part
2079 #               $args_synop - reference to the DocBook for the Arg Synopsis part
2080 #               $args_desc - reference to the DocBook for the Arg Description part
2081 #               $hierarchy - reference to the DocBook for the Object Hierarchy part
2082 #               $interfaces - reference to the DocBook for the Interfaces part
2083 #               $implementations - reference to the DocBook for the Known Implementations part
2084 #               $prerequisites - reference to the DocBook for the Prerequisites part
2085 #               $derived - reference to the DocBook for the Derived Interfaces part
2086 #               $file_objects - reference to an array of objects in this file
2087 #############################################################################
2089 sub OutputSGMLFile {
2090     my ($file, $title, $section_id, $includes, $synopsis, $details, $signals_synop, $signals_desc, $args_synop, $args_desc, $hierarchy, $interfaces, $implementations, $prerequisites, $derived, $file_objects) = @_;
2092     #print "Output sgml for file $file with title '$title'\n";
2093     
2094     # The edited title overrides the one from the sections file.
2095     my $new_title = $SymbolDocs{"$TMPL_DIR/$file:Title"};
2096     if (defined ($new_title) && $new_title !~ m/^\s*$/) {
2097         $title = $new_title;
2098         #print "Found title: $title\n";
2099     }
2100     my $short_desc = $SymbolDocs{"$TMPL_DIR/$file:Short_Description"};
2101     if (!defined ($short_desc) || $short_desc =~ m/^\s*$/) {
2102         $short_desc = "";
2103     } else {
2104         $short_desc = &ExpandAbbreviations("$title:Short_description",
2105                                            $short_desc);
2106         #print "Found short_desc: $short_desc";
2107     }
2108     my $long_desc = $SymbolDocs{"$TMPL_DIR/$file:Long_Description"};
2109     if (!defined ($long_desc) || $long_desc =~ m/^\s*$/) {
2110         $long_desc = "";
2111     } else {
2112         $long_desc = &ExpandAbbreviations("$title:Long_description",
2113                                           $long_desc);
2114         #print "Found long_desc: $long_desc";
2115     }
2116     my $see_also = $SymbolDocs{"$TMPL_DIR/$file:See_Also"};
2117     if (!defined ($see_also) || $see_also =~ m%^\s*(<para>)?\s*(</para>)?\s*$%) {
2118         $see_also = "";
2119     } else {
2120         $see_also = &ExpandAbbreviations("$title:See_Also", $see_also);
2121         #print "Found see_also: $see_also";
2122     }
2123     if ($see_also) {
2124         $see_also = "<refsect1 id=\"$section_id.see-also\">\n<title>See Also</title>\n$see_also\n</refsect1>\n";
2125     }
2126     my $stability = $SymbolDocs{"$TMPL_DIR/$file:Stability_Level"};
2127     if (!defined ($stability) || $stability =~ m/^\s*$/) {
2128         $stability = "";
2129     } else {
2130         $stability = &ParseStabilityLevel($stability, $file, $., "Section stability level");
2131         #print "Found stability: $stability";
2132     }
2133     if ($stability) {
2134         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$stability, unless otherwise indicated\n</refsect1>\n";
2135     } elsif ($DEFAULT_STABILITY) {
2136         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$DEFAULT_STABILITY, unless otherwise indicated\n</refsect1>\n";
2137     }
2139     my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
2140         gmtime (time);
2141     my $month = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))[$mon];
2142     $year += 1900;
2144     my $include_output = "";
2145     my $include;
2146     foreach $include (split (/,/, $includes)) {
2147         if ($include =~ m/^\".+\"$/) {
2148             $include_output .= "#include ${include}\n";
2149         }
2150         else {
2151             $include =~ s/^\s+|\s+$//gs;
2152             $include_output .= "#include &lt;${include}&gt;\n";
2153         }
2154     }
2155     if ($include_output ne '') {
2156         $include_output = "\n$include_output\n";
2157     }
2158     
2159     my $extralinks = OutputSectionExtraLinks($title,"Section:$file");
2161     my $old_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT";
2162     my $new_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT.new";
2164     open (OUTPUT, ">$new_sgml_file")
2165         || die "Can't create $new_sgml_file: $!";
2167     my $object_anchors = "";
2168     foreach my $object (@$file_objects) {
2169         next if ($object eq $section_id);
2170         my $id = CreateValidSGMLID($object);
2171         #print "Debug: Adding anchor for $object\n";
2172         $object_anchors .= "<anchor id=\"$id\"$empty_element_end";
2173     }
2175     # We used to output this, but is messes up our UpdateFileIfChanged code
2176     # since it changes every day (and it is only used in the man pages):
2177     # "<refentry id="$section_id" revision="$mday $month $year">"
2179     if (lc($OUTPUT_FORMAT) eq "xml") {
2180         print OUTPUT $doctype_header;
2181     }
2183     print OUTPUT <<EOF;
2184 <refentry id="$section_id">
2185 <refmeta>
2186 <refentrytitle role="top_of_page" id="$section_id.top_of_page">$title</refentrytitle>
2187 <manvolnum>3</manvolnum>
2188 <refmiscinfo>\U$MODULE\E Library</refmiscinfo>
2189 </refmeta>
2190 <refnamediv>
2191 <refname>$title</refname>
2192 <refpurpose>$short_desc</refpurpose>
2193 </refnamediv>
2194 $stability
2195 <refsynopsisdiv id="$section_id.synopsis" role="synopsis">
2196 <title role="synopsis.title">Synopsis</title>
2197 $object_anchors
2198 <synopsis>$include_output$${synopsis}</synopsis>
2199 </refsynopsisdiv>
2200 $$hierarchy$$prerequisites$$derived$$interfaces$$implementations$$args_synop$$signals_synop
2201 <refsect1 id="$section_id.description" role="desc">
2202 <title role="desc.title">Description</title>
2203 $extralinks$long_desc
2204 </refsect1>
2205 <refsect1 id="$section_id.details" role="details">
2206 <title role="details.title">Details</title>
2207 $$details
2208 </refsect1>
2209 $$args_desc$$signals_desc$see_also
2210 </refentry>
2212     close (OUTPUT);
2214     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2218 #############################################################################
2219 # Function    : OutputExtraFile
2220 # Description : Copies an "extra" DocBook file into the output directory,
2221 #               expanding abbreviations
2222 # Arguments   : $file - the source file.
2223 #############################################################################
2224 sub OutputExtraFile {
2225     my ($file) = @_;
2227     my $basename;
2229     ($basename = $file) =~ s!^.*/!!;
2231     my $old_sgml_file = "$SGML_OUTPUT_DIR/$basename";
2232     my $new_sgml_file = "$SGML_OUTPUT_DIR/$basename.new";
2234     my $contents;
2236     open(EXTRA_FILE, "<$file") || die "Can't open $file";
2238     {
2239         local $/;
2240         $contents = <EXTRA_FILE>;
2241     }
2243     open (OUTPUT, ">$new_sgml_file")
2244         || die "Can't create $new_sgml_file: $!";
2246     print OUTPUT &ExpandAbbreviations ("$basename file", $contents);
2247     close (OUTPUT);
2249     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2251 #############################################################################
2252 # Function    : OutputBook
2253 # Description : Outputs the SGML entities that need to be included into the
2254 #               main SGML file for the module.
2255 # Arguments   : $book_top - the declarations of the entities, which are added
2256 #                 at the top of the main SGML file.
2257 #               $book_bottom - the references to the entities, which are
2258 #                 added in the main SGML file at the desired position.
2259 #############################################################################
2261 sub OutputBook {
2262     my ($book_top, $book_bottom) = @_;
2264     my $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top";
2265     my $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top.new";
2267     open (OUTPUT, ">$new_file")
2268         || die "Can't create $new_file: $!";
2269     print OUTPUT $book_top;
2270     close (OUTPUT);
2272     &UpdateFileIfChanged ($old_file, $new_file, 0);
2275     $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom";
2276     $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom.new";
2278     open (OUTPUT, ">$new_file")
2279         || die "Can't create $new_file: $!";
2280     print OUTPUT $book_bottom;
2281     close (OUTPUT);
2283     &UpdateFileIfChanged ($old_file, $new_file, 0);
2286     # If the main SGML file hasn't been created yet, we create it here.
2287     # The user can tweak it later.
2288     if ($MAIN_SGML_FILE && ! -e $MAIN_SGML_FILE) {
2289       open (OUTPUT, ">$MAIN_SGML_FILE")
2290         || die "Can't create $MAIN_SGML_FILE: $!";
2292       if (lc($OUTPUT_FORMAT) eq "xml") {
2293           print OUTPUT <<EOF;
2294 <?xml version="1.0"?>
2295 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
2296                "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd"
2298   <!ENTITY % local.common.attrib "xmlns:xi  CDATA  #FIXED 'http://www.w3.org/2003/XInclude'">
2300 <book id="index">
2302       } else {
2303         print OUTPUT <<EOF;
2304 <!doctype book PUBLIC "-//Davenport//DTD DocBook V3.0//EN" [
2305 $book_top
2307 <book id="index">
2309       }
2311 print OUTPUT <<EOF;
2312   <bookinfo>
2313     <title>$MODULE Reference Manual</title>
2314     <releaseinfo>
2315       for $MODULE [VERSION].
2316       The latest version of this documentation can be found on-line at
2317       <ulink role="online-location" url="http://[SERVER]/$MODULE/index.html">http://[SERVER]/$MODULE/</ulink>.
2318     </releaseinfo>
2319   </bookinfo>
2321   <chapter>
2322     <title>[Insert title here]</title>
2323     $book_bottom
2324   </chapter>
2326   if (-e $OBJECT_TREE_FILE) {
2327     print OUTPUT <<EOF;
2328   <chapter id="object-tree">
2329     <title>Object Hierarchy</title>
2330      <xi:include href="xml/tree_index.sgml"/>
2331   </chapter>
2333   }
2335 print OUTPUT <<EOF;
2336   <index id="api-index-full">
2337     <title>API Index</title>
2338     <xi:include href="xml/api-index-full.xml"><xi:fallback /></xi:include>
2339   </index>
2341   <xi:include href="xml/annotation-glossary.xml"><xi:fallback /></xi:include>
2342 </book>
2345       close (OUTPUT);
2346     }
2350 #############################################################################
2351 # Function    : CreateValidSGML
2352 # Description : This turns any chars which are used in SGML into entities,
2353 #               e.g. '<' into '&lt;'
2354 # Arguments   : $text - the text to turn into proper SGML.
2355 #############################################################################
2357 sub CreateValidSGML {
2358     my ($text) = @_;
2359     $text =~ s/&/&amp;/g;       # Do this first, or the others get messed up.
2360     $text =~ s/</&lt;/g;
2361     $text =~ s/>/&gt;/g;
2362     # browers render single tabs inconsistently
2363     $text =~ s/([^\s])\t([^\s])/$1&#160;$2/g;
2364     return $text;
2367 #############################################################################
2368 # Function    : ConvertSGMLChars
2369 # Description : This is used for text in source code comment blocks, to turn
2370 #               chars which are used in SGML into entities, e.g. '<' into
2371 #               '&lt;'. Depending on $SGML_MODE, this is done
2372 #               unconditionally or only if the character doesn't seem to be
2373 #               part of an SGML construct (tag or entity reference).
2374 # Arguments   : $text - the text to turn into proper SGML.
2375 #############################################################################
2377 sub ConvertSGMLChars {
2378     my ($symbol, $text) = @_;
2380     if ($SGML_MODE) {
2381         # For the SGML mode only convert to entities outside CDATA sections.
2382         return &ModifyXMLElements ($text, $symbol,
2383                                    "<!\\[CDATA\\[|<programlisting[^>]*>",
2384                                    \&ConvertSGMLCharsEndTag,
2385                                    \&ConvertSGMLCharsCallback);
2386     } else {
2387         # For the simple non-sgml mode, convert to entities everywhere.
2388         $text =~ s/&/&amp;/g;   # Do this first, or the others get messed up.
2389         $text =~ s/</&lt;/g;
2390         $text =~ s/>/&gt;/g;
2391         return $text;
2392     }
2396 sub ConvertSGMLCharsEndTag {
2397   if ($_[0] eq "<!\[CDATA\[") {
2398     return "]]>";
2399   } else {
2400     return "</programlisting>";
2401   }
2404 sub ConvertSGMLCharsCallback {
2405   my ($text, $symbol, $tag) = @_;
2407   if ($tag =~ m/^<programlisting/) {
2408     # We can handle <programlisting> specially here.
2409     return &ModifyXMLElements ($text, $symbol,
2410                                "<!\\[CDATA\\[",
2411                                \&ConvertSGMLCharsEndTag,
2412                                \&ConvertSGMLCharsCallback2);
2413   } elsif ($tag eq "") {
2414     # If we're not in CDATA convert to entities.
2415     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2416     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2417     $text =~ s/(?<![a-zA-Z0-9"'\/-])>/&gt;/g;
2419     # Handle "#include <xxxxx>"
2420     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2421   }
2423   return $text;
2426 sub ConvertSGMLCharsCallback2 {
2427   my ($text, $symbol, $tag) = @_;
2429   # If we're not in CDATA convert to entities.
2430   # We could handle <programlisting> differently, though I'm not sure it helps.
2431   if ($tag eq "") {
2432     # replace only if its not a tag
2433     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2434     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2435     $text =~ s/(?<![a-zA-Z0-9"'\/-])>/&gt;/g;
2437     # Handle "#include <xxxxx>"
2438     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2439   }
2441   return $text;
2444 #############################################################################
2445 # Function    : ExpandAnnotation
2446 # Description : This turns annotations into acrony tags.
2447 # Arguments   : $symbol - the symbol being documented, for error messages.
2448 #               $text - the text to expand.
2449 #############################################################################
2450 sub ExpandAnnotation {
2451     my ($symbol, $param_desc) = @_;
2452     my $param_annotations = "";
2453     
2454     if ($param_desc =~ m%\s*\((.*)\):%) {
2455         my @annotations;
2456         my $annotation;
2457         my $annotation_extra = "";
2458         $param_desc = $';
2459     
2460         @annotations = split(/\)\s*\(/,$1);
2461         foreach $annotation (@annotations) {
2462             # need to search for the longest key-match in %AnnotationDefinition
2463             my $match_length=0;
2464             my $match_annotation="";
2465             my $annotationdef;
2466             foreach $annotationdef (keys %AnnotationDefinition) {
2467                 if ($annotation =~ m/^$annotationdef/) {
2468                     if (length($annotationdef)>$match_length) {
2469                         $match_length=length($annotationdef);
2470                         $match_annotation=$annotationdef;
2471                     }
2472                 }
2473             }
2474             if ($match_annotation ne "") {
2475                 if ($annotation =~ m%$match_annotation\s+(.*)%) {
2476                     $annotation_extra = " $1";
2477                 }
2478                 $AnnotationsUsed{$match_annotation} = 1;
2479                 $param_annotations .= "<acronym>$match_annotation</acronym>$annotation_extra. ";
2480             }
2481             else {
2482                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2483                     "unknown annotation \"$annotation\" in documentation for $symbol.");
2484                 $param_annotations=$annotation;
2485             }
2486         }
2487         chomp($param_desc);
2488         $param_desc =~ m/^(.*)\.*\s*$/;
2489         $param_desc = "$1. ";
2490     }    
2491     return ($param_desc, $param_annotations);
2494 #############################################################################
2495 # Function    : ExpandAbbreviations
2496 # Description : This turns the abbreviations function(), macro(), @param,
2497 #               %constant, and #symbol into appropriate DocBook markup.
2498 #               CDATA sections and <programlisting> parts are skipped.
2499 # Arguments   : $symbol - the symbol being documented, for error messages.
2500 #               $text - the text to expand.
2501 #############################################################################
2503 sub ExpandAbbreviations {
2504   my ($symbol, $text) = @_;
2506   # Convert "|[" and "]|" into the start and end of program listing examples.
2507   $text =~ s%\|\[%<informalexample><programlisting>%g;
2508   $text =~ s%\]\|%</programlisting></informalexample>%g;
2509   # TODO: check for a xml comment after |[ and pick the language attribute from
2510   # that
2512   # keep CDATA unmodified, preserve ulink tags (ideally we preseve all tags
2513   # as such)
2514   return &ModifyXMLElements ($text, $symbol,
2515                              "<!\\[CDATA\\[|<ulink[^>]*>|<programlisting[^>]*>|<!DOCTYPE",
2516                              \&ExpandAbbreviationsEndTag,
2517                              \&ExpandAbbreviationsCallback);
2521 # Returns the end tag corresponding to the given start tag.
2522 sub ExpandAbbreviationsEndTag {
2523   my ($start_tag) = @_;
2525   if ($start_tag eq "<!\[CDATA\[") {
2526     return "]]>";
2527   } elsif ($start_tag eq "<!DOCTYPE") {
2528     return "]>";
2529   } elsif ($start_tag =~ m/<(\w+)/) {
2530     return "</$1>";
2531   }
2534 # Called inside or outside each CDATA or <programlisting> section.
2535 sub ExpandAbbreviationsCallback {
2536   my ($text, $symbol, $tag) = @_;
2538   if ($tag =~ m/^<programlisting/) {
2539     # Handle any embedded CDATA sections.
2540     return &ModifyXMLElements ($text, $symbol,
2541                                "<!\\[CDATA\\[",
2542                                \&ExpandAbbreviationsEndTag,
2543                                \&ExpandAbbreviationsCallback2);
2544   } elsif ($tag eq "") {
2545     # We are outside any CDATA or <programlisting> sections, so we expand
2546     # any gtk-doc abbreviations.
2548     # Convert 'function()' or 'macro()'.
2549     # if there is abc_*_def() we don't want to make a link to _def()
2550     # FIXME: also handle abc(....) : but that would need to be done recursively :/
2551     $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2552     # handle #Object.func()
2553     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2555     # Convert '@param', but not '\@param'.
2556     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)/$1<parameter>$2<\/parameter>/g;
2557     $text =~ s/\\\@/\@/g;
2559     # Convert '%constant', but not '\%constant'.
2560     # Also allow negative numbers, e.g. %-1.
2561     $text =~ s/(\A|[^\\])\%(-?\w+)/$1.&MakeXRef($2, &tagify($2, "literal"));/eg;
2562     $text =~ s/\\\%/\%/g;
2564     # Convert '#symbol', but not '\#symbol'.
2565     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)/$1.&MakeHashXRef($2, "type");/eg;
2566     $text =~ s/\\#/#/g;
2567     
2568     # Expand urls
2569     # FIXME: should we skip urls that are already tagged? (e.g. <literal>http://...</literal>)
2570     # this is apparently also called for markup and not just for plain text
2571     # disable for now.
2572     #$text =~ s%(http|https|ftp)://(.*?)((?:\s|,|\)|\]|\<|\.\s))%<ulink url="$1://$2">$2</ulink>$3%g;
2573   }
2575   return $text;
2578 # This is called inside a <programlisting>
2579 sub ExpandAbbreviationsCallback2 {
2580   my ($text, $symbol, $tag) = @_;
2582   if ($tag eq "") {
2583     # We are inside a <programlisting> but outside any CDATA sections,
2584     # so we expand any gtk-doc abbreviations.
2585     # FIXME: why is this different from &ExpandAbbreviationsCallback(),
2586     #        why not just call it
2587     $text =~ s/#(\w+)/&MakeHashXRef($1, "");/eg;
2588   }
2590   return $text;
2593 sub MakeHashXRef {
2594     my ($symbol, $tag) = @_;;
2595     my $text = $symbol;
2597     # Check for things like '#include', '#define', and skip them.
2598     if ($PreProcessorDirectives{$symbol}) {
2599       return "#$symbol";
2600     }
2602     # Get rid of any special '-struct' suffix.
2603     $text =~ s/-struct$//;
2605     # If the symbol is in the form "Object::signal", then change the symbol to
2606     # "Object-signal" and use "signal" as the text.
2607     if ($symbol =~ s/::/-/) {
2608       $text = "\"$'\"";
2609     }
2611     # If the symbol is in the form "Object:property", then change the symbol to
2612     # "Object--property" and use "property" as the text.
2613     if ($symbol =~ s/:/--/) {
2614       $text = "\"$'\"";
2615     }
2617     if ($tag ne "") {
2618       $text = tagify ($text, $tag);
2619     }
2620     
2621     return &MakeXRef($symbol, $text);
2625 #############################################################################
2626 # Function    : ModifyXMLElements
2627 # Description : Looks for given XML element tags within the text, and calls
2628 #               the callback on pieces of text inside & outside those elements.
2629 #               Used for special handling of text inside things like CDATA
2630 #               and <programlisting>.
2631 # Arguments   : $text - the text.
2632 #               $symbol - the symbol currently being documented (only used for
2633 #                      error messages).
2634 #               $start_tag_regexp - the regular expression to match start tags.
2635 #                      e.g. "<!\\[CDATA\\[|<programlisting[^>]*>" to match
2636 #                      CDATA sections or programlisting elements.
2637 #               $end_tag_func - function which is passed the matched start tag
2638 #                      and should return the appropriate end tag string.
2639 #               $callback - callback called with each part of the text. It is
2640 #                      called with a piece of text, the symbol being
2641 #                      documented, and the matched start tag or "" if the text
2642 #                      is outside the XML elements being matched.
2643 #############################################################################
2644 sub ModifyXMLElements {
2645     my ($text, $symbol, $start_tag_regexp, $end_tag_func, $callback) = @_;
2646     my ($before_tag, $start_tag, $end_tag_regexp, $end_tag);
2647     my $result = "";
2649     while ($text =~ m/$start_tag_regexp/s) {
2650       $before_tag = $`; # Prematch for last successful match string
2651       $start_tag = $&;  # Last successful match
2652       $text = $';       # Postmatch for last successful match string
2654       $result .= &$callback ($before_tag, $symbol, "");
2655       $result .= $start_tag;
2657       # get the mathing end-tag for current tag
2658       $end_tag_regexp = &$end_tag_func ($start_tag);
2660       if ($text =~ m/$end_tag_regexp/s) {
2661         $before_tag = $`;
2662         $end_tag = $&;
2663         $text = $';
2665         $result .= &$callback ($before_tag, $symbol, $start_tag);
2666         $result .= $end_tag;
2667       } else {
2668         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2669             "Can't find tag end: $end_tag_regexp in docs for: $symbol.");
2670         # Just assume it is all inside the tag.
2671         $result .= &$callback ($text, $symbol, $start_tag);
2672         $text = "";
2673       }
2674     }
2676     # Handle any remaining text outside the tags.
2677     $result .= &$callback ($text, $symbol, "");
2679     return $result;
2682 sub noop {
2683   return $_[0];
2686 # Adds a tag around some text.
2687 # e.g tagify("Text", "literal") => "<literal>Text</literal>".
2688 sub tagify {
2689    my ($text, $elem) = @_;
2690    return "<" . $elem . ">" . $text . "</" . $elem . ">";
2694 #############################################################################
2695 # Function    : MakeXRef
2696 # Description : This returns a cross-reference link to the given symbol.
2697 #               Though it doesn't try to do this for a few standard C types
2698 #               that it knows won't be in the documentation.
2699 # Arguments   : $symbol - the symbol to try to create a XRef to.
2700 #               $text - text text to put inside the XRef, defaults to $symbol
2701 #############################################################################
2703 sub MakeXRef {
2704     my ($symbol, $text) = ($_[0], $_[1]);
2706     $symbol =~ s/^\s+//;
2707     $symbol =~ s/\s+$//;
2709     if (!defined($text)) {
2710         $text = $symbol;
2712         # Get rid of special '-struct' suffix.
2713         $text =~ s/-struct$//;
2714     }
2716     if ($symbol =~ m/ /) {
2717         return "$text";
2718     }
2720     #print "Getting type link for $symbol -> $text\n";
2722     my $symbol_id = &CreateValidSGMLID ($symbol);
2723     return "<link linkend=\"$symbol_id\">$text</link>";
2727 #############################################################################
2728 # Function    : MakeIndexterms
2729 # Description : This returns a indexterm elements for the given symbol
2730 # Arguments   : $symbol - the symbol to create indexterms for
2731 #############################################################################
2733 sub MakeIndexterms {
2734   my ($symbol, $id) = @_;
2735   my $terms =  "";
2736   my $sortas = "";
2737   
2738   # make the index useful, by ommiting the namespace when sorting
2739   if ($NAME_SPACE ne "") {
2740     if ($symbol =~ m/^$NAME_SPACE\_?(.*)/i) {
2741        $sortas=" sortas=\"$1\"";
2742     }
2743   }
2745   if (exists $Deprecated{$symbol}) {
2746       $terms .= "<indexterm zone=\"$id\" role=\"deprecated\"><primary$sortas>$symbol</primary></indexterm>";
2747       $IndexEntriesDeprecated{$symbol}=$id;
2748       $IndexEntriesFull{$symbol}=$id;
2749   }
2750   if (exists $Since{$symbol}) {
2751      my $since = $Since{$symbol};
2752      $since =~ s/^\s+//;
2753      $since =~ s/\s+$//;
2754      if ($since ne "") {
2755          $terms .= "<indexterm zone=\"$id\" role=\"$since\"><primary$sortas>$symbol</primary></indexterm>";
2756      }
2757      $IndexEntriesSince{$symbol}=$id;
2758      $IndexEntriesFull{$symbol}=$id;
2759   }
2760   if ($terms eq "") {
2761      $terms .= "<indexterm zone=\"$id\"><primary$sortas>$symbol</primary></indexterm>";
2762      $IndexEntriesFull{$symbol}=$id;
2763   }
2765   return $terms;
2768 #############################################################################
2769 # Function    : MakeDeprecationNote
2770 # Description : This returns a deprecation warning for the given symbol.
2771 # Arguments   : $symbol - the symbol to try to create a warning for.
2772 #############################################################################
2774 sub MakeDeprecationNote {
2775     my ($symbol) = $_[0];
2776     my $desc = "";
2777     my $note = "";
2778     if (exists $Deprecated{$symbol}) {
2779         $desc .= "<warning>";
2781         if ($Deprecated{$symbol} =~ /^\s*([0-9\.]+)\s*:/) {
2782                 $desc .= "<para><literal>$symbol</literal> has been deprecated since version $1 and should not be used in newly-written code.";
2783         } else {
2784                 $desc .= "<para><literal>$symbol</literal> is deprecated and should not be used in newly-written code.";
2785         }
2786         if ($Deprecated{$symbol} ne "") {
2787             $note = &ExpandAbbreviations($symbol, $Deprecated{$symbol});
2788             $note =~ s/^\s*([0-9\.]+)\s*:\s*//;
2789             $note =~ s/^\s+//;
2790             $note =~ s/\s+$//;
2791             $note =~ s%\n{2,}%\n</para>\n<para>\n%g;
2792             $desc .= " " . $note;
2793         }
2794         $desc .= "</para></warning>\n";
2795     }
2796     return $desc;
2799 #############################################################################
2800 # Function    : MakeConditionDescription
2801 # Description : This returns a sumary of conditions for the given symbol.
2802 # Arguments   : $symbol - the symbol to try to create the sumary.
2803 #############################################################################
2805 sub MakeConditionDescription {
2806     my ($symbol) = $_[0];
2807     my $desc = "";
2809     if (exists $Deprecated{$symbol}) {
2810         if ($desc ne "") {
2811             $desc .= "|";
2812         }
2814         if ($Deprecated{$symbol} =~ /^\s*(.*?)\s*$/) {
2815                 $desc .= "deprecated:$1";
2816         } else {
2817                 $desc .= "deprecated";
2818         }
2819     }
2821     if (exists $Since{$symbol}) {
2822         if ($desc ne "") {
2823             $desc .= "|";
2824         }
2826         if ($Since{$symbol} =~ /^\s*(.*?)\s*$/) {
2827                 $desc .= "since:$1";
2828         } else {
2829                 $desc .= "since";
2830         }
2831     }
2833     if (exists $StabilityLevel{$symbol}) {
2834         if ($desc ne "") {
2835             $desc .= "|";
2836         }
2837         $desc .= "stability:".$StabilityLevel{$symbol};
2838     }
2840     if ($desc ne "") {
2841         $desc=" condition=\"".$desc."\"";
2842         #print "condition for '$symbol' = '$desc'\n";
2843     }
2844     return $desc;
2847 #############################################################################
2848 # Function    : GetHierarchy
2849 # Description : Returns the DocBook output describing the ancestors and
2850 #               immediate children of a GObject subclass. It uses the
2851 #               global @Objects and @ObjectLevels arrays to walk the tree.
2852 # Arguments   : $object - the GtkObject subclass.
2853 #############################################################################
2855 sub GetHierarchy {
2856     my ($object) = @_;
2858     # Find object in the objects array.
2859     my $found = 0;
2860     my @children = ();
2861     my $i;
2862     my $level;
2863     my $j;
2864     for ($i = 0; $i < @Objects; $i++) {
2865         if ($found) {
2866             if ($ObjectLevels[$i] <= $level) {
2867             last;
2868         }
2869             elsif ($ObjectLevels[$i] == $level + 1) {
2870                 push (@children, $Objects[$i]);
2871             }
2872         }
2873         elsif ($Objects[$i] eq $object) {
2874             $found = 1;
2875             $j = $i;
2876             $level = $ObjectLevels[$i];
2877         }
2878     }
2879     if (!$found) {
2880         return "";
2881     }
2883     # Walk up the hierarchy, pushing ancestors onto the ancestors array.
2884     my @ancestors = ();
2885     push (@ancestors, $object);
2886     #print "Level: $level\n";
2887     while ($level > 1) {
2888         $j--;
2889         if ($ObjectLevels[$j] < $level) {
2890             push (@ancestors, $Objects[$j]);
2891             $level = $ObjectLevels[$j];
2892             #print "Level: $level\n";
2893         }
2894     }
2896     # Output the ancestors list, indented and with links.
2897     my $hierarchy = "<synopsis>\n";
2898     $level = 0;
2899     for ($i = $#ancestors; $i >= 0; $i--) {
2900         my $link_text;
2901         # Don't add a link to the current widget, i.e. when i == 0.
2902         if ($i > 0) {
2903             my $ancestor_id = &CreateValidSGMLID ($ancestors[$i]);
2904             $link_text = "<link linkend=\"$ancestor_id\">$ancestors[$i]</link>";
2905         } else {
2906             $link_text = "$ancestors[$i]";
2907         }
2908         if ($level == 0) {
2909             $hierarchy .= "  $link_text\n";
2910         } else {
2911 #           $hierarchy .= ' ' x ($level * 6 - 3) . "|\n";
2912             $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
2913         }
2914         $level++;
2915     }
2916     for ($i = 0; $i <= $#children; $i++) {
2917       my $id = &CreateValidSGMLID ($children[$i]);
2918       my $link_text = "<link linkend=\"$id\">$children[$i]</link>";
2919       $hierarchy .= ' ' x ($level * 6 - 3) . "+----$link_text\n";
2920     }
2921     $hierarchy .= "</synopsis>\n";
2923     return $hierarchy;
2927 #############################################################################
2928 # Function    : GetInterfaces
2929 # Description : Returns the DocBook output describing the interfaces
2930 #               implemented by a class. It uses the global %Interfaces hash.
2931 # Arguments   : $object - the GtkObject subclass.
2932 #############################################################################
2934 sub GetInterfaces {
2935     my ($object) = @_;
2936     my $text = "";
2937     my $i;
2939     # Find object in the objects array.
2940     if (exists($Interfaces{$object})) {
2941         my @ifaces = split(' ', $Interfaces{$object});
2942         $text = <<EOF;
2943 <para>
2944 $object implements
2946         for ($i = 0; $i <= $#ifaces; $i++) {
2947             my $id = &CreateValidSGMLID ($ifaces[$i]);
2948             $text .= " <link linkend=\"$id\">$ifaces[$i]</link>";
2949             if ($i < $#ifaces - 1) {
2950                 $text .= ', ';
2951             }
2952             elsif ($i < $#ifaces) {
2953                 $text .= ' and ';
2954             }
2955             else {
2956                 $text .= '.';
2957             }
2958         }
2959         $text .= <<EOF;
2960 </para>
2962     }
2964     return $text;
2967 #############################################################################
2968 # Function    : GetImplementations
2969 # Description : Returns the DocBook output describing the implementations
2970 #               of an interface. It uses the global %Interfaces hash.
2971 # Arguments   : $object - the GtkObject subclass.
2972 #############################################################################
2974 sub GetImplementations {
2975     my ($object) = @_;
2976     my @impls = ();
2977     my $text = "";
2978     my $i;
2979     foreach my $key (keys %Interfaces) {
2980         if ($Interfaces{$key} =~ /\b$object\b/) {
2981             push (@impls, $key);
2982         }
2983     }
2984     if ($#impls >= 0) {
2985         $text = <<EOF;
2986 <para>
2987 $object is implemented by
2989         for ($i = 0; $i <= $#impls; $i++) {
2990             my $id = &CreateValidSGMLID ($impls[$i]);
2991             $text .= " <link linkend=\"$id\">$impls[$i]</link>";
2992             if ($i < $#impls - 1) {
2993                 $text .= ', ';
2994             }
2995             elsif ($i < $#impls) {
2996                 $text .= ' and ';
2997             }
2998             else {
2999                 $text .= '.';
3000             }
3001         }
3002         $text .= <<EOF;
3003 </para>
3005     }
3006     return $text;
3010 #############################################################################
3011 # Function    : GetPrerequisites
3012 # Description : Returns the DocBook output describing the prerequisites
3013 #               of an interface. It uses the global %Prerequisites hash.
3014 # Arguments   : $iface - the interface.
3015 #############################################################################
3017 sub GetPrerequisites {
3018     my ($iface) = @_;
3019     my $text = "";
3020     my $i;
3022     if (exists($Prerequisites{$iface})) {
3023         $text = <<EOF;
3024 <para>
3025 $iface requires
3027         my @prereqs = split(' ', $Prerequisites{$iface});
3028         for ($i = 0; $i <= $#prereqs; $i++) {
3029             my $id = &CreateValidSGMLID ($prereqs[$i]);
3030             $text .= " <link linkend=\"$id\">$prereqs[$i]</link>";
3031             if ($i < $#prereqs - 1) {
3032                 $text .= ', ';
3033             }
3034             elsif ($i < $#prereqs) {
3035                 $text .= ' and ';
3036             }
3037             else {
3038                 $text .= '.';
3039             }
3040         }
3041         $text .= <<EOF;
3042 </para>
3044     }
3045     return $text;
3048 #############################################################################
3049 # Function    : GetDerived
3050 # Description : Returns the DocBook output describing the derived interfaces
3051 #               of an interface. It uses the global %Prerequisites hash.
3052 # Arguments   : $iface - the interface.
3053 #############################################################################
3055 sub GetDerived {
3056     my ($iface) = @_;
3057     my $text = "";
3058     my $i;
3060     my @derived = ();
3061     foreach my $key (keys %Prerequisites) {
3062         if ($Prerequisites{$key} =~ /\b$iface\b/) {
3063             push (@derived, $key);
3064         }
3065     }
3066     if ($#derived >= 0) {
3067         $text = <<EOF;
3068 <para>
3069 $iface is required by
3071         for ($i = 0; $i <= $#derived; $i++) {
3072             my $id = &CreateValidSGMLID ($derived[$i]);
3073             $text .= " <link linkend=\"$id\">$derived[$i]</link>";
3074             if ($i < $#derived - 1) {
3075                 $text .= ', ';
3076             }
3077             elsif ($i < $#derived) {
3078                 $text .= ' and ';
3079             }
3080             else {
3081                 $text .= '.';
3082             }
3083         }
3084         $text .= <<EOF;
3085 </para>
3087     }
3088     return $text;
3092 #############################################################################
3093 # Function    : GetSignals
3094 # Description : Returns the synopsis and detailed description DocBook output
3095 #               for the signal handlers of a given GtkObject subclass.
3096 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3097 #############################################################################
3099 sub GetSignals {
3100     my ($object) = @_;
3101     my $synop = "";
3102     my $desc = "";
3104     my $i;
3105     for ($i = 0; $i <= $#SignalObjects; $i++) {
3106         if ($SignalObjects[$i] eq $object) {
3107             #print "Found signal: $SignalNames[$i]\n";
3108             my $name = $SignalNames[$i];
3109             my $symbol = "${object}::${name}";
3110             my $id = &CreateValidSGMLID ("$object-$name");
3112             my $pad = ' ' x (46 - length($name));
3113             $synop .= "  &quot;<link linkend=\"$id\">$name</link>&quot;$pad ";
3115             $desc .= "<refsect2 id=\"$id\" role=\"signal\"><title>The <literal>&quot;$name&quot;</literal> signal</title>\n";
3116             $desc .= MakeIndexterms($symbol, $id);
3117             $desc .= "\n";
3118             $desc .= OutputSymbolExtraLinks($symbol);
3120             $desc .= "<programlisting>";
3122             $SignalReturns[$i] =~ m/\s*(const\s+)?(\w+)\s*(\**)/;
3123             my $type_modifier = defined($1) ? $1 : "";
3124             my $type = $2;
3125             my $pointer = $3;
3126             my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
3128             my $ret_type_len = length ($type_modifier) + length ($pointer)
3129                 + length ($type);
3130             my $ret_type_output = "$type_modifier$xref$pointer"
3131                 . (' ' x ($RETURN_TYPE_FIELD_WIDTH - $ret_type_len));
3133             $desc  .= "${ret_type_output}user_function " . &MakeReturnField("") . " (";
3135             my $sourceparams = $SourceSymbolParams{$symbol};
3136             my @params = split ("\n", $SignalPrototypes[$i]);
3137             my $j;
3138             my $l;
3139             my $type_len = length("gpointer");
3140             my $name_len = length("user_data");
3141             # do two passes, the first one is to calculate padding
3142             for ($l = 0; $l < 2; $l++) {
3143                 for ($j = 0; $j <= $#params; $j++) {
3144                     # allow alphanumerics, '_', '[' & ']' in param names
3145                     if ($params[$j] =~ m/^\s*(\w+)\s*(\**)\s*([\w\[\]]+)\s*$/) {
3146                         $type = $1;
3147                         $pointer = $2;
3148                         if (defined($sourceparams)) {
3149                             $name = $$sourceparams[$PARAM_FIELD_COUNT * $j];
3150                         }
3151                         else {
3152                             $name = $3;
3153                         }
3154                         if (!defined($name)) {
3155                             $name = "arg$j";
3156                         }
3157                         if ($l == 0) {
3158                             if (length($type) + length($pointer) > $type_len) {
3159                                 $type_len = length($type) + length($pointer);
3160                             }
3161                             if (length($name) > $name_len) {
3162                                 $name_len = length($name);
3163                             }
3164                         }
3165                         else {
3166                             $xref = &MakeXRef ($type, &tagify($type, "type"));
3167                             $pad = ' ' x ($type_len - length($type) - length($pointer));
3168                             $desc .= "$xref$pad $pointer$name,\n";
3169                             $desc .= (' ' x ($SYMBOL_FIELD_WIDTH + $RETURN_TYPE_FIELD_WIDTH));
3170                         }
3171                     } else {
3172                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
3173                              "Can't parse arg: $params[$j]\nArgs:$SignalPrototypes[$i]");
3174                     }
3175                 }
3176             }
3177             $xref = &MakeXRef ("gpointer", &tagify("gpointer", "type"));
3178             $pad = ' ' x ($type_len - length("gpointer"));
3179             $desc  .= "$xref$pad user_data)";
3181             my $flags = $SignalFlags[$i];
3182             my $flags_string = "";
3184             if (defined ($flags)) {
3185               if ($flags =~ m/f/) {
3186                 $flags_string = "Run First";
3187               }
3188               elsif ($flags =~ m/l/) {
3189                 $flags_string = "Run Last";
3190               }
3191               elsif ($flags =~ m/c/) {
3192                 $flags_string = "Cleanup";
3193               }
3194               if ($flags =~ m/r/) {
3195                 if ($flags_string) { $flags_string .= " / "; }
3196                 $flags_string .= "No Recursion";
3197               }
3198               if ($flags =~ m/d/) {
3199                 if ($flags_string) { $flags_string .= " / "; }
3200                 $flags_string .= "Has Details";
3201               }
3202               if ($flags =~ m/a/) {
3203                 if ($flags_string) { $flags_string .= " / "; }
3204                 $flags_string .= "Action";
3205               }
3206               if ($flags =~ m/h/) {
3207                 if ($flags_string) { $flags_string .= " / "; }
3208                 $flags_string .= "No Hooks";
3209               }
3210             }
3212             if ($flags_string)
3213               {
3214                 $synop .= ": $flags_string\n";
3216                 $pad = ' ' x (5 + $name_len - length("user_data"));
3217                 $desc  .= "$pad : $flags_string</programlisting>\n";
3218               }
3219             else
3220               {
3221                 $synop .= "\n";
3222                 $desc  .= "</programlisting>\n";
3223               }
3225             $desc .= &MakeDeprecationNote($symbol);
3227             my $parameters = &OutputParamDescriptions ("SIGNAL", $symbol);
3228             my $parameters_output = 0;
3230             $AllSymbols{$symbol} = 1;
3231             if (defined ($SymbolDocs{$symbol})) {
3232                 my $symbol_docs = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
3234                 # Try to insert the parameter table at the author's desired
3235                 # position. Otherwise we need to tag it onto the end.
3236                 if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
3237                   $parameters_output = 1;
3238                 }
3239                 $desc .= $symbol_docs;
3241                 if (!IsEmptyDoc($SymbolDocs{$symbol})) {
3242                     $AllDocumentedSymbols{$symbol} = 1;
3243                 }
3244             }
3246             if ($parameters_output == 0) {
3247                 $desc .= $parameters;
3248               }
3249             $desc .= OutputSymbolTraits ($symbol);
3250             $desc .= "</refsect2>";
3251         }
3252     }
3253     return ($synop, $desc);
3257 #############################################################################
3258 # Function    : GetArgs
3259 # Description : Returns the synopsis and detailed description DocBook output
3260 #               for the Args of a given GtkObject subclass.
3261 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3262 #############################################################################
3264 sub GetArgs {
3265     my ($object) = @_;
3266     my $synop = "";
3267     my $desc = "";
3268     my $child_synop = "";
3269     my $child_desc = "";
3270     my $style_synop = "";
3271     my $style_desc = "";
3273     my $i;
3274     for ($i = 0; $i <= $#ArgObjects; $i++) {
3275         if ($ArgObjects[$i] eq $object) {
3276             #print "Found arg: $ArgNames[$i]\n";
3277             my $name = $ArgNames[$i];
3278             my $flags = $ArgFlags[$i];
3279             my $flags_string = "";
3280             my $kind = "";
3281             my $id_sep = "";
3283             if ($flags =~ m/c/) {
3284                 $kind = "child property";
3285                 $id_sep = "c-";
3286             }
3287             elsif ($flags =~ m/s/) {
3288                 $kind = "style property";
3289                 $id_sep = "s-";
3290             }
3291             else {
3292                 $kind = "property";
3293             }
3295             # Remember only one colon so we don't clash with signals.
3296             my $symbol = "${object}:${name}";
3297             # use two dashes and ev. an extra separator here for the same reason.
3298             my $id = &CreateValidSGMLID ("$object--$id_sep$name");
3300             my $type = $ArgTypes[$i];
3301             my $type_output;
3302             my $range = $ArgRanges[$i];
3303             my $range_output = CreateValidSGML ($range);
3304             my $default = $ArgDefaults[$i];
3305             my $default_output = CreateValidSGML ($default);
3307             if ($type eq "GtkString") {
3308                 $type = "char*";
3309             }
3310             if ($type eq "GtkSignal") {
3311                 $type = "GtkSignalFunc, gpointer";
3312                 $type_output = &MakeXRef ("GtkSignalFunc") . ", "
3313                     . &MakeXRef ("gpointer");
3314             } elsif ($type =~ m/^(\w+)\*$/) {
3315                 $type_output = &MakeXRef ($1, &tagify($1, "type")) . "*";
3316             } else {
3317                 $type_output = &MakeXRef ($type, &tagify($type, "type"));
3318             }
3320             if ($flags =~ m/r/) {
3321                 $flags_string = "Read";
3322             }
3323             if ($flags =~ m/w/) {
3324                 if ($flags_string) { $flags_string .= " / "; }
3325                 $flags_string .= "Write";
3326             }
3327             if ($flags =~ m/x/) {
3328                 if ($flags_string) { $flags_string .= " / "; }
3329                 $flags_string .= "Construct";
3330             }
3331             if ($flags =~ m/X/) {
3332                 if ($flags_string) { $flags_string .= " / "; }
3333                 $flags_string .= "Construct Only";
3334             }
3336             $AllSymbols{$symbol} = 1;
3337             my $blurb;
3338             if (defined($SymbolDocs{$symbol}) &&
3339                 !IsEmptyDoc($SymbolDocs{$symbol})) {
3340                 $blurb = &ExpandAbbreviations($symbol, $SymbolDocs{$symbol});
3341                 #print ".. [$SymbolDocs{$symbol}][$blurb]\n";
3342                 $AllDocumentedSymbols{$symbol} = 1;
3343             }
3344             else {
3345                 if (!($ArgBlurbs[$i] eq "")) {
3346                     $AllDocumentedSymbols{$symbol} = 1;
3347                 } else {
3348                     # FIXME: print a warning?
3349                     #print ".. no description\n";
3350                 }
3351                 $blurb = "<para>" . &CreateValidSGML ($ArgBlurbs[$i]) . "</para>";
3352             }
3354             my $pad1 = " " x (24 - length ($name));
3355             my $pad2 = " " x (20 - length ($type));
3357             my $arg_synop = "  &quot;<link linkend=\"$id\">$name</link>&quot;$pad1 $type_output $pad2 : $flags_string\n";
3358             my $arg_desc = "<refsect2 id=\"$id\" role=\"property\"><title>The <literal>&quot;$name&quot;</literal> $kind</title>\n";
3359             $arg_desc .= MakeIndexterms($symbol, $id);
3360             $arg_desc .= "\n";
3361             $arg_desc .= OutputSymbolExtraLinks($symbol);
3363             $arg_desc .= "<programlisting>  &quot;$name&quot;$pad1 $type_output $pad2 : $flags_string</programlisting>\n";
3364             $arg_desc .= &MakeDeprecationNote($symbol);
3365             $arg_desc .= $blurb;
3366             if ($range ne "") {
3367                 $arg_desc .= "<para>Allowed values: $range_output</para>\n";
3368             }
3369             if ($default ne "") {
3370                 $arg_desc .= "<para>Default value: $default_output</para>\n";
3371             }
3372             $arg_desc .= OutputSymbolTraits ($symbol);
3373             $arg_desc .= "</refsect2>\n";
3375             if ($flags =~ m/c/) {
3376                 $child_synop .= $arg_synop;
3377                 $child_desc .= $arg_desc;
3378             }
3379             elsif ($flags =~ m/s/) {
3380                 $style_synop .= $arg_synop;
3381                 $style_desc .= $arg_desc;
3382             }
3383             else {
3384                 $synop .= $arg_synop;
3385                 $desc .= $arg_desc;
3386             }
3387         }
3388     }
3389     return ($synop, $child_synop, $style_synop, $desc, $child_desc, $style_desc);
3393 #############################################################################
3394 # Function    : ReadSourceDocumentation
3395 # Description : This reads in the documentation embedded in comment blocks
3396 #               in the source code (for Gnome).
3398 #               Parameter descriptions override any in the template files.
3399 #               Function descriptions are placed before any description from
3400 #               the template files.
3402 #               It recursively descends the source directory looking for .c
3403 #               files and scans them looking for specially-formatted comment
3404 #               blocks.
3406 # Arguments   : $source_dir - the directory to scan.
3407 #############m###############################################################
3409 sub ReadSourceDocumentation {
3410     my ($source_dir) = @_;
3411     my ($file, $dir, @suffix_list, $suffix);
3412     #print "Scanning source directory: $source_dir\n";
3414     # This array holds any subdirectories found.
3415     my (@subdirs) = ();
3417     @suffix_list = split (/,/, $SOURCE_SUFFIXES);
3419     opendir (SRCDIR, $source_dir)
3420         || die "Can't open source directory $source_dir: $!";
3422     foreach $file (readdir (SRCDIR)) {
3423       if ($file =~ /^\./) {
3424         next;
3425       } elsif (-d "$source_dir/$file") {
3426         push (@subdirs, $file);
3427       } elsif (@suffix_list) {
3428         foreach $suffix (@suffix_list) {
3429           if ($file =~ m/\.\Q${suffix}\E$/) {
3430             &ScanSourceFile ("$source_dir/$file");
3431           }
3432         }
3433       } elsif ($file =~ m/\.[ch]$/) {
3434         &ScanSourceFile ("$source_dir/$file");
3435       }
3436     }
3437     closedir (SRCDIR);
3439     # Now recursively scan the subdirectories.
3440     foreach $dir (@subdirs) {
3441         next if ($IGNORE_FILES =~ m/(\s|^)\Q${dir}\E(\s|$)/);
3442         &ReadSourceDocumentation ("$source_dir/$dir");
3443     }
3447 #############################################################################
3448 # Function    : ScanSourceFile
3449 # Description : Scans one source file looking for specially-formatted comment
3450 #               blocks. Later &MergeSourceDocumentation is used to merge any
3451 #               documentation found with the documentation already read in
3452 #               from the template files.
3454 # Arguments   : $file - the file to scan.
3455 #############################################################################
3457 sub ScanSourceFile {
3458     my ($file) = @_;
3459     my $basename;
3461     if ($file =~ m/^.*[\/\\]([^\/\\]*)$/) {
3462         $basename = $1;
3463     } else {
3464         &LogWarning ($file, 1, "Can't find basename for this filename.");
3465         $basename = $file;
3466     }
3468     # Check if the basename is in the list of files to ignore.
3469     if ($IGNORE_FILES =~ m/(\s|^)\Q${basename}\E(\s|$)/) {
3470         return;
3471     }
3473     #print "DEBUG: Scanning $file\n";
3475     open (SRCFILE, $file)
3476         || die "Can't open $file: $!";
3477     my $in_comment_block = 0;
3478     my $symbol;
3479     my ($in_description, $in_return, $in_since, $in_stability, $in_deprecated);
3480     my ($description, $return_desc, $return_start, $return_style);
3481     my ($since_desc, $stability_desc, $deprecated_desc);
3482     my $current_param;
3483     my $ignore_broken_returns;
3484     my @params;
3485     while (<SRCFILE>) {
3486         # Look for the start of a comment block.
3487         if (!$in_comment_block) {
3488             if (m%^\s*/\*.*\*/%) {
3489                 #one-line comment - not gtkdoc
3490             } elsif (m%^\s*/\*\*\s%) {
3491                 #print "Found comment block start\n";
3493                 $in_comment_block = 1;
3495                 # Reset all the symbol data.
3496                 $symbol = "";
3497                 $in_description = 0;
3498                 $in_return = 0;
3499                 $in_since = 0;
3500                 $in_deprecated = 0;
3501                 $in_stability = 0;
3502                 $description = "";
3503                 $return_desc = "";
3504                 $return_style = "";
3505                 $since_desc = "";
3506                 $deprecated_desc = "";
3507                 $stability_desc = "";
3508                 $current_param = -1;
3509                 $ignore_broken_returns = 0;
3510                 @params = ();
3511             }
3512             next;
3513         }
3515         # We're in a comment block. Check if we've found the end of it.
3516         if (m%^\s*\*+/%) {
3517             if (!$symbol) {
3518                 # maybe its not even meant to be a gtk-doc comment?
3519                 &LogWarning ($file, $., "Symbol name not found at the start of the comment block.");
3520             } else {
3521                 # Add the return value description onto the end of the params.
3522                 if ($return_desc) {
3523                     push (@params, "Returns");
3524                     push (@params, $return_desc);
3525                     if ($return_style eq 'broken') {
3526                         &LogWarning ($file, $., "Free-form return value description in $symbol. Use `Returns:' to avoid ambiguities.");
3527                     }
3528                 }
3529                 # Convert special SGML characters
3530                 $description = &ConvertSGMLChars ($symbol, $description);
3531                 my $k;
3532                 for ($k = 1; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3533                     $params[$k] = &ConvertSGMLChars ($symbol, $params[$k]);
3534                 }
3536                 # Handle Section docs
3537                 if ($symbol =~ m/SECTION:\s*(.*)/) {
3538                     my $real_symbol=$1;
3539                     my $key;
3541                     if (scalar %KnownSymbols) {
3542                         if ((! defined($KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"})) || $KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"} != 1) {
3543                             &LogWarning ($file, $., "Section $real_symbol is not defined in the $MODULE-section.txt file.");
3544                         }
3545                     }
3547                     #print "SECTION DOCS found in source for : '$real_symbol'\n";
3548                     $ignore_broken_returns = 1;
3549                     for ($k = 0; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3550                         #print "   '".$params[$k]."'\n";
3551                         $params[$k] = "\L$params[$k]";
3552                         undef $key;
3553                         if ($params[$k] eq "short_description") {
3554                             $key = "$TMPL_DIR/$real_symbol:Short_Description";
3555                         } elsif ($params[$k] eq "see_also") {
3556                             $key = "$TMPL_DIR/$real_symbol:See_Also";
3557                         } elsif ($params[$k] eq "title") {
3558                             $key = "$TMPL_DIR/$real_symbol:Title";
3559                         } elsif ($params[$k] eq "stability") {
3560                             $key = "$TMPL_DIR/$real_symbol:Stability_Level";
3561                         } elsif ($params[$k] eq "section_id") {
3562                             $key = "$TMPL_DIR/$real_symbol:Section_Id";
3563                         } elsif ($params[$k] eq "include") {
3564                             $key = "$TMPL_DIR/$real_symbol:Include";
3565                         }
3566                         if (defined($key)) {
3567                             $SourceSymbolDocs{$key}=$params[$k+1];
3568                             $SourceSymbolSourceFile{$key} = $file;
3569                             $SourceSymbolSourceLine{$key} = $.;
3570                         }
3571                     }
3572                     $SourceSymbolDocs{"$TMPL_DIR/$real_symbol:Long_Description"}=$description;
3573                     $SourceSymbolSourceFile{"$TMPL_DIR/$real_symbol:Long_Description"} = $file;
3574                     $SourceSymbolSourceLine{"$TMPL_DIR/$real_symbol:Long_Description"} = $.;
3575                     #$SourceSymbolTypes{$symbol} = "SECTION";
3576                 } else {
3577                     #print "SYMBOL DOCS found in source for : '$symbol' ",length($description), "\n";
3578                     $SourceSymbolDocs{$symbol} = $description;
3579                     $SourceSymbolParams{$symbol} = [ @params ];
3580                     # FIXME $SourceSymbolTypes{$symbol} = "STRUCT,SIGNAL,ARG,FUNCTION,MACRO";
3581                     #if (defined $DeclarationTypes{$symbol}) {
3582                     #    $SourceSymbolTypes{$symbol} = $DeclarationTypes{$symbol}
3583                     #}
3584                     $SourceSymbolSourceFile{$symbol} = $file;
3585                     $SourceSymbolSourceLine{$symbol} = $.;
3586                 }
3588                 if ($since_desc) {
3589                      ($since_desc, my @extra_lines) = split ("\n", $since_desc);
3590                      $since_desc =~ s/^\s+//;
3591                      $since_desc =~ s/\s+$//;
3592                      #print "Since($symbol) : [$since_desc]\n";
3593                      $Since{$symbol} = &ConvertSGMLChars ($symbol, $since_desc);
3594                      if(scalar @extra_lines) {
3595                          &LogWarning ($file, $., "multi-line since docs found");
3596                      }
3597                 }
3599                 if ($stability_desc) {
3600                     $stability_desc = &ParseStabilityLevel($stability_desc, $file, $., "Stability level for $symbol");
3601                     $StabilityLevel{$symbol} = &ConvertSGMLChars ($symbol, $stability_desc);
3602                 }
3604                 if ($deprecated_desc) {
3605                     if (exists $Deprecated{$symbol}) {
3606                     }
3607                     else {
3608                          # don't warn for signals and properties
3609                          #if ($symbol !~ m/::?(.*)/) {
3610                          if (defined $DeclarationTypes{$symbol}) {
3611                              &LogWarning ($file, $., 
3612                                  "$symbol is deprecated in the inline comments, but no deprecation guards were found around the declaration.".
3613                                  " (See the --deprecated-guards option for gtkdoc-scan.)");
3614                          }
3615                     }
3616                     $Deprecated{$symbol} = &ConvertSGMLChars ($symbol, $deprecated_desc);
3617                 }
3618             }
3620             $in_comment_block = 0;
3621             next;
3622         }
3624         # Get rid of ' * ' at start of every line in the comment block.
3625         s%^\s*\*\s?%%;
3626         # But make sure we don't get rid of the newline at the end.
3627         if (!$_) {
3628             $_ = "\n";
3629         }
3630         #print "DEBUG: scanning :$_";
3632         # If we haven't found the symbol name yet, look for it.
3633         if (!$symbol) {
3634             if (m%^\s*(SECTION:\s*\S+)%) {
3635                 $symbol = $1;
3636                 #print "SECTION DOCS found in source for : '$symbol'\n";
3637                 $ignore_broken_returns = 1;
3638             } elsif (m%^\s*([\w:-]*\w)\s*:?\s*$%) {
3639                 $symbol = $1;
3640                 #print "SYMBOL DOCS found in source for : '$symbol'\n";
3641             }
3642             next;
3643         }
3645         # If we're in the return value description, add it to the end.
3646         if ($in_return) {
3647             # If we find another valid returns line, we assume that the first
3648             # one was really part of the description.
3649             if (m/^\s*(returns:|return\s+value:)/i) {
3650                 if ($return_style eq 'broken') {
3651                     $description .= $return_start . $return_desc;
3652                 }
3653                 $return_start = $1;
3654                 if ($return_style eq 'sane') {
3655                     &LogWarning ($file, $., "Multiple Returns for $symbol.");
3656                 }
3657                 $return_style = 'sane';
3658                 $ignore_broken_returns = 1;
3659                 $return_desc = $';
3660             } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3661                 $description .= $return_start . $return_desc;
3662                 $return_start = $1;
3663                 $return_style = 'broken';
3664                 $return_desc = $';
3665             } elsif (m%^\s*since:%i) {
3666                 $since_desc = $';
3667                 $in_since = 1;
3668                 $in_return = 0;
3669             } elsif (m%^\s*stability:%i) {
3670                 $stability_desc = $';
3671                 $in_stability = 1;
3672                 $in_return = 0;
3673             } elsif (m%^\s*deprecated:%i) {
3674                 $deprecated_desc = $';
3675                 $in_deprecated = 1;
3676                 $in_return = 0;
3677             } else {
3678                 $return_desc .= $_;
3679             }
3680             next;
3681         }
3683         if ($in_since) {
3684             if (m/^\s*(returns:|return\s+value:)/i) {
3685                 if ($return_style eq 'broken') {
3686                     $description .= $return_start . $return_desc;
3687                 }
3688                 $return_start = $1;
3689                 if ($return_style eq 'sane') {
3690                     &LogWarning ($file, $., "Multiple Returns for $symbol.");
3691                 }
3692                 $return_style = 'sane';
3693                 $ignore_broken_returns = 1;
3694                 $return_desc = $';
3695                 $in_return = 1;
3696                 $in_since = 0;
3697             } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3698                 $return_start = $1;
3699                 $return_style = 'broken';
3700                 $return_desc = $';
3701                 $in_return = 1;
3702                 $in_since = 0;
3703             } elsif (m%^\s*deprecated:%i) {
3704                 $deprecated_desc = $';
3705                 $in_deprecated = 1;
3706                 $in_since = 0;
3707             } elsif (m%^\s*stability:%i) {
3708                 $stability_desc = $';
3709                 $in_stability = 1;
3710                 $in_since = 0;
3711             } else {
3712                 $since_desc .= $_;
3713             }
3714             next;
3715         }
3717         if ($in_stability) {
3718             if (m/^\s*(returns:|return\s+value:)/i) {
3719                 if ($return_style eq 'broken') {
3720                     $description .= $return_start . $return_desc;
3721                 }
3722                 $return_start = $1;
3723                 if ($return_style eq 'sane') {
3724                     &LogWarning ($file, $., "Multiple Returns for $symbol.");
3725                 }
3726                 $return_style = 'sane';
3727                 $ignore_broken_returns = 1;
3728                 $return_desc = $';
3729                 $in_return = 1;
3730                 $in_stability = 0;
3731             } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3732                 $return_start = $1;
3733                 $return_style = 'broken';
3734                 $return_desc = $';
3735                 $in_return = 1;
3736                 $in_stability = 0;
3737             } elsif (m%^\s*deprecated:%i) {
3738                 $deprecated_desc = $';
3739                 $in_deprecated = 1;
3740                 $in_stability = 0;
3741             } elsif (m%^\s*since:%i) {
3742                 $since_desc = $';
3743                 $in_since = 1;
3744                 $in_stability = 0;
3745             } else {
3746                 $stability_desc .= $_;
3747             }
3748             next;
3749         }
3751         if ($in_deprecated) {
3752             if (m/^\s*(returns:|return\s+value:)/i) {
3753                 if ($return_style eq 'broken') {
3754                     $description .= $return_start . $return_desc;
3755                 }
3756                 $return_start = $1;
3757                 if ($return_style eq 'sane') {
3758                     &LogWarning ($file, $., "Multiple Returns for $symbol.");
3759                 }
3760                 $return_style = 'sane';
3761                 $ignore_broken_returns = 1;
3762                 $return_desc = $';
3763                 $in_return = 1;
3764                 $in_deprecated = 0;
3765             } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3766                 $return_start = $1;
3767                 $return_style = 'broken';
3768                 $return_desc = $';
3769                 $in_return = 1;
3770                 $in_deprecated = 0;
3771             } elsif (m%^\s*since:%i) {
3772                 $since_desc = $';
3773                 $in_since = 1;
3774                 $in_deprecated = 0;
3775             } elsif (m%^\s*stability:%i) {
3776                 $stability_desc = $';
3777                 $in_stability = 1;
3778                 $in_deprecated = 0;
3779             } else {
3780                 $deprecated_desc .= $_;
3781             }
3782             next;
3783         }
3785         # If we're in the description part, check for the 'Returns:' line.
3786         # If that isn't found, add the text to the end.
3787         if ($in_description) {
3788             # Get rid of 'Description:'
3789             s%^\s*Description:%%;
3791             if (m/^\s*(returns:|return\s+value:)/i) {
3792                 if ($return_style eq 'broken') {
3793                     $description .= $return_start . $return_desc;
3794                 }
3795                 $return_start = $1;
3796                 if ($return_style eq 'sane') {
3797                     &LogWarning ($file, $., "Multiple Returns for $symbol.");
3798                 }
3799                 $return_style = 'sane';
3800                 $ignore_broken_returns = 1;
3801                 $return_desc = $';
3802                 $in_return = 1;
3803                 next;
3804             } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
3805                 $return_start = $1;
3806                 $return_style = 'broken';
3807                 $return_desc = $';
3808                 $in_return = 1;
3809                 next;
3810             } elsif (m%^\s*since:%i) {
3811                 $since_desc = $';
3812                 $in_since = 1;
3813                 next;
3814             } elsif (m%^\s*deprecated:%i) {
3815                 $deprecated_desc = $';
3816                 $in_deprecated = 1;
3817                 next;
3818             } elsif (m%^\s*stability:%i) {
3819                 $stability_desc = $';
3820                 $in_stability = 1;
3821                 next;
3822             }
3824             $description .= $_;
3825             next;
3826         }
3828         # We must be in the parameters. Check for the empty line below them.
3829         if (m%^\s*$%) {
3830             $in_description = 1;
3831             next;
3832         }
3834         # Look for a parameter name.
3835         if (m%^\s*@(\S+)\s*:\s*%) {
3836             my $param_name = $1;
3837             my $param_desc = $';
3839             #print "Found parameter: $param_name\n";
3840             # Allow '...' as the Varargs parameter.
3841             if ($param_name eq "...") {
3842                 $param_name = "Varargs";
3843             }
3844             if ("\L$param_name" eq "returns") {
3845                 $return_style = 'sane';
3846                 $ignore_broken_returns = 1;
3847             }
3848             push (@params, $param_name);
3849             push (@params, $param_desc);
3850             $current_param += $PARAM_FIELD_COUNT;
3851             next;
3852         }
3854         # We must be in the middle of a parameter description, so add it on
3855         # to the last element in @params.
3856         if ($current_param == -1) {
3857             &LogWarning ($file, $., "Parsing comment block file : parameter expected.");
3858         } else {
3859             $params[$#params] .= $_;
3860         }
3861     }
3862     close (SRCFILE);
3865 #############################################################################
3866 # Function    : OutputMissingDocumentation
3867 # Description : Outputs report of documentation coverage to a file
3869 # Arguments   : none
3870 #############################################################################
3872 sub OutputMissingDocumentation {
3873     my $n_documented = 0;
3874     my $n_incomplete = 0;
3875     my $total = 0;
3876     my $symbol;
3877     my $percent;
3878     my $msg;
3879     my $buffer = "";
3880     my $buffer_deprecated = "";
3881     my $buffer_descriptions = "";
3882     
3883     open (UNDOCUMENTED, ">$ROOT_DIR/$MODULE-undocumented.txt")
3884       || die "Can't create $ROOT_DIR/$MODULE-undocumented.txt: $!";
3885     
3886     foreach $symbol (sort (keys (%AllSymbols))) {
3887         # FIXME: should we print LogWarnings for undocumented stuff?
3888         # DEBUG
3889         #my $ssfile = &GetSymbolSourceFile($symbol);
3890         #my $ssline = &GetSymbolSourceLine($symbol);
3891         #my $location = "defined at " . (defined($ssfile)?$ssfile:"?") . ":" . (defined($ssline)?$ssline:"0") . "\n";
3892         # DEBUG
3893         if ($symbol !~ /:(Title|Long_Description|Short_Description|See_Also|Stability_Level|Include|Section_Id)/) {
3894             $total++;
3895             if (exists ($AllDocumentedSymbols{$symbol})) {
3896                 $n_documented++;
3897                 if (exists ($AllIncompleteSymbols{$symbol})) {
3898                     $n_incomplete++;
3899                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
3900                     #$buffer .= "\t0: ".$location;
3901                 }
3902             } elsif (exists $Deprecated{$symbol}) {
3903                 if (exists ($AllIncompleteSymbols{$symbol})) {
3904                     $n_incomplete++;
3905                     $buffer_deprecated .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
3906                     #$buffer .= "\t1a: ".$location;
3907                 } else {
3908                     $buffer_deprecated .= $symbol . "\n";
3909                     #$buffer .= "\t1b: ".$location;
3910                 }
3911             } else {
3912                 if (exists ($AllIncompleteSymbols{$symbol})) {
3913                     $n_incomplete++;
3914                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
3915                     #$buffer .= "\t2a: ".$location;
3916                 } else {
3917                     $buffer .= $symbol . "\n";
3918                     #$buffer .= "\t2b: ".$location;
3919                 }
3920             }
3921         } elsif ($symbol =~ /:(Long_Description|Short_Description)/) {
3922             $total++;
3923             #my $len1=(exists($SymbolDocs{$symbol}))?length($SymbolDocs{$symbol}):-1;
3924             #my $len2=(exists($AllDocumentedSymbols{$symbol}))?length($AllDocumentedSymbols{$symbol}):-1;
3925             #print "%%%% $symbol : $len1,$len2\n";
3926             if (((exists ($SymbolDocs{$symbol})) && (length ($SymbolDocs{$symbol}) > 0))
3927             || ((exists ($AllDocumentedSymbols{$symbol})) && (length ($AllDocumentedSymbols{$symbol}) > 0))) {
3928               $n_documented++;
3929             } else {
3930               # cut off the leading namespace ($TMPL_DIR)
3931               $symbol =~ m/^.*\/(.*)$/;
3932               $buffer_descriptions .= $1 . "\n";
3933             }
3934         }
3935     }
3936     
3937     $buffer .= "\n" . $buffer_deprecated . "\n" . $buffer_descriptions;
3938     
3939     if ($total == 0) {
3940       $percent = 100;
3941     } else {
3942       $percent = ($n_documented / $total) * 100.0;
3943     }
3944     
3945     printf UNDOCUMENTED "%.0f%% symbol docs coverage.\n", $percent;
3946     print UNDOCUMENTED "$n_documented symbols documented.\n";
3947     print UNDOCUMENTED "$n_incomplete symbols incomplete.\n";
3948     print UNDOCUMENTED ($total - $n_documented) . " not documented.\n\n\n";
3949     
3950     print UNDOCUMENTED $buffer;
3951     
3952     close (UNDOCUMENTED);
3953     
3954     printf (("%.0f%% symbol docs coverage ($n_documented symbols documented, $n_incomplete symbols incomplete, " . ($total - $n_documented) . " not documented)\nSee $MODULE-undocumented.txt for a list of missing docs.\nThe doc coverage percentage doesn't include intro sections.\n"), $percent);
3958 #############################################################################
3959 # Function    : OutputUndeclaredSymbols
3960 # Description : Outputs symbols that are undeclared yet documented to a file
3962 # Arguments   : none
3963 #############################################################################
3965 sub OutputUndeclaredSymbols {
3966     open(UNDECLARED, ">$ROOT_DIR/$MODULE-undeclared.txt")
3967         || die "Can't create $ROOT_DIR/$MODULE-undeclared.txt";
3969     if (%UndeclaredSymbols) {
3970         print UNDECLARED (join("\n", sort keys %UndeclaredSymbols));
3971         print UNDECLARED "\n";
3972         print "See $MODULE-undeclared.txt for the list of undeclared symbols.\n"
3973     }
3974     close(UNDECLARED);
3978 #############################################################################
3979 # Function    : OutputAllSymbols
3980 # Description : Outputs list of all symbols to a file
3982 # Arguments   : none
3983 #############################################################################
3985 sub OutputAllSymbols {
3986      my $n_documented = 0;
3987      my $total = 0;
3988      my $symbol;
3989      my $percent;
3990      my $msg;
3992      open (SYMBOLS, ">$ROOT_DIR/$MODULE-symbols.txt")
3993           || die "Can't create $ROOT_DIR/$MODULE-symbols.txt: $!";
3995      foreach $symbol (sort (keys (%AllSymbols))) {
3996           print SYMBOLS $symbol . "\n";
3997      }
3999      close (SYMBOLS);
4002 #############################################################################
4003 # Function    : OutputSymbolsWithoutSince
4004 # Description : Outputs list of all symbols without a since tag to a file
4006 # Arguments   : none
4007 #############################################################################
4009 sub OutputSymbolsWithoutSince {
4010      my $n_documented = 0;
4011      my $total = 0;
4012      my $symbol;
4013      my $percent;
4014      my $msg;
4016      open (SYMBOLS, ">$ROOT_DIR/$MODULE-nosince.txt")
4017           || die "Can't create $ROOT_DIR/$MODULE-nosince.txt: $!";
4019      foreach $symbol (sort (keys (%SourceSymbolDocs))) {
4020          if (!defined $Since{$symbol}) {
4021              print SYMBOLS $symbol . "\n";
4022          }
4023      }
4025      close (SYMBOLS);
4029 #############################################################################
4030 # Function    : MergeSourceDocumentation
4031 # Description : This merges documentation read from a source file into the
4032 #               documentation read in from a template file.
4034 #               Parameter descriptions override any in the template files.
4035 #               Function descriptions are placed before any description from
4036 #               the template files.
4038 # Arguments   : none
4039 #############################################################################
4041 sub MergeSourceDocumentation {
4042     my $symbol;
4043     my @Symbols;
4045     if (scalar %SymbolDocs) {
4046         @Symbols=keys (%SymbolDocs);
4047         #print "num existing entries: ".(scalar @Symbols)."\n";
4048         #print "  ",$Symbols[0], " ",$Symbols[1],"\n";
4049     }
4050     else {
4051         # filter scanned declarations, with what we suppress from -sections.txt
4052         my %tmp = ();
4053         foreach $symbol (keys (%Declarations)) {
4054             if (defined($KnownSymbols{$symbol}) && $KnownSymbols{$symbol} == 1) {
4055                 $tmp{$symbol}=1;
4056             }
4057         }
4058         # , add the rest from -sections.txt
4059         foreach $symbol (keys (%KnownSymbols)) {
4060             if ($KnownSymbols{$symbol} == 1) {
4061                 $tmp{$symbol}=1;
4062             }
4063         }
4064         # and add whats found in the source
4065         foreach $symbol (keys (%SourceSymbolDocs)) {
4066             $tmp{$symbol}=1;
4067         }
4068         @Symbols = keys (%tmp);
4069         #print "num source entries: ".(scalar @Symbols)."\n";
4070     }
4071     foreach $symbol (@Symbols) {
4072         $AllSymbols{$symbol} = 1;
4074         my $have_tmpl_docs = 0;
4076         ## See if the symbol is documented in template
4077         my $tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4078         my $check_tmpl_doc =$tmpl_doc;
4079         # remove all xml-tags and whitespaces
4080         #$check_tmpl_doc =~ s/<\/?[a-z]+>//g;
4081         $check_tmpl_doc =~ s/<.*?>//g;
4082         $check_tmpl_doc =~ s/\s//g;
4083         # anything left ?
4084         if ($check_tmpl_doc ne "") {
4085             $have_tmpl_docs = 1;
4086             #print "## [$check_tmpl_doc]\n";
4087         } else {
4088             $tmpl_doc = "";
4089         }
4091         if (exists ($SourceSymbolDocs{$symbol})) {
4092             my $type = $DeclarationTypes {$symbol};
4094             #print "merging [$symbol] from source\n";
4096             my $item = "Parameter";
4097             if (defined ($type)) {
4098                 if ($type eq 'STRUCT') {
4099                     $item = "Field";
4100                 } elsif ($type eq 'ENUM') {
4101                     $item = "Value";
4102                 } elsif ($type eq 'UNION') {
4103                     $item = "Field";
4104                 }
4105             } else {
4106                 $type="SIGNAL";
4107             }
4109             my $src_doc = $SourceSymbolDocs{$symbol};
4110             # remove leading and training whitespaces
4111             $src_doc =~ s/^\s+//;
4112             $src_doc =~ s/\s+$//;
4114             # Don't output warnings for overridden titles as titles are
4115             # automatically generated in the -sections.txt file, and thus they
4116             # are often overridden.
4117             if ($have_tmpl_docs && $symbol !~ m/:Title$/) {
4118                 # check if content is different
4119                 if ($tmpl_doc ne $src_doc) {
4120                     #print "[$tmpl_doc] [$src_doc]\n";
4121                     &LogWarning ($SourceSymbolSourceFile{$symbol}, $SourceSymbolSourceLine{$symbol},
4122                         "Documentation in template ".$SymbolSourceFile{$symbol}.":".$SymbolSourceLine{$symbol}." for $symbol being overridden by inline comments.");
4123                 }
4124             }
4126             if ($src_doc ne "") {
4127                  $AllDocumentedSymbols{$symbol} = 1;
4128             }
4130             # Convert <!--PARAMETERS--> with any blank lines around it to
4131             # a </para> followed by <!--PARAMETERS--> followed by <para>.
4132             $src_doc =~ s%\n+\s*<!--PARAMETERS-->\s*\n+%\n</para>\n<!--PARAMETERS-->\n<para>\n%g;
4134             # If there is a blank line, finish the paragraph and start another.
4135             $src_doc = &ConvertBlankLines ($src_doc, $symbol);
4136             # Do not add <para> to nothing, it breaks missing docs checks.
4137             my $src_doc_para = "";
4138             if ($src_doc) {
4139                 $src_doc_para = "<para>\n$src_doc</para>\n";
4140                 #print "$symbol : [$src_doc][$src_doc_para]\n";
4141             }
4143             if ($symbol =~ m/$TMPL_DIR\/.+:Long_Description/) {
4144                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4145             } elsif ($symbol =~ m/$TMPL_DIR\/.+:.+/) {
4146                 # For the title/summary/see also section docs we don't want to
4147                 # add any <para> tags.
4148                 $SymbolDocs{$symbol} = "$src_doc"
4149             } else {
4150                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4151             }
4153             # merge parameters
4154             if ($symbol =~ m/.*::.*/) {
4155                 # For signals we prefer the param names from the source docs,
4156                 # since the ones from the templates are likely to contain the
4157                 # artificial argn names which are generated by gtkdoc-scangobj.
4158                 $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4159                 # FIXME: we need to check for empty docs here as well!
4160             } else {
4161                 # The templates contain the definitive parameter names and order,
4162                 # so we will not change that. We only override the actual text.
4163                 my $tmpl_params = $SymbolParams{$symbol};
4164                 if (!defined ($tmpl_params)) {
4165                     #print "No merge needed for $symbol\n";
4166                     $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4167                     #  FIXME: we still like to get the number of params and merge
4168                     #  1) we would noticed that params have been removed/renamed
4169                     #  2) we would catch undocumented params
4170                     #  params are not (yet) exported in -decl.txt so that we
4171                     #  could easily grab them :/
4172                 } else {
4173                     my $params = $SourceSymbolParams{$symbol};
4174                     my $j;
4175                     #print "Merge needed for $symbol, tmpl_params: ",$#$tmpl_params,", source_params: ",$#$params," \n";
4176                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4177                         my $tmpl_param_name = $$tmpl_params[$j];
4179                         # Allow '...' as the Varargs parameter.
4180                         if ($tmpl_param_name eq "...") {
4181                             $tmpl_param_name = "Varargs";
4182                         }
4184                         # Try to find the param in the source comment documentation.
4185                         my $found = 0;
4186                         my $k;
4187                         #print "  try merge param $tmpl_param_name\n";
4188                         for ($k = 0; $k <= $#$params; $k += $PARAM_FIELD_COUNT) {
4189                             my $param_name = $$params[$k];
4190                             my $param_desc = $$params[$k + 1];
4192                             #print "    test param  $param_name\n";
4193                             # We accept changes in case, since the Gnome source
4194                             # docs contain a lot of these.
4195                             if ("\L$param_name" eq "\L$tmpl_param_name") {
4196                                 $found = 1;
4198                                 # Override the description.
4199                                 $$tmpl_params[$j + 1] = $param_desc;
4201                                 # Set the name to "" to mark it as used.
4202                                 $$params[$k] = "";
4203                                 last;
4204                             }
4205                         }
4207                         # If it looks like the parameters are there, but not
4208                         # in the right place, try to explain a bit better.
4209                         if ((!$found) && ($src_doc =~ m/\@$tmpl_param_name:/)) {
4210                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4211                                 "Parameters for $symbol must start on the line immediately after the function or macro name.");
4212                         }
4213                     }
4215                     # Now we output a warning if parameters have been described which
4216                     # do not exist.
4217                     for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
4218                         my $param_name = $$params[$j];
4219                         if ($param_name) {
4220                             # the template builder cannot detect if a macro returns
4221                             # a result or not
4222                             if(($type eq "MACRO") && ($param_name eq "Returns")) {
4223                                 # FIXME: do we need to add it then to tmpl_params[] ?
4224                                 my $num=$#$tmpl_params;
4225                                 #print "  adding Returns: to macro docs for $symbol.\n";
4226                                 $$tmpl_params[$num+1]="Returns";
4227                                 $$tmpl_params[$num+2]=$$params[$j+1];
4228                                 next;
4229                             }
4230                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4231                                 "$item described in source code comment block but does not exist. $type: $symbol $item: $param_name.");
4232                         }
4233                     }
4234                 }
4235             }
4236         } else {
4237             if ($have_tmpl_docs) {
4238                 $AllDocumentedSymbols{$symbol} = 1;
4239                 #print "merging [$symbol] from template\n";
4240             }
4241             else {
4242                 #print "[$symbol] undocumented\n";
4243             }
4244         }
4246         # if this symbol is documented, check if docs are complete
4247         $check_tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4248         # remove all xml-tags and whitespaces
4249         #$check_tmpl_doc =~ s/<\/?[a-z]+>//g;
4250         $check_tmpl_doc =~ s/<.*?>//g;
4251         $check_tmpl_doc =~ s/\s//g;
4252         if ($check_tmpl_doc ne "") {
4253             my $tmpl_params = $SymbolParams{$symbol};
4254             if (defined ($tmpl_params)) {
4255                 my $type = $DeclarationTypes {$symbol};
4257                 my $item = "Parameter";
4258                 if (defined ($type)) {
4259                     if ($type eq 'STRUCT') {
4260                         $item = "Field";
4261                     } elsif ($type eq 'ENUM') {
4262                         $item = "Value";
4263                     } elsif ($type eq 'UNION') {
4264                         $item = "Field";
4265                     }
4266                 } else {
4267                     $type="SIGNAL";
4268                 }
4270                 #print "Check param docs for $symbol, tmpl_params: ",$#$tmpl_params," entries, type=$type\n";
4272                 if ($#$tmpl_params > 0) {
4273                     my $j;
4274                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4275                         # Output a warning if the parameter is empty and
4276                         # remember for stats.
4277                         my $tmpl_param_name = $$tmpl_params[$j];
4278                         my $tmpl_param_desc = $$tmpl_params[$j + 1];
4279                         if ($tmpl_param_desc !~ m/\S/) {
4280                             if (exists ($AllIncompleteSymbols{$symbol})) {
4281                                 $AllIncompleteSymbols{$symbol}.=", ".$tmpl_param_name;
4282                             } else {
4283                                 $AllIncompleteSymbols{$symbol}=$tmpl_param_name;
4284                             }
4285                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4286                                 "$item description for $symbol"."::"."$tmpl_param_name is missing in source code comment block.");
4287                         }
4288                     }
4289                 }
4290                 else {
4291                     if ($#$tmpl_params == 0) {
4292                         $AllIncompleteSymbols{$symbol}="<items>";
4293                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4294                             "$item descriptions for $symbol are missing in source code comment block.");
4295                     }
4296                     # $#$tmpl_params==-1 means we don't know about parameters
4297                     # this unfortunately does not tell if there should be some
4298                 }
4299             }
4300         }
4301    }
4302    #print "num doc entries: ".(scalar %SymbolDocs)."\n";
4305 #############################################################################
4306 # Function    : IsEmptyDoc
4307 # Description : Check if a doc-string is empty. Its also regarded as empty if
4308 #               it only consist of whitespace or e.g. FIXME.
4309 # Arguments   : the doc-string
4310 #############################################################################
4311 sub IsEmptyDoc {
4312     my ($doc) = @_;
4313     
4314     if ($doc =~ /^\s*$/) {
4315         return 1;
4316     }
4318     if ($doc =~ /^\s*<para>\s*(FIXME)?\s*<\/para>\s*$/) {
4319         return 1;
4320     }
4322     return 0;
4326 # This converts blank lines to "</para><para>", but only outside CDATA and
4327 # <programlisting> tags.
4328 sub ConvertBlankLines {
4329     return &ModifyXMLElements ($_[0], $_[1],
4330                                "<!\\[CDATA\\[|<programlisting[^>]*>|\\|\\[",
4331                                \&ConvertBlankLinesEndTag,
4332                                \&ConvertBlankLinesCallback);
4336 sub ConvertBlankLinesEndTag {
4337   if ($_[0] eq "<!\[CDATA\[") {
4338     return "]]>";
4339   } elsif ($_[0] eq "|[") {
4340     return "]\\|";
4341   } else {
4342     return "</programlisting>";
4343   }
4346 sub ConvertBlankLinesCallback {
4347   my ($text, $symbol, $tag) = @_;
4349   # If we're not in CDATA or a <programlisting> we convert blank lines so
4350   # they start a new <para>.
4351   if ($tag eq "") {
4352     $text =~ s%\n{2,}%\n</para>\n<para>\n%g;
4353   }
4355   return $text;
4359 #############################################################################
4360 # LIBRARY FUNCTIONS -   These functions are used in both gtkdoc-mkdb and
4361 #                       gtkdoc-mktmpl and should eventually be moved to a
4362 #                       separate library.
4363 #############################################################################
4365 #############################################################################
4366 # Function    : ReadDeclarationsFile
4367 # Description : This reads in a file containing the function/macro/enum etc.
4368 #               declarations.
4370 #               Note that in some cases there are several declarations with
4371 #               the same name, e.g. for conditional macros. In this case we
4372 #               set a flag in the %DeclarationConditional hash so the
4373 #               declaration is not shown in the docs.
4375 #               If a macro and a function have the same name, e.g. for
4376 #               gtk_object_ref, the function declaration takes precedence.
4378 #               Some opaque structs are just declared with 'typedef struct
4379 #               _name name;' in which case the declaration may be empty.
4380 #               The structure may have been found later in the header, so
4381 #               that overrides the empty declaration.
4383 # Arguments   : $file - the declarations file to read
4384 #               $override - if declarations in this file should override
4385 #                       any current declaration.
4386 #############################################################################
4388 sub ReadDeclarationsFile {
4389     my ($file, $override) = @_;
4391     if ($override == 0) {
4392         %Declarations = ();
4393         %DeclarationTypes = ();
4394         %DeclarationConditional = ();
4395         %DeclarationOutput = ();
4396     }
4398     open (INPUT, $file)
4399         || die "Can't open $file: $!";
4400     my $declaration_type = "";
4401     my $declaration_name;
4402     my $declaration;
4403     my $is_deprecated = 0;
4404     while (<INPUT>) {
4405         if (!$declaration_type) {
4406             if (m/^<([^>]+)>/) {
4407                 $declaration_type = $1;
4408                 $declaration_name = "";
4409                 #print "Found declaration: $declaration_type\n";
4410                 $declaration = "";
4411             }
4412         } else {
4413             if (m%^<NAME>(.*)</NAME>%) {
4414                 $declaration_name = $1;
4415             } elsif (m%^<DEPRECATED/>%) {
4416                 $is_deprecated = 1;
4417             } elsif (m%^</$declaration_type>%) {
4418                 #print "Found end of declaration: $declaration_name\n";
4419                 # Check that the declaration has a name
4420                 if ($declaration_name eq "") {
4421                     print "ERROR: $declaration_type has no name $file:$.\n";
4422                 }
4424                 # If the declaration is an empty typedef struct _XXX XXX
4425                 # set the flag to indicate the struct has a typedef.
4426                 if ($declaration_type eq 'STRUCT'
4427                     && $declaration =~ m/^\s*$/) {
4428                     #print "Struct has typedef: $declaration_name\n";
4429                     $StructHasTypedef{$declaration_name} = 1;
4430                 }
4432                 # Check if the symbol is already defined.
4433                 if (defined ($Declarations{$declaration_name})
4434                     && $override == 0) {
4435                     # Function declarations take precedence.
4436                     if ($DeclarationTypes{$declaration_name} eq 'FUNCTION') {
4437                         # Ignore it.
4438                     } elsif ($declaration_type eq 'FUNCTION') {
4439                         if ($is_deprecated) {
4440                             $Deprecated{$declaration_name} = "";
4441                         }
4442                         $Declarations{$declaration_name} = $declaration;
4443                         $DeclarationTypes{$declaration_name} = $declaration_type;
4444                     } elsif ($DeclarationTypes{$declaration_name}
4445                               eq $declaration_type) {
4446                         # If the existing declaration is empty, or is just a
4447                         # forward declaration of a struct, override it.
4448                         if ($declaration_type eq 'STRUCT') {
4449                             if ($Declarations{$declaration_name} =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
4450                                 if ($is_deprecated) {
4451                                     $Deprecated{$declaration_name} = "";
4452                                 }
4453                                 $Declarations{$declaration_name} = $declaration;
4454                             } elsif ($declaration =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
4455                                 # Ignore an empty or forward declaration.
4456                             } else {
4457                                 &LogWarning ($file, $., "Structure $declaration_name has multiple definitions.");
4458                             }
4459                         } else {
4460                             # set flag in %DeclarationConditional hash for
4461                             # multiply defined macros/typedefs.
4462                             $DeclarationConditional{$declaration_name} = 1;
4463                         }
4464                     } else {
4465                         &LogWarning ($file, $., "$declaration_name has multiple definitions.");
4466                     }
4467                 } else {
4468                     if ($is_deprecated) {
4469                         $Deprecated{$declaration_name} = "";
4470                     }
4471                     $Declarations{$declaration_name} = $declaration;
4472                     $DeclarationTypes{$declaration_name} = $declaration_type;
4473                 }
4475                 $declaration_type = "";
4476                 $is_deprecated = 0;
4477             } else {
4478                 $declaration .= $_;
4479             }
4480         }
4481     }
4482     close (INPUT);
4486 #############################################################################
4487 # Function    : ReadSignalsFile
4488 # Description : This reads in an existing file which contains information on
4489 #               all GTK signals. It creates the arrays @SignalNames and
4490 #               @SignalPrototypes containing info on the signals. The first
4491 #               line of the SignalPrototype is the return type of the signal
4492 #               handler. The remaining lines are the parameters passed to it.
4493 #               The last parameter, "gpointer user_data" is always the same
4494 #               so is not included.
4495 # Arguments   : $file - the file containing the signal handler prototype
4496 #                       information.
4497 #############################################################################
4499 sub ReadSignalsFile {
4500     my ($file) = @_;
4502     my $in_signal = 0;
4503     my $signal_object;
4504     my $signal_name;
4505     my $signal_returns;
4506     my $signal_flags;
4507     my $signal_prototype;
4509     # Reset the signal info.
4510     @SignalObjects = ();
4511     @SignalNames = ();
4512     @SignalReturns = ();
4513     @SignalFlags = ();
4514     @SignalPrototypes = ();
4516     if (! -f $file) {
4517         return;
4518     }
4519     if (!open (INPUT, $file)) {
4520         warn "Can't open $file - skipping signals\n";
4521         return;
4522     }
4523     while (<INPUT>) {
4524         if (!$in_signal) {
4525             if (m/^<SIGNAL>/) {
4526                 $in_signal = 1;
4527                 $signal_object = "";
4528                 $signal_name = "";
4529                 $signal_returns = "";
4530                 $signal_prototype = "";
4531             }
4532         } else {
4533             if (m/^<NAME>(.*)<\/NAME>/) {
4534                 $signal_name = $1;
4535                 if ($signal_name =~ m/^(.*)::(.*)$/) {
4536                     $signal_object = $1;
4537                     ($signal_name = $2) =~ s/_/-/g;
4538                     #print "Found signal: $signal_name\n";
4539                 } else {
4540                     &LogWarning ($file, $., "Invalid signal name: $signal_name.");
4541                 }
4542             } elsif (m/^<RETURNS>(.*)<\/RETURNS>/) {
4543                 $signal_returns = $1;
4544             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
4545                 $signal_flags = $1;
4546             } elsif (m%^</SIGNAL>%) {
4547                 #print "Found end of signal: ${signal_object}::${signal_name}\nReturns: ${signal_returns}\n${signal_prototype}";
4548                 push (@SignalObjects, $signal_object);
4549                 push (@SignalNames, $signal_name);
4550                 push (@SignalReturns, $signal_returns);
4551                 push (@SignalFlags, $signal_flags);
4552                 push (@SignalPrototypes, $signal_prototype);
4553                 $in_signal = 0;
4554             } else {
4555                 $signal_prototype .= $_;
4556             }
4557         }
4558     }
4559     close (INPUT);
4563 #############################################################################
4564 # Function    : ReadTemplateFile
4565 # Description : This reads in the manually-edited documentation file
4566 #               corresponding to the file currently being created, so we can
4567 #               insert the documentation at the appropriate places.
4568 #               It outputs %SymbolTypes, %SymbolDocs and %SymbolParams, which
4569 #               is a hash of arrays.
4570 #               NOTE: This function is duplicated in gtkdoc-mktmpl (but
4571 #               slightly different).
4572 # Arguments   : $docsfile - the template file to read in.
4573 #               $skip_unused_params - 1 if the unused parameters should be
4574 #                       skipped.
4575 #############################################################################
4577 sub ReadTemplateFile {
4578     my ($docsfile, $skip_unused_params) = @_;
4580     my $template = "$docsfile.sgml";
4581     if (! -f $template) {
4582         #print "File doesn't exist: $template\n";
4583         return 0;
4584     }
4585     #print "Reading $template\n";
4587     # start with empty hashes, we merge the source comment for each file
4588     # afterwards
4589     %SymbolDocs = ();
4590     %SymbolTypes = ();
4591     %SymbolParams = ();
4593     my $current_type = "";      # Type of symbol being read.
4594     my $current_symbol = "";    # Name of symbol being read.
4595     my $symbol_doc = "";                # Description of symbol being read.
4596     my @params;                 # Parameter names and descriptions of current
4597                                 #   function/macro/function typedef.
4598     my $current_param = -1;     # Index of parameter currently being read.
4599                                 #   Note that the param array contains pairs
4600                                 #   of param name & description.
4601     my $in_unused_params = 0;   # True if we are reading in the unused params.
4602     my $in_deprecated = 0;
4603     my $in_since = 0;
4604     my $in_stability = 0;
4606     open (DOCS, "$template")
4607         || die "Can't open $template: $!";
4608     while (<DOCS>) {
4609         if (m/^<!-- ##### ([A-Z_]+) (\S+) ##### -->/) {
4610             my $type = $1;
4611             my $symbol = $2;
4612             if ($symbol eq "Title"
4613                 || $symbol eq "Short_Description"
4614                 || $symbol eq "Long_Description"
4615                 || $symbol eq "See_Also"
4616                 || $symbol eq "Stability_Level"
4617                 || $symbol eq "Include") {
4619                 $symbol = $docsfile . ":" . $symbol;
4620             }
4622             #print "Found symbol: $symbol\n";
4623             # Remember file and line for the symbol
4624             $SymbolSourceFile{$symbol} = $template;
4625             $SymbolSourceLine{$symbol} = $.;
4627             # Store previous symbol, but remove any trailing blank lines.
4628             if ($current_symbol ne "") {
4629                 $symbol_doc =~ s/\s+$//;
4630                 $SymbolTypes{$current_symbol} = $current_type;
4631                 $SymbolDocs{$current_symbol} = $symbol_doc;
4633                 # Check that the stability level is valid.
4634                 if ($StabilityLevel{$current_symbol}) {
4635                     $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
4636                 }
4638                 if ($current_param >= 0) {
4639                     $SymbolParams{$current_symbol} = [ @params ];
4640                 } else {
4641                     # Delete any existing params in case we are overriding a
4642                     # previously read template.
4643                     delete $SymbolParams{$current_symbol};
4644                 }
4645             }
4646             $current_type = $type;
4647             $current_symbol = $symbol;
4648             $current_param = -1;
4649             $in_unused_params = 0;
4650             $in_deprecated = 0;
4651             $in_since = 0;
4652             $in_stability = 0;
4653             $symbol_doc = "";
4654             @params = ();
4656         } elsif (m/^<!-- # Unused Parameters # -->/) {
4657             #print "DEBUG: Found unused parameters\n";
4658             $in_unused_params = 1;
4659             next;
4661         } elsif ($in_unused_params && $skip_unused_params) {
4662             # When outputting the DocBook we skip unused parameters.
4663             #print "DEBUG: Skipping unused param: $_";
4664             next;
4666         } else {
4667             # Check if param found. Need to handle "..." and "format...".
4668             if (s/^\@([\w\.]+):\040?//) {
4669                 my $param_name = $1;
4670                 my $param_desc = $_;
4671                 # Allow variations of 'Returns'
4672                 if ($param_name =~ m/^[Rr]eturns?$/) {
4673                     $param_name = "Returns";
4674                 }
4676                 # strip trailing whitespaces and blank lines
4677                 s/\s+\n$/\n/m;
4678                 s/\n+$/\n/sm;
4679                 #print "Found param for symbol $current_symbol : '$param_name'= '$_'";
4681                 if ($param_name eq "Deprecated") {
4682                     $in_deprecated = 1;
4683                     $Deprecated{$current_symbol} = $_;
4684                 } elsif ($param_name eq "Since") {
4685                     $in_since = 1;
4686                     chomp;
4687                     $Since{$current_symbol} = $_;
4688                 } elsif ($param_name eq "Stability") {
4689                     $in_stability = 1;
4690                     $StabilityLevel{$current_symbol} = $_;
4691                 } else {
4692                     push (@params, $param_name);
4693                     push (@params, $param_desc);
4694                     $current_param += $PARAM_FIELD_COUNT;
4695                 }
4696             } else {
4697                 # strip trailing whitespaces and blank lines
4698                 s/\s+\n$/\n/m;
4699                 s/\n+$/\n/sm;
4700                 
4701                 if (!m/^\s+$/) {
4702                     if ($in_deprecated) {
4703                         $Deprecated{$current_symbol} .= $_;
4704                     } elsif ($in_since) {
4705                         &LogWarning ($template, $., "multi-line since docs found");
4706                         #$Since{$current_symbol} .= $_;
4707                     } elsif ($in_stability) {
4708                         $StabilityLevel{$current_symbol} .= $_;
4709                     } elsif ($current_param >= 0) {
4710                         $params[$current_param] .= $_;
4711                     } else {
4712                         $symbol_doc .= $_;
4713                     }
4714                 }
4715             }
4716         }
4717     }
4719     # Remember to finish the current symbol doccs.
4720     if ($current_symbol ne "") {
4722         $symbol_doc =~ s/\s+$//;
4723         $SymbolTypes{$current_symbol} = $current_type;
4724         $SymbolDocs{$current_symbol} = $symbol_doc;
4726         # Check that the stability level is valid.
4727         if ($StabilityLevel{$current_symbol}) {
4728             $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
4729         }
4731         if ($current_param >= 0) {
4732             $SymbolParams{$current_symbol} = [ @params ];
4733         } else {
4734             # Delete any existing params in case we are overriding a
4735             # previously read template.
4736             delete $SymbolParams{$current_symbol};
4737         }
4738     }
4740     close (DOCS);
4741     return 1;
4745 #############################################################################
4746 # Function    : ReadObjectHierarchy
4747 # Description : This reads in the $MODULE-hierarchy.txt file containing all
4748 #               the GtkObject subclasses described in this module (and their
4749 #               ancestors).
4750 #               It places them in the @Objects array, and places their level
4751 #               in the widget hierarchy in the @ObjectLevels array, at the
4752 #               same index. GtkObject, the root object, has a level of 1.
4754 #               FIXME: the version in gtkdoc-mkdb also generates tree_index.sgml
4755 #               as it goes along, this should be split out into a separate
4756 #               function.
4758 # Arguments   : none
4759 #############################################################################
4761 sub ReadObjectHierarchy {
4762     @Objects = ();
4763     @ObjectLevels = ();
4765     if (! -f $OBJECT_TREE_FILE) {
4766         return;
4767     }
4768     if (!open (INPUT, $OBJECT_TREE_FILE)) {
4769         warn "Can't open $OBJECT_TREE_FILE - skipping object tree\n";
4770         return;
4771     }
4773     # FIXME: use $OUTPUT_FORMAT
4774     # my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.$OUTPUT_FORMAT";
4775     my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.sgml";
4776     my $new_tree_index = "$SGML_OUTPUT_DIR/tree_index.new";
4778     open (OUTPUT, ">$new_tree_index")
4779         || die "Can't create $new_tree_index: $!";
4781     if (lc($OUTPUT_FORMAT) eq "xml") {
4782         my $tree_header = $doctype_header;
4784         $tree_header =~ s/<!DOCTYPE \w+/<!DOCTYPE screen/;
4785         print (OUTPUT "$tree_header");
4786     }
4787     print (OUTPUT "<screen>\n");
4789     # Only emit objects if they are supposed to be documented, or if
4790     # they have documented children. To implement this, we maintain a
4791     # stack of pending objects which will be emitted if a documented
4792     # child turns up.
4793     my @pending_objects = ();
4794     my @pending_levels = ();
4795     while (<INPUT>) {
4796         if (m/\S+/) {
4797             my $object = $&;
4798             my $level = (length($`)) / 2 + 1;
4799             my $xref = "";
4801             while (($#pending_levels >= 0) && ($pending_levels[$#pending_levels] >= $level)) {
4802                 my $pobject = pop(@pending_objects);
4803                 my $plevel = pop(@pending_levels);
4804             }
4806             push (@pending_objects, $object);
4807             push (@pending_levels, $level);
4809             if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
4810                 while ($#pending_levels >= 0) {
4811                     $object = shift @pending_objects;
4812                     $level = shift @pending_levels;
4813                     $xref = &MakeXRef ($object);
4815                     print (OUTPUT ' ' x ($level * 4), "$xref\n");
4816                     push (@Objects, $object);
4817                     push (@ObjectLevels, $level);
4818                 }
4819             }
4820             #else {
4821             #    LogWarning ($OBJECT_TREE_FILE, $., "unknown type $object");
4822             #}
4823         }
4824     }
4825     print (OUTPUT "</screen>\n");
4827     close (INPUT);
4828     close (OUTPUT);
4830     &UpdateFileIfChanged ($old_tree_index, $new_tree_index, 0);
4832     &OutputObjectList;
4835 #############################################################################
4836 # Function    : ReadInterfaces
4837 # Description : This reads in the $MODULE.interfaces file.
4839 # Arguments   : none
4840 #############################################################################
4842 sub ReadInterfaces {
4843     %Interfaces = ();
4845     if (! -f $INTERFACES_FILE) {
4846         return;
4847     }
4848     if (!open (INPUT, $INTERFACES_FILE)) {
4849         warn "Can't open $INTERFACES_FILE - skipping interfaces\n";
4850         return;
4851     }
4853     while (<INPUT>) {
4854        chomp;
4855        my ($object, @ifaces) = split;
4856        if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
4857            my @knownIfaces = ();
4859            # filter out private interfaces, but leave foreign interfaces
4860            foreach my $iface (@ifaces) {
4861                if (!exists($KnownSymbols{$iface}) || $KnownSymbols{$iface} == 1) {
4862                    push (@knownIfaces, $iface);
4863                }
4864              }
4866            $Interfaces{$object} = join(' ', @knownIfaces);
4867        }
4868     }
4869     close (INPUT);
4872 #############################################################################
4873 # Function    : ReadPrerequisites
4874 # Description : This reads in the $MODULE.prerequisites file.
4876 # Arguments   : none
4877 #############################################################################
4879 sub ReadPrerequisites {
4880     %Prerequisites = ();
4882     if (! -f $PREREQUISITES_FILE) {
4883         return;
4884     }
4885     if (!open (INPUT, $PREREQUISITES_FILE)) {
4886         warn "Can't open $PREREQUISITES_FILE - skipping prerequisites\n";
4887         return;
4888     }
4890     while (<INPUT>) {
4891        chomp;
4892        my ($iface, @prereqs) = split;
4893        if (exists($KnownSymbols{$iface}) && $KnownSymbols{$iface} == 1) {
4894            my @knownPrereqs = ();
4896            # filter out private prerequisites, but leave foreign prerequisites
4897            foreach my $prereq (@prereqs) {
4898                if (!exists($KnownSymbols{$prereq}) || $KnownSymbols{$prereq} == 1) {
4899                   push (@knownPrereqs, $prereq);
4900                }
4901            }
4903            $Prerequisites{$iface} = join(' ', @knownPrereqs);
4904        }
4905     }
4906     close (INPUT);
4909 #############################################################################
4910 # Function    : ReadArgsFile
4911 # Description : This reads in an existing file which contains information on
4912 #               all GTK args. It creates the arrays @ArgObjects, @ArgNames,
4913 #               @ArgTypes, @ArgFlags, @ArgNicks and @ArgBlurbs containing info
4914 #               on the args.
4915 # Arguments   : $file - the file containing the arg information.
4916 #############################################################################
4918 sub ReadArgsFile {
4919     my ($file) = @_;
4921     my $in_arg = 0;
4922     my $arg_object;
4923     my $arg_name;
4924     my $arg_type;
4925     my $arg_flags;
4926     my $arg_nick;
4927     my $arg_blurb;
4928     my $arg_default;
4929     my $arg_range;
4931     # Reset the args info.
4932     @ArgObjects = ();
4933     @ArgNames = ();
4934     @ArgTypes = ();
4935     @ArgFlags = ();
4936     @ArgNicks = ();
4937     @ArgBlurbs = ();
4938     @ArgDefaults = ();
4939     @ArgRanges = ();
4941     if (! -f $file) {
4942         return;
4943     }
4944     if (!open (INPUT, $file)) {
4945         warn "Can't open $file - skipping args\n";
4946         return;
4947     }
4948     while (<INPUT>) {
4949         if (!$in_arg) {
4950             if (m/^<ARG>/) {
4951                 $in_arg = 1;
4952                 $arg_object = "";
4953                 $arg_name = "";
4954                 $arg_type = "";
4955                 $arg_flags = "";
4956                 $arg_nick = "";
4957                 $arg_blurb = "";
4958                 $arg_default = "";
4959                 $arg_range = "";
4960             }
4961         } else {
4962             if (m/^<NAME>(.*)<\/NAME>/) {
4963                 $arg_name = $1;
4964                 if ($arg_name =~ m/^(.*)::(.*)$/) {
4965                     $arg_object = $1;
4966                     ($arg_name = $2) =~ s/_/-/g;
4967                     #print "Found arg: $arg_name\n";
4968                 } else {
4969                     &LogWarning ($file, $., "Invalid argument name: $arg_name");
4970                 }
4971             } elsif (m/^<TYPE>(.*)<\/TYPE>/) {
4972                 $arg_type = $1;
4973             } elsif (m/^<RANGE>(.*)<\/RANGE>/) {
4974                 $arg_range = $1;
4975             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
4976                 $arg_flags = $1;
4977             } elsif (m/^<NICK>(.*)<\/NICK>/) {
4978                 $arg_nick = $1;
4979             } elsif (m/^<BLURB>(.*)<\/BLURB>/) {
4980                 $arg_blurb = $1;
4981                 if ($arg_blurb eq "(null)") {
4982                   $arg_blurb = "";
4983                   &LogWarning ($file, $., "Property ${arg_object}:${arg_name} has no documentation.");
4984                 }
4985             } elsif (m/^<DEFAULT>(.*)<\/DEFAULT>/) {
4986                 $arg_default = $1;
4987             } elsif (m%^</ARG>%) {
4988                 #print "Found end of arg: ${arg_object}::${arg_name}\n${arg_type} : ${arg_flags}\n";
4989                 push (@ArgObjects, $arg_object);
4990                 push (@ArgNames, $arg_name);
4991                 push (@ArgTypes, $arg_type);
4992                 push (@ArgRanges, $arg_range);
4993                 push (@ArgFlags, $arg_flags);
4994                 push (@ArgNicks, $arg_nick);
4995                 push (@ArgBlurbs, $arg_blurb);
4996                 push (@ArgDefaults, $arg_default);
4997                 $in_arg = 0;
4998             }
4999         }
5000     }
5001     close (INPUT);
5005 #############################################################################
5006 # Function    : CheckIsObject
5007 # Description : Returns 1 if the given name is a GtkObject or a subclass.
5008 #               It uses the global @Objects array.
5009 #               Note that the @Objects array only contains classes in the
5010 #               current module and their ancestors - not all GTK classes.
5011 # Arguments   : $name - the name to check.
5012 #############################################################################
5014 sub CheckIsObject {
5015     my ($name) = @_;
5017     my $object;
5018     foreach $object (@Objects) {
5019         if ($object eq $name) {
5020             return 1;
5021         }
5022     }
5023     return 0;
5027 #############################################################################
5028 # Function    : MakeReturnField
5029 # Description : Pads a string to $RETURN_TYPE_FIELD_WIDTH.
5030 # Arguments   : $str - the string to pad.
5031 #############################################################################
5033 sub MakeReturnField {
5034     my ($str) = @_;
5036     return $str . (' ' x ($RETURN_TYPE_FIELD_WIDTH - length ($str)));
5039 #############################################################################
5040 # Function    : GetSymbolSourceFile
5041 # Description : Get the filename where the symbol docs where taken from.
5042 # Arguments   : $symbol - the symbol name
5043 #############################################################################
5045 sub GetSymbolSourceFile {
5046     my ($symbol) = @_;
5048     if (defined($SourceSymbolSourceFile{$symbol})) {
5049         return $SourceSymbolSourceFile{$symbol};
5050     } elsif (defined($SymbolSourceFile{$symbol})) {
5051         return $SymbolSourceFile{$symbol};
5052     } else {
5053         return "";
5054     }
5057 #############################################################################
5058 # Function    : GetSymbolSourceLine
5059 # Description : Get the file line where the symbol docs where taken from.
5060 # Arguments   : $symbol - the symbol name
5061 #############################################################################
5063 sub GetSymbolSourceLine {
5064     my ($symbol) = @_;
5066     if (defined($SourceSymbolSourceLine{$symbol})) {
5067         return $SourceSymbolSourceLine{$symbol};
5068     } elsif (defined($SymbolSourceLine{$symbol})) {
5069         return $SymbolSourceLine{$symbol};
5070     } else {
5071         return 0;
5072     }