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