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://www.freedesktop.org/software/pkgconfig">
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. One possible avenue for this is via
793 <ulink url="http://cvs.gnome.org/lxr/source/libegg/">libegg</ulink>.</para>
795 <para>Before you spend months of your valuable time implementing your
796 revolutionary widget, it is highly recommended that you get some
797 feedback on your idea via the appropriate
798 <link linkend="faq-MailLists">mailing list</link>.</para>
801 <!-- ----------------------------------------------------------------- -->
804 <title>Is anyone working on bindings for languages other than
805 C? <emphasis>[GTK 2.x]</emphasis></title>
807 <para>There is a list of <ulink url="http://www.gtk.org/bindings.html">
808 language bindings</ulink> on the GTK+ website.</para>
810 <para>The 'official' language bindings are C++, Ada and Python.
811 However, bindings for many other languages are available.</para>
816 <!-- ***************************************************************** -->
818 <title>Development with GTK+: the begining</title>
820 <!-- ----------------------------------------------------------------- -->
823 <title>How do I get started? <emphasis>[GTK 2.x]</emphasis></title>
825 <para>So, after you have installed GTK+ there are a couple of
826 things that can ease you into developing applications with
827 it. There is the GTK+ Tutorial <ulink
828 url="http://www.gtk.org/tutorial/">
829 http://www.gtk.org/tutorial/</ulink>, which is undergoing
830 development. This will introduce you to writing applications
833 <para>The GTK+ Tutorial doesn't contain information on all of
834 the widgets that are in GTK+. For example code on how to use
835 the basics of all the GTK+ widgets you should look in the
836 directory 'tests' (and associated source files) within the GTK+
837 distribution. Looking at these examples will give you a good
838 grounding on what the widgets can do.</para>
842 <!-- ----------------------------------------------------------------- -->
845 <title>How do I use the Glade GUI builder with GTK+? <emphasis>[GTK 2.x]</emphasis></title>
847 <para>There are two ways to use Glade. The first way is to use
848 Glade's facilities for generating code; the second
849 way is to use the libglade library which directly loads
850 the XML user interface description files that Glade
851 generates into a running program.</para>
853 <para>Experienced GTK+ programmers generally strongly recommend
854 using libglade; you don't have to worry about the interaction
855 between Glade generating the source and you editing it,
856 and its been shown to be a method that works better
857 for large projects, so there is a lot of example code
858 out there you can look at.</para>
860 <para>An introduction to using libglade can be found in the
862 (<ulink url="http://developer.gnome.org/doc/API/2.0/libglade/libglade-notes.html#libglade-basics">
863 http://developer.gnome.org/doc/API/2.0/libglade/libglade-notes.html#libglade-basics</ulink>)
868 <!-- ----------------------------------------------------------------- -->
871 <title>How do I write security sensitive/SUID/SGID programs with GTK+?
872 Is GTK+ secure? What's this GTK_MODULES security hole I heard about?
873 <emphasis>[GTK 2.x]</emphasis></title>
875 <para>The short answer to this question is: you can't, so don't write SUID/SGID
876 programs with GTK+</para>
878 <para>GTK+ will refuse to run with elevated privileges, as it is not designed
879 to be used in this manner. The only correct way to write a setuid program with
880 a graphical user interface is to have a setuid backend that communicates with
881 the non-setuid graphical user interface via a mechanism such as a pipe and that
882 considers the input it receives to be untrusted.</para>
884 <para>For a more thorough explanation of the GTK+ Developers position on
885 this issue see <ulink
886 url="http://www.gtk.org/setuid.html">http://www.gtk.org/setuid.html</ulink>.</para>
890 <!-- ----------------------------------------------------------------- -->
893 <title>I tried to compile a small <command>Hello World</command> of mine,
894 but it failed. Any clue? <emphasis>[GTK 2.x]</emphasis></title>
896 <para>Since you are good at coding, we will not deal with
897 compile time errors here :)</para>
899 <para>The classic command line to compile a GTK+ based program is</para>
900 <para><literallayout>
901 <literal>gcc -o myprog [c files] `pkg-config gtk+-2.0 --cflags --libs`</literal>
902 </literallayout></para>
904 <para>You should notice the backquote character which is used
905 in this command line. A common mistake when you start a GTK+
906 based development is to use quotes instead of backquotes. If
907 you do so, the compiler will complain about an unknown file
908 called <filename>pkg-config gtk+-2.0 --cflags --libs</filename>. The
909 text in backquotes is an instruction to your shell to
910 substitute the output of executing this command into the
913 <para>The command line above ensures that:</para>
916 <listitem><simpara>the correct C compiler flags will be used
917 to compile the program (including the complete C header
918 directory list)</simpara>
921 <listitem><simpara>your program will be linked with the
922 needed libraries.</simpara>
928 <!-- ----------------------------------------------------------------- -->
931 <title>What about using the <command>make</command>
932 utility? <emphasis>[GTK 2.x]</emphasis></title>
934 <para>This is a sample makefile which compiles a GTK+ based
937 <programlisting role="C">
938 # basic GTK+ app makefile
939 SOURCES = myprg.c foo.c bar.c
940 OBJS = ${SOURCES:.c=.o}
941 CFLAGS = `pkg-config gtk+-2.0 --cflags`
942 LDADD = `pkg-config gtk+-2.0 --libs`
947 ${CC} -o ${PACKAGE} ${OBJS} ${LDADD}
950 ${CC} ${CFLAGS} -c $<
955 <para>For more information about the <command>make</command> utility, you
956 should read either the related man page or the relevant info file.</para>
960 <!-- ----------------------------------------------------------------- -->
963 <title>I use the backquote stuff in my makefiles, but my make
964 process failed. <emphasis>[GTK 2.x]</emphasis></title>
966 <para>The backquote construction seems to not be accepted by
967 some old <command>make</command> utilities. If you use one of these, the
968 make process will probably fail. In order to have the
969 backquote syntax working again, you should use the GNU make
970 utility (get it on the GNU ftp server at <ulink
971 url="ftp://ftp.gnu.org/gnu/make/">ftp://ftp.gnu.org/gnu/make/</ulink>).</para>
975 <!-- ----------------------------------------------------------------- -->
978 <title>I want to add some configure stuff, how could I do
979 this? <emphasis>[GTK 2.x]</emphasis></title>
981 <para>To use autoconf/automake, you must first install the
982 relevant packages. These are:</para>
984 <itemizedlist spacing=Compact>
985 <listitem><simpara>the m4 preprocessor v1.4 or better</simpara>
988 <listitem><simpara>autoconf v2.54 or better</simpara>
991 <listitem><simpara>automake v1.7 or better suggested</simpara>
995 <para>You'll find these packages on the main GNU ftp server
996 (<ulink url="ftp://ftp.gnu.org/">ftp://ftp.gnu.org/</ulink>)
997 or on any GNU mirror.</para>
999 <para>In order to use the powerful autoconf/automake scheme,
1000 you must create a configure.in which may look like:</para>
1002 <programlisting role="C">
1003 dnl Process this file with autoconf to produce a configure script.
1004 dnl configure.in for a GTK+ based program
1007 AM_INIT_AUTOMAKE(mypkgname, 0.0.1)
1008 AM_CONFIG_HEADER(config.h)
1010 dnl Checks for programs.
1011 AC_PROG_CC dnl check for the c compiler
1012 dnl you should add CFLAGS="" here, 'cos it is set to -g by PROG_CC
1014 dnl Checks for libraries.
1015 AM_PATH_GTK_2_0(2.2.0,,AC_MSG_ERROR(mypkgname 0.1 needs GTK+ 2.2.0))
1022 <para>You must add a Makefile.am file:</para>
1024 <programlisting role="C">
1025 bin_PROGRAMS = myprg
1026 myprg_SOURCES = myprg.c foo.c bar.c
1027 INCLUDES = @GTK_CFLAGS@
1030 DISTCLEANFILES = .deps/*.P
1033 <para>If your project contains more than one subdirectory,
1034 you'll have to create one Makefile.am in each directory plus a
1035 master Makefile.am which will look like:</para>
1037 <programlisting role="C">
1038 SUBDIRS = mydir1 mydir2 mydir3
1041 <para>then, to use these, simply type the following
1044 <programlisting role="C">
1048 automake --add-missing --include-deps --foreign
1051 <para>For further information, you should look at the autoconf
1052 and the automake documentation (the shipped info files are
1053 really easy to understand, and there are plenty of web
1054 resources that deal with autoconf and automake).</para>
1058 <!-- ----------------------------------------------------------------- -->
1061 <title>I try to debug my GTK+ application with gdb, but it
1062 hangs my X server when I hit some breakpoint. Any
1063 Idea? <emphasis>[GTK 2.x]</emphasis></title>
1065 <para>From Federico Mena Quintero:</para>
1067 <para><quote>X is not locked up. It is likely that you are hitting a
1068 breakpoint inside a callback that is called from a place in Gtk that has
1069 a mouse grab.</quote></para>
1071 <para><quote>Run your program with the <literal>--sync</literal>
1072 option; it will make it easier to debug. Also, you may want to
1073 use the console for running the debugger, and just let the
1074 program run in another console with the X server.</quote></para>
1076 <para>Eric Mouw had another solution:</para>
1078 <para><quote>An old terminal connected to an otherwise unused serial
1079 port is also great for debugging X programs. Old vt100/vt220
1080 terminals are dirt cheap but a bit hard to get (here in The
1081 Netherlands, YMMV).</quote></para>
1084 Another option is to run your application on Xnest. Xnest is an X server
1085 which displays its root window in a regular window of another X server.
1086 A pointer grab on the Xnest display will not affect the GUI of your debugger
1087 running on your regular X server.
1097 <!-- ***************************************************************** -->
1099 <title>Development with GTK+: general questions</title>
1101 <!-- ----------------------------------------------------------------- -->
1104 <title>What widgets are in GTK?</title>
1106 <para>The GTK+ Tutorial lists the following widgets:</para>
1108 <programlisting role="C">
1119 | | | `GtkAspectFrame
1124 | | | | `GtkCheckMenuItem
1125 | | | | `GtkRadioMenuItem
1129 | | +GtkColorSelectionDialog
1131 | | | `GtkInputDialog
1132 | | `GtkFileSelection
1135 | | | +GtkHButtonBox
1136 | | | `GtkVButtonBox
1141 | | +GtkColorSelection
1145 | | `GtkToggleButton
1159 | +GtkScrolledWindow
1193 <!-- ----------------------------------------------------------------- -->
1196 <title>Is GTK+ thread safe? How do I write multi-threaded GTK+
1197 applications? <emphasis>[GTK 2.x]</emphasis></title>
1199 <para>The GLib library can be used in a thread-safe mode by
1200 calling g_thread_init() before making any other GLib
1201 calls. In this mode GLib automatically locks all internal
1202 data structures as needed. This does not mean that two
1203 threads can simultaneously access, for example, a single hash
1204 table, but they can access two different hash tables
1205 simultaneously. If two different threads need to access the
1206 same hash table, the application is responsible for locking
1209 <para>In order to make GDK thread aware, you also need to
1210 call gdk_threads_init() in conjunction with the above call.
1211 There is a single global
1212 lock that you must acquire with gdk_threads_enter() before
1213 making any GDK calls, and release with gdk_threads_leave()
1214 afterwards throughout your code.</para>
1216 <para>A minimal main program for a threaded GTK+ application
1219 <programlisting role="C">
1221 main (int argc, char *argv[])
1226 g_thread_init(NULL);
1230 gtk_init(&argc, &argv);
1232 window = create_window();
1233 gtk_widget_show(window);
1235 gdk_threads_enter();
1237 gdk_threads_leave();
1243 <para>Callbacks require a bit of attention. Callbacks from
1244 GTK+ (signals) are made within the GTK+ lock. However
1245 callbacks from GLib (timeouts, IO callbacks, and idle
1246 functions) are made outside of the GTK+ lock. So, within a
1247 signal handler you do not need to call gdk_threads_enter(),
1248 but within the other types of callbacks, you do.</para>
1250 <para>Erik Mouw contributed the following code example to
1251 illustrate how to use threads within GTK+ programs.</para>
1253 <programlisting role="C">
1254 /*-------------------------------------------------------------------------
1255 * Filename: gtk-thread.c
1257 * Copyright: Copyright (C) 1999, Erik Mouw
1258 * Author: Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
1259 * Description: GTK threads example.
1260 * Created at: Sun Oct 17 21:27:09 1999
1261 * Modified by: Owen Taylor <otaylor@gtk.org>
1262 * Modified at: Wed May 28 10:43:00 2003
1263 *-----------------------------------------------------------------------*/
1267 * cc -o gtk-thread gtk-thread.c `pkg-config --cflags --libs gtk+-2.0 gthread-2.0`
1269 * Thanks to Sebastian Wilhelmi for pointing out some bugs in earlier versions.
1273 #include <unistd.h>
1274 #include <gtk/gtk.h>
1276 #define YES_IT_IS (1)
1277 #define NO_IT_IS_NOT (0)
1285 G_LOCK_DEFINE_STATIC (yes_or_no);
1286 static volatile int yes_or_no = YES_IT_IS;
1288 void destroy(GtkWidget *widget, gpointer data)
1293 void *argument_thread(void *args)
1295 yes_or_no_args *data = (yes_or_no_args *)args;
1296 gboolean say_something;
1301 sleep(g_random_int_range (1, 4));
1303 /* lock the yes_or_no_variable */
1306 /* do we have to say something? */
1307 say_something = (yes_or_no != data->what);
1311 /* set the variable */
1312 yes_or_no = data->what;
1315 /* Unlock the yes_or_no variable */
1316 G_UNLOCK(yes_or_no);
1320 /* get GTK thread lock */
1321 gdk_threads_enter();
1323 /* set label text */
1324 if(data->what == YES_IT_IS)
1325 gtk_label_set_text(GTK_LABEL(data->label), "O yes, it is!");
1327 gtk_label_set_text(GTK_LABEL(data->label), "O no, it isn't!");
1329 /* Make sure all X commands are sent to the X server; not strictly
1330 * necessary here, but always a good idea when you do anything
1331 * from a thread other than the one where the main loop is running.
1335 /* release GTK thread lock */
1336 gdk_threads_leave();
1343 int main(int argc, char *argv[])
1347 GError *error = NULL;
1348 yes_or_no_args yes_args, no_args;
1351 g_thread_init(NULL);
1355 gtk_init(&argc, &argv);
1357 /* create a window */
1358 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1360 g_signal_connect(window, "destroy",
1361 G_CALLBACK(destroy), NULL);
1363 gtk_container_set_border_width(GTK_CONTAINER (window), 10);
1365 /* create a label */
1366 label = gtk_label_new("And now for something completely different ...");
1367 gtk_container_add(GTK_CONTAINER(window), label);
1369 /* show everything */
1370 gtk_widget_show(label);
1371 gtk_widget_show (window);
1373 /* create the threads */
1374 yes_args.label = label;
1375 yes_args.what = YES_IT_IS;
1376 if (!g_thread_create(argument_thread, &yes_args, FALSE, &error))
1378 g_printerr ("Failed to create YES thread: %s\n", error->message);
1382 no_args.label = label;
1383 no_args.what = NO_IT_IS_NOT;
1384 if (!g_thread_create(argument_thread, &no_args, FALSE, &error))
1386 g_printerr ("Failed to create NO thread: %s\n", error->message);
1390 /* enter the GTK main loop */
1391 gdk_threads_enter();
1393 gdk_threads_leave();
1400 <!-- ----------------------------------------------------------------- -->
1403 <title>I'm doing some stuff with GTK+ in a separate thread, and
1404 properly locking with gdk_threads_enter/gdk_threads_leave()
1405 but the display doesn't update properly. <emphasis>[GTK 2.x]</emphasis>
1408 <para>For efficiency, the X window system batches up commands
1409 and sends them to the X server in batches instead of sending
1410 out immediately.</para>
1412 <para>In a non-multithreaded program, you don't have to worry about
1413 this, since the first thing that happens when control returns
1414 to the main loop is that any outstanding X requests are
1415 sent to the X server.</para>
1417 <para>However, if you are making GTK+ calls from a thread other
1418 than the main loop, then GTK+ doesn't know when to send batched
1419 commands out. For that reason, after making GTK+ calls
1420 in a separate thread, it is usually a good idea to call
1421 gdk_flush() before gdk_thread_leave().</para>
1423 <para>Actually, gdk_flush() is more expensive than is necessary here,
1424 since it waits for the X server to finish outstanding commands
1425 as well; if performance is an issue, you may want to call
1426 XFlush() directly:</para>
1428 <programlisting role="C">
1430 #include <gdk/gdkx.h>
1432 void my_flush_commands (void)
1434 GdkDisplay *display = gdk_display_get_default ();
1435 XFlush (GDK_DISPLAY_XDISPLAY (display);
1441 <!-- ----------------------------------------------------------------- -->
1444 <title>What's an easy way to run a function in the thread with
1445 the main loop? <emphasis>[GTK 2.x]</emphasis></title>
1447 <para>Sometimes the simplest way to set up a threaded program
1448 is to make all the GTK+ calls in a single thread. In such
1449 a program, you should still call g_threads_init(), but
1450 don't need to call gdk_threads_init(), gkd_threads_enter(),
1451 and gdk_threads_leave().</para>
1453 <para>If you set your program up this way, how then do you get
1454 the thread making GTK+ calls and running the main loop
1455 to do something in response to another thread?</para>
1457 <para>An easy way to do it is to take advantage of the fact that
1458 the GLib main loop functions are all thread safe, and can
1459 be called from any thread by adding an idle function
1460 with g_idle_add(). The function provided will be called
1461 at the next opportunity by the main thread. If you want
1462 your function to take priority over event handling and
1463 drawing, you can instead use g_idle_add_full() and pass
1464 in a priority of G_PRIORITY_HIGH.</para>
1468 <!-- ----------------------------------------------------------------- -->
1471 <title>Why does this strange 'x io error' occur when I
1472 <literal>fork()</literal> in my GTK+ app? <emphasis>[GTK 2.x]</emphasis></title>
1474 <para>This is not really a GTK+ problem, and the problem is
1475 not related to <literal>fork()</literal> either. If the 'x io
1476 error' occurs then you probably use the <literal>exit()</literal> function
1477 in order to exit from the child process.</para>
1479 <para>When GDK opens an X display, it creates a socket file
1480 descriptor. When you use the <literal>exit()</literal>
1481 function, you implicitly close all the open file descriptors,
1482 and the underlying X library really doesn't like this.</para>
1484 <para>The right function to use here is
1485 <literal>_exit()</literal>.</para>
1487 <para>Erik Mouw contributed the following code example to
1488 illustrate handling fork() and exit().</para>
1490 <programlisting role="C">
1491 /*-------------------------------------------------------------------------
1492 * Filename: gtk-fork.c
1494 * Copyright: Copyright (C) 1999, Erik Mouw
1495 * Author: Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
1496 * Description: GTK+ fork example
1497 * Created at: Thu Sep 23 21:37:55 1999
1498 * Modified by: Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
1499 * Modified at: Thu Sep 23 22:39:39 1999
1500 * Modified by: Tony Gale <gale@gtk.org>
1501 * Modified at: Wed Jan 14 12:38:00 2004
1502 *-----------------------------------------------------------------------*/
1506 * cc -o gtk-fork gtk-fork.c `pkg-config gtk+-2.0 --cflags --libs`
1510 #include <stdio.h>
1511 #include <stdlib.h>
1512 #include <signal.h>
1513 #include <sys/types.h>
1514 #include <sys/wait.h>
1515 #include <unistd.h>
1516 #include <gtk/gtk.h>
1518 void sigchld_handler(int num)
1520 sigset_t set, oldset;
1522 int status, exitstatus;
1524 /* block other incoming SIGCHLD signals */
1525 sigemptyset(&set);
1526 sigaddset(&set, SIGCHLD);
1527 sigprocmask(SIG_BLOCK, &set, &oldset);
1529 /* wait for child */
1530 while((pid = waitpid((pid_t)-1, &status, WNOHANG)) > 0)
1532 if(WIFEXITED(status))
1534 exitstatus = WEXITSTATUS(status);
1537 "Parent: child exited, pid = %d, exit status = %d\n",
1538 (int)pid, exitstatus);
1540 else if(WIFSIGNALED(status))
1542 exitstatus = WTERMSIG(status);
1545 "Parent: child terminated by signal %d, pid = %d\n",
1546 exitstatus, (int)pid);
1548 else if(WIFSTOPPED(status))
1550 exitstatus = WSTOPSIG(status);
1553 "Parent: child stopped by signal %d, pid = %d\n",
1554 exitstatus, (int)pid);
1559 "Parent: child exited magically, pid = %d\n",
1564 /* re-install the signal handler (some systems need this) */
1565 signal(SIGCHLD, sigchld_handler);
1567 /* and unblock it */
1568 sigemptyset(&set);
1569 sigaddset(&set, SIGCHLD);
1570 sigprocmask(SIG_UNBLOCK, &set, &oldset);
1573 gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
1578 void destroy(GtkWidget *widget, gpointer data)
1583 void fork_me(GtkWidget *widget, gpointer data)
1591 /* ouch, fork() failed */
1598 fprintf(stderr, "Child: pid = %d\n", (int)getpid());
1600 execlp("ls", "ls", "-CF", "/", NULL);
1602 /* if exec() returns, there is something wrong */
1605 /* exit child. note the use of _exit() instead of exit() */
1611 fprintf(stderr, "Parent: forked a child with pid = %d\n", (int)pid);
1615 int main(int argc, char *argv[])
1620 gtk_init(&argc, &argv);
1622 /* the basic stuff: make a window and set callbacks for destroy and
1625 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1627 g_signal_connect(G_OBJECT (window), "delete_event",
1628 G_CALLBACK(delete_event), NULL);
1630 g_signal_connect(G_OBJECT (window), "destroy",
1631 G_CALLBACK(destroy), NULL);
1633 #if (GTK_MAJOR_VERSION == 1) && (GTK_MINOR_VERSION == 0)
1634 gtk_container_border_width(GTK_CONTAINER (window), 10);
1636 gtk_container_set_border_width(GTK_CONTAINER (window), 10);
1639 /* add a button to do something useful */
1640 button = gtk_button_new_with_label("Fork me!");
1642 g_signal_connect(G_OBJECT (button), "clicked",
1643 G_CALLBACK(fork_me), NULL);
1645 gtk_container_add(GTK_CONTAINER(window), button);
1647 /* show everything */
1648 gtk_widget_show (button);
1649 gtk_widget_show (window);
1652 /* install a signal handler for SIGCHLD signals */
1653 signal(SIGCHLD, sigchld_handler);
1664 <!-- ----------------------------------------------------------------- -->
1667 <title>Why don't the contents of a button move when the button
1668 is pressed? Here's a patch to make it work that way... <emphasis>[GTK 2.x]</emphasis></title>
1670 <para>From: Peter Mattis</para>
1672 <para><quote>The reason buttons don't move their child down and to
1673 the right when they are depressed is because I don't think
1674 that's what is happening visually. My view of buttons is
1675 that you are looking at them straight on. That is, the user
1676 interface lies in a plane and you're above it looking
1677 straight at it. When a button gets pressed it moves directly
1678 away from you. To be absolutely correct I guess the child
1679 should actually shrink a tiny amount. But I don't see why
1680 the child should shift down and to the left. Remember, the
1681 child is supposed to be attached to the buttons surface. Its
1682 not good for it to appear like the child is slipping on the
1683 surface of the button.</quote></para>
1685 <para><quote>On a more practical note, I did implement this at one point
1686 and determined it didn't look good and removed it.</quote></para>
1690 <!-- ----------------------------------------------------------------- -->
1693 <title>How do I identifiy a widgets top level window or other
1694 ancestor? <emphasis>[GTK 2.x]</emphasis></title>
1696 <para>There are a couple of ways to find the top level parent
1697 of a widget. The easiest way is to call the
1698 <literal>gtk_widget_get_toplevel()</literal> function that
1699 returns a pointer to a GtkWidget that is the top level
1702 <para>A more complicated way to do this (but less limited, as
1703 it allows the user to get the closest ancestor of a known type) is to use
1704 <literal>gtk_widget_get_ancestor()</literal> as in:</para>
1706 <programlisting role="C">
1708 widget = gtk_widget_get_ancestor(w, GTK_TYPE_WINDOW);
1711 <para>Since virtually all the GTK_TYPEs can be used as the
1712 second parameter of this function, you can get any parent
1713 widget of a particular widget. Suppose you have an hbox which
1714 contains a vbox, which in turn contains some other atomic
1715 widget (entry, label, etc. To find the master hbox using the
1716 <literal>entry</literal> widget simply use:</para>
1718 <programlisting role="C">
1720 hbox = gtk_widget_get_ancestor(w, GTK_TYPE_HBOX);
1723 <para>You can also follow the a widgets ancestry by using the function
1724 <literal>gtk_widget_get_parent()</literal> that returns a pointer
1725 to a widgets parent widget.</para>
1729 <!-- ----------------------------------------------------------------- -->
1732 <title>How do I get the Window ID of a GtkWindow? <emphasis>[GTK 2.x]</emphasis></title>
1734 <para>The actual Gdk/X window will be created when the widget
1735 gets realized. You can get the Window ID with:</para>
1737 <programlisting role="C">
1738 #include <gdk/gdkx.h>
1740 Window xwin = GDK_WINDOW_XWINDOW (GTK_WIDGET (my_window)->window);
1744 <!-- ----------------------------------------------------------------- -->
1747 <title>How do I catch a double click event? <emphasis>[GTK 2.x]</emphasis></title>
1749 <para>Tim Janik wrote to gtk-list (slightly modified):</para>
1751 <para>Define a signal handler:</para>
1753 <programlisting role="C">
1755 signal_handler_event(GtkWidget *widget, GdkEventButton *event, gpointer func_data)
1757 if (GTK_IS_BUTTON(widget) &&
1758 (event->type==GDK_2BUTTON_PRESS ||
1759 event->type==GDK_3BUTTON_PRESS) ) {
1760 printf("I feel %s clicked with button %d\n",
1761 event->type==GDK_2BUTTON_PRESS ? "double" : "triple",
1768 <para>And connect the handler to your object:</para>
1770 <programlisting role="C">
1772 /* button init stuff */
1774 g_signal_connect(G_OBJECT(button),
1775 "button_press_event",
1776 G_CALLBACK(signal_handler_event),
1781 g_signal_connect(G_OBJECT(button),
1782 "button_release_event",
1783 G_CALLBACK(signal_handler_event),
1786 /* something else */
1790 <para>and, Owen Taylor wrote:</para>
1792 <para><quote>Note that a single button press will be received
1793 beforehand, and if you are doing this for a button, you will
1794 therefore also get a "clicked" signal for the button. (This
1795 is going to be true for any toolkit, since computers aren't
1796 good at reading one's mind.)</quote></para>
1800 <!-- ----------------------------------------------------------------- -->
1803 <title>By the way, what are the differences between signals
1806 <para>First of all, Havoc Pennington gives a rather complete
1807 description of the differences between events and signals in
1808 his free book (two chapters can be found at <ulink
1809 url="http://www106.pair.com/rhp/sample_chapters.html">
1810 http://www106.pair.com/rhp/sample_chapters.html</ulink>).</para>
1812 <para>Moreover, Havoc posted this to the <literal>gtk-list</literal>
1813 <quote>Events are a stream of messages received from the X
1814 server. They drive the Gtk main loop; which more or less
1815 amounts to "wait for events, process them" (not exactly, it
1816 is really more general than that and can wait on many
1817 different input streams at once). Events are a Gdk/Xlib
1818 concept.</quote></para>
1820 <para><quote>Signals are a feature of GtkObject and its subclasses. They
1821 have nothing to do with any input stream; really a signal is just a way
1822 to keep a list of callbacks around and invoke them ("emit" the
1823 signal). There are lots of details and extra features of
1824 course. Signals are emitted by object instances, and are entirely
1825 unrelated to the Gtk main loop. Conventionally, signals are emitted
1826 "when something changes" about the object emitting the
1827 signal.</quote></para>
1829 <para><quote>Signals and events only come together because GtkWidget
1830 happens to emit signals when it gets events. This is purely a
1831 convenience, so you can connect callbacks to be invoked when a
1832 particular widget receives a particular event. There is nothing about
1833 this that makes signals and events inherently related concepts, any more
1834 than emitting a signal when you click a button makes button clicking and
1835 signals related concepts.</quote></para>
1839 <!-- ----------------------------------------------------------------- -->
1842 <title>Data I pass to the <literal>delete_event</literal> (or other event)
1843 handler gets corrupted.</title>
1845 <para>All event handlers take an additional argument which
1846 contains information about the event that triggered the
1847 handler. So, a <literal>delete_event</literal> handler must
1848 be declared as:</para>
1851 <programlisting role="C">
1852 gint delete_event_handler (GtkWidget *widget,
1859 <!-- ----------------------------------------------------------------- -->
1862 <title>I have my signal connected to the the (whatever) event,
1863 but it seems I don't catch it. What's wrong?</title>
1865 <para>There is some special initialisation to do in order to
1866 catch some particular events. In fact, you must set the
1867 correct event mask bit of your widget before getting some
1868 particular events.</para>
1870 <para>For example,</para>
1872 <programlisting role="C">
1873 gtk_widget_add_events(window, GDK_KEY_RELEASE_MASK);
1876 <para>lets you catch the key release events. If you want to
1877 catch every events, simply us the GDK_ALL_EVENTS_MASK event
1880 <para>All the event masks are defined in the
1881 <filename>gdktypes.h</filename> file.</para>
1885 <!-- ----------------------------------------------------------------- -->
1888 <title>I need to add a new signal to a GTK+ widget. Any
1891 <para>If the signal you want to add may be beneficial for
1892 other GTK+ users, you may want to submit a patch that
1893 presents your changes. Check the tutorial for more
1894 information about adding signals to a widget class.</para>
1896 <para>If you don't think it is the case or if your patch is
1897 not applied you'll have to use the
1898 <literal>gtk_object_class_user_signal_new</literal>
1899 function. <literal>gtk_object_class_user_signal_new</literal> allows you
1900 to add a new signal to a predefined GTK+ widget without any
1901 modification of the GTK+ source code. The new signal can be
1902 emited with <literal>gtk_signal_emit</literal> and can be
1903 handled in the same way as other signals.</para>
1905 <para>Tim Janik posted this code snippet:</para>
1907 <programlisting role="C">
1908 static guint signal_user_action = 0;
1910 signal_user_action =
1911 gtk_object_class_user_signal_new (gtk_type_class (GTK_TYPE_WIDGET),
1913 GTK_RUN_LAST | GTK_RUN_ACTION,
1914 gtk_marshal_NONE__POINTER,
1919 gtk_widget_user_action (GtkWidget *widget,
1922 g_return_if_fail (GTK_IS_WIDGET (widget));
1924 gtk_signal_emit (GTK_OBJECT (widget), signal_user_action, act_data);
1928 <para>If you want your new signal to have more than the
1929 classical gpointer parameter, you'll have to play with GTK+
1934 <!-- ----------------------------------------------------------------- -->
1937 <title>Is it possible to get some text displayed which is
1938 truncated to fit inside its allocation?</title>
1940 <para>GTK's behavior (no clipping) is a consequence of its
1941 attempts to conserve X resources. Label widgets (among
1942 others) don't get their own X window - they just draw their
1943 contents on their parent's window. While it might be possible
1944 to have clipping occur by setting the clip mask before
1945 drawing the text, this would probably cause a substantial
1946 performance penalty.</para>
1948 <para>Its possible that, in the long term, the best solution
1949 to such problems might be just to change gtk to give labels X
1950 windows. A short term workaround is to put the label widget
1951 inside another widget that does get its own window - one
1952 possible candidate would be the viewport widget.</para>
1954 <programlisting role="C">
1955 viewport = gtk_viewport (NULL, NULL);
1956 gtk_widget_set_usize (viewport, 50, 25);
1957 gtk_viewport_set_shadow_type (GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1958 gtk_widget_show(viewport);
1960 label = gtk_label ("a really long label that won't fit");
1961 gtk_container_add (GTK_CONTAINER(viewport), label);
1962 gtk_widget_show (label);
1965 <para>If you were doing this for a bunch of widgets, you might
1966 want to copy gtkviewport.c and strip out the adjustment and
1967 shadow functionality (perhaps you could call it
1971 <!-- ----------------------------------------------------------------- -->
1974 <title>How do I make my window modal? / How do I make a single
1975 window active?</title>
1977 <para>After you create your window, do
1978 <literal>gtk_grab_add(my_window)</literal>. And after closing the window
1979 do <literal>gtk_grab_remove(my_window)</literal>.</para>
1983 <!-- ----------------------------------------------------------------- -->
1986 <title>Why doesn't my widget (e.g. progressbar)
1987 update? <emphasis>[GTK 2.x]</emphasis></title>
1989 <para>You are probably doing all the changes within a function without
1990 returning control to <literal>gtk_main()</literal>. This may
1991 be the case if you do some lengthy calculation in your
1992 code. Most drawing updates are only placed on a queue, which
1993 is processed within <literal>gtk_main()</literal>. You can force the
1994 drawing queue to be processed using something like:</para>
1997 <programlisting role="C">
1998 while (g_main_context_iteration(NULL, FALSE));
2001 <para>inside you're function that changes the widget.</para>
2003 <para>What the above snippet does is run all pending events
2004 and high priority idle functions, then return immediately
2005 (the drawing is done in a high priority idle function).</para>
2009 <!-- ----------------------------------------------------------------- -->
2012 <title>How do I attach data to some GTK+ object/widget?
2013 <emphasis>[GTK 2.x]</emphasis></title>
2015 <para>First of all, the attached data is stored in the
2016 object_data field of a GtkObject. The type of this field is
2017 GData, which is defined in glib.h. So you should read the
2018 gdataset.c file in your glib source directory very
2021 <para>There are two (easy) ways to attach some data to a gtk
2022 object. Using <literal>g_object_set_data()</literal> and
2023 <literal>g_object_get_data()</literal> seems to be the most
2024 common way to do this, as it provides a powerful interface to
2025 connect objects and data.</para>
2027 <programlisting role="C">
2028 void g_object_set_data(GObject *object, const gchar *key, gpointer data);
2030 gpointer g_object_get_data(GObject *object, const gchar *key);
2033 <para>Since a short example is better than any lengthy speech:</para>
2035 <programlisting role="C">
2036 struct my_struct p1,p2,*result;
2039 g_object_set_data(G_OBJECT(w),"p1 data",(gpointer)&p1);
2040 g_object_set_data(G_OBJECT(w),"p2 data",(gpointer)&p2);
2042 result = g_object_get_data(G_OBJECT(w),"p1 data");
2045 <para>The <literal>gtk_object_set_user_data()</literal> and
2046 <literal>gtk_object_get_user_data()</literal> functions does
2047 exactly the same thing as the functions above, but does not
2048 let you specify the "key" parameter.Instead, it uses a
2049 standard "user_data" key. Note that the use of these functions
2050 is deprecated in 1.2. They only provide a compatibility mode
2051 with some old gtk packages.</para>
2055 <!-- ----------------------------------------------------------------- -->
2058 <title>How do I remove the data I have attached to an
2061 <para>When attaching the data to the object, you can use the
2062 <literal>gtk_object_set_data_full()</literal> function. The three
2063 first arguments of the function are the same as in
2064 <literal>gtk_object_set_data()</literal>. The fourth one is a
2065 pointer to a callback function which is called when the data
2066 is destroyed. The data is destroyed when you:</para>
2069 <listitem><simpara> destroy the object</simpara>
2072 <listitem><simpara> replace the data with a new one (with
2073 the same key)</simpara>
2076 <listitem><simpara> replace the data with NULL (with the
2084 <!-- ----------------------------------------------------------------- -->
2087 <title>How do I reparent a widget?</title>
2089 <para>The normal way to reparent (ie change the owner) of a
2090 widget should be to use the function:</para>
2092 <programlisting role="C">
2093 void gtk_widget_reparent (GtkWidget *widget,
2094 GtkWidget *new_parent)
2097 <para>But this is only a "should be" since this function does
2098 not correctly do its job on some specific widgets. The main
2099 goal of gtk_widget_reparent() is to avoid unrealizing widget
2100 if both widget and new_parent are realized (in this case,
2101 widget->window is successfully reparented). The problem here
2102 is that some widgets in the GTK+ hierarchy have multiple
2103 attached X subwindows and this is notably the case for the
2104 GtkSpinButton widget. For those, gtk_widget_reparent() will
2105 fail by leaving an unrealized child window where it should
2108 <para>To avoid this problem, simply use the following code
2111 <programlisting role="C">
2112 gtk_widget_ref(widget);
2113 gtk_container_remove(GTK_CONTAINER(old_parent), widget);
2114 gtk_container_add(GTK_CONTAINER(new_parent), widget);
2115 gtk_widget_unref(widget);
2120 <!-- ----------------------------------------------------------------- -->
2123 <title>How could I get any widgets position?</title>
2125 <para>As Tim Janik pointed out, there are different cases, and
2126 each case requires a different solution.</para>
2129 <listitem><simpara> If you want the position of a widget
2130 relative to its parent, you should use
2131 <literal>widget->allocation.x</literal> and
2132 <literal>widget->allocation.y</literal>.</simpara>
2135 <listitem><simpara> If you want the position of a window
2136 relative to the X root window, you should use
2137 <literal>gdk_window_get_geometry()</literal>
2138 <literal>gdk_window_get_position()</literal> or
2139 <literal>gdk_window_get_origin()</literal>.</simpara>
2142 <listitem><simpara> If you want to get the position of the
2143 window (including the WM decorations), you should use
2144 <literal>gdk_window_get_root_origin()</literal>.</simpara>
2147 <listitem><simpara> Last but not least, if you want to get a Window
2148 Manager frame position, you should use
2149 <literal>gdk_window_get_deskrelative_origin()</literal>.</simpara>
2153 <para>Your choice of Window Manager will have an effect of the
2154 results of the above functions. You should keep this in mind
2155 when writing your application. This is dependant upon how the
2156 Window Managers manage the decorations that they add around
2161 <!-- ----------------------------------------------------------------- -->
2164 <title>How do I set the size of a widget/window? How do I
2165 prevent the user resizing my window? <emphasis>[GTK 2.x]</emphasis></title>
2167 <para>The <literal>gtk_widget_set_size_request()</literal> function
2168 is used to set the size of a widget to a specific size.
2171 <literal>gtk_window_set_resizable()</literal> function sets whether
2172 the user can resize a window, which they can by default. The
2173 definition of these functions are:</para>
2175 <programlisting role="C">
2176 void gtk_widget_set_size_request (GtkWidget *widget,
2180 void gtk_window_set_resizable (GtkWindow *window,
2181 gboolean resizable);
2187 <!-- ----------------------------------------------------------------- -->
2190 <title>How do I add a popup menu to my GTK+ application?</title>
2192 <para>The <literal>menu</literal> example in the examples/menu
2193 directory of the GTK+ distribution implements a popup menu
2194 with this technique:</para>
2196 <programlisting role="C">
2197 static gint button_press (GtkWidget *widget, GdkEvent *event)
2200 if (event->type == GDK_BUTTON_PRESS) {
2201 GdkEventButton *bevent = (GdkEventButton *) event;
2202 gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
2203 bevent->button, bevent->time);
2204 /* Tell calling code that we have handled this event; the buck
2209 /* Tell calling code that we have not handled this event; pass it on. */
2216 <!-- ----------------------------------------------------------------- -->
2219 <title>How do I disable or enable a widget, such as a
2222 <para>To disable (or to enable) a widget, use the
2223 <literal>gtk_widget_set_sensitive()</literal> function. The
2224 first parameter is you widget pointer. The second parameter is
2225 a boolean value: when this value is TRUE, the widget is
2229 <!-- ----------------------------------------------------------------- -->
2232 <title>Shouldn't the text argument in the gtk_clist_*
2233 functions be declared const?</title>
2235 <para>For example:</para>
2237 <programlisting role="C">
2238 gint gtk_clist_prepend (GtkCList *clist,
2242 <para>Answer: No, while a type "gchar*" (pointer to char) can
2243 automatically be cast into "const gchar*" (pointer to const
2244 char), this does not apply for "gchar *[]" (array of an
2245 unspecified number of pointers to char) into "const gchar *[]"
2246 (array of an unspecified number of pointers to const char).</para>
2248 <para>The type qualifier "const" may be subject to automatic
2249 casting, but in the array case, it is not the array itself
2250 that needs the (const) qualified cast, but its members, thus
2251 changing the whole type.</para>
2254 <!-- ----------------------------------------------------------------- -->
2257 <title>How do I render pixels (image data) to the
2260 <para>There are several ways to approach this. The simplest
2261 way is to use GdkRGB, see gdk/gdkrgb.h. You create an RGB
2262 buffer, render to your RGB buffer, then use GdkRGB routines to
2263 copy your RGB buffer to a drawing area or custom widget. The
2264 book "GTK+/Gnome Application Development" gives some details;
2265 GdkRGB is also documented in the GTK+ reference
2266 documentation.</para>
2268 <para>If you're writing a game or other graphics-intensive
2269 application, you might consider a more elaborate
2270 solution. OpenGL is the graphics standard that will let you
2271 access hardware accelaration in future versions of XFree86; so
2272 for maximum speed, you probably want to use OpenGL. A
2273 GtkGLArea widget is available for using OpenGL with GTK+ (but
2274 GtkGLArea does not come with GTK+ itself). There are also
2275 several open source game libraries, such as ClanLib and Loki's
2276 Simple DirectMedia Layer library (SDL).</para>
2278 <para>You do NOT want to use
2279 <literal>gdk_draw_point()</literal>, that will be extremely
2283 <!-- ----------------------------------------------------------------- -->
2286 <title>How do I create a pixmap without having my window being
2287 realized/shown?</title>
2289 <para>Functions such as
2290 <literal>gdk_pixmap_create_from_xpm()</literal> require a
2291 valid window as a parameter. During the initialisation phase
2292 of an application, a valid window may not be available without
2293 showing a window, which may be inappropriate. In order to
2294 avoid this, a function such as
2295 <literal>gdk_pixmap_colormap_create_from_xpm</literal> can be
2298 <programlisting role="C">
2299 char *pixfile = "foo.xpm";
2300 GtkWidget *top, *box, *pixw;
2301 GdkPixmap *pixmap, *pixmap_mask;
2303 top = gtk_window_new (GKT_WINDOW_TOPLEVEL);
2304 box = gtk_hbox_new (FALSE, 4);
2305 gtk_conainer_add (GTK_CONTAINER(top), box);
2307 pixmap = gdk_pixmap_colormap_create_from_xpm (
2308 NULL, gtk_widget_get_colormap(top),
2309 &pixmap_mask, NULL, pixfile);
2310 pixw = gtk_pixmap_new (pixmap, pixmap_mask);
2311 gdk_pixmap_unref (pixmap);
2312 gdk_pixmap_unref (pixmap_mask);
2317 <!-- ----------------------------------------------------------------- -->
2320 <title>How do I do drag-and-drop?</title>
2322 <para>GTK+ has a high level set of functions for doing inter-process
2323 communication via the drag-and-drop system. GTK+ can perform
2324 drag-and-drop on top of the low level Xdnd and Motif drag-and-drop
2327 <para>The documentation on GTK+ drag-and-drop isn't complete, but there
2328 is some information in the <ulink
2329 url="http://www.gtk.org/tutorial/">Tutorial</ulink>. You should also
2330 look at the drag-and-drop example code that is part of the GTK+ source
2331 distribution, in the file <filename>gtk/testdnd.c</filename>.</para>
2335 <!-- ----------------------------------------------------------------- -->
2338 <title>Why does GTK+/GLib leak memory?</title>
2340 <para>It doesn't. Both GLib and the C library (malloc implementation)
2341 will cache allocated memory on occasion, even if you free it with
2344 <para>So you can't generally use tools such as top to see if you are
2345 using free() properly (aside from the very roughest of estimations, i.e.
2346 if you are really, really screwing up top will show that, but you can't
2347 distinguish small mistakes from the GLib/malloc caches).</para>
2349 <para>In order to find memory leaks, use proper memory profiling
2356 <!-- ***************************************************************** -->
2358 <title>Development with GTK+: widget specific questions</title>
2360 <!-- ----------------------------------------------------------------- -->
2363 <title>How do I find out about the selection of a GtkList?</title>
2365 <para>Get the selection something like this:</para>
2367 <programlisting role="C">
2369 sel = GTK_LIST(list)->selection;
2372 <para>This is how GList is defined (quoting glist.h):</para>
2374 <programlisting role="C">
2375 typedef struct _GList GList;
2385 <para>A GList structure is just a simple structure for doubly
2386 linked lists. There exist several g_list_*() functions to
2387 modify a linked list in glib.h. However the
2388 GTK_LIST(MyGtkList)->selection is maintained by the
2389 gtk_list_*() functions and should not be modified.</para>
2392 <para>The selection_mode of the GtkList determines the
2393 selection facilities of a GtkList and therefore the contents
2394 of GTK_LIST(AnyGtkList)->selection:</para>
2396 <informaltable frame="all">
2400 <entry><literal>selection_mode</literal></entry>
2401 <entry><literal> GTK_LIST()->selection</literal>
2408 <entry><literal>GTK_SELECTION_SINGLE</literal></entry>
2409 <entry>selection is either NULL or contains a GList*
2410 pointer for a single selected item.</entry>
2414 <entry><literal>GTK_SELECTION_BROWSE</literal></entry>
2415 <entry>selection is NULL if the list contains no
2416 widgets, otherwise it contains a GList*
2417 pointer for one GList structure.</entry>
2421 <entry><literal>GTK_SELECTION_MULTIPLE</literal></entry>
2422 <entry>selection is NULL if no listitems are selected
2423 or a a GList* pointer for the first selected
2424 item. that in turn points to a GList structure
2425 for the second selected item and so
2430 <entry><literal>GTK_SELECTION_EXTENDED</literal></entry>
2431 <entry>selection is NULL.</entry>
2438 <para>The data field of the GList structure
2439 GTK_LIST(MyGtkList)->selection points to the first
2440 GtkListItem that is selected. So if you would like to
2441 determine which listitems are selected you should go like
2444 <programlisting role="C">
2446 gchar *list_items[]={
2452 guint nlist_items=sizeof(list_items)/sizeof(list_items[0]);
2453 GtkWidget *list_item;
2456 list=gtk_list_new();
2457 gtk_list_set_selection_mode(GTK_LIST(list), GTK_SELECTION_MULTIPLE);
2458 gtk_container_add(GTK_CONTAINER(AnyGtkContainer), list);
2459 gtk_widget_show (list);
2461 for (i = 0; i < nlist_items; i++)
2463 list_item=gtk_list_item_new_with_label(list_items[i]);
2464 gtk_object_set_user_data(GTK_OBJECT(list_item), (gpointer)i);
2465 gtk_container_add(GTK_CONTAINER(list), list_item);
2466 gtk_widget_show(list_item);
2471 <para>To get known about the selection:</para>
2473 <programlisting role="C">
2477 items=GTK_LIST(list)->selection;
2479 printf("Selected Items: ");
2481 if (GTK_IS_LIST_ITEM(items->data))
2482 printf("%d ", (guint)
2483 gtk_object_get_user_data(items->data));
2492 <!-- ----------------------------------------------------------------- -->
2495 <title>How do I stop the column headings of a GtkCList
2496 disappearing when the list is scrolled?</title>
2498 <para>This happens when a GtkCList is packed into a
2499 GtkScrolledWindow using the function
2500 <literal>gtk_scroll_window_add_with_viewport()</literal>. The prefered
2501 method of adding a CList to a scrolled window is to use the
2502 function <literal>gtk_container_add</literal>, as in:</para>
2504 <programlisting role="C">
2505 GtkWidget *scrolled, *clist;
2506 char *titles[] = { "Title1" , "Title2" };
2508 scrolled = gtk_scrolled_window_new(NULL, NULL);
2510 clist = gtk_clist_new_with_titles(2, titles);
2511 gtk_container_add(GTK_CONTAINER(scrolled), clist);
2516 <!-- ----------------------------------------------------------------- -->
2519 <title>I don't want the user of my applications to enter text
2520 into a GtkCombo. Any idea?</title>
2522 <para>A GtkCombo has an associated entry which can be accessed
2523 using the following expression:</para>
2525 <programlisting role="C">
2526 GTK_COMBO(combo_widget)->entry
2529 <para>If you don't want the user to be able to modify the
2530 content of this entry, you can use the
2531 gtk_entry_set_editable() function:</para>
2534 <programlisting role="C">
2535 void gtk_entry_set_editable(GtkEntry *entry,
2539 <para>Set the editable parameter to FALSE to disable typing
2540 into the entry.</para>
2543 <!-- ----------------------------------------------------------------- -->
2546 <title>How do I catch a combo box change?</title>
2548 <para>The entry which is associated to your GtkCombo send a
2549 "changed" signal when:</para>
2552 <listitem><simpara>some text is typed in</simpara>
2555 <listitem><simpara>the selection of the combo box is changed</simpara>
2559 <para>To catch any combo box change, simply connect your
2560 signal handler with</para>
2562 <programlisting role="C">
2563 gtk_signal_connect(GTK_COMBO(cb)->entry,
2565 GTK_SIGNAL_FUNC(my_cb_change_handler),
2571 <!-- ----------------------------------------------------------------- -->
2574 <title>How can I define a separation line in a menu?</title>
2576 <para>See the <ulink
2577 url="http://www.gtk.org/tutorial/">Tutorial</ulink> for
2578 information on how to create menus. However, to create a
2579 separation line in a menu, just insert an empty menu item:</para>
2581 <programlisting role="C">
2582 menuitem = gtk_menu_item_new();
2583 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
2584 gtk_widget_show(menuitem);
2589 <!-- ----------------------------------------------------------------- -->
2592 <title>How can I right justify a menu, such as Help?</title>
2594 <para>Depending on if you use the MenuFactory or not, there
2595 are two ways to proceed. With the MenuFactory, use something
2596 like the following:</para>
2598 <programlisting role="C">
2599 menu_path = gtk_menu_factory_find (factory, "<MyApp>/Help");
2600 gtk_menu_item_right_justify(menu_path->widget);
2603 <para>If you do not use the MenuFactory, you should simply
2607 <programlisting role="C">
2608 gtk_menu_item_right_justify(my_menu_item);
2613 <!-- ----------------------------------------------------------------- -->
2616 <title>How do I add some underlined accelerators to menu
2619 <para>Damon Chaplin, the technical force behind the Glade
2620 project, provided the following code sample (this code is an
2621 output from Glade). It creates a small <GUIMenu>File</guimenu> menu item
2622 with only one child (<guimenu>New</guimenu>). The F in
2623 <guimenu>File</guimenu> and the N in <guimenu>New</guimenu> are
2624 underlined, and the relevant accelerators are created.</para>
2626 <programlisting role="C">
2627 menubar1 = gtk_menu_bar_new ();
2628 gtk_object_set_data (GTK_OBJECT (window1), "menubar1", menubar1);
2629 gtk_widget_show (menubar1);
2630 gtk_box_pack_start (GTK_BOX (vbox1), menubar1, FALSE, FALSE, 0);
2632 file1 = gtk_menu_item_new_with_label ("");
2633 tmp_key = gtk_label_parse_uline (GTK_LABEL (GTK_BIN (file1)->child),
2635 gtk_widget_add_accelerator (file1, "activate_item", accel_group,
2636 tmp_key, GDK_MOD1_MASK, 0);
2637 gtk_object_set_data (GTK_OBJECT (window1), "file1", file1);
2638 gtk_widget_show (file1);
2639 gtk_container_add (GTK_CONTAINER (menubar1), file1);
2641 file1_menu = gtk_menu_new ();
2642 file1_menu_accels = gtk_menu_ensure_uline_accel_group (GTK_MENU (file1_menu));
2643 gtk_object_set_data (GTK_OBJECT (window1), "file1_menu", file1_menu);
2644 gtk_menu_item_set_submenu (GTK_MENU_ITEM (file1), file1_menu);
2646 new1 = gtk_menu_item_new_with_label ("");
2647 tmp_key = gtk_label_parse_uline (GTK_LABEL (GTK_BIN (new1)->child),
2649 gtk_widget_add_accelerator (new1, "activate_item", file1_menu_accels,
2651 gtk_object_set_data (GTK_OBJECT (window1), "new1", new1);
2652 gtk_widget_show (new1);
2653 gtk_container_add (GTK_CONTAINER (file1_menu), new1);
2658 <!-- ----------------------------------------------------------------- -->
2661 <title>How can I retrieve the text from a GtkMenuItem?</title>
2663 <para>You can usually retrieve the label of a specific
2664 GtkMenuItem with:</para>
2666 <programlisting role="C">
2667 if (GTK_BIN (menu_item)->child)
2669 GtkWidget *child = GTK_BIN (menu_item)->child;
2671 /* do stuff with child */
2672 if (GTK_IS_LABEL (child))
2676 gtk_label_get (GTK_LABEL (child), &text);
2677 g_print ("menu item text: %s\n", text);
2682 <para>To get the active menu item from a GtkOptionMenu you can
2685 <programlisting role="C">
2686 if (GTK_OPTION_MENU (option_menu)->menu_item)
2688 GtkWidget *menu_item = GTK_OPTION_MENU (option_menu)->menu_item;
2692 <para>But, there's a catch. For this specific case, you can
2693 <emphasis>not</emphasis> get the label widget from
2694 <literal>menu_item</literal> with the above code, because the
2695 option menu reparents the menu_item's child temporarily to
2696 display the currently active contents. So to retrive the child
2697 of the currently active menu_item of an option menu, you'll
2700 <programlisting role="C">
2701 if (GTK_BIN (option_menu)->child)
2703 GtkWidget *child = GTK_BIN (option_menu)->child;
2705 /* do stuff with child */
2711 <!-- ----------------------------------------------------------------- -->
2714 <title>How do I right (or otherwise) justify a
2717 <para>Are you sure you want to <emphasis>justify</emphasis>
2718 the labels? The label class contains the
2719 <literal>gtk_label_set_justify()</literal> function that is
2720 used to control the justification of a multi-line
2723 <para>What you probably want is to set the <emphasis>alignment</emphasis>
2724 of the label, ie right align it, center it or left align
2725 it. If you want to do this, you should use:</para>
2727 <programlisting role="C">
2728 void gtk_misc_set_alignment (GtkMisc *misc,
2733 <para>where the <literal>xalign</literal> and
2734 <literal>yalign</literal> values are floats in
2737 <programlisting role="C">
2740 /* horizontal : left align, vertical : top */
2741 gtk_misc_set_alignment(GTK_MISC(label), 0.0f, 0.0f);
2743 /* horizontal : centered, vertical : centered */
2744 gtk_misc_set_alignment(GTK_MISC(label), 0.5f, 0.5f);
2746 /* horizontal : right align, vertical : bottom */
2747 gtk_misc_set_alignment(GTK_MISC(label), 1.0f, 1.0f);
2752 <!-- ----------------------------------------------------------------- -->
2755 <title>How do I set the background color of a GtkLabel
2758 <para>The GtkLabel widget is one of a few GTK+ widgets that
2759 don't create their own window to render themselves
2760 into. Instead, they draw themselves directly onto their
2761 parents window.</para>
2763 <para>This means that in order to set the background color for
2764 a GtkLabel widget, you need to change the background color of
2765 its parent, i.e. the object that you pack it into.</para>
2769 <!-- ----------------------------------------------------------------- -->
2772 <title>How do I set the color and font of a GtkLabel using a
2773 Resource File?</title>
2775 <para>The widget name path constructed for a Label consists of
2776 the widget names of its object hierarchy as well, e.g.</para>
2778 <para><literallayout>
2779 <literal>window (name: humphrey)</literal>
2780 <literal> hbox</literal>
2781 <literal> label (name: mylabel)</literal>
2782 </literallayout></para>
2784 <para>The widget path your pattern needs to match would be:
2785 <literal>humphrey.GtkHBox.mylabel</literal></para>
2787 <para>The resource file may look something like:</para>
2789 <programlisting role="C">
2792 fg[NORMAL] = {1.0, 0.0, 0.0}
2793 font = "-adobe-helvetica-bold-r-normal--*-140-*-*-*-*-*-*"
2795 widget "*mylabel" style "title"
2798 <para>In your program, you would also need to give a name to
2799 the Label widget, which can be done using:</para>
2801 <programlisting role="C">
2802 label = gtk_label_new("Some Label Text");
2803 gtk_widget_set_name(label, "mylabel");
2804 gtk_widget_show(label);
2809 <!-- ----------------------------------------------------------------- -->
2812 <title>How do I configure Tooltips in a Resource File?</title>
2814 <para>The tooltip's window is named "gtk-tooltips",
2815 GtkTooltips in itself is not a GtkWidget (though a GtkObject)
2816 and as such is not attempted to match any widget styles.</para>
2818 <para>So, you resource file should look something like:</para>
2820 <programlisting role="C">
2823 bg[NORMAL] = {1.0, 1.0, 0.0}
2825 widget "gtk-tooltips*" style "postie"
2830 <!-- ----------------------------------------------------------------- -->
2833 <title>I can't add more than (something like) 2000 chars in a
2834 GtkEntry. What's wrong?</title>
2836 <para>There is now a known problem in the GtkEntry widget. In
2837 the <literal>gtk_entry_insert_text()</literal> function, the
2838 following lines limit the number of chars in the entry to
2841 <programlisting role="C">
2842 /* The algorithms here will work as long as, the text size (a
2843 * multiple of 2), fits into a guint16 but we specify a shorter
2844 * maximum length so that if the user pastes a very long text, there
2845 * is not a long hang from the slow X_LOCALE functions. */
2847 if (entry->text_max_length == 0)
2850 max_length = MIN (2047, entry->text_max_length);
2855 <!-- ----------------------------------------------------------------- -->
2858 <title>How do I make a GtkEntry widget activate on pressing
2859 the Return key?</title>
2861 <para>The Entry widget emits an 'activate' signal when you
2862 press return in it. Just attach to the activate signal on the
2863 entry and do whatever you want to do. Typical code would
2866 <programlisting role="C">
2867 entry = gtk_entry_new();
2868 gtk_signal_connect (GTK_OBJECT(entry), "activate",
2869 GTK_SIGNAL_FUNC(entry_callback),
2875 <!-- ----------------------------------------------------------------- -->
2878 <title>How do I validate/limit/filter the input to a GtkEntry? <emphasis>[GTK 2.x]</emphasis></title>
2880 <para>If you want to validate the text that a user enters into
2881 a GtkEntry widget you can attach to the "insert_text" signal
2882 of the entry, and modify the text within the callback
2883 function. The example below forces all characters to
2884 uppercase, and limits the range of characters to A-Z. Note
2885 that the entry is cast to an object of type GtkEditable, from
2886 which GtkEntry is derived.</para>
2888 <programlisting role="C">
2889 #include <ctype.h>
2890 #include <gtk/gtk.h>
2892 void insert_text_handler (GtkEntry *entry,
2898 GtkEditable *editable = GTK_EDITABLE(entry);
2900 gchar *result = g_new (gchar, length);
2902 for (i=0; i < length; i++) {
2903 if (!isalpha(text[i]))
2905 result[count++] = islower(text[i]) ? toupper(text[i]) : text[i];
2909 g_signal_handlers_block_by_func (G_OBJECT (editable),
2910 G_CALLBACK (insert_text_handler),
2912 gtk_editable_insert_text (editable, result, count, position);
2913 g_signal_handlers_unblock_by_func (G_OBJECT (editable),
2914 G_CALLBACK (insert_text_handler),
2917 g_signal_stop_emission_by_name (G_OBJECT (editable), "insert_text");
2928 gtk_init (&argc, &argv);
2930 /* create a new window */
2931 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2932 gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
2933 g_signal_connect (G_OBJECT (window), "destroy",
2934 G_CALLBACK (gtk_main_quit),
2937 entry = gtk_entry_new();
2938 g_signal_connect(G_OBJECT(entry), "insert_text",
2939 G_CALLBACK(insert_text_handler),
2941 gtk_container_add(GTK_CONTAINER (window), entry);
2942 gtk_widget_show(entry);
2944 gtk_widget_show(window);
2953 <!-- ----------------------------------------------------------------- -->
2956 <title>How do I use horizontal scrollbars with a GtkText widget?</title>
2958 <para>The short answer is that you can't. The current version
2959 of the GtkText widget does not support horizontal
2960 scrolling. There is an intention to completely rewrite the
2961 GtkText widget, at which time this limitation will be
2966 <!-- ----------------------------------------------------------------- -->
2969 <title>How do I change the font of a GtkText widget?</title>
2971 <para>There are a couple of ways of doing this. As GTK+ allows
2972 the appearance of applications to be changed at run time using
2973 resources you can use something like the following in the
2974 appropriate file:</para>
2976 <programlisting role="C">
2979 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
2983 <para>Another way to do this is to load a font within your
2984 program, and then use this in the functions for adding text to
2985 the text widget. You can load a font using, for example:</para>
2987 <programlisting role="C">
2989 font = gdk_font_load("-adobe-helvetica-medium-r-normal--*-140-*-*-*-*-*-*");
2994 <!-- ----------------------------------------------------------------- -->
2997 <title>How do I set the cursor position in a GtkText
3000 <para>Notice that the response is valid for any object that
3001 inherits from the GtkEditable class.</para>
3003 <para>Are you sure that you want to move the cursor position?
3004 Most of the time, while the cursor position is good, the
3005 insertion point does not match the cursor position. If this
3006 apply to what you really want, then you should use the
3007 <literal>gtk_text_set_point()</literal> function. If you want
3008 to set the insertion point at the current cursor position, use
3009 the following:</para>
3011 <programlisting role="C">
3012 gtk_text_set_point(GTK_TEXT(text),
3013 gtk_editable_get_position(GTK_EDITABLE(text)));
3016 <para>If you want the insertion point to follow the cursor at
3017 all time, you should probably catch the button press event,
3018 and then move the insertion point. Be careful : you'll have to
3019 catch it after the widget has changed the cursor position
3020 though. Thomas Mailund Jensen proposed the following
3023 <programlisting role="C">
3025 insert_bar (GtkWidget *text)
3027 /* jump to cursor mark */
3028 gtk_text_set_point (GTK_TEXT (text),
3029 gtk_editable_get_position (GTK_EDITABLE (text)));
3031 gtk_text_insert (GTK_TEXT (text), NULL, NULL, NULL,
3032 "bar", strlen ("bar"));
3036 main (int argc, char *argv[])
3038 GtkWidget *window, *text;
3040 gtk_init (&argc, &argv);
3042 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3043 text = gtk_text_new (NULL, NULL);
3044 gtk_text_set_editable (GTK_TEXT (text), TRUE);
3045 gtk_container_add (GTK_CONTAINER (window), text);
3047 /* connect after everything else */
3048 gtk_signal_connect_after (GTK_OBJECT(text), "button_press_event",
3049 GTK_SIGNAL_FUNC (insert_bar), NULL);
3051 gtk_widget_show_all(window);
3058 <para>Now, if you really want to change the cursor position,
3060 <literal>gtk_editable_set_position()</literal>
3067 <!-- ***************************************************************** -->
3069 <title>About GDK</title>
3071 <!-- ----------------------------------------------------------------- -->
3074 <title>What is GDK?</title>
3076 <para>GDK is basically a wrapper around the standard Xlib
3077 function calls. If you are at all familiar with Xlib, a lot of
3078 the functions in GDK will require little or no getting used
3079 to. All functions are written to provide an way to access Xlib
3080 functions in an easier and slightly more intuitive manner. In
3081 addition, since GDK uses GLib (see below), it will be more
3082 portable and safer to use on multiple platforms.</para>
3084 <!-- Examples, anybody? I've been mulling some over. NF -->
3088 <!-- ----------------------------------------------------------------- -->
3091 <title>How do I use color allocation?</title>
3093 <para>One of the nice things about GDK is that it's based on
3094 top of Xlib; this is also a problem, especially in the area of
3095 color management. If you want to use color in your program
3096 (drawing a rectangle or such, your code should look something
3099 <programlisting role="C">
3108 /* first, create a GC to draw on */
3109 gc = gdk_gc_new(widget->window);
3111 /* find proper dimensions for rectangle */
3112 gdk_window_get_size(widget->window, &width, &height);
3114 /* the color we want to use */
3115 color = (GdkColor *)malloc(sizeof(GdkColor));
3117 /* red, green, and blue are passed values, indicating the RGB triple
3118 * of the color we want to draw. Note that the values of the RGB components
3119 * within the GdkColor are taken from 0 to 65535, not 0 to 255.
3121 color->red = red * (65535/255);
3122 color->green = green * (65535/255);
3123 color->blue = blue * (65535/255);
3125 /* the pixel value indicates the index in the colormap of the color.
3126 * it is simply a combination of the RGB values we set earlier
3128 color->pixel = (gulong)(red*65536 + green*256 + blue);
3130 /* However, the pixel valule is only truly valid on 24-bit (TrueColor)
3131 * displays. Therefore, this call is required so that GDK and X can
3132 * give us the closest color available in the colormap
3134 gdk_color_alloc(gtk_widget_get_colormap(widget), color);
3136 /* set the foreground to our color */
3137 gdk_gc_set_foreground(gc, color);
3139 /* draw the rectangle */
3140 gdk_draw_rectangle(widget->window, gc, 1, 0, 0, width, height);
3150 <!-- ***************************************************************** -->
3152 <title>About GLib</title>
3154 <!-- ----------------------------------------------------------------- -->
3157 <title>What is GLib?</title>
3159 <para>GLib is a library of useful functions and definitions
3160 available for use when creating GDK and GTK applications. It
3161 provides replacements for some standard libc functions, such
3162 as malloc, which are buggy on some systems.</para>
3164 <para>It also provides routines for handling:</para>
3166 <itemizedlist spacing=compact>
3167 <listitem><simpara>Doubly Linked Lists</simpara>
3170 <listitem><simpara>Singly Linked Lists</simpara>
3173 <listitem><simpara>Timers</simpara>
3176 <listitem><simpara>String Handling</simpara>
3179 <listitem><simpara>A Lexical Scanner</simpara>
3182 <listitem><simpara>Error Functions</simpara>
3188 <!-- ----------------------------------------------------------------- -->
3191 <title>How can I use the doubly linked lists?</title>
3193 <para>The GList object is defined as:</para>
3195 <programlisting role="C">
3196 typedef struct _GList GList;
3206 <para>To use the GList objects, simply:</para>
3208 <programlisting role="C">
3211 gint array[] = { 1, 2, 3, 4, 5, 6 };
3215 /* add data to the list */
3216 for (pos=0;pos < sizeof array; pos++) {
3217 list = g_list_append(list, (gpointer)&array[pos]);
3220 /* run through the list */
3221 listrunner = g_list_first(list);
3222 while (listrunner) {
3223 value = (gint *)listrunner->data;
3224 printf("%d\n", *value);
3225 listrunner = g_list_next(listrunner);
3228 /* removing datas from the list */
3229 listrunner = g_list_first(list);
3230 list = g_list_remove_link(list, listrunner);
3231 list = g_list_remove(list, &array[4]);
3234 <para>The same code is usable with singly linked lists (GSList
3235 objects) by replacing g_list_* functions with the relevant
3236 g_slist_* ones (g_slist_append, g_slist_remove, ...). Just
3237 remember that since you can't go backward in a singly linked
3238 list, there is no g_slist_first function - you'll need to keep
3239 a reference on the first node of the list.</para>
3241 <!-- Some Examples might be useful here! NF -->
3242 <!-- I believe it should be better :) ED -->
3243 <!-- Linked lists are pretty standard data structures - don't want to
3244 over do it - TRG -->
3248 <!-- ----------------------------------------------------------------- -->
3251 <title>Memory does not seem to be released when I free the
3252 list nodes I've allocated</title>
3254 <para>GLib tries to be "intelligent" on this special issue: it
3255 assumes that you are likely to reuse the objects, so caches
3256 the allocated memory. If you do not want to use this behavior,
3257 you'll probably want to set up a special allocator.</para>
3259 <para>To quote Tim Janik:</para>
3260 <para><quote>If you have a certain portion of code that uses *lots*
3261 of GLists or GNodes, and you know you'd better want to release
3262 all of them after a short while, you'd want to use a
3263 GAllocator. Pushing an allocator into g_list will make all
3264 subsequent glist operations private to that allocator's memory
3265 pool (and thus you have to take care to pop the allocator
3266 again, before making any external calls): </quote></para>
3268 <programlisting role="C">
3269 GAllocator *allocator;
3273 /* set a new allocation pool for GList nodes */
3274 allocator = g_allocator_new ("list heap", 1024);
3275 g_list_push_allocator (allocator);
3277 /* do some list operations */
3278 for (i = 0; i < 4096; i++)
3279 list = g_list_prepend (list, NULL);
3280 list = g_list_reverse (list);
3282 /* beware to pop allocator befor calling external functions */
3283 g_list_pop_allocator ();
3284 gtk_label_set_text (GTK_LABEL (some_label), "some text");
3286 /* and set our private glist pool again */
3287 g_list_push_allocator (allocator);
3289 /* do some list operations */
3292 for (i = 0; i < 4096; i++)
3293 list = g_list_prepend (list, NULL);
3295 /* and back out (while freeing all of the list nodes in our pool) */
3296 g_list_pop_allocator ();
3297 g_allocator_free (allocator);
3302 <!-- ----------------------------------------------------------------- -->
3305 <title>Why use g_print, g_malloc, g_strdup and fellow glib
3308 <para>Thanks to Tim Janik who wrote to gtk-list: (slightly
3311 <para><quote>Regarding g_malloc(), g_free() and siblings, these
3312 functions are much safer than their libc equivalents. For
3313 example, g_free() just returns if called with NULL. Also, if
3314 USE_DMALLOC is defined, the definition for these functions
3315 changes (in glib.h) to use MALLOC(), FREE() etc... If
3316 MEM_PROFILE or MEM_CHECK are defined, there are even small
3317 statistics made counting the used block sizes (shown by
3318 g_mem_profile() / g_mem_check()).</quote></para>
3320 <para><quote>Considering the fact that glib provides an interface for
3321 memory chunks to save space if you have lots of blocks that
3322 are always the same size and to mark them ALLOC_ONLY if
3323 needed, it is just straight forward to create a small saver
3324 (debug able) wrapper around the normal malloc/free stuff as
3325 well - just like gdk covers Xlib. ;)</quote></para>
3327 <para><quote>Using g_error() and g_warning() inside of applications
3328 like the GIMP that fully rely on gtk even gives the
3329 opportunity to pop up a window showing the messages inside of
3330 a gtk window with your own handler (by using
3331 g_set_error_handler()) along the lines of
3332 <literal>gtk_print()</literal> (inside of
3333 gtkmain.c).</quote></para>
3337 <!-- ----------------------------------------------------------------- -->
3340 <title>What's a GScanner and how do I use one?</title>
3342 <para>A GScanner will tokenize your text, that is, it'll return
3343 an integer for every word or number that appears in its input
3344 stream, following certain (customizable) rules to perform this
3345 translation. You still need to write the parsing functions on
3346 your own though.</para>
3348 <para>Here's a little test program supplied by Tim Janik that
3351 <para><literallayout>
3352 <literal><SYMBOL> = <OPTIONAL-MINUS> <NUMBER> ;</literal>
3353 </literallayout></para>
3355 <para>constructs, while skipping "#\n" and "/**/" style
3358 <programlisting role="C">
3359 #include <glib.h>
3361 /* some test text to be fed into the scanner */
3362 static const gchar *test_text =
3364 "/* slide in some \n"
3365 " * comments, just for the\n"
3370 "# the next value is a float\n"
3373 "ping = - 0.5;\n" );
3375 /* define enumeration values to be returned for specific symbols */
3377 SYMBOL_PING = G_TOKEN_LAST + 1,
3378 SYMBOL_PONG = G_TOKEN_LAST + 2,
3379 SYMBOL_ZONK = G_TOKEN_LAST + 3
3383 static const struct {
3387 { "ping", SYMBOL_PING, },
3388 { "pong", SYMBOL_PONG, },
3389 { "zonk", SYMBOL_ZONK, },
3391 }, *symbol_p = symbols;
3393 static gfloat ping = 0;
3394 static gfloat pong = 0;
3395 static gfloat zonk = 0;
3398 parse_symbol (GScanner *scanner)
3401 gboolean negate = FALSE;
3403 /* expect a valid symbol */
3404 g_scanner_get_next_token (scanner);
3405 symbol = scanner->token;
3406 if (symbol < SYMBOL_PING ||
3407 symbol > SYMBOL_ZONK)
3408 return G_TOKEN_SYMBOL;
3411 g_scanner_get_next_token (scanner);
3412 if (scanner->token != '=')
3415 /* feature optional '-' */
3416 g_scanner_peek_next_token (scanner);
3417 if (scanner->next_token == '-')
3419 g_scanner_get_next_token (scanner);
3423 /* expect a float (ints are converted to floats on the fly) */
3424 g_scanner_get_next_token (scanner);
3425 if (scanner->token != G_TOKEN_FLOAT)
3426 return G_TOKEN_FLOAT;
3428 /* make sure the next token is a ';' */
3429 if (g_scanner_peek_next_token (scanner) != ';')
3431 /* not so, eat up the non-semicolon and error out */
3432 g_scanner_get_next_token (scanner);
3436 /* assign value, eat the semicolon and exit successfully */
3440 ping = negate ? - scanner->value.v_float : scanner->value.v_float;
3443 pong = negate ? - scanner->value.v_float : scanner->value.v_float;
3446 zonk = negate ? - scanner->value.v_float : scanner->value.v_float;
3449 g_scanner_get_next_token (scanner);
3451 return G_TOKEN_NONE;
3455 main (int argc, char *argv[])
3458 guint expected_token;
3460 scanner = g_scanner_new (NULL);
3462 /* adjust lexing behaviour to suit our needs
3464 /* convert non-floats (octal values, hex values...) to G_TOKEN_INT */
3465 scanner->config->numbers_2_int = TRUE;
3466 /* convert G_TOKEN_INT to G_TOKEN_FLOAT */
3467 scanner->config->int_2_float = TRUE;
3468 /* don't return G_TOKEN_SYMBOL, but the symbol's value */
3469 scanner->config->symbol_2_token = TRUE;
3471 /* load symbols into the scanner */
3472 while (symbol_p->symbol_name)
3474 g_scanner_add_symbol (scanner,
3475 symbol_p->symbol_name,
3476 GINT_TO_POINTER (symbol_p->symbol_token));
3480 /* feed in the text */
3481 g_scanner_input_text (scanner, test_text, strlen (test_text));
3483 /* give the error handler an idea on how the input is named */
3484 scanner->input_name = "test text";
3486 /* scanning loop, we parse the input until its end is reached,
3487 * the scanner encountered a lexing error, or our sub routine came
3488 * across invalid syntax
3492 expected_token = parse_symbol (scanner);
3494 g_scanner_peek_next_token (scanner);
3496 while (expected_token == G_TOKEN_NONE &&
3497 scanner->next_token != G_TOKEN_EOF &&
3498 scanner->next_token != G_TOKEN_ERROR);
3500 /* give an error message upon syntax errors */
3501 if (expected_token != G_TOKEN_NONE)
3502 g_scanner_unexp_token (scanner, expected_token, NULL, "symbol", NULL, NULL, TRUE);
3504 /* finsish parsing */
3505 g_scanner_destroy (scanner);
3508 g_print ("ping: %f\n", ping);
3509 g_print ("pong: %f\n", pong);
3510 g_print ("zonk: %f\n", zonk);
3516 <para>You need to understand that the scanner will parse its
3517 input and tokenize it, it is up to you to interpret these
3518 tokens, not define their types before they get parsed,
3519 e.g. watch gscanner parse a string:</para>
3521 <para><literallayout>
3522 <literal>"hi i am 17"</literal>
3523 <literal> | | | |</literal>
3524 <literal> | | | v</literal>
3525 <literal> | | v TOKEN_INT, value: 17</literal>
3526 <literal> | v TOKEN_IDENTIFIER, value: "am"</literal>
3527 <literal> v TOKEN_CHAR, value: 'i'</literal>
3528 <literal>TOKEN_IDENTIFIER, value: "hi"</literal>
3529 </literallayout></para>
3531 <para>If you configure the scanner with:</para>
3533 <programlisting role="C">
3534 scanner->config->int_2_float = TRUE;
3535 scanner->config->char_2_token = TRUE;
3536 scanner->config->scan_symbols = TRUE;
3539 <para>and add "am" as a symbol with</para>
3541 <programlisting role="C">
3542 g_scanner_add_symbol (scanner, "am", "symbol value");
3545 <para>GScanner will parse it as</para>
3547 <para><literallayout>
3548 <literal>"hi i am 17"</literal>
3549 <literal> | | | |</literal>
3550 <literal> | | | v</literal>
3551 <literal> | | v TOKEN_FLOAT, value: 17.0 (automatic int->float conversion)</literal>
3552 <literal> | | TOKEN_SYMBOL, value: "symbol value" (a successfull hash table lookup</literal>
3553 <literal> | | turned a TOKEN_IDENTIFIER into a</literal>
3554 <literal> | | TOKEN_SYMBOL and took over the</literal>
3555 <literal> | v symbol's value)</literal>
3556 <literal> v 'i' ('i' can be a valid token as well, as all chars >0 and <256)</literal>
3557 <literal>TOKEN_IDENTIFIER, value: "hi"</literal>
3558 </literallayout></para>
3560 <para>You need to match the token sequence with your code, and
3561 if you encounter something that you don't want, you error
3564 <programlisting role="C">
3565 /* expect an identifier ("hi") */
3566 g_scanner_get_next_token (scanner);
3567 if (scanner->token != G_TOKEN_IDENTIFIER)
3568 return G_TOKEN_IDENTIFIER;
3569 /* expect a token 'i' */
3570 g_scanner_get_next_token (scanner);
3571 if (scanner->token != 'i')
3573 /* expect a symbol ("am") */
3574 g_scanner_get_next_token (scanner);
3575 if (scanner->token != G_TOKEN_SYMBOL)
3576 return G_TOKEN_SYMBOL;
3577 /* expect a float (17.0) */
3578 g_scanner_get_next_token (scanner);
3579 if (scanner->token != G_TOKEN_FLOAT)
3580 return G_TOKEN_FLOAT;
3583 <para>If you got past here, you have parsed "hi i am 17" and
3584 would have accepted "dooh i am 42" and "bah i am 0.75" as
3585 well, but you would have not accepted "hi 7 am 17" or "hi i hi
3592 <!-- ***************************************************************** -->
3595 <title>GTK+ FAQ Contributions, Maintainers and Copyright</title>
3597 <para>If you would like to make a contribution to the FAQ, send either one
3598 of us an e-mail message with the exact text you think should be
3599 included (question and answer). With your help, this document can grow
3600 and become more useful!</para>
3602 <para>This document is maintained by
3604 <ulink url="mailto:gale@gtk.org"><gale@gtk.org></ulink>
3606 This FAQ was created by Shawn T. Amundson
3607 <ulink url="mailto:amundson@gimp.org">
3608 <amundson@gimp.org></ulink>.
3610 Contributions should be sent to Tony Gale <ulink
3611 url="mailto:gale@gtk.org"><gale@gtk.org></ulink></para>
3613 <para>The GTK+ FAQ is Copyright (C) 1997-2003 by Shawn T. Amundson,
3616 <para>Permission is granted to make and distribute verbatim copies of this
3617 manual provided the copyright notice and this permission notice are
3618 preserved on all copies.</para>
3620 <para>Permission is granted to copy and distribute modified versions of this
3621 document under the conditions for verbatim copying, provided that this
3622 copyright notice is included exactly as in the original, and that the
3623 entire resulting derived work is distributed under the terms of a
3624 permission notice identical to this one.</para>
3626 <para>Permission is granted to copy and distribute translations of this
3627 document into another language, under the above conditions for
3628 modified versions.</para>
3630 <para>If you are intending to incorporate this document into a published
3631 work, please contact one of the maintainers, and we will make an
3632 effort to ensure that you have the most up to date information
3635 <para>There is no guarentee that this document lives up to its intended
3636 purpose. This is simply provided as a free resource. As such, the
3637 authors and maintainers of the information provided within can not
3638 make any guarentee that the information is even accurate.</para>
3642 <!-- ----------------------------------------------------------------- -->