Timeouts, I/O and Idle Functions

Timeouts
You may be wondering how to make gtkmm do useful work while it's idling along. Happily, you have several options. Using the following methods you can create a timeout method that will be called every few milliseconds.

sigc::connection Glib::SignalTimeout::connect(const sigc::slot<bool>& slot,
                                      unsigned int interval, int priority = Glib::PRIORITY_DEFAULT);

The first argument is a slot you wish to have called when the timeout occurs. The second argument is the number of milliseconds between calls to that method. You receive a sigc::connection object that can be used to deactivate the connection using its disconnect() method:

my_connection.disconnect();

Another way of destroying the connection is your signal handler. It has to be of the type sigc::slot<bool>. As you see from the definition your signal handler has to return a value of the type bool. A definition of a sample method might look like this:

bool MyCallback() { std::cout << "Hello World!\n" << std::endl; return true; }

You can stop the timeout method by returning false from your signal handler. Therefore, if you want your method to be called repeatedly, it should return true.
Here's an example of this technique:
Source Code
File: timerexample.h (For use with gtkmm 3, not gtkmm 2)

#ifndef GTKMM_EXAMPLE_TIMEREXAMPLE_H
#define GTKMM_EXAMPLE_TIMEREXAMPLE_H

#include <gtkmm.h>
#include <iostream>
#include <map>

class TimerExample : public Gtk::Window
{
public:
  TimerExample();

protected:
  // signal handlers
  void on_button_add_timer();
  void on_button_delete_timer();
  void on_button_quit();

  // This is the callback function the timeout will call
  bool on_timeout(int timer_number);

  // Member data:

  Gtk::Box m_Box;
  Gtk::Button m_ButtonAddTimer, m_ButtonDeleteTimer, m_ButtonQuit;

  // Keep track of the timers being added:
  int m_timer_number;

  // These two constants are initialized in the constructor's member initializer:
  const int count_value;
  const int timeout_value;

  // STL map for storing our connections
  std::map<int, sigc::connection> m_timers;

  // STL map for storing our timer values.
  // Each timer counts back from COUNT_VALUE to 0 and is removed when it reaches 0
  std::map<int, int> m_counters;
};

#endif // GTKMM_EXAMPLE_TIMEREXAMPLE_H

File: timerexample.cc (For use with gtkmm 3, not gtkmm 2)

#include "timerexample.h"

TimerExample::TimerExample() :
  m_Box(Gtk::ORIENTATION_HORIZONTAL, 10),
  m_ButtonAddTimer("_Add", true),
  m_ButtonDeleteTimer("_Remove", true),
  m_ButtonQuit("_Quit", true),
  m_timer_number(0), // start numbering the timers at 0
  count_value(5), // each timer will count down 5 times before disconnecting
  timeout_value(1500) // 1500 ms = 1.5 seconds
{
  set_border_width(10);

  add(m_Box);
  m_Box.pack_start(m_ButtonAddTimer);
  m_Box.pack_start(m_ButtonDeleteTimer);
  m_Box.pack_start(m_ButtonQuit);

  // Connect the three buttons:
  m_ButtonQuit.signal_clicked().connect(sigc::mem_fun(*this,
              &TimerExample::on_button_quit));
  m_ButtonAddTimer.signal_clicked().connect(sigc::mem_fun(*this,
              &TimerExample::on_button_add_timer));
  m_ButtonDeleteTimer.signal_clicked().connect(sigc::mem_fun(*this,
              &TimerExample::on_button_delete_timer));

  show_all_children();
}

void TimerExample::on_button_quit()
{
  hide();
}

void TimerExample::on_button_add_timer()
{
  // Creation of a new object prevents long lines and shows us a little
  // how slots work.  We have 0 parameters and bool as a return value
  // after calling sigc::bind.
  sigc::slot<bool> my_slot = sigc::bind(sigc::mem_fun(*this,
              &TimerExample::on_timeout), m_timer_number);

  // This is where we connect the slot to the Glib::signal_timeout()
  sigc::connection conn = Glib::signal_timeout().connect(my_slot,
          timeout_value);

  // Remember the connection:
  m_timers[m_timer_number] = conn;

  // Initialize timer count:
  m_counters[m_timer_number] = count_value + 1;

  // Print some info to the console for the user:
  std::cout << "added timeout " << m_timer_number++ << std::endl;
}

void TimerExample::on_button_delete_timer()
{
  // any timers?
  if(m_timers.empty())
  {
    // no timers left
    std::cout << "Sorry, there are no timers left." << std::endl;
  }
  else
  {
    // get the number of the first timer
    int timer_number = m_timers.begin()->first;

    // Give some info to the user:
    std::cout << "manually disconnecting timer " << timer_number
        << std::endl;

    // Remove the entry in the counter values
    m_counters.erase(timer_number);

    // Diconnect the signal handler:
    m_timers[timer_number].disconnect();

    // Forget the connection:
    m_timers.erase(timer_number);
  }
}

bool TimerExample::on_timeout(int timer_number)
{
  // Print the timer:
  std::cout << "This is timer " << timer_number;

  // decrement and check counter value
  if (--m_counters[timer_number] == 0)
  {
    std::cout << " being disconnected" <<  std::endl;

    // delete the counter entry in the STL MAP
    m_counters.erase(timer_number);

    // delete the connection entry in the STL MAP
    m_timers.erase(timer_number);

    // Note that we do not have to explicitly call disconnect() on the
    // connection since Gtk::Main does this for us when we return false.
    return false;
  }

  // Print the timer value
  std::cout << " - " << m_counters[timer_number] << "/"
      << count_value << std::endl;

 // Keep going (do not disconnect yet):
  return true;
}

File: main.cc (For use with gtkmm 3, not gtkmm 2)

#include "timerexample.h"
#include <gtkmm/application.h>

int main (int argc, char *argv[])
{
  Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  TimerExample example;
  return app->run(example);
}

Monitoring I/O
A nifty feature of Glib (one of the libraries underlying gtkmm) is the ability to have it check for data on a file descriptor for you. This is especially useful for networking applications. The following method is used to do this:

sigc::connection Glib::SignalIO::connect(const sigc::slot<bool,Glib::IOCondition>& slot,
                                 int fd, Glib::IOCondition condition,
                                 int priority = Glib::PRIORITY_DEFAULT);

The first argument is a slot you wish to have called when the specified event (see argument 3) occurs on the file descriptor you specify using argument two. Argument three may be one or more (using |) of:
Glib::IO_IN - Call your method when there is data ready for reading on your file descriptor.
Glib::IO_OUT - Call your method when the file descriptor is ready for writing.
Glib::IO_PRI - Call your method when the file descriptor has urgent data to be read.
Glib::IO_ERR - Call your method when an error has occurred on the file descriptor.
Glib::IO_HUP - Call your method when hung up (the connection has been broken usually for pipes and sockets).
The return value is a sigc::connection that may be used to stop monitoring this file descriptor using its disconnect() method. The slot signal handler should be declared as follows:

bool input_callback(Glib::IOCondition condition);

where condition is as specified above. As usual the slot is created with sigc::mem_fun() (for a member method of an object), or sigc::ptr_fun() (for a function).
A little example follows. To use the example just execute it from a terminal; it doesn't create a window. It will create a pipe named testfifo in the current directory. Then start another shell and execute echo "Hello" > testfifo. The example will print each line you enter until you execute echo "Q" > testfifo.
Source Code
File: main.cc (For use with gtkmm 3, not gtkmm 2)

#include <build/config.h>
#include <gtkmm/application.h>
#include <glibmm/main.h>
#include <glibmm/iochannel.h>
#include <fcntl.h>
#include <iostream>

#include <unistd.h> //The SUN Forte compiler puts F_OK here.

//The SUN Forte compiler needs these for mkfifo:
#include <sys/types.h>
#include <sys/stat.h>

Glib::RefPtr<Gtk::Application> app;

int read_fd;
Glib::RefPtr<Glib::IOChannel> iochannel;

/*
  send to the fifo with:
  echo "Hello" > testfifo

  quit the program with:
  echo "Q" > testfifo
*/

// this will be our signal handler for read operations
// it will print out the message sent to the fifo
// and quit the program if the message was 'Q'.
bool MyCallback(Glib::IOCondition io_condition)
{
  if ((io_condition & Glib::IO_IN) == 0) {
    std::cerr << "Invalid fifo response" << std::endl;
  }
  else {
   Glib::ustring buf;

   iochannel->read_line(buf);
   std::cout << buf;
   if (buf == "Q\n")
     app->quit();

  }
  return true;
}


int main(int argc, char *argv[])
{
  app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  if (access("testfifo", F_OK) == -1) {
    // fifo doesn't exist - create it
    #ifdef HAVE_MKFIFO
    if (mkfifo("testfifo", 0666) != 0) {
      std::cerr << "error creating fifo" << std::endl;
      return -1;
    }
    #else
      std::cerr << "error creating fifo: This platform does not have mkfifo()"
          << std::endl;
    #endif //HAVE_MKFIFO
  }

  read_fd = open("testfifo", O_RDONLY);
  if (read_fd == -1)
  {
    std::cerr << "error opening fifo" << std::endl;
    return -1;
  }

  // connect the signal handler
  Glib::signal_io().connect(sigc::ptr_fun(MyCallback), read_fd, Glib::IO_IN);

  // Creates a iochannel from the file descriptor
  iochannel = Glib::IOChannel::create_from_fd(read_fd);

  // and last but not least - run the application main loop
  app->hold(); // keep the application running without a window
  app->run();

  // now remove the temporary fifo
  if(unlink("testfifo"))
    std::cerr << "error removing fifo" << std::endl;

  return 0;
}

Idle Functions
If you want to specify a method that gets called when nothing else is happening, use the following:

sigc::connection  Glib::SignalIdle::connect(const sigc::slot<bool>& slot,
                                    int priority = Glib::PRIORITY_DEFAULT_IDLE);

This causes gtkmm to call the specified method whenever nothing else is happening. You can add a priority (lower numbers are higher priorities). There are two ways to remove the signal handler: calling disconnect() on the sigc::connection object, or returning false in the signal handler, which should be declared as follows:

bool idleFunc();

Since this is very similar to the methods above this explanation should be sufficient to understand what's going on. However, here's a little example:
Source Code
File: idleexample.h (For use with gtkmm 3, not gtkmm 2)

#ifndef GTKMM_EXAMPLE_IDLEEXAMPLE_H
#define GTKMM_EXAMPLE_IDLEEXAMPLE_H

#include <gtkmm.h>
#include <iostream>

class IdleExample : public Gtk::Window
{
public:
  IdleExample();

protected:
  // Signal Handlers:
  bool on_timer();
  bool on_idle();
  void on_button_clicked();

  // Member data:
  Gtk::Box m_Box;
  Gtk::Button m_ButtonQuit;
  Gtk::ProgressBar m_ProgressBar_c;
  Gtk::ProgressBar m_ProgressBar_d;
};

#endif // GTKMM_EXAMPLE_IDLEEXAMPLE_H

File: main.cc (For use with gtkmm 3, not gtkmm 2)

#include "idleexample.h"
#include <gtkmm/application.h>

int main (int argc, char *argv[])
{
  Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  IdleExample example;
  return app->run(example);
}

File: idleexample.cc (For use with gtkmm 3, not gtkmm 2)

#include "idleexample.h"

IdleExample::IdleExample() :
  m_Box(Gtk::ORIENTATION_VERTICAL, 5),
  m_ButtonQuit("_Quit", true)
{
  set_border_width(5);

  // Put buttons into container

  // Adding a few widgets:
  add(m_Box);
  m_Box.pack_start( *Gtk::manage(new Gtk::Label("Formatting Windows drive C:")));
  m_Box.pack_start( *Gtk::manage(new Gtk::Label("100 MB")) );
  m_Box.pack_start(m_ProgressBar_c);

  m_Box.pack_start( *Gtk::manage(new Gtk::Label("")) );

  m_Box.pack_start( *Gtk::manage(new Gtk::Label("Formatting Windows drive D:")));
  m_Box.pack_start( *Gtk::manage(new Gtk::Label("5000 MB")) );
  m_Box.pack_start(m_ProgressBar_d);

  Gtk::Box* hbox = Gtk::manage( new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL,10));
  m_Box.pack_start(*hbox);
  hbox->pack_start(m_ButtonQuit, Gtk::PACK_EXPAND_PADDING);

  // Connect the signal handlers:
  m_ButtonQuit.signal_clicked().connect( sigc::mem_fun(*this,
              &IdleExample::on_button_clicked) );

  // formatting drive c in timeout signal handler - called once every 50ms
  Glib::signal_timeout().connect( sigc::mem_fun(*this, &IdleExample::on_timer),
          50 );

  // formatting drive d in idle signal handler - called as quickly as possible
  Glib::signal_idle().connect( sigc::mem_fun(*this, &IdleExample::on_idle) );

  show_all_children();
}


void IdleExample::on_button_clicked()
{
  hide();
}

// this timer callback function is executed once every 50ms (set in connection
// above).  Use timeouts when speed is not critical. (ie periodically updating
// something).
bool IdleExample::on_timer()
{
  double value = m_ProgressBar_c.get_fraction();

  // Update progressbar 1/500th each time:
  m_ProgressBar_c.set_fraction(value + 0.002);
 
  return value < 0.99;  // return false when done
}


// This idle callback function is executed as often as possible, hence it is
// ideal for processing intensive tasks.
bool IdleExample::on_idle()
{
  double value = m_ProgressBar_d.get_fraction();

  // Update progressbar 1/5000th each time:
  m_ProgressBar_d.set_fraction(value + 0.0002);

  return value < 0.99;  // return false when done
}

This example points out the difference of idle and timeout methods a little. If you need methods that are called periodically, and speed is not very important, then you want timeout methods. If you want methods that are called as often as possible (like calculating a fractal in background), then use idle methods.
Try executing the example and increasing the system load. The upper progress bar will increase steadily; the lower one will slow down.