Clock, a Count down, Visual effects or Animations or Timer in Gtk+

The following example demostrates a timer example. Timers are used when we have some repeating tasks. It could be a clock, a count down, visual effects or animations.

#include 
#include
#include
static char buffer[256];
static gboolean
on_expose_event(GtkWidget *widget,
GdkEventExpose *event,
gpointer data)
{
cairo_t *cr;
cr = gdk_cairo_create(widget->window);
cairo_move_to(cr, 30, 30);
cairo_show_text(cr, buffer);
cairo_destroy(cr);
return FALSE;
}
static gboolean
time_handler(GtkWidget *widget)
{
if (widget->window == NULL) return FALSE;
time_t curtime;
struct tm *loctime;
curtime = time(NULL);
loctime = localtime(&curtime);
strftime(buffer, 256, "%T", loctime);
gtk_widget_queue_draw(widget);
return TRUE;
}
int main (int argc, char *argv[])
{
GtkWidget *window;
GtkWidget *darea;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
darea = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER (window), darea);
g_signal_connect(darea, "expose-event",
G_CALLBACK(on_expose_event), NULL);
g_signal_connect(window, "destroy",
G_CALLBACK(gtk_main_quit), NULL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 170, 100);
gtk_window_set_title(GTK_WINDOW(window), "timer");
g_timeout_add(1000, (GSourceFunc) time_handler, (gpointer) window);
gtk_widget_show_all(window);
time_handler(window);
gtk_main();
return 0;
}

We will display a current local time on the window. We use the Cairo 2D library.

g_signal_connect(darea, "expose-event",
G_CALLBACK(on_expose_event), NULL);

We will draw the time inside the on_expose_event() callback. The callback is connected to
the expose-event signal. The signal is emitted, when the window is going to be redrawn.


g_timeout_add(1000, (GSourceFunc) time_handler, (gpointer) window);

This function registers the timer. The time_handler()
function is called repeteadly at regular intervals. In our case in
every second. The timer function is called until it returns FALSE.

time_handler(window);

This calles the timer function immediately. Otherwise, there would be one sec delay.

cairo_t *cr;
cr = gdk_cairo_create(widget->window);
cairo_move_to(cr, 30, 30);
cairo_show_text(cr, buffer);
cairo_destroy(cr);

This code draws the current time on the window.

if (widget->window == NULL) return FALSE;

When the window is destroyed, it may happen, that the timer function is
called. This line will prevent working on already destroyed widget.

time_t curtime;
struct tm *loctime;
curtime = time(NULL);
loctime = localtime(&curtime);
strftime(buffer, 256, "%T", loctime);

These lines determine the current local time.

gtk_widget_queue_draw(widget);

This will invalidate the window area, which will emit the expose-event signal.






No comments:

 
Top Blogs