test: add a second enum to test merging of hierarchies
[gtk-doc.git] / gtkdoc-mkdb.in
blob338a968960e126d99b737a300fd95649eb8df068
1 #!@PERL@ -w
2 # -*- cperl -*-
4 # gtk-doc - GTK DocBook documentation generator.
5 # Copyright (C) 1998  Damon Chaplin
6 #               2007,2008,2009  Stefan Kost
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 #############################################################################
24 # Script      : gtkdoc-mkdb
25 # Description : This creates the DocBook files from the edited templates.
26 #############################################################################
28 use warnings;
29 use strict;
30 use Getopt::Long;
32 push @INC, '@PACKAGE_DATA_DIR@';
33 require "gtkdoc-common.pl";
35 # Options
37 # name of documentation module
38 my $MODULE;
39 my $TMPL_DIR;
40 my $SGML_OUTPUT_DIR;
41 my @SOURCE_DIRS;
42 my $SOURCE_SUFFIXES = "";
43 my $IGNORE_FILES = "";
44 my $PRINT_VERSION;
45 my $PRINT_HELP;
46 my $MAIN_SGML_FILE;
47 my $EXPAND_CONTENT_FILES = "";
48 my $INLINE_MARKUP_MODE;
49 my $DEFAULT_STABILITY;
50 my $DEFAULT_INCLUDES;
51 my $OUTPUT_FORMAT;
52 my $NAME_SPACE = "";
53 my $OUTPUT_ALL_SYMBOLS;
54 my $OUTPUT_SYMBOLS_WITHOUT_SINCE;
56 my %optctl = ('module' => \$MODULE,
57               'source-dir' => \@SOURCE_DIRS,
58               'source-suffixes' => \$SOURCE_SUFFIXES,
59               'ignore-files' => \$IGNORE_FILES,
60               'output-dir' => \$SGML_OUTPUT_DIR,
61               'tmpl-dir' => \$TMPL_DIR,
62               'version' => \$PRINT_VERSION,
63               'help' => \$PRINT_HELP,
64               'main-sgml-file' => \$MAIN_SGML_FILE,
65               'expand-content-files' => \$EXPAND_CONTENT_FILES,
66               'sgml-mode' => \$INLINE_MARKUP_MODE,
67               'xml-mode' => \$INLINE_MARKUP_MODE,
68               'default-stability' => \$DEFAULT_STABILITY,
69               'default-includes' => \$DEFAULT_INCLUDES,
70               'output-format' => \$OUTPUT_FORMAT,
71               'name-space' => \$NAME_SPACE,
72               'outputallsymbols' => \$OUTPUT_ALL_SYMBOLS,
73               'outputsymbolswithoutsince' => \$OUTPUT_SYMBOLS_WITHOUT_SINCE
74               );
75 GetOptions(\%optctl, "module=s", "source-dir:s", "source-suffixes:s",
76     "ignore-files:s", "output-dir:s", "tmpl-dir:s", "version", "outputallsymbols",
77     "outputsymbolswithoutsince",
78     "expand-content-files:s", "main-sgml-file:s", "extra-db-files:s", "help",
79     "sgml-mode", "xml-mode", "default-stability:s", "default-includes:s",
80     "output-format:s", "name-space:s");
82 if ($PRINT_VERSION) {
83     print "@VERSION@\n";
84     exit 0;
87 if (!$MODULE) {
88     $PRINT_HELP = 1;
91 if ($DEFAULT_STABILITY && $DEFAULT_STABILITY ne "Stable"
92     && $DEFAULT_STABILITY ne "Private" && $DEFAULT_STABILITY ne "Unstable") {
93     $PRINT_HELP = 1;
96 if ($PRINT_HELP) {
97     print <<EOF;
98 gtkdoc-mkdb version @VERSION@ - generate docbook files
100 --module=MODULE_NAME       Name of the doc module being parsed
101 --source-dir=DIRNAME       Directories which contain inline reference material
102 --source-suffixes=SUFFIXES Suffixes of source files to scan, comma-separated
103 --ignore-files=FILES       Files or directories which should not be scanned
104                            May be used more than once for multiple directories
105 --output-dir=DIRNAME       Directory to put the generated DocBook files in
106 --tmpl-dir=DIRNAME         Directory in which template files may be found
107 --main-sgml-file=FILE      File containing the toplevel DocBook file.
108 --expand-content-files=FILES Extra DocBook files to expand abbreviations in.
109 --output-format=FORMAT     Format to use for the generated docbook, XML or SGML.
110 --{xml,sgml}-mode          Allow DocBook markup in inline documentation.
111 --default-stability=LEVEL  Specify default stability Level. Valid values are
112                            Stable, Unstable, or Private.
113 --default-includes=FILENAMES Specify default includes for section Synopsis
114 --name-space=NS            Omit namespace in index.
115 --version                  Print the version of this program
116 --help                     Print this help
118     exit 0;
121 my ($empty_element_end, $doctype_header);
123 # autodetect output format
124 if (! defined($OUTPUT_FORMAT) || ($OUTPUT_FORMAT eq "")) {
125     if (!$MAIN_SGML_FILE) {
126         if (-e "${MODULE}-docs.xml") {
127             $OUTPUT_FORMAT = "xml";
128         } else {
129             $OUTPUT_FORMAT = "sgml";
130         }
131     } else {
132         if ($MAIN_SGML_FILE =~ m/.*\.(.*ml)$/i) {
133             $OUTPUT_FORMAT = lc($1);
134         }
135     }
137 } else {
138     $OUTPUT_FORMAT = lc($OUTPUT_FORMAT);
141 #print "DEBUG: output-format: [$OUTPUT_FORMAT]\n";
143 if ($OUTPUT_FORMAT eq "xml") {
144     if (!$MAIN_SGML_FILE) {
145         # backwards compatibility
146         if (-e "${MODULE}-docs.sgml") {
147             $MAIN_SGML_FILE = "${MODULE}-docs.sgml";
148         } else {
149             $MAIN_SGML_FILE = "${MODULE}-docs.xml";
150         }
151     }
152     $empty_element_end = "/>";
154     if (-e $MAIN_SGML_FILE) {
155         open(INPUT, "<$MAIN_SGML_FILE") || die "Can't open $MAIN_SGML_FILE";
156         $doctype_header = "";
157         while (<INPUT>) {
158             if (/^\s*<(book|chapter|article)/) {
159                 # check that the top-level tag or the doctype decl contain the xinclude namespace decl
160                 if (($_ !~ m/http:\/\/www.w3.org\/200[13]\/XInclude/) && ($doctype_header !~ m/http:\/\/www.w3.org\/200[13]\/XInclude/m)) {
161                     $doctype_header = "";
162                 }
163                 last;
164             }
165             $doctype_header .= $_;
166         }
167         close(INPUT);
168         $doctype_header =~ s/<!DOCTYPE \w+/<!DOCTYPE refentry/;
169         # if there are SYSTEM ENTITIES here, we should prepend "../" to the path
170         # FIXME: not sure if we can do this now, as people already work-around the problem
171         # $doctype_header =~ s#<!ENTITY % ([a-zA-Z-]+) SYSTEM \"([^/][a-zA-Z./]+)\">#<!ENTITY % $1 SYSTEM \"../$2\">#g;
172     } else {
173         $doctype_header =
174 "<?xml version=\"1.0\"?>\n" .
175 "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.3//EN\"\n" .
176 "               \"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd\"\n" .
177 "[\n" .
178 "  <!ENTITY % local.common.attrib \"xmlns:xi  CDATA  #FIXED 'http://www.w3.org/2003/XInclude'\">\n" .
179 "]>\n";
180     }
181 } else {
182     if (!$MAIN_SGML_FILE) {
183         $MAIN_SGML_FILE = "${MODULE}-docs.sgml";
184     }
185     $empty_element_end = ">";
186     $doctype_header = "";
189 my $ROOT_DIR = ".";
191 # All the files are written in subdirectories beneath here.
192 $TMPL_DIR = $TMPL_DIR ? $TMPL_DIR : "$ROOT_DIR/tmpl";
194 # This is where we put all the DocBook output.
195 $SGML_OUTPUT_DIR = $SGML_OUTPUT_DIR ? $SGML_OUTPUT_DIR : "$ROOT_DIR/$OUTPUT_FORMAT";
197 # This file contains the object hierarchy.
198 my $OBJECT_TREE_FILE = "$ROOT_DIR/$MODULE.hierarchy";
200 # This file contains the interfaces.
201 my $INTERFACES_FILE = "$ROOT_DIR/$MODULE.interfaces";
203 # This file contains the prerequisites.
204 my $PREREQUISITES_FILE = "$ROOT_DIR/$MODULE.prerequisites";
206 # This file contains signal arguments and names.
207 my $SIGNALS_FILE = "$ROOT_DIR/$MODULE.signals";
209 # The file containing Arg information.
210 my $ARGS_FILE = "$ROOT_DIR/$MODULE.args";
212 # These global arrays store information on signals. Each signal has an entry
213 # in each of these arrays at the same index, like a multi-dimensional array.
214 my @SignalObjects;        # The GtkObject which emits the signal.
215 my @SignalNames;        # The signal name.
216 my @SignalReturns;        # The return type.
217 my @SignalFlags;        # Flags for the signal
218 my @SignalPrototypes;        # The rest of the prototype of the signal handler.
220 # These global arrays store information on Args. Each Arg has an entry
221 # in each of these arrays at the same index, like a multi-dimensional array.
222 my @ArgObjects;                # The GtkObject which has the Arg.
223 my @ArgNames;                # The Arg name.
224 my @ArgTypes;                # The Arg type - gint, GtkArrowType etc.
225 my @ArgFlags;                # How the Arg can be used - readable/writable etc.
226 my @ArgNicks;                # The nickname of the Arg.
227 my @ArgBlurbs;          # Docstring of the Arg.
228 my @ArgDefaults;        # Default value of the Arg.
229 my @ArgRanges;                # The range of the Arg type
230 # These global hashes store declaration info keyed on a symbol name.
231 my %Declarations;
232 my %DeclarationTypes;
233 my %DeclarationConditional;
234 my %DeclarationOutput;
235 my %Deprecated;
236 my %Since;
237 my %StabilityLevel;
238 my %StructHasTypedef;
240 # These global hashes store the existing documentation.
241 my %SymbolDocs;
242 my %SymbolTypes;
243 my %SymbolParams;
244 my %SymbolSourceFile;
245 my %SymbolSourceLine;
247 # These global hashes store documentation scanned from the source files.
248 my %SourceSymbolDocs;
249 my %SourceSymbolParams;
250 my %SourceSymbolSourceFile;
251 my %SourceSymbolSourceLine;
253 # all documentation goes in here, so we can do coverage analysis
254 my %AllSymbols;
255 my %AllIncompleteSymbols;
256 my %AllUnusedSymbols;
257 my %AllDocumentedSymbols;
259 # Undeclared yet documented symbols
260 my %UndeclaredSymbols;
262 # These global arrays store GObject, subclasses and the hierarchy (also of
263 # non-object derived types).
264 my @Objects;
265 my @ObjectLevels;
266 my %ObjectRoots;
268 my %Interfaces;
269 my %Prerequisites;
271 # holds the symbols which are mentioned in $MODULE-sections.txt and in which
272 # section they are defined
273 my %KnownSymbols;
274 my %SymbolSection;
275 my %SymbolSectionId;
277 # collects index entries
278 my %IndexEntriesFull;
279 my %IndexEntriesSince;
280 my %IndexEntriesDeprecated;
282 # Standard C preprocessor directives, which we ignore for '#' abbreviations.
283 my %PreProcessorDirectives;
284 $PreProcessorDirectives{"assert"} = 1;
285 $PreProcessorDirectives{"define"} = 1;
286 $PreProcessorDirectives{"elif"} = 1;
287 $PreProcessorDirectives{"else"} = 1;
288 $PreProcessorDirectives{"endif"} = 1;
289 $PreProcessorDirectives{"error"} = 1;
290 $PreProcessorDirectives{"if"} = 1;
291 $PreProcessorDirectives{"ifdef"} = 1;
292 $PreProcessorDirectives{"ifndef"} = 1;
293 $PreProcessorDirectives{"include"} = 1;
294 $PreProcessorDirectives{"line"} = 1;
295 $PreProcessorDirectives{"pragma"} = 1;
296 $PreProcessorDirectives{"unassert"} = 1;
297 $PreProcessorDirectives{"undef"} = 1;
298 $PreProcessorDirectives{"warning"} = 1;
300 # remember used annotation (to write minimal glossary)
301 my %AnnotationsUsed;
303 # the annotations are defined at:
304 # https://live.gnome.org/GObjectIntrospection/Annotations
305 my %AnnotationDefinition = (
306     'allow-none' => "NULL is ok, both for passing and for returning.",
307     'array' => "Parameter points to an array of items.",
308     'attribute' => "Deprecated free-form custom annotation, replaced by (attributes) annotation.",
309     'attributes' => "Free-form key-value pairs.",
310     'closure' => "This parameter is a 'user_data', for callbacks; many bindings can pass NULL here.",
311     'constructor' => "This symbol is a constructor, not a static method.",
312     'destroy' => "This parameter is a 'destroy_data', for callbacks.",
313     'default' => "Default parameter value (for in case the <acronym>shadows</acronym>-to function has less parameters).",
314     'element-type' => "Generics and defining elements of containers and arrays.",
315     'error-domains' => "Typed errors. Similar to throws in Java.",
316     'foreign' => "This is a foreign struct.",
317     'get-value-func' => "The specified function is used to convert a struct from a GValue, must be a GTypeInstance.",
318     'in' => "Parameter for input. Default is <acronym>transfer none</acronym>.",
319     'inout' => "Parameter for input and for returning results. Default is <acronym>transfer full</acronym>.",
320     'in-out' => "Parameter for input and for returning results. Default is <acronym>transfer full</acronym>.",
321     'method' => "This is a method",
322     'not-error' => "A GError parameter is not to be handled like a normal GError.",
323     'out' => "Parameter for returning results. Default is <acronym>transfer full</acronym>.",
324     'out caller-allocates' => "Out parameter, where caller must allocate storage.",
325     'out callee-allocates' => "Out parameter, where caller must allocate storage.",
326     'ref-func' => "The specified function is used to ref a struct, must be a GTypeInstance.",
327     'rename-to' => "Rename the original symbol's name to SYMBOL.",
328     'scope call' => "The callback is valid only during the call to the method.",
329     'scope async' => "The callback is valid until first called.",
330     'scope notified' => "The callback is valid until the GDestroyNotify argument is called.",
331     'set-value-func' => "The specified function is used to convert from a struct to a GValue, must be a GTypeInstance.",
332     'skip' => "Exposed in C code, not necessarily available in other languages.",
333     'transfer container' => "Free data container after the code is done.",
334     'transfer floating' => "Alias for <acronym>transfer none</acronym>, used for objects with floating refs.",
335     'transfer full' => "Free data after the code is done.",
336     'transfer none' => "Don't free data after the code is done.",
337     'type' => "Override the parsed C type with given type.",
338     'unref-func' => "The specified function is used to unref a struct, must be a GTypeInstance.",
339     'virtual' => "This is the invoker for a virtual method.",
340     'value' => "The specified value overrides the evaluated value of the constant."
343 # Elements to consider non-block items in MarkDown parsing
344 my %MD_TEXT_LEVEL_ELEMENTS = ( "literal" => 1,
345                                "emphasis" => 1,
346                                "envar" => 1,
347                                "filename" => 1,
348                                "firstterm" => 1,
349                                "function" => 1,
350                                "manvolnum" => 1,
351                                "option" => 1,
352                                "replaceable" => 1,
353                                "structname" => 1,
354                                "title" => 1,
355                                "varname" => 1 );
356 my %MD_ESCAPABLE_CHARS = ( "\\" => 1,
357                            "`" => 1,
358                            "*" => 1,
359                            "_" => 1,
360                            "{" => 1,
361                            "}" => 1,
362                            "[" => 1,
363                            "]" => 1,
364                            "(" => 1,
365                            ")" => 1,
366                            ">" => 1,
367                            "#" => 1,
368                            "+" => 1,
369                            "-" => 1,
370                            "." => 1,
371                            "!" => 1 );
372 my %MD_GTK_ESCAPABLE_CHARS = ( "@" => 1,
373                                "%" => 1 );
375 # Create the root DocBook output directory if it doens't exist.
376 if (! -e $SGML_OUTPUT_DIR) {
377     mkdir ("$SGML_OUTPUT_DIR", 0777)
378         || die "Can't create directory: $SGML_OUTPUT_DIR";
381 # Function and other declaration output settings.
382 my $RETURN_TYPE_FIELD_WIDTH = 20;
383 my $SYMBOL_FIELD_WIDTH = 36;
384 my $MAX_SYMBOL_FIELD_WIDTH = 40;
385 my $SIGNAL_FIELD_WIDTH = 16;
386 my $PARAM_FIELD_COUNT = 2;
388 &ReadKnownSymbols ("$ROOT_DIR/$MODULE-sections.txt");
389 &ReadSignalsFile ($SIGNALS_FILE);
390 &ReadArgsFile ($ARGS_FILE);
391 &ReadObjectHierarchy;
392 &ReadInterfaces;
393 &ReadPrerequisites;
395 &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-decl.txt", 0);
396 if (-f "$ROOT_DIR/$MODULE-overrides.txt") {
397     &ReadDeclarationsFile ("$ROOT_DIR/$MODULE-overrides.txt", 1);
400 for my $dir (@SOURCE_DIRS) {
401     &ReadSourceDocumentation ($dir);
404 my $changed = &OutputSGML ("$ROOT_DIR/$MODULE-sections.txt");
406 # If any of the DocBook SGML files have changed, update the timestamp file (so
407 # it can be used for Makefile dependencies).
408 if ($changed || ! -e "$ROOT_DIR/sgml.stamp") {
410     # try to detect the common prefix
411     # GtkWidget, GTK_WIDGET, gtk_widget -> gtk
412     if ($NAME_SPACE eq "") {
413         $NAME_SPACE="";
414         my $pos=0;
415         my $ratio=0.0;
416         do {
417             my %prefix;
418             my $letter="";
419             foreach my $symbol (keys(%IndexEntriesFull)) {
420                 if(($NAME_SPACE eq "") || $symbol =~ /^$NAME_SPACE/i) {
421                     if (length($symbol)>$pos) {
422                         $letter=substr($symbol,$pos,1);
423                         # stop prefix scanning
424                         if ($letter eq "_") {
425                             # stop on "_"
426                             last;
427                         }
428                         # Should we also stop on a uppercase char, if last was lowercase
429                         #   GtkWidget, if we have the 'W' and had the 't' before
430                         # or should we count upper and lowercase, and stop one 2nd uppercase, if we already had a lowercase
431                         #   GtkWidget, the 'W' would be the 2nd uppercase and with 't','k' we had lowercase chars before
432                         # need to recound each time as this is per symbol
433                         $prefix{uc($letter)}++;
434                     }
435                 }
436             }
437             if ($letter ne "" && $letter ne "_") {
438                 my $maxletter="";
439                 my $maxsymbols=0;
440                 foreach $letter (keys(%prefix)) {
441                     #print "$letter: $prefix{$letter}.\n";
442                     if ($prefix{$letter}>$maxsymbols) {
443                         $maxletter=$letter;
444                         $maxsymbols=$prefix{$letter};
445                     }
446                 }
447                 $ratio = scalar(keys(%IndexEntriesFull)) / $prefix{$maxletter};
448                 #print "most symbols start with $maxletter, that is ". (100 * $ratio) ." %\n";
449                 if ($ratio > 0.9) {
450                     # do another round
451                     $NAME_SPACE .= $maxletter;
452                 }
453                 $pos++;
454             }
455             else {
456                 $ratio=0.0;
457             }
458         } while ($ratio > 0.9);
459         #print "most symbols start with $NAME_SPACE\n";
460     }
462     &OutputIndexFull;
463     &OutputDeprecatedIndex;
464     &OutputSinceIndexes;
465     &OutputAnnotationGlossary;
467     open (TIMESTAMP, ">$ROOT_DIR/sgml.stamp")
468         || die "Can't create $ROOT_DIR/sgml.stamp: $!";
469     print (TIMESTAMP "timestamp");
470     close (TIMESTAMP);
473 #############################################################################
474 # Function    : OutputObjectList
475 # Description : This outputs the alphabetical list of objects, in a columned
476 #                table.
477 #               FIXME: Currently this also outputs ancestor objects
478 #                which may not actually be in this module.
479 # Arguments   : none
480 #############################################################################
482 sub OutputObjectList {
483     my $cols = 3;
485     # FIXME: use $OUTPUT_FORMAT
486     # my $old_object_index = "$SGML_OUTPUT_DIR/object_index.$OUTPUT_FORMAT";
487     my $old_object_index = "$SGML_OUTPUT_DIR/object_index.sgml";
488     my $new_object_index = "$SGML_OUTPUT_DIR/object_index.new";
490     open (OUTPUT, ">$new_object_index")
491         || die "Can't create $new_object_index: $!";
493     if ($OUTPUT_FORMAT eq "xml") {
494         my $header = $doctype_header;
496         $header =~ s/<!DOCTYPE \w+/<!DOCTYPE informaltable/;
497         print (OUTPUT "$header");
498     }
500     print (OUTPUT <<EOF);
501 <informaltable pgwide="1" frame="none">
502 <tgroup cols="$cols">
503 <colspec colwidth="1*"${empty_element_end}
504 <colspec colwidth="1*"${empty_element_end}
505 <colspec colwidth="1*"${empty_element_end}
506 <tbody>
509     my $count = 0;
510     my $object;
511     foreach $object (sort (@Objects)) {
512         my $xref = &MakeXRef ($object);
513         if ($count % $cols == 0) { print (OUTPUT "<row>\n"); }
514         print (OUTPUT "<entry>$xref</entry>\n");
515         if ($count % $cols == ($cols - 1)) { print (OUTPUT "</row>\n"); }
516         $count++;
517     }
518     if ($count == 0) {
519         # emit an empty row, since empty tables are invalid
520         print (OUTPUT "<row><entry> </entry></row>\n");
521     }
522     else {
523         if ($count % $cols > 0) {
524             print (OUTPUT "</row>\n");
525         }
526     }
528     print (OUTPUT <<EOF);
529 </tbody></tgroup></informaltable>
531     close (OUTPUT);
533     &UpdateFileIfChanged ($old_object_index, $new_object_index, 0);
536 #############################################################################
537 # Function    : TrimTextBlock
538 # Description : Trims extra whitespace. Empty lines inside a block are
539 #                preserved.
540 # Arguments   : $desc - the text block to trim. May contain newlines.
541 #############################################################################
543 sub TrimTextBlock {
544   my ($desc) = @_;
545   
546   # strip leading spaces on the block
547   $desc =~ s/^\s+//s;
548   # strip trailing spaces on every line
549   $desc =~ s/\s+$/\n/mg;
550   
551   return $desc;
555 #############################################################################
556 # Function    : OutputSGML
557 # Description : This collects the output for each section of the docs, and
558 #                outputs each file when the end of the section is found.
559 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
560 #                the functions/macros/structs etc. being documented, organised
561 #                into sections and subsections.
562 #############################################################################
564 sub OutputSGML {
565     my ($file) = @_;
567     #print "Reading: $file\n";
568     open (INPUT, $file)
569         || die "Can't open $file: $!";
570     my $filename = "";
571     my $book_top = "";
572     my $book_bottom = "";
573     my $includes = (defined $DEFAULT_INCLUDES) ? $DEFAULT_INCLUDES : "";
574     my $section_includes = "";
575     my $in_section = 0;
576     my $title = "";
577     my $section_id = "";
578     my $subsection = "";
579     my $num_symbols;
580     my $changed = 0;
581     my $functions_synop = "";
582     my $other_synop = "";
583     my $functions_details = "";
584     my $other_details = "";
585     my $signals_synop = "";
586     my $signals_desc = "";
587     my $args_synop = "";
588     my $child_args_synop = "";
589     my $style_args_synop = "";
590     my $args_desc = "";
591     my $child_args_desc = "";
592     my $style_args_desc = "";
593     my $hierarchy = "";
594     my $interfaces = "";
595     my $implementations = "";
596     my $prerequisites = "";
597     my $derived = "";
598     my @file_objects = ();
599     my %templates = ();
600     my %symbol_def_line = ();
602     # merge the source docs, in case there are no templates
603     &MergeSourceDocumentation;
605     while (<INPUT>) {
606         if (m/^#/) {
607             next;
609         } elsif (m/^<SECTION>/) {
610             $num_symbols = 0;
611             $in_section = 1;
612             @file_objects = ();
613             %symbol_def_line = ();
615         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
616             $other_synop .= "\n";
617             $functions_synop .= "\n";
618             $subsection = $1;
620         } elsif (m/^<SUBSECTION>/) {
622         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
623             $title = $1;
624             #print "Section: $title\n";
626             # We don't want warnings if object & class structs aren't used.
627             $DeclarationOutput{$title} = 1;
628             $DeclarationOutput{"${title}Class"} = 1;
629             $DeclarationOutput{"${title}Iface"} = 1;
630             $DeclarationOutput{"${title}Interface"} = 1;
632         } elsif (m/^<FILE>(.*)<\/FILE>/) {
633             $filename = $1;
634             if (! defined $templates{$filename}) {
635                if (&ReadTemplateFile ("$TMPL_DIR/$filename", 1)) {
636                    &MergeSourceDocumentation;
637                    $templates{$filename}=$.;
638                }
639             } else {
640                 &LogWarning ($file, $., "Double <FILE>$filename</FILE> entry. ".
641                     "Previous occurrence on line ".$templates{$filename}.".");
642             }
643             if (($title eq "") and (defined $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"})) {
644                 $title = $SourceSymbolDocs{"$TMPL_DIR/$filename:Title"};
645                  # Remove trailing blanks
646                 $title =~ s/\s+$//;
647            }
649         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
650             if ($in_section) {
651                 $section_includes = $1;
652             } else {
653                 if (defined $DEFAULT_INCLUDES) {
654                     &LogWarning ($file, $., "Default <INCLUDE> being overridden by command line option.");
655                 }
656                 else {
657                     $includes = $1;
658                 }
659             }
661         } elsif (m/^<\/SECTION>/) {
662             #print "End of section: $title\n";
663             if ($num_symbols > 0) {
664                 # collect documents
665                 if ($OUTPUT_FORMAT eq "xml") {
666                     $book_bottom .= "    <xi:include href=\"xml/$filename.xml\"/>\n";
667                 } else {
668                     $book_top.="<!ENTITY $section_id SYSTEM \"sgml/$filename.sgml\">\n";
669                     $book_bottom .= "    &$section_id;\n";
670                 }
672                 if (defined ($SourceSymbolDocs{"$TMPL_DIR/$filename:Include"})) {
673                     if ($section_includes) {
674                         &LogWarning ($file, $., "Section <INCLUDE> being overridden by inline comments.");
675                     }
676                     $section_includes = $SourceSymbolDocs{"$TMPL_DIR/$filename:Include"};
677                 }
678                 if ($section_includes eq "") {
679                     $section_includes = $includes;
680                 }
682                  $signals_synop =~ s/^\n*//g;
683                  $signals_synop =~ s/\n+$/\n/g;
684                 if ($signals_synop ne '') {
685                     $signals_synop = <<EOF;
686 <refsect1 id="$section_id.signals" role="signal_proto">
687 <title role="signal_proto.title">Signals</title>
688 <informaltable frame="none">
689 <tgroup cols="3">
690 <colspec colname="signals_return" colwidth="150px"/>
691 <colspec colname="signals_name" colwidth="300px"/>
692 <colspec colname="signals_flags" colwidth="200px"/>
693 <tbody>
694 ${signals_synop}
695 </tbody>
696 </tgroup>
697 </informaltable>
698 </refsect1>
700                      $signals_desc = TrimTextBlock($signals_desc);
701                     $signals_desc  = <<EOF;
702 <refsect1 id="$section_id.signal-details" role="signals">
703 <title role="signals.title">Signal Details</title>
704 $signals_desc
705 </refsect1>
707                 }
709                 $args_synop =~ s/^\n*//g;
710                 $args_synop =~ s/\n+$/\n/g;
711                 if ($args_synop ne '') {
712                     $args_synop = <<EOF;
713 <refsect1 id="$section_id.properties" role="properties">
714 <title role="properties.title">Properties</title>
715 <informaltable frame="none">
716 <tgroup cols="3">
717 <colspec colname="properties_type" colwidth="150px"/>
718 <colspec colname="properties_name" colwidth="300px"/>
719 <colspec colname="properties_flags" colwidth="200px"/>
720 <tbody>
721 ${args_synop}
722 </tbody>
723 </tgroup>
724 </informaltable>
725 </refsect1>
727                      $args_desc = TrimTextBlock($args_desc);
728                     $args_desc  = <<EOF;
729 <refsect1 id="$section_id.property-details" role="property_details">
730 <title role="property_details.title">Property Details</title>
731 $args_desc
732 </refsect1>
734                 }
736                 $child_args_synop =~ s/^\n*//g;
737                 $child_args_synop =~ s/\n+$/\n/g;
738                 if ($child_args_synop ne '') {
739                     $args_synop .= <<EOF;
740 <refsect1 id="$section_id.child-properties" role="child_properties">
741 <title role="child_properties.title">Child Properties</title>
742 <informaltable frame="none">
743 <tgroup cols="3">
744 <colspec colname="child_properties_type" colwidth="150px"/>
745 <colspec colname="child_properties_name" colwidth="300px"/>
746 <colspec colname="child_properties_flags" colwidth="200px"/>
747 <tbody>
748 ${child_args_synop}
749 </tbody>
750 </tgroup>
751 </informaltable>
752 </refsect1>
754                      $child_args_desc = TrimTextBlock($child_args_desc);
755                      $args_desc .= <<EOF;
756 <refsect1 id="$section_id.child-property-details" role="child_property_details">
757 <title role="child_property_details.title">Child Property Details</title>
758 $child_args_desc
759 </refsect1>
761                 }
763                 $style_args_synop =~ s/^\n*//g;
764                 $style_args_synop =~ s/\n+$/\n/g;
765                 if ($style_args_synop ne '') {
766                     $args_synop .= <<EOF;
767 <refsect1 id="$section_id.style-properties" role="style_properties">
768 <title role="style_properties.title">Style Properties</title>
769 <informaltable frame="none">
770 <tgroup cols="3">
771 <colspec colname="style_properties_type" colwidth="150px"/>
772 <colspec colname="style_properties_name" colwidth="300px"/>
773 <colspec colname="style_properties_flags" colwidth="200px"/>
774 <tbody>
775 ${style_args_synop}
776 </tbody>
777 </tgroup>
778 </informaltable>
779 </refsect1>
781                      $style_args_desc = TrimTextBlock($style_args_desc);
782                     $args_desc .= <<EOF;
783 <refsect1 id="$section_id.style-property-details" role="style_properties_details">
784 <title role="style_properties_details.title">Style Property Details</title>
785 $style_args_desc
786 </refsect1>
788                 }
790                 $hierarchy = TrimTextBlock($hierarchy);
791                 if ($hierarchy ne "") {
792                     $hierarchy = <<EOF;
793 <refsect1 id="$section_id.object-hierarchy" role="object_hierarchy">
794 <title role="object_hierarchy.title">Object Hierarchy</title>
795 <screen>$hierarchy</screen>
796 </refsect1>
798                 }
800                  $interfaces =~ TrimTextBlock($interfaces);
801                 if ($interfaces ne "") {
802                     $interfaces = <<EOF;
803 <refsect1 id="$section_id.implemented-interfaces" role="impl_interfaces">
804 <title role="impl_interfaces.title">Implemented Interfaces</title>
805 $interfaces
806 </refsect1>
808                 }
810                  $implementations = TrimTextBlock($implementations);
811                 if ($implementations ne "") {
812                     $implementations = <<EOF;
813 <refsect1 id="$section_id.implementations" role="implementations">
814 <title role="implementations.title">Known Implementations</title>
815 $implementations
816 </refsect1>
818                 }
820                  $prerequisites = TrimTextBlock($prerequisites);
821                 if ($prerequisites ne "") {
822                     $prerequisites = <<EOF;
823 <refsect1 id="$section_id.prerequisites" role="prerequisites">
824 <title role="prerequisites.title">Prerequisites</title>
825 $prerequisites
826 </refsect1>
828                 }
830                  $derived = TrimTextBlock($derived);
831                 if ($derived ne "") {
832                     $derived = <<EOF;
833 <refsect1 id="$section_id.derived-interfaces" role="derived_interfaces">
834 <title role="derived_interfaces.title">Known Derived Interfaces</title>
835 $derived
836 </refsect1>
838                 }
840                 $functions_synop =~ s/^\n*//g;
841                 $functions_synop =~ s/\n+$/\n/g;
842                 if ($functions_synop ne '') {
843                   $functions_synop = <<EOF;
844 <refsect1 id="$section_id.functions" role="functions_proto">
845 <title role="functions_proto.title">Functions</title>
846 <informaltable pgwide="1" frame="none">
847 <tgroup cols="2">
848 <colspec colname="functions_return" colwidth="150px"/>
849 <colspec colname="functions_name"/>
850 <tbody>
851 ${functions_synop}
852 </tbody>
853 </tgroup>
854 </informaltable>
855 </refsect1>
857                 }
859                 $other_synop =~ s/^\n*//g;
860                 $other_synop =~ s/\n+$/\n/g;
861                 if ($other_synop ne '') {
862                   $other_synop = <<EOF;
863 <refsect1 id="$section_id.other" role="other_proto">
864 <title role="other_proto.title">Types and Values</title>
865 <informaltable role="enum_members_table" pgwide="1" frame="none">
866 <tgroup cols="2">
867 <colspec colname="name" colwidth="150px"/>
868 <colspec colname="description"/>
869 <tbody>
870 ${other_synop}
871 </tbody>
872 </tgroup>
873 </informaltable>
874 </refsect1>
876                 }
878                 my $file_changed = &OutputSGMLFile ($filename, $title, $section_id,
879                                                     $section_includes,
880                                                     \$functions_synop, \$other_synop,
881                                                     \$functions_details, \$other_details,
882                                                     \$signals_synop, \$signals_desc,
883                                                     \$args_synop, \$args_desc,
884                                                     \$hierarchy, \$interfaces,
885                                                     \$implementations,
886                                                     \$prerequisites, \$derived,
887                                                     \@file_objects);
888                 if ($file_changed) {
889                     $changed = 1;
890                 }
891             }
892             $title = "";
893             $section_id = "";
894             $subsection = "";
895             $in_section = 0;
896             $section_includes = "";
897             $functions_synop = "";
898             $other_synop = "";
899             $functions_details = "";
900             $other_details = "";
901             $signals_synop = "";
902             $signals_desc = "";
903             $args_synop = "";
904             $child_args_synop = "";
905             $style_args_synop = "";
906             $args_desc = "";
907             $child_args_desc = "";
908             $style_args_desc = "";
909             $hierarchy = "";
910             $interfaces = "";
911             $implementations = "";
912             $prerequisites = "";
913             $derived = "";
915         } elsif (m/^(\S+)/) {
916             my $symbol = $1;
917             @TRACE@("  Symbol: $symbol in subsection: $subsection\n");
919             # check for duplicate entries
920             if (! defined $symbol_def_line{$symbol}) {
921                 my $declaration = $Declarations{$symbol};
922                 if (defined ($declaration)) {
923                     if (&CheckIsObject ($symbol)) {
924                         push @file_objects, $symbol;
925                     }
926                     # We don't want standard macros/functions of GObjects,
927                     # or private declarations.
928                     if ($subsection ne "Standard" && $subsection ne "Private") {
929                         my ($synop, $desc) = &OutputDeclaration ($symbol,
930                                                                  $declaration);
931                         my $type = $DeclarationTypes {$symbol};
932         
933                         if ($type eq 'FUNCTION' || $type eq 'USER_FUNCTION') {
934                           $functions_synop .= $synop;
935                           $functions_details .= $desc;
936                         } elsif ($type eq 'MACRO' && $declaration =~ /$symbol[ ]*\(/) {
937                           $functions_synop .= $synop;
938                           $functions_details .= $desc;
939                         } else {
940                           $other_synop .= $synop;
941                           $other_details .= $desc;
942                         }
943                     }
944                     my ($sig_synop, $sig_desc) = &GetSignals ($symbol);
945                     my ($arg_synop, $child_arg_synop, $style_arg_synop,
946                         $arg_desc, $child_arg_desc, $style_arg_desc) = &GetArgs ($symbol);
947                     my $hier = &GetHierarchy ($symbol);
948                     my $ifaces = &GetInterfaces ($symbol);
949                     my $impls = &GetImplementations ($symbol);
950                     my $prereqs = &GetPrerequisites ($symbol);
951                     my $der = &GetDerived ($symbol);
953                     $signals_synop .= $sig_synop;
954                     $signals_desc .= $sig_desc;
955                     $args_synop .= $arg_synop;
956                     $child_args_synop .= $child_arg_synop;
957                     $style_args_synop .= $style_arg_synop;
958                     $args_desc .= $arg_desc;
959                     $child_args_desc .= $child_arg_desc;
960                     $style_args_desc .= $style_arg_desc;
961                     # FIXME: we'd like to merge e.g. multiple enums
962                     $hierarchy .= $hier;
963                     $interfaces .= $ifaces;
964                     $implementations .= $impls;
965                     $prerequisites .= $prereqs;
966                     $derived .= $der;
968                     # Note that the declaration has been output.
969                     $DeclarationOutput{$symbol} = 1;
970                 } elsif ($subsection ne "Standard" && $subsection ne "Private") {
971                     $UndeclaredSymbols{$symbol} = 1;
972                     &LogWarning ($file, $., "No declaration found for $symbol.");
973                 }
974                 $num_symbols++;
975                 $symbol_def_line{$symbol}=$.;
977                 if ($section_id eq "") {
978                     if($title eq "" && $filename eq "") {
979                         &LogWarning ($file, $., "Section has no title and no file.");
980                     }
981                     # FIXME: one of those would be enough
982                     # filename should be an internal detail for gtk-doc
983                     if ($title eq "") {
984                         $title = $filename;
985                     } elsif ($filename eq "") {
986                         $filename = $title;
987                     }
988                     $filename =~ s/\s/_/g;
990                     $section_id = $SourceSymbolDocs{"$TMPL_DIR/$filename:Section_Id"};
991                     if (defined ($section_id) && $section_id !~ m/^\s*$/) {
992                         # Remove trailing blanks and use as is
993                         $section_id =~ s/\s+$//;
994                     } elsif (&CheckIsObject ($title)) {
995                         # GObjects use their class name as the ID.
996                         $section_id = &CreateValidSGMLID ($title);
997                     } else {
998                         $section_id = &CreateValidSGMLID ("$MODULE-$title");
999                     }
1000                 }
1001                 $SymbolSection{$symbol}=$title;
1002                 $SymbolSectionId{$symbol}=$section_id;
1003             }
1004             else {
1005                 &LogWarning ($file, $., "Double symbol entry for $symbol. ".
1006                     "Previous occurrence on line ".$symbol_def_line{$symbol}.".");
1007             }
1008         }
1009     }
1010     close (INPUT);
1012     &OutputMissingDocumentation;
1013     &OutputUndeclaredSymbols;
1014     &OutputUnusedSymbols;
1016     if ($OUTPUT_ALL_SYMBOLS) {
1017         &OutputAllSymbols;
1018     }
1019     if ($OUTPUT_SYMBOLS_WITHOUT_SINCE) {
1020         &OutputSymbolsWithoutSince;
1021     }
1023     for $filename (split (' ', $EXPAND_CONTENT_FILES)) {
1024         my $file_changed = &OutputExtraFile ($filename);
1025         if ($file_changed) {
1026             $changed = 1;
1027         }
1028     }
1030     &OutputBook ($book_top, $book_bottom);
1032     return $changed;
1035 #############################################################################
1036 # Function    : OutputIndex
1037 # Description : This writes an indexlist that can be included into the main-
1038 #               document into an <index> tag.
1039 #############################################################################
1041 sub OutputIndex {
1042     my ($basename, $apiindexref ) = @_;
1043     my %apiindex = %{$apiindexref};
1044     my $old_index = "$SGML_OUTPUT_DIR/$basename.xml";
1045     my $new_index = "$SGML_OUTPUT_DIR/$basename.new";
1046     my $lastletter = " ";
1047     my $divopen = 0;
1048     my $symbol;
1049     my $short_symbol;
1051     open (OUTPUT, ">$new_index")
1052         || die "Can't create $new_index";
1054     my $header = $doctype_header;
1055     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE indexdiv/;
1057     print (OUTPUT "$header<indexdiv>\n");
1059     #print "generate $basename index (".%apiindex." entries)\n";
1061     # do a case insensitive sort while chopping off the prefix
1062     foreach my $hash (
1063         sort { $$a{criteria} cmp $$b{criteria} }
1064         map { my $x = uc($_); $x =~ s/^$NAME_SPACE\_?(.*)/$1/i; { criteria => $x, original => $_, short => $1 } }
1065         keys %apiindex) {
1067         $symbol = $$hash{original};
1068         if (defined($$hash{short})) {
1069             $short_symbol = $$hash{short};
1070         } else {
1071             $short_symbol = $symbol;
1072         }
1074         # generate a short symbol description
1075         my $symbol_desc = "";
1076         my $symbol_section = "";
1077         my $symbol_section_id = "";
1078         my $symbol_type = "";
1079         if (defined($DeclarationTypes{$symbol})) {
1080           $symbol_type = lc($DeclarationTypes{$symbol});
1081         }
1082         if ($symbol_type eq "") {
1083             #print "trying symbol $symbol\n";
1084             if ($symbol =~ m/(.*)::(.*)/) {
1085                 my $oname = $1;
1086                 my $osym = $2;
1087                 my $i;
1088                 #print "  trying object signal ${oname}:$osym in ".$#SignalNames." signals\n";
1089                 for ($i = 0; $i <= $#SignalNames; $i++) {
1090                     if ($SignalNames[$i] eq $osym) {
1091                         $symbol_type = "object signal";
1092                         if (defined($SymbolSection{$oname})) {
1093                            $symbol_section = $SymbolSection{$oname};
1094                            $symbol_section_id = $SymbolSectionId{$oname};
1095                         }
1096                         last;
1097                     }
1098                 }
1099             } elsif ($symbol =~ m/(.*):(.*)/) {
1100                 my $oname = $1;
1101                 my $osym = $2;
1102                 my $i;
1103                 #print "  trying object property ${oname}::$osym in ".$#ArgNames." properties\n";
1104                 for ($i = 0; $i <= $#ArgNames; $i++) {
1105                     #print "    ".$ArgNames[$i]."\n";
1106                     if ($ArgNames[$i] eq $osym) {
1107                         $symbol_type = "object property";
1108                         if (defined($SymbolSection{$oname})) {
1109                            $symbol_section = $SymbolSection{$oname};
1110                            $symbol_section_id = $SymbolSectionId{$oname};
1111                         }
1112                         last;
1113                     }
1114                 }
1115             }
1116         } else {
1117            if (defined($SymbolSection{$symbol})) {
1118                $symbol_section = $SymbolSection{$symbol};
1119                $symbol_section_id = $SymbolSectionId{$symbol};
1120            }
1121         }
1122         if ($symbol_type ne "") {
1123            $symbol_desc=", $symbol_type";
1124            if ($symbol_section ne "") {
1125                $symbol_desc.=" in <link linkend=\"$symbol_section_id\">$symbol_section</link>";
1126                #$symbol_desc.=" in ". &ExpandAbbreviations($symbol, "#$symbol_section");
1127            }
1128         }
1130         my $curletter = uc(substr($short_symbol,0,1));
1131         my $id = $apiindex{$symbol};
1133         #print "  add symbol $symbol with $id to index in section $curletter\n";
1135         if ($curletter ne $lastletter) {
1136             $lastletter = $curletter;
1138             if ($divopen == 1) {
1139                 print (OUTPUT "</indexdiv>\n");
1140             }
1141             print (OUTPUT "<indexdiv><title>$curletter</title>\n");
1142             $divopen = 1;
1143         }
1145         print (OUTPUT <<EOF);
1146 <indexentry><primaryie linkends="$id"><link linkend="$id">$symbol</link>$symbol_desc</primaryie></indexentry>
1148     }
1150     if ($divopen == 1) {
1151         print (OUTPUT "</indexdiv>\n");
1152     }
1153     print (OUTPUT "</indexdiv>\n");
1154     close (OUTPUT);
1156     &UpdateFileIfChanged ($old_index, $new_index, 0);
1160 #############################################################################
1161 # Function    : OutputIndexFull
1162 # Description : This writes the full api indexlist that can be included into the
1163 #               main document into an <index> tag.
1164 #############################################################################
1166 sub OutputIndexFull {
1167     &OutputIndex ("api-index-full", \%IndexEntriesFull);
1171 #############################################################################
1172 # Function    : OutputDeprecatedIndex
1173 # Description : This writes the deprecated api indexlist that can be included
1174 #               into the main document into an <index> tag.
1175 #############################################################################
1177 sub OutputDeprecatedIndex {
1178     &OutputIndex ("api-index-deprecated", \%IndexEntriesDeprecated);
1182 #############################################################################
1183 # Function    : OutputSinceIndexes
1184 # Description : This writes the 'since' api indexlists that can be included into
1185 #               the main document into an <index> tag.
1186 #############################################################################
1188 sub OutputSinceIndexes {
1189     my @sinces = keys %{{ map { $_ => 1 } values %Since }};
1191     foreach my $version (@sinces) {
1192         #print "Since : [$version]\n";
1193         # TODO make filtered hash
1194         #my %index = grep { $Since{$_} eq $version } %IndexEntriesSince;
1195         my %index = map { $_ => $IndexEntriesSince{$_} } grep { $Since{$_} eq $version } keys %IndexEntriesSince;
1197         &OutputIndex ("api-index-$version", \%index);
1198     }
1201 #############################################################################
1202 # Function    : OutputAnnotationGlossary
1203 # Description : This writes a glossary of the used annotation terms into a
1204 #               separate glossary file that can be included into the main
1205 #               document.
1206 #############################################################################
1208 sub OutputAnnotationGlossary {
1209     my $old_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.xml";
1210     my $new_glossary = "$SGML_OUTPUT_DIR/annotation-glossary.new";
1211     my $lastletter = " ";
1212     my $divopen = 0;
1214     # if there are no annotations used return
1215     return if (! keys(%AnnotationsUsed));
1217     # add acronyms that are referenced from acronym text
1218 rerun:
1219     foreach my $annotation (keys(%AnnotationsUsed)) {
1220         if(defined($AnnotationDefinition{$annotation})) {
1221             if($AnnotationDefinition{$annotation} =~ m/<acronym>([\w ]+)<\/acronym>/) {
1222                 if (!exists($AnnotationsUsed{$1})) {
1223                     $AnnotationsUsed{$1} = 1;
1224                     goto rerun;
1225                 }
1226             }
1227         }
1228     }
1230     open (OUTPUT, ">$new_glossary")
1231         || die "Can't create $new_glossary";
1233     my $header = $doctype_header;
1234     $header =~ s/<!DOCTYPE \w+/<!DOCTYPE glossary/;
1236     print (OUTPUT  <<EOF);
1237 $header
1238 <glossary id="annotation-glossary">
1239   <title>Annotation Glossary</title>
1242     foreach my $annotation (sort(keys(%AnnotationsUsed))) {
1243         if(defined($AnnotationDefinition{$annotation})) {
1244             my $def = $AnnotationDefinition{$annotation};
1245             my $curletter = uc(substr($annotation,0,1));
1247             if ($curletter ne $lastletter) {
1248                 $lastletter = $curletter;
1250                 if ($divopen == 1) {
1251                     print (OUTPUT "</glossdiv>\n");
1252                 }
1253                 print (OUTPUT "<glossdiv><title>$curletter</title>\n");
1254                 $divopen = 1;
1255             }
1256             print (OUTPUT <<EOF);
1257     <glossentry>
1258       <glossterm><anchor id="annotation-glossterm-$annotation"/>$annotation</glossterm>
1259       <glossdef>
1260         <para>$def</para>
1261       </glossdef>
1262     </glossentry>
1264         }
1265     }
1267     if ($divopen == 1) {
1268         print (OUTPUT "</glossdiv>\n");
1269     }
1270     print (OUTPUT "</glossary>\n");
1271     close (OUTPUT);
1273     &UpdateFileIfChanged ($old_glossary, $new_glossary, 0);
1276 #############################################################################
1277 # Function    : ReadKnownSymbols
1278 # Description : This collects the names of non-private symbols from the
1279 #               $MODULE-sections.txt file.
1280 # Arguments   : $file - the $MODULE-sections.txt file which contains all of
1281 #                the functions/macros/structs etc. being documented, organised
1282 #                into sections and subsections.
1283 #############################################################################
1285 sub ReadKnownSymbols {
1286     my ($file) = @_;
1288     my $subsection = "";
1290     #print "Reading: $file\n";
1291     open (INPUT, $file)
1292         || die "Can't open $file: $!";
1294     while (<INPUT>) {
1295         if (m/^#/) {
1296             next;
1298         } elsif (m/^<SECTION>/) {
1299             $subsection = "";
1301         } elsif (m/^<SUBSECTION\s*(.*)>/i) {
1302             $subsection = $1;
1304         } elsif (m/^<SUBSECTION>/) {
1305             next;
1307         } elsif (m/^<TITLE>(.*)<\/TITLE>/) {
1308             next;
1310         } elsif (m/^<FILE>(.*)<\/FILE>/) {
1311             $KnownSymbols{"$TMPL_DIR/$1:Long_Description"} = 1;
1312             $KnownSymbols{"$TMPL_DIR/$1:Short_Description"} = 1;
1313             next;
1315         } elsif (m/^<INCLUDE>(.*)<\/INCLUDE>/) {
1316             next;
1318         } elsif (m/^<\/SECTION>/) {
1319             next;
1321         } elsif (m/^(\S+)/) {
1322             my $symbol = $1;
1324             if ($subsection ne "Standard" && $subsection ne "Private") {
1325                 $KnownSymbols{$symbol} = 1;
1326             }
1327             else {
1328                 $KnownSymbols{$symbol} = 0;
1329             }
1330         }
1331     }
1332     close (INPUT);
1336 #############################################################################
1337 # Function    : OutputDeclaration
1338 # Description : Returns the synopsis and detailed description DocBook
1339 #                describing one function/macro etc.
1340 # Arguments   : $symbol - the name of the function/macro begin described.
1341 #                $declaration - the declaration of the function/macro.
1342 #############################################################################
1344 sub OutputDeclaration {
1345     my ($symbol, $declaration) = @_;
1347     my $type = $DeclarationTypes {$symbol};
1348     if ($type eq 'MACRO') {
1349         return &OutputMacro ($symbol, $declaration);
1350     } elsif ($type eq 'TYPEDEF') {
1351         return &OutputTypedef ($symbol, $declaration);
1352     } elsif ($type eq 'STRUCT') {
1353         return &OutputStruct ($symbol, $declaration);
1354     } elsif ($type eq 'ENUM') {
1355         return &OutputEnum ($symbol, $declaration);
1356     } elsif ($type eq 'UNION') {
1357         return &OutputUnion ($symbol, $declaration);
1358     } elsif ($type eq 'VARIABLE') {
1359         return &OutputVariable ($symbol, $declaration);
1360     } elsif ($type eq 'FUNCTION') {
1361         return &OutputFunction ($symbol, $declaration, $type);
1362     } elsif ($type eq 'USER_FUNCTION') {
1363         return &OutputFunction ($symbol, $declaration, $type);
1364     } else {
1365         die "Unknown symbol type";
1366     }
1370 #############################################################################
1371 # Function    : OutputSymbolTraits
1372 # Description : Returns the Since and StabilityLevel paragraphs for a symbol.
1373 # Arguments   : $symbol - the name of the function/macro begin described.
1374 #############################################################################
1376 sub OutputSymbolTraits {
1377     my ($symbol) = @_;
1378     my $desc = "";
1380     if (exists $Since{$symbol}) {
1381         $desc .= "<para role=\"since\">Since $Since{$symbol}</para>";
1382     }
1383     if (exists $StabilityLevel{$symbol}) {
1384         $desc .= "<para role=\"stability\">Stability Level: $StabilityLevel{$symbol}</para>";
1385     }
1386     return $desc;
1389 #############################################################################
1390 # Function    : Output{Symbol,Section}ExtraLinks
1391 # Description : Returns extralinks for the symbol (if enabled).
1392 # Arguments   : $symbol - the name of the function/macro begin described.
1393 #############################################################################
1395 sub uri_escape {
1396     my $text = $_[0];
1397     return undef unless defined $text;
1399     # Build a char to hex map
1400     my %escapes = ();
1401     for (0..255) {
1402             $escapes{chr($_)} = sprintf("%%%02X", $_);
1403     }
1405     # Default unsafe characters.  RFC 2732 ^(uric - reserved)
1406     $text =~ s/([^A-Za-z0-9\-_.!~*'()])/$escapes{$1}/g;
1408     return $text;
1411 sub OutputSymbolExtraLinks {
1412     my ($symbol) = @_;
1413     my $desc = "";
1415     if (0) { # NEW FEATURE: needs configurability
1416     my $sstr = &uri_escape($symbol);
1417     my $mstr = &uri_escape($MODULE);
1418     $desc .= <<EOF;
1419 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1420 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$sstr">edit documentation</ulink>
1422     }
1423     return $desc;
1426 sub OutputSectionExtraLinks {
1427     my ($symbol,$docsymbol) = @_;
1428     my $desc = "";
1430     if (0) { # NEW FEATURE: needs configurability
1431     my $sstr = &uri_escape($symbol);
1432     my $mstr = &uri_escape($MODULE);
1433     my $dsstr = &uri_escape($docsymbol);
1434     $desc .= <<EOF;
1435 <ulink role="extralinks" url="http://www.google.com/codesearch?q=$sstr">code search</ulink>
1436 <ulink role="extralinks" url="http://library.gnome.org/edit?module=$mstr&amp;symbol=$dsstr">edit documentation</ulink>
1438     }
1439     return $desc;
1443 #############################################################################
1444 # Function    : OutputMacro
1445 # Description : Returns the synopsis and detailed description of a macro.
1446 # Arguments   : $symbol - the macro.
1447 #                $declaration - the declaration of the macro.
1448 #############################################################################
1450 sub OutputMacro {
1451     my ($symbol, $declaration) = @_;
1452     my $id = &CreateValidSGMLID ($symbol);
1453     my $condition = &MakeConditionDescription ($symbol);
1454     my $synop = "<row><entry role=\"define_keyword\">#define</entry><entry role=\"function_name\"><link linkend=\"$id\">$symbol</link>";
1455     my $desc;
1457     my @fields = ParseMacroDeclaration($declaration, \&CreateValidSGML);
1458     my $title = $symbol . (@fields ? "()" : "");
1460     $desc = "<refsect2 id=\"$id\" role=\"macro\"$condition>\n<title>$title</title>\n";
1461     $desc .= MakeIndexterms($symbol, $id);
1462     $desc .= "\n";
1463     $desc .= OutputSymbolExtraLinks($symbol);
1465     if (@fields) {
1466         $synop .= "<phrase role=\"c_punctuation\">()</phrase>";
1467     }
1468     $synop .= "</entry></row>\n";
1470     # Don't output the macro definition if is is a conditional macro or it
1471     # looks like a function, i.e. starts with "g_" or "_?gnome_", or it is
1472     # longer than 2 lines, otherwise we get lots of complicated macros like
1473     # g_assert.
1474     if (!defined ($DeclarationConditional{$symbol}) && ($symbol !~ m/^g_/)
1475         && ($symbol !~ m/^_?gnome_/) && (($declaration =~ tr/\n//) < 2)) {
1476         my $decl_out = &CreateValidSGML ($declaration);
1477         $desc .= "<programlisting language=\"C\">$decl_out</programlisting>\n";
1478     } else {
1479         $desc .= "<programlisting language=\"C\">" . &MakeReturnField("#define") . "$symbol";
1480         if ($declaration =~ m/^\s*#\s*define\s+\w+(\([^\)]*\))/) {
1481             my $args = $1;
1482             my $pad = ' ' x ($RETURN_TYPE_FIELD_WIDTH - length ("#define "));
1483             # Align each line so that if should all line up OK.
1484             $args =~ s/\n/\n$pad/gm;
1485             $desc .= &CreateValidSGML ($args);
1486         }
1487         $desc .= "</programlisting>\n";
1488     }
1490     $desc .= &MakeDeprecationNote($symbol);
1492     my $parameters = &OutputParamDescriptions ("MACRO", $symbol, @fields);
1493     my $parameters_output = 0;
1495     if (defined ($SymbolDocs{$symbol})) {
1496         my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1498         # Try to insert the parameter table at the author's desired position.
1499         # Otherwise we need to tag it onto the end.
1500         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
1501           $parameters_output = 1;
1502         }
1503         $desc .= $symbol_docs;
1504     }
1506     if ($parameters_output == 0) {
1507         $desc .= $parameters;
1508     }
1510     $desc .= OutputSymbolTraits ($symbol);
1511     $desc .= "</refsect2>\n";
1512     return ($synop, $desc);
1516 #############################################################################
1517 # Function    : OutputTypedef
1518 # Description : Returns the synopsis and detailed description of a typedef.
1519 # Arguments   : $symbol - the typedef.
1520 #                $declaration - the declaration of the typedef,
1521 #                  e.g. 'typedef unsigned int guint;'
1522 #############################################################################
1524 sub OutputTypedef {
1525     my ($symbol, $declaration) = @_;
1526     my $id = &CreateValidSGMLID ($symbol);
1527     my $condition = &MakeConditionDescription ($symbol);
1528     my $desc = "<refsect2 id=\"$id\" role=\"typedef\"$condition>\n<title>$symbol</title>\n";
1529     my $synop = "<row><entry role=\"typedef_keyword\">typedef</entry><entry role=\"function_name\"><link linkend=\"$id\">$symbol</link></entry></row>\n";
1531     $desc .= MakeIndexterms($symbol, $id);
1532     $desc .= "\n";
1533     $desc .= OutputSymbolExtraLinks($symbol);
1535     if (!defined ($DeclarationConditional{$symbol})) {
1536         my $decl_out = &CreateValidSGML ($declaration);
1537         $desc .= "<programlisting language=\"C\">$decl_out</programlisting>\n";
1538     }
1540     $desc .= &MakeDeprecationNote($symbol);
1542     if (defined ($SymbolDocs{$symbol})) {
1543         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1544     }
1545     $desc .= OutputSymbolTraits ($symbol);
1546     $desc .= "</refsect2>\n";
1547     return ($synop, $desc);
1551 #############################################################################
1552 # Function    : OutputStruct
1553 # Description : Returns the synopsis and detailed description of a struct.
1554 #                We check if it is a object struct, and if so we only output
1555 #                parts of it that are noted as public fields.
1556 #                We also use a different SGML ID for object structs, since the
1557 #                original ID is used for the entire RefEntry.
1558 # Arguments   : $symbol - the struct.
1559 #                $declaration - the declaration of the struct.
1560 #############################################################################
1562 sub OutputStruct {
1563     my ($symbol, $declaration) = @_;
1565     my $is_gtype = 0;
1566     my $default_to_public = 1;
1567     if (&CheckIsObject ($symbol)) {
1568         #print "Found struct gtype: $symbol\n";
1569         $is_gtype = 1;
1570         $default_to_public = $ObjectRoots{$symbol} eq 'GBoxed';
1571     }
1573     my $id;
1574     my $condition;
1575     if ($is_gtype) {
1576         $id = &CreateValidSGMLID ($symbol . "_struct");
1577         $condition = &MakeConditionDescription ($symbol . "_struct");
1578     } else {
1579         $id = &CreateValidSGMLID ($symbol);
1580         $condition = &MakeConditionDescription ($symbol);
1581     }
1583     # Determine if it is a simple struct or it also has a typedef.
1584     my $has_typedef = 0;
1585     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1586       $has_typedef = 1;
1587     }
1589     my $type_output;
1590     my $desc;
1591     if ($has_typedef) {
1592         # For structs with typedefs we just output the struct name.
1593         $type_output = "";
1594         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>$symbol</title>\n";
1595     } else {
1596         $type_output = "struct";
1597         $desc = "<refsect2 id=\"$id\" role=\"struct\"$condition>\n<title>struct $symbol</title>\n";
1598     }
1599     my $synop = "<row><entry role=\"datatype_keyword\">${type_output}</entry><entry role=\"function_name\"><link linkend=\"$id\">$symbol</link></entry></row>\n";
1601     $desc .= MakeIndexterms($symbol, $id);
1602     $desc .= "\n";
1603     $desc .= OutputSymbolExtraLinks($symbol);
1605     # Form a pretty-printed, private-data-removed form of the declaration
1607     my $decl_out = "";
1608     if ($declaration =~ m/^\s*$/) {
1609         #print "Found opaque struct: $symbol\n";
1610         $decl_out = "typedef struct _$symbol $symbol;";
1611     } elsif ($declaration =~ m/^\s*struct\s+\w+\s*;\s*$/) {
1612         #print "Found opaque struct: $symbol\n";
1613         $decl_out = "struct $symbol;";
1614     } else {
1615         my $public = $default_to_public;
1616         my $new_declaration = "";
1617         my $decl_line;
1618         my $decl = $declaration;
1620         if ($decl =~ m/^\s*(typedef\s+)?struct\s*\w*\s*(?:\/\*.*\*\/)?\s*{(.*)}\s*\w*\s*;\s*$/s) {
1621             my $struct_contents = $2;
1623             foreach $decl_line (split (/\n/, $struct_contents)) {
1624                 #print "Struct line: $decl_line\n";
1625                 if ($decl_line =~ m%/\*\s*<\s*public\s*>\s*\*/%) {
1626                     $public = 1;
1627                 } elsif ($decl_line =~ m%/\*\s*<\s*(private|protected)\s*>\s*\*/%) {
1628                     $public = 0;
1629                 } elsif ($public) {
1630                     $new_declaration .= $decl_line . "\n";
1631                 }
1632             }
1634             if ($new_declaration) {
1635                 # Strip any blank lines off the ends.
1636                 $new_declaration =~ s/^\s*\n//;
1637                 $new_declaration =~ s/\n\s*$/\n/;
1639                 if ($has_typedef) {
1640                     $decl_out = "typedef struct {\n" . $new_declaration
1641                       . "} $symbol;\n";
1642                 } else {
1643                     $decl_out = "struct $symbol {\n" . $new_declaration
1644                       . "};\n";
1645                 }
1646             }
1647         } else {
1648             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1649                 "Couldn't parse struct:\n$declaration");
1650         }
1652         # If we couldn't parse the struct or it was all private, output an
1653         # empty struct declaration.
1654         if ($decl_out eq "") {
1655             if ($has_typedef) {
1656                 $decl_out = "typedef struct _$symbol $symbol;";
1657             } else {
1658                 $decl_out = "struct $symbol;";
1659             }
1660         }
1661     }
1663     $decl_out = &CreateValidSGML ($decl_out);
1664     $desc .= "<programlisting language=\"C\">$decl_out</programlisting>\n";
1666     $desc .= &MakeDeprecationNote($symbol);
1668     if (defined ($SymbolDocs{$symbol})) {
1669         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1670     }
1672     # Create a table of fields and descriptions
1674     # FIXME: Inserting &#160's into the produced type declarations here would
1675     #        improve the output in most situations ... except for function
1676     #        members of structs!
1677     my @fields = ParseStructDeclaration($declaration, !$default_to_public,
1678                                         0, \&MakeXRef,
1679                                         sub {
1680                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1681                                         });
1682     my $params = $SymbolParams{$symbol};
1684     # If no parameters are filled in, we don't generate the description
1685     # table, for backwards compatibility.
1687     my $found = 0;
1688     if (defined $params) {
1689         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1690             if ($params->[$i] =~ /\S/) {
1691                 $found = 1;
1692                 last;
1693             }
1694         }
1695     }
1697     if ($found) {
1698         my %field_descrs = @$params;
1699         my $missing_parameters = "";
1700         my $unused_parameters = "";
1702         $desc .= <<EOF;
1703 <refsect3 role="struct_members">\n<title>Members</title>
1704 <informaltable role="struct_members_table" pgwide="1" frame="none">
1705 <tgroup cols="3">
1706 <colspec colname="struct_members_name" colwidth="300px"/>
1707 <colspec colname="struct_members_description"/>
1708 <colspec colname="struct_members_annotations" colwidth="200px"/>
1709 <tbody>
1712         while (@fields) {
1713             my $field_name = shift @fields;
1714             my $text = shift @fields;
1715             my $field_descr = $field_descrs{$field_name};
1716             my $param_annotations = "";
1718             $desc .= "<row><entry role=\"struct_member_name\"><para>$text</para></entry>\n";
1719             if (defined $field_descr) {
1720                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1721                 $field_descr = &ConvertMarkDown($symbol, $field_descr);
1722                 # trim
1723                 $field_descr =~ s/^(\s|\n)+//msg;
1724                 $field_descr =~ s/(\s|\n)+$//msg;
1725                 $desc .= "<listitem>$field_descr</listitem>\n";
1726                 $desc .= "<entry role=\"struct_member_description\">$field_descr</entry>\n<entry role=\"struct_member_annotations\">$param_annotations</entry>\n";
1727                 delete $field_descrs{$field_name};
1728             } else {
1729                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1730                     "Field description for $symbol"."::"."$field_name is missing in source code comment block.");
1731                 if ($missing_parameters ne "") {
1732                   $missing_parameters .= ", ".$field_name;
1733                 } else {
1734                     $missing_parameters = $field_name;
1735                 }
1736                 $desc .= "<entry /><entry />\n";
1737             }
1738             $desc .= "</row>\n";
1739         }
1740         $desc .= "</tbody></tgroup></informaltable>\n</refsect3>\n";
1741         foreach my $field_name (keys %field_descrs) {
1742             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1743                 "Field description for $symbol"."::"."$field_name is not used from source code comment block.");
1744             if ($unused_parameters ne "") {
1745               $unused_parameters .= ", ".$field_name;
1746             } else {
1747                $unused_parameters = $field_name;
1748             }
1749         }
1751         # remember missing/unused parameters (needed in tmpl-free build)
1752         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1753             $AllIncompleteSymbols{$symbol}=$missing_parameters;
1754         }
1755         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1756             $AllUnusedSymbols{$symbol}=$unused_parameters;
1757         }
1758     }
1759     else {
1760         if (scalar(@fields) > 0) {
1761             if (! exists ($AllIncompleteSymbols{$symbol})) {
1762                 $AllIncompleteSymbols{$symbol}="<items>";
1763                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1764                     "Field descriptions for struct $symbol are missing in source code comment block.");
1765                 @TRACE@("Remaining structs fields: ".@fields.":".join(',',@fields)."\n");
1766             }
1767         }
1768     }
1770     $desc .= OutputSymbolTraits ($symbol);
1771     $desc .= "</refsect2>\n";
1772     return ($synop, $desc);
1776 #############################################################################
1777 # Function    : OutputUnion
1778 # Description : Returns the synopsis and detailed description of a union.
1779 # Arguments   : $symbol - the union.
1780 #                $declaration - the declaration of the union.
1781 #############################################################################
1783 sub OutputUnion {
1784     my ($symbol, $declaration) = @_;
1786     my $is_gtype = 0;
1787     if (&CheckIsObject ($symbol)) {
1788         @TRACE@("Found union gtype: $symbol\n");
1789         $is_gtype = 1;
1790     }
1792     my $id;
1793     my $condition;
1794     if ($is_gtype) {
1795         $id = &CreateValidSGMLID ($symbol . "_union");
1796         $condition = &MakeConditionDescription ($symbol . "_union");
1797     } else {
1798         $id = &CreateValidSGMLID ($symbol);
1799         $condition = &MakeConditionDescription ($symbol);
1800     }
1802     # Determine if it is a simple struct or it also has a typedef.
1803     my $has_typedef = 0;
1804     if ($StructHasTypedef{$symbol} || $declaration =~ m/^\s*typedef\s+/) {
1805       $has_typedef = 1;
1806     }
1808     my $type_output;
1809     my $desc;
1810     if ($has_typedef) {
1811         # For unions with typedefs we just output the union name.
1812         $type_output = "";
1813         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>$symbol</title>\n";
1814     } else {
1815         $type_output = "union";
1816         $desc = "<refsect2 id=\"$id\" role=\"union\"$condition>\n<title>union $symbol</title>\n";
1817     }
1818     my $synop = "<row><entry role=\"datatype_keyword\">${type_output}</entry><entry role=\"function_name\"><link linkend=\"$id\">$symbol</link></entry></row>\n";
1820     $desc .= MakeIndexterms($symbol, $id);
1821     $desc .= "\n";
1822     $desc .= OutputSymbolExtraLinks($symbol);
1823     $desc .= &MakeDeprecationNote($symbol);
1825     if (defined ($SymbolDocs{$symbol})) {
1826         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1827     }
1829     # Create a table of fields and descriptions
1831     # FIXME: Inserting &#160's into the produced type declarations here would
1832     #        improve the output in most situations ... except for function
1833     #        members of structs!
1834     my @fields = ParseStructDeclaration($declaration, 0,
1835                                         0, \&MakeXRef,
1836                                         sub {
1837                                             "<structfield id=\"".&CreateValidSGMLID("$id.$_[0]")."\">$_[0]</structfield>";
1838                                         });
1839     my $params = $SymbolParams{$symbol};
1841     # If no parameters are filled in, we don't generate the description
1842     # table, for backwards compatibility
1844     my $found = 0;
1845     if (defined $params) {
1846         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1847             if ($params->[$i] =~ /\S/) {
1848                 $found = 1;
1849                 last;
1850             }
1851         }
1852     }
1854     if ($found) {
1855         my %field_descrs = @$params;
1856         my $missing_parameters = "";
1857         my $unused_parameters = "";
1859         $desc .= <<EOF;
1860 <refsect3 role="union_members">\n<title>Members</title>
1861 <informaltable role="union_members_table" pgwide="1" frame="none">
1862 <tgroup cols="3">
1863 <colspec colname="union_members_name" colwidth="300px"/>
1864 <colspec colname="union_members_description"/>
1865 <colspec colname="union_members_annotations" colwidth="200px"/>
1866 <tbody>
1869         while (@fields) {
1870             my $field_name = shift @fields;
1871             my $text = shift @fields;
1872             my $field_descr = $field_descrs{$field_name};
1873             my $param_annotations = "";
1875             $desc .= "<row><entry role=\"union_member_name\"><para>$text</para></entry>\n";
1876             if (defined $field_descr) {
1877                 ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
1878                 $field_descr = &ConvertMarkDown($symbol, $field_descr);
1880                 # trim
1881                 $field_descr =~ s/^(\s|\n)+//msg;
1882                 $field_descr =~ s/(\s|\n)+$//msg;
1883                 $desc .= "<entry role=\"union_member_description\">$field_descr</entry>\n<entry role=\"union_member_annotations\">$param_annotations</entry>\n";
1884                 delete $field_descrs{$field_name};
1885             } else {
1886                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1887                     "Field description for $symbol"."::"."$field_name is missing in source code comment block.");
1888                 if ($missing_parameters ne "") {
1889                     $missing_parameters .= ", ".$field_name;
1890                 } else {
1891                     $missing_parameters = $field_name;
1892                 }
1893                 $desc .= "<entry /><entry />\n";
1894             }
1895             $desc .= "</row>\n";
1896         }
1897         $desc .= "</tbody></tgroup></informaltable>\n</refsect3>";
1898         foreach my $field_name (keys %field_descrs) {
1899             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1900                 "Field description for $symbol"."::"."$field_name is not used from source code comment block.");
1901             if ($unused_parameters ne "") {
1902               $unused_parameters .= ", ".$field_name;
1903             } else {
1904                $unused_parameters = $field_name;
1905             }
1906         }
1908         # remember missing/unused parameters (needed in tmpl-free build)
1909         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
1910             $AllIncompleteSymbols{$symbol}=$missing_parameters;
1911         }
1912         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
1913             $AllUnusedSymbols{$symbol}=$unused_parameters;
1914         }
1915     }
1916     else {
1917         if (scalar(@fields) > 0) {
1918             if (! exists ($AllIncompleteSymbols{$symbol})) {
1919                 $AllIncompleteSymbols{$symbol}="<items>";
1920                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
1921                     "Field descriptions for union $symbol are missing in source code comment block.");
1922                 @TRACE@("Remaining union fields: ".@fields.":".join(',',@fields)."\n");
1923             }
1924         }
1925     }
1927     $desc .= OutputSymbolTraits ($symbol);
1928     $desc .= "</refsect2>\n";
1929     return ($synop, $desc);
1933 #############################################################################
1934 # Function    : OutputEnum
1935 # Description : Returns the synopsis and detailed description of a enum.
1936 # Arguments   : $symbol - the enum.
1937 #                $declaration - the declaration of the enum.
1938 #############################################################################
1940 sub OutputEnum {
1941     my ($symbol, $declaration) = @_;
1943     my $is_gtype = 0;
1944     if (&CheckIsObject ($symbol)) {
1945         #print "Found enum gtype: $symbol\n";
1946         $is_gtype = 1;
1947     }
1949     my $id;
1950     my $condition;
1951     if ($is_gtype) {
1952         $id = &CreateValidSGMLID ($symbol . "_enum");
1953         $condition = &MakeConditionDescription ($symbol . "_enum");
1954     } else {
1955         $id = &CreateValidSGMLID ($symbol);
1956         $condition = &MakeConditionDescription ($symbol);
1957     }
1959     my $synop = "<row><entry role=\"datatype_keyword\">enum</entry><entry role=\"function_name\"><link linkend=\"$id\">$symbol</link></entry></row>\n";
1960     my $desc = "<refsect2 id=\"$id\" role=\"enum\"$condition>\n<title>enum $symbol</title>\n";
1962     $desc .= MakeIndexterms($symbol, $id);
1963     $desc .= "\n";
1964     $desc .= OutputSymbolExtraLinks($symbol);
1965     $desc .= &MakeDeprecationNote($symbol);
1967     if (defined ($SymbolDocs{$symbol})) {
1968         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
1969     }
1971     # Create a table of fields and descriptions
1973     my @fields = ParseEnumDeclaration($declaration);
1974     my $params = $SymbolParams{$symbol};
1976     # If nothing at all is documented log a single summary warning at the end.
1977     # Otherwise, warn about each undocumented item.
1979     my $found = 0;
1980     if (defined $params) {
1981         for (my $i = 1; $i <= $#$params; $i += $PARAM_FIELD_COUNT) {
1982             if ($params->[$i] =~ /\S/) {
1983                 $found = 1;
1984                 last;
1985             }
1986         }
1987     }
1989     my %field_descrs = (defined $params ? @$params : ());
1990     my $missing_parameters = "";
1991     my $unused_parameters = "";
1993     $desc .= <<EOF;
1994 <refsect3 role="enum_members">\n<title>Members</title>
1995 <informaltable role="enum_members_table" pgwide="1" frame="none">
1996 <tgroup cols="3">
1997 <colspec colname="enum_members_name" colwidth="300px"/>
1998 <colspec colname="enum_members_description"/>
1999 <colspec colname="enum_members_annotations" colwidth="200px"/>
2000 <tbody>
2003     for my $field_name (@fields) {
2004         my $field_descr = $field_descrs{$field_name};
2005         my $param_annotations = "";
2007         $id = &CreateValidSGMLID ($field_name);
2008         $condition = &MakeConditionDescription ($field_name);
2009         $desc .= "<row role=\"constant\"><entry role=\"enum_member_name\"><para id=\"$id\">$field_name</para></entry>\n";
2010         if (defined $field_descr) {
2011             ($field_descr,$param_annotations) = &ExpandAnnotation($symbol, $field_descr);
2012             $field_descr = &ConvertMarkDown($symbol, $field_descr);
2013             $desc .= "<entry role=\"enum_member_description\">$field_descr</entry>\n<entry role=\"enum_member_annotations\">$param_annotations</entry>\n";
2014             delete $field_descrs{$field_name};
2015         } else {
2016             if ($found) {
2017                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2018                     "Value description for $symbol"."::"."$field_name is missing in source code comment block.");
2019                 if ($missing_parameters ne "") {
2020                     $missing_parameters .= ", ".$field_name;
2021                 } else {
2022                     $missing_parameters = $field_name;
2023                 }
2024             }
2025             $desc .= "<entry /><entry />\n";
2026         }
2027         $desc .= "</row>\n";
2028     }
2029     $desc .= "</tbody></tgroup></informaltable>\n</refsect3>";
2030     foreach my $field_name (keys %field_descrs) {
2031         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2032             "Value description for $symbol"."::"."$field_name is not used from source code comment block.");
2033         if ($unused_parameters ne "") {
2034             $unused_parameters .= ", ".$field_name;
2035         } else {
2036             $unused_parameters = $field_name;
2037         }
2038     }
2040     # remember missing/unused parameters (needed in tmpl-free build)
2041     if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
2042         $AllIncompleteSymbols{$symbol}=$missing_parameters;
2043     }
2044     if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
2045         $AllUnusedSymbols{$symbol}=$unused_parameters;
2046     }
2048     if (!$found) {
2049         if (scalar(@fields) > 0) {
2050             if (! exists ($AllIncompleteSymbols{$symbol})) {
2051                 $AllIncompleteSymbols{$symbol}="<items>";
2052                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2053                     "Value descriptions for $symbol are missing in source code comment block.");
2054             }
2055         }
2056     }
2058     $desc .= OutputSymbolTraits ($symbol);
2059     $desc .= "</refsect2>\n";
2060     return ($synop, $desc);
2064 #############################################################################
2065 # Function    : OutputVariable
2066 # Description : Returns the synopsis and detailed description of a variable.
2067 # Arguments   : $symbol - the extern'ed variable.
2068 #                $declaration - the declaration of the variable.
2069 #############################################################################
2071 sub OutputVariable {
2072     my ($symbol, $declaration) = @_;
2073     my $id = &CreateValidSGMLID ($symbol);
2074     my $condition = &MakeConditionDescription ($symbol);
2075     
2076     @TRACE@("ouputing variable: '$symbol' '$declaration'");
2078     my $type_output;
2079     if ($declaration =~ m/^\s*extern\s+((const\s+|signed\s+|unsigned\s+|long\s+|short\s+)*\w+)(\s+\*+|\*+|\s)(\s*)(const\s+)*([A-Za-z]\w*)\s*;/) {
2080         my $mod1 = defined ($1) ? $1 : "";
2081         my $ptr = defined ($3) ? $3 : "";
2082         my $space = defined ($4) ? $4 : "";
2083         my $mod2 = defined ($5) ? $5 : "";
2084         $type_output = "extern $mod1$ptr$space$mod2";
2085     } elsif ($declaration =~ m/^\s*((const\s+|signed\s+|unsigned\s+|long\s+|short\s+)*\w+)(\s+\*+|\*+|\s)(\s*)(const\s+)*([A-Za-z]\w*)\s*=/) {
2086         my $mod1 = defined ($1) ? $1 : "";
2087         my $ptr = defined ($3) ? $3 : "";
2088         my $space = defined ($4) ? $4 : "";
2089         my $mod2 = defined ($5) ? $5 : "";
2090         $type_output = "$mod1$ptr$space$mod2";
2091     } else {
2092         $type_output = "extern";
2093     }
2094     my $synop = "<row><entry role=\"variable_type\">${type_output}</entry><entry role=\"function_name\"><link linkend=\"$id\">$symbol</link></entry></row>\n";
2096     my $desc = "<refsect2 id=\"$id\" role=\"variable\"$condition>\n<title>$symbol</title>\n";
2098     $desc .= MakeIndexterms($symbol, $id);
2099     $desc .= "\n";
2100     $desc .= OutputSymbolExtraLinks($symbol);
2102     my $decl_out = &CreateValidSGML ($declaration);
2103     $desc .= "<programlisting language=\"C\">$decl_out</programlisting>\n";
2105     $desc .= &MakeDeprecationNote($symbol);
2107     if (defined ($SymbolDocs{$symbol})) {
2108         $desc .= &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
2109     }
2110     $desc .= OutputSymbolTraits ($symbol);
2111     $desc .= "</refsect2>\n";
2112     return ($synop, $desc);
2116 #############################################################################
2117 # Function    : OutputFunction
2118 # Description : Returns the synopsis and detailed description of a function.
2119 # Arguments   : $symbol - the function.
2120 #                $declaration - the declaration of the function.
2121 #############################################################################
2123 sub OutputFunction {
2124     my ($symbol, $declaration, $symbol_type) = @_;
2125     my $id = &CreateValidSGMLID ($symbol);
2126     my $condition = &MakeConditionDescription ($symbol);
2128     # Take out the return type     $1                                                                                       $2   $3
2129     $declaration =~ s/<RETURNS>\s*((?:const\s+|G_CONST_RETURN\s+|signed\s+|unsigned\s+|long\s+|short\s+|struct\s+|enum\s+)*)(\w+)(\s*\**\s*(?:const|G_CONST_RETURN)?\s*\**\s*(?:restrict)?\s*)<\/RETURNS>\n//;
2130     my $type_modifier = defined($1) ? $1 : "";
2131     my $type = $2;
2132     my $pointer = $3;
2133     # Trim trailing spaces as we are going to pad to $RETURN_TYPE_FIELD_WIDTH below anyway
2134     $pointer =~ s/\s+$//;
2135     my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
2136     my $start = "";
2137     #if ($symbol_type eq 'USER_FUNCTION') {
2138     #    $start = "typedef ";
2139     #}
2141     # We output const rather than G_CONST_RETURN.
2142     $type_modifier =~ s/G_CONST_RETURN/const/g;
2143     $pointer =~ s/G_CONST_RETURN/const/g;
2144     $pointer =~ s/^\s+/&#160;/g;
2146     my $ret_type_output;
2147     $ret_type_output = "$start$type_modifier$xref$pointer\n";
2149     my $indent_len;
2150     $indent_len = length ($symbol) + 2;
2151     my $char1 = my $char2 = my $char3 = "";
2152     if ($symbol_type eq 'USER_FUNCTION') {
2153         $indent_len += 3;
2154         $char1 = "<phrase role=\"c_punctuation\">(</phrase>";
2155         $char2 = "*";
2156         $char3 = "<phrase role=\"c_punctuation\">)</phrase>";
2157     }
2159     my ($symbol_output, $symbol_desc_output);
2160     $symbol_output = "$char1<link linkend=\"$id\">$char2$symbol</link>$char3";
2161     if ($indent_len < $MAX_SYMBOL_FIELD_WIDTH) {
2162         $symbol_desc_output = "$char1$char2$symbol$char3 ";
2163     } else {
2164         $indent_len = $MAX_SYMBOL_FIELD_WIDTH - 8;
2165         $symbol_desc_output = "$char1$char2$symbol$char3\n"
2166           . (' ' x ($indent_len - 1));
2167     }
2169     my $synop = "<row><entry role=\"function_type\">${ret_type_output}</entry><entry role=\"function_name\">${symbol_output}&#160;<phrase role=\"c_punctuation\">()</phrase></entry></row>\n";
2171     my $desc = "<refsect2 id=\"$id\" role=\"function\"$condition>\n<title>${symbol}&#160;()</title>\n";
2173     $desc .= MakeIndexterms($symbol, $id);
2174     $desc .= "\n";
2175     $desc .= OutputSymbolExtraLinks($symbol);
2177     $desc  .= "<programlisting language=\"C\">${ret_type_output}$symbol_desc_output(";
2179     my @fields = ParseFunctionDeclaration($declaration, \&MakeXRef,
2180                                         sub {
2181                                             &tagify($_[0],"parameter");
2182                                         });
2184     for (my $i = 1; $i <= $#fields; $i += 2) {
2185         my $field_name = $fields[$i];
2187         if ($i == 1) {
2188             $desc  .= "$field_name";
2189         } else {
2190             $desc  .= ",\n"
2191                 . (' ' x $indent_len)
2192                 . "$field_name";
2193         }
2195     }
2197     $desc  .= ");</programlisting>\n";
2199     $desc .= &MakeDeprecationNote($symbol);
2201     my $parameters = &OutputParamDescriptions ("FUNCTION", $symbol, @fields);
2202     my $parameters_output = 0;
2204     if (defined ($SymbolDocs{$symbol})) {
2205         my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
2207         # Try to insert the parameter table at the author's desired position.
2208         # Otherwise we need to tag it onto the end.
2209         # FIXME: document that in the user manual and make it useable for other
2210         # types too
2211         if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
2212           $parameters_output = 1;
2213         }
2214         $desc .= $symbol_docs;
2215     }
2217     if ($parameters_output == 0) {
2218         $desc .= $parameters;
2219     }
2221     $desc .= OutputSymbolTraits ($symbol);
2222     $desc .= "</refsect2>\n";
2223     return ($synop, $desc);
2227 #############################################################################
2228 # Function    : OutputParamDescriptions
2229 # Description : Returns the DocBook output describing the parameters of a
2230 #                function, macro or signal handler.
2231 # Arguments   : $symbol_type - 'FUNCTION', 'MACRO' or 'SIGNAL'. Signal
2232 #                  handlers have an implicit user_data parameter last.
2233 #                $symbol - the name of the function/macro being described.
2234 #               @fields - parsed fields from the declaration, used to determine
2235 #                  undocumented/unused entries
2236 #############################################################################
2238 sub OutputParamDescriptions {
2239     my ($symbol_type, $symbol, @fields) = @_;
2240     my $output = "";
2241     my $params = $SymbolParams{$symbol};
2242     my $num_params = 0;
2243     my %field_descrs = ();
2245     if (@fields) {
2246         %field_descrs = @fields;
2247         delete $field_descrs{"void"};
2248         delete $field_descrs{"Returns"};
2249     }
2251     if (defined $params) {
2252         my $returns = "";
2253         my $params_desc = "";
2254         my $missing_parameters = "";
2255         my $unused_parameters = "";
2256         my $j;
2258         for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
2259             my $param_name = $$params[$j];
2260             my $param_desc = $$params[$j + 1];
2261             my $param_annotations = "";
2263             ($param_desc,$param_annotations) = & ExpandAnnotation($symbol, $param_desc);
2264             $param_desc = &ConvertMarkDown($symbol, $param_desc);
2265             # trim
2266             $param_desc =~ s/^(\s|\n)+//msg;
2267             $param_desc =~ s/(\s|\n)+$//msg;
2268             if ($param_name eq "Returns") {
2269                 $returns = "$param_desc\n<para>$param_annotations</para>";
2270             } elsif ($param_name eq "void") {
2271                 #print "!!!! void in params for $symbol?\n";
2272             } else {
2273                 if (@fields) {
2274                     if (!defined $field_descrs{$param_name}) {
2275                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2276                             "Parameter description for $symbol"."::"."$param_name is not used from source code comment block.");
2277                         if ($unused_parameters ne "") {
2278                           $unused_parameters .= ", ".$param_name;
2279                         } else {
2280                            $unused_parameters = $param_name;
2281                         }
2282                     } else {
2283                         delete $field_descrs{$param_name};
2284                     }
2285                 }
2286                 if($param_desc ne "") {
2287                     $params_desc .= "<row><entry role=\"parameter_name\"><para>$param_name</para></entry>\n<entry role=\"parameter_description\">$param_desc</entry>\n<entry role=\"parameter_annotations\">$param_annotations</entry></row>\n";
2288                     $num_params++;
2289                 }
2290             }
2291         }
2292         foreach my $param_name (keys %field_descrs) {
2293             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2294                 "Parameter description for $symbol"."::"."$param_name is missing in source code comment block.");
2295             if ($missing_parameters ne "") {
2296               $missing_parameters .= ", ".$param_name;
2297             } else {
2298                $missing_parameters = $param_name;
2299             }
2300         }
2302         # Signals have an implicit user_data parameter which we describe.
2303         if ($symbol_type eq "SIGNAL") {
2304             $params_desc .= "<row><entry role=\"parameter_name\"><simpara>user_data</simpara></entry>\n<entry role=\"parameter_description\"><simpara>user data set when the signal handler was connected.</simpara></entry>\n<entry role=\"parameter_annotations\"></entry></row>\n";
2305         }
2307         # Start a table if we need one.
2308         if ($params_desc ne "") {
2309           $output .= <<EOF;
2310 <refsect3 role="parameters">\n<title>Parameters</title>
2311 <informaltable role="parameters_table" pgwide="1" frame="none">
2312 <tgroup cols="3">
2313 <colspec colname="parameters_name" colwidth="150px"/>
2314 <colspec colname="parameters_description"/>
2315 <colspec colname="parameters_annotations" colwidth="200px"/>
2316 <tbody>
2318           $output .= $params_desc;
2319           $output .= "</tbody></tgroup></informaltable>\n</refsect3>";
2320         }
2322         # Output the returns info last
2323         if ($returns ne "") {
2324           $output .= <<EOF;
2325 <refsect3 role=\"returns\">\n<title>Returns</title>
2327           $output .= $returns;
2328           $output .= "\n</refsect3>";
2329         }
2331         # remember missing/unused parameters (needed in tmpl-free build)
2332         if (($missing_parameters ne "") and (! exists ($AllIncompleteSymbols{$symbol}))) {
2333             $AllIncompleteSymbols{$symbol}=$missing_parameters;
2334         }
2335         if (($unused_parameters ne "") and (! exists ($AllUnusedSymbols{$symbol}))) {
2336             $AllUnusedSymbols{$symbol}=$unused_parameters;
2337         }
2338     }
2339     if (($num_params == 0) && @fields && (scalar(keys(%field_descrs)) > 0)) {
2340         if (! exists ($AllIncompleteSymbols{$symbol})) {
2341             $AllIncompleteSymbols{$symbol}="<parameters>";
2342         }
2343     }
2345     return $output;
2349 #############################################################################
2350 # Function    : ParseStabilityLevel
2351 # Description : Parses a stability level and outputs a warning if it isn't
2352 #               valid.
2353 # Arguments   : $stability - the stability text.
2354 #                $file, $line - context for error message
2355 #                $message - description of where the level is from, to use in
2356 #               any error message.
2357 # Returns     : The parsed stability level string.
2358 #############################################################################
2360 sub ParseStabilityLevel {
2361     my ($stability, $file, $line, $message) = @_;
2363     $stability =~ s/^\s*//;
2364     $stability =~ s/\s*$//;
2365     if ($stability =~ m/^stable$/i) {
2366         $stability = "Stable";
2367     } elsif ($stability =~ m/^unstable$/i) {
2368         $stability = "Unstable";
2369     } elsif ($stability =~ m/^private$/i) {
2370         $stability = "Private";
2371     } else {
2372         &LogWarning ($file, $line, "$message is $stability.".
2373             "It should be one of these: Stable, Unstable, or Private.");
2374     }
2375     return $stability;
2379 #############################################################################
2380 # Function    : OutputSGMLFile
2381 # Description : Outputs the final DocBook file for one section.
2382 # Arguments   : $file - the name of the file.
2383 #               $title - the title from the $MODULE-sections.txt file, which
2384 #                 will be overridden by the title in the template file.
2385 #               $section_id - the SGML id to use for the toplevel tag.
2386 #               $includes - comma-separates list of include files added at top of
2387 #                 synopsis, with '<' '>' around them (if not already enclosed in "").
2388 #               $functions_synop - reference to the DocBook for the Functions Synopsis part.
2389 #               $other_synop - reference to the DocBook for the Types and Values Synopsis part.
2390 #               $functions_details - reference to the DocBook for the Functions Details part.
2391 #               $other_details - reference to the DocBook for the Types and Values Details part.
2392 #               $signal_synop - reference to the DocBook for the Signal Synopsis part
2393 #               $signal_desc - reference to the DocBook for the Signal Description part
2394 #               $args_synop - reference to the DocBook for the Arg Synopsis part
2395 #               $args_desc - reference to the DocBook for the Arg Description part
2396 #               $hierarchy - reference to the DocBook for the Object Hierarchy part
2397 #               $interfaces - reference to the DocBook for the Interfaces part
2398 #               $implementations - reference to the DocBook for the Known Implementations part
2399 #               $prerequisites - reference to the DocBook for the Prerequisites part
2400 #               $derived - reference to the DocBook for the Derived Interfaces part
2401 #               $file_objects - reference to an array of objects in this file
2402 #############################################################################
2404 sub OutputSGMLFile {
2405     my ($file, $title, $section_id, $includes, $functions_synop, $other_synop, $functions_details, $other_details, $signals_synop, $signals_desc, $args_synop, $args_desc, $hierarchy, $interfaces, $implementations, $prerequisites, $derived, $file_objects) = @_;
2407     #print "Output sgml for file $file with title '$title'\n";
2409     # The edited title overrides the one from the sections file.
2410     my $new_title = $SymbolDocs{"$TMPL_DIR/$file:Title"};
2411     if (defined ($new_title) && $new_title !~ m/^\s*$/) {
2412         $title = $new_title;
2413         #print "Found title: $title\n";
2414     }
2415     my $short_desc = $SymbolDocs{"$TMPL_DIR/$file:Short_Description"};
2416     if (!defined ($short_desc) || $short_desc =~ m/^\s*$/) {
2417         $short_desc = "";
2418     } else {
2419         # Don't use ConvertMarkDown here for now since we don't want blocks
2420         $short_desc = &ExpandAbbreviations("$title:Short_description",
2421                                            $short_desc);
2422         #print "Found short_desc: $short_desc";
2423     }
2424     my $long_desc = $SymbolDocs{"$TMPL_DIR/$file:Long_Description"};
2425     if (!defined ($long_desc) || $long_desc =~ m/^\s*$/) {
2426         $long_desc = "";
2427     } else {
2428         $long_desc = &ConvertMarkDown("$title:Long_description",
2429                                           $long_desc);
2430         #print "Found long_desc: $long_desc";
2431     }
2432     my $see_also = $SymbolDocs{"$TMPL_DIR/$file:See_Also"};
2433     if (!defined ($see_also) || $see_also =~ m%^\s*(<para>)?\s*(</para>)?\s*$%) {
2434         $see_also = "";
2435     } else {
2436         $see_also = &ConvertMarkDown("$title:See_Also", $see_also);
2437         #print "Found see_also: $see_also";
2438     }
2439     if ($see_also) {
2440         $see_also = "<refsect1 id=\"$section_id.see-also\">\n<title>See Also</title>\n$see_also\n</refsect1>\n";
2441     }
2442     my $stability = $SymbolDocs{"$TMPL_DIR/$file:Stability_Level"};
2443     if (!defined ($stability) || $stability =~ m/^\s*$/) {
2444         $stability = "";
2445     } else {
2446         $stability = &ParseStabilityLevel($stability, $file, $., "Section stability level");
2447         #print "Found stability: $stability";
2448     }
2449     if ($stability) {
2450         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$stability, unless otherwise indicated\n</refsect1>\n";
2451     } elsif ($DEFAULT_STABILITY) {
2452         $stability = "<refsect1 id=\"$section_id.stability-level\">\n<title>Stability Level</title>\n$DEFAULT_STABILITY, unless otherwise indicated\n</refsect1>\n";
2453     }
2455     my $image = $SymbolDocs{"$TMPL_DIR/$file:Image"};
2456     if (!defined ($image) || $image =~ m/^\s*$/) {
2457       $image = "";
2458     } else {
2459       $image =~ s/^\s*//;
2460       $image =~ s/\s*$//;
2462       my $format;
2464       if ($image =~ /jpe?g$/i) {
2465         $format = "format='JPEG'";
2466       } elsif ($image =~ /png$/i) {
2467         $format = "format='PNG'";
2468       } elsif ($image =~ /svg$/i) {
2469         $format = "format='SVG'";
2470       } else {
2471         $format = "";
2472       }
2474       $image = "  <inlinegraphic fileref='$image' $format/>\n"
2475     }
2477     my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
2478         gmtime (time);
2479     my $month = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))[$mon];
2480     $year += 1900;
2482     my $include_output = "";
2483     if ($includes) {
2484       $include_output .= "<refsect1 id=\"$section_id.includes\"><title>Includes</title><synopsis>";
2485       my $include;
2486       foreach $include (split (/,/, $includes)) {
2487         if ($include =~ m/^\".+\"$/) {
2488           $include_output .= "#include ${include}\n";
2489         }
2490         else {
2491           $include =~ s/^\s+|\s+$//gs;
2492           $include_output .= "#include &lt;${include}&gt;\n";
2493         }
2494       }
2495       $include_output .= "</synopsis></refsect1>\n";
2496     }
2498     my $extralinks = OutputSectionExtraLinks($title,"Section:$file");
2500     my $old_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT";
2501     my $new_sgml_file = "$SGML_OUTPUT_DIR/$file.$OUTPUT_FORMAT.new";
2503     open (OUTPUT, ">$new_sgml_file")
2504         || die "Can't create $new_sgml_file: $!";
2506     my $object_anchors = "";
2507     foreach my $object (@$file_objects) {
2508         next if ($object eq $section_id);
2509         my $id = CreateValidSGMLID($object);
2510         #print "Debug: Adding anchor for $object\n";
2511         $object_anchors .= "<anchor id=\"$id\"$empty_element_end";
2512     }
2514     # We used to output this, but is messes up our UpdateFileIfChanged code
2515     # since it changes every day (and it is only used in the man pages):
2516     # "<refentry id="$section_id" revision="$mday $month $year">"
2518     if ($OUTPUT_FORMAT eq "xml") {
2519         print OUTPUT $doctype_header;
2520     }
2522     print OUTPUT <<EOF;
2523 <refentry id="$section_id">
2524 <refmeta>
2525 <refentrytitle role="top_of_page" id="$section_id.top_of_page">$title</refentrytitle>
2526 <manvolnum>3</manvolnum>
2527 <refmiscinfo>
2528   \U$MODULE\E Library
2529 $image</refmiscinfo>
2530 </refmeta>
2531 <refnamediv>
2532 <refname>$title</refname>
2533 <refpurpose>$short_desc</refpurpose>
2534 </refnamediv>
2535 $stability
2536 $$functions_synop$$args_synop$$signals_synop$object_anchors$$other_synop$$hierarchy$$prerequisites$$derived$$interfaces$$implementations
2537 $include_output
2538 <refsect1 id="$section_id.description" role="desc">
2539 <title role="desc.title">Description</title>
2540 $extralinks$long_desc
2541 </refsect1>
2542 <refsect1 id="$section_id.functions_details" role="details">
2543 <title role="details.title">Functions</title>
2544 $$functions_details
2545 </refsect1>
2546 <refsect1 id="$section_id.other_details" role="details">
2547 <title role="details.title">Types and Values</title>
2548 $$other_details
2549 </refsect1>
2550 $$args_desc$$signals_desc$see_also
2551 </refentry>
2553     close (OUTPUT);
2555     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2559 #############################################################################
2560 # Function    : OutputExtraFile
2561 # Description : Copies an "extra" DocBook file into the output directory,
2562 #               expanding abbreviations
2563 # Arguments   : $file - the source file.
2564 #############################################################################
2565 sub OutputExtraFile {
2566     my ($file) = @_;
2568     my $basename;
2570     ($basename = $file) =~ s!^.*/!!;
2572     my $old_sgml_file = "$SGML_OUTPUT_DIR/$basename";
2573     my $new_sgml_file = "$SGML_OUTPUT_DIR/$basename.new";
2575     my $contents;
2577     open(EXTRA_FILE, "<$file") || die "Can't open $file";
2579     {
2580         local $/;
2581         $contents = <EXTRA_FILE>;
2582     }
2584     open (OUTPUT, ">$new_sgml_file")
2585         || die "Can't create $new_sgml_file: $!";
2587     print OUTPUT &ExpandAbbreviations ("$basename file", $contents);
2588     close (OUTPUT);
2590     return &UpdateFileIfChanged ($old_sgml_file, $new_sgml_file, 0);
2592 #############################################################################
2593 # Function    : OutputBook
2594 # Description : Outputs the SGML entities that need to be included into the
2595 #                main SGML file for the module.
2596 # Arguments   : $book_top - the declarations of the entities, which are added
2597 #                  at the top of the main SGML file.
2598 #                $book_bottom - the references to the entities, which are
2599 #                  added in the main SGML file at the desired position.
2600 #############################################################################
2602 sub OutputBook {
2603     my ($book_top, $book_bottom) = @_;
2605     my $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top";
2606     my $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.top.new";
2608     open (OUTPUT, ">$new_file")
2609         || die "Can't create $new_file: $!";
2610     print OUTPUT $book_top;
2611     close (OUTPUT);
2613     &UpdateFileIfChanged ($old_file, $new_file, 0);
2616     $old_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom";
2617     $new_file = "$SGML_OUTPUT_DIR/$MODULE-doc.bottom.new";
2619     open (OUTPUT, ">$new_file")
2620         || die "Can't create $new_file: $!";
2621     print OUTPUT $book_bottom;
2622     close (OUTPUT);
2624     &UpdateFileIfChanged ($old_file, $new_file, 0);
2627     # If the main SGML/XML file hasn't been created yet, we create it here.
2628     # The user can tweak it later.
2629     if ($MAIN_SGML_FILE && ! -e $MAIN_SGML_FILE) {
2630       open (OUTPUT, ">$MAIN_SGML_FILE")
2631         || die "Can't create $MAIN_SGML_FILE: $!";
2633       if ($OUTPUT_FORMAT eq "xml") {
2634           print OUTPUT <<EOF;
2635 <?xml version="1.0"?>
2636 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
2637                "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd"
2639   <!ENTITY % local.common.attrib "xmlns:xi  CDATA  #FIXED 'http://www.w3.org/2003/XInclude'">
2641 <book id="index">
2643       } else {
2644         print OUTPUT <<EOF;
2645 <!doctype book PUBLIC "-//Davenport//DTD DocBook V3.0//EN" [
2646 $book_top
2648 <book id="index">
2650       }
2652 print OUTPUT <<EOF;
2653   <bookinfo>
2654     <title>$MODULE Reference Manual</title>
2655     <releaseinfo>
2656       for $MODULE [VERSION].
2657       The latest version of this documentation can be found on-line at
2658       <ulink role="online-location" url="http://[SERVER]/$MODULE/index.html">http://[SERVER]/$MODULE/</ulink>.
2659     </releaseinfo>
2660   </bookinfo>
2662   <chapter>
2663     <title>[Insert title here]</title>
2664     $book_bottom
2665   </chapter>
2667   if (-e $OBJECT_TREE_FILE) {
2668     print OUTPUT <<EOF;
2669   <chapter id="object-tree">
2670     <title>Object Hierarchy</title>
2671      <xi:include href="xml/tree_index.sgml"/>
2672   </chapter>
2674   }
2676 print OUTPUT <<EOF;
2677   <index id="api-index-full">
2678     <title>API Index</title>
2679     <xi:include href="xml/api-index-full.xml"><xi:fallback /></xi:include>
2680   </index>
2681   <index id="deprecated-api-index" role="deprecated">
2682     <title>Index of deprecated API</title>
2683     <xi:include href="xml/api-index-deprecated.xml"><xi:fallback /></xi:include>
2684   </index>
2686   <xi:include href="xml/annotation-glossary.xml"><xi:fallback /></xi:include>
2687 </book>
2690       close (OUTPUT);
2691     }
2695 #############################################################################
2696 # Function    : CreateValidSGML
2697 # Description : This turns any chars which are used in SGML into entities,
2698 #                e.g. '<' into '&lt;'
2699 # Arguments   : $text - the text to turn into proper SGML.
2700 #############################################################################
2702 sub CreateValidSGML {
2703     my ($text) = @_;
2704     $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2705     $text =~ s/</&lt;/g;
2706     $text =~ s/>/&gt;/g;
2707     # browers render single tabs inconsistently
2708     $text =~ s/([^\s])\t([^\s])/$1&#160;$2/g;
2709     return $text;
2712 #############################################################################
2713 # Function    : ConvertSGMLChars
2714 # Description : This is used for text in source code comment blocks, to turn
2715 #               chars which are used in SGML into entities, e.g. '<' into
2716 #               '&lt;'. Depending on $INLINE_MARKUP_MODE, this is done
2717 #               unconditionally or only if the character doesn't seem to be
2718 #               part of an SGML construct (tag or entity reference).
2719 # Arguments   : $text - the text to turn into proper SGML.
2720 #############################################################################
2722 sub ConvertSGMLChars {
2723     my ($symbol, $text) = @_;
2725     if ($INLINE_MARKUP_MODE) {
2726         # For the XML/SGML mode only convert to entities outside CDATA sections.
2727         return &ModifyXMLElements ($text, $symbol,
2728                                    "<!\\[CDATA\\[|<programlisting[^>]*>",
2729                                    \&ConvertSGMLCharsEndTag,
2730                                    \&ConvertSGMLCharsCallback);
2731     } else {
2732         # For the simple non-sgml mode, convert to entities everywhere.
2733         $text =~ s/&/&amp;/g;        # Do this first, or the others get messed up.
2734         $text =~ s/</&lt;/g;
2735         $text =~ s/>/&gt;/g;
2736         return $text;
2737     }
2741 sub ConvertSGMLCharsEndTag {
2742   if ($_[0] eq "<!\[CDATA\[") {
2743     return "]]>";
2744   } else {
2745     return "</programlisting>";
2746   }
2749 sub ConvertSGMLCharsCallback {
2750   my ($text, $symbol, $tag) = @_;
2752   if ($tag =~ m/^<programlisting/) {
2753     # We can handle <programlisting> specially here.
2754     return &ModifyXMLElements ($text, $symbol,
2755                                "<!\\[CDATA\\[",
2756                                \&ConvertSGMLCharsEndTag,
2757                                \&ConvertSGMLCharsCallback2);
2758   } elsif ($tag eq "") {
2759     # If we're not in CDATA convert to entities.
2760     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2761     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2762     # Allow ">" at beginning of string for blockquote markdown
2763     $text =~ s/(?<=[^\w\n"'\/-])>/&gt;/g;
2765     # Handle "#include <xxxxx>"
2766     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2767   }
2769   return $text;
2772 sub ConvertSGMLCharsCallback2 {
2773   my ($text, $symbol, $tag) = @_;
2775   # If we're not in CDATA convert to entities.
2776   # We could handle <programlisting> differently, though I'm not sure it helps.
2777   if ($tag eq "") {
2778     # replace only if its not a tag
2779     $text =~ s/&(?![a-zA-Z#]+;)/&amp;/g;        # Do this first, or the others get messed up.
2780     $text =~ s/<(?![a-zA-Z\/!])/&lt;/g;
2781     $text =~ s/(?<![a-zA-Z0-9"'\/-])>/&gt;/g;
2783     # Handle "#include <xxxxx>"
2784     $text =~ s/#include(\s+)<([^>]+)>/#include$1&lt;$2&gt;/g;
2785   }
2787   return $text;
2790 #############################################################################
2791 # Function    : ExpandAnnotation
2792 # Description : This turns annotations into acronym tags.
2793 # Arguments   : $symbol - the symbol being documented, for error messages.
2794 #                $text - the text to expand.
2795 #############################################################################
2796 sub ExpandAnnotation {
2797     my ($symbol, $param_desc) = @_;
2798     my $param_annotations = "";
2800     # look for annotations at the start of the comment part
2801     if ($param_desc =~ m%^\s*\((.*?)\):%) {
2802         my @annotations;
2803         my $annotation;
2804         $param_desc = $';
2806         @annotations = split(/\)\s*\(/,$1);
2807         foreach $annotation (@annotations) {
2808             # need to search for the longest key-match in %AnnotationDefinition
2809             my $match_length=0;
2810             my $match_annotation="";
2811             my $annotationdef;
2812             foreach $annotationdef (keys %AnnotationDefinition) {
2813                 if ($annotation =~ m/^$annotationdef/) {
2814                     if (length($annotationdef)>$match_length) {
2815                         $match_length=length($annotationdef);
2816                         $match_annotation=$annotationdef;
2817                     }
2818                 }
2819             }
2820             my $annotation_extra = "";
2821             if ($match_annotation ne "") {
2822                 if ($annotation =~ m%$match_annotation\s+(.*)%) {
2823                     $annotation_extra = " $1";
2824                 }
2825                 $AnnotationsUsed{$match_annotation} = 1;
2826                 $param_annotations .= "[<acronym>$match_annotation</acronym>$annotation_extra]";
2827             }
2828             else {
2829                 &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
2830                     "unknown annotation \"$annotation\" in documentation for $symbol.");
2831                 $param_annotations .= "[$annotation]";
2832             }
2833         }
2834         chomp($param_desc);
2835         $param_desc =~ m/^(.*?)\.*\s*$/s;
2836         $param_desc = "$1. ";
2837     }
2838     if ($param_annotations ne "") {
2839         $param_annotations = "<emphasis role=\"annotation\">$param_annotations</emphasis>";
2840     }
2841     return ($param_desc, $param_annotations);
2844 #############################################################################
2845 # Function    : ExpandAbbreviations
2846 # Description : This turns the abbreviations function(), macro(), @param,
2847 #                %constant, and #symbol into appropriate DocBook markup.
2848 #               CDATA sections and <programlisting> parts are skipped.
2849 # Arguments   : $symbol - the symbol being documented, for error messages.
2850 #                $text - the text to expand.
2851 #############################################################################
2853 sub ExpandAbbreviations {
2854   my ($symbol, $text) = @_;
2856   # Note: This is a fallback and normally done in the markdown parser
2858   # Convert "|[" and "]|" into the start and end of program listing examples.
2859   # Support \[<!-- language="C" --> modifiers
2860   $text =~ s%\|\[<!-- language="([^"]+)" -->%<informalexample><programlisting language="$1"><![CDATA[%g;
2861   $text =~ s%\|\[%<informalexample><programlisting><![CDATA[%g;
2862   $text =~ s%\]\|%]]></programlisting></informalexample>%g;
2864   # keep CDATA unmodified, preserve ulink tags (ideally we preseve all tags
2865   # as such)
2866   return &ModifyXMLElements ($text, $symbol,
2867                              "<!\\[CDATA\\[|<ulink[^>]*>|<programlisting[^>]*>|<!DOCTYPE",
2868                              \&ExpandAbbreviationsEndTag,
2869                              \&ExpandAbbreviationsCallback);
2873 # Returns the end tag (as a regexp) corresponding to the given start tag.
2874 sub ExpandAbbreviationsEndTag {
2875   my ($start_tag) = @_;
2877   if ($start_tag eq "<!\[CDATA\[") {
2878     return "]]>";
2879   } elsif ($start_tag eq "<!DOCTYPE") {
2880     return ">";
2881   } elsif ($start_tag =~ m/<(\w+)/) {
2882     return "</$1>";
2883   }
2886 # Called inside or outside each CDATA or <programlisting> section.
2887 sub ExpandAbbreviationsCallback {
2888   my ($text, $symbol, $tag) = @_;
2890   if ($tag =~ m/^<programlisting/) {
2891     # Handle any embedded CDATA sections.
2892     return &ModifyXMLElements ($text, $symbol,
2893                                "<!\\[CDATA\\[",
2894                                \&ExpandAbbreviationsEndTag,
2895                                \&ExpandAbbreviationsCallback2);
2896   } elsif ($tag eq "") {
2897     # NOTE: this is a fallback. It is normally done by the Markdown parser.
2899     # We are outside any CDATA or <programlisting> sections, so we expand
2900     # any gtk-doc abbreviations.
2902     # Convert '@param()'
2903     # FIXME: we could make those also links ($symbol.$2), but that would be less
2904     # useful as the link target is a few lines up or down
2905     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)/$1<parameter>$2()<\/parameter>/g;
2907     # Convert 'function()' or 'macro()'.
2908     # if there is abc_*_def() we don't want to make a link to _def()
2909     # FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
2910     $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2911     # handle #Object.func()
2912     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
2914     # Convert '@param', but not '\@param'.
2915     $text =~ s/(\A|[^\\])\@(\w+((\.|->)\w+)*)/$1<parameter>$2<\/parameter>/g;
2916     $text =~ s/\\\@/\@/g;
2918     # Convert '%constant', but not '\%constant'.
2919     # Also allow negative numbers, e.g. %-1.
2920     $text =~ s/(\A|[^\\])\%(-?\w+)/$1.&MakeXRef($2, &tagify($2, "literal"));/eg;
2921     $text =~ s/\\\%/\%/g;
2923     # Convert '#symbol', but not '\#symbol'.
2924     $text =~ s/(\A|[^\\])#([\w\-:\.]+[\w]+)/$1.&MakeHashXRef($2, "type");/eg;
2925     $text =~ s/\\#/#/g;
2926   }
2928   return $text;
2931 # This is called inside a <programlisting>
2932 sub ExpandAbbreviationsCallback2 {
2933   my ($text, $symbol, $tag) = @_;
2935   if ($tag eq "") {
2936     # We are inside a <programlisting> but outside any CDATA sections,
2937     # so we expand any gtk-doc abbreviations.
2938     # FIXME: why is this different from &ExpandAbbreviationsCallback(),
2939     #        why not just call it
2940     $text =~ s/#(\w+)/&MakeHashXRef($1, "");/eg;
2941   } elsif ($tag eq "<![CDATA[") {
2942     # NOTE: this is a fallback. It is normally done by the Markdown parser.
2943     $text = &ReplaceEntities ($text, $symbol);
2944   }
2946   return $text;
2949 sub MakeHashXRef {
2950     my ($symbol, $tag) = @_;;
2951     my $text = $symbol;
2953     # Check for things like '#include', '#define', and skip them.
2954     if ($PreProcessorDirectives{$symbol}) {
2955       return "#$symbol";
2956     }
2958     # Get rid of special suffixes ('-struct','-enum').
2959     $text =~ s/-struct$//;
2960     $text =~ s/-enum$//;
2962     # If the symbol is in the form "Object::signal", then change the symbol to
2963     # "Object-signal" and use "signal" as the text.
2964     if ($symbol =~ s/::/-/) {
2965       $text = "“$'”";
2966     }
2968     # If the symbol is in the form "Object:property", then change the symbol to
2969     # "Object--property" and use "property" as the text.
2970     if ($symbol =~ s/:/--/) {
2971       $text = "“$'”";
2972     }
2974     if ($tag ne "") {
2975       $text = tagify ($text, $tag);
2976     }
2978     return &MakeXRef($symbol, $text);
2982 #############################################################################
2983 # Function    : ModifyXMLElements
2984 # Description : Looks for given XML element tags within the text, and calls
2985 #               the callback on pieces of text inside & outside those elements.
2986 #               Used for special handling of text inside things like CDATA
2987 #               and <programlisting>.
2988 # Arguments   : $text - the text.
2989 #               $symbol - the symbol currently being documented (only used for
2990 #                      error messages).
2991 #               $start_tag_regexp - the regular expression to match start tags.
2992 #                      e.g. "<!\\[CDATA\\[|<programlisting[^>]*>" to match
2993 #                      CDATA sections or programlisting elements.
2994 #               $end_tag_func - function which is passed the matched start tag
2995 #                      and should return the appropriate end tag string regexp.
2996 #               $callback - callback called with each part of the text. It is
2997 #                      called with a piece of text, the symbol being
2998 #                      documented, and the matched start tag or "" if the text
2999 #                      is outside the XML elements being matched.
3000 #############################################################################
3001 sub ModifyXMLElements {
3002     my ($text, $symbol, $start_tag_regexp, $end_tag_func, $callback) = @_;
3003     my ($before_tag, $start_tag, $end_tag_regexp, $end_tag);
3004     my $result = "";
3006     while ($text =~ m/$start_tag_regexp/s) {
3007       $before_tag = $`; # Prematch for last successful match string
3008       $start_tag = $&;  # Last successful match
3009       $text = $';       # Postmatch for last successful match string
3011       $result .= &$callback ($before_tag, $symbol, "");
3012       $result .= $start_tag;
3014       # get the matching end-tag for current tag
3015       $end_tag_regexp = &$end_tag_func ($start_tag);
3017       if ($text =~ m/$end_tag_regexp/s) {
3018         $before_tag = $`;
3019         $end_tag = $&;
3020         $text = $';
3022         $result .= &$callback ($before_tag, $symbol, $start_tag);
3023         $result .= $end_tag;
3024       } else {
3025         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
3026             "Can't find tag end: $end_tag_regexp in docs for: $symbol.");
3027         # Just assume it is all inside the tag.
3028         $result .= &$callback ($text, $symbol, $start_tag);
3029         $text = "";
3030       }
3031     }
3033     # Handle any remaining text outside the tags.
3034     $result .= &$callback ($text, $symbol, "");
3036     return $result;
3039 sub noop {
3040   return $_[0];
3043 # Adds a tag around some text.
3044 # e.g tagify("Text", "literal") => "<literal>Text</literal>".
3045 sub tagify {
3046    my ($text, $elem) = @_;
3047    return "<" . $elem . ">" . $text . "</" . $elem . ">";
3051 #############################################################################
3052 # Function    : MakeXRef
3053 # Description : This returns a cross-reference link to the given symbol.
3054 #                Though it doesn't try to do this for a few standard C types
3055 #                that it        knows won't be in the documentation.
3056 # Arguments   : $symbol - the symbol to try to create a XRef to.
3057 #               $text - text text to put inside the XRef, defaults to $symbol
3058 #############################################################################
3060 sub MakeXRef {
3061     my ($symbol, $text) = ($_[0], $_[1]);
3063     $symbol =~ s/^\s+//;
3064     $symbol =~ s/\s+$//;
3066     if (!defined($text)) {
3067         $text = $symbol;
3069         # Get rid of special suffixes ('-struct','-enum').
3070         $text =~ s/-struct$//;
3071         $text =~ s/-enum$//;
3072     }
3074     if ($symbol =~ m/ /) {
3075         return "$text";
3076     }
3078     #print "Getting type link for $symbol -> $text\n";
3080     my $symbol_id = &CreateValidSGMLID ($symbol);
3081     return "<link linkend=\"$symbol_id\">$text</link>";
3085 #############################################################################
3086 # Function    : MakeIndexterms
3087 # Description : This returns a indexterm elements for the given symbol
3088 # Arguments   : $symbol - the symbol to create indexterms for
3089 #############################################################################
3091 sub MakeIndexterms {
3092   my ($symbol, $id) = @_;
3093   my $terms =  "";
3094   my $sortas = "";
3096   # make the index useful, by ommiting the namespace when sorting
3097   if ($NAME_SPACE ne "") {
3098     if ($symbol =~ m/^$NAME_SPACE\_?(.*)/i) {
3099        $sortas=" sortas=\"$1\"";
3100     }
3101   }
3103   if (exists $Deprecated{$symbol}) {
3104       $terms .= "<indexterm zone=\"$id\" role=\"deprecated\"><primary$sortas>$symbol</primary></indexterm>";
3105       $IndexEntriesDeprecated{$symbol}=$id;
3106       $IndexEntriesFull{$symbol}=$id;
3107   }
3108   if (exists $Since{$symbol}) {
3109      my $since = $Since{$symbol};
3110      $since =~ s/^\s+//;
3111      $since =~ s/\s+$//;
3112      if ($since ne "") {
3113          $terms .= "<indexterm zone=\"$id\" role=\"$since\"><primary$sortas>$symbol</primary></indexterm>";
3114      }
3115      $IndexEntriesSince{$symbol}=$id;
3116      $IndexEntriesFull{$symbol}=$id;
3117   }
3118   if ($terms eq "") {
3119      $terms .= "<indexterm zone=\"$id\"><primary$sortas>$symbol</primary></indexterm>";
3120      $IndexEntriesFull{$symbol}=$id;
3121   }
3123   return $terms;
3126 #############################################################################
3127 # Function    : MakeDeprecationNote
3128 # Description : This returns a deprecation warning for the given symbol.
3129 # Arguments   : $symbol - the symbol to try to create a warning for.
3130 #############################################################################
3132 sub MakeDeprecationNote {
3133     my ($symbol) = $_[0];
3134     my $desc = "";
3135     if (exists $Deprecated{$symbol}) {
3136         my $note;
3138         $desc .= "<warning><para><literal>$symbol</literal> ";
3140         $note = $Deprecated{$symbol};
3142         if ($note =~ /^\s*([0-9\.]+)\s*:?/) {
3143                 $desc .= "has been deprecated since version $1 and should not be used in newly-written code.</para>";
3144         } else {
3145                 $desc .= "is deprecated and should not be used in newly-written code.</para>";
3146         }
3147         $note =~ s/^\s*([0-9\.]+)\s*:?\s*//;
3148         $note =~ s/^\s+//;
3149         $note =~ s/\s+$//;
3150         if ($note ne "") {
3151             $note = &ConvertMarkDown($symbol, $note);
3152             $desc .= " " . $note;
3153         }
3154         $desc .= "</warning>\n";
3155     }
3156     return $desc;
3159 #############################################################################
3160 # Function    : MakeConditionDescription
3161 # Description : This returns a sumary of conditions for the given symbol.
3162 # Arguments   : $symbol - the symbol to try to create the sumary.
3163 #############################################################################
3165 sub MakeConditionDescription {
3166     my ($symbol) = $_[0];
3167     my $desc = "";
3169     if (exists $Deprecated{$symbol}) {
3170         if ($desc ne "") {
3171             $desc .= "|";
3172         }
3174         if ($Deprecated{$symbol} =~ /^\s*(.*?)\s*$/) {
3175                 $desc .= "deprecated:$1";
3176         } else {
3177                 $desc .= "deprecated";
3178         }
3179     }
3181     if (exists $Since{$symbol}) {
3182         if ($desc ne "") {
3183             $desc .= "|";
3184         }
3186         if ($Since{$symbol} =~ /^\s*(.*?)\s*$/) {
3187                 $desc .= "since:$1";
3188         } else {
3189                 $desc .= "since";
3190         }
3191     }
3193     if (exists $StabilityLevel{$symbol}) {
3194         if ($desc ne "") {
3195             $desc .= "|";
3196         }
3197         $desc .= "stability:".$StabilityLevel{$symbol};
3198     }
3200     if ($desc ne "") {
3201         my $cond = $desc;
3202         $cond =~ s/\"/&quot;/g;
3203         $desc=" condition=\"".$cond."\"";
3204         #print "condition for '$symbol' = '$desc'\n";
3205     }
3206     return $desc;
3209 #############################################################################
3210 # Function    : GetHierarchy
3211 # Description : Returns the DocBook output describing the ancestors and
3212 #               immediate children of a GObject subclass. It uses the
3213 #               global @Objects and @ObjectLevels arrays to walk the tree.
3215 #               FIXME: See ReadObjectHierarchy() for some overlap
3217 # Arguments   : $object - the GtkObject subclass.
3218 #############################################################################
3220 sub GetHierarchy {
3221     my ($object) = @_;
3223     # Find object in the objects array.
3224     my $found = 0;
3225     my @children = ();
3226     my $i;
3227     my $level;
3228     my $j;
3229     for ($i = 0; $i < @Objects; $i++) {
3230         if ($found) {
3231             if ($ObjectLevels[$i] <= $level) {
3232             last;
3233         }
3234             elsif ($ObjectLevels[$i] == $level + 1) {
3235                 push (@children, $Objects[$i]);
3236             }
3237         }
3238         elsif ($Objects[$i] eq $object) {
3239             $found = 1;
3240             $j = $i;
3241             $level = $ObjectLevels[$i];
3242         }
3243     }
3244     if (!$found) {
3245         return "";
3246     }
3248     # Walk up the hierarchy, pushing ancestors onto the ancestors array.
3249     my @ancestors = ();
3250     push (@ancestors, $object);
3251     #print "Level: $level\n";
3252     while ($level > 1) {
3253         $j--;
3254         if ($ObjectLevels[$j] < $level) {
3255             push (@ancestors, $Objects[$j]);
3256             $level = $ObjectLevels[$j];
3257             #print "Level: $level\n";
3258         }
3259     }
3261     # Output the ancestors, indented and with links.
3262     my @tree = ();
3263     $level = 1;
3264     for ($i = $#ancestors; $i >= 0; $i--) {
3265         my $link_text;
3266         # Don't add a link to the current object, i.e. when i == 0.
3267         if ($i > 0) {
3268             my $ancestor_id = &CreateValidSGMLID ($ancestors[$i]);
3269             $link_text = "<link linkend=\"$ancestor_id\">$ancestors[$i]</link>";
3270         } else {
3271             $link_text = "$ancestors[$i]";
3272         }
3273         push (@tree, ' ' x ($level * 4) . $link_text);
3274         $level++;
3275     }
3276     # Output the children, indented and with links.
3277     for ($i = 0; $i <= $#children; $i++) {
3278       my $id = &CreateValidSGMLID ($children[$i]);
3279       my $link_text = "<link linkend=\"$id\">$children[$i]</link>";
3280       push (@tree, ' ' x ($level * 4) . $link_text);
3281     }
3283     # prevent trimming of initial indent
3284     return "<!-- -->" . &AddTreeLineArt(\@tree) . "\n"; 
3288 #############################################################################
3289 # Function    : GetInterfaces
3290 # Description : Returns the DocBook output describing the interfaces
3291 #               implemented by a class. It uses the global %Interfaces hash.
3292 # Arguments   : $object - the GtkObject subclass.
3293 #############################################################################
3295 sub GetInterfaces {
3296     my ($object) = @_;
3297     my $text = "";
3298     my $i;
3300     # Find object in the objects array.
3301     if (exists($Interfaces{$object})) {
3302         my @ifaces = split(' ', $Interfaces{$object});
3303         $text = <<EOF;
3304 <para>
3305 $object implements
3307         for ($i = 0; $i <= $#ifaces; $i++) {
3308             my $id = &CreateValidSGMLID ($ifaces[$i]);
3309             $text .= " <link linkend=\"$id\">$ifaces[$i]</link>";
3310             if ($i < $#ifaces - 1) {
3311                 $text .= ', ';
3312             }
3313             elsif ($i < $#ifaces) {
3314                 $text .= ' and ';
3315             }
3316             else {
3317                 $text .= '.';
3318             }
3319         }
3320         $text .= <<EOF;
3321 </para>
3323     }
3325     return $text;
3328 #############################################################################
3329 # Function    : GetImplementations
3330 # Description : Returns the DocBook output describing the implementations
3331 #               of an interface. It uses the global %Interfaces hash.
3332 # Arguments   : $object - the GtkObject subclass.
3333 #############################################################################
3335 sub GetImplementations {
3336     my ($object) = @_;
3337     my @impls = ();
3338     my $text = "";
3339     my $i;
3340     foreach my $key (keys %Interfaces) {
3341         if ($Interfaces{$key} =~ /\b$object\b/) {
3342             push (@impls, $key);
3343         }
3344     }
3345     if ($#impls >= 0) {
3346         @impls = sort @impls;
3347         $text = <<EOF;
3348 <para>
3349 $object is implemented by
3351         for ($i = 0; $i <= $#impls; $i++) {
3352             my $id = &CreateValidSGMLID ($impls[$i]);
3353             $text .= " <link linkend=\"$id\">$impls[$i]</link>";
3354             if ($i < $#impls - 1) {
3355                 $text .= ', ';
3356             }
3357             elsif ($i < $#impls) {
3358                 $text .= ' and ';
3359             }
3360             else {
3361                 $text .= '.';
3362             }
3363         }
3364         $text .= <<EOF;
3365 </para>
3367     }
3368     return $text;
3372 #############################################################################
3373 # Function    : GetPrerequisites
3374 # Description : Returns the DocBook output describing the prerequisites
3375 #               of an interface. It uses the global %Prerequisites hash.
3376 # Arguments   : $iface - the interface.
3377 #############################################################################
3379 sub GetPrerequisites {
3380     my ($iface) = @_;
3381     my $text = "";
3382     my $i;
3384     if (exists($Prerequisites{$iface})) {
3385         $text = <<EOF;
3386 <para>
3387 $iface requires
3389         my @prereqs = split(' ', $Prerequisites{$iface});
3390         for ($i = 0; $i <= $#prereqs; $i++) {
3391             my $id = &CreateValidSGMLID ($prereqs[$i]);
3392             $text .= " <link linkend=\"$id\">$prereqs[$i]</link>";
3393             if ($i < $#prereqs - 1) {
3394                 $text .= ', ';
3395             }
3396             elsif ($i < $#prereqs) {
3397                 $text .= ' and ';
3398             }
3399             else {
3400                 $text .= '.';
3401             }
3402         }
3403         $text .= <<EOF;
3404 </para>
3406     }
3407     return $text;
3410 #############################################################################
3411 # Function    : GetDerived
3412 # Description : Returns the DocBook output describing the derived interfaces
3413 #               of an interface. It uses the global %Prerequisites hash.
3414 # Arguments   : $iface - the interface.
3415 #############################################################################
3417 sub GetDerived {
3418     my ($iface) = @_;
3419     my $text = "";
3420     my $i;
3422     my @derived = ();
3423     foreach my $key (keys %Prerequisites) {
3424         if ($Prerequisites{$key} =~ /\b$iface\b/) {
3425             push (@derived, $key);
3426         }
3427     }
3428     if ($#derived >= 0) {
3429         @derived = sort @derived;
3430         $text = <<EOF;
3431 <para>
3432 $iface is required by
3434         for ($i = 0; $i <= $#derived; $i++) {
3435             my $id = &CreateValidSGMLID ($derived[$i]);
3436             $text .= " <link linkend=\"$id\">$derived[$i]</link>";
3437             if ($i < $#derived - 1) {
3438                 $text .= ', ';
3439             }
3440             elsif ($i < $#derived) {
3441                 $text .= ' and ';
3442             }
3443             else {
3444                 $text .= '.';
3445             }
3446         }
3447         $text .= <<EOF;
3448 </para>
3450     }
3451     return $text;
3455 #############################################################################
3456 # Function    : GetSignals
3457 # Description : Returns the synopsis and detailed description DocBook output
3458 #                for the signal handlers of a given GtkObject subclass.
3459 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3460 #############################################################################
3462 sub GetSignals {
3463     my ($object) = @_;
3464     my $synop = "";
3465     my $desc = "";
3467     my $i;
3468     for ($i = 0; $i <= $#SignalObjects; $i++) {
3469         if ($SignalObjects[$i] eq $object) {
3470             #print "Found signal: $SignalNames[$i]\n";
3471             my $name = $SignalNames[$i];
3472             my $symbol = "${object}::${name}";
3473             my $id = &CreateValidSGMLID ("$object-$name");
3475             $desc .= "<refsect2 id=\"$id\" role=\"signal\"><title>The <literal>“$name”</literal> signal</title>\n";
3476             $desc .= MakeIndexterms($symbol, $id);
3477             $desc .= "\n";
3478             $desc .= OutputSymbolExtraLinks($symbol);
3480             $desc .= "<programlisting language=\"C\">";
3482             $SignalReturns[$i] =~ m/\s*(const\s+)?(\w+)\s*(\**)/;
3483             my $type_modifier = defined($1) ? $1 : "";
3484             my $type = $2;
3485             my $pointer = $3;
3486             my $xref = &MakeXRef ($type, &tagify($type, "returnvalue"));
3488             my $ret_type_output = "$type_modifier$xref$pointer";
3489             my $callback_name = "user_function";
3490             $desc  .= "${ret_type_output}\n${callback_name} (";
3492             my $indentation = ' ' x (length($callback_name) + 2);
3493             my $pad = $indentation;
3495             my $sourceparams = $SourceSymbolParams{$symbol};
3496             my @params = split ("\n", $SignalPrototypes[$i]);
3497             my $j;
3498             my $l;
3499             my $type_len = length("gpointer");
3500             my $name_len = length("user_data");
3501             # do two passes, the first one is to calculate padding
3502             for ($l = 0; $l < 2; $l++) {
3503                 for ($j = 0; $j <= $#params; $j++) {
3504                     my $param_name;
3505                     # allow alphanumerics, '_', '[' & ']' in param names
3506                     if ($params[$j] =~ m/^\s*(\w+)\s*(\**)\s*([\w\[\]]+)\s*$/) {
3507                         $type = $1;
3508                         $pointer = $2;
3509                         if (defined($sourceparams)) {
3510                             $param_name = $$sourceparams[$PARAM_FIELD_COUNT * $j];
3511                         }
3512                         else {
3513                             $param_name = $3;
3514                         }
3515                         if (!defined($param_name)) {
3516                             $param_name = "arg$j";
3517                         }
3518                         if ($l == 0) {
3519                             if (length($type) + length($pointer) > $type_len) {
3520                                 $type_len = length($type) + length($pointer);
3521                             }
3522                             if (length($param_name) > $name_len) {
3523                                 $name_len = length($param_name);
3524                             }
3525                         }
3526                         else {
3527                             $xref = &MakeXRef ($type, &tagify($type, "type"));
3528                             $pad = ' ' x ($type_len - length($type) - length($pointer));
3529                             $desc .= "$xref$pad $pointer${param_name},\n";
3530                             $desc .= $indentation;
3531                         }
3532                     } else {
3533                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
3534                              "Can't parse arg: $params[$j]\nArgs:$SignalPrototypes[$i]");
3535                     }
3536                 }
3537             }
3538             $xref = &MakeXRef ("gpointer", &tagify("gpointer", "type"));
3539             $pad = ' ' x ($type_len - length("gpointer"));
3540             $desc  .= "$xref$pad user_data)";
3541             $desc  .= "</programlisting>\n";
3543             my $flags = $SignalFlags[$i];
3544             my $flags_string = "";
3546             if (defined ($flags)) {
3547               if ($flags =~ m/f/) {
3548                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-FIRST:CAPS\">Run First</link>";
3549               }
3550               elsif ($flags =~ m/l/) {
3551                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-LAST:CAPS\">Run Last</link>";
3552               }
3553               elsif ($flags =~ m/c/) {
3554                 $flags_string = "<link linkend=\"G-SIGNAL-RUN-CLEANUP:CAPS\">Cleanup</link>";
3555                 $flags_string = "Cleanup";
3556               }
3557               if ($flags =~ m/r/) {
3558                 if ($flags_string) { $flags_string .= " / "; }
3559                 $flags_string = "<link linkend=\"G-SIGNAL-NO-RECURSE:CAPS\">No Recursion</link>";
3560               }
3561               if ($flags =~ m/d/) {
3562                 if ($flags_string) { $flags_string .= " / "; }
3563                 $flags_string = "<link linkend=\"G-SIGNAL-DETAILED:CAPS\">Has Details</link>";
3564               }
3565               if ($flags =~ m/a/) {
3566                 if ($flags_string) { $flags_string .= " / "; }
3567                 $flags_string = "<link linkend=\"G-SIGNAL-ACTION:CAPS\">Action</link>";
3568               }
3569               if ($flags =~ m/h/) {
3570                 if ($flags_string) { $flags_string .= " / "; }
3571                 $flags_string = "<link linkend=\"G-SIGNAL-NO-HOOKS:CAPS\">No Hooks</link>";
3572               }
3573             }
3575             $synop .= "<row><entry role=\"signal_type\">${ret_type_output}</entry><entry role=\"signal_name\"><link linkend=\"$id\">${name}</link></entry><entry role=\"signal_flags\">${flags_string}</entry></row>\n";
3577             my $parameters = &OutputParamDescriptions ("SIGNAL", $symbol);
3578             my $parameters_output = 0;
3580             $AllSymbols{$symbol} = 1;
3581             if (defined ($SymbolDocs{$symbol})) {
3582                 my $symbol_docs = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
3584                 # Try to insert the parameter table at the author's desired
3585                 # position. Otherwise we need to tag it onto the end.
3586                 if ($symbol_docs =~ s/<!--PARAMETERS-->/$parameters/) {
3587                   $parameters_output = 1;
3588                 }
3589                 $desc .= $symbol_docs;
3591                 if (!IsEmptyDoc($SymbolDocs{$symbol})) {
3592                     $AllDocumentedSymbols{$symbol} = 1;
3593                 }
3594             }
3595             $desc .= &MakeDeprecationNote($symbol);
3597             if ($parameters_output == 0) {
3598                 $desc .= $parameters;
3599             }
3600             if ($flags_string) {
3601                 $desc  .= "<para>Flags: $flags_string</para>\n";
3602             }
3603             $desc .= OutputSymbolTraits ($symbol);
3604             $desc .= "</refsect2>";
3605         }
3606     }
3607     return ($synop, $desc);
3611 #############################################################################
3612 # Function    : GetArgs
3613 # Description : Returns the synopsis and detailed description DocBook output
3614 #                for the Args of a given GtkObject subclass.
3615 # Arguments   : $object - the GtkObject subclass, e.g. 'GtkButton'.
3616 #############################################################################
3618 sub GetArgs {
3619     my ($object) = @_;
3620     my $synop = "";
3621     my $desc = "";
3622     my $child_synop = "";
3623     my $child_desc = "";
3624     my $style_synop = "";
3625     my $style_desc = "";
3627     my $i;
3628     for ($i = 0; $i <= $#ArgObjects; $i++) {
3629         if ($ArgObjects[$i] eq $object) {
3630             #print "Found arg: $ArgNames[$i]\n";
3631             my $name = $ArgNames[$i];
3632             my $flags = $ArgFlags[$i];
3633             my $flags_string = "";
3634             my $kind = "";
3635             my $id_sep = "";
3637             if ($flags =~ m/c/) {
3638                 $kind = "child property";
3639                 $id_sep = "c-";
3640             }
3641             elsif ($flags =~ m/s/) {
3642                 $kind = "style property";
3643                 $id_sep = "s-";
3644             }
3645             else {
3646                 $kind = "property";
3647             }
3649             # Remember only one colon so we don't clash with signals.
3650             my $symbol = "${object}:${name}";
3651             # use two dashes and ev. an extra separator here for the same reason.
3652             my $id = &CreateValidSGMLID ("$object--$id_sep$name");
3654             my $type = $ArgTypes[$i];
3655             my $type_output;
3656             my $range = $ArgRanges[$i];
3657             my $range_output = CreateValidSGML ($range);
3658             my $default = $ArgDefaults[$i];
3659             my $default_output = CreateValidSGML ($default);
3661             if ($type eq "GtkString") {
3662                 $type = "char&#160;*";
3663             }
3664             if ($type eq "GtkSignal") {
3665                 $type = "GtkSignalFunc, gpointer";
3666                 $type_output = &MakeXRef ("GtkSignalFunc") . ", "
3667                     . &MakeXRef ("gpointer");
3668             } elsif ($type =~ m/^(\w+)\*$/) {
3669                 $type_output = &MakeXRef ($1, &tagify($1, "type")) . "&#160;*";
3670             } else {
3671                 $type_output = &MakeXRef ($type, &tagify($type, "type"));
3672             }
3674             if ($flags =~ m/r/) {
3675                 $flags_string = "Read";
3676             }
3677             if ($flags =~ m/w/) {
3678                 if ($flags_string) { $flags_string .= " / "; }
3679                 $flags_string .= "Write";
3680             }
3681             if ($flags =~ m/x/) {
3682                 if ($flags_string) { $flags_string .= " / "; }
3683                 $flags_string .= "Construct";
3684             }
3685             if ($flags =~ m/X/) {
3686                 if ($flags_string) { $flags_string .= " / "; }
3687                 $flags_string .= "Construct Only";
3688             }
3690             $AllSymbols{$symbol} = 1;
3691             my $blurb;
3692             if (defined($SymbolDocs{$symbol}) &&
3693                 !IsEmptyDoc($SymbolDocs{$symbol})) {
3694                 $blurb = &ConvertMarkDown($symbol, $SymbolDocs{$symbol});
3695                 #print ".. [$SymbolDocs{$symbol}][$blurb]\n";
3696                 $AllDocumentedSymbols{$symbol} = 1;
3697             }
3698             else {
3699                 if (!($ArgBlurbs[$i] eq "")) {
3700                     $AllDocumentedSymbols{$symbol} = 1;
3701                 } else {
3702                     # FIXME: print a warning?
3703                     #print ".. no description\n";
3704                 }
3705                 $blurb = "<para>" . &CreateValidSGML ($ArgBlurbs[$i]) . "</para>";
3706             }
3708             my $pad1 = " " x (24 - length ($name));
3710             my $arg_synop = "<row><entry role=\"property_type\">$type_output</entry><entry role=\"property_name\"><link linkend=\"$id\">$name</link></entry><entry role=\"property_flags\">$flags_string</entry></row>\n";
3711             my $arg_desc = "<refsect2 id=\"$id\" role=\"property\"><title>The <literal>“$name”</literal> $kind</title>\n";
3712             $arg_desc .= MakeIndexterms($symbol, $id);
3713             $arg_desc .= "\n";
3714             $arg_desc .= OutputSymbolExtraLinks($symbol);
3716             $arg_desc .= "<programlisting>  “$name”$pad1 $type_output</programlisting>\n";
3717             $arg_desc .= $blurb;
3718             $arg_desc .= &MakeDeprecationNote($symbol);
3720             if ($flags_string) {
3721               $arg_desc  .= "<para>Flags: $flags_string</para>\n";
3722             }
3723             if ($range ne "") {
3724                 $arg_desc .= "<para>Allowed values: $range_output</para>\n";
3725             }
3726             if ($default ne "") {
3727                 $arg_desc .= "<para>Default value: $default_output</para>\n";
3728             }
3729             $arg_desc .= OutputSymbolTraits ($symbol);
3730             $arg_desc .= "</refsect2>\n";
3732             if ($flags =~ m/c/) {
3733                 $child_synop .= $arg_synop;
3734                 $child_desc .= $arg_desc;
3735             }
3736             elsif ($flags =~ m/s/) {
3737                 $style_synop .= $arg_synop;
3738                 $style_desc .= $arg_desc;
3739             }
3740             else {
3741                 $synop .= $arg_synop;
3742                 $desc .= $arg_desc;
3743             }
3744         }
3745     }
3746     return ($synop, $child_synop, $style_synop, $desc, $child_desc, $style_desc);
3750 #############################################################################
3751 # Function    : ReadSourceDocumentation
3752 # Description : This reads in the documentation embedded in comment blocks
3753 #                in the source code (for Gnome).
3755 #                Parameter descriptions override any in the template files.
3756 #                Function descriptions are placed before any description from
3757 #                the template files.
3759 #                It recursively descends the source directory looking for .c
3760 #                files and scans them looking for specially-formatted comment
3761 #                blocks.
3763 # Arguments   : $source_dir - the directory to scan.
3764 #############m###############################################################
3766 sub ReadSourceDocumentation {
3767     my ($source_dir) = @_;
3768     my ($file, $dir, @suffix_list, $suffix);
3770     # prepend entries from @SOURCE_DIR
3771     for my $dir (@SOURCE_DIRS) {
3772         # Check if the filename is in the ignore list.
3773         if ($source_dir =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3774             @TRACE@("Skipping source directory: $source_dir");
3775             return;
3776         }
3777     }
3779     @TRACE@("Scanning source directory: $source_dir");
3781     # This array holds any subdirectories found.
3782     my (@subdirs) = ();
3784     @suffix_list = split (/,/, $SOURCE_SUFFIXES);
3786     opendir (SRCDIR, $source_dir)
3787         || die "Can't open source directory $source_dir: $!";
3789     foreach $file (readdir (SRCDIR)) {
3790       if ($file =~ /^\./) {
3791         next;
3792       } elsif (-d "$source_dir/$file") {
3793         push (@subdirs, $file);
3794       } elsif (@suffix_list) {
3795         foreach $suffix (@suffix_list) {
3796           if ($file =~ m/\.\Q${suffix}\E$/) {
3797             &ScanSourceFile ("$source_dir/$file");
3798           }
3799         }
3800       } elsif ($file =~ m/\.[ch]$/) {
3801         &ScanSourceFile ("$source_dir/$file");
3802       }
3803     }
3804     closedir (SRCDIR);
3806     # Now recursively scan the subdirectories.
3807     foreach $dir (@subdirs) {
3808         &ReadSourceDocumentation ("$source_dir/$dir");
3809     }
3813 #############################################################################
3814 # Function    : ScanSourceFile
3815 # Description : Scans one source file looking for specially-formatted comment
3816 #                blocks. Later &MergeSourceDocumentation is used to merge any
3817 #                documentation found with the documentation already read in
3818 #                from the template files.
3820 # Arguments   : $file - the file to scan.
3821 #############################################################################
3823 sub ScanSourceFile {
3824     my ($file) = @_;
3825     my $basename;
3827     # prepend entries from @SOURCE_DIR
3828     for my $dir (@SOURCE_DIRS) {
3829         # Check if the filename is in the ignore list.
3830         if ($file =~ m%^\Q$dir\E/(.*)$% and $IGNORE_FILES =~ m/(\s|^)\Q$1\E(\s|$)/) {
3831             @TRACE@("Skipping source file: $file");
3832             return;
3833         }
3834     }
3836     if ($file =~ m/^.*[\/\\]([^\/\\]*)$/) {
3837         $basename = $1;
3838     } else {
3839         &LogWarning ($file, 1, "Can't find basename for this filename.");
3840         $basename = $file;
3841     }
3843     # Check if the basename is in the list of files to ignore.
3844     if ($IGNORE_FILES =~ m/(\s|^)\Q${basename}\E(\s|$)/) {
3845         @TRACE@("Skipping source file: $file");
3846         return;
3847     }
3849     @TRACE@("Scanning source file: $file");
3851     open (SRCFILE, $file)
3852         || die "Can't open $file: $!";
3853     my $in_comment_block = 0;
3854     my $symbol;
3855     my $in_part = "";
3856     my ($description, $return_desc, $return_start, $return_style);
3857     my ($since_desc, $stability_desc, $deprecated_desc);
3858     my $current_param;
3859     my $ignore_broken_returns;
3860     my @params;
3861     while (<SRCFILE>) {
3862         # Look for the start of a comment block.
3863         if (!$in_comment_block) {
3864             if (m%^\s*/\*.*\*/%) {
3865                 #one-line comment - not gtkdoc
3866             } elsif (m%^\s*/\*\*\s%) {
3867                 #print "Found comment block start\n";
3869                 $in_comment_block = 1;
3871                 # Reset all the symbol data.
3872                 $symbol = "";
3873                 $in_part = "";
3874                 $description = "";
3875                 $return_desc = "";
3876                 $return_style = "";
3877                 $since_desc = "";
3878                 $deprecated_desc = "";
3879                 $stability_desc = "";
3880                 $current_param = -1;
3881                 $ignore_broken_returns = 0;
3882                 @params = ();
3883             }
3884             next;
3885         }
3887         # We're in a comment block. Check if we've found the end of it.
3888         if (m%^\s*\*+/%) {
3889             if (!$symbol) {
3890                 # maybe its not even meant to be a gtk-doc comment?
3891                 &LogWarning ($file, $., "Symbol name not found at the start of the comment block.");
3892             } else {
3893                 # Add the return value description onto the end of the params.
3894                 if ($return_desc) {
3895                     push (@params, "Returns");
3896                     push (@params, $return_desc);
3897                     if ($return_style eq 'broken') {
3898                         &LogWarning ($file, $., "Free-form return value description in $symbol. Use `Returns:' to avoid ambiguities.");
3899                     }
3900                 }
3901                 # Convert special SGML characters
3902                 $description = &ConvertSGMLChars ($symbol, $description);
3903                 my $k;
3904                 for ($k = 1; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3905                     $params[$k] = &ConvertSGMLChars ($symbol, $params[$k]);
3906                 }
3908                 # Handle Section docs
3909                 if ($symbol =~ m/SECTION:\s*(.*)/) {
3910                     my $real_symbol=$1;
3911                     my $key;
3913                     if (scalar %KnownSymbols) {
3914                         if ((! defined($KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"})) || $KnownSymbols{"$TMPL_DIR/$real_symbol:Long_Description"} != 1) {
3915                             &LogWarning ($file, $., "Section $real_symbol is not defined in the $MODULE-sections.txt file.");
3916                         }
3917                     }
3919                     #print "SECTION DOCS found in source for : '$real_symbol'\n";
3920                     $ignore_broken_returns = 1;
3921                     for ($k = 0; $k <= $#params; $k += $PARAM_FIELD_COUNT) {
3922                         #print "   '".$params[$k]."'\n";
3923                         $params[$k] = "\L$params[$k]";
3924                         undef $key;
3925                         if ($params[$k] eq "short_description") {
3926                             $key = "$TMPL_DIR/$real_symbol:Short_Description";
3927                         } elsif ($params[$k] eq "see_also") {
3928                             $key = "$TMPL_DIR/$real_symbol:See_Also";
3929                         } elsif ($params[$k] eq "title") {
3930                             $key = "$TMPL_DIR/$real_symbol:Title";
3931                         } elsif ($params[$k] eq "stability") {
3932                             $key = "$TMPL_DIR/$real_symbol:Stability_Level";
3933                         } elsif ($params[$k] eq "section_id") {
3934                             $key = "$TMPL_DIR/$real_symbol:Section_Id";
3935                         } elsif ($params[$k] eq "include") {
3936                             $key = "$TMPL_DIR/$real_symbol:Include";
3937                         } elsif ($params[$k] eq "image") {
3938                             $key = "$TMPL_DIR/$real_symbol:Image";
3939                         }
3940                         if (defined($key)) {
3941                             $SourceSymbolDocs{$key}=$params[$k+1];
3942                             $SourceSymbolSourceFile{$key} = $file;
3943                             $SourceSymbolSourceLine{$key} = $.;
3944                         }
3945                     }
3946                     $SourceSymbolDocs{"$TMPL_DIR/$real_symbol:Long_Description"}=$description;
3947                     $SourceSymbolSourceFile{"$TMPL_DIR/$real_symbol:Long_Description"} = $file;
3948                     $SourceSymbolSourceLine{"$TMPL_DIR/$real_symbol:Long_Description"} = $.;
3949                     #$SourceSymbolTypes{$symbol} = "SECTION";
3950                 } else {
3951                     #print "SYMBOL DOCS found in source for : '$symbol' ",length($description), "\n";
3952                     $SourceSymbolDocs{$symbol} = $description;
3953                     $SourceSymbolParams{$symbol} = [ @params ];
3954                     # FIXME $SourceSymbolTypes{$symbol} = "STRUCT,SIGNAL,ARG,FUNCTION,MACRO";
3955                     #if (defined $DeclarationTypes{$symbol}) {
3956                     #    $SourceSymbolTypes{$symbol} = $DeclarationTypes{$symbol}
3957                     #}
3958                     $SourceSymbolSourceFile{$symbol} = $file;
3959                     $SourceSymbolSourceLine{$symbol} = $.;
3960                 }
3962                 if ($since_desc) {
3963                      ($since_desc, my @extra_lines) = split ("\n", $since_desc);
3964                      $since_desc =~ s/^\s+//;
3965                      $since_desc =~ s/\s+$//;
3966                      #print "Since($symbol) : [$since_desc]\n";
3967                      $Since{$symbol} = &ConvertSGMLChars ($symbol, $since_desc);
3968                      if(scalar @extra_lines) {
3969                          &LogWarning ($file, $., "multi-line since docs found");
3970                      }
3971                 }
3973                 if ($stability_desc) {
3974                     $stability_desc = &ParseStabilityLevel($stability_desc, $file, $., "Stability level for $symbol");
3975                     $StabilityLevel{$symbol} = &ConvertSGMLChars ($symbol, $stability_desc);
3976                 }
3978                 if ($deprecated_desc) {
3979                     if (!exists $Deprecated{$symbol}) {
3980                          # don't warn for signals and properties
3981                          #if ($symbol !~ m/::?(.*)/) {
3982                          if (defined $DeclarationTypes{$symbol}) {
3983                              &LogWarning ($file, $.,
3984                                  "$symbol is deprecated in the inline comments, but no deprecation guards were found around the declaration.".
3985                                  " (See the --deprecated-guards option for gtkdoc-scan.)");
3986                          }
3987                     }
3988                     $Deprecated{$symbol} = &ConvertSGMLChars ($symbol, $deprecated_desc);
3989                 }
3990             }
3992             $in_comment_block = 0;
3993             next;
3994         }
3996         # Get rid of ' * ' at start of every line in the comment block.
3997         s%^\s*\*\s?%%;
3998         # But make sure we don't get rid of the newline at the end.
3999         if (!$_) {
4000             $_ = "\n";
4001         }
4002         #print "DEBUG: scanning :$_";
4004         # If we haven't found the symbol name yet, look for it.
4005         if (!$symbol) {
4006             if (m%^\s*(SECTION:\s*\S+)%) {
4007                 $symbol = $1;
4008                 #print "SECTION DOCS found in source for : '$symbol'\n";
4009                 $ignore_broken_returns = 1;
4010             } elsif (m%^\s*([\w:-]*\w)\s*:?\s*(\([-a-z0-9_ ]+\)\s*)*$%) {
4011                 $symbol = $1;
4012                 #print "SYMBOL DOCS found in source for : '$symbol'\n";
4013             }
4014             next;
4015         }
4017         if ($in_part eq "description") {
4018             # Get rid of 'Description:'
4019             s%^\s*Description:%%;
4020         }
4022         if (m/^\s*(returns:|return\s+value:)/i) {
4023             if ($return_style eq 'broken') {
4024                 $description .= $return_start . $return_desc;
4025             }
4026             $return_start = $1;
4027             if ($return_style eq 'sane') {
4028                 &LogWarning ($file, $., "Multiple Returns for $symbol.");
4029             }
4030             $return_style = 'sane';
4031             $ignore_broken_returns = 1;
4032             $return_desc = $';
4033             $in_part = "return";
4034             next;
4035         } elsif (!$ignore_broken_returns && m/^\s*(returns\b\s*)/i) {
4036             $return_start = $1;
4037             $return_style = 'broken';
4038             $return_desc = $';
4039             $in_part = "return";
4040             next;
4041         } elsif (m%^\s*since:%i) {
4042             # we're in param section and have not seen the blank line
4043             if($in_part ne "") {
4044               $since_desc = $';
4045               $in_part = "since";
4046               next;
4047             }
4048         } elsif (m%^\s*deprecated:%i) {
4049             # we're in param section and have not seen the blank line
4050             if($in_part ne "") {
4051               $deprecated_desc = $';
4052               $in_part = "deprecated";
4053               next;
4054             }
4055         } elsif (m%^\s*stability:%i) {
4056             $stability_desc = $';
4057             $in_part = "stability";
4058             next;
4059         }
4061         if ($in_part eq "description") {
4062             $description .= $_;
4063             next;
4064         } elsif ($in_part eq "return") {
4065             $return_desc .= $_;
4066             next;
4067         } elsif ($in_part eq "since") {
4068             $since_desc .= $_;
4069             next;
4070         } elsif ($in_part eq "stability") {
4071             $stability_desc .= $_;
4072             next;
4073         } elsif ($in_part eq "deprecated") {
4074             $deprecated_desc .= $_;
4075             next;
4076         }
4078         # We must be in the parameters. Check for the empty line below them.
4079         if (m%^\s*$%) {
4080             $in_part = "description";
4081             next;
4082         }
4084         # Look for a parameter name.
4085         if (m%^\s*@(\S+)\s*:\s*%) {
4086             my $param_name = $1;
4087             my $param_desc = $';
4089             #print "Found parameter: $param_name\n";
4090             # Allow varargs variations
4091             if ($param_name =~ m/^\.\.\.$/) {
4092                 $param_name = "...";
4093             }
4094             if ("\L$param_name" eq "returns") {
4095                 $return_style = 'sane';
4096                 $ignore_broken_returns = 1;
4097             }
4098             @TRACE@("Found param for symbol $symbol : '$param_name'= '$_'");
4100             push (@params, $param_name);
4101             push (@params, $param_desc);
4102             $current_param += $PARAM_FIELD_COUNT;
4103             next;
4104         }
4106         # We must be in the middle of a parameter description, so add it on
4107         # to the last element in @params.
4108         if ($current_param == -1) {
4109             &LogWarning ($file, $., "Parsing comment block file : parameter expected.");
4110         } else {
4111             $params[$#params] .= $_;
4112         }
4113     }
4114     close (SRCFILE);
4117 #############################################################################
4118 # Function    : OutputMissingDocumentation
4119 # Description : Outputs report of documentation coverage to a file
4121 # Arguments   : none
4122 #############################################################################
4124 sub OutputMissingDocumentation {
4125     my $old_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.txt";
4126     my $new_undocumented_file = "$ROOT_DIR/$MODULE-undocumented.new";
4128     my $n_documented = 0;
4129     my $n_incomplete = 0;
4130     my $total = 0;
4131     my $symbol;
4132     my $percent;
4133     my $msg;
4134     my $buffer = "";
4135     my $buffer_deprecated = "";
4136     my $buffer_descriptions = "";
4138     open(UNDOCUMENTED, ">$new_undocumented_file")
4139       || die "Can't create $new_undocumented_file";
4141     foreach $symbol (sort (keys (%AllSymbols))) {
4142         # FIXME: should we print LogWarnings for undocumented stuff?
4143         # DEBUG
4144         #my $ssfile = &GetSymbolSourceFile($symbol);
4145         #my $ssline = &GetSymbolSourceLine($symbol);
4146         #my $location = "defined at " . (defined($ssfile)?$ssfile:"?") . ":" . (defined($ssline)?$ssline:"0") . "\n";
4147         # DEBUG
4148         if ($symbol !~ /:(Title|Long_Description|Short_Description|See_Also|Stability_Level|Include|Section_Id|Image)/) {
4149             $total++;
4150             if (exists ($AllDocumentedSymbols{$symbol})) {
4151                 $n_documented++;
4152                 if (exists ($AllIncompleteSymbols{$symbol})) {
4153                     $n_incomplete++;
4154                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4155                     #$buffer .= "\t0: ".$location;
4156                 }
4157             } elsif (exists $Deprecated{$symbol}) {
4158                 if (exists ($AllIncompleteSymbols{$symbol})) {
4159                     $n_incomplete++;
4160                     $buffer_deprecated .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4161                     #$buffer .= "\t1a: ".$location;
4162                 } else {
4163                     $buffer_deprecated .= $symbol . "\n";
4164                     #$buffer .= "\t1b: ".$location;
4165                 }
4166             } else {
4167                 if (exists ($AllIncompleteSymbols{$symbol})) {
4168                     $n_incomplete++;
4169                     $buffer .= $symbol . " (" . $AllIncompleteSymbols{$symbol} . ")\n";
4170                     #$buffer .= "\t2a: ".$location;
4171                 } else {
4172                     $buffer .= $symbol . "\n";
4173                     #$buffer .= "\t2b: ".$location;
4174                 }
4175             }
4176         } elsif ($symbol =~ /:(Long_Description|Short_Description)/) {
4177             $total++;
4178             #my $len1=(exists($SymbolDocs{$symbol}))?length($SymbolDocs{$symbol}):-1;
4179             #my $len2=(exists($AllDocumentedSymbols{$symbol}))?length($AllDocumentedSymbols{$symbol}):-1;
4180             #print "%%%% $symbol : $len1,$len2\n";
4181             if (((exists ($SymbolDocs{$symbol})) && (length ($SymbolDocs{$symbol}) > 0))
4182             || ((exists ($AllDocumentedSymbols{$symbol})) && (length ($AllDocumentedSymbols{$symbol}) > 0))) {
4183               $n_documented++;
4184             } else {
4185               # cut off the leading namespace ($TMPL_DIR)
4186               $symbol =~ m/^.*\/(.*)$/;
4187               $buffer_descriptions .= $1 . "\n";
4188             }
4189         }
4190     }
4192     $buffer .= "\n" . $buffer_deprecated . "\n" . $buffer_descriptions;
4194     if ($total == 0) {
4195       $percent = 100;
4196     } else {
4197       $percent = ($n_documented / $total) * 100.0;
4198     }
4200     printf UNDOCUMENTED "%.0f%% symbol docs coverage.\n", $percent;
4201     print UNDOCUMENTED "$n_documented symbols documented.\n";
4202     print UNDOCUMENTED "$n_incomplete symbols incomplete.\n";
4203     print UNDOCUMENTED ($total - $n_documented) . " not documented.\n\n\n";
4205     print UNDOCUMENTED $buffer;
4206     close (UNDOCUMENTED);
4208     return &UpdateFileIfChanged ($old_undocumented_file, $new_undocumented_file, 0);
4210     printf "%.0f%% symbol docs coverage", $percent;
4211     print "($n_documented symbols documented, $n_incomplete symbols incomplete, " . ($total - $n_documented) . " not documented)\n";
4212     print "See $MODULE-undocumented.txt for a list of missing docs.\nThe doc coverage percentage doesn't include intro sections.\n";
4216 #############################################################################
4217 # Function    : OutputUndeclaredSymbols
4218 # Description : Outputs symbols that are listed in the section file, but not
4219 #               declaration is found in the sources
4221 # Arguments   : none
4222 #############################################################################
4224 sub OutputUndeclaredSymbols {
4225     my $old_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.txt";
4226     my $new_undeclared_file = "$ROOT_DIR/$MODULE-undeclared.new";
4228     open(UNDECLARED, ">$new_undeclared_file")
4229         || die "Can't create $new_undeclared_file";
4231     if (%UndeclaredSymbols) {
4232         print UNDECLARED (join("\n", sort keys %UndeclaredSymbols));
4233         print UNDECLARED "\n";
4234         print "See $MODULE-undeclared.txt for the list of undeclared symbols.\n"
4235     }
4236     close(UNDECLARED);
4238     return &UpdateFileIfChanged ($old_undeclared_file, $new_undeclared_file, 0);
4241 #############################################################################
4242 # Function    : OutputUnusedSymbols
4243 # Description : Outputs symbols that are documented in comments, but not
4244 #               declared in the sources
4246 # Arguments   : none
4247 #############################################################################
4249 sub OutputUnusedSymbols {
4250     my $num_unused = 0;
4251     my $old_unused_file = "$ROOT_DIR/$MODULE-unused.txt";
4252     my $new_unused_file = "$ROOT_DIR/$MODULE-unused.new";
4254     open (UNUSED, ">$new_unused_file")
4255         || die "Can't open $new_unused_file";
4256     my ($symbol);
4257     foreach $symbol (sort keys (%Declarations)) {
4258         if (!defined ($DeclarationOutput{$symbol})) {
4259             print (UNUSED "$symbol\n");
4260             $num_unused++;
4261         }
4262     }
4263     foreach $symbol (sort (keys (%AllUnusedSymbols))) {
4264         print (UNUSED "$symbol(" . $AllUnusedSymbols{$symbol} . ")\n");
4265         $num_unused++;
4266     }
4267     close (UNUSED);
4268     if ($num_unused != 0) {
4269         &LogWarning ($old_unused_file, 1, "$num_unused unused declarations.".
4270             "They should be added to $MODULE-sections.txt in the appropriate place.");
4271     }
4273     return &UpdateFileIfChanged ($old_unused_file, $new_unused_file, 0);
4277 #############################################################################
4278 # Function    : OutputAllSymbols
4279 # Description : Outputs list of all symbols to a file
4281 # Arguments   : none
4282 #############################################################################
4284 sub OutputAllSymbols {
4285      my $n_documented = 0;
4286      my $total = 0;
4287      my $symbol;
4288      my $percent;
4289      my $msg;
4291      open (SYMBOLS, ">$ROOT_DIR/$MODULE-symbols.txt")
4292           || die "Can't create $ROOT_DIR/$MODULE-symbols.txt: $!";
4294      foreach $symbol (sort (keys (%AllSymbols))) {
4295           print SYMBOLS $symbol . "\n";
4296      }
4298      close (SYMBOLS);
4301 #############################################################################
4302 # Function    : OutputSymbolsWithoutSince
4303 # Description : Outputs list of all symbols without a since tag to a file
4305 # Arguments   : none
4306 #############################################################################
4308 sub OutputSymbolsWithoutSince {
4309      my $n_documented = 0;
4310      my $total = 0;
4311      my $symbol;
4312      my $percent;
4313      my $msg;
4315      open (SYMBOLS, ">$ROOT_DIR/$MODULE-nosince.txt")
4316           || die "Can't create $ROOT_DIR/$MODULE-nosince.txt: $!";
4318      foreach $symbol (sort (keys (%SourceSymbolDocs))) {
4319          if (!defined $Since{$symbol}) {
4320              print SYMBOLS $symbol . "\n";
4321          }
4322      }
4324      close (SYMBOLS);
4328 #############################################################################
4329 # Function    : MergeSourceDocumentation
4330 # Description : This merges documentation read from a source file into the
4331 #                documentation read in from a template file.
4333 #                Parameter descriptions override any in the template files.
4334 #                Function descriptions are placed before any description from
4335 #                the template files.
4337 # Arguments   : none
4338 #############################################################################
4340 sub MergeSourceDocumentation {
4341     my $symbol;
4342     my @Symbols;
4344     if (scalar %SymbolDocs) {
4345         @Symbols=keys (%SymbolDocs);
4346         #print "num existing entries: ".(scalar @Symbols)."\n";
4347         #print "  ",$Symbols[0], " ",$Symbols[1],"\n";
4348     }
4349     else {
4350         # filter scanned declarations, with what we suppress from -sections.txt
4351         my %tmp = ();
4352         foreach $symbol (keys (%Declarations)) {
4353             if (defined($KnownSymbols{$symbol}) && $KnownSymbols{$symbol} == 1) {
4354                 $tmp{$symbol}=1;
4355             }
4356         }
4357         # , add the rest from -sections.txt
4358         foreach $symbol (keys (%KnownSymbols)) {
4359             if ($KnownSymbols{$symbol} == 1) {
4360                 $tmp{$symbol}=1;
4361             }
4362         }
4363         # and add whats found in the source
4364         foreach $symbol (keys (%SourceSymbolDocs)) {
4365             $tmp{$symbol}=1;
4366         }
4367         @Symbols = keys (%tmp);
4368         #print "num source entries: ".(scalar @Symbols)."\n";
4369     }
4370     foreach $symbol (@Symbols) {
4371         $AllSymbols{$symbol} = 1;
4373         my $have_tmpl_docs = 0;
4375         ## see if the symbol is documented in template
4376         my $tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4377         my $check_tmpl_doc =$tmpl_doc;
4378         # remove all xml-tags and whitespaces
4379         $check_tmpl_doc =~ s/<.*?>//g;
4380         $check_tmpl_doc =~ s/\s//g;
4381         # anything left ?
4382         if ($check_tmpl_doc ne "") {
4383             $have_tmpl_docs = 1;
4384             #print "## [$check_tmpl_doc]\n";
4385         } else {
4386             # if the docs have just an empty para, don't merge that.
4387             $check_tmpl_doc = $tmpl_doc;
4388             $check_tmpl_doc =~ s/(\s|\n)//msg;
4389             if ($check_tmpl_doc eq "<para></para>") {
4390                $tmpl_doc = "";
4391             }
4392         }
4394         if (exists ($SourceSymbolDocs{$symbol})) {
4395             my $type = $DeclarationTypes {$symbol};
4397             #print "merging [$symbol] from source\n";
4399             my $item = "Parameter";
4400             if (defined ($type)) {
4401                 if ($type eq 'STRUCT') {
4402                     $item = "Field";
4403                 } elsif ($type eq 'ENUM') {
4404                     $item = "Value";
4405                 } elsif ($type eq 'UNION') {
4406                     $item = "Field";
4407                 }
4408             } else {
4409                 $type="SIGNAL";
4410             }
4412             my $src_doc = $SourceSymbolDocs{$symbol};
4413             # remove leading and training whitespaces
4414             $src_doc =~ s/^\s+//;
4415             $src_doc =~ s/\s+$//;
4417             # Don't output warnings for overridden titles as titles are
4418             # automatically generated in the -sections.txt file, and thus they
4419             # are often overridden.
4420             if ($have_tmpl_docs && $symbol !~ m/:Title$/) {
4421                 # check if content is different
4422                 if ($tmpl_doc ne $src_doc) {
4423                     #print "[$tmpl_doc] [$src_doc]\n";
4424                     &LogWarning ($SourceSymbolSourceFile{$symbol}, $SourceSymbolSourceLine{$symbol},
4425                         "Documentation in template ".$SymbolSourceFile{$symbol}.":".$SymbolSourceLine{$symbol}." for $symbol being overridden by inline comments.");
4426                 }
4427             }
4429             if ($src_doc ne "") {
4430                  $AllDocumentedSymbols{$symbol} = 1;
4431             }
4433             # Convert <!--PARAMETERS--> with any blank lines around it to
4434             # a </para> followed by <!--PARAMETERS--> followed by <para>.
4435             $src_doc =~ s%\n+\s*<!--PARAMETERS-->\s*\n+%\n</para>\n<!--PARAMETERS-->\n<para>\n%g;
4437             # Do not add <para> to nothing, it breaks missing docs checks.
4438             my $src_doc_para = "";
4439             if ($src_doc ne "") {
4440                 $src_doc_para = $src_doc;
4441             }
4443             if ($symbol =~ m/$TMPL_DIR\/.+:Long_Description/) {
4444                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4445             } elsif ($symbol =~ m/$TMPL_DIR\/.+:.+/) {
4446                 # For the title/summary/see also section docs we don't want to
4447                 # add any <para> tags.
4448                 $SymbolDocs{$symbol} = "$src_doc"
4449             } else {
4450                 $SymbolDocs{$symbol} = "$src_doc_para$tmpl_doc";
4451             }
4453             # merge parameters
4454             if ($symbol =~ m/.*::.*/) {
4455                 # For signals we prefer the param names from the source docs,
4456                 # since the ones from the templates are likely to contain the
4457                 # artificial argn names which are generated by gtkdoc-scangobj.
4458                 $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4459                 # FIXME: we need to check for empty docs here as well!
4460             } else {
4461                 # The templates contain the definitive parameter names and order,
4462                 # so we will not change that. We only override the actual text.
4463                 my $tmpl_params = $SymbolParams{$symbol};
4464                 if (!defined ($tmpl_params)) {
4465                     #print "No merge needed for $symbol\n";
4466                     $SymbolParams{$symbol} = $SourceSymbolParams{$symbol};
4467                     #  FIXME: we still like to get the number of params and merge
4468                     #  1) we would noticed that params have been removed/renamed
4469                     #  2) we would catch undocumented params
4470                     #  params are not (yet) exported in -decl.txt so that we
4471                     #  could easily grab them :/
4472                 } else {
4473                     my $params = $SourceSymbolParams{$symbol};
4474                     my $j;
4475                     #print "Merge needed for $symbol, tmpl_params: ",$#$tmpl_params,", source_params: ",$#$params," \n";
4476                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4477                         my $tmpl_param_name = $$tmpl_params[$j];
4479                         # Try to find the param in the source comment documentation.
4480                         my $found = 0;
4481                         my $k;
4482                         #print "  try merge param $tmpl_param_name\n";
4483                         for ($k = 0; $k <= $#$params; $k += $PARAM_FIELD_COUNT) {
4484                             my $param_name = $$params[$k];
4485                             my $param_desc = $$params[$k + 1];
4487                             #print "    test param  $param_name\n";
4488                             # We accept changes in case, since the Gnome source
4489                             # docs contain a lot of these.
4490                             if ("\L$param_name" eq "\L$tmpl_param_name") {
4491                                 $found = 1;
4493                                 # Override the description.
4494                                 $$tmpl_params[$j + 1] = $param_desc;
4496                                 # Set the name to "" to mark it as used.
4497                                 $$params[$k] = "";
4498                                 last;
4499                             }
4500                         }
4502                         # If it looks like the parameters are there, but not
4503                         # in the right place, try to explain a bit better.
4504                         if ((!$found) && ($src_doc =~ m/\@$tmpl_param_name:/)) {
4505                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4506                                 "Parameters for $symbol must start on the line immediately after the function or macro name.");
4507                         }
4508                     }
4510                     # Now we output a warning if parameters have been described which
4511                     # do not exist.
4512                     for ($j = 0; $j <= $#$params; $j += $PARAM_FIELD_COUNT) {
4513                         my $param_name = $$params[$j];
4514                         if ($param_name) {
4515                             # the template builder cannot detect if a macro returns
4516                             # a result or not
4517                             if(($type eq "MACRO") && ($param_name eq "Returns")) {
4518                                 # FIXME: do we need to add it then to tmpl_params[] ?
4519                                 my $num=$#$tmpl_params;
4520                                 #print "  adding Returns: to macro docs for $symbol.\n";
4521                                 $$tmpl_params[$num+1]="Returns";
4522                                 $$tmpl_params[$num+2]=$$params[$j+1];
4523                                 next;
4524                             }
4525                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4526                                 "$item described in source code comment block but does not exist. $type: $symbol $item: $param_name.");
4527                         }
4528                     }
4529                 }
4530             }
4531         } else {
4532             if ($have_tmpl_docs) {
4533                 $AllDocumentedSymbols{$symbol} = 1;
4534                 #print "merging [$symbol] from template\n";
4535             }
4536             else {
4537                 #print "[$symbol] undocumented\n";
4538             }
4539         }
4541         # if this symbol is documented, check if docs are complete
4542         $check_tmpl_doc = defined ($SymbolDocs{$symbol}) ? $SymbolDocs{$symbol} : "";
4543         # remove all xml-tags and whitespaces
4544         $check_tmpl_doc =~ s/<.*?>//g;
4545         $check_tmpl_doc =~ s/\s//g;
4546         if ($check_tmpl_doc ne "") {
4547             my $tmpl_params = $SymbolParams{$symbol};
4548             if (defined ($tmpl_params)) {
4549                 my $type = $DeclarationTypes {$symbol};
4551                 my $item = "Parameter";
4552                 if (defined ($type)) {
4553                     if ($type eq 'STRUCT') {
4554                         $item = "Field";
4555                     } elsif ($type eq 'ENUM') {
4556                         $item = "Value";
4557                     } elsif ($type eq 'UNION') {
4558                         $item = "Field";
4559                     }
4560                 } else {
4561                     $type="SIGNAL";
4562                 }
4564                 #print "Check param docs for $symbol, tmpl_params: ",$#$tmpl_params," entries, type=$type\n";
4566                 if ($#$tmpl_params > 0) {
4567                     my $j;
4568                     for ($j = 0; $j <= $#$tmpl_params; $j += $PARAM_FIELD_COUNT) {
4569                         # Output a warning if the parameter is empty and
4570                         # remember for stats.
4571                         my $tmpl_param_name = $$tmpl_params[$j];
4572                         my $tmpl_param_desc = $$tmpl_params[$j + 1];
4573                         if ($tmpl_param_name ne "void" && $tmpl_param_desc !~ m/\S/) {
4574                             if (exists ($AllIncompleteSymbols{$symbol})) {
4575                                 $AllIncompleteSymbols{$symbol}.=", ".$tmpl_param_name;
4576                             } else {
4577                                 $AllIncompleteSymbols{$symbol}=$tmpl_param_name;
4578                             }
4579                             &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4580                                 "$item description for $symbol"."::"."$tmpl_param_name is missing in source code comment block.");
4581                         }
4582                     }
4583                 }
4584                 else {
4585                     if ($#$tmpl_params == 0) {
4586                         $AllIncompleteSymbols{$symbol}="<items>";
4587                         &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
4588                             "$item descriptions for $symbol are missing in source code comment block.");
4589                     }
4590                     # $#$tmpl_params==-1 means we don't know about parameters
4591                     # this unfortunately does not tell if there should be some
4592                 }
4593             }
4594         }
4595    }
4596    #print "num doc entries: ".(scalar %SymbolDocs)."\n";
4599 #############################################################################
4600 # Function    : IsEmptyDoc
4601 # Description : Check if a doc-string is empty. Its also regarded as empty if
4602 #               it only consist of whitespace or e.g. FIXME.
4603 # Arguments   : the doc-string
4604 #############################################################################
4605 sub IsEmptyDoc {
4606     my ($doc) = @_;
4608     if ($doc =~ /^\s*$/) {
4609         return 1;
4610     }
4612     if ($doc =~ /^\s*<para>\s*(FIXME)?\s*<\/para>\s*$/) {
4613         return 1;
4614     }
4616     return 0;
4619 #############################################################################
4620 # Function    : ConvertMarkDown
4621 # Description : Converts mark down syntax to the respective docbook.
4622 #               http://de.wikipedia.org/wiki/Markdown
4623 #               Inspired by the design of ParseDown
4624 #               http://parsedown.org/
4625 #               Copyright (c) 2013 Emanuil Rusev, erusev.com
4626 # Arguments   : the symbol name, the doc-string
4627 #############################################################################
4629 sub ConvertMarkDown {
4630     my ($symbol, $text) = @_;
4632     $text = &MarkDownParse ($text, $symbol);
4634     return $text
4637 # SUPPORTED MARKDOWN
4638 # ==================
4640 # Atx-style Headers
4641 # -----------------
4643 # # Header 1
4645 # ## Header 2 ##
4647 # Setext-style Headers
4648 # --------------------
4650 # Header 1
4651 # ========
4653 # Header 2
4654 # --------
4656 # Ordered (unnested) Lists
4657 # ------------------------
4659 # 1. item 1
4661 # 1. item 2 with loooong
4662 #    description
4664 # 3. item 3
4666 # Note: we require a blank line above the list items
4669 # TODO(ensonic): it would be nice to add id parameters to the refsect2 elements
4671 sub MarkDownParseBlocks {
4672   my ($linesref, $symbol, $context) = @_;
4673   my $line;
4674   my @md_blocks = ();
4675   my $md_block = { type => "" };
4677  OUTER: foreach $line (@$linesref) {
4678     my $first_char = substr ($line, 0, 1);
4679     my $deindented_line;
4681     if ($md_block->{"type"} eq "markup") {
4682       if (!$md_block->{"closed"}) {
4683         if (index ($line, $md_block->{"start"}) != -1) {
4684           $md_block->{"depth"}++;
4685         }
4686         if (index ($line, $md_block->{"end"}) != -1) {
4687           if ($md_block->{"depth"} > 0) {
4688             $md_block->{"depth"}--;
4689           } else {
4690             $md_block->{"closed"} = 1;
4691           }
4692         }
4693         $md_block->{"text"} .= "\n" . $line;
4694         next OUTER;
4695       }
4696     }
4698     $deindented_line = $line;
4699     $deindented_line =~ s/^\s+//;
4701     if ($md_block->{"type"} eq "heading") {
4702       # a heading is ended by any level less than or equal
4703       if ($md_block->{"level"} == 1) {
4704         if ($line =~ /^={4,}[ \t]*$/) {
4705           my $text = pop $md_block->{"lines"};
4706           $md_block->{"interrupted"} = 0;
4707           push @md_blocks, $md_block;
4709           $md_block = { type => "heading",
4710                         text => $text,
4711                         lines => [],
4712                         level => 1 };
4713           next OUTER;
4714         } elsif ($line =~ /^[#][ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4715           $md_block->{"interrupted"} = 0;
4716           push @md_blocks, $md_block;
4718           $md_block = { type => "heading",
4719                         text => $1,
4720                         id => $2,
4721                         lines => [],
4722                         level => 1 };
4723           next OUTER;
4724         } else {
4725           # push lines into the block until the end is reached
4726           push $md_block->{"lines"}, $line;
4727           next OUTER;
4728         }
4729       } else {
4730         if ($line =~ /^[=]{4,}[ \t]*$/) {
4731           my $text = pop $md_block->{"lines"};
4732           $md_block->{"interrupted"} = 0;
4733           push @md_blocks, $md_block;
4735           $md_block = { type => "heading",
4736                         text => $text,
4737                         lines => [],
4738                         level => 1 };
4739           next OUTER;
4740         } elsif ($line =~ /^[-]{4,}[ \t]*$/) {
4741           my $text = pop $md_block->{"lines"};
4742           $md_block->{"interrupted"} = 0;
4743           push @md_blocks, $md_block;
4745           $md_block = { type => "heading",
4746                         text => $text,
4747                         lines => [],
4748                         level => 2 };
4749           next OUTER;
4750         } elsif ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4751           $md_block->{"interrupted"} = 0;
4752           push @md_blocks, $md_block;
4754           $md_block = { type => "heading",
4755                         text => $2,
4756                         id => $3,
4757                         lines => [],
4758                         level => length($1) };
4759           next OUTER;
4760         } else {
4761           # push lines into the block until the end is reached
4762           push $md_block->{"lines"}, $line;
4763           next OUTER;
4764         }
4765       }
4766     } elsif ($md_block->{"type"} eq "code") {
4767       if ($line =~ /^[ \t]*\]\|/) {
4768         push @md_blocks, $md_block;
4769         $md_block = { type => "paragraph",
4770                       text => "",
4771                       lines => [] };
4772       } else {
4773         push $md_block->{"lines"}, $line;
4774       }
4775       next OUTER;
4776     }
4778     if ($deindented_line eq "") {
4779       $md_block->{"interrupted"} = 1;
4780       next;
4781     }
4783     if ($md_block->{"type"} eq "quote") {
4784       if (!$md_block->{"interrupted"}) {
4785         $line =~ s/^[ ]*>[ ]?//;
4786         push $md_block->{"lines"}, $line;
4787         next OUTER;
4788       }
4789     } elsif ($md_block->{"type"} eq "li") {
4790       my $marker = $md_block->{"marker"};
4791       if ($line =~ /^([ ]{0,3})($marker)[ ](.*)/) {
4792         my $indentation = $1;
4793         if ($md_block->{"indentation"} ne $indentation) {
4794           push $md_block->{"lines"}, $line;
4795         } else {
4796           my $lines = $3;
4797           my $ordered = $md_block->{"ordered"};
4798           $lines =~ s/^[ ]{0,4}//;
4799           $md_block->{"last"} = 0;
4800           push @md_blocks, $md_block;
4801           $md_block = { type => "li",
4802                         ordered => $ordered,
4803                         indentation => $indentation,
4804                         marker => $marker,
4805                         first => 0,
4806                         last => 1,
4807                         lines => [ $lines ] };
4808         }
4809         next OUTER;
4810       }
4812       if ($md_block->{"interrupted"}) {
4813         if ($first_char eq " ") {
4814           push $md_block->{"lines"}, "";
4815           $line =~ s/^[ ]{0,4}//;
4816           push $md_block->{"lines"}, $line;
4817           $md_block->{"interrupted"} = 0;
4818           next OUTER;
4819         }
4820       } else {
4821         $line =~ s/^[ ]{0,4}//;
4822         push $md_block->{"lines"}, $line;
4823         next OUTER;
4824       }
4825     }
4827     # indentation sensitive types
4829     if ($line =~ /^([#]{1,2})[ \t]+(.+?)[ \t]*[#]*[ \t]*(?:{#([^}]+)})?[ \t]*$/) {
4830       # atx heading (#)
4831       push @md_blocks, $md_block;
4833       $md_block = { type => "heading",
4834                     text => $2,
4835                     id => $3,
4836                     lines => [],
4837                     level => length($1) };
4839       next OUTER;
4840     } elsif ($line =~ /^={4,}[ \t]*$/) {
4841       # setext heading (====)
4843       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4844         push @md_blocks, $md_block;
4845         $md_block->{"type"} = "heading";
4846         $md_block->{"lines"} = [];
4847         $md_block->{"level"} = 1;
4848       }
4850       next OUTER;
4851     } elsif ($line =~ /^-{4,}[ \t]*$/) {
4852       # setext heading (-----)
4854       if ($md_block->{"type"} eq "paragraph" && $md_block->{"interrupted"}) {
4855         push @md_blocks, $md_block;
4856         $md_block->{"type"} = "heading";
4857         $md_block->{"lines"} = [];
4858         $md_block->{"level"} = 2;
4859       }
4861       next OUTER;
4862     } elsif ($line =~ /^[ \t]*\|\[[ ]*(?:<!-- language="([^"]+?)" -->)?/) {
4863       # code
4864       $md_block->{"interrupted"} = 1;
4865       push @md_blocks, $md_block;
4866       $md_block = { type => "code",
4867                     language => $1,
4868                     lines => [] };
4869       next OUTER;
4870     }
4872     # indentation insensitive types
4874     if ($line =~ /^[ ]*<!DOCTYPE/) {
4875       push @md_blocks, $md_block;
4877       $md_block = { type   => "markup",
4878                     text   => $deindented_line,
4879                     start  => "<",
4880                     end    => ">",
4881                     closed => 0,
4882                     depth  => 0 };
4884     } elsif ($line =~ /^[ ]*<\??(\w+)[^>]*([\/\?])?[ \t]*>/) {
4885       # markup, including <?xml version="1.0"?>
4886       my $tag = $1;
4887       my $is_self_closing = defined($2);
4888       # FIXME: why do we need to skip https? here, if we generalize this to all
4889       # uri schemes we get parsing errors
4890       if (! $MD_TEXT_LEVEL_ELEMENTS{$tag} && $tag !~ /^https?/) {
4891         push @md_blocks, $md_block;
4893         if ($is_self_closing) {
4894           $md_block = { type => "self-closing tag",
4895                         text => $deindented_line };
4896           $is_self_closing = 0;
4897           next OUTER;
4898         }
4900         $md_block = { type   => "markup",
4901                       text   => $deindented_line,
4902                       start  => "<" . $tag . ">",
4903                       end    => "</" . $tag . ">",
4904                       closed => 0,
4905                       depth  => 0 };
4906         if ($deindented_line =~ /<\/$tag>/) {
4907           $md_block->{"closed"} = 1;
4908         }
4909         next OUTER;
4910       }
4911     } elsif ($line =~ /^([ ]*)[*+-][ ](.*)/) {
4912       # li
4913       push @md_blocks, $md_block;
4914       my $lines = $2;
4915       my $indentation = $1;
4916       $lines =~ s/^[ ]{0,4}//;
4917       $md_block = { type => "li",
4918                     ordered => 0,
4919                     indentation => $indentation,
4920                     marker => "[*+-]",
4921                     first => 1,
4922                     last => 1,
4923                     lines => [ $lines ] };
4924       next OUTER;
4925     } elsif ($line =~ /^[ ]*>[ ]?(.*)/) {
4926       push @md_blocks, $md_block;
4927       $md_block = { type => "quote",
4928                     lines => [ $1 ] };
4929       next OUTER;
4930     }
4932     # list item
4934     if ($line =~ /^([ ]{0,4})\d+[.][ ]+(.*)/) {
4935       push @md_blocks, $md_block;
4936       my $lines = $2;
4937       my $indentation = $1;
4938       $lines =~ s/^[ ]{0,4}//;
4940       $md_block = { type => "li",
4941                     ordered => 1,
4942                     indentation => $indentation,
4943                     marker => "\\d+[.]",
4944                     first => 1,
4945                     last => 1,
4946                     lines => [ $lines ] };
4948       next;
4949     }
4951     # paragraph
4952     if ($md_block->{"type"} eq "paragraph") {
4953       if ($md_block->{"interrupted"}) {
4954         push @md_blocks, $md_block;
4955         $md_block = { type => "paragraph",
4956                       interrupted => 0,
4957                       text => $line };
4958       } else {
4959         $md_block->{"text"} .= "\n" . $line;
4960       }
4961     } else {
4962       push @md_blocks, $md_block;
4963       $md_block = { type => "paragraph",
4964                     text => $line };
4965     }
4966   }
4968   push @md_blocks, $md_block;
4970   shift @md_blocks;
4972   return @md_blocks;
4975 sub MarkDownParseSpanElementsInner {
4976   my ($text, $markersref) = @_;
4977   my $markup = "";
4978   my %markers = map { $_ => 1 } @$markersref;
4980   while ($text ne "") {
4981     my $closest_marker = "";
4982     my $closest_marker_index = 0;
4983     my $closest_marker_position = -1;
4984     my $text_marker = "";
4985     my $i = 0;
4986     my $offset = 0;
4987     my @markers_rest;
4988     my $marker;
4989     my $use;
4991     while ( ($marker, $use) = each %markers ) {
4992       my $marker_position;
4994       if (!$use) {
4995         next;
4996       }
4998       $marker_position = index ($text, $marker);
5000       if ($marker_position < 0) {
5001         $markers{$marker} = 0;
5002         next;
5003       }
5005       if ($closest_marker eq "" || $marker_position < $closest_marker_position) {
5006         $closest_marker = $marker;
5007         $closest_marker_index = $i;
5008         $closest_marker_position = $marker_position;
5009       }
5010     }
5012     if ($closest_marker_position >= 0) {
5013       $text_marker = substr ($text, $closest_marker_position);
5014     }
5016     if ($text_marker eq "") {
5017       $markup .= $text;
5018       $text = "";
5019       next; # last
5020     }
5022     $markup .= substr ($text, 0, $closest_marker_position);
5023     $text = substr ($text, $closest_marker_position);
5024     @markers_rest = map { $markers{$_} ? ($_ eq $closest_marker ? () : $_) : () } keys %markers;
5026     if ($closest_marker eq "![" || $closest_marker eq "[") {
5027       my %element;
5029       if (index ($text, "]") && $text =~ /\[((?:[^][]|(?R))*)\]/) {
5030         my $remaining_text;
5032         %element = ( "!" => (substr ($text, 0, 1) eq "!"),
5033                      "a" => $1 );
5035         $offset = length ($&);
5036         if ($element{"!"}) {
5037           $offset++;
5038         }
5040         $remaining_text = substr ($text, $offset);
5041         if ($remaining_text =~ /^\([ ]*([^)'"]*?)(?:[ ]+['"](.+?)['"])?[ ]*\)/) {
5042           $element{"»"} = $1;
5043           if (defined ($2)) {
5044             $element{"#"} = $2;
5045           }
5046           $offset += length ($&);
5047         } elsif ($remaining_text =~ /^\s*\[([^\]<]*?)\]/) {
5048           $element{"ref"} = $1;
5049           $offset += length ($&);
5050         } else {
5051           undef %element;
5052         }
5053       }
5055       if (%element) {
5056         if ($element{"»"}) {
5057           $element{"»"} =~ s/&/&amp;/g;
5058           $element{"»"} =~ s/</&lt;/g;
5059         }
5060         if ($element{"!"}) {
5061           $markup .= "<inlinemediaobject><imageobject><imagedata fileref=\"" . $element{"»"} . "\"></imagedata></imageobject>";
5063           if (defined ($element{"a"})) {
5064             $markup .= "<textobject><phrase>" . $element{"a"} . "</phrase></textobject>";
5065           }
5067           $markup .= "</inlinemediaobject>";
5068         } elsif ($element{"ref"}) {
5069           $element{"a"} = &MarkDownParseSpanElementsInner ($element{"a"}, \@markers_rest);
5070           $markup .= "<link linkend=\"" . $element{"ref"} . "\"";
5072           if (defined ($element{"#"})) {
5073             # title attribute not supported
5074           }
5076           $markup .= ">" . $element{"a"} . "</link>";
5077         } else {
5078           $element{"a"} = &MarkDownParseSpanElementsInner ($element{"a"}, \@markers_rest);
5079           $markup .= "<ulink url=\"" . $element{"»"} . "\"";
5081           if (defined ($element{"#"})) {
5082             # title attribute not supported
5083           }
5085           $markup .= ">" . $element{"a"} . "</ulink>";
5086         }
5087       } else {
5088         $markup .= $closest_marker;
5089         if ($closest_marker eq "![") {
5090           $offset = 2;
5091         } else {
5092           $offset = 1;
5093         }
5094       }
5095     } elsif ($closest_marker eq "<") {
5096       if ($text =~ /^<(https?:[\/]{2}[^\s]+?)>/i) {
5097         my $element_url = $1;
5098         $element_url =~ s/&/&amp;/g;
5099         $element_url =~ s/</&lt;/g;
5101         $markup .= "<ulink url=\"" . $element_url . "\">" . $element_url . "</ulink>";
5102         $offset = length ($&);
5103       } elsif ($text =~ /^<([A-Za-z0-9._-]+?@[A-Za-z0-9._-]+?)>/) {
5104         $markup .= "<ulink url=\"mailto:" . $1 . "\">" . $1 . "</ulink>";
5105         $offset = length ($&);
5106       } elsif ($text =~ /^<[^>]+?>/) {
5107         $markup .= $&;
5108         $offset = length ($&);
5109       } else {
5110         $markup .= "&lt;";
5111         $offset = 1;
5112       }
5113     } elsif ($closest_marker eq "\\") {
5114       my $special_char = substr ($text, 1, 1);
5115       if ($MD_ESCAPABLE_CHARS{$special_char} ||
5116           $MD_GTK_ESCAPABLE_CHARS{$special_char}) {
5117         $markup .= $special_char;
5118         $offset = 2;
5119       } else {
5120         $markup .= "\\";
5121         $offset = 1;
5122       }
5123     } elsif ($closest_marker eq "`") {
5124       if ($text =~ /^(`+)([^`]+?)\1(?!`)/) {
5125         my $element_text = $2;
5126         $markup .= "<literal>" . $element_text . "</literal>";
5127         $offset = length ($&);
5128       } else {
5129         $markup .= "`";
5130         $offset = 1;
5131       }
5132     } elsif ($closest_marker eq "@") {
5133       # Convert '@param()'
5134       # FIXME: we could make those also links ($symbol.$2), but that would be less
5135       # useful as the link target is a few lines up or down
5136       if ($text =~ /^(\A|[^\\])\@(\w+((\.|->)\w+)*)\s*\(\)/) {
5137         $markup .= $1 . "<parameter>" . $2 . "()</parameter>\n";
5138         $offset = length ($&);
5139       } elsif ($text =~ /^(\A|[^\\])\@(\w+((\.|->)\w+)*)/) {
5140         # Convert '@param', but not '\@param'.
5141         $markup .= $1 . "<parameter>" . $2 . "</parameter>\n";
5142         $offset = length ($&);
5143       } elsif ($text =~ /^\\\@/) {
5144         $markup .= "\@";
5145         $offset = length ($&);
5146       } else {
5147         $markup .= "@";
5148         $offset = 1;
5149       }
5150     } elsif ($closest_marker eq "#") {
5151       if ($text =~ /^(\A|[^\\])#([\w\-:\.]+[\w]+)\s*\(\)/) {
5152         # handle #Object.func()
5153         $markup .= $1 . &MakeXRef ($2, &tagify ($2 . "()", "function"));
5154         $offset = length ($&);
5155       } elsif ($text =~ /^(\A|[^\\])#([\w\-:\.]+[\w]+)/) {
5156         # Convert '#symbol', but not '\#symbol'.
5157         $markup .= $1 . &MakeHashXRef ($2, "type");
5158         $offset = length ($&);
5159       } elsif ($text =~ /^\\#/) {
5160         $markup .= "#";
5161         $offset = length ($&);
5162       } else {
5163         $markup .= "#";
5164         $offset = 1;
5165       }
5166     } elsif ($closest_marker eq "%") {
5167       if ($text =~ /^(\A|[^\\])\%(-?\w+)/) {
5168         # Convert '%constant', but not '\%constant'.
5169         # Also allow negative numbers, e.g. %-1.
5170         $markup .= $1 . &MakeXRef ($2, &tagify ($2, "literal"));
5171         $offset = length ($&);
5172       } elsif ($text =~ /^\\%/) {
5173         $markup .= "\%";
5174         $offset = length ($&);
5175       } else {
5176         $markup .= "%";
5177         $offset = 1;
5178       }
5179     }
5181     if ($offset > 0) {
5182       $text = substr ($text, $offset);
5183     }
5184   }
5186   return $markup;
5189 sub MarkDownParseSpanElements {
5190   my ($text) = @_;
5191   my @markers = ( "\\", "<", "![", "[", "`", "%", "#", "@" );
5193   $text = &MarkDownParseSpanElementsInner ($text, \@markers);
5195   # Convert 'function()' or 'macro()'.
5196   # if there is abc_*_def() we don't want to make a link to _def()
5197   # FIXME: also handle abc(def(....)) : but that would need to be done recursively :/
5198   $text =~ s/([^\*.\w])(\w+)\s*\(\)/$1.&MakeXRef($2, &tagify($2 . "()", "function"));/eg;
5200   return $text;
5203 sub ReplaceEntities {
5204   my ($text, $symbol) = @_;
5205   my $warn = "";
5206   my @entities = ( [ "&lt;", "<" ],
5207                    [ "&gt;", ">" ],
5208                    [ "&ast;", "*" ],
5209                    [ "&num;", "#" ],
5210                    [ "&percnt;", "%"],
5211                    [ "&colon;", ":" ],
5212                    [ "&quot;", "\"" ],
5213                    [ "&apos;", "'" ],
5214                    [ "&nbsp;", " " ],
5215                    [ "&amp;", "&" ] ); # Do this last, or the others get messed up.
5216   my $i;
5218   # Expand entities in <programlisting> even inside CDATA since
5219   # we changed the definition of |[ to add CDATA
5220   for ($i = 0; $i <= $#entities; $i++) {
5221     if ($text =~ s/$entities[$i][0]/$entities[$i][1]/g) {
5222       # don't warn about &ast; since it is expected to be present
5223       # for C-style comments
5224       if ($entities[$i][0] ne "&ast;") {
5225         $warn .= "$entities[$i][0] ";
5226       }
5227     }
5228   }
5230   if ($warn ne "") {
5231     chomp $warn;
5232     &LogWarning (&GetSymbolSourceFile ($symbol), &GetSymbolSourceLine($symbol),
5233                  "Deprecated entities found in documentation for $symbol: $warn");
5234   }
5236   return $text;
5239 sub MarkDownOutputDocBook {
5240   my ($blocksref, $symbol, $context) = @_;
5241   my $output = "";
5242   my $block;
5243   my @blocks = @$blocksref;
5245   foreach $block (@blocks) {
5246     my $text;
5247     my $title;
5249     if ($block->{"type"} eq "paragraph") {
5250       $text = &MarkDownParseSpanElements ($block->{"text"});
5251       if ($context eq "li" && $output eq "") {
5252         if ($block->{"interrupted"}) {
5253           $output .= "\n"."<para>".$text."</para>"."\n";
5254         } else {
5255           $output .= "<para>".$text."</para>";
5256           if ($#blocks > 0) {
5257             $output .= "\n";
5258           }
5259         }
5260       } else {
5261         $output .= "<para>".$text."</para>"."\n";
5262       }
5264     } elsif ($block->{"type"} eq "heading") {
5265       my $tag;
5267       $title = &MarkDownParseSpanElements ($block->{"text"});
5269       if ($block->{"level"} == 1) {
5270         $tag = "refsect2";
5271       } else {
5272         $tag = "refsect3";
5273       }
5275       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "heading");
5276       if (defined ($block->{"id"})) {
5277         $output .= "<" . $tag . " id=\"" . $block->{"id"} . "\">";
5278       } else {
5279         $output .= "<" . $tag . ">";
5280       }
5282       $output .= "<title>" . $title . "</title>" . $text . "</" . $tag . ">\n";
5283     } elsif ($block->{"type"} eq "li") {
5284       my $tag = "itemizedlist";
5286       if ($block->{"first"}) {
5287         if ($block->{"ordered"}) {
5288           $tag = "orderedlist";
5289         }
5290         $output .= "<".$tag.">\n";
5291       }
5293       if ($block->{"interrupted"}) {
5294         push $block->{"lines"}, "";
5295       }
5297       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "li");
5298       $output .= "<listitem>".$text."</listitem>\n";
5299       if ($block->{"last"}) {
5300         if ($block->{"ordered"}) {
5301           $tag = "orderedlist";
5302         }
5303         $output .= "</".$tag.">\n";
5304       }
5305     } elsif ($block->{"type"} eq "quote") {
5306       $text = &MarkDownParseLines ($block->{"lines"}, $symbol, "quote");
5307       $output .= "<blockquote>\n" . $text . "</blockquote>\n";
5308     } elsif ($block->{"type"} eq "code") {
5309       if ($block->{"language"}) {
5310         $output .= "<informalexample><programlisting language=\"" . $block->{"language"} . "\"><![CDATA[\n";
5311       } else {
5312         $output .= "<informalexample><programlisting><![CDATA[\n";
5313       }
5314       foreach (@{$block->{"lines"}}) {
5315         $output .= &ReplaceEntities ($_, $symbol) . "\n";
5316       }
5317       $output .= "]]></programlisting></informalexample>\n";
5318     } elsif ($block->{"type"} eq "markup") {
5319       $text = &ExpandAbbreviations($symbol, $block->{"text"});
5320       $output .= $text."\n";
5321     } else {
5322       $output .= $block->{"text"}."\n";
5323     }
5324   }
5326   return $output;
5329 sub MarkDownParseLines {
5330   my ($linesref, $symbol, $context) = @_;
5331   my $output;
5332   my @lines = @$linesref;
5333   my @blocks;
5335   @blocks = &MarkDownParseBlocks (\@lines, $symbol, $context);
5336   $output = &MarkDownOutputDocBook (\@blocks, $symbol, $context);
5338   return $output;
5341 sub MarkDownParse {
5342   my ($text, $symbol) = @_;
5343   my @lines;
5345   # take out some variability in line endings
5346   $text =~ s%\r\n%\n%g;
5347   $text =~ s%\r%\n%g;
5349   # split lines
5350   @lines = split("\n", $text);
5351   $text = MarkDownParseLines(\@lines, $symbol, "");
5353   return $text;
5356 #############################################################################
5357 # LIBRARY FUNCTIONS -        These functions are used in both gtkdoc-mkdb and
5358 #                        gtkdoc-mktmpl and should eventually be moved to a
5359 #                        separate library.
5360 #############################################################################
5362 #############################################################################
5363 # Function    : ReadDeclarationsFile
5364 # Description : This reads in a file containing the function/macro/enum etc.
5365 #                declarations.
5367 #                Note that in some cases there are several declarations with
5368 #                the same name, e.g. for conditional macros. In this case we
5369 #                set a flag in the %DeclarationConditional hash so the
5370 #                declaration is not shown in the docs.
5372 #                If a macro and a function have the same name, e.g. for
5373 #                gtk_object_ref, the function declaration takes precedence.
5375 #                Some opaque structs are just declared with 'typedef struct
5376 #                _name name;' in which case the declaration may be empty.
5377 #                The structure may have been found later in the header, so
5378 #                that overrides the empty declaration.
5380 # Arguments   : $file - the declarations file to read
5381 #                $override - if declarations in this file should override
5382 #                        any current declaration.
5383 #############################################################################
5385 sub ReadDeclarationsFile {
5386     my ($file, $override) = @_;
5388     if ($override == 0) {
5389         %Declarations = ();
5390         %DeclarationTypes = ();
5391         %DeclarationConditional = ();
5392         %DeclarationOutput = ();
5393     }
5395     open (INPUT, $file)
5396         || die "Can't open $file: $!";
5397     my $declaration_type = "";
5398     my $declaration_name;
5399     my $declaration;
5400     my $is_deprecated = 0;
5401     while (<INPUT>) {
5402         if (!$declaration_type) {
5403             if (m/^<([^>]+)>/) {
5404                 $declaration_type = $1;
5405                 $declaration_name = "";
5406                 #print "Found declaration: $declaration_type\n";
5407                 $declaration = "";
5408             }
5409         } else {
5410             if (m%^<NAME>(.*)</NAME>%) {
5411                 $declaration_name = $1;
5412             } elsif (m%^<DEPRECATED/>%) {
5413                 $is_deprecated = 1;
5414             } elsif (m%^</$declaration_type>%) {
5415                 #print "Found end of declaration: $declaration_name\n";
5416                 # Check that the declaration has a name
5417                 if ($declaration_name eq "") {
5418                     print "ERROR: $declaration_type has no name $file:$.\n";
5419                 }
5421                 # If the declaration is an empty typedef struct _XXX XXX
5422                 # set the flag to indicate the struct has a typedef.
5423                 if ($declaration_type eq 'STRUCT'
5424                     && $declaration =~ m/^\s*$/) {
5425                     #print "Struct has typedef: $declaration_name\n";
5426                     $StructHasTypedef{$declaration_name} = 1;
5427                 }
5429                 # Check if the symbol is already defined.
5430                 if (defined ($Declarations{$declaration_name})
5431                     && $override == 0) {
5432                     # Function declarations take precedence.
5433                     if ($DeclarationTypes{$declaration_name} eq 'FUNCTION') {
5434                         # Ignore it.
5435                     } elsif ($declaration_type eq 'FUNCTION') {
5436                         if ($is_deprecated) {
5437                             $Deprecated{$declaration_name} = "";
5438                         }
5439                         $Declarations{$declaration_name} = $declaration;
5440                         $DeclarationTypes{$declaration_name} = $declaration_type;
5441                     } elsif ($DeclarationTypes{$declaration_name}
5442                               eq $declaration_type) {
5443                         # If the existing declaration is empty, or is just a
5444                         # forward declaration of a struct, override it.
5445                         if ($declaration_type eq 'STRUCT') {
5446                             if ($Declarations{$declaration_name} =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5447                                 if ($is_deprecated) {
5448                                     $Deprecated{$declaration_name} = "";
5449                                 }
5450                                 $Declarations{$declaration_name} = $declaration;
5451                             } elsif ($declaration =~ m/^\s*(struct\s+\w+\s*;)?\s*$/) {
5452                                 # Ignore an empty or forward declaration.
5453                             } else {
5454                                 &LogWarning ($file, $., "Structure $declaration_name has multiple definitions.");
5455                             }
5456                         } else {
5457                             # set flag in %DeclarationConditional hash for
5458                             # multiply defined macros/typedefs.
5459                             $DeclarationConditional{$declaration_name} = 1;
5460                         }
5461                     } else {
5462                         &LogWarning ($file, $., "$declaration_name has multiple definitions.");
5463                     }
5464                 } else {
5465                     if ($is_deprecated) {
5466                         $Deprecated{$declaration_name} = "";
5467                     }
5468                     $Declarations{$declaration_name} = $declaration;
5469                     $DeclarationTypes{$declaration_name} = $declaration_type;
5470                 }
5472                 $declaration_type = "";
5473                 $is_deprecated = 0;
5474             } else {
5475                 $declaration .= $_;
5476             }
5477         }
5478     }
5479     close (INPUT);
5483 #############################################################################
5484 # Function    : ReadSignalsFile
5485 # Description : This reads in an existing file which contains information on
5486 #                all GTK signals. It creates the arrays @SignalNames and
5487 #                @SignalPrototypes containing info on the signals. The first
5488 #                line of the SignalPrototype is the return type of the signal
5489 #                handler. The remaining lines are the parameters passed to it.
5490 #                The last parameter, "gpointer user_data" is always the same
5491 #                so is not included.
5492 # Arguments   : $file - the file containing the signal handler prototype
5493 #                        information.
5494 #############################################################################
5496 sub ReadSignalsFile {
5497     my ($file) = @_;
5499     my $in_signal = 0;
5500     my $signal_object;
5501     my $signal_name;
5502     my $signal_returns;
5503     my $signal_flags;
5504     my $signal_prototype;
5506     # Reset the signal info.
5507     @SignalObjects = ();
5508     @SignalNames = ();
5509     @SignalReturns = ();
5510     @SignalFlags = ();
5511     @SignalPrototypes = ();
5513     if (! -f $file) {
5514         return;
5515     }
5516     if (!open (INPUT, $file)) {
5517         warn "Can't open $file - skipping signals\n";
5518         return;
5519     }
5520     while (<INPUT>) {
5521         if (!$in_signal) {
5522             if (m/^<SIGNAL>/) {
5523                 $in_signal = 1;
5524                 $signal_object = "";
5525                 $signal_name = "";
5526                 $signal_returns = "";
5527                 $signal_prototype = "";
5528             }
5529         } else {
5530             if (m/^<NAME>(.*)<\/NAME>/) {
5531                 $signal_name = $1;
5532                 if ($signal_name =~ m/^(.*)::(.*)$/) {
5533                     $signal_object = $1;
5534                     ($signal_name = $2) =~ s/_/-/g;
5535                     #print "Found signal: $signal_name\n";
5536                 } else {
5537                     &LogWarning ($file, $., "Invalid signal name: $signal_name.");
5538                 }
5539             } elsif (m/^<RETURNS>(.*)<\/RETURNS>/) {
5540                 $signal_returns = $1;
5541             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5542                 $signal_flags = $1;
5543             } elsif (m%^</SIGNAL>%) {
5544                 #print "Found end of signal: ${signal_object}::${signal_name}\nReturns: ${signal_returns}\n${signal_prototype}";
5545                 push (@SignalObjects, $signal_object);
5546                 push (@SignalNames, $signal_name);
5547                 push (@SignalReturns, $signal_returns);
5548                 push (@SignalFlags, $signal_flags);
5549                 push (@SignalPrototypes, $signal_prototype);
5550                 $in_signal = 0;
5551             } else {
5552                 $signal_prototype .= $_;
5553             }
5554         }
5555     }
5556     close (INPUT);
5560 #############################################################################
5561 # Function    : ReadTemplateFile
5562 # Description : This reads in the manually-edited documentation file
5563 #               corresponding to the file currently being created, so we can
5564 #               insert the documentation at the appropriate places.
5565 #               It outputs %SymbolTypes, %SymbolDocs and %SymbolParams, which
5566 #               is a hash of arrays.
5567 #               NOTE: This function is duplicated in gtkdoc-mktmpl (but
5568 #               slightly different).
5569 # Arguments   : $docsfile - the template file to read in.
5570 #               $skip_unused_params - 1 if the unused parameters should be
5571 #                 skipped.
5572 #############################################################################
5574 sub ReadTemplateFile {
5575     my ($docsfile, $skip_unused_params) = @_;
5577     my $template = "$docsfile.sgml";
5578     if (! -f $template) {
5579         #print "File doesn't exist: $template\n";
5580         return 0;
5581     }
5583     # start with empty hashes, we merge the source comment for each file
5584     # afterwards
5585     %SymbolDocs = ();
5586     %SymbolTypes = ();
5587     %SymbolParams = ();
5589     my $current_type = "";        # Type of symbol being read.
5590     my $current_symbol = "";        # Name of symbol being read.
5591     my $symbol_doc = "";                # Description of symbol being read.
5592     my @params;                        # Parameter names and descriptions of current
5593                                 #   function/macro/function typedef.
5594     my $current_param = -1;        # Index of parameter currently being read.
5595                                 #   Note that the param array contains pairs
5596                                 #   of param name & description.
5597     my $in_unused_params = 0;        # True if we are reading in the unused params.
5598     my $in_deprecated = 0;
5599     my $in_since = 0;
5600     my $in_stability = 0;
5602     open (DOCS, "$template")
5603         || die "Can't open $template: $!";
5605     @TRACE@("reading template $template");
5607     while (<DOCS>) {
5608         if (m/^<!-- ##### ([A-Z_]+) (\S+) ##### -->/) {
5609             my $type = $1;
5610             my $symbol = $2;
5611             if ($symbol eq "Title"
5612                 || $symbol eq "Short_Description"
5613                 || $symbol eq "Long_Description"
5614                 || $symbol eq "See_Also"
5615                 || $symbol eq "Stability_Level"
5616                 || $symbol eq "Include"
5617                 || $symbol eq "Image") {
5619                 $symbol = $docsfile . ":" . $symbol;
5620             }
5622             #print "Found symbol: $symbol\n";
5623             # Remember file and line for the symbol
5624             $SymbolSourceFile{$symbol} = $template;
5625             $SymbolSourceLine{$symbol} = $.;
5627             # Store previous symbol, but remove any trailing blank lines.
5628             if ($current_symbol ne "") {
5629                 $symbol_doc =~ s/\s+$//;
5630                 $SymbolTypes{$current_symbol} = $current_type;
5631                 $SymbolDocs{$current_symbol} = $symbol_doc;
5633                 # Check that the stability level is valid.
5634                 if ($StabilityLevel{$current_symbol}) {
5635                     $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5636                 }
5638                 if ($current_param >= 0) {
5639                     $SymbolParams{$current_symbol} = [ @params ];
5640                 } else {
5641                     # Delete any existing params in case we are overriding a
5642                     # previously read template.
5643                     delete $SymbolParams{$current_symbol};
5644                 }
5645             }
5646             $current_type = $type;
5647             $current_symbol = $symbol;
5648             $current_param = -1;
5649             $in_unused_params = 0;
5650             $in_deprecated = 0;
5651             $in_since = 0;
5652             $in_stability = 0;
5653             $symbol_doc = "";
5654             @params = ();
5656         } elsif (m/^<!-- # Unused Parameters # -->/) {
5657             #print "DEBUG: Found unused parameters\n";
5658             $in_unused_params = 1;
5659             next;
5661         } elsif ($in_unused_params && $skip_unused_params) {
5662             # When outputting the DocBook we skip unused parameters.
5663             #print "DEBUG: Skipping unused param: $_";
5664             next;
5666         } else {
5667             # Check if param found. Need to handle "..." and "format...".
5668             if (s/^\@([\w\.]+):\040?//) {
5669                 my $param_name = $1;
5670                 my $param_desc = $_;
5671                 # Allow variations of 'Returns'
5672                 if ($param_name =~ m/^[Rr]eturns?$/) {
5673                     $param_name = "Returns";
5674                 }
5675                 # Allow varargs variations
5676                 if ($param_name =~ m/^.*\.\.\.$/) {
5677                     $param_name = "...";
5678                 }
5680                 # strip trailing whitespaces and blank lines
5681                 s/\s+\n$/\n/m;
5682                 s/\n+$/\n/sm;
5683                 @TRACE@("Found param for symbol $current_symbol : '$param_name'= '$_'");
5685                 if ($param_name eq "Deprecated") {
5686                     $in_deprecated = 1;
5687                     $Deprecated{$current_symbol} = $_;
5688                 } elsif ($param_name eq "Since") {
5689                     $in_since = 1;
5690                     chomp;
5691                     $Since{$current_symbol} = $_;
5692                 } elsif ($param_name eq "Stability") {
5693                     $in_stability = 1;
5694                     $StabilityLevel{$current_symbol} = $_;
5695                 } else {
5696                     push (@params, $param_name);
5697                     push (@params, $param_desc);
5698                     $current_param += $PARAM_FIELD_COUNT;
5699                 }
5700             } else {
5701                 # strip trailing whitespaces and blank lines
5702                 s/\s+\n$/\n/m;
5703                 s/\n+$/\n/sm;
5705                 if (!m/^\s+$/) {
5706                     if ($in_deprecated) {
5707                         $Deprecated{$current_symbol} .= $_;
5708                     } elsif ($in_since) {
5709                         &LogWarning ($template, $., "multi-line since docs found");
5710                         #$Since{$current_symbol} .= $_;
5711                     } elsif ($in_stability) {
5712                         $StabilityLevel{$current_symbol} .= $_;
5713                     } elsif ($current_param >= 0) {
5714                         $params[$current_param] .= $_;
5715                     } else {
5716                         $symbol_doc .= $_;
5717                     }
5718                 }
5719             }
5720         }
5721     }
5723     # Remember to finish the current symbol doccs.
5724     if ($current_symbol ne "") {
5726         $symbol_doc =~ s/\s+$//;
5727         $SymbolTypes{$current_symbol} = $current_type;
5728         $SymbolDocs{$current_symbol} = $symbol_doc;
5730         # Check that the stability level is valid.
5731         if ($StabilityLevel{$current_symbol}) {
5732             $StabilityLevel{$current_symbol} = &ParseStabilityLevel($StabilityLevel{$current_symbol}, $template, $., "Stability level for $current_symbol");
5733         }
5735         if ($current_param >= 0) {
5736             $SymbolParams{$current_symbol} = [ @params ];
5737         } else {
5738             # Delete any existing params in case we are overriding a
5739             # previously read template.
5740             delete $SymbolParams{$current_symbol};
5741         }
5742     }
5744     close (DOCS);
5745     return 1;
5749 #############################################################################
5750 # Function    : ReadObjectHierarchy
5751 # Description : This reads in the $MODULE-hierarchy.txt file containing all
5752 #               the GtkObject subclasses described in this module (and their
5753 #               ancestors).
5754 #               It places them in the @Objects array, and places their level
5755 #               in the object hierarchy in the @ObjectLevels array, at the
5756 #               same index. GtkObject, the root object, has a level of 1.
5758 #               This also generates tree_index.sgml as it goes along.
5760 # Arguments   : none
5761 #############################################################################
5763 sub ReadObjectHierarchy {
5764     @Objects = ();
5765     @ObjectLevels = ();
5767     if (! -f $OBJECT_TREE_FILE) {
5768         return;
5769     }
5770     if (!open (INPUT, $OBJECT_TREE_FILE)) {
5771         warn "Can't open $OBJECT_TREE_FILE - skipping object tree\n";
5772         return;
5773     }
5775     # Only emit objects if they are supposed to be documented, or if
5776     # they have documented children. To implement this, we maintain a
5777     # stack of pending objects which will be emitted if a documented
5778     # child turns up.
5779     my @pending_objects = ();
5780     my @pending_levels = ();
5781     my $root;
5782     my @tree = ();
5783     while (<INPUT>) {
5784         if (m/\S+/) {
5785             my $object = $&;
5786             my $level = (length($`)) / 2 + 1;
5787             my $xref = "";
5789             if ($level == 1) {
5790                 $root = $object;
5791             }
5793             while (($#pending_levels >= 0) && ($pending_levels[$#pending_levels] >= $level)) {
5794                 my $pobject = pop(@pending_objects);
5795                 my $plevel = pop(@pending_levels);
5796             }
5798             push (@pending_objects, $object);
5799             push (@pending_levels, $level);
5801             if (exists($KnownSymbols{$object})) {
5802                 while ($#pending_levels >= 0) {
5803                     $object = shift @pending_objects;
5804                     $level = shift @pending_levels;
5805                     $xref = &MakeXRef ($object);
5807                     push (@tree, ' ' x ($level * 4) . "$xref");
5808                     push (@Objects, $object);
5809                     push (@ObjectLevels, $level);
5810                     $ObjectRoots{$object} = $root;
5811                 }
5812             }
5813             #else {
5814             #    LogWarning ($OBJECT_TREE_FILE, $., "unknown type $object");
5815             #}
5816         }
5817     }
5818     close (INPUT);
5820     # FIXME: use $OUTPUT_FORMAT
5821     # my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.$OUTPUT_FORMAT";
5822     my $old_tree_index = "$SGML_OUTPUT_DIR/tree_index.sgml";
5823     my $new_tree_index = "$SGML_OUTPUT_DIR/tree_index.new";
5825     open (OUTPUT, ">$new_tree_index")
5826         || die "Can't create $new_tree_index: $!";
5828     if ($OUTPUT_FORMAT eq "xml") {
5829         my $tree_header = $doctype_header;
5831         $tree_header =~ s/<!DOCTYPE \w+/<!DOCTYPE screen/;
5832         print (OUTPUT "$tree_header");
5833     }
5834     print (OUTPUT "<screen>\n" . &AddTreeLineArt(\@tree) . "\n</screen>\n");
5835     close (OUTPUT);
5837     &UpdateFileIfChanged ($old_tree_index, $new_tree_index, 0);
5839     &OutputObjectList;
5842 #############################################################################
5843 # Function    : ReadInterfaces
5844 # Description : This reads in the $MODULE.interfaces file.
5846 # Arguments   : none
5847 #############################################################################
5849 sub ReadInterfaces {
5850     %Interfaces = ();
5852     if (! -f $INTERFACES_FILE) {
5853         return;
5854     }
5855     if (!open (INPUT, $INTERFACES_FILE)) {
5856         warn "Can't open $INTERFACES_FILE - skipping interfaces\n";
5857         return;
5858     }
5860     while (<INPUT>) {
5861        chomp;
5862        my ($object, @ifaces) = split;
5863        if (exists($KnownSymbols{$object}) && $KnownSymbols{$object} == 1) {
5864            my @knownIfaces = ();
5866            # filter out private interfaces, but leave foreign interfaces
5867            foreach my $iface (@ifaces) {
5868                if (!exists($KnownSymbols{$iface}) || $KnownSymbols{$iface} == 1) {
5869                    push (@knownIfaces, $iface);
5870                }
5871              }
5873            $Interfaces{$object} = join(' ', @knownIfaces);
5874        }
5875     }
5876     close (INPUT);
5879 #############################################################################
5880 # Function    : ReadPrerequisites
5881 # Description : This reads in the $MODULE.prerequisites file.
5883 # Arguments   : none
5884 #############################################################################
5886 sub ReadPrerequisites {
5887     %Prerequisites = ();
5889     if (! -f $PREREQUISITES_FILE) {
5890         return;
5891     }
5892     if (!open (INPUT, $PREREQUISITES_FILE)) {
5893         warn "Can't open $PREREQUISITES_FILE - skipping prerequisites\n";
5894         return;
5895     }
5897     while (<INPUT>) {
5898        chomp;
5899        my ($iface, @prereqs) = split;
5900        if (exists($KnownSymbols{$iface}) && $KnownSymbols{$iface} == 1) {
5901            my @knownPrereqs = ();
5903            # filter out private prerequisites, but leave foreign prerequisites
5904            foreach my $prereq (@prereqs) {
5905                if (!exists($KnownSymbols{$prereq}) || $KnownSymbols{$prereq} == 1) {
5906                   push (@knownPrereqs, $prereq);
5907                }
5908            }
5910            $Prerequisites{$iface} = join(' ', @knownPrereqs);
5911        }
5912     }
5913     close (INPUT);
5916 #############################################################################
5917 # Function    : ReadArgsFile
5918 # Description : This reads in an existing file which contains information on
5919 #                all GTK args. It creates the arrays @ArgObjects, @ArgNames,
5920 #                @ArgTypes, @ArgFlags, @ArgNicks and @ArgBlurbs containing info
5921 #               on the args.
5922 # Arguments   : $file - the file containing the arg information.
5923 #############################################################################
5925 sub ReadArgsFile {
5926     my ($file) = @_;
5928     my $in_arg = 0;
5929     my $arg_object;
5930     my $arg_name;
5931     my $arg_type;
5932     my $arg_flags;
5933     my $arg_nick;
5934     my $arg_blurb;
5935     my $arg_default;
5936     my $arg_range;
5938     # Reset the args info.
5939     @ArgObjects = ();
5940     @ArgNames = ();
5941     @ArgTypes = ();
5942     @ArgFlags = ();
5943     @ArgNicks = ();
5944     @ArgBlurbs = ();
5945     @ArgDefaults = ();
5946     @ArgRanges = ();
5948     if (! -f $file) {
5949         return;
5950     }
5951     if (!open (INPUT, $file)) {
5952         warn "Can't open $file - skipping args\n";
5953         return;
5954     }
5955     while (<INPUT>) {
5956         if (!$in_arg) {
5957             if (m/^<ARG>/) {
5958                 $in_arg = 1;
5959                 $arg_object = "";
5960                 $arg_name = "";
5961                 $arg_type = "";
5962                 $arg_flags = "";
5963                 $arg_nick = "";
5964                 $arg_blurb = "";
5965                 $arg_default = "";
5966                 $arg_range = "";
5967             }
5968         } else {
5969             if (m/^<NAME>(.*)<\/NAME>/) {
5970                 $arg_name = $1;
5971                 if ($arg_name =~ m/^(.*)::(.*)$/) {
5972                     $arg_object = $1;
5973                     ($arg_name = $2) =~ s/_/-/g;
5974                     #print "Found arg: $arg_name\n";
5975                 } else {
5976                     &LogWarning ($file, $., "Invalid argument name: $arg_name");
5977                 }
5978             } elsif (m/^<TYPE>(.*)<\/TYPE>/) {
5979                 $arg_type = $1;
5980             } elsif (m/^<RANGE>(.*)<\/RANGE>/) {
5981                 $arg_range = $1;
5982             } elsif (m/^<FLAGS>(.*)<\/FLAGS>/) {
5983                 $arg_flags = $1;
5984             } elsif (m/^<NICK>(.*)<\/NICK>/) {
5985                 $arg_nick = $1;
5986             } elsif (m/^<BLURB>(.*)<\/BLURB>/) {
5987                 $arg_blurb = $1;
5988                 if ($arg_blurb eq "(null)") {
5989                   $arg_blurb = "";
5990                   &LogWarning ($file, $., "Property ${arg_object}:${arg_name} has no documentation.");
5991                 }
5992             } elsif (m/^<DEFAULT>(.*)<\/DEFAULT>/) {
5993                 $arg_default = $1;
5994             } elsif (m%^</ARG>%) {
5995                 #print "Found end of arg: ${arg_object}::${arg_name}\n${arg_type} : ${arg_flags}\n";
5996                 push (@ArgObjects, $arg_object);
5997                 push (@ArgNames, $arg_name);
5998                 push (@ArgTypes, $arg_type);
5999                 push (@ArgRanges, $arg_range);
6000                 push (@ArgFlags, $arg_flags);
6001                 push (@ArgNicks, $arg_nick);
6002                 push (@ArgBlurbs, $arg_blurb);
6003                 push (@ArgDefaults, $arg_default);
6004                 $in_arg = 0;
6005             }
6006         }
6007     }
6008     close (INPUT);
6011 #############################################################################
6012 # Function    : AddTreeLineArt
6013 # Description : Add unicode lineart to a pre-indented string array and returns
6014 #               it as as multiline string.
6015 # Arguments   : @tree - array of indented strings.
6016 #############################################################################
6018 sub AddTreeLineArt {
6019   my @tree = @{$_[0]};
6020   my $i;
6021   my $j;
6022   my $indent;
6023   
6024   # iterate bottom up over the tree 
6025   for ($i = $#tree; $i >= 0; $i--) {
6026     # count leading spaces
6027     $tree[$i] =~ /^([^<A-Za-z]*)/;
6028     $indent = length( $1 );
6029     # replace with ╰───, if place of ╰ is not space insert ├
6030     if ($indent > 4) {
6031       if (substr($tree[$i],$indent-4,1) eq " ") {
6032         substr($tree[$i],$indent-4,4) = "--- ";
6033       } else {
6034         substr($tree[$i],$indent-4,4) = "+-- ";
6035       }
6036       # go lines up while space and insert |
6037       for ($j = $i - 1; ($j >= 0 && substr($tree[$j],$indent-4,1) eq ' '); $j--) {
6038         substr($tree[$j],$indent-4,1) = '|';
6039       }
6040     }
6041   }
6042   
6043   my $res = join("\n", @tree);
6044   # unicode chars for: ╰──
6045   $res =~ s%---%<phrase role=\"lineart\">&#9584;&#9472;&#9472;</phrase>%g;
6046   # unicde chars for: ├──
6047   $res =~ s%\+--%<phrase role=\"lineart\">&#9500;&#9472;&#9472;</phrase>%g;
6048   # unicode char for: │
6049   $res =~ s%\|%<phrase role=\"lineart\">&#9474;</phrase>%g;
6050   
6051   return $res;
6055 #############################################################################
6056 # Function    : CheckIsObject
6057 # Description : Returns 1 if the given name is a GObject or a subclass.
6058 #                It uses the global @Objects array.
6059 #                Note that the @Objects array only contains classes in the
6060 #                current module and their ancestors - not all GObject classes.
6061 # Arguments   : $name - the name to check.
6062 #############################################################################
6064 sub CheckIsObject {
6065     my ($name) = @_;
6066     my $root = $ObjectRoots{$name};
6067     # Let GBoxed pass as an object here to get -struct appended to the id
6068     # and prevent conflicts with sections.
6069     return (defined($root) and $root ne 'GEnum' and $root ne 'GFlags');
6073 #############################################################################
6074 # Function    : MakeReturnField
6075 # Description : Pads a string to $RETURN_TYPE_FIELD_WIDTH.
6076 # Arguments   : $str - the string to pad.
6077 #############################################################################
6079 sub MakeReturnField {
6080     my ($str) = @_;
6082     return $str . (' ' x ($RETURN_TYPE_FIELD_WIDTH - length ($str)));
6085 #############################################################################
6086 # Function    : GetSymbolSourceFile
6087 # Description : Get the filename where the symbol docs where taken from.
6088 # Arguments   : $symbol - the symbol name
6089 #############################################################################
6091 sub GetSymbolSourceFile {
6092     my ($symbol) = @_;
6094     if (defined($SourceSymbolSourceFile{$symbol})) {
6095         return $SourceSymbolSourceFile{$symbol};
6096     } elsif (defined($SymbolSourceFile{$symbol})) {
6097         return $SymbolSourceFile{$symbol};
6098     } else {
6099         return "";
6100     }
6103 #############################################################################
6104 # Function    : GetSymbolSourceLine
6105 # Description : Get the file line where the symbol docs where taken from.
6106 # Arguments   : $symbol - the symbol name
6107 #############################################################################
6109 sub GetSymbolSourceLine {
6110     my ($symbol) = @_;
6112     if (defined($SourceSymbolSourceLine{$symbol})) {
6113         return $SourceSymbolSourceLine{$symbol};
6114     } elsif (defined($SymbolSourceLine{$symbol})) {
6115         return $SymbolSourceLine{$symbol};
6116     } else {
6117         return 0;
6118     }