1 <!doctype book PUBLIC "-//OASIS//DTD DocBook V3.1//EN" []>
5 <date>January 14th 2004</date>
6 <title>GTK+ FAQ</title>
9 <firstname>Tony</firstname>
10 <surname>Gale</surname>
13 <firstname>Shawn</firstname>
14 <surname>Amundson</surname>
17 <firstname>Emmanuel</firstname>
18 <surname>Deloget</surname>
22 <para> This document is intended to answer questions that are
23 likely to be frequently asked by programmers using GTK+ or
24 people who are just looking at using GTK+. </para>
25 <para><emphasis>Note: </emphasis> This FAQ mainly covers GTK+ 1.2.
26 Where the text covers GTK+ 2.x this will be indicated</para>
32 <!-- ***************************************************************** -->
34 <title>General Information</title>
36 <!-- ----------------------------------------------------------------- -->
39 <title>Note: This FAQ is undergoing conversion to GTK+ 2.x</title>
40 <para>This FAQ is undergoing conversion to GTK+ 2.x.
41 Where the text covers GTK+ 2.x this will be indicated by prefixing the
42 text with: <emphasis>[GTK+ 2.x]</emphasis>. Where this is not
43 indicated, the text has not yet been updated from GTK+ 1.2 and may
44 not be totally correct.
48 <!-- ----------------------------------------------------------------- -->
51 <title>Before anything else: the greetings <emphasis>[GTK 2.x]</emphasis></title>
52 <para>The FAQ authors want to thank:</para>
53 <itemizedlist spacing=Compact>
55 <simpara>Havoc Pennington</simpara>
58 <simpara>Erik Mouw</simpara>
61 <simpara>Owen Taylor</simpara>
64 <simpara>Tim Janik</simpara>
67 <simpara>Thomas Mailund Jensen</simpara>
70 <simpara>Joe Pfeiffer</simpara>
73 <simpara>Andy Kahn</simpara>
76 <simpara>Federico Mena Quntero</simpara>
79 <simpara>Damon Chaplin</simpara>
82 <simpara>and all the members of the GTK+ lists</simpara>
83 </listitem></itemizedlist>
84 <para> If we forgot you, please email us! Thanks again (I know,
85 it's really short :) </para>
88 <!-- ----------------------------------------------------------------- -->
91 <title>Authors <emphasis>[GTK 2.x]</emphasis></title>
93 <para>The original authors of GTK+ were:</para>
95 <itemizedlist spacing=Compact>
97 <simpara>Peter Mattis</simpara>
100 <simpara>Spencer Kimball</simpara>
103 <simpara>Josh MacDonald</simpara>
107 <para>Since then, much has been added by others. Please see the
108 AUTHORS file in the distribution for the GTK+ Team. The people currently
109 contributing the most code to GTK+ are (in no particular order):</para>
112 <itemizedlist spacing=Compact>
114 <simpara>Owen Taylor</simpara>
117 <simpara>Matthias Clasen</simpara>
120 <simpara>Federico Mena Quintero</simpara>
123 <simpara>Soeren Sandmann</simpara>
126 <simpara>Padraig O'Briain</simpara>
129 <simpara>Manish Singh</simpara>
132 <simpara>Kristian Rietveld</simpara>
135 <simpara>Tor Lillqvist</simpara>
141 <!-- ----------------------------------------------------------------- -->
144 <title>What is GTK+? <emphasis>[GTK 2.x]</emphasis></title>
146 <para>GTK+ is a multi-platform toolkit for creating graphical user
147 interfaces, originally designed with
148 the general look and feel of Motif. In reality, it looks much
149 better than Motif. It contains common and complex widgets, such as
150 file selection, and color selection widgets.</para>
152 <para>GTK+ was initially developed as a widget set for the GIMP (GNU Image
153 Manipulation Program). It has grown extensively since then, and is today
154 used by a large number of applications, and is the toolkit used by the
155 <ulink url="http://www.gnome.org/">GNOME</ulink> desktop project.</para>
157 <para>GTK+ is free software and part of the GNU Project. However, the
158 licensing terms for GTK+, the GNU LGPL, allow it to be used by all developers,
159 including those developing proprietary software, without any license fees
162 <para>GTK+ has been designed from the ground up to support a range of
163 <ulink url="http://www.gtk.org/bindings.html">
164 language bindings</ulink>, not only C/C++. Using GTK+ from languages
165 such as Perl and Python (especially in combination with the Glade GUI
166 builder) provides an effective method of rapid application
170 <!-- ----------------------------------------------------------------- -->
173 <title>What is the + in GTK+? <emphasis>[GTK 2.x]</emphasis></title>
175 <para>Peter Mattis informed the gtk mailing list that:</para>
177 <para><quote>I originally wrote gtk which included the three
178 libraries, libglib, libgdk and libgtk. It featured a flat
179 widget hierarchy. That is, you couldn't derive a new widget
180 from an existing one. And it contained a more standard
181 callback mechanism instead of the signal mechanism now present
182 in gtk+. The + was added to distinguish between the original
183 version of gtk and the new version. You can think of it as
184 being an enhancement to the original gtk that adds object
185 oriented features.</quote></para>
187 <para>Although much has changed with GTK+, and Peter, Spencer and Josh
188 don't have any direct involvement these days, the name is kept to keep
189 a link with the heritage of GTK+.</para>
191 <para>GTK+ is now additionally based upon the Pango and ATK
192 libraries, that provide text layout and rendering and accessibility
196 <!-- ----------------------------------------------------------------- -->
199 <title>Does the G in GTK+, GDK and GLib stand for? <emphasis>[GTK 2.x]</emphasis></title>
201 <para>GTK+ == The GIMP Toolkit</para>
202 <para>GDK == GTK+ Drawing Kit</para>
203 <para>GLib == G Library</para>
207 <!-- ----------------------------------------------------------------- -->
210 <title>Where is the documentation for GTK+? <emphasis>[GTK 2.x]</emphasis></title>
212 <para>In the GTK+ distribution's doc/ directory you will find
213 the API Reference for both GTK and GDK, this FAQ and the
216 <para>In addition, you can find links to HTML versions of
217 these documents by going to <ulink url="http://www.gtk.org/">
218 http://www.gtk.org/</ulink>. A
219 packaged version of the GTK Tutorial, with SGML, HTML,
220 Postscript, DVI and text versions can be found in <ulink
221 url="ftp://ftp.gtk.org/pub/gtk/tutorial">
222 ftp://ftp.gtk.org/pub/gtk/tutorial
225 <para>There are now a few books available that deal with
226 programming GTK+, GDK and GNOME. Unfortunately, they
227 currently are all based upon GTK+ 1.x:</para>
230 <listitem><simpara>Eric Harlows book entitled "Developing
231 Linux Applications with GTK+ and GDK". The ISBN is
232 0-7357-0021-4</simpara>
234 <listitem><simpara>The example code from Eric's book is
235 available on-line at <ulink
236 url="http://www.bcpl.net/~eharlow/book">
237 http://www.bcpl.net/~eharlow/book</ulink></simpara>
239 <listitem><simpara>Havoc Pennington has released a book called
240 "GTK+/GNOME Application Development". The ISBN is
241 0-7357-0078-8</simpara>
242 <simpara>The free version of the book lives here: <ulink
243 url="http://developer.gnome.org/doc/GGAD/">
244 http://developer.gnome.org/doc/GGAD/
246 <simpara>And Havoc maintains information about it and
248 url="http://pobox.com/~hp/gnome-app-devel.html">
249 http://pobox.com/~hp/gnome-app-devel.html
252 <listitem><simpara>"GTK+ Programming in C" by
253 Syd Logan. ISBN: 0-1301-4264-6</simpara>
255 <listitem><simpara>"Linux GNOME/GTK+ Programming Bible" by
256 Arthur Griffith. ISBN: 0-7645-4640-6</simpara>
258 <listitem><simpara>"Beginning GTK+/GNOME Programming" by
259 Peter Wright. ISBN: 1-8610-0381-1</simpara>
261 <listitem><simpara>"Sams Teach Yourself GTK+ Programming
262 in 21 Days" by Donna Martin
263 . ISBN: 0-6723-1829-6</simpara>
269 <!-- ----------------------------------------------------------------- -->
271 <sect1 id="faq-MailLists">
272 <title>Is there a mailing list (or mailing list archive) for
273 GTK+? <emphasis>[GTK 2.x]</emphasis></title>
275 <para>Information on mailing lists relating to GTK+ can be
277 url="http://www.gtk.org/mailinglists.html">
278 http://www.gtk.org/mailinglists.html
283 <!-- ----------------------------------------------------------------- -->
286 <title>How to get help with GTK+ <emphasis>[GTK 2.x]</emphasis></title>
288 <para>First, make sure your question isn't answered in the
289 documentation, this FAQ or the tutorial. Done that? You're
290 sure you've done that, right? In that case, the best place to
291 post questions is to the GTK+ mailing list.</para>
295 <!-- ----------------------------------------------------------------- -->
298 <title>How to report bugs in GTK+ <emphasis>[GTK 2.x]</emphasis></title>
300 <para>Bugs should be reported to the GNOME bug tracking system
301 (<ulink url="http://bugzilla.gnome.org">http://bugzilla.gnome.org</ulink>).
302 You will need to enter your email address and receive a password before
303 you can use the system to register a new bug report.</para>
305 <para>There are a number of options to select and boxes to fill in when
306 submitting a bug report. Please remember that the more information you
307 give, the easier it will be to track the problem down. Extra information
308 that may prove useful includes:</para>
311 <listitem><simpara> How to reproduce the bug.</simpara>
312 <simpara>If you can reproduce it with the testgtk program
313 that is built in the gtk/ subdirectory, that will be most
314 convenient. Otherwise, please include a complete, short test
315 program that exhibits the behavior. As a last resort, you can also
316 provide a pointer to a larger piece of software that can
317 be downloaded.</simpara>
319 <simpara>(Bugs that can be reproduced within the GIMP are
320 almost as good as bugs that can be reproduced in
321 testgtk. If you are reporting a bug found with the GIMP,
322 please include the version number of the GIMP you are
326 <listitem><simpara> If the bug was a crash, the exact text that was
327 printed out when the crash occurred. If you can easily reproduce this
328 crash then running the program under a debugger (e.g. gdb) and getting
329 a backtrace when the crash occurs is very useful.</simpara>
332 <listitem><simpara> Further information such as stack traces
333 may be useful. If you do send a stack trace,
334 and the error is an X error, it will be more useful if the stacktrace is
335 produced running the test program with the <literal>--sync</literal>
336 command line option.</simpara>
342 <!-- ----------------------------------------------------------------- -->
345 <title>Is there a Windows version of GTK+? <emphasis>[GTK 2.x]</emphasis></title>
347 <para>The Win32 port of GTK+ is maintained concurrently with the Xwindows
348 version in CVS. As such it is a supported architecture.</para>
350 <para>The Win32 port has been predominately done by Tor Lillqvist. Tor
351 maintains some information on <ulink url="http://www.gimp.org/~tml/gimp/win32/">
352 GTK+ and GIMP for Windows</ulink>.</para>
354 <para>There is a pre-compiled, easy-to-install version of GTK+ for
355 windows on the <ulink url="http://www.dropline.net/gtk/">
356 Dropline GTK+</ulink> site.</para>
360 <!-- ----------------------------------------------------------------- -->
363 <title>What applications have been written with GTK+? <emphasis>[GTK 2.x]</emphasis></title>
365 <para>The GNOME software map contains a catalogue of software that is
366 built using GNOME and GTK+. The catalogue is searchable and browsable, so
367 provides easy access.</para>
369 <para>Some of the best known projects utilising GTK+ are:</para>
372 <listitem><simpara> GIMP (<ulink
373 url="http://www.gimp.org/">http://www.gimp.org/</ulink>), an
374 image manipulation program</simpara>
376 <listitem><simpara> AbiWord (<ulink
377 url="http://www.abiword.org/">http://www.abiword.com/</ulink>),
378 a professional word processor</simpara>
380 <listitem><simpara> Dia (<ulink
381 url="http://www.lysator.liu.se/~alla/dia/dia.html">
382 http://www.lysator.liu.se/~alla/dia/dia.html</ulink>),
383 a diagram creation program</simpara>
385 <listitem><simpara> GnuCash (<ulink
386 url="http://www.gnucash.org/">
387 http://www.gnucash.org/</ulink>),
388 a personal finance manager</simpara>
390 <listitem><simpara> Gnumeric (<ulink
391 url="http://www.gnome.org/projects/gnumeric/">
392 http://www.gnome.org/projects/gnumeric/</ulink>),
393 the GNOME spreadsheet application</simpara>
395 <listitem><simpara> Glade (<ulink
396 url="http://glade.gnome.org/">http://glade.gnome.org/</ulink>), a
397 GTK+ based RAD tool which produces GTK+ and GNOME applications</simpara>
399 <listitem><simpara> Anjuta (<ulink
400 url="http://anjuta.sourceforge.net/">http://anjuta.sourceforge.net/</ulink>),
401 a versatile Integrated Development Environment (IDE) using C and C++ for GTK+
409 <!-- ***************************************************************** -->
411 <title>How to find, configure, install, and troubleshoot GTK+</title>
413 <!-- ----------------------------------------------------------------- -->
415 <sect1 id="faq-Compile">
416 <title>What do I need to compile GTK+? <emphasis>[GTK 2.x]</emphasis></title>
418 <para>GTK+ is a large package that is dependent on a number of other
419 tools and libraries. It is recommended that you use precompiled
420 binary packages for your system if possible</para>
422 <para>To compile GTK+ from source you need a C compiler (gcc) and
423 the X Window System and associated development libraries and packages
424 on your system.</para>
426 <para>You will also need to have installed the tools
427 and libraries that GTK+ depends upon. These are listed below in the order
428 in which they need to be installed:</para>
430 <itemizedlist spacing=compact>
431 <listitem><simpara> pkg-config
432 (<ulink url="http://pkg-config.freedesktop.org/wiki">
433 pkg-config Site</ulink>)</simpara>
436 <listitem><simpara> GNU make
437 (<ulink url="http://www.gnu.org/software/make/">
438 GNU make Site</ulink>)</simpara>
441 <listitem><simpara> JPEG, PNG and TIFF image libraries
442 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/dependencies/">
443 GTK+ Site</ulink>)</simpara>
446 <listitem><simpara> FreeType
447 (<ulink url="http://www.freetype.org/">
448 FreeType Site</ulink>)</simpara>
451 <listitem><simpara> fontconfig
452 (<ulink url="http://www.fontconfig.org/">
453 fontconfig Site</ulink>)</simpara>
456 <listitem><simpara> GNU libiconv library (if your system doesn't have iconv())
457 (<ulink url="http://www.gnu.org/software/libiconv/">
458 GNU libiconv Site</ulink>)</simpara>
461 <listitem><simpara> GNU gettext (if your system doesn't have gettext())
462 (<ulink url="http://www.gnu.org/software/gettext/">
463 GTK+ Site</ulink>)</simpara>
466 <listitem><simpara> GLib
467 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
468 GTK+ Site</ulink>)</simpara>
471 <listitem><simpara> Pango
472 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
473 GTK+ Site</ulink>)</simpara>
476 <listitem><simpara> ATK
477 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
478 GTK+ Site</ulink>)</simpara>
481 <listitem><simpara> GTK+
482 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
483 GTK+ Site</ulink>)</simpara>
489 <!-- ----------------------------------------------------------------- -->
492 <title>Where can I get GTK+? <emphasis>[GTK 2.x]</emphasis></title>
494 <para>The canonical site is <ulink
495 url="ftp://ftp.gtk.org/pub/gtk">ftp://ftp.gtk.org/pub/gtk</ulink>.</para>
497 <para>This site tends to get busy around the time of a new
498 GTK+ release so try and use one of the mirror sites that are
500 url="ftp://ftp.gtk.org/etc/mirrors">ftp://ftp.gtk.org/etc/mirrors
503 <para>Here's a few mirror sites to get you started:</para>
505 <itemizedlist spacing=compact>
506 <listitem><simpara> Africa -
507 <ulink url="ftp://ftp.is.co.za/applications/gimp">
508 ftp://ftp.is.co.za/applications/gimp</ulink></simpara>
511 <listitem><simpara> Australia -
513 url="ftp://ftp.planetmirror.com/pub/gimp/gtk">
514 ftp://ftp.planetmirror.com/pub/gimp/gtk</ulink></simpara>
517 <listitem><simpara> Finland -
518 <ulink url="ftp://ftp.funet.fi/pub/sci/graphics/packages/gimp/gtk">
519 ftp://ftp.funet.fi/pub/sci/graphics/packages/gimp/gtk</ulink></simpara>
522 <listitem><simpara> Germany -
523 <ulink url="ftp://ftp.gwdg.de/pub/misc/grafik/gimp/gtk">
524 ftp://ftp.gwdg.de/pub/misc/grafik/gimp/gtk</ulink></simpara>
527 <listitem><simpara> Japan -
528 <ulink url="ftp://sunsite.sut.ac.jp/pub/archives/packages/gimp/gtk">
529 ftp://sunsite.sut.ac.jp/pub/archives/packages/gimp/gtk</ulink></simpara>
532 <listitem><simpara> UK -
533 <ulink url="http://www.mirror.ac.uk/sites/ftp.gimp.org/pub/gtk/">
534 http://www.mirror.ac.uk/sites/ftp.gimp.org/pub/gtk/</ulink></simpara>
539 <!-- ----------------------------------------------------------------- -->
542 <title>How do I configure/compile GTK+? <emphasis>[GTK 2.x]</emphasis></title>
544 <para>Generally, the minimum you need to do is issue the commands:</para>
546 <para><literallayout><literal>./configure</literal>
547 <literal>make</literal>
548 <literal>make install</literal></literallayout></para>
550 <para>in the GTK+ source directory.</para>
552 <para>This generally also holds true for each of the packages that GTK+
553 depends upon, listed <link linkend="faq-Compile">above</link>.</para>
555 <para>There are various options that you can pass to the configure script
556 in order to change its default settings. The one that you are most likely
557 to want to use is the <literal>--prefix</literal>
558 argument, which defines where the package is to be install, e.g.</para>
561 <literallayout><literal>./configure --prefix=/usr</literal></literallayout>
565 <!-- ----------------------------------------------------------------- -->
568 <title>When compiling GTK+ I get an error like: <literal>make:
569 file `Makefile' line 456: Syntax error</literal> <emphasis>[GTK 2.x]</emphasis></title>
571 <para>Make sure that you are using GNU make
572 (use <literal>make -v</literal>
573 to check). There are many weird and wonderful versions of make
574 out there, and not all of them handle the automatically
575 generated Makefiles.</para>
579 <!-- ----------------------------------------------------------------- -->
582 <title>I've compiled and installed GTK+, but I can't get any
583 programs to link with it! <emphasis>[GTK 2.x]</emphasis></title>
585 <para>This problem is most often encountered when the GTK+
586 libraries can't be found or are the wrong version. Generally,
587 the compiler will complain about an 'unresolved symbol'.</para>
589 <para>Make sure that the libraries can be
590 found. You want to edit <filename>/etc/ld.so.conf</filename> to
591 include the directories which contain the GTK libraries,
592 so it looks something like:</para>
594 <para><literallayout><literal>/usr/X11R6/lib</literal>
595 <literal>/usr/local/lib</literal></literallayout></para>
597 <para>Then you need to run /sbin/ldconfig as root. You can
598 find what libraries GTK requires using</para>
600 <para><literallayout><literal>pkg-config gtk+-2.0 --libs</literal>
601 </literallayout></para>
603 <para>If your system doesn't use ld.so to find libraries
604 (such as Solaris), then you will have to use the LD_LIBRARY_PATH
605 environment variable (or compile the path into your program, which I'm
606 not going to cover here). So, with a Bourne type shell you can do (if
607 your GTK libraries are in /usr/local/lib):</para>
609 <para><literallayout>
610 <literal>export LD_LIBRARY_PATH=/usr/local/lib</literal>
611 </literallayout></para>
613 <para>and in a csh, you can do:</para>
615 <para><literallayout>
616 <literal>setenv LD_LIBRARY_PATH /usr/local/lib</literal>
617 </literallayout></para>
621 <!-- ----------------------------------------------------------------- -->
624 <title>When installing a GTK+ application, configure reports
625 that it can't find GTK. <emphasis>[GTK 2.x]</emphasis></title>
627 <para>There are several common reasons for this:</para>
630 <listitem><simpara>You have an old version of GTK installed
631 somewhere. You should remove this old copy, but note that
632 this may break applications that have been compiled against
633 the old version.</simpara>
636 <listitem><simpara><literal>pkg-config</literal> (or another
637 component of GTK) isn't in your path, or there is an old
638 version on your system. Type:</simpara>
640 <para><literallayout>
641 <literal>pkg-config gtk+-2.0 --modversion</literal>
642 </literallayout></para>
644 <para>to check for both of these. If it returns a value
645 different from what you expect, then you have an old
646 version of GTK on your system.</para>
649 <listitem><simpara>The ./configure script can't find the GTK
650 libraries. As ./configure compiles various test programs, it needs to be
651 able to find the GTK libraries. See the question above
652 for help on this. </simpara></listitem>
655 <para>If none of the above help, then have a look in
656 config.log, which is generated by ./configure as it runs. At the
657 bottom will be the last action it took before failing. If it is a
658 section of source code, copy the source code to a file and compile it
659 with the line just above it in config.log. If the compilation is
660 successful, try executing it.</para>
666 <!-- ***************************************************************** -->
668 <title>Development of GTK+</title>
670 <!-- ----------------------------------------------------------------- -->
673 <title>Whats this CVS thing that everyone keeps talking about,
674 and how do I access it? <emphasis>[GTK 2.x]</emphasis></title>
676 <para>CVS is the Concurrent Version System and is a very
677 popular means of version control for software projects. It is
678 designed to allow multiple authors to simultanously operate on the same
679 source tree. This source tree is centrally maintained, but each
680 developer has a local mirror of this repository that they make
681 their changes to.</para>
683 <para>The GTK+ developers use a CVS repository to store the
684 master copy of the current development version of GTK+. As
685 such, people wishing to contribute patches to GTK+ should
686 generate them against the CVS version. Normal people should
687 use the packaged releases.</para>
689 <para>The CVS toolset is available as RPM packages from the
690 usual RedHat sites. The latest version is available at <ulink
691 url="http://download.cyclic.com/pub/">http://download.cyclic.com/pub/
694 <para>Anyone can download the latest CVS version of GTK+ by
695 using anonymous access using the following steps:</para>
698 <listitem><simpara> In a bourne shell descendant (e.g. bash) type:</simpara>
699 <para><literallayout>
700 <literal>CVSROOT=':pserver:anonymous@anoncvs.gnome.org:/cvs/gnome'</literal>
701 <literal>export CVSROOT</literal>
702 </literallayout></para>
705 <listitem><simpara>Next, the first time the source tree is
706 checked out, a cvs login is needed. </simpara>
707 <para><literallayout>
708 <literal>cvs login</literal>
709 </literallayout></para>
710 <para>This will ask you for a password. There is no
711 password for cvs.gimp.org, so just enter a carriage return.</para>
714 <listitem><simpara>To get the tree and place it in a subdir of your
715 current working directory, issue the command:</simpara>
716 <para><literallayout>
717 <literal>cvs -z3 get gtk+</literal>
718 </literallayout></para>
719 <para>Note that with the GTK+ 1.1 tree, glib has been moved to
720 a separate CVS module, so if you don't have glib installed you will
721 need to get that as well:</para>
722 <para><literallayout>
723 <literal>cvs -z3 get glib</literal>
724 </literallayout></para>
728 <para>The CVS archive stores both the current development version of
729 GTK+ (the CVS HEAD branch) and all current and past stable versions.
730 If you want to retrieve a specific version of GTK+ you have to specify
731 the CVS tag corresponding to the version you want to checkout. If you
732 want to checkout the current GTK+ 2.2 stable source code, you would need
733 to use the following command:</para>
735 <para><literallayout>
736 <literal>cvs -z3 get -r gtk-2-2 gtk+</literal>
737 </literallayout></para>
740 <!-- ----------------------------------------------------------------- -->
742 <sect1 id="faq-Patches">
743 <title>How can I contribute to GTK+? <emphasis>[GTK 2.x]</emphasis></title>
745 <para>It's simple. If something doesn't work like you think it
746 should in a program, check the documentation to make sure
747 you're not missing something. If it is a true bug or missing
748 feature, track it down in the GTK+ source, change it, and
749 then generate a patch in the form of a 'context diff'. This
750 can be done using a command such as <literal>diff -ru
751 <oldfile> <newfile></literal>.</para>
753 <para>The patch should then be attached to a bug report in
754 the GNOME bug tracking system, which can also be used to store
756 (<ulink url="http://bugzilla.gnome.org">http://bugzilla.gnome.org</ulink>).
759 <para>This method ensures that the patch will not be lost.</para>
763 <!-- ----------------------------------------------------------------- -->
766 <title>How do I know if my patch got applied, and if not, why
767 not? <emphasis>[GTK 2.x]</emphasis></title>
769 <para>If you have used the GNOME bug tracking system (as stated
770 <link linkend="faq-Patches">above</link>) then the status
771 of your patch should be reflected in the bug report.</para>
773 <para>The GTK+ developers will generally add comments to the bug
774 report stating what needs to be done to get the patch applied,
775 or why the patch is not appropriate.</para>
778 <!-- ----------------------------------------------------------------- -->
781 <title>What is the policy on incorporating new widgets into
782 the library? <emphasis>[GTK 2.x]</emphasis></title>
784 <para>This is up to the authors, so you will have to ask them
785 once you are done with your widget. As a general guideline,
786 widgets that are generally useful, work, and are not a
787 disgrace to the widget set will gladly be included.</para>
789 <para>The new widgets that get added to GTK+ are generally either
790 replacements for existing widgets that are no longer
791 deemed to be adequate, or have been developed externally to GTK+ but
792 have been widely tested.
794 <para>Before you spend months of your valuable time implementing your
795 revolutionary widget, it is highly recommended that you get some
796 feedback on your idea via the appropriate
797 <link linkend="faq-MailLists">mailing list</link>.</para>
800 <!-- ----------------------------------------------------------------- -->
803 <title>Is anyone working on bindings for languages other than
804 C? <emphasis>[GTK 2.x]</emphasis></title>
806 <para>There is a list of <ulink url="http://www.gtk.org/bindings.html">
807 language bindings</ulink> on the GTK+ website.</para>
809 <para>The 'official' language bindings are C++, Ada and Python.
810 However, bindings for many other languages are available.</para>
815 <!-- ***************************************************************** -->
817 <title>Development with GTK+: the begining</title>
819 <!-- ----------------------------------------------------------------- -->
822 <title>How do I get started? <emphasis>[GTK 2.x]</emphasis></title>
824 <para>So, after you have installed GTK+ there are a couple of
825 things that can ease you into developing applications with
826 it. There is the GTK+ Tutorial <ulink
827 url="http://library.gnome.org/devel/gtk-tutorial/stable/">
828 http://library.gnome.org/devel/gtk-tutorial/stable/</ulink>, which is undergoing
829 development. This will introduce you to writing applications
832 <para>The GTK+ Tutorial doesn't contain information on all of
833 the widgets that are in GTK+. For example code on how to use
834 the basics of all the GTK+ widgets you should look in the
835 directory 'tests' (and associated source files) within the GTK+
836 distribution. Looking at these examples will give you a good
837 grounding on what the widgets can do.</para>
841 <!-- ----------------------------------------------------------------- -->
844 <title>How do I use the Glade GUI builder with GTK+? <emphasis>[GTK 2.x]</emphasis></title>
846 <para>There are two ways to use Glade. The first way is to use
847 Glade's facilities for generating code; the second
848 way is to use the libglade library which directly loads
849 the XML user interface description files that Glade
850 generates into a running program.</para>
852 <para>Experienced GTK+ programmers generally strongly recommend
853 using libglade; you don't have to worry about the interaction
854 between Glade generating the source and you editing it,
855 and its been shown to be a method that works better
856 for large projects, so there is a lot of example code
857 out there you can look at.</para>
859 <para>An introduction to using libglade can be found in the
861 (<ulink url="http://developer.gnome.org/doc/API/2.0/libglade/libglade-notes.html#libglade-basics">
862 http://developer.gnome.org/doc/API/2.0/libglade/libglade-notes.html#libglade-basics</ulink>)
867 <!-- ----------------------------------------------------------------- -->
870 <title>How do I write security sensitive/SUID/SGID programs with GTK+?
871 Is GTK+ secure? What's this GTK_MODULES security hole I heard about?
872 <emphasis>[GTK 2.x]</emphasis></title>
874 <para>The short answer to this question is: you can't, so don't write SUID/SGID
875 programs with GTK+</para>
877 <para>GTK+ will refuse to run with elevated privileges, as it is not designed
878 to be used in this manner. The only correct way to write a setuid program with
879 a graphical user interface is to have a setuid backend that communicates with
880 the non-setuid graphical user interface via a mechanism such as a pipe and that
881 considers the input it receives to be untrusted.</para>
883 <para>For a more thorough explanation of the GTK+ Developers position on
884 this issue see <ulink
885 url="http://www.gtk.org/setuid.html">http://www.gtk.org/setuid.html</ulink>.</para>
889 <!-- ----------------------------------------------------------------- -->
892 <title>I tried to compile a small <command>Hello World</command> of mine,
893 but it failed. Any clue? <emphasis>[GTK 2.x]</emphasis></title>
895 <para>Since you are good at coding, we will not deal with
896 compile time errors here :)</para>
898 <para>The classic command line to compile a GTK+ based program is</para>
899 <para><literallayout>
900 <literal>gcc -o myprog [c files] `pkg-config gtk+-2.0 --cflags --libs`</literal>
901 </literallayout></para>
903 <para>You should notice the backquote character which is used
904 in this command line. A common mistake when you start a GTK+
905 based development is to use quotes instead of backquotes. If
906 you do so, the compiler will complain about an unknown file
907 called <filename>pkg-config gtk+-2.0 --cflags --libs</filename>. The
908 text in backquotes is an instruction to your shell to
909 substitute the output of executing this command into the
912 <para>The command line above ensures that:</para>
915 <listitem><simpara>the correct C compiler flags will be used
916 to compile the program (including the complete C header
917 directory list)</simpara>
920 <listitem><simpara>your program will be linked with the
921 needed libraries.</simpara>
927 <!-- ----------------------------------------------------------------- -->
930 <title>What about using the <command>make</command>
931 utility? <emphasis>[GTK 2.x]</emphasis></title>
933 <para>This is a sample makefile which compiles a GTK+ based
936 <programlisting role="C">
937 # basic GTK+ app makefile
938 SOURCES = myprg.c foo.c bar.c
939 OBJS = ${SOURCES:.c=.o}
940 CFLAGS = `pkg-config gtk+-2.0 --cflags`
941 LDADD = `pkg-config gtk+-2.0 --libs`
946 ${CC} -o ${PACKAGE} ${OBJS} ${LDADD}
949 ${CC} ${CFLAGS} -c $<
954 <para>For more information about the <command>make</command> utility, you
955 should read either the related man page or the relevant info file.</para>
959 <!-- ----------------------------------------------------------------- -->
962 <title>I use the backquote stuff in my makefiles, but my make
963 process failed. <emphasis>[GTK 2.x]</emphasis></title>
965 <para>The backquote construction seems to not be accepted by
966 some old <command>make</command> utilities. If you use one of these, the
967 make process will probably fail. In order to have the
968 backquote syntax working again, you should use the GNU make
969 utility (get it on the GNU ftp server at <ulink
970 url="ftp://ftp.gnu.org/gnu/make/">ftp://ftp.gnu.org/gnu/make/</ulink>).</para>
974 <!-- ----------------------------------------------------------------- -->
977 <title>I want to add some configure stuff, how could I do
978 this? <emphasis>[GTK 2.x]</emphasis></title>
980 <para>To use autoconf/automake, you must first install the
981 relevant packages. These are:</para>
983 <itemizedlist spacing=Compact>
984 <listitem><simpara>the m4 preprocessor v1.4 or better</simpara>
987 <listitem><simpara>autoconf v2.54 or better</simpara>
990 <listitem><simpara>automake v1.7 or better suggested</simpara>
994 <para>You'll find these packages on the main GNU ftp server
995 (<ulink url="ftp://ftp.gnu.org/">ftp://ftp.gnu.org/</ulink>)
996 or on any GNU mirror.</para>
998 <para>In order to use the powerful autoconf/automake scheme,
999 you must create a configure.ac which may look like:</para>
1001 <programlisting role="C">
1002 dnl Process this file with autoconf to produce a configure script.
1003 dnl configure.ac for a GTK+ based program
1006 AM_INIT_AUTOMAKE(mypkgname, 0.0.1)
1007 AM_CONFIG_HEADER(config.h)
1009 dnl Checks for programs.
1010 AC_PROG_CC dnl check for the c compiler
1011 dnl you should add CFLAGS="" here, 'cos it is set to -g by PROG_CC
1013 dnl Checks for libraries.
1014 AM_PATH_GTK_2_0(2.2.0,,AC_MSG_ERROR(mypkgname 0.1 needs GTK+ 2.2.0))
1021 <para>You must add a Makefile.am file:</para>
1023 <programlisting role="C">
1024 bin_PROGRAMS = myprg
1025 myprg_SOURCES = myprg.c foo.c bar.c
1026 INCLUDES = @GTK_CFLAGS@
1029 DISTCLEANFILES = .deps/*.P
1032 <para>If your project contains more than one subdirectory,
1033 you'll have to create one Makefile.am in each directory plus a
1034 master Makefile.am which will look like:</para>
1036 <programlisting role="C">
1037 SUBDIRS = mydir1 mydir2 mydir3
1040 <para>then, to use these, simply type the following
1043 <programlisting role="C">
1047 automake --add-missing --include-deps --foreign
1050 <para>For further information, you should look at the autoconf
1051 and the automake documentation (the shipped info files are
1052 really easy to understand, and there are plenty of web
1053 resources that deal with autoconf and automake).</para>
1057 <!-- ----------------------------------------------------------------- -->
1060 <title>I try to debug my GTK+ application with gdb, but it
1061 hangs my X server when I hit some breakpoint. Any
1062 Idea? <emphasis>[GTK 2.x]</emphasis></title>
1064 <para>From Federico Mena Quintero:</para>
1066 <para><quote>X is not locked up. It is likely that you are hitting a
1067 breakpoint inside a callback that is called from a place in Gtk that has
1068 a mouse grab.</quote></para>
1070 <para><quote>Run your program with the <literal>--sync</literal>
1071 option; it will make it easier to debug. Also, you may want to
1072 use the console for running the debugger, and just let the
1073 program run in another console with the X server.</quote></para>
1075 <para>Eric Mouw had another solution:</para>
1077 <para><quote>An old terminal connected to an otherwise unused serial
1078 port is also great for debugging X programs. Old vt100/vt220
1079 terminals are dirt cheap but a bit hard to get (here in The
1080 Netherlands, YMMV).</quote></para>
1083 Another option is to run your application on Xnest. Xnest is an X server
1084 which displays its root window in a regular window of another X server.
1085 A pointer grab on the Xnest display will not affect the GUI of your debugger
1086 running on your regular X server.
1096 <!-- ***************************************************************** -->
1098 <title>Development with GTK+: general questions</title>
1100 <!-- ----------------------------------------------------------------- -->
1103 <title>What widgets are in GTK?</title>
1105 <para>The GTK+ Tutorial lists the following widgets:</para>
1107 <programlisting role="C">
1118 | | | `GtkAspectFrame
1123 | | | | `GtkCheckMenuItem
1124 | | | | `GtkRadioMenuItem
1128 | | +GtkColorSelectionDialog
1130 | | | `GtkInputDialog
1131 | | `GtkFileSelection
1134 | | | +GtkHButtonBox
1135 | | | `GtkVButtonBox
1140 | | `GtkColorSelection
1143 | | `GtkToggleButton
1157 | +GtkScrolledWindow
1190 <!-- ----------------------------------------------------------------- -->
1193 <title>Is GTK+ thread safe? How do I write multi-threaded GTK+
1194 applications? <emphasis>[GTK 2.x]</emphasis></title>
1196 <para>The GLib library can be used in a thread-safe mode by
1197 calling g_thread_init() before making any other GLib
1198 calls. In this mode GLib automatically locks all internal
1199 data structures as needed. This does not mean that two
1200 threads can simultaneously access, for example, a single hash
1201 table, but they can access two different hash tables
1202 simultaneously. If two different threads need to access the
1203 same hash table, the application is responsible for locking
1206 <para>In order to make GDK thread aware, you also need to
1207 call gdk_threads_init() in conjunction with the above call.
1208 There is a single global
1209 lock that you must acquire with gdk_threads_enter() before
1210 making any GDK calls, and release with gdk_threads_leave()
1211 afterwards throughout your code.</para>
1213 <para>A minimal main program for a threaded GTK+ application
1216 <programlisting role="C">
1218 main (int argc, char *argv[])
1223 g_thread_init(NULL);
1227 gtk_init(&argc, &argv);
1229 window = create_window();
1230 gtk_widget_show(window);
1232 gdk_threads_enter();
1234 gdk_threads_leave();
1240 <para>Callbacks require a bit of attention. Callbacks from
1241 GTK+ (signals) are made within the GTK+ lock. However
1242 callbacks from GLib (timeouts, IO callbacks, and idle
1243 functions) are made outside of the GTK+ lock. So, within a
1244 signal handler you do not need to call gdk_threads_enter(),
1245 but within the other types of callbacks, you do.</para>
1247 <para>Erik Mouw contributed the following code example to
1248 illustrate how to use threads within GTK+ programs.</para>
1250 <programlisting role="C">
1251 /*-------------------------------------------------------------------------
1252 * Filename: gtk-thread.c
1254 * Copyright: Copyright (C) 1999, Erik Mouw
1255 * Author: Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
1256 * Description: GTK threads example.
1257 * Created at: Sun Oct 17 21:27:09 1999
1258 * Modified by: Owen Taylor <otaylor@gtk.org>
1259 * Modified at: Wed May 28 10:43:00 2003
1260 *-----------------------------------------------------------------------*/
1264 * cc -o gtk-thread gtk-thread.c `pkg-config --cflags --libs gtk+-2.0 gthread-2.0`
1266 * Thanks to Sebastian Wilhelmi for pointing out some bugs in earlier versions.
1270 #include <unistd.h>
1271 #include <gtk/gtk.h>
1273 #define YES_IT_IS (1)
1274 #define NO_IT_IS_NOT (0)
1282 G_LOCK_DEFINE_STATIC (yes_or_no);
1283 static volatile int yes_or_no = YES_IT_IS;
1285 void destroy(GtkWidget *widget, gpointer data)
1290 void *argument_thread(void *args)
1292 yes_or_no_args *data = (yes_or_no_args *)args;
1293 gboolean say_something;
1298 sleep(g_random_int_range (1, 4));
1300 /* lock the yes_or_no_variable */
1303 /* do we have to say something? */
1304 say_something = (yes_or_no != data->what);
1308 /* set the variable */
1309 yes_or_no = data->what;
1312 /* Unlock the yes_or_no variable */
1313 G_UNLOCK(yes_or_no);
1317 /* get GTK thread lock */
1318 gdk_threads_enter();
1320 /* set label text */
1321 if(data->what == YES_IT_IS)
1322 gtk_label_set_text(GTK_LABEL(data->label), "O yes, it is!");
1324 gtk_label_set_text(GTK_LABEL(data->label), "O no, it isn't!");
1326 /* Make sure all X commands are sent to the X server; not strictly
1327 * necessary here, but always a good idea when you do anything
1328 * from a thread other than the one where the main loop is running.
1332 /* release GTK thread lock */
1333 gdk_threads_leave();
1340 int main(int argc, char *argv[])
1344 GError *error = NULL;
1345 yes_or_no_args yes_args, no_args;
1348 g_thread_init(NULL);
1352 gtk_init(&argc, &argv);
1354 /* create a window */
1355 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1357 g_signal_connect(window, "destroy",
1358 G_CALLBACK(destroy), NULL);
1360 gtk_container_set_border_width(GTK_CONTAINER (window), 10);
1362 /* create a label */
1363 label = gtk_label_new("And now for something completely different ...");
1364 gtk_container_add(GTK_CONTAINER(window), label);
1366 /* show everything */
1367 gtk_widget_show(label);
1368 gtk_widget_show (window);
1370 /* create the threads */
1371 yes_args.label = label;
1372 yes_args.what = YES_IT_IS;
1373 if (!g_thread_create(argument_thread, &yes_args, FALSE, &error))
1375 g_printerr ("Failed to create YES thread: %s\n", error->message);
1379 no_args.label = label;
1380 no_args.what = NO_IT_IS_NOT;
1381 if (!g_thread_create(argument_thread, &no_args, FALSE, &error))
1383 g_printerr ("Failed to create NO thread: %s\n", error->message);
1387 /* enter the GTK main loop */
1388 gdk_threads_enter();
1390 gdk_threads_leave();
1397 <!-- ----------------------------------------------------------------- -->
1400 <title>I'm doing some stuff with GTK+ in a separate thread, and
1401 properly locking with gdk_threads_enter/gdk_threads_leave()
1402 but the display doesn't update properly. <emphasis>[GTK 2.x]</emphasis>
1405 <para>For efficiency, the X window system batches up commands
1406 and sends them to the X server in batches instead of sending
1407 out immediately.</para>
1409 <para>In a non-multithreaded program, you don't have to worry about
1410 this, since the first thing that happens when control returns
1411 to the main loop is that any outstanding X requests are
1412 sent to the X server.</para>
1414 <para>However, if you are making GTK+ calls from a thread other
1415 than the main loop, then GTK+ doesn't know when to send batched
1416 commands out. For that reason, after making GTK+ calls
1417 in a separate thread, it is usually a good idea to call
1418 gdk_flush() before gdk_thread_leave().</para>
1420 <para>Actually, gdk_flush() is more expensive than is necessary here,
1421 since it waits for the X server to finish outstanding commands
1422 as well; if performance is an issue, you may want to call
1423 XFlush() directly:</para>
1425 <programlisting role="C">
1427 #include <gdk/gdkx.h>
1429 void my_flush_commands (void)
1431 GdkDisplay *display = gdk_display_get_default ();
1432 XFlush (GDK_DISPLAY_XDISPLAY (display);
1438 <!-- ----------------------------------------------------------------- -->
1441 <title>What's an easy way to run a function in the thread with
1442 the main loop? <emphasis>[GTK 2.x]</emphasis></title>
1444 <para>Sometimes the simplest way to set up a threaded program
1445 is to make all the GTK+ calls in a single thread. In such
1446 a program, you should still call g_threads_init(), but
1447 don't need to call gdk_threads_init(), gkd_threads_enter(),
1448 and gdk_threads_leave().</para>
1450 <para>If you set your program up this way, how then do you get
1451 the thread making GTK+ calls and running the main loop
1452 to do something in response to another thread?</para>
1454 <para>An easy way to do it is to take advantage of the fact that
1455 the GLib main loop functions are all thread safe, and can
1456 be called from any thread by adding an idle function
1457 with g_idle_add(). The function provided will be called
1458 at the next opportunity by the main thread. If you want
1459 your function to take priority over event handling and
1460 drawing, you can instead use g_idle_add_full() and pass
1461 in a priority of G_PRIORITY_HIGH.</para>
1465 <!-- ----------------------------------------------------------------- -->
1468 <title>Why does this strange 'x io error' occur when I
1469 <literal>fork()</literal> in my GTK+ app? <emphasis>[GTK 2.x]</emphasis></title>
1471 <para>This is not really a GTK+ problem, and the problem is
1472 not related to <literal>fork()</literal> either. If the 'x io
1473 error' occurs then you probably use the <literal>exit()</literal> function
1474 in order to exit from the child process.</para>
1476 <para>When GDK opens an X display, it creates a socket file
1477 descriptor. When you use the <literal>exit()</literal>
1478 function, you implicitly close all the open file descriptors,
1479 and the underlying X library really doesn't like this.</para>
1481 <para>The right function to use here is
1482 <literal>_exit()</literal>.</para>
1484 <para>Erik Mouw contributed the following code example to
1485 illustrate handling fork() and exit().</para>
1487 <programlisting role="C">
1488 /*-------------------------------------------------------------------------
1489 * Filename: gtk-fork.c
1491 * Copyright: Copyright (C) 1999, Erik Mouw
1492 * Author: Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
1493 * Description: GTK+ fork example
1494 * Created at: Thu Sep 23 21:37:55 1999
1495 * Modified by: Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
1496 * Modified at: Thu Sep 23 22:39:39 1999
1497 * Modified by: Tony Gale <gale@gtk.org>
1498 * Modified at: Wed Jan 14 12:38:00 2004
1499 *-----------------------------------------------------------------------*/
1503 * cc -o gtk-fork gtk-fork.c `pkg-config gtk+-2.0 --cflags --libs`
1507 #include <stdio.h>
1508 #include <stdlib.h>
1509 #include <signal.h>
1510 #include <sys/types.h>
1511 #include <sys/wait.h>
1512 #include <unistd.h>
1513 #include <gtk/gtk.h>
1515 void sigchld_handler(int num)
1517 sigset_t set, oldset;
1519 int status, exitstatus;
1521 /* block other incoming SIGCHLD signals */
1522 sigemptyset(&set);
1523 sigaddset(&set, SIGCHLD);
1524 sigprocmask(SIG_BLOCK, &set, &oldset);
1526 /* wait for child */
1527 while((pid = waitpid((pid_t)-1, &status, WNOHANG)) > 0)
1529 if(WIFEXITED(status))
1531 exitstatus = WEXITSTATUS(status);
1534 "Parent: child exited, pid = %d, exit status = %d\n",
1535 (int)pid, exitstatus);
1537 else if(WIFSIGNALED(status))
1539 exitstatus = WTERMSIG(status);
1542 "Parent: child terminated by signal %d, pid = %d\n",
1543 exitstatus, (int)pid);
1545 else if(WIFSTOPPED(status))
1547 exitstatus = WSTOPSIG(status);
1550 "Parent: child stopped by signal %d, pid = %d\n",
1551 exitstatus, (int)pid);
1556 "Parent: child exited magically, pid = %d\n",
1561 /* re-install the signal handler (some systems need this) */
1562 signal(SIGCHLD, sigchld_handler);
1564 /* and unblock it */
1565 sigemptyset(&set);
1566 sigaddset(&set, SIGCHLD);
1567 sigprocmask(SIG_UNBLOCK, &set, &oldset);
1570 gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
1575 void destroy(GtkWidget *widget, gpointer data)
1580 void fork_me(GtkWidget *widget, gpointer data)
1588 /* ouch, fork() failed */
1595 fprintf(stderr, "Child: pid = %d\n", (int)getpid());
1597 execlp("ls", "ls", "-CF", "/", NULL);
1599 /* if exec() returns, there is something wrong */
1602 /* exit child. note the use of _exit() instead of exit() */
1608 fprintf(stderr, "Parent: forked a child with pid = %d\n", (int)pid);
1612 int main(int argc, char *argv[])
1617 gtk_init(&argc, &argv);
1619 /* the basic stuff: make a window and set callbacks for destroy and
1622 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1624 g_signal_connect(G_OBJECT (window), "delete_event",
1625 G_CALLBACK(delete_event), NULL);
1627 g_signal_connect(G_OBJECT (window), "destroy",
1628 G_CALLBACK(destroy), NULL);
1630 gtk_container_set_border_width(GTK_CONTAINER (window), 10);
1632 /* add a button to do something useful */
1633 button = gtk_button_new_with_label("Fork me!");
1635 g_signal_connect(G_OBJECT (button), "clicked",
1636 G_CALLBACK(fork_me), NULL);
1638 gtk_container_add(GTK_CONTAINER(window), button);
1640 /* show everything */
1641 gtk_widget_show (button);
1642 gtk_widget_show (window);
1645 /* install a signal handler for SIGCHLD signals */
1646 signal(SIGCHLD, sigchld_handler);
1657 <!-- ----------------------------------------------------------------- -->
1660 <title>Why don't the contents of a button move when the button
1661 is pressed? Here's a patch to make it work that way... <emphasis>[GTK 2.x]</emphasis></title>
1663 <para>From: Peter Mattis</para>
1665 <para><quote>The reason buttons don't move their child down and to
1666 the right when they are depressed is because I don't think
1667 that's what is happening visually. My view of buttons is
1668 that you are looking at them straight on. That is, the user
1669 interface lies in a plane and you're above it looking
1670 straight at it. When a button gets pressed it moves directly
1671 away from you. To be absolutely correct I guess the child
1672 should actually shrink a tiny amount. But I don't see why
1673 the child should shift down and to the left. Remember, the
1674 child is supposed to be attached to the buttons surface. Its
1675 not good for it to appear like the child is slipping on the
1676 surface of the button.</quote></para>
1678 <para><quote>On a more practical note, I did implement this at one point
1679 and determined it didn't look good and removed it.</quote></para>
1683 <!-- ----------------------------------------------------------------- -->
1686 <title>How do I identifiy a widgets top level window or other
1687 ancestor? <emphasis>[GTK 2.x]</emphasis></title>
1689 <para>There are a couple of ways to find the top level parent
1690 of a widget. The easiest way is to call the
1691 <literal>gtk_widget_get_toplevel()</literal> function that
1692 returns a pointer to a GtkWidget that is the top level
1695 <para>A more complicated way to do this (but less limited, as
1696 it allows the user to get the closest ancestor of a known type) is to use
1697 <literal>gtk_widget_get_ancestor()</literal> as in:</para>
1699 <programlisting role="C">
1701 widget = gtk_widget_get_ancestor(w, GTK_TYPE_WINDOW);
1704 <para>Since virtually all the GTK_TYPEs can be used as the
1705 second parameter of this function, you can get any parent
1706 widget of a particular widget. Suppose you have an hbox which
1707 contains a vbox, which in turn contains some other atomic
1708 widget (entry, label, etc. To find the master hbox using the
1709 <literal>entry</literal> widget simply use:</para>
1711 <programlisting role="C">
1713 hbox = gtk_widget_get_ancestor(w, GTK_TYPE_HBOX);
1716 <para>You can also follow the a widgets ancestry by using the function
1717 <literal>gtk_widget_get_parent()</literal> that returns a pointer
1718 to a widgets parent widget.</para>
1722 <!-- ----------------------------------------------------------------- -->
1725 <title>How do I get the Window ID of a GtkWindow? <emphasis>[GTK 2.x]</emphasis></title>
1727 <para>The actual Gdk/X window will be created when the widget
1728 gets realized. You can get the Window ID with:</para>
1730 <programlisting role="C">
1731 #include <gdk/gdkx.h>
1733 Window xwin = GDK_WINDOW_XWINDOW (GTK_WIDGET (my_window)->window);
1737 <!-- ----------------------------------------------------------------- -->
1740 <title>How do I catch a double click event? <emphasis>[GTK 2.x]</emphasis></title>
1742 <para>Tim Janik wrote to gtk-list (slightly modified):</para>
1744 <para>Define a signal handler:</para>
1746 <programlisting role="C">
1748 signal_handler_event(GtkWidget *widget, GdkEventButton *event, gpointer func_data)
1750 if (GTK_IS_BUTTON(widget) &&
1751 (event->type==GDK_2BUTTON_PRESS ||
1752 event->type==GDK_3BUTTON_PRESS) ) {
1753 printf("I feel %s clicked with button %d\n",
1754 event->type==GDK_2BUTTON_PRESS ? "double" : "triple",
1761 <para>And connect the handler to your object:</para>
1763 <programlisting role="C">
1765 /* button init stuff */
1767 g_signal_connect(G_OBJECT(button),
1768 "button_press_event",
1769 G_CALLBACK(signal_handler_event),
1774 g_signal_connect(G_OBJECT(button),
1775 "button_release_event",
1776 G_CALLBACK(signal_handler_event),
1779 /* something else */
1783 <para>and, Owen Taylor wrote:</para>
1785 <para><quote>Note that a single button press will be received
1786 beforehand, and if you are doing this for a button, you will
1787 therefore also get a "clicked" signal for the button. (This
1788 is going to be true for any toolkit, since computers aren't
1789 good at reading one's mind.)</quote></para>
1793 <!-- ----------------------------------------------------------------- -->
1796 <title>By the way, what are the differences between signals
1799 <para>First of all, Havoc Pennington gives a rather complete
1800 description of the differences between events and signals in
1801 his free book (two chapters can be found at <ulink
1802 url="http://www106.pair.com/rhp/sample_chapters.html">
1803 http://www106.pair.com/rhp/sample_chapters.html</ulink>).</para>
1805 <para>Moreover, Havoc posted this to the <literal>gtk-list</literal>
1806 <quote>Events are a stream of messages received from the X
1807 server. They drive the Gtk main loop; which more or less
1808 amounts to "wait for events, process them" (not exactly, it
1809 is really more general than that and can wait on many
1810 different input streams at once). Events are a Gdk/Xlib
1811 concept.</quote></para>
1813 <para><quote>Signals are a feature of GtkObject and its subclasses. They
1814 have nothing to do with any input stream; really a signal is just a way
1815 to keep a list of callbacks around and invoke them ("emit" the
1816 signal). There are lots of details and extra features of
1817 course. Signals are emitted by object instances, and are entirely
1818 unrelated to the Gtk main loop. Conventionally, signals are emitted
1819 "when something changes" about the object emitting the
1820 signal.</quote></para>
1822 <para><quote>Signals and events only come together because GtkWidget
1823 happens to emit signals when it gets events. This is purely a
1824 convenience, so you can connect callbacks to be invoked when a
1825 particular widget receives a particular event. There is nothing about
1826 this that makes signals and events inherently related concepts, any more
1827 than emitting a signal when you click a button makes button clicking and
1828 signals related concepts.</quote></para>
1832 <!-- ----------------------------------------------------------------- -->
1835 <title>Data I pass to the <literal>delete_event</literal> (or other event)
1836 handler gets corrupted.</title>
1838 <para>All event handlers take an additional argument which
1839 contains information about the event that triggered the
1840 handler. So, a <literal>delete_event</literal> handler must
1841 be declared as:</para>
1844 <programlisting role="C">
1845 gint delete_event_handler (GtkWidget *widget,
1852 <!-- ----------------------------------------------------------------- -->
1855 <title>I have my signal connected to the the (whatever) event,
1856 but it seems I don't catch it. What's wrong?</title>
1858 <para>There is some special initialisation to do in order to
1859 catch some particular events. In fact, you must set the
1860 correct event mask bit of your widget before getting some
1861 particular events.</para>
1863 <para>For example,</para>
1865 <programlisting role="C">
1866 gtk_widget_add_events(window, GDK_KEY_RELEASE_MASK);
1869 <para>lets you catch the key release events. If you want to
1870 catch every events, simply us the GDK_ALL_EVENTS_MASK event
1873 <para>All the event masks are defined in the
1874 <filename>gdktypes.h</filename> file.</para>
1878 <!-- ----------------------------------------------------------------- -->
1881 <title>I need to add a new signal to a GTK+ widget. Any
1884 <para>If the signal you want to add may be beneficial for
1885 other GTK+ users, you may want to submit a patch that
1886 presents your changes. Check the tutorial for more
1887 information about adding signals to a widget class.</para>
1889 <para>If you don't think it is the case or if your patch is
1890 not applied you'll have to use the
1891 <literal>gtk_object_class_user_signal_new</literal>
1892 function. <literal>gtk_object_class_user_signal_new</literal> allows you
1893 to add a new signal to a predefined GTK+ widget without any
1894 modification of the GTK+ source code. The new signal can be
1895 emited with <literal>g_signal_emit</literal> and can be
1896 handled in the same way as other signals.</para>
1898 <para>Tim Janik posted this code snippet:</para>
1900 <programlisting role="C">
1901 static guint signal_user_action = 0;
1903 signal_user_action =
1904 gtk_object_class_user_signal_new (gtk_type_class (GTK_TYPE_WIDGET),
1906 GTK_RUN_LAST | GTK_RUN_ACTION,
1907 gtk_marshal_NONE__POINTER,
1912 gtk_widget_user_action (GtkWidget *widget,
1915 g_return_if_fail (GTK_IS_WIDGET (widget));
1917 g_signal_emit (widget, signal_user_action, act_data);
1921 <para>If you want your new signal to have more than the
1922 classical gpointer parameter, you'll have to play with GTK+
1927 <!-- ----------------------------------------------------------------- -->
1930 <title>Is it possible to get some text displayed which is
1931 truncated to fit inside its allocation?</title>
1933 <para>GTK's behavior (no clipping) is a consequence of its
1934 attempts to conserve X resources. Label widgets (among
1935 others) don't get their own X window - they just draw their
1936 contents on their parent's window. While it might be possible
1937 to have clipping occur by setting the clip mask before
1938 drawing the text, this would probably cause a substantial
1939 performance penalty.</para>
1941 <para>Its possible that, in the long term, the best solution
1942 to such problems might be just to change gtk to give labels X
1943 windows. A short term workaround is to put the label widget
1944 inside another widget that does get its own window - one
1945 possible candidate would be the viewport widget.</para>
1947 <programlisting role="C">
1948 viewport = gtk_viewport (NULL, NULL);
1949 gtk_widget_set_usize (viewport, 50, 25);
1950 gtk_viewport_set_shadow_type (GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1951 gtk_widget_show(viewport);
1953 label = gtk_label ("a really long label that won't fit");
1954 gtk_container_add (GTK_CONTAINER(viewport), label);
1955 gtk_widget_show (label);
1958 <para>If you were doing this for a bunch of widgets, you might
1959 want to copy gtkviewport.c and strip out the adjustment and
1960 shadow functionality (perhaps you could call it
1964 <!-- ----------------------------------------------------------------- -->
1967 <title>How do I make my window modal? / How do I make a single
1968 window active?</title>
1970 <para>After you create your window, do
1971 <literal>gtk_grab_add(my_window)</literal>. And after closing the window
1972 do <literal>gtk_grab_remove(my_window)</literal>.</para>
1976 <!-- ----------------------------------------------------------------- -->
1979 <title>Why doesn't my widget (e.g. progressbar)
1980 update? <emphasis>[GTK 2.x]</emphasis></title>
1982 <para>You are probably doing all the changes within a function without
1983 returning control to <literal>gtk_main()</literal>. This may
1984 be the case if you do some lengthy calculation in your
1985 code. Most drawing updates are only placed on a queue, which
1986 is processed within <literal>gtk_main()</literal>. You can force the
1987 drawing queue to be processed using something like:</para>
1990 <programlisting role="C">
1991 while (g_main_context_iteration(NULL, FALSE));
1994 <para>inside you're function that changes the widget.</para>
1996 <para>What the above snippet does is run all pending events
1997 and high priority idle functions, then return immediately
1998 (the drawing is done in a high priority idle function).</para>
2002 <!-- ----------------------------------------------------------------- -->
2005 <title>How do I attach data to some GTK+ object/widget?
2006 <emphasis>[GTK 2.x]</emphasis></title>
2008 <para>First of all, the attached data is stored in the
2009 object_data field of a GtkObject. The type of this field is
2010 GData, which is defined in glib.h. So you should read the
2011 gdataset.c file in your glib source directory very
2014 <para>There are two (easy) ways to attach some data to a gtk
2015 object. Using <literal>g_object_set_data()</literal> and
2016 <literal>g_object_get_data()</literal> seems to be the most
2017 common way to do this, as it provides a powerful interface to
2018 connect objects and data.</para>
2020 <programlisting role="C">
2021 void g_object_set_data(GObject *object, const gchar *key, gpointer data);
2023 gpointer g_object_get_data(GObject *object, const gchar *key);
2026 <para>Since a short example is better than any lengthy speech:</para>
2028 <programlisting role="C">
2029 struct my_struct p1,p2,*result;
2032 g_object_set_data(G_OBJECT(w),"p1 data",(gpointer)&p1);
2033 g_object_set_data(G_OBJECT(w),"p2 data",(gpointer)&p2);
2035 result = g_object_get_data(G_OBJECT(w),"p1 data");
2038 <para>The <literal>gtk_object_set_user_data()</literal> and
2039 <literal>gtk_object_get_user_data()</literal> functions does
2040 exactly the same thing as the functions above, but does not
2041 let you specify the "key" parameter.Instead, it uses a
2042 standard "user_data" key. Note that the use of these functions
2043 is deprecated in 1.2. They only provide a compatibility mode
2044 with some old gtk packages.</para>
2048 <!-- ----------------------------------------------------------------- -->
2051 <title>How do I remove the data I have attached to an
2054 <para>When attaching the data to the object, you can use the
2055 <literal>gtk_object_set_data_full()</literal> function. The three
2056 first arguments of the function are the same as in
2057 <literal>gtk_object_set_data()</literal>. The fourth one is a
2058 pointer to a callback function which is called when the data
2059 is destroyed. The data is destroyed when you:</para>
2062 <listitem><simpara> destroy the object</simpara>
2065 <listitem><simpara> replace the data with a new one (with
2066 the same key)</simpara>
2069 <listitem><simpara> replace the data with NULL (with the
2077 <!-- ----------------------------------------------------------------- -->
2080 <title>How do I reparent a widget?</title>
2082 <para>The normal way to reparent (ie change the owner) of a
2083 widget should be to use the function:</para>
2085 <programlisting role="C">
2086 void gtk_widget_reparent (GtkWidget *widget,
2087 GtkWidget *new_parent)
2090 <para>But this is only a "should be" since this function does
2091 not correctly do its job on some specific widgets. The main
2092 goal of gtk_widget_reparent() is to avoid unrealizing widget
2093 if both widget and new_parent are realized (in this case,
2094 widget->window is successfully reparented). The problem here
2095 is that some widgets in the GTK+ hierarchy have multiple
2096 attached X subwindows and this is notably the case for the
2097 GtkSpinButton widget. For those, gtk_widget_reparent() will
2098 fail by leaving an unrealized child window where it should
2101 <para>To avoid this problem, simply use the following code
2104 <programlisting role="C">
2105 g_object_ref(widget);
2106 gtk_container_remove(GTK_CONTAINER(old_parent), widget);
2107 gtk_container_add(GTK_CONTAINER(new_parent), widget);
2108 g_object_unref(widget);
2113 <!-- ----------------------------------------------------------------- -->
2116 <title>How could I get any widgets position?</title>
2118 <para>As Tim Janik pointed out, there are different cases, and
2119 each case requires a different solution.</para>
2122 <listitem><simpara> If you want the position of a widget
2123 relative to its parent, you should use
2124 <literal>widget->allocation.x</literal> and
2125 <literal>widget->allocation.y</literal>.</simpara>
2128 <listitem><simpara> If you want the position of a window
2129 relative to the X root window, you should use
2130 <literal>gdk_window_get_geometry()</literal>
2131 <literal>gdk_window_get_position()</literal> or
2132 <literal>gdk_window_get_origin()</literal>.</simpara>
2135 <listitem><simpara> If you want to get the position of the
2136 window (including the WM decorations), you should use
2137 <literal>gdk_window_get_root_origin()</literal>.</simpara>
2140 <listitem><simpara> Last but not least, if you want to get a Window
2141 Manager frame position, you should use
2142 <literal>gdk_window_get_deskrelative_origin()</literal>.</simpara>
2146 <para>Your choice of Window Manager will have an effect of the
2147 results of the above functions. You should keep this in mind
2148 when writing your application. This is dependant upon how the
2149 Window Managers manage the decorations that they add around
2154 <!-- ----------------------------------------------------------------- -->
2157 <title>How do I set the size of a widget/window? How do I
2158 prevent the user resizing my window? <emphasis>[GTK 2.x]</emphasis></title>
2160 <para>The <literal>gtk_widget_set_size_request()</literal> function
2161 is used to set the size of a widget to a specific size.
2164 <literal>gtk_window_set_resizable()</literal> function sets whether
2165 the user can resize a window, which they can by default. The
2166 definition of these functions are:</para>
2168 <programlisting role="C">
2169 void gtk_widget_set_size_request (GtkWidget *widget,
2173 void gtk_window_set_resizable (GtkWindow *window,
2174 gboolean resizable);
2180 <!-- ----------------------------------------------------------------- -->
2183 <title>How do I add a popup menu to my GTK+ application?</title>
2185 <para>The <literal>menu</literal> example in the examples/menu
2186 directory of the GTK+ distribution implements a popup menu
2187 with this technique:</para>
2189 <programlisting role="C">
2190 static gint button_press (GtkWidget *widget, GdkEvent *event)
2193 if (event->type == GDK_BUTTON_PRESS) {
2194 GdkEventButton *bevent = (GdkEventButton *) event;
2195 gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
2196 bevent->button, bevent->time);
2197 /* Tell calling code that we have handled this event; the buck
2202 /* Tell calling code that we have not handled this event; pass it on. */
2209 <!-- ----------------------------------------------------------------- -->
2212 <title>How do I disable or enable a widget, such as a
2215 <para>To disable (or to enable) a widget, use the
2216 <literal>gtk_widget_set_sensitive()</literal> function. The
2217 first parameter is you widget pointer. The second parameter is
2218 a boolean value: when this value is TRUE, the widget is
2222 <!-- ----------------------------------------------------------------- -->
2225 <title>Shouldn't the text argument in the gtk_clist_*
2226 functions be declared const?</title>
2228 <para>For example:</para>
2230 <programlisting role="C">
2231 gint gtk_clist_prepend (GtkCList *clist,
2235 <para>Answer: No, while a type "gchar*" (pointer to char) can
2236 automatically be cast into "const gchar*" (pointer to const
2237 char), this does not apply for "gchar *[]" (array of an
2238 unspecified number of pointers to char) into "const gchar *[]"
2239 (array of an unspecified number of pointers to const char).</para>
2241 <para>The type qualifier "const" may be subject to automatic
2242 casting, but in the array case, it is not the array itself
2243 that needs the (const) qualified cast, but its members, thus
2244 changing the whole type.</para>
2247 <!-- ----------------------------------------------------------------- -->
2250 <title>How do I render pixels (image data) to the
2253 <para>There are several ways to approach this. The simplest
2254 way is to use GdkRGB, see gdk/gdkrgb.h. You create an RGB
2255 buffer, render to your RGB buffer, then use GdkRGB routines to
2256 copy your RGB buffer to a drawing area or custom widget. The
2257 book "GTK+/Gnome Application Development" gives some details;
2258 GdkRGB is also documented in the GTK+ reference
2259 documentation.</para>
2261 <para>If you're writing a game or other graphics-intensive
2262 application, you might consider a more elaborate
2263 solution. OpenGL is the graphics standard that will let you
2264 access hardware accelaration in future versions of XFree86; so
2265 for maximum speed, you probably want to use OpenGL. A
2266 GtkGLArea widget is available for using OpenGL with GTK+ (but
2267 GtkGLArea does not come with GTK+ itself). There are also
2268 several open source game libraries, such as ClanLib and Loki's
2269 Simple DirectMedia Layer library (SDL).</para>
2271 <para>You do NOT want to use
2272 <literal>gdk_draw_point()</literal>, that will be extremely
2276 <!-- ----------------------------------------------------------------- -->
2279 <title>How do I create a pixmap without having my window being
2280 realized/shown?</title>
2282 <para>Functions such as
2283 <literal>gdk_pixmap_create_from_xpm()</literal> require a
2284 valid window as a parameter. During the initialisation phase
2285 of an application, a valid window may not be available without
2286 showing a window, which may be inappropriate. In order to
2287 avoid this, a function such as
2288 <literal>gdk_pixmap_colormap_create_from_xpm</literal> can be
2291 <programlisting role="C">
2292 char *pixfile = "foo.xpm";
2293 GtkWidget *top, *box, *pixw;
2294 GdkPixmap *pixmap, *pixmap_mask;
2296 top = gtk_window_new (GKT_WINDOW_TOPLEVEL);
2297 box = gtk_hbox_new (FALSE, 4);
2298 gtk_conainer_add (GTK_CONTAINER(top), box);
2300 pixmap = gdk_pixmap_colormap_create_from_xpm (
2301 NULL, gtk_widget_get_colormap(top),
2302 &pixmap_mask, NULL, pixfile);
2303 pixw = gtk_pixmap_new (pixmap, pixmap_mask);
2304 g_object_unref (pixmap);
2305 g_object_unref (pixmap_mask);
2310 <!-- ----------------------------------------------------------------- -->
2313 <title>How do I do drag-and-drop?</title>
2315 <para>GTK+ has a high level set of functions for doing inter-process
2316 communication via the drag-and-drop system. GTK+ can perform
2317 drag-and-drop on top of the low level Xdnd and Motif drag-and-drop
2320 <para>The documentation on GTK+ drag-and-drop isn't complete, but there
2321 is some information in the <ulink
2322 url="http://www.gtk.org/tutorial/">Tutorial</ulink>. You should also
2323 look at the drag-and-drop example code that is part of the GTK+ source
2324 distribution, in the file <filename>gtk/testdnd.c</filename>.</para>
2328 <!-- ----------------------------------------------------------------- -->
2331 <title>Why does GTK+/GLib leak memory?</title>
2333 <para>It doesn't. Both GLib and the C library (malloc implementation)
2334 will cache allocated memory on occasion, even if you free it with
2337 <para>So you can't generally use tools such as top to see if you are
2338 using free() properly (aside from the very roughest of estimations, i.e.
2339 if you are really, really screwing up top will show that, but you can't
2340 distinguish small mistakes from the GLib/malloc caches).</para>
2342 <para>In order to find memory leaks, use proper memory profiling
2349 <!-- ***************************************************************** -->
2351 <title>Development with GTK+: widget specific questions</title>
2353 <!-- ----------------------------------------------------------------- -->
2356 <title>How do I find out about the selection of a GtkList?</title>
2358 <para>Get the selection something like this:</para>
2360 <programlisting role="C">
2362 sel = GTK_LIST(list)->selection;
2365 <para>This is how GList is defined (quoting glist.h):</para>
2367 <programlisting role="C">
2368 typedef struct _GList GList;
2378 <para>A GList structure is just a simple structure for doubly
2379 linked lists. There exist several g_list_*() functions to
2380 modify a linked list in glib.h. However the
2381 GTK_LIST(MyGtkList)->selection is maintained by the
2382 gtk_list_*() functions and should not be modified.</para>
2385 <para>The selection_mode of the GtkList determines the
2386 selection facilities of a GtkList and therefore the contents
2387 of GTK_LIST(AnyGtkList)->selection:</para>
2389 <informaltable frame="all">
2393 <entry><literal>selection_mode</literal></entry>
2394 <entry><literal> GTK_LIST()->selection</literal>
2401 <entry><literal>GTK_SELECTION_SINGLE</literal></entry>
2402 <entry>selection is either NULL or contains a GList*
2403 pointer for a single selected item.</entry>
2407 <entry><literal>GTK_SELECTION_BROWSE</literal></entry>
2408 <entry>selection is NULL if the list contains no
2409 widgets, otherwise it contains a GList*
2410 pointer for one GList structure.</entry>
2414 <entry><literal>GTK_SELECTION_MULTIPLE</literal></entry>
2415 <entry>selection is NULL if no listitems are selected
2416 or a a GList* pointer for the first selected
2417 item. that in turn points to a GList structure
2418 for the second selected item and so
2423 <entry><literal>GTK_SELECTION_EXTENDED</literal></entry>
2424 <entry>selection is NULL.</entry>
2431 <para>The data field of the GList structure
2432 GTK_LIST(MyGtkList)->selection points to the first
2433 GtkListItem that is selected. So if you would like to
2434 determine which listitems are selected you should go like
2437 <programlisting role="C">
2439 gchar *list_items[]={
2445 guint nlist_items=sizeof(list_items)/sizeof(list_items[0]);
2446 GtkWidget *list_item;
2449 list=gtk_list_new();
2450 gtk_list_set_selection_mode(GTK_LIST(list), GTK_SELECTION_MULTIPLE);
2451 gtk_container_add(GTK_CONTAINER(AnyGtkContainer), list);
2452 gtk_widget_show (list);
2454 for (i = 0; i < nlist_items; i++)
2456 list_item=gtk_list_item_new_with_label(list_items[i]);
2457 gtk_object_set_user_data(GTK_OBJECT(list_item), (gpointer)i);
2458 gtk_container_add(GTK_CONTAINER(list), list_item);
2459 gtk_widget_show(list_item);
2464 <para>To get known about the selection:</para>
2466 <programlisting role="C">
2470 items=GTK_LIST(list)->selection;
2472 printf("Selected Items: ");
2474 if (GTK_IS_LIST_ITEM(items->data))
2475 printf("%d ", (guint)
2476 gtk_object_get_user_data(items->data));
2485 <!-- ----------------------------------------------------------------- -->
2488 <title>How do I stop the column headings of a GtkCList
2489 disappearing when the list is scrolled?</title>
2491 <para>This happens when a GtkCList is packed into a
2492 GtkScrolledWindow using the function
2493 <literal>gtk_scroll_window_add_with_viewport()</literal>. The prefered
2494 method of adding a CList to a scrolled window is to use the
2495 function <literal>gtk_container_add</literal>, as in:</para>
2497 <programlisting role="C">
2498 GtkWidget *scrolled, *clist;
2499 char *titles[] = { "Title1" , "Title2" };
2501 scrolled = gtk_scrolled_window_new(NULL, NULL);
2503 clist = gtk_clist_new_with_titles(2, titles);
2504 gtk_container_add(GTK_CONTAINER(scrolled), clist);
2509 <!-- ----------------------------------------------------------------- -->
2512 <title>I don't want the user of my applications to enter text
2513 into a GtkCombo. Any idea?</title>
2515 <para>A GtkCombo has an associated entry which can be accessed
2516 using the following expression:</para>
2518 <programlisting role="C">
2519 GTK_COMBO(combo_widget)->entry
2522 <para>If you don't want the user to be able to modify the
2523 content of this entry, you can use the
2524 gtk_editable_set_editable() function:</para>
2527 <programlisting role="C">
2528 void gtk_editable_set_editable (GtkEditable *editable,
2529 gboolean is_editable);
2532 <para>Set the is_editable parameter to FALSE to disable typing
2533 into the entry.</para>
2536 <!-- ----------------------------------------------------------------- -->
2539 <title>How do I catch a combo box change?</title>
2541 <para>The entry which is associated to your GtkCombo send a
2542 "changed" signal when:</para>
2545 <listitem><simpara>some text is typed in</simpara>
2548 <listitem><simpara>the selection of the combo box is changed</simpara>
2552 <para>To catch any combo box change, simply connect your
2553 signal handler with</para>
2555 <programlisting role="C">
2556 g_signal_connect(GTK_COMBO(cb)->entry,
2558 G_CALLBACK(my_cb_change_handler),
2564 <!-- ----------------------------------------------------------------- -->
2567 <title>How can I define a separation line in a menu?</title>
2569 <para>See the <ulink
2570 url="http://www.gtk.org/tutorial/">Tutorial</ulink> for
2571 information on how to create menus. However, to create a
2572 separation line in a menu, just insert an empty menu item:</para>
2574 <programlisting role="C">
2575 menuitem = gtk_menu_item_new();
2576 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
2577 gtk_widget_show(menuitem);
2582 <!-- ----------------------------------------------------------------- -->
2585 <title>How can I right justify a menu, such as Help?</title>
2587 <para>Depending on if you use the MenuFactory or not, there
2588 are two ways to proceed. With the MenuFactory, use something
2589 like the following:</para>
2591 <programlisting role="C">
2592 menu_path = gtk_menu_factory_find (factory, "<MyApp>/Help");
2593 gtk_menu_item_right_justify(menu_path->widget);
2596 <para>If you do not use the MenuFactory, you should simply
2600 <programlisting role="C">
2601 gtk_menu_item_right_justify(my_menu_item);
2606 <!-- ----------------------------------------------------------------- -->
2609 <title>How do I add some underlined accelerators to menu
2612 <para>Damon Chaplin, the technical force behind the Glade
2613 project, provided the following code sample (this code is an
2614 output from Glade). It creates a small <GUIMenu>File</guimenu> menu item
2615 with only one child (<guimenu>New</guimenu>). The F in
2616 <guimenu>File</guimenu> and the N in <guimenu>New</guimenu> are
2617 underlined, and the relevant accelerators are created.</para>
2619 <programlisting role="C">
2620 menubar1 = gtk_menu_bar_new ();
2621 gtk_object_set_data (GTK_OBJECT (window1), "menubar1", menubar1);
2622 gtk_widget_show (menubar1);
2623 gtk_box_pack_start (GTK_BOX (vbox1), menubar1, FALSE, FALSE, 0);
2625 file1 = gtk_menu_item_new_with_label ("");
2626 gtk_label_set_use_underline (GTK_LABEL (gtk_bin_get_child (GTK_BIN (file1))),
2628 gtk_widget_add_accelerator (file1, "activate_item", accel_group,
2629 tmp_key, GDK_MOD1_MASK, 0);
2630 gtk_object_set_data (GTK_OBJECT (window1), "file1", file1);
2631 gtk_widget_show (file1);
2632 gtk_container_add (GTK_CONTAINER (menubar1), file1);
2634 file1_menu = gtk_menu_new ();
2635 file1_menu_accels = gtk_menu_ensure_uline_accel_group (GTK_MENU (file1_menu));
2636 gtk_object_set_data (GTK_OBJECT (window1), "file1_menu", file1_menu);
2637 gtk_menu_item_set_submenu (GTK_MENU_ITEM (file1), file1_menu);
2639 new1 = gtk_menu_item_new_with_label ("");
2640 gtk_label_set_use_underline (GTK_LABEL (gtk_bin_get_child (GTK_BIN (new1))),
2642 gtk_widget_add_accelerator (new1, "activate_item", file1_menu_accels,
2644 gtk_object_set_data (GTK_OBJECT (window1), "new1", new1);
2645 gtk_widget_show (new1);
2646 gtk_container_add (GTK_CONTAINER (file1_menu), new1);
2651 <!-- ----------------------------------------------------------------- -->
2654 <title>How can I retrieve the text from a GtkMenuItem?</title>
2656 <para>You can usually retrieve the label of a specific
2657 GtkMenuItem with:</para>
2659 <programlisting role="C">
2660 if (GTK_BIN (menu_item)->child)
2662 GtkWidget *child = GTK_BIN (menu_item)->child;
2664 /* do stuff with child */
2665 if (GTK_IS_LABEL (child))
2669 text = gtk_label_get_text (GTK_LABEL (child));
2670 g_print ("menu item text: %s\n", text);
2675 <para>To get the active menu item from a GtkOptionMenu you can
2678 <programlisting role="C">
2679 if (GTK_OPTION_MENU (option_menu)->menu_item)
2681 GtkWidget *menu_item = GTK_OPTION_MENU (option_menu)->menu_item;
2685 <para>But, there's a catch. For this specific case, you can
2686 <emphasis>not</emphasis> get the label widget from
2687 <literal>menu_item</literal> with the above code, because the
2688 option menu reparents the menu_item's child temporarily to
2689 display the currently active contents. So to retrive the child
2690 of the currently active menu_item of an option menu, you'll
2693 <programlisting role="C">
2694 if (GTK_BIN (option_menu)->child)
2696 GtkWidget *child = GTK_BIN (option_menu)->child;
2698 /* do stuff with child */
2704 <!-- ----------------------------------------------------------------- -->
2707 <title>How do I right (or otherwise) justify a
2710 <para>Are you sure you want to <emphasis>justify</emphasis>
2711 the labels? The label class contains the
2712 <literal>gtk_label_set_justify()</literal> function that is
2713 used to control the justification of a multi-line
2716 <para>What you probably want is to set the <emphasis>alignment</emphasis>
2717 of the label, ie right align it, center it or left align
2718 it. If you want to do this, you should use:</para>
2720 <programlisting role="C">
2721 void gtk_misc_set_alignment (GtkMisc *misc,
2726 <para>where the <literal>xalign</literal> and
2727 <literal>yalign</literal> values are floats in
2730 <programlisting role="C">
2733 /* horizontal : left align, vertical : top */
2734 gtk_misc_set_alignment(GTK_MISC(label), 0.0f, 0.0f);
2736 /* horizontal : centered, vertical : centered */
2737 gtk_misc_set_alignment(GTK_MISC(label), 0.5f, 0.5f);
2739 /* horizontal : right align, vertical : bottom */
2740 gtk_misc_set_alignment(GTK_MISC(label), 1.0f, 1.0f);
2745 <!-- ----------------------------------------------------------------- -->
2748 <title>How do I set the background color of a GtkLabel
2751 <para>The GtkLabel widget is one of a few GTK+ widgets that
2752 don't create their own window to render themselves
2753 into. Instead, they draw themselves directly onto their
2754 parents window.</para>
2756 <para>This means that in order to set the background color for
2757 a GtkLabel widget, you need to change the background color of
2758 its parent, i.e. the object that you pack it into.</para>
2762 <!-- ----------------------------------------------------------------- -->
2765 <title>How do I set the color and font of a GtkLabel using a
2766 Resource File?</title>
2768 <para>The widget name path constructed for a Label consists of
2769 the widget names of its object hierarchy as well, e.g.</para>
2771 <para><literallayout>
2772 <literal>window (name: humphrey)</literal>
2773 <literal> hbox</literal>
2774 <literal> label (name: mylabel)</literal>
2775 </literallayout></para>
2777 <para>The widget path your pattern needs to match would be:
2778 <literal>humphrey.GtkHBox.mylabel</literal></para>
2780 <para>The resource file may look something like:</para>
2782 <programlisting role="C">
2785 fg[NORMAL] = {1.0, 0.0, 0.0}
2786 font = "-adobe-helvetica-bold-r-normal--*-140-*-*-*-*-*-*"
2788 widget "*mylabel" style "title"
2791 <para>In your program, you would also need to give a name to
2792 the Label widget, which can be done using:</para>
2794 <programlisting role="C">
2795 label = gtk_label_new("Some Label Text");
2796 gtk_widget_set_name(label, "mylabel");
2797 gtk_widget_show(label);
2802 <!-- ----------------------------------------------------------------- -->
2805 <title>How do I configure Tooltips in a Resource File?</title>
2807 <para>The tooltip's window is named "gtk-tooltips",
2808 GtkTooltips in itself is not a GtkWidget (though a GtkObject)
2809 and as such is not attempted to match any widget styles.</para>
2811 <para>So, your resource file should look something like:</para>
2813 <programlisting role="C">
2816 bg[NORMAL] = {1.0, 1.0, 0.0}
2818 widget "gtk-tooltips*" style "postie"
2823 <!-- ----------------------------------------------------------------- -->
2826 <title>I can't add more than (something like) 2000 chars in a
2827 GtkEntry. What's wrong?</title>
2829 <para>There is now a known problem in the GtkEntry widget. In
2830 the <literal>gtk_entry_insert_text()</literal> function, the
2831 following lines limit the number of chars in the entry to
2834 <programlisting role="C">
2835 /* The algorithms here will work as long as, the text size (a
2836 * multiple of 2), fits into a guint16 but we specify a shorter
2837 * maximum length so that if the user pastes a very long text, there
2838 * is not a long hang from the slow X_LOCALE functions. */
2840 if (entry->text_max_length == 0)
2843 max_length = MIN (2047, entry->text_max_length);
2848 <!-- ----------------------------------------------------------------- -->
2851 <title>How do I make a GtkEntry widget activate on pressing
2852 the Return key?</title>
2854 <para>The Entry widget emits an 'activate' signal when you
2855 press return in it. Just attach to the activate signal on the
2856 entry and do whatever you want to do. Typical code would
2859 <programlisting role="C">
2860 entry = gtk_entry_new();
2861 g_signal_connect (entry, "activate",
2862 G_CALLBACK(entry_callback),
2868 <!-- ----------------------------------------------------------------- -->
2871 <title>How do I validate/limit/filter the input to a GtkEntry? <emphasis>[GTK 2.x]</emphasis></title>
2873 <para>If you want to validate the text that a user enters into
2874 a GtkEntry widget you can attach to the "insert_text" signal
2875 of the entry, and modify the text within the callback
2876 function. The example below forces all characters to
2877 uppercase, and limits the range of characters to A-Z. Note
2878 that the entry is cast to an object of type GtkEditable, from
2879 which GtkEntry is derived.</para>
2881 <programlisting role="C">
2882 #include <ctype.h>
2883 #include <gtk/gtk.h>
2885 void insert_text_handler (GtkEntry *entry,
2891 GtkEditable *editable = GTK_EDITABLE(entry);
2893 gchar *result = g_new (gchar, length);
2895 for (i=0; i < length; i++) {
2896 if (!isalpha(text[i]))
2898 result[count++] = islower(text[i]) ? toupper(text[i]) : text[i];
2902 g_signal_handlers_block_by_func (G_OBJECT (editable),
2903 G_CALLBACK (insert_text_handler),
2905 gtk_editable_insert_text (editable, result, count, position);
2906 g_signal_handlers_unblock_by_func (G_OBJECT (editable),
2907 G_CALLBACK (insert_text_handler),
2910 g_signal_stop_emission_by_name (G_OBJECT (editable), "insert_text");
2921 gtk_init (&argc, &argv);
2923 /* create a new window */
2924 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2925 gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
2926 g_signal_connect (G_OBJECT (window), "destroy",
2927 G_CALLBACK (gtk_main_quit),
2930 entry = gtk_entry_new();
2931 g_signal_connect(G_OBJECT(entry), "insert_text",
2932 G_CALLBACK(insert_text_handler),
2934 gtk_container_add(GTK_CONTAINER (window), entry);
2935 gtk_widget_show(entry);
2937 gtk_widget_show(window);
2946 <!-- ----------------------------------------------------------------- -->
2949 <title>How do I use horizontal scrollbars with a GtkText widget?</title>
2951 <para>The short answer is that you can't. The current version
2952 of the GtkText widget does not support horizontal
2953 scrolling. There is an intention to completely rewrite the
2954 GtkText widget, at which time this limitation will be
2959 <!-- ----------------------------------------------------------------- -->
2962 <title>How do I change the font of a GtkText widget?</title>
2964 <para>There are a couple of ways of doing this. As GTK+ allows
2965 the appearance of applications to be changed at run time using
2966 resources you can use something like the following in the
2967 appropriate file:</para>
2969 <programlisting role="C">
2972 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
2976 <para>Another way to do this is to load a font within your
2977 program, and then use this in the functions for adding text to
2978 the text widget. You can load a font using, for example:</para>
2980 <programlisting role="C">
2982 font = gdk_font_load("-adobe-helvetica-medium-r-normal--*-140-*-*-*-*-*-*");
2987 <!-- ----------------------------------------------------------------- -->
2990 <title>How do I set the cursor position in a GtkText
2993 <para>Notice that the response is valid for any object that
2994 inherits from the GtkEditable class.</para>
2996 <para>Are you sure that you want to move the cursor position?
2997 Most of the time, while the cursor position is good, the
2998 insertion point does not match the cursor position. If this
2999 apply to what you really want, then you should use the
3000 <literal>gtk_text_set_point()</literal> function. If you want
3001 to set the insertion point at the current cursor position, use
3002 the following:</para>
3004 <programlisting role="C">
3005 gtk_text_set_point(GTK_TEXT(text),
3006 gtk_editable_get_position(GTK_EDITABLE(text)));
3009 <para>If you want the insertion point to follow the cursor at
3010 all time, you should probably catch the button press event,
3011 and then move the insertion point. Be careful : you'll have to
3012 catch it after the widget has changed the cursor position
3013 though. Thomas Mailund Jensen proposed the following
3016 <programlisting role="C">
3018 insert_bar (GtkWidget *text)
3020 /* jump to cursor mark */
3021 gtk_text_set_point (GTK_TEXT (text),
3022 gtk_editable_get_position (GTK_EDITABLE (text)));
3024 gtk_text_insert (GTK_TEXT (text), NULL, NULL, NULL,
3025 "bar", strlen ("bar"));
3029 main (int argc, char *argv[])
3031 GtkWidget *window, *text;
3033 gtk_init (&argc, &argv);
3035 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3036 text = gtk_text_new (NULL, NULL);
3037 gtk_text_set_editable (GTK_TEXT (text), TRUE);
3038 gtk_container_add (GTK_CONTAINER (window), text);
3040 /* connect after everything else */
3041 g_signal_connect_after (text, "button_press_event",
3042 G_CALLBACK (insert_bar), NULL);
3044 gtk_widget_show_all(window);
3051 <para>Now, if you really want to change the cursor position,
3053 <literal>gtk_editable_set_position()</literal>
3060 <!-- ***************************************************************** -->
3062 <title>About GDK</title>
3064 <!-- ----------------------------------------------------------------- -->
3067 <title>What is GDK?</title>
3069 <para>GDK is basically a wrapper around the standard Xlib
3070 function calls. If you are at all familiar with Xlib, a lot of
3071 the functions in GDK will require little or no getting used
3072 to. All functions are written to provide an way to access Xlib
3073 functions in an easier and slightly more intuitive manner. In
3074 addition, since GDK uses GLib (see below), it will be more
3075 portable and safer to use on multiple platforms.</para>
3077 <!-- Examples, anybody? I've been mulling some over. NF -->
3081 <!-- ----------------------------------------------------------------- -->
3084 <title>How do I use color allocation?</title>
3086 <para>One of the nice things about GDK is that it's based on
3087 top of Xlib; this is also a problem, especially in the area of
3088 color management. If you want to use color in your program
3089 (drawing a rectangle or such, your code should look something
3092 <programlisting role="C">
3101 /* first, create a GC to draw on */
3102 gc = gdk_gc_new(widget->window);
3104 /* find proper dimensions for rectangle */
3105 gdk_window_get_size(widget->window, &width, &height);
3107 /* the color we want to use */
3108 color = (GdkColor *)malloc(sizeof(GdkColor));
3110 /* red, green, and blue are passed values, indicating the RGB triple
3111 * of the color we want to draw. Note that the values of the RGB components
3112 * within the GdkColor are taken from 0 to 65535, not 0 to 255.
3114 color->red = red * (65535/255);
3115 color->green = green * (65535/255);
3116 color->blue = blue * (65535/255);
3118 /* the pixel value indicates the index in the colormap of the color.
3119 * it is simply a combination of the RGB values we set earlier
3121 color->pixel = (gulong)(red*65536 + green*256 + blue);
3123 /* However, the pixel valule is only truly valid on 24-bit (TrueColor)
3124 * displays. Therefore, this call is required so that GDK and X can
3125 * give us the closest color available in the colormap
3127 gdk_color_alloc(gtk_widget_get_colormap(widget), color);
3129 /* set the foreground to our color */
3130 gdk_gc_set_foreground(gc, color);
3132 /* draw the rectangle */
3133 gdk_draw_rectangle(widget->window, gc, 1, 0, 0, width, height);
3143 <!-- ***************************************************************** -->
3145 <title>About GLib</title>
3147 <!-- ----------------------------------------------------------------- -->
3150 <title>What is GLib?</title>
3152 <para>GLib is a library of useful functions and definitions
3153 available for use when creating GDK and GTK applications. It
3154 provides replacements for some standard libc functions, such
3155 as malloc, which are buggy on some systems.</para>
3157 <para>It also provides routines for handling:</para>
3159 <itemizedlist spacing=compact>
3160 <listitem><simpara>Doubly Linked Lists</simpara>
3163 <listitem><simpara>Singly Linked Lists</simpara>
3166 <listitem><simpara>Timers</simpara>
3169 <listitem><simpara>String Handling</simpara>
3172 <listitem><simpara>A Lexical Scanner</simpara>
3175 <listitem><simpara>Error Functions</simpara>
3181 <!-- ----------------------------------------------------------------- -->
3184 <title>How can I use the doubly linked lists?</title>
3186 <para>The GList object is defined as:</para>
3188 <programlisting role="C">
3189 typedef struct _GList GList;
3199 <para>To use the GList objects, simply:</para>
3201 <programlisting role="C">
3204 gint array[] = { 1, 2, 3, 4, 5, 6 };
3208 /* add data to the list */
3209 for (pos=0;pos < sizeof array; pos++) {
3210 list = g_list_append(list, (gpointer)&array[pos]);
3213 /* run through the list */
3214 listrunner = g_list_first(list);
3215 while (listrunner) {
3216 value = (gint *)listrunner->data;
3217 printf("%d\n", *value);
3218 listrunner = g_list_next(listrunner);
3221 /* removing datas from the list */
3222 listrunner = g_list_first(list);
3223 list = g_list_remove_link(list, listrunner);
3224 list = g_list_remove(list, &array[4]);
3227 <para>The same code is usable with singly linked lists (GSList
3228 objects) by replacing g_list_* functions with the relevant
3229 g_slist_* ones (g_slist_append, g_slist_remove, ...). Just
3230 remember that since you can't go backward in a singly linked
3231 list, there is no g_slist_first function - you'll need to keep
3232 a reference on the first node of the list.</para>
3234 <!-- Some Examples might be useful here! NF -->
3235 <!-- I believe it should be better :) ED -->
3236 <!-- Linked lists are pretty standard data structures - don't want to
3237 over do it - TRG -->
3241 <!-- ----------------------------------------------------------------- -->
3244 <title>Memory does not seem to be released when I free the
3245 list nodes I've allocated</title>
3247 <para>GLib tries to be "intelligent" on this special issue: it
3248 assumes that you are likely to reuse the objects, so caches
3249 the allocated memory. If you do not want to use this behavior,
3250 you'll probably want to set up a special allocator.</para>
3252 <para>To quote Tim Janik:</para>
3253 <para><quote>If you have a certain portion of code that uses *lots*
3254 of GLists or GNodes, and you know you'd better want to release
3255 all of them after a short while, you'd want to use a
3256 GAllocator. Pushing an allocator into g_list will make all
3257 subsequent glist operations private to that allocator's memory
3258 pool (and thus you have to take care to pop the allocator
3259 again, before making any external calls): </quote></para>
3261 <programlisting role="C">
3262 GAllocator *allocator;
3266 /* set a new allocation pool for GList nodes */
3267 allocator = g_allocator_new ("list heap", 1024);
3268 g_list_push_allocator (allocator);
3270 /* do some list operations */
3271 for (i = 0; i < 4096; i++)
3272 list = g_list_prepend (list, NULL);
3273 list = g_list_reverse (list);
3275 /* beware to pop allocator befor calling external functions */
3276 g_list_pop_allocator ();
3277 gtk_label_set_text (GTK_LABEL (some_label), "some text");
3279 /* and set our private glist pool again */
3280 g_list_push_allocator (allocator);
3282 /* do some list operations */
3285 for (i = 0; i < 4096; i++)
3286 list = g_list_prepend (list, NULL);
3288 /* and back out (while freeing all of the list nodes in our pool) */
3289 g_list_pop_allocator ();
3290 g_allocator_free (allocator);
3295 <!-- ----------------------------------------------------------------- -->
3298 <title>Why use g_print, g_malloc, g_strdup and fellow glib
3301 <para>Thanks to Tim Janik who wrote to gtk-list: (slightly
3304 <para><quote>Regarding g_malloc(), g_free() and siblings, these
3305 functions are much safer than their libc equivalents. For
3306 example, g_free() just returns if called with NULL. Also, if
3307 USE_DMALLOC is defined, the definition for these functions
3308 changes (in glib.h) to use MALLOC(), FREE() etc... If
3309 MEM_PROFILE or MEM_CHECK are defined, there are even small
3310 statistics made counting the used block sizes (shown by
3311 g_mem_profile() / g_mem_check()).</quote></para>
3313 <para><quote>Considering the fact that glib provides an interface for
3314 memory chunks to save space if you have lots of blocks that
3315 are always the same size and to mark them ALLOC_ONLY if
3316 needed, it is just straight forward to create a small saver
3317 (debug able) wrapper around the normal malloc/free stuff as
3318 well - just like gdk covers Xlib. ;)</quote></para>
3320 <para><quote>Using g_error() and g_warning() inside of applications
3321 like the GIMP that fully rely on gtk even gives the
3322 opportunity to pop up a window showing the messages inside of
3323 a gtk window with your own handler (by using
3324 g_set_error_handler()) along the lines of
3325 <literal>gtk_print()</literal> (inside of
3326 gtkmain.c).</quote></para>
3330 <!-- ----------------------------------------------------------------- -->
3333 <title>What's a GScanner and how do I use one?</title>
3335 <para>A GScanner will tokenize your text, that is, it'll return
3336 an integer for every word or number that appears in its input
3337 stream, following certain (customizable) rules to perform this
3338 translation. You still need to write the parsing functions on
3339 your own though.</para>
3341 <para>Here's a little test program supplied by Tim Janik that
3344 <para><literallayout>
3345 <literal><SYMBOL> = <OPTIONAL-MINUS> <NUMBER> ;</literal>
3346 </literallayout></para>
3348 <para>constructs, while skipping "#\n" and "/**/" style
3351 <programlisting role="C">
3352 #include <glib.h>
3354 /* some test text to be fed into the scanner */
3355 static const gchar *test_text =
3357 "/* slide in some \n"
3358 " * comments, just for the\n"
3363 "# the next value is a float\n"
3366 "ping = - 0.5;\n" );
3368 /* define enumeration values to be returned for specific symbols */
3370 SYMBOL_PING = G_TOKEN_LAST + 1,
3371 SYMBOL_PONG = G_TOKEN_LAST + 2,
3372 SYMBOL_ZONK = G_TOKEN_LAST + 3
3376 static const struct {
3380 { "ping", SYMBOL_PING, },
3381 { "pong", SYMBOL_PONG, },
3382 { "zonk", SYMBOL_ZONK, },
3384 }, *symbol_p = symbols;
3386 static gfloat ping = 0;
3387 static gfloat pong = 0;
3388 static gfloat zonk = 0;
3391 parse_symbol (GScanner *scanner)
3394 gboolean negate = FALSE;
3396 /* expect a valid symbol */
3397 g_scanner_get_next_token (scanner);
3398 symbol = scanner->token;
3399 if (symbol < SYMBOL_PING ||
3400 symbol > SYMBOL_ZONK)
3401 return G_TOKEN_SYMBOL;
3404 g_scanner_get_next_token (scanner);
3405 if (scanner->token != '=')
3408 /* feature optional '-' */
3409 g_scanner_peek_next_token (scanner);
3410 if (scanner->next_token == '-')
3412 g_scanner_get_next_token (scanner);
3416 /* expect a float (ints are converted to floats on the fly) */
3417 g_scanner_get_next_token (scanner);
3418 if (scanner->token != G_TOKEN_FLOAT)
3419 return G_TOKEN_FLOAT;
3421 /* make sure the next token is a ';' */
3422 if (g_scanner_peek_next_token (scanner) != ';')
3424 /* not so, eat up the non-semicolon and error out */
3425 g_scanner_get_next_token (scanner);
3429 /* assign value, eat the semicolon and exit successfully */
3433 ping = negate ? - scanner->value.v_float : scanner->value.v_float;
3436 pong = negate ? - scanner->value.v_float : scanner->value.v_float;
3439 zonk = negate ? - scanner->value.v_float : scanner->value.v_float;
3442 g_scanner_get_next_token (scanner);
3444 return G_TOKEN_NONE;
3448 main (int argc, char *argv[])
3451 guint expected_token;
3453 scanner = g_scanner_new (NULL);
3455 /* adjust lexing behaviour to suit our needs
3457 /* convert non-floats (octal values, hex values...) to G_TOKEN_INT */
3458 scanner->config->numbers_2_int = TRUE;
3459 /* convert G_TOKEN_INT to G_TOKEN_FLOAT */
3460 scanner->config->int_2_float = TRUE;
3461 /* don't return G_TOKEN_SYMBOL, but the symbol's value */
3462 scanner->config->symbol_2_token = TRUE;
3464 /* load symbols into the scanner */
3465 while (symbol_p->symbol_name)
3467 g_scanner_add_symbol (scanner,
3468 symbol_p->symbol_name,
3469 GINT_TO_POINTER (symbol_p->symbol_token));
3473 /* feed in the text */
3474 g_scanner_input_text (scanner, test_text, strlen (test_text));
3476 /* give the error handler an idea on how the input is named */
3477 scanner->input_name = "test text";
3479 /* scanning loop, we parse the input until its end is reached,
3480 * the scanner encountered a lexing error, or our sub routine came
3481 * across invalid syntax
3485 expected_token = parse_symbol (scanner);
3487 g_scanner_peek_next_token (scanner);
3489 while (expected_token == G_TOKEN_NONE &&
3490 scanner->next_token != G_TOKEN_EOF &&
3491 scanner->next_token != G_TOKEN_ERROR);
3493 /* give an error message upon syntax errors */
3494 if (expected_token != G_TOKEN_NONE)
3495 g_scanner_unexp_token (scanner, expected_token, NULL, "symbol", NULL, NULL, TRUE);
3497 /* finsish parsing */
3498 g_scanner_destroy (scanner);
3501 g_print ("ping: %f\n", ping);
3502 g_print ("pong: %f\n", pong);
3503 g_print ("zonk: %f\n", zonk);
3509 <para>You need to understand that the scanner will parse its
3510 input and tokenize it, it is up to you to interpret these
3511 tokens, not define their types before they get parsed,
3512 e.g. watch gscanner parse a string:</para>
3514 <para><literallayout>
3515 <literal>"hi i am 17"</literal>
3516 <literal> | | | |</literal>
3517 <literal> | | | v</literal>
3518 <literal> | | v TOKEN_INT, value: 17</literal>
3519 <literal> | v TOKEN_IDENTIFIER, value: "am"</literal>
3520 <literal> v TOKEN_CHAR, value: 'i'</literal>
3521 <literal>TOKEN_IDENTIFIER, value: "hi"</literal>
3522 </literallayout></para>
3524 <para>If you configure the scanner with:</para>
3526 <programlisting role="C">
3527 scanner->config->int_2_float = TRUE;
3528 scanner->config->char_2_token = TRUE;
3529 scanner->config->scan_symbols = TRUE;
3532 <para>and add "am" as a symbol with</para>
3534 <programlisting role="C">
3535 g_scanner_add_symbol (scanner, "am", "symbol value");
3538 <para>GScanner will parse it as</para>
3540 <para><literallayout>
3541 <literal>"hi i am 17"</literal>
3542 <literal> | | | |</literal>
3543 <literal> | | | v</literal>
3544 <literal> | | v TOKEN_FLOAT, value: 17.0 (automatic int->float conversion)</literal>
3545 <literal> | | TOKEN_SYMBOL, value: "symbol value" (a successfull hash table lookup</literal>
3546 <literal> | | turned a TOKEN_IDENTIFIER into a</literal>
3547 <literal> | | TOKEN_SYMBOL and took over the</literal>
3548 <literal> | v symbol's value)</literal>
3549 <literal> v 'i' ('i' can be a valid token as well, as all chars >0 and <256)</literal>
3550 <literal>TOKEN_IDENTIFIER, value: "hi"</literal>
3551 </literallayout></para>
3553 <para>You need to match the token sequence with your code, and
3554 if you encounter something that you don't want, you error
3557 <programlisting role="C">
3558 /* expect an identifier ("hi") */
3559 g_scanner_get_next_token (scanner);
3560 if (scanner->token != G_TOKEN_IDENTIFIER)
3561 return G_TOKEN_IDENTIFIER;
3562 /* expect a token 'i' */
3563 g_scanner_get_next_token (scanner);
3564 if (scanner->token != 'i')
3566 /* expect a symbol ("am") */
3567 g_scanner_get_next_token (scanner);
3568 if (scanner->token != G_TOKEN_SYMBOL)
3569 return G_TOKEN_SYMBOL;
3570 /* expect a float (17.0) */
3571 g_scanner_get_next_token (scanner);
3572 if (scanner->token != G_TOKEN_FLOAT)
3573 return G_TOKEN_FLOAT;
3576 <para>If you got past here, you have parsed "hi i am 17" and
3577 would have accepted "dooh i am 42" and "bah i am 0.75" as
3578 well, but you would have not accepted "hi 7 am 17" or "hi i hi
3585 <!-- ***************************************************************** -->
3588 <title>GTK+ FAQ Contributions, Maintainers and Copyright</title>
3590 <para>If you would like to make a contribution to the FAQ, send either one
3591 of us an e-mail message with the exact text you think should be
3592 included (question and answer). With your help, this document can grow
3593 and become more useful!</para>
3595 <para>This document is maintained by
3597 <ulink url="mailto:gale@gtk.org"><gale@gtk.org></ulink>
3599 This FAQ was created by Shawn T. Amundson
3600 <ulink url="mailto:amundson@gimp.org">
3601 <amundson@gimp.org></ulink>.
3603 Contributions should be sent to Tony Gale <ulink
3604 url="mailto:gale@gtk.org"><gale@gtk.org></ulink></para>
3606 <para>The GTK+ FAQ is Copyright (C) 1997-2003 by Shawn T. Amundson,
3609 <para>Permission is granted to make and distribute verbatim copies of this
3610 manual provided the copyright notice and this permission notice are
3611 preserved on all copies.</para>
3613 <para>Permission is granted to copy and distribute modified versions of this
3614 document under the conditions for verbatim copying, provided that this
3615 copyright notice is included exactly as in the original, and that the
3616 entire resulting derived work is distributed under the terms of a
3617 permission notice identical to this one.</para>
3619 <para>Permission is granted to copy and distribute translations of this
3620 document into another language, under the above conditions for
3621 modified versions.</para>
3623 <para>If you are intending to incorporate this document into a published
3624 work, please contact one of the maintainers, and we will make an
3625 effort to ensure that you have the most up to date information
3628 <para>There is no guarentee that this document lives up to its intended
3629 purpose. This is simply provided as a free resource. As such, the
3630 authors and maintainers of the information provided within can not
3631 make any guarentee that the information is even accurate.</para>
3635 <!-- ----------------------------------------------------------------- -->