]> Pileus Git - ~andy/gtk/blob - docs/faq/gtk-faq.sgml
Rename configure.in to configure.ac
[~andy/gtk] / docs / faq / gtk-faq.sgml
1 <!doctype book PUBLIC "-//OASIS//DTD DocBook V3.1//EN" []>
2 <book>
3
4 <bookinfo>
5   <date>January 14th 2004</date>
6   <title>GTK+ FAQ</title>
7   <authorgroup>
8     <author>
9 <firstname>Tony</firstname>
10 <surname>Gale</surname>
11     </author>
12     <author>
13 <firstname>Shawn</firstname>
14 <surname>Amundson</surname>
15     </author>
16     <author>
17 <firstname>Emmanuel</firstname>
18 <surname>Deloget</surname>
19     </author>
20   </authorgroup>
21   <abstract>
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>
27   </abstract>
28 </bookinfo>
29
30 <toc></toc>
31
32 <!-- ***************************************************************** -->
33 <chapter>
34 <title>General Information</title>
35
36 <!-- ----------------------------------------------------------------- -->
37
38 <sect1>
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.
45 </para>
46 </sect1>
47
48 <!-- ----------------------------------------------------------------- -->
49
50 <sect1>
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>
54 <listitem>
55 <simpara>Havoc Pennington</simpara>
56 </listitem>
57 <listitem>
58 <simpara>Erik Mouw</simpara>
59 </listitem>
60 <listitem>
61 <simpara>Owen Taylor</simpara>
62 </listitem>
63 <listitem>
64 <simpara>Tim Janik</simpara>
65 </listitem>
66 <listitem>
67 <simpara>Thomas Mailund Jensen</simpara>
68 </listitem>
69 <listitem>
70 <simpara>Joe Pfeiffer</simpara>
71 </listitem>
72 <listitem>
73 <simpara>Andy Kahn</simpara>
74 </listitem>
75 <listitem>
76 <simpara>Federico Mena Quntero</simpara>
77 </listitem>
78 <listitem>
79 <simpara>Damon Chaplin</simpara>
80 </listitem>
81 <listitem>
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>
86 </sect1>
87
88 <!-- ----------------------------------------------------------------- -->
89
90 <sect1>
91 <title>Authors <emphasis>[GTK 2.x]</emphasis></title>
92
93 <para>The original authors of GTK+ were:</para>
94
95 <itemizedlist spacing=Compact>
96 <listitem>
97 <simpara>Peter Mattis</simpara>
98 </listitem>
99 <listitem>
100 <simpara>Spencer Kimball</simpara>
101 </listitem>
102 <listitem>
103 <simpara>Josh MacDonald</simpara>
104 </listitem>
105 </itemizedlist>
106
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>
110
111
112 <itemizedlist spacing=Compact>
113 <listitem>
114 <simpara>Owen Taylor</simpara>
115 </listitem>
116 <listitem>
117 <simpara>Matthias Clasen</simpara>
118 </listitem>
119 <listitem>
120 <simpara>Federico Mena Quintero</simpara>
121 </listitem>
122 <listitem>
123 <simpara>Soeren Sandmann</simpara>
124 </listitem>
125 <listitem>
126 <simpara>Padraig O'Briain</simpara>
127 </listitem>
128 <listitem>
129 <simpara>Manish Singh</simpara>
130 </listitem>
131 <listitem>
132 <simpara>Kristian Rietveld</simpara>
133 </listitem>
134 <listitem>
135 <simpara>Tor Lillqvist</simpara>
136 </listitem>
137 </itemizedlist>
138
139 </sect1>
140
141 <!-- ----------------------------------------------------------------- -->
142
143 <sect1>
144 <title>What is GTK+? <emphasis>[GTK 2.x]</emphasis></title>
145
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>
151
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>
156
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
160 or royalties.</para>
161
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
167 development..</para>
168 </sect1>
169
170 <!-- ----------------------------------------------------------------- -->
171
172 <sect1>
173 <title>What is the + in GTK+? <emphasis>[GTK 2.x]</emphasis></title>
174
175 <para>Peter Mattis informed the gtk mailing list that:</para>
176
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>
186
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>
190
191 <para>GTK+ is now additionally based upon the Pango and ATK
192 libraries, that provide text layout and rendering and accessibility
193 interfaces.</para>
194 </sect1>
195
196 <!-- ----------------------------------------------------------------- -->
197
198 <sect1>
199 <title>Does the G in GTK+, GDK and GLib stand for? <emphasis>[GTK 2.x]</emphasis></title>
200
201 <para>GTK+ == The GIMP Toolkit</para>
202 <para>GDK == GTK+ Drawing Kit</para>
203 <para>GLib == G Library</para>
204
205 </sect1>
206
207 <!-- ----------------------------------------------------------------- -->
208
209 <sect1>
210 <title>Where is the documentation for GTK+? <emphasis>[GTK 2.x]</emphasis></title>
211
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
214 GTK Tutorial.</para>
215
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
223 </ulink></para>
224
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>
228
229 <itemizedlist>
230 <listitem><simpara>Eric Harlows book entitled "Developing
231 Linux Applications with GTK+ and GDK". The ISBN is
232 0-7357-0021-4</simpara>
233 </listitem>
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>
238 </listitem>
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/
245 </ulink></simpara>
246 <simpara>And Havoc maintains information about it and
247 errata here: <ulink
248 url="http://pobox.com/~hp/gnome-app-devel.html">
249 http://pobox.com/~hp/gnome-app-devel.html
250 </ulink></simpara>
251 </listitem>
252 <listitem><simpara>"GTK+ Programming in C" by
253 Syd Logan. ISBN: 0-1301-4264-6</simpara>
254 </listitem>
255 <listitem><simpara>"Linux GNOME/GTK+ Programming Bible" by
256 Arthur Griffith. ISBN: 0-7645-4640-6</simpara>
257 </listitem>
258 <listitem><simpara>"Beginning GTK+/GNOME Programming" by
259 Peter Wright. ISBN: 1-8610-0381-1</simpara>
260 </listitem>
261 <listitem><simpara>"Sams Teach Yourself GTK+ Programming
262 in 21 Days" by Donna Martin
263 . ISBN: 0-6723-1829-6</simpara>
264 </listitem>
265 </itemizedlist>
266
267 </sect1>
268
269 <!-- ----------------------------------------------------------------- -->
270
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>
274
275 <para>Information on mailing lists relating to GTK+ can be
276 found at: <ulink
277 url="http://www.gtk.org/mailinglists.html">
278 http://www.gtk.org/mailinglists.html
279 </ulink></para>
280
281 </sect1>
282
283 <!-- ----------------------------------------------------------------- -->
284
285 <sect1>
286 <title>How to get help with GTK+ <emphasis>[GTK 2.x]</emphasis></title>
287
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>
292
293 </sect1>
294
295 <!-- ----------------------------------------------------------------- -->
296
297 <sect1>
298 <title>How to report bugs in GTK+ <emphasis>[GTK 2.x]</emphasis></title>
299
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>
304
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>
309
310 <itemizedlist>
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>
318
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
323 using)</simpara>
324 </listitem>
325
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>
330 </listitem>
331
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>
337 </listitem>
338 </itemizedlist>
339
340 </sect1>
341
342 <!-- ----------------------------------------------------------------- -->
343
344 <sect1>
345 <title>Is there a Windows version of GTK+? <emphasis>[GTK 2.x]</emphasis></title>
346
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>
349
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>
353
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>
357
358 </sect1>
359
360 <!-- ----------------------------------------------------------------- -->
361
362 <sect1>
363 <title>What applications have been written with GTK+? <emphasis>[GTK 2.x]</emphasis></title>
364
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>
368
369 <para>Some of the best known projects utilising GTK+ are:</para>
370
371 <itemizedlist>
372 <listitem><simpara> GIMP (<ulink
373 url="http://www.gimp.org/">http://www.gimp.org/</ulink>), an
374 image manipulation program</simpara>
375 </listitem>
376 <listitem><simpara> AbiWord (<ulink
377 url="http://www.abiword.org/">http://www.abiword.com/</ulink>),
378 a professional word processor</simpara>
379 </listitem>
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>
384 </listitem>
385 <listitem><simpara> GnuCash (<ulink
386 url="http://www.gnucash.org/">
387 http://www.gnucash.org/</ulink>),
388 a personal finance manager</simpara>
389 </listitem>
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>
394 </listitem>
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>
398 </listitem>
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+
402 and GIMP.</simpara>
403 </listitem>
404 </itemizedlist>
405 </sect1>
406
407 </chapter>
408
409 <!-- ***************************************************************** -->
410 <chapter>
411 <title>How to find, configure, install, and troubleshoot GTK+</title>
412
413 <!-- ----------------------------------------------------------------- -->
414
415 <sect1 id="faq-Compile">
416 <title>What do I need to compile GTK+? <emphasis>[GTK 2.x]</emphasis></title>
417
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>
421
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>
425
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>
429
430 <itemizedlist spacing=compact>
431 <listitem><simpara> pkg-config
432 (<ulink url="http://pkg-config.freedesktop.org/wiki">
433 pkg-config Site</ulink>)</simpara>
434 </listitem>
435
436 <listitem><simpara> GNU make
437 (<ulink url="http://www.gnu.org/software/make/">
438 GNU make Site</ulink>)</simpara>
439 </listitem>
440
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>
444 </listitem>
445
446 <listitem><simpara> FreeType
447 (<ulink url="http://www.freetype.org/">
448 FreeType Site</ulink>)</simpara>
449 </listitem>
450
451 <listitem><simpara> fontconfig
452 (<ulink url="http://www.fontconfig.org/">
453 fontconfig Site</ulink>)</simpara>
454 </listitem>
455
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>
459 </listitem>
460
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>
464 </listitem>
465
466 <listitem><simpara> GLib
467 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
468 GTK+ Site</ulink>)</simpara>
469 </listitem>
470
471 <listitem><simpara> Pango
472 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
473 GTK+ Site</ulink>)</simpara>
474 </listitem>
475
476 <listitem><simpara> ATK
477 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
478 GTK+ Site</ulink>)</simpara>
479 </listitem>
480
481 <listitem><simpara> GTK+
482 (<ulink url="ftp://ftp.gtk.org/pub/gtk/v2.2/">
483 GTK+ Site</ulink>)</simpara>
484 </listitem>
485 </itemizedlist>
486
487 </sect1>
488
489 <!-- ----------------------------------------------------------------- -->
490
491 <sect1>
492 <title>Where can I get GTK+? <emphasis>[GTK 2.x]</emphasis></title>
493
494 <para>The canonical site is <ulink
495 url="ftp://ftp.gtk.org/pub/gtk">ftp://ftp.gtk.org/pub/gtk</ulink>.</para>
496
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
499 listed in <ulink
500 url="ftp://ftp.gtk.org/etc/mirrors">ftp://ftp.gtk.org/etc/mirrors
501 </ulink></para>
502
503 <para>Here's a few mirror sites to get you started:</para>
504
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> 
509 </listitem>
510
511 <listitem><simpara> Australia -
512 <ulink
513 url="ftp://ftp.planetmirror.com/pub/gimp/gtk">
514 ftp://ftp.planetmirror.com/pub/gimp/gtk</ulink></simpara> 
515 </listitem>
516
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> 
520 </listitem>
521
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> 
525 </listitem>
526
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> 
530 </listitem>
531
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>
535 </listitem>
536 </itemizedlist>
537 </sect1>
538
539 <!-- ----------------------------------------------------------------- -->
540
541 <sect1>
542 <title>How do I configure/compile GTK+? <emphasis>[GTK 2.x]</emphasis></title>
543
544 <para>Generally, the minimum you need to do is issue the commands:</para>
545
546 <para><literallayout><literal>./configure</literal>
547 <literal>make</literal>
548 <literal>make install</literal></literallayout></para>
549
550 <para>in the GTK+ source directory.</para>
551
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>
554
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>
559
560 <para>
561 <literallayout><literal>./configure --prefix=/usr</literal></literallayout>
562 </para>
563 </sect1>
564
565 <!-- ----------------------------------------------------------------- -->
566
567 <sect1>
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>
570
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>
576
577 </sect1>
578
579 <!-- ----------------------------------------------------------------- -->
580
581 <sect1>
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>
584
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>
588
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>
593
594 <para><literallayout><literal>/usr/X11R6/lib</literal>
595 <literal>/usr/local/lib</literal></literallayout></para>
596
597 <para>Then you need to run /sbin/ldconfig as root. You can
598 find what libraries GTK requires using</para>
599
600 <para><literallayout><literal>pkg-config gtk+-2.0 --libs</literal>
601 </literallayout></para>
602
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>
608
609 <para><literallayout>
610 <literal>export LD_LIBRARY_PATH=/usr/local/lib</literal>
611 </literallayout></para>
612
613 <para>and in a csh, you can do:</para>
614
615 <para><literallayout>
616 <literal>setenv LD_LIBRARY_PATH /usr/local/lib</literal>
617 </literallayout></para>
618
619 </sect1>
620
621 <!-- ----------------------------------------------------------------- -->
622
623 <sect1>
624 <title>When installing a GTK+ application, configure reports
625 that it can't find GTK. <emphasis>[GTK 2.x]</emphasis></title>
626
627 <para>There are several common reasons for this:</para>
628
629 <itemizedlist>
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>
634 </listitem>
635
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>
639
640 <para><literallayout>
641 <literal>pkg-config gtk+-2.0 --modversion</literal>
642 </literallayout></para>
643
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>
647 </listitem>
648
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>
653 </itemizedlist>
654
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>
661
662 </sect1>
663
664 </chapter>
665
666 <!-- ***************************************************************** -->
667 <chapter>
668 <title>Development of GTK+</title>
669
670 <!-- ----------------------------------------------------------------- -->
671
672 <sect1>
673 <title>Whats this CVS thing that everyone keeps talking about,
674 and how do I access it? <emphasis>[GTK 2.x]</emphasis></title>
675
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>
682
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>
688
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/
692 </ulink></para>
693
694 <para>Anyone can download the latest CVS version of GTK+ by
695 using anonymous access using the following steps:</para>
696
697 <itemizedlist>
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>
703 </listitem>
704
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>
712 </listitem>
713
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>
725 </listitem>
726 </itemizedlist>
727
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>
734
735 <para><literallayout>
736 <literal>cvs -z3 get -r gtk-2-2 gtk+</literal>
737 </literallayout></para>
738 </sect1>
739
740 <!-- ----------------------------------------------------------------- -->
741
742 <sect1 id="faq-Patches">
743 <title>How can I contribute to GTK+? <emphasis>[GTK 2.x]</emphasis></title>
744
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 &lt;oldfile&gt; &lt;newfile&gt;</literal>.</para>
752
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
755 general patches
756 (<ulink url="http://bugzilla.gnome.org">http://bugzilla.gnome.org</ulink>).
757 </para>
758
759 <para>This method ensures that the patch will not be lost.</para>
760
761 </sect1>
762
763 <!-- ----------------------------------------------------------------- -->
764
765 <sect1>
766 <title>How do I know if my patch got applied, and if not, why
767 not? <emphasis>[GTK 2.x]</emphasis></title>
768
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>
772
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>
776 </sect1>
777
778 <!-- ----------------------------------------------------------------- -->
779
780 <sect1>
781 <title>What is the policy on incorporating new widgets into
782 the library? <emphasis>[GTK 2.x]</emphasis></title>
783
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>
788
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. 
793
794 <para>Before you spend months of your valuable time implementing your
795 revolutionary widget, it is highly recommended that you get some
796 feedback on your idea via the appropriate 
797 <link linkend="faq-MailLists">mailing list</link>.</para>
798 </sect1>
799
800 <!-- ----------------------------------------------------------------- -->
801
802 <sect1>
803 <title>Is anyone working on bindings for languages other than
804 C? <emphasis>[GTK 2.x]</emphasis></title>
805
806 <para>There is a list of <ulink url="http://www.gtk.org/bindings.html">
807 language bindings</ulink> on the GTK+ website.</para>
808
809 <para>The 'official' language bindings are C++, Ada and Python.
810 However, bindings for many other languages are available.</para>
811 </sect1>
812
813 </chapter>
814
815 <!-- ***************************************************************** -->
816 <chapter>
817 <title>Development with GTK+: the begining</title>
818
819 <!-- ----------------------------------------------------------------- -->
820
821 <sect1>
822 <title>How do I get started? <emphasis>[GTK 2.x]</emphasis></title>
823
824 <para>So, after you have installed GTK+ there are a couple of
825 things that can ease you into developing applications with
826 it. There is the GTK+ Tutorial <ulink
827 url="http://library.gnome.org/devel/gtk-tutorial/stable/">
828 http://library.gnome.org/devel/gtk-tutorial/stable/</ulink>, which is undergoing
829 development. This will introduce you to writing applications
830 using C.</para>
831
832 <para>The GTK+ Tutorial doesn't contain information on all of
833 the widgets that are in GTK+. For example code on how to use
834 the basics of all the GTK+ widgets you should look in the
835 directory 'tests' (and associated source files) within the GTK+
836 distribution. Looking at these examples will give you a good
837 grounding on what the widgets can do.</para>
838
839 </sect1>
840
841 <!-- ----------------------------------------------------------------- -->
842
843 <sect1>
844 <title>How do I use the Glade GUI builder with GTK+? <emphasis>[GTK 2.x]</emphasis></title>
845
846 <para>There are two ways to use Glade. The first way is to use
847 Glade's facilities for generating code; the second
848 way is to use the libglade library which directly loads
849 the XML user interface description files that Glade
850 generates into a running program.</para>
851
852 <para>Experienced GTK+ programmers generally strongly recommend
853 using libglade; you don't have to worry about the interaction
854 between Glade generating the source and you editing it,
855 and its been shown to be a method that works better
856 for large projects, so there is a lot of example code
857 out there you can look at.</para>
858
859 <para>An introduction to using libglade can be found in the 
860 libglade API docs
861 (<ulink url="http://developer.gnome.org/doc/API/2.0/libglade/libglade-notes.html#libglade-basics">
862 http://developer.gnome.org/doc/API/2.0/libglade/libglade-notes.html#libglade-basics</ulink>)
863 .</para>
864
865 </sect1>
866
867 <!-- ----------------------------------------------------------------- -->
868
869 <sect1>
870 <title>How do I write security sensitive/SUID/SGID programs with GTK+?
871 Is GTK+ secure? What's this GTK_MODULES security hole I heard about?
872 <emphasis>[GTK 2.x]</emphasis></title>
873
874 <para>The short answer to this question is: you can't, so don't write SUID/SGID
875 programs with GTK+</para>
876
877 <para>GTK+ will refuse to run with elevated privileges, as it is not designed
878 to be used in this manner. The only correct way to write a setuid program with
879 a graphical user interface is to have a setuid backend that communicates with
880 the non-setuid graphical user interface via a mechanism such as a pipe and that
881 considers the input it receives to be untrusted.</para>
882
883 <para>For a more thorough explanation of the GTK+ Developers position on
884 this issue see <ulink
885 url="http://www.gtk.org/setuid.html">http://www.gtk.org/setuid.html</ulink>.</para>
886
887 </sect1>
888
889 <!-- ----------------------------------------------------------------- -->
890
891 <sect1>
892 <title>I tried to compile a small <command>Hello World</command> of mine,
893 but it failed. Any clue? <emphasis>[GTK 2.x]</emphasis></title>
894
895 <para>Since you are good at coding, we will not deal with
896 compile time errors here :)</para>
897
898 <para>The classic command line to compile a GTK+ based program is</para>
899 <para><literallayout>
900 <literal>gcc -o myprog [c files] `pkg-config gtk+-2.0 --cflags --libs`</literal>
901 </literallayout></para>
902
903 <para>You should notice the backquote character which is used
904 in this command line. A common mistake when you start a GTK+
905 based development is to use quotes instead of backquotes. If
906 you do so, the compiler will complain about an unknown file
907 called <filename>pkg-config gtk+-2.0 --cflags --libs</filename>. The
908 text in backquotes is an instruction to your shell to
909 substitute the output of executing this command into the
910 commandline.</para>
911
912 <para>The command line above ensures that:</para>
913
914 <itemizedlist>
915 <listitem><simpara>the correct C compiler flags will be used
916 to compile the program (including the complete C header
917 directory list)</simpara>
918 </listitem>
919
920 <listitem><simpara>your program will be linked with the
921 needed libraries.</simpara>
922 </listitem>
923 </itemizedlist>
924
925 </sect1>
926
927 <!-- ----------------------------------------------------------------- -->
928
929 <sect1>
930 <title>What about using the <command>make</command>
931 utility? <emphasis>[GTK 2.x]</emphasis></title>
932
933 <para>This is a sample makefile which compiles a GTK+ based
934 program:</para>
935
936 <programlisting role="C">
937 # basic GTK+ app makefile
938 SOURCES = myprg.c foo.c bar.c
939 OBJS    = ${SOURCES:.c=.o}
940 CFLAGS  = `pkg-config gtk+-2.0 --cflags`
941 LDADD   = `pkg-config gtk+-2.0 --libs`
942 CC      = gcc
943 PACKAGE = myprg
944
945 all : ${OBJS}
946   ${CC} -o ${PACKAGE} ${OBJS} ${LDADD}
947
948 .c.o:
949   ${CC} ${CFLAGS} -c $<
950
951 # end of file
952 </programlisting>
953
954 <para>For more information about the <command>make</command> utility, you
955 should read either the related man page or the relevant info file.</para>
956
957 </sect1>
958
959 <!-- ----------------------------------------------------------------- -->
960
961 <sect1>
962 <title>I use the backquote stuff in my makefiles, but my make
963 process failed. <emphasis>[GTK 2.x]</emphasis></title>
964
965 <para>The backquote construction seems to not be accepted by
966 some old <command>make</command> utilities. If you use one of these, the
967 make process will probably fail. In order to have the
968 backquote syntax working again, you should use the GNU make
969 utility (get it on the GNU ftp server at <ulink
970 url="ftp://ftp.gnu.org/gnu/make/">ftp://ftp.gnu.org/gnu/make/</ulink>).</para>
971
972 </sect1>
973
974 <!-- ----------------------------------------------------------------- -->
975
976 <sect1>
977 <title>I want to add some configure stuff, how could I do
978 this? <emphasis>[GTK 2.x]</emphasis></title>
979
980 <para>To use autoconf/automake, you must first install the
981 relevant packages. These are:</para>
982
983 <itemizedlist spacing=Compact>
984 <listitem><simpara>the m4 preprocessor v1.4 or better</simpara>
985 </listitem>
986
987 <listitem><simpara>autoconf v2.54 or better</simpara>
988 </listitem>
989
990 <listitem><simpara>automake v1.7 or better suggested</simpara>
991 </listitem>
992 </itemizedlist>
993
994 <para>You'll find these packages on the main GNU ftp server
995 (<ulink url="ftp://ftp.gnu.org/">ftp://ftp.gnu.org/</ulink>)
996 or on any GNU mirror.</para>
997
998 <para>In order to use the powerful autoconf/automake scheme,
999 you must create a configure.ac which may look like:</para>
1000
1001 <programlisting role="C">
1002 dnl Process this file with autoconf to produce a configure script.
1003 dnl configure.ac for a GTK+ based program
1004
1005 AC_INIT(myprg.c)
1006 AM_INIT_AUTOMAKE(mypkgname, 0.0.1)
1007 AM_CONFIG_HEADER(config.h)
1008
1009 dnl Checks for programs.
1010 AC_PROG_CC dnl check for the c compiler
1011 dnl you should add CFLAGS="" here, 'cos it is set to -g by PROG_CC
1012
1013 dnl Checks for libraries.
1014 AM_PATH_GTK_2_0(2.2.0,,AC_MSG_ERROR(mypkgname 0.1 needs GTK+ 2.2.0))
1015
1016 AC_OUTPUT(
1017         Makefile
1018 )
1019 </programlisting>
1020
1021 <para>You must add a Makefile.am file:</para>
1022
1023 <programlisting role="C">
1024 bin_PROGRAMS    = myprg
1025 myprg_SOURCES   = myprg.c foo.c bar.c
1026 INCLUDES        = @GTK_CFLAGS@
1027 LDADD           = @GTK_LIBS@
1028 CLEANFILES      = *~
1029 DISTCLEANFILES  = .deps/*.P
1030 </programlisting>
1031
1032 <para>If your project contains more than one subdirectory,
1033 you'll have to create one Makefile.am in each directory plus a
1034 master Makefile.am which will look like:</para>
1035
1036 <programlisting role="C">
1037 SUBDIRS         = mydir1 mydir2 mydir3
1038 </programlisting>
1039
1040 <para>then, to use these, simply type the following
1041 commands:</para>
1042
1043 <programlisting role="C">
1044 aclocal
1045 autoheader
1046 autoconf
1047 automake --add-missing --include-deps --foreign 
1048 </programlisting>
1049
1050 <para>For further information, you should look at the autoconf
1051 and the automake documentation (the shipped info files are
1052 really easy to understand, and there are plenty of web
1053 resources that deal with autoconf and automake).</para>
1054
1055 </sect1>
1056
1057 <!-- ----------------------------------------------------------------- -->
1058
1059 <sect1>
1060 <title>I try to debug my GTK+ application with gdb, but it
1061 hangs my X server when I hit some breakpoint. Any
1062 Idea? <emphasis>[GTK 2.x]</emphasis></title>
1063
1064 <para>From Federico Mena Quintero:</para>
1065
1066 <para><quote>X is not locked up.  It is likely that you are hitting a
1067 breakpoint inside a callback that is called from a place in Gtk that has
1068 a mouse grab.</quote></para>
1069
1070 <para><quote>Run your program with the <literal>--sync</literal>
1071 option; it will make it easier to debug. Also, you may want to
1072 use the console for running the debugger, and just let the
1073 program run in another console with the X server.</quote></para>
1074
1075 <para>Eric Mouw had another solution:</para>
1076
1077 <para><quote>An old terminal connected to an otherwise unused serial
1078 port is also great for debugging X programs. Old vt100/vt220
1079 terminals are dirt cheap but a bit hard to get (here in The
1080 Netherlands, YMMV).</quote></para>
1081
1082 <para>
1083 Another option is to run your application on Xnest. Xnest is an X server
1084 which displays its root window in a regular window of another X server.  
1085 A pointer grab on the Xnest display will not affect the GUI of your debugger
1086 running on your regular X server.
1087 <programlisting>
1088 Xnest :1
1089 twm -display :1
1090 myapp --display=:1
1091 </programlisting>
1092 </para>
1093 </sect1>
1094 </chapter>
1095
1096 <!-- ***************************************************************** -->
1097 <chapter>
1098 <title>Development with GTK+: general questions</title>
1099
1100 <!-- ----------------------------------------------------------------- -->
1101
1102 <sect1>
1103 <title>What widgets are in GTK?</title>
1104
1105 <para>The GTK+ Tutorial lists the following widgets:</para>
1106
1107 <programlisting role="C">
1108   GtkObject
1109    +GtkData
1110    | +GtkAdjustment
1111    | `GtkTooltips
1112    `GtkWidget
1113      +GtkContainer
1114      | +GtkBin
1115      | | +GtkAlignment
1116      | | +GtkEventBox
1117      | | +GtkFrame
1118      | | | `GtkAspectFrame
1119      | | +GtkHandleBox
1120      | | +GtkItem
1121      | | | +GtkListItem
1122      | | | +GtkMenuItem
1123      | | | | `GtkCheckMenuItem
1124      | | | |   `GtkRadioMenuItem
1125      | | | `GtkTreeItem
1126      | | +GtkViewport
1127      | | `GtkWindow
1128      | |   +GtkColorSelectionDialog
1129      | |   +GtkDialog
1130      | |   | `GtkInputDialog
1131      | |   `GtkFileSelection
1132      | +GtkBox
1133      | | +GtkButtonBox
1134      | | | +GtkHButtonBox
1135      | | | `GtkVButtonBox
1136      | | +GtkHBox
1137      | | | +GtkCombo
1138      | | | `GtkStatusbar
1139      | | `GtkVBox
1140      | |   `GtkColorSelection
1141      | +GtkButton
1142      | | +GtkOptionMenu
1143      | | `GtkToggleButton
1144      | |   `GtkCheckButton
1145      | |     `GtkRadioButton
1146      | +GtkCList
1147      |   `GtkCTree
1148      | +GtkFixed
1149      | +GtkList
1150      | +GtkMenuShell
1151      | | +GtkMenuBar
1152      | | `GtkMenu
1153      | +GtkNotebook
1154      | +GtkPaned
1155      | | +GtkHPaned
1156      | | `GtkVPaned
1157      | +GtkScrolledWindow
1158      | +GtkTable
1159      | +GtkToolbar
1160      | `GtkTree
1161      +GtkDrawingArea
1162      +GtkEditable
1163      | +GtkEntry
1164      | | `GtkSpinButton
1165      | `GtkText
1166      +GtkMisc
1167      | +GtkArrow
1168      | +GtkImage
1169      | +GtkLabel
1170      | | `GtkTipsQuery
1171      | `GtkPixmap
1172      +GtkPreview
1173      +GtkProgressBar
1174      +GtkRange
1175      | +GtkScale
1176      | | +GtkHScale
1177      | | `GtkVScale
1178      | `GtkScrollbar
1179      |   +GtkHScrollbar
1180      |   `GtkVScrollbar
1181      +GtkRuler
1182      | +GtkHRuler
1183      | `GtkVRuler
1184      `GtkSeparator
1185        +GtkHSeparator
1186        `GtkVSeparator
1187 </programlisting>
1188 </sect1>
1189
1190 <!-- ----------------------------------------------------------------- -->
1191
1192 <sect1>
1193 <title>Is GTK+ thread safe? How do I write multi-threaded GTK+
1194 applications? <emphasis>[GTK 2.x]</emphasis></title>
1195
1196 <para>The GLib library can be used in a thread-safe mode by
1197 calling g_thread_init() before making any other GLib
1198 calls. In this mode GLib automatically locks all internal
1199 data structures as needed.  This does not mean that two
1200 threads can simultaneously access, for example, a single hash
1201 table, but they can access two different hash tables
1202 simultaneously. If two different threads need to access the
1203 same hash table, the application is responsible for locking
1204 itself.</para>
1205
1206 <para>In order to make GDK thread aware, you also need to
1207 call gdk_threads_init() in conjunction with the above call.
1208 There is a single global
1209 lock that you must acquire with gdk_threads_enter() before
1210 making any GDK calls, and release with gdk_threads_leave()
1211 afterwards throughout your code.</para>
1212
1213 <para>A minimal main program for a threaded GTK+ application
1214 looks like:</para>
1215
1216 <programlisting role="C">
1217 int
1218 main (int argc, char *argv[])
1219 {
1220   GtkWidget *window;
1221
1222   /* init threads */    
1223   g_thread_init(NULL);
1224   gdk_threads_init();
1225   
1226   /* init gtk */
1227   gtk_init(&amp;argc, &amp;argv);
1228
1229   window = create_window();
1230   gtk_widget_show(window);
1231
1232   gdk_threads_enter();
1233   gtk_main();
1234   gdk_threads_leave();
1235
1236   return 0;
1237 }
1238 </programlisting>
1239
1240 <para>Callbacks require a bit of attention. Callbacks from
1241 GTK+ (signals) are made within the GTK+ lock. However
1242 callbacks from GLib (timeouts, IO callbacks, and idle
1243 functions) are made outside of the GTK+ lock. So, within a
1244 signal handler you do not need to call gdk_threads_enter(),
1245 but within the other types of callbacks, you do.</para>
1246
1247 <para>Erik Mouw contributed the following code example to
1248 illustrate how to use threads within GTK+ programs.</para>
1249
1250 <programlisting role="C">
1251 /*-------------------------------------------------------------------------
1252  * Filename:      gtk-thread.c
1253  * Version:       1.99.1
1254  * Copyright:     Copyright (C) 1999, Erik Mouw
1255  * Author:        Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl&gt;
1256  * Description:   GTK threads example.
1257  * Created at:    Sun Oct 17 21:27:09 1999
1258  * Modified by:   Owen Taylor &lt;otaylor@gtk.org&gt;
1259  * Modified at:   Wed May 28 10:43:00 2003
1260  *-----------------------------------------------------------------------*/
1261 /*
1262  * Compile with:
1263  *
1264  * cc -o gtk-thread gtk-thread.c `pkg-config --cflags --libs gtk+-2.0 gthread-2.0`
1265  *
1266  * Thanks to Sebastian Wilhelmi for pointing out some bugs in earlier versions.
1267  *
1268  */
1269
1270 #include &lt;unistd.h&gt;
1271 #include &lt;gtk/gtk.h&gt;
1272
1273 #define YES_IT_IS    (1)
1274 #define NO_IT_IS_NOT (0)
1275
1276 typedef struct
1277 {
1278   GtkWidget *label;
1279   int what;
1280 } yes_or_no_args;
1281
1282 G_LOCK_DEFINE_STATIC (yes_or_no);
1283 static volatile int yes_or_no = YES_IT_IS;
1284
1285 void destroy(GtkWidget *widget, gpointer data)
1286 {
1287   gtk_main_quit();
1288 }
1289
1290 void *argument_thread(void *args)
1291 {
1292   yes_or_no_args *data = (yes_or_no_args *)args;
1293   gboolean say_something;
1294
1295   for(;;)
1296     {
1297       /* sleep a while */
1298       sleep(g_random_int_range (1, 4));
1299
1300       /* lock the yes_or_no_variable */
1301       G_LOCK(yes_or_no);
1302
1303       /* do we have to say something? */
1304       say_something = (yes_or_no != data->what);
1305
1306       if(say_something)
1307         {
1308           /* set the variable */
1309           yes_or_no = data->what;
1310         }
1311
1312       /* Unlock the yes_or_no variable */
1313       G_UNLOCK(yes_or_no);
1314
1315       if(say_something)
1316         {
1317           /* get GTK thread lock */
1318           gdk_threads_enter();
1319
1320           /* set label text */
1321           if(data->what == YES_IT_IS)
1322             gtk_label_set_text(GTK_LABEL(data->label), "O yes, it is!");
1323           else
1324             gtk_label_set_text(GTK_LABEL(data->label), "O no, it isn't!");
1325
1326           /* Make sure all X commands are sent to the X server; not strictly
1327            * necessary here, but always a good idea when you do anything
1328            * from a thread other than the one where the main loop is running.
1329            */
1330           gdk_flush ();
1331
1332           /* release GTK thread lock */
1333           gdk_threads_leave();
1334         }
1335     }
1336
1337   return NULL;
1338 }
1339
1340 int main(int argc, char *argv[])
1341 {
1342   GtkWidget *window;
1343   GtkWidget *label;
1344   GError *error = NULL;
1345   yes_or_no_args yes_args, no_args;
1346
1347   /* init threads */
1348   g_thread_init(NULL);
1349   gdk_threads_init();
1350
1351   /* init gtk */
1352   gtk_init(&amp;argc, &amp;argv);
1353
1354   /* create a window */
1355   window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1356
1357   g_signal_connect(window, "destroy",
1358                    G_CALLBACK(destroy), NULL);
1359
1360   gtk_container_set_border_width(GTK_CONTAINER (window), 10);
1361
1362   /* create a label */
1363   label = gtk_label_new("And now for something completely different ...");
1364   gtk_container_add(GTK_CONTAINER(window), label);
1365
1366   /* show everything */
1367   gtk_widget_show(label);
1368   gtk_widget_show (window);
1369
1370   /* create the threads */
1371   yes_args.label = label;
1372   yes_args.what = YES_IT_IS;
1373   if (!g_thread_create(argument_thread, &amp;yes_args, FALSE, &amp;error))
1374     {
1375       g_printerr ("Failed to create YES thread: %s\n", error->message);
1376       return 1;
1377     }
1378
1379   no_args.label = label;
1380   no_args.what = NO_IT_IS_NOT;
1381   if (!g_thread_create(argument_thread, &amp;no_args, FALSE, &amp;error))
1382     {
1383       g_printerr ("Failed to create NO thread: %s\n", error->message);
1384       return 1;
1385     }
1386
1387   /* enter the GTK main loop */
1388   gdk_threads_enter();
1389   gtk_main();
1390   gdk_threads_leave();
1391
1392   return 0;
1393 }
1394 </programlisting>
1395 </sect1>
1396
1397 <!-- ----------------------------------------------------------------- -->
1398
1399 <sect1>
1400 <title>I'm doing some stuff with GTK+ in a separate thread, and
1401 properly locking with gdk_threads_enter/gdk_threads_leave()
1402 but the display doesn't update properly. <emphasis>[GTK 2.x]</emphasis>
1403 </title>
1404
1405 <para>For efficiency, the X window system batches up commands
1406 and sends them to the X server in batches instead of sending
1407 out immediately.</para>
1408
1409 <para>In a non-multithreaded program, you don't have to worry about
1410 this, since the first thing that happens when control returns
1411 to the main loop is that any outstanding X requests are 
1412 sent to the X server.</para>
1413
1414 <para>However, if you are making GTK+ calls from a thread other
1415 than the main loop, then GTK+ doesn't know when to send batched
1416 commands out. For that reason, after making GTK+ calls 
1417 in a separate thread, it is usually a good idea to call
1418 gdk_flush() before gdk_thread_leave().</para>
1419
1420 <para>Actually, gdk_flush() is more expensive than is necessary here,
1421 since it waits for the X server to finish outstanding commands
1422 as well; if performance is an issue, you may want to call
1423 XFlush() directly:</para>
1424
1425 <programlisting role="C">
1426
1427 #include &lt;gdk/gdkx.h&gt;
1428
1429 void my_flush_commands (void)
1430 {
1431   GdkDisplay *display = gdk_display_get_default ();
1432   XFlush (GDK_DISPLAY_XDISPLAY (display);
1433 }
1434 </programlisting>
1435
1436 </sect1>
1437
1438 <!-- ----------------------------------------------------------------- -->
1439
1440 <sect1>
1441 <title>What's an easy way to run a function in the thread with
1442 the main loop? <emphasis>[GTK 2.x]</emphasis></title>
1443
1444 <para>Sometimes the simplest way to set up a threaded program
1445 is to make all the GTK+ calls in a single thread. In such
1446 a program, you should still call g_threads_init(), but
1447 don't need to call gdk_threads_init(), gkd_threads_enter(),
1448 and gdk_threads_leave().</para>
1449
1450 <para>If you set your program up this way, how then do you get
1451 the thread making GTK+ calls and running the main loop
1452 to do something in response to another thread?</para>
1453
1454 <para>An easy way to do it is to take advantage of the fact that
1455 the GLib main loop functions are all thread safe, and can
1456 be called from any thread by adding an idle function
1457 with g_idle_add(). The function provided will be called
1458 at the next opportunity by the main thread. If you want
1459 your function to take priority over event handling and
1460 drawing, you can instead use g_idle_add_full() and pass
1461 in a priority of G_PRIORITY_HIGH.</para>
1462
1463 </sect1>
1464
1465 <!-- ----------------------------------------------------------------- -->
1466
1467 <sect1>
1468 <title>Why does this strange 'x io error' occur when I
1469 <literal>fork()</literal> in my GTK+ app? <emphasis>[GTK 2.x]</emphasis></title>
1470
1471 <para>This is not really a GTK+ problem, and the problem is
1472 not related to <literal>fork()</literal> either. If the 'x io
1473 error' occurs then you probably use the <literal>exit()</literal> function
1474 in order to exit from the child process.</para>
1475
1476 <para>When GDK opens an X display, it creates a socket file
1477 descriptor. When you use the <literal>exit()</literal>
1478 function, you implicitly close all the open file descriptors,
1479 and the underlying X library really doesn't like this.</para>
1480
1481 <para>The right function to use here is
1482 <literal>_exit()</literal>.</para> 
1483
1484 <para>Erik Mouw contributed the following code example to
1485 illustrate handling fork() and exit().</para>
1486
1487 <programlisting role="C">
1488 /*-------------------------------------------------------------------------
1489  * Filename:      gtk-fork.c
1490  * Version:       0.99.2
1491  * Copyright:     Copyright (C) 1999, Erik Mouw
1492  * Author:        Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl&gt;
1493  * Description:   GTK+ fork example
1494  * Created at:    Thu Sep 23 21:37:55 1999
1495  * Modified by:   Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl&gt;
1496  * Modified at:   Thu Sep 23 22:39:39 1999
1497  * Modified by:   Tony Gale &lt;gale@gtk.org&gt;
1498  * Modified at:   Wed Jan 14 12:38:00 2004
1499  *-----------------------------------------------------------------------*/
1500 /*
1501  * Compile with:
1502  *
1503  * cc -o gtk-fork gtk-fork.c `pkg-config gtk+-2.0 --cflags --libs`
1504  *
1505  */
1506
1507 #include &lt;stdio.h&gt;
1508 #include &lt;stdlib.h&gt;
1509 #include &lt;signal.h&gt;
1510 #include &lt;sys/types.h&gt;
1511 #include &lt;sys/wait.h&gt;
1512 #include &lt;unistd.h&gt;
1513 #include &lt;gtk/gtk.h&gt;
1514
1515 void sigchld_handler(int num)
1516 {
1517   sigset_t set, oldset;
1518   pid_t pid;
1519   int status, exitstatus;
1520
1521   /* block other incoming SIGCHLD signals */
1522   sigemptyset(&amp;set);
1523   sigaddset(&amp;set, SIGCHLD);
1524   sigprocmask(SIG_BLOCK, &amp;set, &amp;oldset);
1525
1526   /* wait for child */
1527   while((pid = waitpid((pid_t)-1, &amp;status, WNOHANG)) &gt; 0)
1528     {
1529       if(WIFEXITED(status))
1530         {
1531           exitstatus = WEXITSTATUS(status);
1532
1533           fprintf(stderr, 
1534                   "Parent: child exited, pid = %d, exit status = %d\n", 
1535                   (int)pid, exitstatus);
1536         }
1537       else if(WIFSIGNALED(status))
1538         {
1539           exitstatus = WTERMSIG(status);
1540
1541           fprintf(stderr,
1542                   "Parent: child terminated by signal %d, pid = %d\n",
1543                   exitstatus, (int)pid);
1544         }
1545       else if(WIFSTOPPED(status))
1546         {
1547           exitstatus = WSTOPSIG(status);
1548
1549           fprintf(stderr,
1550                   "Parent: child stopped by signal %d, pid = %d\n",
1551                   exitstatus, (int)pid);
1552         }
1553       else
1554         {
1555           fprintf(stderr,
1556                   "Parent: child exited magically, pid = %d\n",
1557                   (int)pid);
1558         }
1559     }
1560
1561   /* re-install the signal handler (some systems need this) */
1562   signal(SIGCHLD, sigchld_handler);
1563   
1564   /* and unblock it */
1565   sigemptyset(&amp;set);
1566   sigaddset(&amp;set, SIGCHLD);
1567   sigprocmask(SIG_UNBLOCK, &amp;set, &amp;oldset);
1568 }
1569
1570 gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
1571 {
1572   return(FALSE);
1573 }
1574
1575 void destroy(GtkWidget *widget, gpointer data)
1576 {
1577   gtk_main_quit();
1578 }
1579
1580 void fork_me(GtkWidget *widget, gpointer data)
1581 {
1582   pid_t pid;
1583
1584   pid = fork();
1585
1586   if(pid == -1)
1587     {
1588       /* ouch, fork() failed */
1589       perror("fork");
1590       exit(-1);
1591     }
1592   else if(pid == 0)
1593     {
1594       /* child */
1595       fprintf(stderr, "Child: pid = %d\n", (int)getpid());
1596
1597       execlp("ls", "ls", "-CF", "/", NULL);
1598       
1599       /* if exec() returns, there is something wrong */
1600       perror("execlp");
1601
1602       /* exit child. note the use of _exit() instead of exit() */
1603       _exit(-1);
1604     }
1605   else
1606     {
1607       /* parent */
1608       fprintf(stderr, "Parent: forked a child with pid = %d\n", (int)pid);
1609     }
1610 }
1611
1612 int main(int argc, char *argv[])
1613 {
1614   GtkWidget *window;
1615   GtkWidget *button;
1616
1617   gtk_init(&amp;argc, &amp;argv);
1618
1619   /* the basic stuff: make a window and set callbacks for destroy and
1620    * delete events 
1621    */
1622   window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1623
1624   g_signal_connect(G_OBJECT (window), "delete_event",
1625                      G_CALLBACK(delete_event), NULL);
1626           
1627   g_signal_connect(G_OBJECT (window), "destroy",
1628                      G_CALLBACK(destroy), NULL);
1629
1630   gtk_container_set_border_width(GTK_CONTAINER (window), 10);
1631
1632   /* add a button to do something useful */
1633   button = gtk_button_new_with_label("Fork me!");
1634           
1635   g_signal_connect(G_OBJECT (button), "clicked",
1636                      G_CALLBACK(fork_me), NULL);
1637
1638   gtk_container_add(GTK_CONTAINER(window), button);
1639           
1640   /* show everything */
1641   gtk_widget_show (button);
1642   gtk_widget_show (window);
1643
1644
1645   /* install a signal handler for SIGCHLD signals */
1646   signal(SIGCHLD, sigchld_handler);
1647
1648   
1649   /* main loop */
1650   gtk_main ();
1651
1652   exit(0);         
1653 }
1654 </programlisting>
1655 </sect1>
1656
1657 <!-- ----------------------------------------------------------------- -->
1658
1659 <sect1>
1660 <title>Why don't the contents of a button move when the button
1661 is pressed? Here's a patch to make it work that way... <emphasis>[GTK 2.x]</emphasis></title>
1662
1663 <para>From: Peter Mattis</para>
1664
1665 <para><quote>The reason buttons don't move their child down and to
1666 the right when they are depressed is because I don't think
1667 that's what is happening visually. My view of buttons is
1668 that you are looking at them straight on. That is, the user
1669 interface lies in a plane and you're above it looking
1670 straight at it. When a button gets pressed it moves directly
1671 away from you. To be absolutely correct I guess the child
1672 should actually shrink a tiny amount. But I don't see why
1673 the child should shift down and to the left. Remember, the
1674 child is supposed to be attached to the buttons surface. Its
1675 not good for it to appear like the child is slipping on the
1676 surface of the button.</quote></para>
1677
1678 <para><quote>On a more practical note, I did implement this at one point
1679 and determined it didn't look good and removed it.</quote></para>
1680
1681 </sect1>
1682
1683 <!-- ----------------------------------------------------------------- -->
1684
1685 <sect1>
1686 <title>How do I identifiy a widgets top level window or other
1687 ancestor? <emphasis>[GTK 2.x]</emphasis></title>
1688
1689 <para>There are a couple of ways to find the top level parent
1690 of a widget. The easiest way is to call the
1691 <literal>gtk_widget_get_toplevel()</literal> function that
1692 returns a pointer to a GtkWidget that is the top level
1693 window.</para>
1694
1695 <para>A more complicated way to do this (but less limited, as
1696 it allows the user to get the closest ancestor of a known type) is to use
1697 <literal>gtk_widget_get_ancestor()</literal> as in:</para>
1698
1699 <programlisting role="C">
1700       GtkWidget       *widget;
1701       widget = gtk_widget_get_ancestor(w, GTK_TYPE_WINDOW);
1702 </programlisting>
1703
1704 <para>Since virtually all the GTK_TYPEs can be used as the
1705 second parameter of this function, you can get any parent
1706 widget of a particular widget. Suppose you have an hbox which
1707 contains a vbox, which in turn contains some other atomic
1708 widget (entry, label, etc. To find the master hbox using the
1709 <literal>entry</literal> widget simply use:</para>
1710
1711 <programlisting role="C">
1712       GtkWidget       *hbox;
1713       hbox = gtk_widget_get_ancestor(w, GTK_TYPE_HBOX);
1714 </programlisting>
1715
1716 <para>You can also follow the a widgets ancestry by using the function
1717 <literal>gtk_widget_get_parent()</literal> that returns a pointer
1718 to a widgets parent widget.</para>
1719
1720 </sect1>
1721
1722 <!-- ----------------------------------------------------------------- -->
1723
1724 <sect1>
1725 <title>How do I get the Window ID of a GtkWindow? <emphasis>[GTK 2.x]</emphasis></title>
1726
1727 <para>The actual Gdk/X window will be created when the widget
1728 gets realized. You can get the Window ID with:</para>
1729
1730 <programlisting role="C">
1731 #include &lt;gdk/gdkx.h&gt;
1732
1733 Window xwin = GDK_WINDOW_XWINDOW (GTK_WIDGET (my_window)->window);
1734 </programlisting>
1735 </sect1>
1736
1737 <!-- ----------------------------------------------------------------- -->
1738
1739 <sect1>
1740 <title>How do I catch a double click event? <emphasis>[GTK 2.x]</emphasis></title>
1741
1742 <para>Tim Janik wrote to gtk-list (slightly modified):</para>
1743
1744 <para>Define a signal handler:</para>
1745
1746 <programlisting role="C">
1747 gint
1748 signal_handler_event(GtkWidget *widget, GdkEventButton *event, gpointer func_data)
1749 {
1750   if (GTK_IS_BUTTON(widget) &&
1751        (event->type==GDK_2BUTTON_PRESS ||
1752         event->type==GDK_3BUTTON_PRESS) ) {
1753     printf("I feel %s clicked with button %d\n",
1754            event->type==GDK_2BUTTON_PRESS ? "double" : "triple",
1755            event->button);
1756   }
1757
1758   return FALSE;
1759 }</programlisting>
1760
1761 <para>And connect the handler to your object:</para>
1762
1763 <programlisting role="C">
1764 {
1765   /* button init stuff */     
1766
1767   g_signal_connect(G_OBJECT(button),
1768                      "button_press_event",
1769                      G_CALLBACK(signal_handler_event),
1770                      NULL);
1771
1772   /* and/or */
1773
1774   g_signal_connect(G_OBJECT(button),
1775                      "button_release_event",
1776                      G_CALLBACK(signal_handler_event),
1777                      NULL);
1778
1779   /* something else */
1780 }
1781 </programlisting>
1782
1783 <para>and, Owen Taylor wrote:</para>
1784
1785 <para><quote>Note that a single button press will be received
1786 beforehand, and if you are doing this for a button, you will
1787 therefore also get a "clicked" signal for the button. (This
1788 is going to be true for any toolkit, since computers aren't
1789 good at reading one's mind.)</quote></para>
1790
1791 </sect1>
1792
1793 <!-- ----------------------------------------------------------------- -->
1794
1795 <sect1>
1796 <title>By the way, what are the differences between signals
1797 and events?</title>
1798
1799 <para>First of all, Havoc Pennington gives a rather complete
1800 description of the differences between events and signals in
1801 his free book (two chapters can be found at <ulink
1802 url="http://www106.pair.com/rhp/sample_chapters.html">
1803 http://www106.pair.com/rhp/sample_chapters.html</ulink>).</para>
1804
1805 <para>Moreover, Havoc posted this to the <literal>gtk-list</literal>
1806 <quote>Events are a stream of messages received from the X
1807 server. They drive the Gtk main loop; which more or less
1808 amounts to "wait for events, process them" (not exactly, it
1809 is really more general than that and can wait on many
1810 different input streams at once). Events are a Gdk/Xlib
1811 concept.</quote></para>
1812
1813 <para><quote>Signals are a feature of GtkObject and its subclasses. They
1814 have nothing to do with any input stream; really a signal is just a way
1815 to keep a list of callbacks around and invoke them ("emit" the
1816 signal). There are lots of details and extra features of
1817 course. Signals are emitted by object instances, and are entirely
1818 unrelated to the Gtk main loop.  Conventionally, signals are emitted
1819 "when something changes" about the object emitting the
1820 signal.</quote></para>
1821
1822 <para><quote>Signals and events only come together because GtkWidget
1823 happens to emit signals when it gets events. This is purely a
1824 convenience, so you can connect callbacks to be invoked when a
1825 particular widget receives a particular event. There is nothing about
1826 this that makes signals and events inherently related concepts, any more
1827 than emitting a signal when you click a button makes button clicking and
1828 signals related concepts.</quote></para>
1829
1830 </sect1>
1831
1832 <!-- ----------------------------------------------------------------- -->
1833
1834 <sect1>
1835 <title>Data I pass to the <literal>delete_event</literal> (or other event)
1836 handler gets corrupted.</title>
1837
1838 <para>All event handlers take an additional argument which
1839 contains information about the event that triggered the
1840 handler. So, a <literal>delete_event</literal> handler must
1841 be declared as:</para>
1842
1843
1844 <programlisting role="C">
1845 gint delete_event_handler (GtkWidget   *widget,
1846                            GdkEventAny *event,
1847                            gpointer     data);
1848 </programlisting>
1849
1850 </sect1>
1851
1852 <!-- ----------------------------------------------------------------- -->
1853
1854 <sect1>
1855 <title>I have my signal connected to the the (whatever) event,
1856 but it seems I don't catch it. What's wrong?</title>
1857
1858 <para>There is some special initialisation to do in order to
1859 catch some particular events. In fact, you must set the
1860 correct event mask bit of your widget before getting some
1861 particular events.</para>
1862
1863 <para>For example,</para>
1864
1865 <programlisting role="C">
1866   gtk_widget_add_events(window, GDK_KEY_RELEASE_MASK);
1867 </programlisting>
1868
1869 <para>lets you catch the key release events. If you want to
1870 catch every events, simply us the GDK_ALL_EVENTS_MASK event
1871 mask.</para>
1872
1873 <para>All the event masks are defined in the
1874 <filename>gdktypes.h</filename> file.</para>
1875
1876 </sect1>
1877
1878 <!-- ----------------------------------------------------------------- -->
1879
1880 <sect1>
1881 <title>I need to add a new signal to a GTK+ widget. Any
1882 idea?</title>
1883
1884 <para>If the signal you want to add may be beneficial for
1885 other GTK+ users, you may want to submit a patch that
1886 presents your changes. Check the tutorial for more
1887 information about adding signals to a widget class.</para>
1888
1889 <para>If you don't think it is the case or if your patch is
1890 not applied you'll have to use the
1891 <literal>gtk_object_class_user_signal_new</literal>
1892 function. <literal>gtk_object_class_user_signal_new</literal> allows you
1893 to add a new signal to a predefined GTK+ widget without any
1894 modification of the GTK+ source code. The new signal can be
1895 emited with <literal>g_signal_emit</literal> and can be
1896 handled in the same way as other signals.</para>
1897
1898 <para>Tim Janik posted this code snippet:</para>
1899
1900 <programlisting role="C">
1901 static guint signal_user_action = 0;
1902
1903 signal_user_action =
1904   gtk_object_class_user_signal_new (gtk_type_class (GTK_TYPE_WIDGET),
1905                     "user_action",
1906                     GTK_RUN_LAST | GTK_RUN_ACTION,
1907                     gtk_marshal_NONE__POINTER,
1908                     GTK_TYPE_NONE, 1,
1909                     GTK_TYPE_POINTER);
1910
1911 void
1912 gtk_widget_user_action (GtkWidget *widget,
1913                         gpointer   act_data)
1914 {
1915   g_return_if_fail (GTK_IS_WIDGET (widget));
1916
1917   g_signal_emit (widget, signal_user_action, act_data);
1918 }
1919 </programlisting>
1920
1921 <para>If you want your new signal to have more than the
1922 classical gpointer parameter, you'll have to play with GTK+
1923 marshallers.</para>
1924
1925 </sect1>
1926
1927 <!-- ----------------------------------------------------------------- -->
1928
1929 <sect1>
1930 <title>Is it possible to get some text displayed which is
1931 truncated to fit inside its allocation?</title>
1932
1933 <para>GTK's behavior (no clipping) is a consequence of its
1934 attempts to conserve X resources. Label widgets (among
1935 others) don't get their own X window - they just draw their
1936 contents on their parent's window. While it might be possible
1937 to have clipping occur by setting the clip mask before
1938 drawing the text, this would probably cause a substantial
1939 performance penalty.</para>
1940
1941 <para>Its possible that, in the long term, the best solution
1942 to such problems might be just to change gtk to give labels X
1943 windows. A short term workaround is to put the label widget
1944 inside another widget that does get its own window - one
1945 possible candidate would be the viewport widget.</para>
1946
1947 <programlisting role="C">
1948 viewport = gtk_viewport (NULL, NULL);
1949 gtk_widget_set_usize (viewport, 50, 25);
1950 gtk_viewport_set_shadow_type (GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
1951 gtk_widget_show(viewport);
1952
1953 label = gtk_label ("a really long label that won't fit");
1954 gtk_container_add (GTK_CONTAINER(viewport), label);
1955 gtk_widget_show (label);
1956 </programlisting>
1957
1958 <para>If you were doing this for a bunch of widgets, you might
1959 want to copy gtkviewport.c and strip out the adjustment and
1960 shadow functionality (perhaps you could call it
1961 GtkClipper).</para>
1962 </sect1>
1963
1964 <!-- ----------------------------------------------------------------- -->
1965
1966 <sect1>
1967 <title>How do I make my window modal? / How do I make a single
1968 window active?</title>
1969
1970 <para>After you create your window, do
1971 <literal>gtk_grab_add(my_window)</literal>. And after closing the window
1972 do <literal>gtk_grab_remove(my_window)</literal>.</para>
1973
1974 </sect1>
1975
1976 <!-- ----------------------------------------------------------------- -->
1977
1978 <sect1>
1979 <title>Why doesn't my widget (e.g. progressbar)
1980 update? <emphasis>[GTK 2.x]</emphasis></title>
1981
1982 <para>You are probably doing all the changes within a function without
1983 returning control to <literal>gtk_main()</literal>. This may
1984 be the case if you do some lengthy calculation in your
1985 code. Most drawing updates are only placed on a queue, which
1986 is processed within <literal>gtk_main()</literal>. You can force the
1987 drawing queue to be processed using something like:</para>
1988
1989
1990 <programlisting role="C">
1991 while (g_main_context_iteration(NULL, FALSE));
1992 </programlisting>
1993
1994 <para>inside you're function that changes the widget.</para>
1995
1996 <para>What the above snippet does is run all pending events
1997 and high priority idle functions, then return immediately
1998 (the drawing is done in a high priority idle function).</para>
1999
2000 </sect1>
2001
2002 <!-- ----------------------------------------------------------------- -->
2003
2004 <sect1>
2005 <title>How do I attach data to some GTK+ object/widget?
2006 <emphasis>[GTK 2.x]</emphasis></title>
2007
2008 <para>First of all, the attached data is stored in the
2009 object_data field of a GtkObject. The type of this field is
2010 GData, which is defined in glib.h.  So you should read the
2011 gdataset.c file in your glib source directory very
2012 carefully.</para>
2013
2014 <para>There are two (easy) ways to attach some data to a gtk
2015 object.  Using <literal>g_object_set_data()</literal> and
2016 <literal>g_object_get_data()</literal> seems to be the most
2017 common way to do this, as it provides a powerful interface to
2018 connect objects and data.</para>
2019
2020 <programlisting role="C">
2021 void g_object_set_data(GObject *object, const gchar *key, gpointer data);
2022
2023 gpointer g_object_get_data(GObject *object, const gchar *key);
2024 </programlisting>
2025
2026 <para>Since a short example is better than any lengthy speech:</para>
2027
2028 <programlisting role="C">
2029 struct my_struct        p1,p2,*result;
2030 GtkWidget               *w;
2031
2032 g_object_set_data(G_OBJECT(w),"p1 data",(gpointer)&amp;p1);
2033 g_object_set_data(G_OBJECT(w),"p2 data",(gpointer)&amp;p2);
2034
2035 result = g_object_get_data(G_OBJECT(w),"p1 data");
2036 </programlisting>
2037
2038 <para>The <literal>gtk_object_set_user_data()</literal> and
2039 <literal>gtk_object_get_user_data()</literal> functions does
2040 exactly the same thing as the functions above, but does not
2041 let you specify the "key" parameter.Instead, it uses a
2042 standard "user_data" key. Note that the use of these functions
2043 is deprecated in 1.2. They only provide a compatibility mode
2044 with some old gtk packages.</para>
2045
2046 </sect1>
2047
2048 <!-- ----------------------------------------------------------------- -->
2049
2050 <sect1>
2051 <title>How do I remove the data I have attached to an
2052 object?</title>
2053
2054 <para>When attaching the data to the object, you can use the
2055 <literal>gtk_object_set_data_full()</literal> function. The three
2056 first arguments of the function are the same as in
2057 <literal>gtk_object_set_data()</literal>. The fourth one is a
2058 pointer to a callback function which is called when the data
2059 is destroyed. The data is destroyed when you:</para>
2060
2061 <itemizedlist>
2062 <listitem><simpara> destroy the object</simpara>
2063 </listitem>
2064
2065 <listitem><simpara> replace the data with a new one (with
2066 the same key)</simpara>
2067 </listitem>
2068
2069 <listitem><simpara> replace the data with NULL (with the
2070 same key)</simpara>
2071 </listitem>
2072
2073 </itemizedlist>
2074
2075 </sect1>
2076
2077 <!-- ----------------------------------------------------------------- -->
2078
2079 <sect1>
2080 <title>How do I reparent a widget?</title>
2081
2082 <para>The normal way to reparent (ie change the owner) of a
2083 widget should be to use the function:</para>
2084
2085 <programlisting role="C">
2086 void gtk_widget_reparent (GtkWidget *widget, 
2087                           GtkWidget *new_parent)
2088 </programlisting>
2089
2090 <para>But this is only a "should be" since this function does
2091 not correctly do its job on some specific widgets. The main
2092 goal of gtk_widget_reparent() is to avoid unrealizing widget
2093 if both widget and new_parent are realized (in this case,
2094 widget->window is successfully reparented). The problem here
2095 is that some widgets in the GTK+ hierarchy have multiple
2096 attached X subwindows and this is notably the case for the
2097 GtkSpinButton widget. For those, gtk_widget_reparent() will
2098 fail by leaving an unrealized child window where it should
2099 not.</para>
2100
2101 <para>To avoid this problem, simply use the following code
2102 snippet:</para>
2103
2104 <programlisting role="C">
2105      g_object_ref(widget);
2106      gtk_container_remove(GTK_CONTAINER(old_parent), widget);
2107      gtk_container_add(GTK_CONTAINER(new_parent), widget);
2108      g_object_unref(widget);
2109 </programlisting>
2110
2111 </sect1>
2112
2113 <!-- ----------------------------------------------------------------- -->
2114
2115 <sect1>
2116 <title>How could I get any widgets position?</title>
2117
2118 <para>As Tim Janik pointed out, there are different cases, and
2119 each case requires a different solution.</para>
2120
2121 <itemizedlist>
2122 <listitem><simpara> If you want the position of a widget
2123 relative to its parent, you should use
2124 <literal>widget->allocation.x</literal> and
2125 <literal>widget->allocation.y</literal>.</simpara>
2126 </listitem>
2127
2128 <listitem><simpara> If you want the position of a window
2129 relative to the X root window, you should use
2130 <literal>gdk_window_get_geometry()</literal>
2131 <literal>gdk_window_get_position()</literal> or
2132 <literal>gdk_window_get_origin()</literal>.</simpara>
2133 </listitem>
2134
2135 <listitem><simpara> If you want to get the position of the
2136 window (including the WM decorations), you should use
2137 <literal>gdk_window_get_root_origin()</literal>.</simpara>
2138 </listitem>
2139
2140 <listitem><simpara> Last but not least, if you want to get a Window
2141 Manager frame position, you should use
2142 <literal>gdk_window_get_deskrelative_origin()</literal>.</simpara>
2143 </listitem>
2144 </itemizedlist>
2145
2146 <para>Your choice of Window Manager will have an effect of the
2147 results of the above functions. You should keep this in mind
2148 when writing your application. This is dependant upon how the
2149 Window Managers manage the decorations that they add around
2150 windows.</para>
2151
2152 </sect1>
2153
2154 <!-- ----------------------------------------------------------------- -->
2155
2156 <sect1>
2157 <title>How do I set the size of a widget/window? How do I
2158 prevent the user resizing my window? <emphasis>[GTK 2.x]</emphasis></title>
2159
2160 <para>The <literal>gtk_widget_set_size_request()</literal> function
2161 is used to set the size of a widget to a specific size.
2162
2163 The function
2164 <literal>gtk_window_set_resizable()</literal> function sets whether
2165 the user can resize a window, which they can by default. The
2166 definition of these functions are:</para>
2167
2168 <programlisting role="C">
2169 void gtk_widget_set_size_request (GtkWidget *widget,
2170                                   gint       width,
2171                                   gint       height);
2172
2173 void gtk_window_set_resizable (GtkWindow *window,
2174                                gboolean   resizable);
2175
2176 </programlisting>
2177
2178 </sect1>
2179
2180 <!-- ----------------------------------------------------------------- -->
2181
2182 <sect1>
2183 <title>How do I add a popup menu to my GTK+ application?</title>
2184
2185 <para>The <literal>menu</literal> example in the examples/menu
2186 directory of the GTK+ distribution implements a popup menu
2187 with this technique:</para>
2188
2189 <programlisting role="C">
2190 static gint button_press (GtkWidget *widget, GdkEvent *event)
2191 {
2192
2193     if (event->type == GDK_BUTTON_PRESS) {
2194         GdkEventButton *bevent = (GdkEventButton *) event; 
2195         gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
2196                         bevent->button, bevent->time);
2197         /* Tell calling code that we have handled this event; the buck
2198          * stops here. */
2199         return TRUE;
2200     }
2201
2202     /* Tell calling code that we have not handled this event; pass it on. */
2203     return FALSE;
2204 }
2205 </programlisting>
2206
2207 </sect1>
2208
2209 <!-- ----------------------------------------------------------------- -->
2210
2211 <sect1>
2212 <title>How do I disable or enable a widget, such as a
2213 button?</title>
2214
2215 <para>To disable (or to enable) a widget, use the
2216 <literal>gtk_widget_set_sensitive()</literal> function. The
2217 first parameter is you widget pointer. The second parameter is
2218 a boolean value: when this value is TRUE, the widget is
2219 enabled.</para>
2220 </sect1>
2221
2222 <!-- ----------------------------------------------------------------- -->
2223
2224 <sect1>
2225 <title>Shouldn't the text argument in the gtk_clist_*
2226 functions be declared const?</title>
2227
2228 <para>For example:</para>
2229
2230 <programlisting role="C">
2231 gint gtk_clist_prepend (GtkCList *clist,
2232                         gchar    *text[]);
2233 </programlisting>
2234
2235 <para>Answer: No, while a type "gchar*" (pointer to char) can
2236 automatically be cast into "const gchar*" (pointer to const
2237 char), this does not apply for "gchar *[]" (array of an
2238 unspecified number of pointers to char) into "const gchar *[]"
2239 (array of an unspecified number of pointers to const char).</para>
2240
2241 <para>The type qualifier "const" may be subject to automatic
2242 casting, but in the array case, it is not the array itself
2243 that needs the (const) qualified cast, but its members, thus
2244 changing the whole type.</para>
2245 </sect1>
2246
2247 <!-- ----------------------------------------------------------------- -->
2248
2249 <sect1>
2250 <title>How do I render pixels (image data) to the
2251 screen?</title>
2252
2253 <para>There are several ways to approach this. The simplest
2254 way is to use GdkRGB, see gdk/gdkrgb.h. You create an RGB
2255 buffer, render to your RGB buffer, then use GdkRGB routines to
2256 copy your RGB buffer to a drawing area or custom widget. The
2257 book "GTK+/Gnome Application Development" gives some details;
2258 GdkRGB is also documented in the GTK+ reference
2259 documentation.</para>
2260
2261 <para>If you're writing a game or other graphics-intensive
2262 application, you might consider a more elaborate
2263 solution. OpenGL is the graphics standard that will let you
2264 access hardware accelaration in future versions of XFree86; so
2265 for maximum speed, you probably want to use OpenGL. A
2266 GtkGLArea widget is available for using OpenGL with GTK+ (but
2267 GtkGLArea does not come with GTK+ itself). There are also
2268 several open source game libraries, such as ClanLib and Loki's
2269 Simple DirectMedia Layer library (SDL).</para>
2270
2271 <para>You do NOT want to use
2272 <literal>gdk_draw_point()</literal>, that will be extremely
2273 slow.</para>
2274 </sect1>
2275
2276 <!-- ----------------------------------------------------------------- -->
2277
2278 <sect1>
2279 <title>How do I create a pixmap without having my window being
2280 realized/shown?</title>
2281
2282 <para>Functions such as
2283 <literal>gdk_pixmap_create_from_xpm()</literal> require a
2284 valid window as a parameter. During the initialisation phase
2285 of an application, a valid window may not be available without
2286 showing a window, which may be inappropriate. In order to
2287 avoid this, a function such as
2288 <literal>gdk_pixmap_colormap_create_from_xpm</literal> can be
2289 used, as in:</para>
2290
2291 <programlisting role="C">
2292   char *pixfile = "foo.xpm";
2293   GtkWidget *top, *box, *pixw;
2294   GdkPixmap *pixmap, *pixmap_mask;
2295
2296   top = gtk_window_new (GKT_WINDOW_TOPLEVEL);
2297   box = gtk_hbox_new (FALSE, 4);
2298   gtk_conainer_add (GTK_CONTAINER(top), box);
2299  
2300   pixmap = gdk_pixmap_colormap_create_from_xpm (
2301                NULL, gtk_widget_get_colormap(top),
2302                &amp;pixmap_mask, NULL, pixfile);
2303   pixw = gtk_pixmap_new (pixmap, pixmap_mask);
2304   g_object_unref (pixmap);
2305   g_object_unref (pixmap_mask);
2306 </programlisting>
2307
2308 </sect1>
2309
2310 <!-- ----------------------------------------------------------------- -->
2311
2312 <sect1>
2313 <title>How do I do drag-and-drop?</title>
2314
2315 <para>GTK+ has a high level set of functions for doing inter-process
2316 communication via the drag-and-drop system. GTK+ can perform
2317 drag-and-drop on top of the low level Xdnd and Motif drag-and-drop
2318 protocols.</para>
2319
2320 <para>The documentation on GTK+ drag-and-drop isn't complete, but there
2321 is some information in the <ulink
2322 url="http://www.gtk.org/tutorial/">Tutorial</ulink>. You should also
2323 look at the drag-and-drop example code that is part of the GTK+ source
2324 distribution, in the file <filename>gtk/testdnd.c</filename>.</para>
2325
2326 </sect1>
2327
2328 <!-- ----------------------------------------------------------------- -->
2329
2330 <sect1>
2331 <title>Why does GTK+/GLib leak memory?</title>
2332
2333 <para>It doesn't. Both GLib and the C library (malloc implementation)
2334 will cache allocated memory on occasion, even if you free it with
2335 free().</para>
2336
2337 <para>So you can't generally use tools such as top to see if you are
2338 using free() properly (aside from the very roughest of estimations, i.e.
2339 if you are really, really screwing up top will show that, but you can't
2340 distinguish small mistakes from the GLib/malloc caches).</para>
2341
2342 <para>In order to find memory leaks, use proper memory profiling
2343 tools.</para>
2344
2345 </sect1>
2346
2347 </chapter>
2348
2349 <!-- ***************************************************************** -->
2350 <chapter>
2351 <title>Development with GTK+: widget specific questions</title>
2352
2353 <!-- ----------------------------------------------------------------- -->
2354
2355 <sect1>
2356 <title>How do I find out about the selection of a GtkList?</title>
2357
2358 <para>Get the selection something like this:</para>
2359
2360 <programlisting role="C">
2361 GList *sel;
2362 sel = GTK_LIST(list)->selection;
2363 </programlisting>
2364
2365 <para>This is how GList is defined (quoting glist.h):</para>
2366
2367 <programlisting role="C">
2368 typedef struct _GList GList;
2369
2370 struct _GList
2371 {
2372   gpointer data;
2373   GList *next;
2374   GList *prev;
2375 };
2376 </programlisting>
2377
2378 <para>A GList structure is just a simple structure for doubly
2379 linked lists. There exist several g_list_*() functions to
2380 modify a linked list in glib.h.  However the
2381 GTK_LIST(MyGtkList)->selection is maintained by the
2382 gtk_list_*() functions and should not be modified.</para>
2383
2384
2385 <para>The selection_mode of the GtkList determines the
2386 selection facilities of a GtkList and therefore the contents
2387 of GTK_LIST(AnyGtkList)->selection:</para>
2388
2389 <informaltable frame="all">
2390 <tgroup cols="2">
2391 <thead>
2392 <row>
2393 <entry><literal>selection_mode</literal></entry>
2394 <entry><literal> GTK_LIST()->selection</literal>
2395 contents</entry>
2396 </row>
2397 </thead>
2398
2399 <tbody>
2400 <row>
2401 <entry><literal>GTK_SELECTION_SINGLE</literal></entry>
2402 <entry>selection is either NULL or contains a GList*
2403 pointer for a single selected item.</entry>
2404 </row>
2405
2406 <row>
2407 <entry><literal>GTK_SELECTION_BROWSE</literal></entry>
2408 <entry>selection is NULL if the list contains no
2409 widgets, otherwise it contains a GList*
2410 pointer for one GList structure.</entry>
2411 </row>
2412
2413 <row>
2414 <entry><literal>GTK_SELECTION_MULTIPLE</literal></entry>
2415 <entry>selection is NULL if no listitems are selected
2416 or a a GList* pointer for the first selected
2417 item. that in turn points to a GList structure
2418 for the second selected item and so
2419 on.</entry>
2420 </row>
2421
2422 <row>
2423 <entry><literal>GTK_SELECTION_EXTENDED</literal></entry>
2424 <entry>selection is NULL.</entry>
2425 </row>
2426
2427 </tbody>
2428 </tgroup>
2429 </informaltable>
2430
2431 <para>The data field of the GList structure
2432 GTK_LIST(MyGtkList)->selection points to the first
2433 GtkListItem that is selected.  So if you would like to
2434 determine which listitems are selected you should go like
2435 this:</para>
2436
2437 <programlisting role="C">
2438 {
2439         gchar           *list_items[]={
2440                                 "Item0",
2441                                 "Item1",
2442                                 "foo",
2443                                 "last Item",
2444                         };
2445         guint           nlist_items=sizeof(list_items)/sizeof(list_items[0]);
2446         GtkWidget       *list_item;
2447         guint           i;
2448
2449         list=gtk_list_new();
2450         gtk_list_set_selection_mode(GTK_LIST(list), GTK_SELECTION_MULTIPLE);
2451         gtk_container_add(GTK_CONTAINER(AnyGtkContainer), list);
2452         gtk_widget_show (list);
2453
2454         for (i = 0; i < nlist_items; i++)
2455         {
2456                 list_item=gtk_list_item_new_with_label(list_items[i]);
2457                 gtk_object_set_user_data(GTK_OBJECT(list_item), (gpointer)i);
2458                 gtk_container_add(GTK_CONTAINER(list), list_item);
2459                 gtk_widget_show(list_item);
2460         }
2461 }
2462 </programlisting>
2463
2464 <para>To get known about the selection:</para>
2465
2466 <programlisting role="C">
2467 {
2468         GList   *items;
2469
2470         items=GTK_LIST(list)->selection;
2471
2472         printf("Selected Items: ");
2473         while (items) {
2474                 if (GTK_IS_LIST_ITEM(items->data))
2475                         printf("%d ", (guint) 
2476                 gtk_object_get_user_data(items->data));
2477                 items=items->next;
2478         }
2479         printf("\n");
2480 }
2481 </programlisting>
2482
2483 </sect1>
2484
2485 <!-- ----------------------------------------------------------------- -->
2486
2487 <sect1>
2488 <title>How do I stop the column headings of a GtkCList
2489 disappearing when the list is scrolled?</title>
2490
2491 <para>This happens when a GtkCList is packed into a
2492 GtkScrolledWindow using the function
2493 <literal>gtk_scroll_window_add_with_viewport()</literal>. The prefered
2494 method of adding a CList to a scrolled window is to use the
2495 function <literal>gtk_container_add</literal>, as in:</para>
2496
2497 <programlisting role="C">
2498     GtkWidget *scrolled, *clist;
2499     char *titles[] = { "Title1" , "Title2" };
2500
2501     scrolled = gtk_scrolled_window_new(NULL, NULL);
2502
2503     clist = gtk_clist_new_with_titles(2, titles);
2504     gtk_container_add(GTK_CONTAINER(scrolled), clist);
2505 </programlisting>
2506
2507 </sect1>
2508
2509 <!-- ----------------------------------------------------------------- -->
2510
2511 <sect1>
2512 <title>I don't want the user of my applications to enter text
2513 into a GtkCombo. Any idea?</title>
2514
2515 <para>A GtkCombo has an associated entry which can be accessed
2516 using the following expression:</para>
2517
2518 <programlisting role="C">
2519       GTK_COMBO(combo_widget)->entry
2520 </programlisting>
2521
2522 <para>If you don't want the user to be able to modify the
2523 content of this entry, you can use the
2524 gtk_editable_set_editable() function:</para>
2525
2526
2527 <programlisting role="C">
2528 void gtk_editable_set_editable (GtkEditable *editable,
2529                                 gboolean     is_editable);
2530 </programlisting>
2531
2532 <para>Set the is_editable parameter to FALSE to disable typing
2533 into the entry.</para>
2534 </sect1>
2535
2536 <!-- ----------------------------------------------------------------- -->
2537
2538 <sect1>
2539 <title>How do I catch a combo box change?</title>
2540
2541 <para>The entry which is associated to your GtkCombo send a
2542 "changed" signal when:</para>
2543
2544 <itemizedlist>
2545 <listitem><simpara>some text is typed in</simpara>
2546 </listitem>
2547
2548 <listitem><simpara>the selection of the combo box is changed</simpara>
2549 </listitem>
2550 </itemizedlist>
2551
2552 <para>To catch any combo box change, simply connect your
2553 signal handler with</para>
2554
2555 <programlisting role="C">
2556       g_signal_connect(GTK_COMBO(cb)->entry,
2557                        "changed",
2558                        G_CALLBACK(my_cb_change_handler),
2559                        NULL);
2560 </programlisting>
2561
2562 </sect1>
2563
2564 <!-- ----------------------------------------------------------------- -->
2565
2566 <sect1>
2567 <title>How can I define a separation line in a menu?</title>
2568
2569 <para>See the <ulink
2570 url="http://www.gtk.org/tutorial/">Tutorial</ulink> for
2571 information on how to create menus. However, to create a
2572 separation line in a menu, just insert an empty menu item:</para>
2573
2574 <programlisting role="C">
2575 menuitem = gtk_menu_item_new();
2576 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem);
2577 gtk_widget_show(menuitem);
2578 </programlisting>
2579
2580 </sect1>
2581
2582 <!-- ----------------------------------------------------------------- -->
2583
2584 <sect1>
2585 <title>How can I right justify a menu, such as Help?</title>
2586
2587 <para>Depending on if you use the MenuFactory or not, there
2588 are two ways to proceed. With the MenuFactory, use something
2589 like the following:</para>
2590
2591 <programlisting role="C">
2592 menu_path = gtk_menu_factory_find (factory,  "&lt;MyApp&gt;/Help");
2593 gtk_menu_item_right_justify(menu_path->widget);
2594 </programlisting>
2595
2596 <para>If you do not use the MenuFactory, you should simply
2597 use:</para>
2598
2599
2600 <programlisting role="C">
2601 gtk_menu_item_right_justify(my_menu_item);
2602 </programlisting>
2603
2604 </sect1>
2605
2606 <!-- ----------------------------------------------------------------- -->
2607
2608 <sect1>
2609 <title>How do I add some underlined accelerators to menu
2610 items?</title>
2611
2612 <para>Damon Chaplin, the technical force behind the Glade
2613 project, provided the following code sample (this code is an
2614 output from Glade). It creates a small <GUIMenu>File</guimenu> menu item
2615 with only one child (<guimenu>New</guimenu>). The F in
2616 <guimenu>File</guimenu> and the N in <guimenu>New</guimenu> are
2617 underlined, and the relevant accelerators are created.</para>
2618
2619 <programlisting role="C">
2620   menubar1 = gtk_menu_bar_new ();
2621   gtk_object_set_data (GTK_OBJECT (window1), "menubar1", menubar1);
2622   gtk_widget_show (menubar1);
2623   gtk_box_pack_start (GTK_BOX (vbox1), menubar1, FALSE, FALSE, 0);
2624
2625   file1 = gtk_menu_item_new_with_label ("");
2626   gtk_label_set_use_underline (GTK_LABEL (gtk_bin_get_child (GTK_BIN (file1))),
2627                                TRUE);
2628   gtk_widget_add_accelerator (file1, "activate_item", accel_group,
2629                               tmp_key, GDK_MOD1_MASK, 0);
2630   gtk_object_set_data (GTK_OBJECT (window1), "file1", file1);
2631   gtk_widget_show (file1);
2632   gtk_container_add (GTK_CONTAINER (menubar1), file1);
2633
2634   file1_menu = gtk_menu_new ();
2635   file1_menu_accels = gtk_menu_ensure_uline_accel_group (GTK_MENU (file1_menu));
2636   gtk_object_set_data (GTK_OBJECT (window1), "file1_menu", file1_menu);
2637   gtk_menu_item_set_submenu (GTK_MENU_ITEM (file1), file1_menu);
2638
2639   new1 = gtk_menu_item_new_with_label ("");
2640   gtk_label_set_use_underline (GTK_LABEL (gtk_bin_get_child (GTK_BIN (new1))),
2641                                TRUE);
2642   gtk_widget_add_accelerator (new1, "activate_item", file1_menu_accels,
2643                               tmp_key, 0, 0);
2644   gtk_object_set_data (GTK_OBJECT (window1), "new1", new1);
2645   gtk_widget_show (new1);
2646   gtk_container_add (GTK_CONTAINER (file1_menu), new1);
2647 </programlisting>
2648
2649 </sect1>
2650
2651 <!-- ----------------------------------------------------------------- -->
2652
2653 <sect1>
2654 <title>How can I retrieve the text from a GtkMenuItem?</title>
2655
2656 <para>You can usually retrieve the label of a specific
2657 GtkMenuItem with:</para>
2658
2659 <programlisting role="C">
2660     if (GTK_BIN (menu_item)->child)
2661     {
2662       GtkWidget *child = GTK_BIN (menu_item)->child;
2663   
2664       /* do stuff with child */
2665       if (GTK_IS_LABEL (child))
2666       {
2667         const gchar *text;
2668     
2669         text = gtk_label_get_text (GTK_LABEL (child));
2670         g_print ("menu item text: %s\n", text);
2671       }
2672     }
2673 </programlisting>
2674
2675 <para>To get the active menu item from a GtkOptionMenu you can
2676 do:</para>
2677
2678 <programlisting role="C">
2679 if (GTK_OPTION_MENU (option_menu)->menu_item)
2680 {
2681   GtkWidget *menu_item = GTK_OPTION_MENU (option_menu)->menu_item;
2682 }
2683 </programlisting>
2684
2685 <para>But, there's a catch. For this specific case, you can
2686 <emphasis>not</emphasis> get the label widget from
2687 <literal>menu_item</literal> with the above code, because the
2688 option menu reparents the menu_item's child temporarily to
2689 display the currently active contents. So to retrive the child
2690 of the currently active menu_item of an option menu, you'll
2691 have to do:</para>
2692
2693 <programlisting role="C">
2694     if (GTK_BIN (option_menu)->child)
2695     {
2696       GtkWidget *child = GTK_BIN (option_menu)->child;
2697
2698       /* do stuff with child */
2699     }
2700 </programlisting>
2701
2702 </sect1>
2703
2704 <!-- ----------------------------------------------------------------- -->
2705
2706 <sect1>
2707 <title>How do I right (or otherwise) justify a
2708 GtkLabel?</title>
2709
2710 <para>Are you sure you want to <emphasis>justify</emphasis>
2711 the labels? The label class contains the
2712 <literal>gtk_label_set_justify()</literal> function that is
2713 used to control the justification of a multi-line
2714 label.</para>
2715
2716 <para>What you probably want is to set the <emphasis>alignment</emphasis>
2717 of the label, ie right align it, center it or left align
2718 it. If you want to do this, you should use:</para>
2719
2720 <programlisting role="C">
2721 void gtk_misc_set_alignment (GtkMisc *misc,
2722                              gfloat xalign,
2723                              gfloat yalign);
2724 </programlisting>
2725
2726 <para>where the <literal>xalign</literal> and
2727 <literal>yalign</literal> values are floats in
2728 [0.00;1.00].</para>
2729
2730 <programlisting role="C">
2731 GtkWidget       *label;
2732
2733 /* horizontal : left align, vertical : top */
2734 gtk_misc_set_alignment(GTK_MISC(label), 0.0f, 0.0f);
2735
2736 /* horizontal : centered, vertical : centered */
2737 gtk_misc_set_alignment(GTK_MISC(label), 0.5f, 0.5f);
2738
2739 /* horizontal : right align, vertical : bottom */
2740 gtk_misc_set_alignment(GTK_MISC(label), 1.0f, 1.0f);
2741 </programlisting>
2742
2743 </sect1>
2744
2745 <!-- ----------------------------------------------------------------- -->
2746
2747 <sect1>
2748 <title>How do I set the background color of a GtkLabel
2749 widget?</title>
2750
2751 <para>The GtkLabel widget is one of a few GTK+ widgets that
2752 don't create their own window to render themselves
2753 into. Instead, they draw themselves directly onto their
2754 parents window.</para>
2755
2756 <para>This means that in order to set the background color for
2757 a GtkLabel widget, you need to change the background color of
2758 its parent, i.e. the object that you pack it into.</para>
2759
2760 </sect1> 
2761
2762 <!-- ----------------------------------------------------------------- -->
2763
2764 <sect1>
2765 <title>How do I set the color and font of a GtkLabel using a
2766 Resource File?</title>
2767
2768 <para>The widget name path constructed for a Label consists of
2769 the widget names of its object hierarchy as well, e.g.</para>
2770
2771 <para><literallayout>
2772 <literal>window (name: humphrey)</literal>
2773 <literal>  hbox</literal>
2774 <literal>     label (name: mylabel)</literal>
2775 </literallayout></para>
2776
2777 <para>The widget path your pattern needs to match would be:
2778 <literal>humphrey.GtkHBox.mylabel</literal></para>
2779
2780 <para>The resource file may look something like:</para>
2781
2782 <programlisting role="C">
2783 style "title"
2784 {
2785       fg[NORMAL] = {1.0, 0.0, 0.0}
2786       font = "-adobe-helvetica-bold-r-normal--*-140-*-*-*-*-*-*"
2787 }
2788 widget "*mylabel" style "title"
2789 </programlisting>
2790
2791 <para>In your program, you would also need to give a name to
2792 the Label widget, which can be done using:</para>
2793
2794 <programlisting role="C">
2795   label = gtk_label_new("Some Label Text");
2796   gtk_widget_set_name(label, "mylabel");
2797   gtk_widget_show(label);
2798 </programlisting>
2799
2800 </sect1>
2801
2802 <!-- ----------------------------------------------------------------- -->
2803
2804 <sect1>
2805 <title>How do I configure Tooltips in a Resource File?</title>
2806
2807 <para>The tooltip's window is named "gtk-tooltips",
2808 GtkTooltips in itself is not a GtkWidget (though a GtkObject)
2809 and as such is not attempted to match any widget styles.</para>
2810
2811 <para>So, your resource file should look something like:</para>
2812
2813 <programlisting role="C">
2814 style "postie"
2815 {
2816       bg[NORMAL] = {1.0, 1.0, 0.0}
2817 }
2818 widget "gtk-tooltips*" style "postie"
2819 </programlisting>
2820
2821 </sect1>
2822
2823 <!-- ----------------------------------------------------------------- -->
2824
2825 <sect1>
2826 <title>I can't add more than (something like) 2000 chars in a
2827 GtkEntry. What's wrong?</title>
2828
2829 <para>There is now a known problem in the GtkEntry widget. In
2830 the <literal>gtk_entry_insert_text()</literal> function, the
2831 following lines limit the number of chars in the entry to
2832 2047.</para>
2833
2834 <programlisting role="C">
2835   /* The algorithms here will work as long as, the text size (a
2836    * multiple of 2), fits into a guint16 but we specify a shorter
2837    * maximum length so that if the user pastes a very long text, there
2838    * is not a long hang from the slow X_LOCALE functions.  */
2839
2840   if (entry->text_max_length == 0)
2841     max_length = 2047;
2842   else
2843     max_length = MIN (2047, entry->text_max_length);
2844 </programlisting>
2845
2846 </sect1>
2847
2848 <!-- ----------------------------------------------------------------- -->
2849
2850 <sect1>
2851 <title>How do I make a GtkEntry widget activate on pressing
2852 the Return key?</title>
2853
2854 <para>The Entry widget emits an 'activate' signal when you
2855 press return in it. Just attach to the activate signal on the
2856 entry and do whatever you want to do. Typical code would
2857 be:</para>
2858
2859 <programlisting role="C">
2860   entry = gtk_entry_new();
2861   g_signal_connect (entry, "activate",
2862                     G_CALLBACK(entry_callback),
2863                     NULL);
2864 </programlisting>
2865
2866 </sect1>
2867
2868 <!-- ----------------------------------------------------------------- -->
2869
2870 <sect1>
2871 <title>How do I validate/limit/filter the input to a GtkEntry? <emphasis>[GTK 2.x]</emphasis></title>
2872
2873 <para>If you want to validate the text that a user enters into
2874 a GtkEntry widget you can attach to the "insert_text" signal
2875 of the entry, and modify the text within the callback
2876 function. The example below forces all characters to
2877 uppercase, and limits the range of characters to A-Z. Note
2878 that the entry is cast to an object of type GtkEditable, from
2879 which GtkEntry is derived.</para>
2880
2881 <programlisting role="C">
2882 #include &lt;ctype.h&gt;
2883 #include &lt;gtk/gtk.h&gt;
2884
2885 void insert_text_handler (GtkEntry    *entry,
2886                           const gchar *text,
2887                           gint         length,
2888                           gint        *position,
2889                           gpointer     data)
2890 {
2891   GtkEditable *editable = GTK_EDITABLE(entry);
2892   int i, count=0;
2893   gchar *result = g_new (gchar, length);
2894
2895   for (i=0; i < length; i++) {
2896     if (!isalpha(text[i]))
2897       continue;
2898     result[count++] = islower(text[i]) ? toupper(text[i]) : text[i];
2899   }
2900   
2901   if (count > 0) {
2902     g_signal_handlers_block_by_func (G_OBJECT (editable),
2903                                      G_CALLBACK (insert_text_handler),
2904                                      data);
2905     gtk_editable_insert_text (editable, result, count, position);
2906     g_signal_handlers_unblock_by_func (G_OBJECT (editable),
2907                                        G_CALLBACK (insert_text_handler),
2908                                        data);
2909   }
2910   g_signal_stop_emission_by_name (G_OBJECT (editable), "insert_text");
2911
2912   g_free (result);
2913 }
2914
2915 int main (int   argc,
2916           char *argv[])
2917 {
2918   GtkWidget *window;
2919   GtkWidget *entry;
2920   
2921   gtk_init (&amp;argc, &amp;argv);
2922   
2923   /* create a new window */
2924   window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2925   gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
2926   g_signal_connect (G_OBJECT (window), "destroy",
2927                     G_CALLBACK (gtk_main_quit),
2928                     NULL);
2929
2930   entry = gtk_entry_new();
2931   g_signal_connect(G_OBJECT(entry), "insert_text",
2932                      G_CALLBACK(insert_text_handler),
2933                      NULL);
2934   gtk_container_add(GTK_CONTAINER (window), entry);
2935   gtk_widget_show(entry);
2936   
2937   gtk_widget_show(window);
2938   
2939   gtk_main();
2940   return(0);
2941 }
2942 </programlisting>
2943
2944 </sect1>
2945
2946 <!-- ----------------------------------------------------------------- -->
2947
2948 <sect1>
2949 <title>How do I use horizontal scrollbars with a GtkText widget?</title>
2950
2951 <para>The short answer is that you can't. The current version
2952 of the GtkText widget does not support horizontal
2953 scrolling. There is an intention to completely rewrite the
2954 GtkText widget, at which time this limitation will be
2955 removed.</para>
2956
2957 </sect1>
2958
2959 <!-- ----------------------------------------------------------------- -->
2960
2961 <sect1>
2962 <title>How do I change the font of a GtkText widget?</title>
2963
2964 <para>There are a couple of ways of doing this. As GTK+ allows
2965 the appearance of applications to be changed at run time using
2966 resources you can use something like the following in the
2967 appropriate file:</para>
2968
2969 <programlisting role="C">
2970 style "text"
2971 {
2972   font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
2973 }
2974 </programlisting>
2975
2976 <para>Another way to do this is to load a font within your
2977 program, and then use this in the functions for adding text to
2978 the text widget. You can load a font using, for example:</para>
2979
2980 <programlisting role="C">
2981   GdkFont *font;
2982   font = gdk_font_load("-adobe-helvetica-medium-r-normal--*-140-*-*-*-*-*-*");
2983 </programlisting>
2984
2985 </sect1>
2986
2987 <!-- ----------------------------------------------------------------- -->
2988
2989 <sect1>
2990 <title>How do I set the cursor position in a GtkText
2991 object?</title>
2992
2993 <para>Notice that the response is valid for any object that
2994 inherits from the GtkEditable class.</para>
2995
2996 <para>Are you sure that you want to move the cursor position?
2997 Most of the time, while the cursor position is good, the
2998 insertion point does not match the cursor position. If this
2999 apply to what you really want, then you should use the
3000 <literal>gtk_text_set_point()</literal> function. If you want
3001 to set the insertion point at the current cursor position, use
3002 the following:</para>
3003
3004 <programlisting role="C">
3005   gtk_text_set_point(GTK_TEXT(text),
3006   gtk_editable_get_position(GTK_EDITABLE(text)));
3007 </programlisting>
3008
3009 <para>If you want the insertion point to follow the cursor at
3010 all time, you should probably catch the button press event,
3011 and then move the insertion point. Be careful : you'll have to
3012 catch it after the widget has changed the cursor position
3013 though. Thomas Mailund Jensen proposed the following
3014 code:</para>
3015
3016 <programlisting role="C">
3017 static void
3018 insert_bar (GtkWidget *text)
3019 {
3020   /* jump to cursor mark */
3021   gtk_text_set_point (GTK_TEXT (text),
3022   gtk_editable_get_position (GTK_EDITABLE  (text)));
3023
3024   gtk_text_insert (GTK_TEXT (text), NULL, NULL, NULL,
3025      "bar", strlen ("bar"));
3026 }
3027
3028 int
3029 main (int argc, char *argv[])
3030 {
3031   GtkWidget *window, *text;
3032
3033   gtk_init (&amp;argc, &amp;argv);
3034
3035   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3036   text = gtk_text_new (NULL, NULL);
3037   gtk_text_set_editable (GTK_TEXT (text), TRUE);
3038   gtk_container_add (GTK_CONTAINER (window), text);
3039
3040   /* connect after everything else */
3041   g_signal_connect_after (text, "button_press_event",
3042                           G_CALLBACK (insert_bar), NULL);
3043
3044   gtk_widget_show_all(window);
3045   gtk_main();
3046
3047   return 0;
3048 }
3049 </programlisting>
3050
3051 <para>Now, if you really want to change the cursor position,
3052 you should use the
3053 <literal>gtk_editable_set_position()</literal>
3054 function.</para>
3055
3056 </sect1>
3057
3058 </chapter>
3059
3060 <!-- ***************************************************************** -->
3061 <chapter>
3062 <title>About GDK</title>
3063
3064 <!-- ----------------------------------------------------------------- -->
3065
3066 <sect1>
3067 <title>What is GDK?</title>
3068
3069 <para>GDK is basically a wrapper around the standard Xlib
3070 function calls. If you are at all familiar with Xlib, a lot of
3071 the functions in GDK will require little or no getting used
3072 to. All functions are written to provide an way to access Xlib
3073 functions in an easier and slightly more intuitive manner. In
3074 addition, since GDK uses GLib (see below), it will be more
3075 portable and safer to use on multiple platforms.</para>
3076
3077 <!-- Examples, anybody? I've been mulling some over. NF -->
3078
3079 </sect1>
3080
3081 <!-- ----------------------------------------------------------------- -->
3082
3083 <sect1>
3084 <title>How do I use color allocation?</title>
3085
3086 <para>One of the nice things about GDK is that it's based on
3087 top of Xlib; this is also a problem, especially in the area of
3088 color management. If you want  to use color in your program
3089 (drawing a rectangle or such, your code  should look something
3090 like this:</para>
3091
3092 <programlisting role="C">
3093 {
3094   GdkColor *color;
3095   int width, height;
3096   GtkWidget *widget;
3097   GdkGC *gc;
3098
3099   ...
3100   
3101   /* first, create a GC to draw on */
3102   gc = gdk_gc_new(widget->window);
3103
3104   /* find proper dimensions for rectangle */
3105   gdk_window_get_size(widget->window, &amp;width, &amp;height);
3106
3107   /* the color we want to use */
3108   color = (GdkColor *)malloc(sizeof(GdkColor));
3109   
3110   /* red, green, and blue are passed values, indicating the RGB triple
3111    * of the color we want to draw. Note that the values of the RGB components
3112    * within the GdkColor are taken from 0 to 65535, not 0 to 255.
3113    */
3114   color->red = red * (65535/255);
3115   color->green = green * (65535/255);
3116   color->blue = blue * (65535/255);
3117   
3118   /* the pixel value indicates the index in the colormap of the color.
3119    * it is simply a combination of the RGB values we set earlier
3120    */
3121   color->pixel = (gulong)(red*65536 + green*256 + blue);
3122
3123   /* However, the pixel valule is only truly valid on 24-bit (TrueColor)
3124    * displays. Therefore, this call is required so that GDK and X can
3125    * give us the closest color available in the colormap
3126    */
3127   gdk_color_alloc(gtk_widget_get_colormap(widget), color);
3128
3129   /* set the foreground to our color */
3130   gdk_gc_set_foreground(gc, color);
3131   
3132   /* draw the rectangle */
3133   gdk_draw_rectangle(widget->window, gc, 1, 0, 0, width, height);
3134
3135   ...
3136 }
3137 </programlisting>
3138
3139 </sect1>
3140
3141 </chapter>
3142
3143 <!-- ***************************************************************** -->
3144 <chapter>
3145 <title>About GLib</title>
3146
3147 <!-- ----------------------------------------------------------------- -->
3148
3149 <sect1>
3150 <title>What is GLib?</title>
3151
3152 <para>GLib is a library of useful functions and definitions
3153 available for use  when creating GDK and GTK applications. It
3154 provides replacements for some standard libc functions, such
3155 as malloc, which are buggy on some systems.</para>
3156
3157 <para>It also provides routines for handling:</para>
3158
3159 <itemizedlist spacing=compact>
3160 <listitem><simpara>Doubly Linked Lists</simpara>
3161 </listitem>
3162
3163 <listitem><simpara>Singly Linked Lists</simpara>
3164 </listitem>
3165
3166 <listitem><simpara>Timers</simpara>
3167 </listitem>
3168
3169 <listitem><simpara>String Handling</simpara>
3170 </listitem>
3171
3172 <listitem><simpara>A Lexical Scanner</simpara>
3173 </listitem>
3174
3175 <listitem><simpara>Error Functions</simpara>
3176 </listitem>
3177 </itemizedlist>
3178
3179 </sect1>
3180
3181 <!-- ----------------------------------------------------------------- -->
3182
3183 <sect1>
3184 <title>How can I use the doubly linked lists?</title>
3185
3186 <para>The GList object is defined as:</para>
3187
3188 <programlisting role="C">
3189 typedef struct _GList GList;
3190
3191 struct _GList
3192 {
3193   gpointer data;
3194   GList *next;
3195   GList *prev;
3196 };
3197 </programlisting>
3198
3199 <para>To use the GList objects, simply:</para>
3200
3201 <programlisting role="C">
3202 GList   *list = NULL;
3203 GList   *listrunner;
3204 gint    array[] = { 1, 2, 3, 4, 5, 6 };
3205 gint    pos;
3206 gint    *value;
3207
3208 /* add data to the list */
3209 for (pos=0;pos < sizeof array; pos++) {
3210   list = g_list_append(list, (gpointer)&amp;array[pos]);
3211 }
3212
3213 /* run through the list */
3214 listrunner = g_list_first(list);
3215 while (listrunner) {
3216   value = (gint *)listrunner->data;
3217   printf("%d\n", *value);
3218   listrunner = g_list_next(listrunner);
3219 }
3220
3221 /* removing datas from the list */
3222 listrunner = g_list_first(list);
3223 list = g_list_remove_link(list, listrunner);
3224 list = g_list_remove(list, &amp;array[4]);
3225 </programlisting>
3226
3227 <para>The same code is usable with singly linked lists (GSList
3228 objects) by replacing g_list_* functions with the relevant
3229 g_slist_* ones (g_slist_append,  g_slist_remove, ...). Just
3230 remember that since you can't go backward in a singly linked
3231 list, there is no g_slist_first function - you'll need to keep
3232 a  reference on the first node of the list.</para>
3233
3234 <!-- Some Examples might be useful here! NF -->
3235 <!-- I believe it should be better :) ED -->
3236 <!-- Linked lists are pretty standard data structures - don't want to
3237 over do it - TRG -->
3238
3239 </sect1>
3240
3241 <!-- ----------------------------------------------------------------- -->
3242
3243 <sect1>
3244 <title>Memory does not seem to be released when I free the
3245 list nodes I've allocated</title>
3246
3247 <para>GLib tries to be "intelligent" on this special issue: it
3248 assumes that you are likely to reuse the objects, so caches
3249 the allocated memory. If you do not want to use this behavior,
3250 you'll probably want to set up a special allocator.</para>
3251
3252 <para>To quote Tim Janik:</para>
3253 <para><quote>If you have a certain portion of code that uses *lots*
3254 of GLists or GNodes, and you know you'd better want to release
3255 all of them after a short while, you'd want to use a
3256 GAllocator. Pushing an allocator into g_list will make all
3257 subsequent glist operations private to that allocator's memory
3258 pool (and thus you have to take care to pop the allocator
3259 again, before making any external calls): </quote></para>
3260
3261 <programlisting role="C">
3262 GAllocator *allocator;
3263 GList *list = NULL;
3264 guint i;
3265
3266 /* set a new allocation pool for GList nodes */
3267 allocator = g_allocator_new ("list heap", 1024);
3268 g_list_push_allocator (allocator);
3269
3270 /* do some list operations */
3271 for (i = 0; i < 4096; i++)
3272   list = g_list_prepend (list, NULL);
3273 list = g_list_reverse (list);
3274
3275 /* beware to pop allocator befor calling external functions */
3276 g_list_pop_allocator ();
3277 gtk_label_set_text (GTK_LABEL (some_label), "some text");
3278
3279 /* and set our private glist pool again */
3280 g_list_push_allocator (allocator);
3281
3282 /* do some list operations */
3283 g_list_free (list);
3284 list = NULL;
3285 for (i = 0; i < 4096; i++)
3286   list = g_list_prepend (list, NULL);
3287   
3288 /* and back out (while freeing all of the list nodes in our pool) */
3289 g_list_pop_allocator ();
3290 g_allocator_free (allocator);
3291 </programlisting>
3292
3293 </sect1>
3294
3295 <!-- ----------------------------------------------------------------- -->
3296
3297 <sect1>
3298 <title>Why use g_print, g_malloc, g_strdup and fellow glib
3299 functions?</title>
3300
3301 <para>Thanks to Tim Janik who wrote to gtk-list: (slightly
3302 modified)</para>
3303
3304 <para><quote>Regarding g_malloc(), g_free() and siblings, these
3305 functions are much safer than their libc equivalents. For
3306 example, g_free() just returns if called with NULL. Also, if
3307 USE_DMALLOC is defined, the definition for these functions
3308 changes (in glib.h) to use MALLOC(), FREE() etc... If
3309 MEM_PROFILE or MEM_CHECK are defined, there are even small
3310 statistics made counting the used block sizes (shown by
3311 g_mem_profile() / g_mem_check()).</quote></para>
3312
3313 <para><quote>Considering the fact that glib provides an interface for
3314 memory chunks to save space if you have lots of blocks that
3315 are always the same size and to mark them ALLOC_ONLY if
3316 needed, it is just straight forward to create a small saver
3317 (debug able) wrapper around the normal malloc/free stuff as
3318 well - just like gdk covers Xlib. ;)</quote></para>
3319
3320 <para><quote>Using g_error() and g_warning() inside of applications
3321 like the GIMP that fully rely on gtk even gives the
3322 opportunity to pop up a window showing the messages inside of
3323 a gtk window with your own handler (by using
3324 g_set_error_handler()) along the lines of
3325 <literal>gtk_print()</literal> (inside of
3326 gtkmain.c).</quote></para>
3327
3328 </sect1>
3329
3330 <!-- ----------------------------------------------------------------- -->
3331
3332 <sect1>
3333 <title>What's a GScanner and how do I use one?</title>
3334
3335 <para>A GScanner will tokenize your text, that is, it'll return
3336 an integer for every word or number that appears in its input
3337 stream, following certain (customizable) rules to perform this
3338 translation. You still need to write the parsing functions on
3339 your own though.</para>
3340
3341 <para>Here's a little test program supplied by Tim Janik that
3342 will parse</para>
3343
3344 <para><literallayout>
3345 <literal>&lt;SYMBOL&gt; = &lt;OPTIONAL-MINUS&gt; &lt;NUMBER&gt; ;</literal>
3346 </literallayout></para>
3347
3348 <para>constructs, while skipping "#\n" and "/**/" style
3349 comments.</para>
3350
3351 <programlisting role="C">
3352 #include &lt;glib.h&gt;
3353
3354 /* some test text to be fed into the scanner */
3355 static const gchar *test_text =
3356 ( "ping = 5;\n"
3357   "/* slide in some \n"
3358   " * comments, just for the\n"
3359   " * fun of it \n"
3360   " */\n"
3361   "pong = -6; \n"
3362   "\n"
3363   "# the next value is a float\n"
3364   "zonk = 0.7;\n"
3365   "# redefine ping\n"
3366   "ping = - 0.5;\n" );
3367
3368 /* define enumeration values to be returned for specific symbols */
3369 enum {
3370   SYMBOL_PING = G_TOKEN_LAST + 1,
3371   SYMBOL_PONG = G_TOKEN_LAST + 2,
3372   SYMBOL_ZONK = G_TOKEN_LAST + 3
3373 };
3374
3375 /* symbol array */
3376 static const struct {
3377   gchar *symbol_name;
3378   guint  symbol_token;
3379 } symbols[] = {
3380   { "ping", SYMBOL_PING, },
3381   { "pong", SYMBOL_PONG, },
3382   { "zonk", SYMBOL_ZONK, },
3383   { NULL, 0, },
3384 }, *symbol_p = symbols;
3385
3386 static gfloat ping = 0;
3387 static gfloat pong = 0;
3388 static gfloat zonk = 0;
3389
3390 static guint
3391 parse_symbol (GScanner *scanner)
3392 {
3393   guint symbol;
3394   gboolean negate = FALSE;
3395
3396   /* expect a valid symbol */
3397   g_scanner_get_next_token (scanner);
3398   symbol = scanner->token;
3399   if (symbol < SYMBOL_PING ||
3400       symbol > SYMBOL_ZONK)
3401     return G_TOKEN_SYMBOL;
3402
3403   /* expect '=' */
3404   g_scanner_get_next_token (scanner);
3405   if (scanner->token != '=')
3406     return '=';
3407
3408   /* feature optional '-' */
3409   g_scanner_peek_next_token (scanner);
3410   if (scanner->next_token == '-')
3411     {
3412       g_scanner_get_next_token (scanner);
3413       negate = !negate;
3414     }
3415
3416   /* expect a float (ints are converted to floats on the fly) */
3417   g_scanner_get_next_token (scanner);
3418   if (scanner->token != G_TOKEN_FLOAT)
3419     return G_TOKEN_FLOAT;
3420
3421   /* make sure the next token is a ';' */
3422   if (g_scanner_peek_next_token (scanner) != ';')
3423     {
3424       /* not so, eat up the non-semicolon and error out */
3425       g_scanner_get_next_token (scanner);
3426       return ';';
3427     }
3428
3429   /* assign value, eat the semicolon and exit successfully */
3430   switch (symbol)
3431     {
3432     case SYMBOL_PING:
3433       ping = negate ? - scanner->value.v_float : scanner->value.v_float;
3434       break;
3435     case SYMBOL_PONG:
3436       pong = negate ? - scanner->value.v_float : scanner->value.v_float;
3437       break;
3438     case SYMBOL_ZONK:
3439       zonk = negate ? - scanner->value.v_float : scanner->value.v_float;
3440       break;
3441     }
3442   g_scanner_get_next_token (scanner);
3443
3444   return G_TOKEN_NONE;
3445 }
3446
3447 int
3448 main (int argc, char *argv[])
3449 {
3450   GScanner *scanner;
3451   guint expected_token;
3452
3453   scanner = g_scanner_new (NULL);
3454
3455   /* adjust lexing behaviour to suit our needs
3456    */
3457   /* convert non-floats (octal values, hex values...) to G_TOKEN_INT */
3458   scanner->config->numbers_2_int = TRUE;
3459   /* convert G_TOKEN_INT to G_TOKEN_FLOAT */
3460   scanner->config->int_2_float = TRUE;
3461   /* don't return G_TOKEN_SYMBOL, but the symbol's value */
3462   scanner->config->symbol_2_token = TRUE;
3463
3464   /* load symbols into the scanner */
3465   while (symbol_p->symbol_name)
3466     {
3467       g_scanner_add_symbol (scanner,
3468                             symbol_p->symbol_name,
3469                             GINT_TO_POINTER (symbol_p->symbol_token));
3470       symbol_p++;
3471     }
3472
3473   /* feed in the text */
3474   g_scanner_input_text (scanner, test_text, strlen (test_text));
3475
3476   /* give the error handler an idea on how the input is named */
3477   scanner->input_name = "test text";
3478
3479   /* scanning loop, we parse the input until its end is reached,
3480    * the scanner encountered a lexing error, or our sub routine came
3481    * across invalid syntax
3482    */
3483   do
3484     {
3485       expected_token = parse_symbol (scanner);
3486       
3487       g_scanner_peek_next_token (scanner);
3488     }
3489   while (expected_token == G_TOKEN_NONE &&
3490          scanner->next_token != G_TOKEN_EOF &&
3491          scanner->next_token != G_TOKEN_ERROR);
3492
3493   /* give an error message upon syntax errors */
3494   if (expected_token != G_TOKEN_NONE)
3495     g_scanner_unexp_token (scanner, expected_token, NULL, "symbol", NULL, NULL, TRUE);
3496
3497   /* finsish parsing */
3498   g_scanner_destroy (scanner);
3499
3500   /* print results */
3501   g_print ("ping: %f\n", ping);
3502   g_print ("pong: %f\n", pong);
3503   g_print ("zonk: %f\n", zonk);
3504   
3505   return 0;
3506 }
3507 </programlisting>
3508
3509 <para>You need to understand that the scanner will parse its
3510 input and tokenize it, it is up to you to interpret these
3511 tokens, not define their types before they get parsed,
3512 e.g. watch gscanner parse a string:</para>
3513
3514 <para><literallayout>
3515 <literal>"hi i am 17"</literal>
3516 <literal> |  | |  |</literal>
3517 <literal> |  | |  v</literal>
3518 <literal> |  | v  TOKEN_INT, value: 17</literal>
3519 <literal> |  v TOKEN_IDENTIFIER, value: "am"</literal>
3520 <literal> v  TOKEN_CHAR, value: 'i'</literal>
3521 <literal>TOKEN_IDENTIFIER, value: "hi"</literal>
3522 </literallayout></para>
3523
3524 <para>If you configure the scanner with:</para>
3525
3526 <programlisting role="C">
3527 scanner->config->int_2_float = TRUE;
3528 scanner->config->char_2_token = TRUE;
3529 scanner->config->scan_symbols = TRUE;
3530 </programlisting>
3531
3532 <para>and add "am" as a symbol with</para>
3533
3534 <programlisting role="C">
3535 g_scanner_add_symbol (scanner, "am", "symbol value");
3536 </programlisting>
3537
3538 <para>GScanner will parse it as</para>
3539
3540 <para><literallayout>
3541 <literal>"hi i am 17"</literal>
3542 <literal> |  | |  |</literal>
3543 <literal> |  | |  v</literal>
3544 <literal> |  | v  TOKEN_FLOAT, value: 17.0  (automatic int->float conversion)</literal>
3545 <literal> |  | TOKEN_SYMBOL, value: "symbol value"  (a successfull hash table lookup</literal>
3546 <literal> |  |                                       turned a TOKEN_IDENTIFIER into a</literal>
3547 <literal> |  |                                       TOKEN_SYMBOL and took over the</literal>
3548 <literal> |  v                                       symbol's value)</literal>
3549 <literal> v  'i'  ('i' can be a valid token as well, as all chars >0 and <256)</literal>
3550 <literal>TOKEN_IDENTIFIER, value: "hi"</literal>
3551 </literallayout></para>
3552
3553 <para>You need to match the token sequence with your code, and
3554 if you encounter something that you don't want, you error
3555 out:</para>
3556
3557 <programlisting role="C">
3558 /* expect an identifier ("hi") */
3559 g_scanner_get_next_token (scanner);
3560 if (scanner->token != G_TOKEN_IDENTIFIER)
3561   return G_TOKEN_IDENTIFIER;
3562 /* expect a token 'i' */
3563 g_scanner_get_next_token (scanner);
3564 if (scanner->token != 'i')
3565   return 'i';
3566 /* expect a symbol ("am") */
3567 g_scanner_get_next_token (scanner);
3568 if (scanner->token != G_TOKEN_SYMBOL)
3569   return G_TOKEN_SYMBOL;
3570 /* expect a float (17.0) */
3571 g_scanner_get_next_token (scanner);
3572 if (scanner->token != G_TOKEN_FLOAT)
3573   return G_TOKEN_FLOAT;
3574 </programlisting>
3575
3576 <para>If you got past here, you have parsed "hi i am 17" and
3577 would have accepted "dooh i am 42" and  "bah i am 0.75" as
3578 well, but you would have not accepted "hi 7 am 17" or "hi i hi
3579 17".</para>
3580
3581 </sect1>
3582
3583 </chapter>
3584
3585 <!-- ***************************************************************** -->
3586
3587 <chapter>
3588 <title>GTK+ FAQ Contributions, Maintainers and Copyright</title>
3589
3590 <para>If you would like to make a contribution to the FAQ, send either one
3591 of us an e-mail message with the exact text you think should be
3592 included (question and answer). With your help, this document can grow
3593 and become more useful!</para>
3594
3595 <para>This document is maintained by
3596 Tony Gale
3597 <ulink url="mailto:gale@gtk.org">&lt;gale@gtk.org&gt;</ulink>
3598
3599 This FAQ was created by Shawn T. Amundson 
3600 <ulink url="mailto:amundson@gimp.org">
3601 &lt;amundson@gimp.org&gt;</ulink>.
3602
3603 Contributions should be sent to Tony Gale <ulink
3604 url="mailto:gale@gtk.org">&lt;gale@gtk.org&gt;</ulink></para>
3605
3606 <para>The GTK+ FAQ is Copyright (C) 1997-2003 by Shawn T. Amundson, 
3607 Tony Gale.</para>
3608
3609 <para>Permission is granted to make and distribute verbatim copies of this
3610 manual provided the copyright notice and this permission notice are
3611 preserved on all copies.</para>
3612
3613 <para>Permission is granted to copy and distribute modified versions of this
3614 document under the conditions for verbatim copying, provided that this
3615 copyright notice is included exactly as in the original, and that the
3616 entire resulting derived work is distributed under the terms of a
3617 permission notice identical to this one.</para>
3618
3619 <para>Permission is granted to copy and distribute translations of this
3620 document into another language, under the above conditions for
3621 modified versions.</para>
3622
3623 <para>If you are intending to incorporate this document into a published
3624 work, please contact one of the maintainers, and we will make an
3625 effort to ensure that you have the most up to date information
3626 available.</para>
3627
3628 <para>There is no guarentee that this document lives up to its intended
3629 purpose.  This is simply provided as a free resource.  As such, the
3630 authors and maintainers of the information provided within can not
3631 make any guarentee that the information is even accurate.</para>
3632
3633 </chapter>
3634
3635 <!-- ----------------------------------------------------------------- -->
3636
3637 </book>