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