demos: Fix and cleanup GP_BackendInit() + docs.
[gfxprim/pasky.git] / demos / c_simple / backend_timers_example.c
blob8a592bee2c96c3879065f5fd8019451577694bc5
1 /*****************************************************************************
2 * This file is part of gfxprim library. *
3 * *
4 * Gfxprim is free software; you can redistribute it and/or *
5 * modify it under the terms of the GNU Lesser General Public *
6 * License as published by the Free Software Foundation; either *
7 * version 2.1 of the License, or (at your option) any later version. *
8 * *
9 * Gfxprim is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
12 * Lesser General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU Lesser General Public *
15 * License along with gfxprim; if not, write to the Free Software *
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, *
17 * Boston, MA 02110-1301 USA *
18 * *
19 * Copyright (C) 2009-2013 Cyril Hrubis <metan@ucw.cz> *
20 * *
21 *****************************************************************************/
25 Simple backend timers example.
29 #include <GP.h>
31 static void redraw(GP_Backend *self)
33 GP_Context *context = self->context;
34 GP_Pixel black_pixel = GP_ColorToContextPixel(GP_COL_BLACK, context);
36 GP_Fill(context, black_pixel);
38 /* Update the backend screen */
39 GP_BackendFlip(self);
42 static uint32_t timer_callback(GP_Timer *self)
44 uint32_t next = random() % 10000;
46 printf("Timer %s callback called, rescheduling after %u.\n",
47 self->id, (unsigned) next);
49 return next;
52 int main(void)
54 GP_Backend *backend;
55 const char *backend_opts = "X11:100x100";
57 backend = GP_BackendInit(backend_opts, "Backend Timers Example");
59 if (backend == NULL) {
60 fprintf(stderr, "Failed to initialize backend\n");
61 return 1;
64 redraw(backend);
67 * Periodic timer with 1000ms interval. As the callback is set to NULL
68 * Timer Event is pushed to event queue upon expiration.
70 GP_TIMER_DECLARE(timer1, 0, 1000, "Timer 1", NULL, NULL);
73 * Timer with a callback, this timer gets scheduled depending on ouput
74 * from callback (0 means disable timer).
76 GP_TIMER_DECLARE(timer2, 5000, 0, "Timer 2", timer_callback, NULL);
78 GP_BackendAddTimer(backend, &timer1);
79 GP_BackendAddTimer(backend, &timer2);
81 /* Handle events */
82 for (;;) {
83 GP_Event ev;
85 GP_BackendWaitEvent(backend, &ev);
87 GP_EventDump(&ev);
89 switch (ev.type) {
90 case GP_EV_KEY:
91 switch (ev.val.val) {
92 case GP_KEY_ESC:
93 case GP_KEY_Q:
94 GP_BackendExit(backend);
95 return 0;
96 break;
98 break;
99 case GP_EV_SYS:
100 switch (ev.code) {
101 case GP_EV_SYS_RESIZE:
102 GP_BackendResizeAck(backend);
103 redraw(backend);
104 break;
105 case GP_EV_SYS_QUIT:
106 GP_BackendExit(backend);
107 return 0;
108 break;
110 break;
114 GP_BackendExit(backend);
116 return 0;