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