Signals

Connecting signal handlers
gtkmm widget classes have signal accessor methods, such as Gtk::Button::signal_clicked(), which allow you to connect your signal handler. Thanks to the flexibility of libsigc++, the callback library used by gtkmm, the signal handler can be almost any kind of function, but you will probably want to use a class method. Among GTK+ C coders, these signal handlers are often named callbacks.
Here's an example of a signal handler being connected to a signal:

#include <gtkmm/button.h>

void on_button_clicked()
{
    std::cout << "Hello World" << std::endl;
}

main()
{
    Gtk::Button button("Hello World");
    button.signal_clicked().connect(sigc::ptr_fun(&on_button_clicked));
}

There's rather a lot to think about in this (non-functional) code. First let's identify the parties involved:
The signal handler is on_button_clicked().
We're hooking it up to the Gtk::Button object called button.
When the Button emits its clicked signal, on_button_clicked() will be called.
Now let's look at the connection again:

    ...
    button.signal_clicked().connect(sigc::ptr_fun(&on_button_clicked));
    ...

Note that we don't pass a pointer to on_button_clicked() directly to the signal's connect() method. Instead, we call sigc::ptr_fun(), and pass the result to connect().
sigc::ptr_fun() generates a sigc::slot. A slot is an object which looks and feels like a function, but is actually an object. These are also known as function objects, or functors. sigc::ptr_fun() generates a slot for a standalone function or static method. sigc::mem_fun() generates a slot for a member method of a particular instance.
Here's a slightly larger example of slots in action:

void on_button_clicked();

class some_class
{
    void on_button_clicked();
};

some_class some_object;

main()
{
    Gtk::Button button;
    button.signal_clicked().connect( sigc::ptr_fun(&on_button_clicked) );
    button.signal_clicked().connect( sigc::mem_fun(some_object, &some_class::on_button_clicked) );
}

The first call to connect() is just like the one we saw last time; nothing new here.
The next is more interesting. sigc::mem_fun() is called with two arguments. The first argument is some_object, which is the object that our new slot will be pointing at. The second argument is a pointer to one of its methods. This particular version of sigc::mem_fun() creates a slot which will, when "called", call the pointed-to method of the specified object, in this case some_object.on_button_clicked().
Another thing to note about this example is that we made the call to connect() twice for the same signal object. This is perfectly fine - when the button is clicked, both signal handlers will be called.
We just told you that the button's clicked signal is expecting to call a method with no arguments. All signals have requirements like this - you can't hook a function with two arguments to a signal expecting none (unless you use an adapter, such as sigc::bind(), of course). Therefore, it's important to know what type of signal handler you'll be expected to connect to a given signal.

Writing signal handlers
To find out what type of signal handler you can connect to a signal, you can look it up in the reference documentation or the header file. Here's an example of a signal declaration you might see in the gtkmm headers:

Glib::SignalProxy1<bool, Gtk::DirectionType> signal_focus()

Other than the signal's name (focus), two things are important to note here: the number following the word SignalProxy at the beginning (1, in this case), and the types in the list (bool and Gtk::DirectionType). The number indicates how many arguments the signal handler should have; the first type, bool, is the type that the signal handler should return; and the next type, Gtk::DirectionType, is the type of this signal's first, and only, argument. By looking at the reference documentation, you can see the names of the arguments too.
The same principles apply for signals which have more arguments. Here's one with three (taken from <gtkmm/textbuffer.h>):

Glib::SignalProxy3<void, const TextBuffer::iterator&, const Glib::ustrin&, int> signal_insert();

It follows the same form. The number 3 at the end of the type's name indicates that our signal handler will need three arguments. The first type in the type list is void, so that should be our signal handler's return type. The following three types are the argument types, in order. Our signal handler's prototype could look like this:

void on_insert(const TextBuffer::iterator& pos, const Glib::ustring& text, int bytes)

Disconnecting signal handlers
Let's take another look at a Signal's connect method:

sigc::signal<void,int>::iterator signal<void,int>::connect( const sigc::slot<void,int>& );

Notice that the return value is of type sigc::signal<void,int>::iterator. This can be implicitly converted into a sigc::connection which in turn can be used to control the connection. By keeping a connection object you can disconnect its associated signal handler using the method sigc::connection::disconnect().

Overriding default signal handlers
So far we've told you to perform actions in response to button-presses and the like by handling signals. That's certainly a good way to do things, but it's not the only way.
Instead of laboriously connecting signal handlers to signals, you can simply make a new class which inherits from a widget - say, a Button - and then override the default signal handler, such as Button::on_clicked(). This can be a lot simpler than hooking up signal handlers for everything.
Subclassing isn't always the best way to accomplish things. It is only useful when you want the widget to handle its own signal by itself. If you want some other class to handle the signal then you'll need to connect a separate handler. This is even more true if you want several objects to handle the same signal, or if you want one signal handler to respond to the same signal from different objects.
gtkmm classes are designed with overriding in mind; they contain virtual member methods specifically intended to be overridden.
Let's look at an example of overriding:

#include <gtkmm/button.h>

class OverriddenButton : public Gtk::Button
{
protected:
    virtual void on_clicked();
}

void OverriddenButton::on_clicked()
{
    std::cout << "Hello World" << std::endl;

    // call the base class's version of the method:
    Gtk::Button::on_clicked();
}

Here we define a new class called OverriddenButton, which inherits from Gtk::Button. The only thing we change is the on_clicked() method, which is called whenever Gtk::Button emits the clicked signal. This method prints "Hello World" to stdout, and then calls the original, overridden method, to let Gtk::Button do what it would have done had we not overridden.
You don't always need to call the parent's method; there are times when you might not want to. Note that we called the parent method after writing "Hello World", but we could have called it before. In this simple example, it hardly matters much, but there are times when it will. With signals, it's not quite so easy to change details like this, and you can do something here which you can't do at all with connected signal handlers: you can call the parent method in the middle of your custom code.

Binding extra arguments
If you use one signal handler to catch the same signal from several widgets, you might like that signal handler to receive some extra information. For instance, you might want to know which button was clicked. You can do this with sigc::bind(). Here's some code from the helloworld2 example.

m_button1.signal_clicked().connect( sigc::bind<Glib::ustring>( sigc::mem_fun(*this, &HelloWorld::on_button_clicked), "button 1") );

This says that we want the signal to send an extra Glib::ustring argument to the signal handler, and that the value of that argument should be "button 1". Of course we will need to add that extra argument to the declaration of our signal handler:

virtual void on_button_clicked(Glib::ustring data);

Of course, a normal "clicked" signal handler would have no arguments.
sigc::bind() is not commonly used, but you might find it helpful sometimes. If you are familiar with GTK+ programming then you have probably noticed that this is similar to the extra gpointer data arguments which all GTK+ callbacks have. This is generally overused in GTK+ to pass information that should be stored as member data in a derived widget, but widget derivation is very difficult in C. We have far less need of this hack in gtkmm.

X Event signals
The Widget class has some special signals which correspond to the underlying X-Windows events. These are suffixed by _event; for instance, Widget::signal_button_press_event().
You might occasionally find it useful to handle X events when there's something you can't accomplish with normal signals. Gtk::Button, for example, does not send mouse-pointer coordinates with its clicked signal, but you could handle button_press_event if you needed this information. X events are also often used to handle key-presses.
These signals behave slightly differently. The value returned from the signal handler indicates whether it has fully "handled" the event. If the value is false then gtkmm will pass the event on to the next signal handler. If the value is true then no other signal handlers will need to be called.
Handling an X event doesn't affect the Widget's other signals. If you handle button_press_event for Gtk::Button, you'll still be able to get the clicked signal. They are emitted at (nearly) the same time.
Note also that not all widgets receive all X events by default. To receive additional X events, you can use Gtk::Widget::set_events() before showing the widget, or Gtk::Widget::add_events() after showing the widget. However, some widgets must first be placed inside an EventBox widget. See the Widgets Without X-Windows chapter.
Here's a simple example:

bool on_button_press(GdkEventButton* event);
Gtk::Button button("label");
button.signal_button_press_event().connect( sigc::ptr_fun(&on_button_press) );

When the mouse is over the button and a mouse button is pressed, on_button_press() will be called.
GdkEventButton is a structure containing the event's parameters, such as the coordinates of the mouse pointer at the time the button was pressed. There are several different types of GdkEvent structures for the various events.

Signal Handler sequence
By default, your signal handlers are called after any previously-connected signal handlers. However, this can be a problem with the X Event signals. For instance, the existing signal handlers, or the default signal handler, might return true to stop other signal handlers from being called. To specify that your signal handler should be called before the other signal handlers, so that it will always be called, you can specify false for the optional after parameter. For instance,

button.signal_button_press_event().connect( sigc::ptr_fun(&on_mywindow_button_press), false );

The event is delivered first to the widget the event occurred in. If all signal handlers in that widget return false (indicating that the event has not been handled), then the signal will be propagated to the parent widget and emitted there. This continues all the way up to the top-level widget if no one handles the event.

Exceptions in signal handlers
When a program is aborted because of an unhandled C++ exception, it's sometimes possible to use a debugger to find the location where the exception was thrown. This is more difficult than usual if the exception was thrown from a signal handler.
This section describes primarily what you can expect on a Linux system, when you use the gdb debugger.
First, let's look at a simple example where an exception is thrown from a normal function (no signal handler).

// without_signal.cc
#include <gtkmm.h>

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  throwSomething();
  Glib::RefPtr<Gtk::Application> app =
    Gtk::Application::create(argc, argv, "org.gtkmm.without_signal");
  return app->run();
}

Here is an excerpt from a gdb session. Only the most interesting parts of the output are shown.

> gdb without_signal
(gdb) run
terminate called after throwing an instance of 'char const*'

Program received signal SIGABRT, Aborted.
(gdb) backtrace
#7  0x08048864 in throwSomething () at without_signal.cc:6
#8  0x0804887d in main (argc=1, argv=0xbfffecd4) at without_signal.cc:12

You can see that the exception was thrown from without_signal.cc, line 6 (throw "Something";).
Now let's see what happens when an exception is thrown from a signal handler. Here's the source code.

// with_signal.cc
#include <gtkmm.h>

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  Glib::signal_timeout().connect(sigc::ptr_fun(throwSomething), 500);
  Glib::RefPtr<Gtk::Application> app =
    Gtk::Application::create(argc, argv, "org.gtkmm.with_signal");
  app->hold();
  return app->run();
}

And here's an excerpt from a gdb session.

> gdb with_signal
(gdb) run
(with_signal:2703): glibmm-ERROR **:
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.
(gdb) backtrace
#2  0x0063c6ab in glibmm_unexpected_exception () at exceptionhandler.cc:77
#3  Glib::exception_handlers_invoke () at exceptionhandler.cc:150
#4  0x0063d370 in glibmm_source_callback (data=0x804d620) at main.cc:212
#13 0x002e1b31 in Gtk::Application::run (this=0x804f300) at application.cc:178
#14 0x08048ccc in main (argc=1, argv=0xbfffecd4) at with_signal.cc:16

The exception is caught in glibmm, and the program ends with a call to g_error(). Other exceptions may result in different behaviour, but in any case the exception from a signal handler is caught in glibmm or gtkmm, and gdb can't see where it was thrown.
To see where the exception is thrown, you can use the gdb command catch throw.

> gdb with_signal
(gdb) catch throw
Catchpoint 1 (throw)
(gdb) run
Catchpoint 1 (exception thrown), 0x00714ff0 in __cxa_throw ()
(gdb) backtrace
#0  0x00714ff0 in __cxa_throw () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#1  0x08048bd4 in throwSomething () at with_signal.cc:6
(gdb) continue
Continuing.
(with_signal:2375): glibmm-ERROR **
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.

If there are many caught exceptions before the interesting uncaught one, this method can be tedious. It can be automated with the following gdb commands.

(gdb) catch throw
(gdb) commands
(gdb)   backtrace
(gdb)   continue
(gdb)   end
(gdb) set pagination off
(gdb) run

These commands will print a backtrace from each throw and continue. The backtrace from the last (or possibly the last but one) throw before the program stops, is the interesting one.