1 <?xml version='1.0' encoding="ISO-8859-1"?> 2 <partintro> 3 <para> 4 This chapter tries to answer the real-life questions of users and presents 5 the most common scenario use cases I could come up with. 6 The use cases are presented from most likely to less likely. 7 </para> 8 </partintro> 9 10 <chapter id="howto-gobject"> 11 <title>How to define and implement a new GObject</title> 12 13 <para> 14 Clearly, this is one of the most common questions people ask: they just 15 want to crank code and implement a subclass of a GObject. Sometimes because 16 they want to create their own class hierarchy, sometimes because they want 17 to subclass one of GTK+'s widget. This chapter will focus on the 18 implementation of a subtype of GObject. 19 </para> 20 21 <sect1 id="howto-gobject-header"> 22 <title>Boilerplate header code</title> 23 24 <para> 25 The first step before writing the code for your GObject is to write the 26 type's header which contains the needed type, function and macro 27 definitions. Each of these elements is nothing but a convention which 28 is followed not only by GTK+'s code but also by most users of GObject. 29 If you feel the need not to obey the rules stated below, think about it 30 twice: 31 <itemizedlist> 32 <listitem><para>If your users are a bit accustomed to GTK+ code or any 33 GLib code, they will be a bit surprised and getting used to the 34 conventions you decided upon will take time (money) and will make them 35 grumpy (not a good thing)</para></listitem> 36 <listitem><para>You must assess the fact that these conventions might 37 have been designed by both smart and experienced people: maybe they 38 were at least partly right. Try to put your ego aside.</para></listitem> 39 </itemizedlist> 40 </para> 41 42 <para> 43 Pick a name convention for your headers and source code and stick to it: 44 <itemizedlist> 45 <listitem><para>use a dash to separate the prefix from the typename: 46 <filename>maman-bar.h</filename> and <filename>maman-bar.c</filename> 47 (this is the convention used by Nautilus and most GNOME libraries).</para></listitem> 48 <listitem><para>use an underscore to separate the prefix from the 49 typename: <filename>maman_bar.h</filename> and 50 <filename>maman_bar.c</filename>.</para></listitem> 51 <listitem><para>Do not separate the prefix from the typename: 52 <filename>mamanbar.h</filename> and <filename>mamanbar.c</filename>. 53 (this is the convention used by GTK+)</para></listitem> 54 </itemizedlist> 55 I personally like the first solution better: it makes reading file names 56 easier for those with poor eyesight like me. 57 </para> 58 59 <para> 60 When you need some private (internal) declarations in several 61 (sub)classes, you can define them in a private header file which 62 is often named by appending the <emphasis>private</emphasis> keyword 63 to the public header name. For example, one could use 64 <filename>maman-bar-private.h</filename>, 65 <filename>maman_bar_private.h</filename> or 66 <filename>mamanbarprivate.h</filename>. Typically, such private header 67 files are not installed. 68 </para> 69 70 <para> 71 The basic conventions for any header which exposes a GType are described 72 in <xref linkend="gtype-conventions"/>. Most GObject-based code also 73 obeys one of of the following conventions: pick one and stick to it. 74 <itemizedlist> 75 <listitem><para> 76 If you want to declare a type named bar with prefix maman, name the type instance 77 <function>MamanBar</function> and its class <function>MamanBarClass</function> 78 (name is case-sensitive). It is customary to declare them with code similar to the 79 following: 80 <programlisting> 81 /* 82 * Copyright/Licensing information. 83 */ 84 85 /* inclusion guard */ 86 #ifndef __MAMAN_BAR_H__ 87 #define __MAMAN_BAR_H__ 88 89 #include <glib-object.h> 90 /* 91 * Potentially, include other headers on which this header depends. 92 */ 93 94 /* 95 * Type macros. 96 */ 97 #define MAMAN_TYPE_BAR (maman_bar_get_type ()) 98 #define MAMAN_BAR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar)) 99 #define MAMAN_IS_BAR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR)) 100 #define MAMAN_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass)) 101 #define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR)) 102 #define MAMAN_BAR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass)) 103 104 typedef struct _MamanBar MamanBar; 105 typedef struct _MamanBarClass MamanBarClass; 106 107 struct _MamanBar 108 { 109 GObject parent_instance; 110 111 /* instance members */ 112 }; 113 114 struct _MamanBarClass 115 { 116 GObjectClass parent_class; 117 118 /* class members */ 119 }; 120 121 /* used by MAMAN_TYPE_BAR */ 122 GType maman_bar_get_type (void); 123 124 /* 125 * Method definitions. 126 */ 127 128 #endif /* __MAMAN_BAR_H__ */ 129 </programlisting> 130 </para></listitem> 131 <listitem><para> 132 Most GTK+ types declare their private fields in the public header 133 with a /* private */ comment, relying on their user's intelligence 134 not to try to play with these fields. Fields not marked private 135 are considered public by default. The /* protected */ comment 136 (same semantics as those of C++) is also used, mainly in the GType 137 library, in code written by Tim Janik. 138 <programlisting> 139 struct _MamanBar 140 { 141 GObject parent_instance; 142 143 /*< private >*/ 144 int hsize; 145 }; 146 </programlisting> 147 </para></listitem> 148 <listitem><para> 149 All of Nautilus code and a lot of GNOME libraries use private 150 indirection members, as described by Herb Sutter in his Pimpl 151 articles(see <ulink url="http://www.gotw.ca/gotw/024.htm">Compilation Firewalls</ulink> 152 and <ulink url="http://www.gotw.ca/gotw/028.htm">The Fast Pimpl Idiom</ulink>: 153 he summarizes the different issues better than I will). 154 <programlisting> 155 typedef struct _MamanBarPrivate MamanBarPrivate; 156 157 struct _MamanBar 158 { 159 GObject parent_instance; 160 161 /*< private >*/ 162 MamanBarPrivate *priv; 163 }; 164 </programlisting> 165 <note><simpara>Do not call this <varname>private</varname>, as 166 that is a registered c++ keyword.</simpara></note> 167 168 The private structure is then defined in the .c file, using the 169 g_type_class_add_private() function to notify the presence of 170 a private memory area for each instance and it can either 171 be retrieved using <function>G_TYPE_INSTANCE_GET_PRIVATE()</function> 172 each time is needed, or assigned to the <literal>priv</literal> 173 member of the instance structure inside the object's 174 <function>init</function> function. 175 <programlisting> 176 #define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate)) 177 178 struct _MamanBarPrivate 179 { 180 int hsize; 181 } 182 183 static void 184 maman_bar_class_init (MamanBarClass *klass) 185 { 186 g_type_class_add_private (klass, sizeof (MamanBarPrivate)); 187 } 188 189 static void 190 maman_bar_init (MamanBar *self) 191 { 192 MamanBarPrivate *priv; 193 194 self->priv = priv = MAMAN_BAR_GET_PRIVATE (self); 195 196 priv->hsize = 42; 197 } 198 </programlisting> 199 </para></listitem> 200 201 <listitem><para> 202 You don't need to free or allocate the private structure, only the 203 objects or pointers that it may contain. Another advantage of this 204 to the previous version is that is lessens memory fragmentation, 205 as the public and private parts of the instance memory are 206 allocated at once. 207 </para></listitem> 208 </itemizedlist> 209 </para> 210 211 <para> 212 Finally, there are different header include conventions. Again, pick one 213 and stick to it. I personally use indifferently any of the two, depending 214 on the codebase I work on: the rule, as always, is consistency. 215 <itemizedlist> 216 <listitem><para> 217 Some people add at the top of their headers a number of #include 218 directives to pull in all the headers needed to compile client 219 code. This allows client code to simply #include "maman-bar.h". 220 </para></listitem> 221 <listitem><para> 222 Other do not #include anything and expect the client to #include 223 themselves the headers they need before including your header. This 224 speeds up compilation because it minimizes the amount of 225 pre-processor work. This can be used in conjunction with the 226 re-declaration of certain unused types in the client code to 227 minimize compile-time dependencies and thus speed up compilation. 228 </para></listitem> 229 </itemizedlist> 230 </para> 231 232 </sect1> 233 234 <sect1 id="howto-gobject-code"> 235 <title>Boilerplate code</title> 236 237 <para> 238 In your code, the first step is to #include the needed headers: depending 239 on your header include strategy, this can be as simple as 240 <literal>#include "maman-bar.h"</literal> or as complicated as tens 241 of #include lines ending with <literal>#include "maman-bar.h"</literal>: 242 <programlisting> 243 /* 244 * Copyright information 245 */ 246 247 #include "maman-bar.h" 248 249 /* If you use Pimpls, include the private structure 250 * definition here. Some people create a maman-bar-private.h header 251 * which is included by the maman-bar.c file and which contains the 252 * definition for this private structure. 253 */ 254 struct _MamanBarPrivate { 255 int member_1; 256 /* stuff */ 257 }; 258 259 /* 260 * forward definitions 261 */ 262 </programlisting> 263 </para> 264 265 <para> 266 Call the <function>G_DEFINE_TYPE</function> macro using the name 267 of the type, the prefix of the functions and the parent GType to 268 reduce the amount of boilerplate needed. This macro will: 269 270 <itemizedlist> 271 <listitem><simpara>implement the <function>maman_bar_get_type</function> 272 function</simpara></listitem> 273 <listitem><simpara>define a parent class pointer accessible from 274 the whole .c file</simpara></listitem> 275 </itemizedlist> 276 277 <programlisting> 278 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT); 279 </programlisting> 280 </para> 281 282 <para> 283 It is also possible to use the 284 <function>G_DEFINE_TYPE_WITH_CODE</function> macro to control the 285 get_type function implementation - for instance, to add a call to 286 <function>G_IMPLEMENT_INTERFACE</function> macro which will 287 call the <function>g_type_implement_interface</function> function. 288 </para> 289 </sect1> 290 291 <sect1 id="howto-gobject-construction"> 292 <title>Object Construction</title> 293 294 <para> 295 People often get confused when trying to construct their GObjects because of the 296 sheer number of different ways to hook into the objects's construction process: it is 297 difficult to figure which is the <emphasis>correct</emphasis>, recommended way. 298 </para> 299 300 <para> 301 <xref linkend="gobject-construction-table"/> shows what user-provided functions 302 are invoked during object instantiation and in which order they are invoked. 303 A user looking for the equivalent of the simple C++ constructor function should use 304 the instance_init method. It will be invoked after all the parent's instance_init 305 functions have been invoked. It cannot take arbitrary construction parameters 306 (as in C++) but if your object needs arbitrary parameters to complete initialization, 307 you can use construction properties. 308 </para> 309 310 <para> 311 Construction properties will be set only after all instance_init functions have run. 312 No object reference will be returned to the client of <function><link linkend="g-object-new">g_object_new</link></function> 313 until all the construction properties have been set. 314 </para> 315 316 <para> 317 As such, I would recommend writing the following code first: 318 <programlisting> 319 static void 320 maman_bar_init (MamanBar *self) 321 { 322 self->priv = MAMAN_BAR_GET_PRIVATE (self); 323 324 /* initialize all public and private members to reasonable default values. */ 325 326 /* If you need specific construction properties to complete initialization, 327 * delay initialization completion until the property is set. 328 */ 329 } 330 </programlisting> 331 </para> 332 333 <para> 334 Now, if you need special construction properties, install the properties in the class_init function, 335 override the set and get methods and implement the get and set methods as described in 336 <xref linkend="gobject-properties"/>. Make sure that these properties use a construct only 337 <type><link linkend="GParamSpec">GParamSpec</link></type> by setting the param spec's flag field to G_PARAM_CONSTRUCT_ONLY: this helps 338 GType ensure that these properties are not set again later by malicious user code. 339 <programlisting> 340 static void 341 bar_class_init (MamanBarClass *klass) 342 { 343 GObjectClass *gobject_class = G_OBJECT_CLASS (klass); 344 GParamSpec *maman_param_spec; 345 346 gobject_class->set_property = bar_set_property; 347 gobject_class->get_property = bar_get_property; 348 349 maman_param_spec = g_param_spec_string ("maman", 350 "Maman construct prop", 351 "Set maman's name", 352 "no-name-set" /* default value */, 353 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE); 354 g_object_class_install_property (gobject_class, 355 PROP_MAMAN, 356 maman_param_spec); 357 } 358 </programlisting> 359 If you need this, make sure you can build and run code similar to the code shown above. Make sure 360 your construct properties can set correctly during construction, make sure you cannot set them 361 afterwards and make sure that if your users do not call <function><link linkend="g-object-new">g_object_new</link></function> 362 with the required construction properties, these will be initialized with the default values. 363 </para> 364 365 <para> 366 I consider good taste to halt program execution if a construction property is set its 367 default value. This allows you to catch client code which does not give a reasonable 368 value to the construction properties. Of course, you are free to disagree but you 369 should have a good reason to do so. 370 </para> 371 372 <para> 373 Some people sometimes need to construct their object but only after 374 the construction properties have been set. This is possible through 375 the use of the constructor class method as described in 376 <xref linkend="gobject-instantiation"/> or, more simply, using 377 the constructed class method available since GLib 2.12. 378 </para> 379 </sect1> 380 381 <sect1 id="howto-gobject-destruction"> 382 <title>Object Destruction</title> 383 384 <para> 385 Again, it is often difficult to figure out which mechanism to use to 386 hook into the object's destruction process: when the last 387 <function><link linkend="g-object-unref">g_object_unref</link></function> 388 function call is made, a lot of things happen as described in 389 <xref linkend="gobject-destruction-table"/>. 390 </para> 391 392 <para> 393 The destruction process of your object might be split in two different 394 phases: dispose and the finalize. 395 <programlisting> 396 #define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate)) 397 398 struct _MamanBarPrivate 399 { 400 GObject *an_object; 401 402 gchar *a_string; 403 }; 404 405 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT); 406 407 static void 408 maman_bar_dispose (GObject *gobject) 409 { 410 MamanBar *self = MAMAN_BAR (gobject); 411 412 /* 413 * In dispose, you are supposed to free all types referenced from this 414 * object which might themselves hold a reference to self. Generally, 415 * the most simple solution is to unref all members on which you own a 416 * reference. 417 */ 418 419 /* dispose might be called multiple times, so we must guard against 420 * calling g_object_unref() on an invalid GObject. 421 */ 422 if (self->priv->an_object) 423 { 424 g_object_unref (self->priv->an_object); 425 426 self->priv->an_object = NULL; 427 } 428 429 /* Chain up to the parent class */ 430 G_OBJECT_CLASS (maman_bar_parent_class)->dispose (gobject); 431 } 432 433 static void 434 maman_bar_finalize (GObject *gobject) 435 { 436 MamanBar *self = MAMAN_BAR (gobject); 437 438 g_free (self->priv->a_string); 439 440 /* Chain up to the parent class */ 441 G_OBJECT_CLASS (maman_bar_parent_class)->finalize (gobject); 442 } 443 444 static void 445 maman_bar_class_init (MamanBarClass *klass) 446 { 447 GObjectClass *gobject_class = G_OBJECT_CLASS (klass); 448 449 gobject_class->dispose = maman_bar_dispose; 450 gobject_class->finalize = maman_bar_finalize; 451 452 g_type_class_add_private (klass, sizeof (MamanBarPrivate)); 453 } 454 455 static void 456 maman_bar_init (MamanBar *self); 457 { 458 self->priv = MAMAN_BAR_GET_PRIVATE (self); 459 460 self->priv->an_object = g_object_new (MAMAN_TYPE_BAZ, NULL); 461 self->priv->a_string = g_strdup ("Maman"); 462 } 463 </programlisting> 464 </para> 465 466 <para> 467 Add similar code to your GObject, make sure the code still builds 468 and runs: dispose and finalize must be called during the last unref. 469 </para> 470 471 <para> 472 It is possible that object methods might be invoked after dispose is 473 run and before finalize runs. GObject does not consider this to be a 474 program error: you must gracefully detect this and neither crash nor 475 warn the user. 476 </para> 477 </sect1> 478 479 <sect1 id="howto-gobject-methods"> 480 <title>Object methods</title> 481 482 <para> 483 Just as with C++, there are many different ways to define object 484 methods and extend them: the following list and sections draw on 485 C++ vocabulary. (Readers are expected to know basic C++ buzzwords. 486 Those who have not had to write C++ code recently can refer to e.g. 487 <ulink url="http://www.cplusplus.com/doc/tutorial/"/> to refresh 488 their memories.) 489 <itemizedlist> 490 <listitem><para> 491 non-virtual public methods, 492 </para></listitem> 493 <listitem><para> 494 virtual public methods and 495 </para></listitem> 496 <listitem><para> 497 virtual private methods 498 </para></listitem> 499 </itemizedlist> 500 </para> 501 502 <sect2> 503 <title>Non-virtual public methods</title> 504 505 <para> 506 These are the simplest: you want to provide a simple method which 507 can act on your object. All you need to do is to provide a function 508 prototype in the header and an implementation of that prototype 509 in the source file. 510 <programlisting> 511 /* declaration in the header. */ 512 void maman_bar_do_action (MamanBar *self, /* parameters */); 513 514 /* implementation in the source file */ 515 void 516 maman_bar_do_action (MamanBar *self, /* parameters */) 517 { 518 g_return_if_fail (MAMAN_IS_BAR (self)); 519 520 /* do stuff here. */ 521 } 522 </programlisting> 523 </para> 524 525 <para>There is really nothing scary about this.</para> 526 </sect2> 527 528 <sect2> 529 <title>Virtual public methods</title> 530 531 <para> 532 This is the preferred way to create polymorphic GObjects. All you 533 need to do is to define the common method and its class function in 534 the public header, implement the common method in the source file 535 and re-implement the class function in each object which inherits 536 from you. 537 <programlisting> 538 /* declaration in maman-bar.h. */ 539 struct _MamanBarClass 540 { 541 GObjectClass parent_class; 542 543 /* stuff */ 544 void (*do_action) (MamanBar *self, /* parameters */); 545 }; 546 547 void maman_bar_do_action (MamanBar *self, /* parameters */); 548 549 /* implementation in maman-bar.c */ 550 void 551 maman_bar_do_action (MamanBar *self, /* parameters */) 552 { 553 g_return_if_fail (MAMAN_IS_BAR (self)); 554 555 MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */); 556 } 557 </programlisting> 558 The code above simply redirects the do_action call to the relevant 559 class function. Some users, concerned about performance, do not 560 provide the <function>maman_bar_do_action</function> wrapper function 561 and require users to dereference the class pointer themselves. This 562 is not such a great idea in terms of encapsulation and makes it 563 difficult to change the object's implementation afterwards, should 564 this be needed. 565 </para> 566 567 <para> 568 Other users, also concerned by performance issues, declare 569 the <function>maman_bar_do_action</function> function inline in the 570 header file. This, however, makes it difficult to change the 571 object's implementation later (although easier than requiring users 572 to directly dereference the class function) and is often difficult 573 to write in a portable way (the <emphasis>inline</emphasis> keyword 574 is part of the C99 standard but not every compiler supports it). 575 </para> 576 577 <para> 578 In doubt, unless a user shows you hard numbers about the performance 579 cost of the function call, just implement <function>maman_bar_do_action</function> 580 in the source file. 581 </para> 582 583 <para> 584 Please, note that it is possible for you to provide a default 585 implementation for this class method in the object's 586 <function>class_init</function> function: initialize the 587 klass->do_action field to a pointer to the actual implementation. 588 You can also make this class method pure virtual by initializing 589 the klass->do_action field to NULL: 590 <programlisting> 591 static void 592 maman_bar_real_do_action_two (MamanBar *self, /* parameters */) 593 { 594 /* Default implementation for the virtual method. */ 595 } 596 597 static void 598 maman_bar_class_init (BarClass *klass) 599 { 600 /* pure virtual method: mandates implementation in children. */ 601 klass->do_action_one = NULL; 602 603 /* merely virtual method. */ 604 klass->do_action_two = maman_bar_real_do_action_two; 605 } 606 607 void 608 maman_bar_do_action_one (MamanBar *self, /* parameters */) 609 { 610 g_return_if_fail (MAMAN_IS_BAR (self)); 611 612 MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */); 613 } 614 615 void 616 maman_bar_do_action_two (MamanBar *self, /* parameters */) 617 { 618 g_return_if_fail (MAMAN_IS_BAR (self)); 619 620 MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */); 621 } 622 </programlisting> 623 </para> 624 </sect2> 625 626 <sect2> 627 <title>Virtual private Methods</title> 628 629 <para> 630 These are very similar to Virtual Public methods. They just don't 631 have a public function to call the function directly. The header 632 file contains only a declaration of the class function: 633 <programlisting> 634 /* declaration in maman-bar.h. */ 635 struct _MamanBarClass 636 { 637 GObjectClass parent; 638 639 /* stuff */ 640 void (* helper_do_specific_action) (MamanBar *self, /* parameters */); 641 }; 642 643 void maman_bar_do_any_action (MamanBar *self, /* parameters */); 644 </programlisting> 645 These class functions are often used to delegate part of the job 646 to child classes: 647 <programlisting> 648 /* this accessor function is static: it is not exported outside of this file. */ 649 static void 650 maman_bar_do_specific_action (MamanBar *self, /* parameters */) 651 { 652 MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */); 653 } 654 655 void 656 maman_bar_do_any_action (MamanBar *self, /* parameters */) 657 { 658 /* random code here */ 659 660 /* 661 * Try to execute the requested action. Maybe the requested action 662 * cannot be implemented here. So, we delegate its implementation 663 * to the child class: 664 */ 665 maman_bar_do_specific_action (self, /* parameters */); 666 667 /* other random code here */ 668 } 669 </programlisting> 670 </para> 671 672 <para> 673 Again, it is possible to provide a default implementation for this 674 private virtual class function: 675 <programlisting> 676 static void 677 maman_bar_class_init (MamanBarClass *klass) 678 { 679 /* pure virtual method: mandates implementation in children. */ 680 klass->do_specific_action_one = NULL; 681 682 /* merely virtual method. */ 683 klass->do_specific_action_two = maman_bar_real_do_specific_action_two; 684 } 685 </programlisting> 686 </para> 687 688 <para> 689 Children can then implement the subclass with code such as: 690 <programlisting> 691 static void 692 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass) 693 { 694 MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass); 695 696 /* implement pure virtual class function. */ 697 bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one; 698 } 699 </programlisting> 700 </para> 701 </sect2> 702 </sect1> 703 704 <sect1 id="howto-gobject-chainup"> 705 <title>Chaining up</title> 706 707 <para>Chaining up is often loosely defined by the following set of 708 conditions: 709 <itemizedlist> 710 <listitem><para>Parent class A defines a public virtual method named <function>foo</function> and 711 provides a default implementation.</para></listitem> 712 <listitem><para>Child class B re-implements method <function>foo</function>.</para></listitem> 713 <listitem><para>In the method B::foo, the child class B calls its parent class method A::foo.</para></listitem> 714 </itemizedlist> 715 There are many uses to this idiom: 716 <itemizedlist> 717 <listitem><para>You need to change the behaviour of a class without modifying its code. You create 718 a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour 719 slightly and chain up to ensure that the previous behaviour is not really modified, just extended. 720 </para></listitem> 721 <listitem><para>You are lazy, you have access to the source code of the parent class but you don't want 722 to modify it to add method calls to new specialized method calls: it is faster to hack the child class 723 to chain up than to modify the parent to call down.</para></listitem> 724 <listitem><para>You need to implement the Chain Of Responsibility pattern: each object of the inheritance 725 tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that 726 they each handler is run in turn.</para></listitem> 727 </itemizedlist> 728 I am personally not really convinced any of the last two uses are really a good idea but since this 729 programming idiom is often used, this section attempts to explain how to implement it. 730 </para> 731 732 <para> 733 To explicitly chain up to the implementation of the virtual method in the parent class, 734 you first need a handle to the original parent class structure. This pointer can then be used to 735 access the original class function pointer and invoke it directly. 736 <footnote> 737 <para> 738 The <emphasis>original</emphasis> adjective used in this sentence is not innocuous. To fully 739 understand its meaning, you need to recall how class structures are initialized: for each object type, 740 the class structure associated to this object is created by first copying the class structure of its 741 parent type (a simple <function>memcpy</function>) and then by invoking the class_init callback on 742 the resulting class structure. Since the class_init callback is responsible for overwriting the class structure 743 with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class 744 structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent 745 class. 746 </para> 747 </footnote> 748 </para> 749 750 <para>The function <function><link linkend="g-type-class-peek-parent">g_type_class_peek_parent</link></function> is used to access the original parent 751 class structure. Its input is a pointer to the class of the derived object and it returns a pointer 752 to the original parent class structure. The code below shows how you could use it: 753 <programlisting> 754 static void 755 b_method_to_call (B *obj, int a) 756 { 757 BClass *klass; 758 AClass *parent_class; 759 760 klass = B_GET_CLASS (obj); 761 parent_class = g_type_class_peek_parent (klass); 762 763 /* do stuff before chain up */ 764 765 parent_class->method_to_call (obj, a); 766 767 /* do stuff after chain up */ 768 } 769 </programlisting> 770 </para> 771 772 </sect1> 773 774 </chapter> 775 <!-- End Howto GObject --> 776 777 <chapter id="howto-interface"> 778 <title>How to define and implement interfaces</title> 779 780 <sect1 id="howto-interface-define"> 781 <title>How to define interfaces</title> 782 783 <para> 784 The bulk of interface definition has already been shown in <xref linkend="gtype-non-instantiable-classed"/> 785 but I feel it is needed to show exactly how to create an interface. 786 </para> 787 788 <para> 789 As above, the first step is to get the header right: 790 <programlisting> 791 #ifndef __MAMAN_IBAZ_H__ 792 #define __MAMAN_IBAZ_H__ 793 794 #include <glib-object.h> 795 796 #define MAMAN_TYPE_IBAZ (maman_ibaz_get_type ()) 797 #define MAMAN_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz)) 798 #define MAMAN_IS_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ)) 799 #define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface)) 800 801 802 typedef struct _MamanIbaz MamanIbaz; /* dummy object */ 803 typedef struct _MamanIbazInterface MamanIbazInterface; 804 805 struct _MamanIbazInterface 806 { 807 GTypeInterface parent_iface; 808 809 void (*do_action) (MamanIbaz *self); 810 }; 811 812 GType maman_ibaz_get_type (void); 813 814 void maman_ibaz_do_action (MamanIbaz *self); 815 816 #endif /* __MAMAN_IBAZ_H__ */ 817 </programlisting> 818 This code is the same as the code for a normal <type><link linkend="GType">GType</link></type> 819 which derives from a <type><link linkend="GObject">GObject</link></type> except for a few details: 820 <itemizedlist> 821 <listitem><para> 822 The <function>_GET_CLASS</function> macro is called <function>_GET_INTERFACE</function> 823 and not implemented with <function><link linkend="G_TYPE_INSTANCE_GET_CLASS">G_TYPE_INSTANCE_GET_CLASS</link></function> 824 but with <function><link linkend="G_TYPE_INSTANCE_GET_INTERFACE">G_TYPE_INSTANCE_GET_INTERFACE</link></function>. 825 </para></listitem> 826 <listitem><para> 827 The instance type, <type>MamanIbaz</type> is not fully defined: it is 828 used merely as an abstract type which represents an instance of 829 whatever object which implements the interface. 830 </para></listitem> 831 <listitem><para> 832 The parent of the <type>MamanIbazInterface</type> is not 833 <type>GObjectClass</type> but <type>GTypeInterface</type>. 834 </para></listitem> 835 </itemizedlist> 836 </para> 837 838 <para> 839 The implementation of the <type>MamanIbaz</type> type itself is trivial: 840 <itemizedlist> 841 <listitem><para><function>maman_ibaz_get_type</function> registers the 842 type in the type system. 843 </para></listitem> 844 <listitem><para><function>maman_ibaz_base_init</function> is expected 845 to register the interface's signals if there are any (we will see a bit 846 (later how to use them). Make sure to use a static local boolean variable 847 to make sure not to run the initialization code twice (as described in 848 <xref linkend="gtype-non-instantiable-classed-init"/>, 849 <function>base_init</function> is run once for each interface implementation 850 instantiation)</para></listitem> 851 <listitem><para><function>maman_ibaz_do_action</function> dereferences 852 the class structure to access its associated class function and calls it. 853 </para></listitem> 854 </itemizedlist> 855 <programlisting> 856 static void 857 maman_ibaz_base_init (gpointer g_class) 858 { 859 static gboolean is_initialized = FALSE; 860 861 if (!is_initialized) 862 { 863 /* add properties and signals to the interface here */ 864 865 is_initialized = TRUE; 866 } 867 } 868 869 GType 870 maman_ibaz_get_type (void) 871 { 872 static GType iface_type = 0; 873 if (iface_type == 0) 874 { 875 static const GTypeInfo info = { 876 sizeof (MamanIbazInterface), 877 maman_ibaz_base_init, /* base_init */ 878 NULL, /* base_finalize */ 879 }; 880 881 iface_type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz", 882 &info, 0); 883 } 884 885 return iface_type; 886 } 887 888 void 889 maman_ibaz_do_action (MamanIbaz *self) 890 { 891 g_return_if_fail (MAMAN_IS_IBAZ (self)); 892 893 MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self); 894 } 895 </programlisting> 896 </para> 897 </sect1> 898 899 <sect1 id="howto-interface-implement"> 900 <title>How To define implement an Interface?</title> 901 902 <para> 903 Once the interface is defined, implementing it is rather trivial. 904 </para> 905 906 <para> 907 The first step is to define a normal GObject class, like: 908 <programlisting> 909 #ifndef __MAMAN_BAZ_H__ 910 #define __MAMAN_BAZ_H__ 911 912 #include <glib-object.h> 913 914 #define MAMAN_TYPE_BAZ (maman_baz_get_type ()) 915 #define MAMAN_BAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz)) 916 #define MAMAN_IS_BAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ)) 917 #define MAMAN_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAZ, MamanbazClass)) 918 #define MAMAN_IS_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAZ)) 919 #define MAMAN_BAZ_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAZ, MamanbazClass)) 920 921 922 typedef struct _MamanBaz MamanBaz; 923 typedef struct _MamanBazClass MamanBazClass; 924 925 struct _MamanBaz 926 { 927 GObject parent_instance; 928 929 int instance_member; 930 }; 931 932 struct _MamanBazClass 933 { 934 GObjectClass parent_class; 935 }; 936 937 GType maman_baz_get_type (void); 938 939 #endif /* __MAMAN_BAZ_H__ */ 940 </programlisting> 941 There is clearly nothing specifically weird or scary about this header: 942 it does not define any weird API or derives from a weird type. 943 </para> 944 945 <para> 946 The second step is to implement <type>MamanBaz</type> by defining 947 its GType. Instead of using <function>G_DEFINE_TYPE</function> we 948 use <function>G_DEFINE_TYPE_WITH_CODE</function> and the 949 <function>G_IMPLEMENT_INTERFACE</function> macros. 950 <programlisting> 951 static void maman_ibaz_interface_init (MamanIbazInterface *iface); 952 953 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT, 954 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ, 955 maman_ibaz_interface_init)); 956 </programlisting> 957 This definition is very much like all the similar functions we looked 958 at previously. The only interface-specific code present here is the call 959 to <function>G_IMPLEMENT_INTERFACE</function>. 960 </para> 961 962 <note><para>Classes can implement multiple interfaces by using multiple 963 calls to <function>G_IMPLEMENT_INTERFACE</function> inside the call 964 to <function>G_DEFINE_TYPE_WITH_CODE</function>.</para></note> 965 966 <para> 967 <function>maman_baz_interface_init</function>, the interface 968 initialization function: inside it every virtual method of the interface 969 must be assigned to its implementation: 970 <programlisting> 971 static void 972 maman_baz_do_action (MamanBaz *self) 973 { 974 g_print ("Baz implementation of IBaz interface Action: 0x%x.\n", 975 self->instance_member); 976 } 977 978 static void 979 maman_ibaz_interface_init (MamanIbazInterface *iface) 980 { 981 iface->do_action = baz_do_action; 982 } 983 984 static void 985 maman_baz_init (MamanBaz *self) 986 { 987 MamanBaz *self = MAMAN_BAZ (instance); 988 self->instance_member = 0xdeadbeaf; 989 } 990 </programlisting> 991 </para> 992 993 </sect1> 994 995 <sect1> 996 <title>Interface definition prerequisites</title> 997 998 <para> 999 To specify that an interface requires the presence of other interfaces 1000 when implemented, GObject introduces the concept of 1001 <emphasis>prerequisites</emphasis>: it is possible to associate 1002 a list of prerequisite interfaces to an interface. For example, if 1003 object A wishes to implement interface I1, and if interface I1 has a 1004 prerequisite on interface I2, A has to implement both I1 and I2. 1005 </para> 1006 1007 <para> 1008 The mechanism described above is, in practice, very similar to 1009 Java's interface I1 extends interface I2. The example below shows 1010 the GObject equivalent: 1011 <programlisting> 1012 /* inside the GType function of the MamanIbar interface */ 1013 type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &info, 0); 1014 1015 /* Make the MamanIbar interface require MamanIbaz interface. */ 1016 g_type_interface_add_prerequisite (type, MAMAN_TYPE_IBAZ); 1017 </programlisting> 1018 The code shown above adds the MamanIbaz interface to the list of 1019 prerequisites of MamanIbar while the code below shows how an 1020 implementation can implement both interfaces and register their 1021 implementations: 1022 <programlisting> 1023 static void 1024 maman_ibar_do_another_action (MamanIbar *ibar) 1025 { 1026 MamanBar *self = MAMAN_BAR (ibar); 1027 1028 g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n", 1029 self->instance_member); 1030 } 1031 1032 static void 1033 maman_ibar_interface_init (MamanIbarInterface *iface) 1034 { 1035 iface->do_another_action = maman_ibar_do_another_action; 1036 } 1037 1038 static void 1039 maman_ibaz_do_action (MamanIbaz *ibaz) 1040 { 1041 MamanBar *self = MAMAN_BAR (ibaz); 1042 1043 g_print ("Bar implementation of IBaz interface Action: 0x%x.\n", 1044 self->instance_member); 1045 } 1046 1047 static void 1048 maman_ibaz_interface_init (MamanIbazInterface *iface) 1049 { 1050 iface->do_action = maman_ibaz_do_action; 1051 } 1052 1053 static void 1054 maman_bar_class_init (MamanBarClass *klass) 1055 { 1056 1057 } 1058 1059 static void 1060 maman_bar_init (MamanBar *self) 1061 { 1062 self->instance_member = 0x666; 1063 } 1064 1065 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT, 1066 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ, 1067 maman_ibaz_interface_init) 1068 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAR, 1069 maman_ibar_interface_init)); 1070 </programlisting> 1071 It is very important to notice that the order in which interface 1072 implementations are added to the main object is not random: 1073 <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function>, 1074 which is called by <function>G_IMPLEMENT_INTERFACE</function>, must be 1075 invoked first on the interfaces which have no prerequisites and then on 1076 the others. 1077 </para> 1078 </sect1> 1079 1080 <sect1 id="howto-interface-properties"> 1081 <title>Interface Properties</title> 1082 1083 <para> 1084 Starting from version 2.4 of GLib, GObject interfaces can also have 1085 properties. Declaration of the interface properties is similar to 1086 declaring the properties of ordinary GObject types as explained in 1087 <xref linkend="gobject-properties"/>, 1088 except that <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function> is used to 1089 declare the properties instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>. 1090 </para> 1091 1092 <para> 1093 To include a property named 'name' of type <type>string</type> in the 1094 <type>maman_ibaz</type> interface example code above, we only need to 1095 add one 1096 <footnote> 1097 <para> 1098 That really is one line extended to six for the sake of clarity 1099 </para> 1100 </footnote> 1101 line in the <function>maman_ibaz_base_init</function> 1102 <footnote> 1103 <para> 1104 The <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function> 1105 can also be called from <function>class_init</function> but it must 1106 not be called after that point. 1107 </para> 1108 </footnote> 1109 as shown below: 1110 <programlisting> 1111 static void 1112 maman_ibaz_base_init (gpointer g_iface) 1113 { 1114 static gboolean is_initialized = FALSE; 1115 1116 if (!is_initialized) 1117 { 1118 g_object_interface_install_property (g_iface, 1119 g_param_spec_string ("name", 1120 "Name", 1121 "Name of the MamanIbaz", 1122 "maman", 1123 G_PARAM_READWRITE)); 1124 is_initialized = TRUE; 1125 } 1126 } 1127 </programlisting> 1128 </para> 1129 1130 <para> 1131 One point worth noting is that the declared property wasn't assigned an 1132 integer ID. The reason being that integer IDs of properties are used 1133 only inside the get and set methods and since interfaces do not 1134 implement properties, there is no need to assign integer IDs to 1135 interface properties. 1136 </para> 1137 1138 <para> 1139 An implementation shall declare and define it's properties in the usual 1140 way as explained in <xref linkend="gobject-properties"/>, except for one 1141 small change: it must declare the properties of the interface it 1142 implements using <function><link linkend="g-object-class-override-property">g_object_class_override_property</link></function> 1143 instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>. 1144 The following code snippet shows the modifications needed in the 1145 <type>MamanBaz</type> declaration and implementation above: 1146 <programlisting> 1147 1148 struct _MamanBaz 1149 { 1150 GObject parent_instance; 1151 1152 gint instance_member; 1153 gchar *name; 1154 }; 1155 1156 enum 1157 { 1158 PROP_0, 1159 1160 PROP_NAME 1161 }; 1162 1163 static void 1164 maman_baz_set_property (GObject *object, 1165 guint property_id, 1166 const GValue *value, 1167 GParamSpec *pspec) 1168 { 1169 MamanBaz *baz = MAMAN_BAZ (object); 1170 GObject *obj; 1171 1172 switch (prop_id) 1173 { 1174 case ARG_NAME: 1175 g_free (baz->name); 1176 baz->name = g_value_dup_string (value); 1177 break; 1178 1179 default: 1180 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); 1181 break; 1182 } 1183 } 1184 1185 static void 1186 maman_baz_get_property (GObject *object, 1187 guint prop_id, 1188 GValue *value, 1189 GParamSpec *pspec) 1190 { 1191 MamanBaz *baz = MAMAN_BAZ (object); 1192 1193 switch (prop_id) 1194 { 1195 case ARG_NAME: 1196 g_value_set_string (value, baz->name); 1197 break; 1198 1199 default: 1200 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); 1201 break; 1202 } 1203 } 1204 1205 static void 1206 maman_baz_class_init (MamanBazClass *klass) 1207 { 1208 GObjectClass *gobject_class = G_OBJECT_CLASS (klass); 1209 1210 gobject_class->set_property = maman_baz_set_property; 1211 gobject_class->get_property = maman_baz_get_property; 1212 1213 g_object_class_override_property (gobject_class, PROP_NAME, "name"); 1214 } 1215 1216 </programlisting> 1217 </para> 1218 1219 </sect1> 1220 </chapter> 1221 <!-- End Howto Interfaces --> 1222 1223 <chapter id="howto-signals"> 1224 <title>How to create and use signals</title> 1225 1226 <para> 1227 The signal system which was built in GType is pretty complex and 1228 flexible: it is possible for its users to connect at runtime any 1229 number of callbacks (implemented in any language for which a binding 1230 exists) 1231 <footnote> 1232 <para>A Python callback can be connected to any signal on any 1233 C-based GObject. 1234 </para> 1235 </footnote> 1236 to any signal and to stop the emission of any signal at any 1237 state of the signal emission process. This flexibility makes it 1238 possible to use GSignal for much more than just emit signals which 1239 can be received by numerous clients. 1240 </para> 1241 1242 <sect1 id="howto-simple-signals"> 1243 <title>Simple use of signals</title> 1244 1245 <para> 1246 The most basic use of signals is to implement simple event 1247 notification: for example, if we have a MamanFile object, and 1248 if this object has a write method, we might wish to be notified 1249 whenever someone has changed something via our MamanFile instance. 1250 The code below shows how the user can connect a callback to the 1251 "changed" signal. 1252 <programlisting> 1253 file = g_object_new (MAMAN_FILE_TYPE, NULL); 1254 1255 g_signal_connect (file, "changed", G_CALLBACK (changed_event), NULL); 1256 1257 maman_file_write (file, buffer, strlen (buffer)); 1258 </programlisting> 1259 </para> 1260 1261 <para> 1262 The <type>MamanFile</type> signal is registered in the class_init 1263 function: 1264 <programlisting> 1265 file_signals[CHANGED] = 1266 g_signal_newv ("changed", 1267 G_TYPE_FROM_CLASS (gobject_class), 1268 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, 1269 NULL /* closure */, 1270 NULL /* accumulator */, 1271 NULL /* accumulator data */, 1272 g_cclosure_marshal_VOID__VOID, 1273 G_TYPE_NONE /* return_type */, 1274 0 /* n_params */, 1275 NULL /* param_types */); 1276 </programlisting> 1277 and the signal is emitted in <function>maman_file_write</function>: 1278 <programlisting> 1279 void 1280 maman_file_write (MamanFile *self, 1281 const guchar *buffer, 1282 gssize size) 1283 { 1284 /* First write data. */ 1285 1286 /* Then, notify user of data written. */ 1287 g_signal_emit (self, file_signals[CHANGED], 0 /* details */); 1288 } 1289 </programlisting> 1290 As shown above, you can safely set the details parameter to zero if 1291 you do not know what it can be used for. For a discussion of what you 1292 could used it for, see <xref linkend="signal-detail"/> 1293 </para> 1294 1295 <para> 1296 The signature of the signal handler in the above example is defined as 1297 <function>g_cclosure_marshal_VOID__VOID</function>. Its name follows 1298 a simple convention which encodes the function parameter and return value 1299 types in the function name. Specifically, the value in front of the 1300 double underscore is the type of the return value, while the value(s) 1301 after the double underscore denote the parameter types. 1302 </para> 1303 1304 <para> 1305 The header <filename>gobject/gmarshal.h</filename> defines a set of 1306 commonly needed closures that one can use. If you want to have complex 1307 marshallers for your signals you should probably use glib-genmarshal 1308 to autogenerate them from a file containing their return and 1309 parameter types. 1310 </para> 1311 </sect1> 1312 1313 <!-- 1314 this is utterly wrong and should be completely removed - or rewritten 1315 with a better example than writing a buffer using synchronous signals. 1316 1317 <sect1> 1318 <title>How to provide more flexibility to users?</title> 1319 1320 <para> 1321 The previous implementation does the job but the signal facility of 1322 GObject can be used to provide even more flexibility to this file 1323 change notification mechanism. One of the key ideas is to make the 1324 process of writing data to the file part of the signal emission 1325 process to allow users to be notified either before or after the 1326 data is written to the file. 1327 </para> 1328 1329 <para> 1330 To integrate the process of writing the data to the file into the 1331 signal emission mechanism, we can register a default class closure 1332 for this signal which will be invoked during the signal emission, 1333 just like any other user-connected signal handler. 1334 </para> 1335 1336 <para> 1337 The first step to implement this idea is to change the signature of 1338 the signal: we need to pass around the buffer to write and its size. 1339 To do this, we use our own marshaller which will be generated 1340 through GLib's glib-genmarshal tool. We thus create a file named <filename>marshall.list</filename> which contains 1341 the following single line: 1342 <programlisting> 1343 VOID:POINTER,UINT 1344 </programlisting> 1345 and use the Makefile provided in <filename>sample/signal/Makefile</filename> to generate the file named 1346 <filename>maman-file-complex-marshall.c</filename>. This C file is finally included in 1347 <filename>maman-file-complex.c</filename>. 1348 </para> 1349 1350 <para> 1351 Once the marshaller is present, we register the signal and its marshaller in the class_init function 1352 of the object <type>MamanFileComplex</type> (full source for this object is included in 1353 <filename>sample/signal/maman-file-complex.{h|c}</filename>): 1354 <programlisting> 1355 GClosure *default_closure; 1356 GType param_types[2]; 1357 1358 default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler), 1359 (gpointer)0xdeadbeaf /* user_data */, 1360 NULL /* destroy_data */); 1361 1362 param_types[0] = G_TYPE_POINTER; 1363 param_types[1] = G_TYPE_UINT; 1364 klass->write_signal_id = 1365 g_signal_newv ("write", 1366 G_TYPE_FROM_CLASS (g_class), 1367 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, 1368 default_closure /* class closure */, 1369 NULL /* accumulator */, 1370 NULL /* accu_data */, 1371 maman_file_complex_VOID__POINTER_UINT, 1372 G_TYPE_NONE /* return_type */, 1373 2 /* n_params */, 1374 param_types /* param_types */); 1375 </programlisting> 1376 The code shown above first creates the closure which contains the code to complete the file write. This 1377 closure is registered as the default class_closure of the newly created signal. 1378 </para> 1379 1380 <para> 1381 Of course, you need to implement completely the code for the default closure since I just provided 1382 a skeleton: 1383 <programlisting> 1384 static void 1385 default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data) 1386 { 1387 g_assert (user_data == (gpointer)0xdeadbeaf); 1388 /* Here, we trigger the real file write. */ 1389 g_print ("default signal handler: 0x%x %u\n", buffer, size); 1390 } 1391 </programlisting> 1392 </para> 1393 1394 <para> 1395 Finally, the client code must invoke the <function>maman_file_complex_write</function> function which 1396 triggers the signal emission: 1397 <programlisting> 1398 void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size) 1399 { 1400 /* trigger event */ 1401 g_signal_emit (self, 1402 MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id, 1403 0, /* details */ 1404 buffer, size); 1405 } 1406 </programlisting> 1407 </para> 1408 1409 <para> 1410 The client code (as shown in <filename>sample/signal/test.c</filename> and below) can now connect signal handlers before 1411 and after the file write is completed: since the default signal handler which does the write itself runs during the 1412 RUN_LAST phase of the signal emission, it will run after all handlers connected with <function><link linkend="g-signal-connect">g_signal_connect</link></function> 1413 and before all handlers connected with <function><link linkend="g-signal-connect-after">g_signal_connect_after</link></function>. If you intent to write a GObject 1414 which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users 1415 have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and 1416 G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you 1417 to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and 1418 you are not reading this). 1419 </para> 1420 1421 <para> 1422 <programlisting> 1423 static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data) 1424 { 1425 g_assert (user_data == NULL); 1426 g_print ("Complex Write event before: 0x%x, %u\n", buffer, size); 1427 } 1428 1429 static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data) 1430 { 1431 g_assert (user_data == NULL); 1432 g_print ("Complex Write event after: 0x%x, %u\n", buffer, size); 1433 } 1434 1435 static void test_file_complex (void) 1436 { 1437 guint8 buffer[100]; 1438 GObject *file; 1439 1440 file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL); 1441 1442 g_signal_connect (G_OBJECT (file), "write", 1443 (GCallback)complex_write_event_before, 1444 NULL); 1445 1446 g_signal_connect_after (G_OBJECT (file), "write", 1447 (GCallback)complex_write_event_after, 1448 NULL); 1449 1450 maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50); 1451 1452 g_object_unref (G_OBJECT (file)); 1453 } 1454 </programlisting> 1455 The code above generates the following output on my machine: 1456 <programlisting> 1457 Complex Write event before: 0xbfffe280, 50 1458 default signal handler: 0xbfffe280 50 1459 Complex Write event after: 0xbfffe280, 50 1460 </programlisting> 1461 </para> 1462 1463 --> 1464 1465 <!-- 1466 this is also utterly wrong on so many levels that I don't even want 1467 to enumerate them. it's also full of completely irrelevant footnotes 1468 about personal preferences demonstrating a severe lack of whatsoever 1469 clue. the whole idea of storing the signal ids inside the Class 1470 structure is so fundamentally flawed that I'll require a frontal 1471 lobotomy just to forget I've ever seen it. 1472 1473 <sect2> 1474 <title>How most people do the same thing with less code</title> 1475 1476 <para>For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions, 1477 there is a much <emphasis>simpler</emphasis> 1478 <footnote> 1479 <para>I personally think that this method is horribly mind-twisting: it adds a new indirection 1480 which unnecessarily complicates the overall code path. However, because this method is widely used 1481 by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way 1482 in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to 1483 create a signal with a default handler than this one. Some people have tried to justify that it is done 1484 that way because it is better, faster (I am extremely doubtful about the faster bit. As a matter of fact, 1485 the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it 1486 because they copy/pasted code from code which did the same. It is probably better to leave this 1487 specific trivia to hacker legends domain... 1488 </para> 1489 </footnote> 1490 way to create a signal with a default handler than to create 1491 a closure by hand and to use the <function><link linkend="g-signal-newv">g_signal_newv</link></function>. 1492 </para> 1493 1494 <para>For example, <function><link linkend="g-signal-new">g_signal_new</link></function> can be used to create a signal which uses a default 1495 handler which is stored in the class structure of the object. More specifically, the class structure 1496 contains a function pointer which is accessed during signal emission to invoke the default handler and 1497 the user is expected to provide to <function><link linkend="g-signal-new">g_signal_new</link></function> the offset from the start of the 1498 class structure to the function pointer. 1499 <footnote> 1500 <para>I would like to point out here that the reason why the default handler of a signal is named everywhere 1501 a class_closure is probably related to the fact that it used to be really a function pointer stored in 1502 the class structure. 1503 </para> 1504 </footnote> 1505 </para> 1506 1507 <para>The following code shows the declaration of the <type>MamanFileSimple</type> class structure which contains 1508 the <function>write</function> function pointer. 1509 <programlisting> 1510 struct _MamanFileSimpleClass { 1511 GObjectClass parent; 1512 1513 guint write_signal_id; 1514 1515 /* signal default handlers */ 1516 void (*write) (MamanFileSimple *self, guint8 *buffer, guint size); 1517 }; 1518 </programlisting> 1519 The <function>write</function> function pointer is initialized in the class_init function of the object 1520 to <function>default_write_signal_handler</function>: 1521 <programlisting> 1522 static void 1523 maman_file_simple_class_init (gpointer g_class, 1524 gpointer g_class_data) 1525 { 1526 GObjectClass *gobject_class = G_OBJECT_CLASS (g_class); 1527 MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class); 1528 1529 klass->write = default_write_signal_handler; 1530 </programlisting> 1531 Finally, the signal is created with <function><link linkend="g-signal-new">g_signal_new</link></function> in the same class_init function: 1532 <programlisting> 1533 klass->write_signal_id = 1534 g_signal_new ("write", 1535 G_TYPE_FROM_CLASS (g_class), 1536 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, 1537 G_STRUCT_OFFSET (MamanFileSimpleClass, write), 1538 NULL /* accumulator */, 1539 NULL /* accu_data */, 1540 maman_file_complex_VOID__POINTER_UINT, 1541 G_TYPE_NONE /* return_type */, 1542 2 /* n_params */, 1543 G_TYPE_POINTER, 1544 G_TYPE_UINT); 1545 </programlisting> 1546 Of note, here, is the 4th argument to the function: it is an integer calculated by the <function><link linkend="G-STRUCT-OFFSET">G_STRUCT_OFFSET</link></function> 1547 macro which indicates the offset of the member <emphasis>write</emphasis> from the start of the 1548 <type>MamanFileSimpleClass</type> class structure. 1549 <footnote> 1550 <para>GSignal uses this offset to create a special wrapper closure 1551 which first retrieves the target function pointer before calling it. 1552 </para> 1553 </footnote> 1554 </para> 1555 1556 <para> 1557 While the complete code for this type of default handler looks less cluttered as shown in 1558 <filename>sample/signal/maman-file-simple.{h|c}</filename>, it contains numerous subtleties. 1559 The main subtle point which everyone must be aware of is that the signature of the default 1560 handler created that way does not have a user_data argument: 1561 <function>default_write_signal_handler</function> is different in 1562 <filename>sample/signal/maman-file-complex.c</filename> and in 1563 <filename>sample/signal/maman-file-simple.c</filename>. 1564 </para> 1565 1566 <para>If you have doubts about which method to use, I would advise you to use the second one which 1567 involves <function><link linkend="g-signal-new">g_signal_new</link></function> rather than <function><link linkend="g-signal-newv">g_signal_newv</link></function>: 1568 it is better to write code which looks like the vast majority of other GTK+/GObject code than to 1569 do it your own way. However, now, you know why. 1570 </para> 1571 1572 </sect2> 1573 1574 </sect1> 1575 --> 1576 1577 <!-- 1578 yet another pointless section. if we are scared of possible abuses 1579 from the users then we should not be mentioning it inside a tutorial 1580 for beginners. but, obviously, there's nothing to be afraid of - it's 1581 just that this section must be completely reworded. 1582 1583 <sect1> 1584 <title>How users can abuse signals (and why some think it is good)</title> 1585 1586 <para>Now that you know how to create signals to which the users can connect easily and at any point in 1587 the signal emission process thanks to <function><link linkend="g-signal-connect">g_signal_connect</link></function>, 1588 <function><link linkend="g-signal-connect-after">g_signal_connect_after</link></function> and G_SIGNAL_RUN_LAST, it is time to look into how your 1589 users can and will screw you. This is also interesting to know how you too, can screw other people. 1590 This will make you feel good and eleet. 1591 </para> 1592 1593 <para> 1594 The users can: 1595 <itemizedlist> 1596 <listitem><para>stop the emission of the signal at anytime</para></listitem> 1597 <listitem><para>override the default handler of the signal if it is stored as a function 1598 pointer in the class structure (which is the preferred way to create a default signal handler, 1599 as discussed in the previous section).</para></listitem> 1600 </itemizedlist> 1601 </para> 1602 1603 <para> 1604 In both cases, the original programmer should be as careful as possible to write code which is 1605 resistant to the fact that the default handler of the signal might not able to run. This is obviously 1606 not the case in the example used in the previous sections since the write to the file depends on whether 1607 or not the default handler runs (however, this might be your goal: to allow the user to prevent the file 1608 write if he wishes to). 1609 </para> 1610 1611 <para> 1612 If all you want to do is to stop the signal emission from one of the callbacks you connected yourself, 1613 you can call <function><link linkend="g-signal-stop-by-name">g_signal_stop_by_name</link></function>. Its use is very simple which is why I won't detail 1614 it further. 1615 </para> 1616 1617 <para> 1618 If the signal's default handler is just a class function pointer, it is also possible to override 1619 it yourself from the class_init function of a type which derives from the parent. That way, when the signal 1620 is emitted, the parent class will use the function provided by the child as a signal default handler. 1621 Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal 1622 handler to ensure the integrity of the parent object. 1623 </para> 1624 1625 <para> 1626 Overriding a class method and chaining up was demonstrated in <xref linkend="howto-gobject-methods"/> 1627 which is why I won't bother to show exactly how to do it here again. 1628 </para> 1629 1630 </sect1> 1631 1632 --> 1633 1634 </chapter> 1635 1636 <!-- 1637 <sect2> 1638 <title>Warning on signal creation and default closure</title> 1639 1640 <para> 1641 Most of the existing code I have seen up to now (in both GTK+, GNOME libraries and 1642 many GTK+ and GNOME applications) using signals uses a small 1643 variation of the default handler pattern I have shown in the previous section. 1644 </para> 1645 1646 <para> 1647 Usually, the <function><link linkend="g-signal-new">g_signal_new</link></function> function is preferred over 1648 <function><link linkend="g-signal-newv">g_signal_newv</link></function>. When <function><link linkend="g-signal-new">g_signal_new</link></function> 1649 is used, the default closure is exported as a class function. For example, 1650 <filename>gobject.h</filename> contains the declaration of <type><link linkend="GObjectClass">GObjectClass</link></type> 1651 whose notify class function is the default handler for the <emphasis>notify</emphasis> 1652 signal: 1653 <programlisting> 1654 struct _GObjectClass 1655 { 1656 GTypeClass g_type_class; 1657 1658 /* class methods and other stuff. */ 1659 1660 /* signals */ 1661 void (*notify) (GObject *object, 1662 GParamSpec *pspec); 1663 }; 1664 </programlisting> 1665 </para> 1666 1667 <para> 1668 <filename>gobject.c</filename>'s <function><link linkend="g-object-do-class-init">g_object_do_class_init</link></function> function 1669 registers the <emphasis>notify</emphasis> signal and initializes this class function 1670 to NULL: 1671 <programlisting> 1672 static void 1673 g_object_do_class_init (GObjectClass *class) 1674 { 1675 1676 /* Stuff */ 1677 1678 class->notify = NULL; 1679 1680 gobject_signals[NOTIFY] = 1681 g_signal_new ("notify", 1682 G_TYPE_FROM_CLASS (class), 1683 G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS, 1684 G_STRUCT_OFFSET (GObjectClass, notify), 1685 NULL, NULL, 1686 g_cclosure_marshal_VOID__PARAM, 1687 G_TYPE_NONE, 1688 1, G_TYPE_PARAM); 1689 } 1690 </programlisting> 1691 <function><link linkend="g-signal-new">g_signal_new</link></function> creates a <type><link linkend="GClosure">GClosure</link></type> which dereferences the 1692 type's class structure to access the class function pointer and invoke it if it not NULL. The 1693 class function is ignored it is set to NULL. 1694 </para> 1695 1696 <para> 1697 To understand the reason for such a complex scheme to access the signal's default handler, 1698 you must remember the whole reason for the use of these signals. The goal here is to delegate 1699 a part of the process to the user without requiring the user to subclass the object to override 1700 one of the class functions. The alternative to subclassing, that is, the use of signals 1701 to delegate processing to the user, is, however, a bit less optimal in terms of speed: rather 1702 than just dereferencing a function pointer in a class structure, you must start the whole 1703 process of signal emission which is a bit heavyweight. 1704 </para> 1705 1706 <para> 1707 This is why some people decided to use class functions for some signal's default handlers: 1708 rather than having users connect a handler to the signal and stop the signal emission 1709 from within that handler, you just need to override the default class function which is 1710 supposedly more efficient. 1711 </para> 1712 1713 </sect2> 1714 --> 1715 1716