if !G_THREADS_ENABLED, eat the trailing semicolon with a bogus function
[platform/upstream/glib.git] / gmain.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gmain.c: Main loop abstraction, timeouts, and idle functions
5  * Copyright 1998 Owen Taylor
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /* 
24  * MT safe
25  */
26
27 #include "glib.h"
28 #include <sys/time.h>
29 #include <unistd.h>
30 #include <errno.h>
31 #include "config.h"
32
33 /* Types */
34
35 typedef struct _GIdleData GIdleData;
36 typedef struct _GTimeoutData GTimeoutData;
37 typedef struct _GSource GSource;
38 typedef struct _GPollRec GPollRec;
39
40 typedef enum
41 {
42   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
43   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
44 } GSourceFlags;
45
46 struct _GSource
47 {
48   GHook hook;
49   gint priority;
50   gpointer source_data;
51 };
52
53 struct _GMainLoop
54 {
55   gboolean flag;
56 };
57
58 struct _GIdleData
59 {
60   GSourceFunc callback;
61 };
62
63 struct _GTimeoutData
64 {
65   GTimeVal    expiration;
66   gint        interval;
67   GSourceFunc callback;
68 };
69
70 struct _GPollRec
71 {
72   gint priority;
73   GPollFD *fd;
74   GPollRec *next;
75 };
76
77 /* Forward declarations */
78
79 static void     g_main_poll               (gint      timeout,
80                                            gboolean  use_priority, 
81                                            gint      priority);
82 static void     g_main_poll_add_unlocking (gint      priority,
83                                            GPollFD  *fd);
84
85 static gboolean g_timeout_prepare      (gpointer  source_data, 
86                                         GTimeVal *current_time,
87                                         gint     *timeout);
88 static gboolean g_timeout_check        (gpointer  source_data,
89                                         GTimeVal *current_time);
90 static gboolean g_timeout_dispatch     (gpointer  source_data,
91                                         GTimeVal *current_time,
92                                         gpointer  user_data);
93 static gboolean g_idle_prepare         (gpointer  source_data, 
94                                         GTimeVal *current_time,
95                                         gint     *timeout);
96 static gboolean g_idle_check           (gpointer  source_data,
97                                         GTimeVal *current_time);
98 static gboolean g_idle_dispatch        (gpointer  source_data,
99                                         GTimeVal *current_time,
100                                         gpointer  user_data);
101
102 /* Data */
103
104 static GSList *pending_dispatches = NULL;
105 static GHookList source_list = { 0 };
106
107 /* The following lock is used for both the list of sources
108  * and the list of poll records
109  */
110 G_LOCK_DECLARE_STATIC (main_loop);
111
112 static GSourceFuncs timeout_funcs = {
113   g_timeout_prepare,
114   g_timeout_check,
115   g_timeout_dispatch,
116   (GDestroyNotify)g_free
117 };
118
119 static GSourceFuncs idle_funcs = {
120   g_idle_prepare,
121   g_idle_check,
122   g_idle_dispatch,
123   (GDestroyNotify)g_free
124 };
125
126 static GPollRec *poll_records = NULL;
127 static GPollRec *poll_free_list = NULL;
128 static GMemChunk *poll_chunk;
129 static guint n_poll_records = 0;
130
131 /* this pipe is used to wake up the main loop when a source is added.
132  */
133 static gint wake_up_pipe[2] = { -1, -1 };
134 static GPollFD wake_up_rec;
135 static gboolean poll_waiting = FALSE;
136
137 #ifdef HAVE_POLL
138 static GPollFunc poll_func = (GPollFunc) poll;
139 #else   /* !HAVE_POLL */
140
141 /* The following implementation of poll() comes from the GNU C Library.
142  * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
143  */
144
145 #include <string.h> /* for bzero on BSD systems */
146
147 #ifdef HAVE_SYS_SELECT_H
148 #include <sys/select.h>
149 #endif /* HAVE_SYS_SELECT_H_ */
150
151 #ifndef NO_FD_SET
152 #  define SELECT_MASK fd_set
153 #else   /* !NO_FD_SET */
154 #  ifndef _AIX
155 typedef long fd_mask;
156 #  endif
157 #  if defined(_IBMR2)
158 #    define SELECT_MASK void
159 #  else
160 #    define SELECT_MASK int
161 #  endif
162 #endif  /* !NO_FD_SET */
163
164 static gint 
165 g_poll (GPollFD *fds, guint nfds, gint timeout)
166 {
167   struct timeval tv;
168   SELECT_MASK rset, wset, xset;
169   GPollFD *f;
170   int ready;
171   int maxfd = 0;
172
173   FD_ZERO (&rset);
174   FD_ZERO (&wset);
175   FD_ZERO (&xset);
176
177   for (f = fds; f < &fds[nfds]; ++f)
178     if (f->fd >= 0)
179       {
180         if (f->events & G_IO_IN)
181           FD_SET (f->fd, &rset);
182         if (f->events & G_IO_OUT)
183           FD_SET (f->fd, &wset);
184         if (f->events & G_IO_PRI)
185           FD_SET (f->fd, &xset);
186         if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
187           maxfd = f->fd;
188       }
189
190   tv.tv_sec = timeout / 1000;
191   tv.tv_usec = (timeout % 1000) * 1000;
192
193   ready = select (maxfd + 1, &rset, &wset, &xset,
194                   timeout == -1 ? NULL : &tv);
195   if (ready > 0)
196     for (f = fds; f < &fds[nfds]; ++f)
197       {
198         f->revents = 0;
199         if (f->fd >= 0)
200           {
201             if (FD_ISSET (f->fd, &rset))
202               f->revents |= G_IO_IN;
203             if (FD_ISSET (f->fd, &wset))
204               f->revents |= G_IO_OUT;
205             if (FD_ISSET (f->fd, &xset))
206               f->revents |= G_IO_PRI;
207           }
208       }
209
210   return ready;
211 }
212 static GPollFunc poll_func = g_poll;
213 #endif  /* !HAVE_POLL */
214
215 /* Hooks for adding to the main loop */
216
217 /* Use knowledge of insert_sorted algorithm here to make
218  * sure we insert at the end of equal priority items
219  */
220 static gint
221 g_source_compare (GHook *a,
222                   GHook *b)
223 {
224   GSource *source_a = (GSource *)a;
225   GSource *source_b = (GSource *)b;
226
227   return (source_a->priority < source_b->priority) ? -1 : 1;
228 }
229
230 guint 
231 g_source_add (gint           priority,
232               gboolean       can_recurse,
233               GSourceFuncs  *funcs,
234               gpointer       source_data, 
235               gpointer       user_data,
236               GDestroyNotify notify)
237 {
238   guint return_val;
239   GSource *source;
240
241   G_LOCK (main_loop);
242
243   if (!source_list.is_setup)
244     g_hook_list_init (&source_list, sizeof(GSource));
245
246   source = (GSource *)g_hook_alloc (&source_list);
247   source->priority = priority;
248   source->source_data = source_data;
249   source->hook.func = funcs;
250   source->hook.data = user_data;
251   source->hook.destroy = notify;
252   
253   g_hook_insert_sorted (&source_list, 
254                         (GHook *)source, 
255                         g_source_compare);
256
257   if (can_recurse)
258     source->hook.flags |= G_SOURCE_CAN_RECURSE;
259
260   return_val = source->hook.hook_id;
261
262   /* Now wake up the main loop if it is waiting in the poll() */
263
264   if (poll_waiting)
265     {
266       poll_waiting = FALSE;
267       write (wake_up_pipe[1], "A", 1);
268     }
269
270   G_UNLOCK (main_loop);
271
272   return return_val;
273 }
274
275 void 
276 g_source_remove (guint tag)
277 {
278   GHook *hook;
279
280   G_LOCK (main_loop);
281
282   hook = g_hook_get (&source_list, tag);
283   if (hook)
284     {
285       GSource *source = (GSource *)hook;
286       
287       ((GSourceFuncs *) source->hook.func)->destroy (source->source_data);
288       g_hook_destroy_link (&source_list, hook);
289     }
290
291   G_UNLOCK (main_loop);
292 }
293
294 void 
295 g_source_remove_by_user_data (gpointer user_data)
296 {
297   GHook *hook;
298   
299   G_LOCK (main_loop);
300   
301   hook = g_hook_find_data (&source_list, TRUE, user_data);
302   if (hook)
303     {
304       GSource *source = (GSource *)hook;
305
306       ((GSourceFuncs *) source->hook.func)->destroy (source->source_data);
307       g_hook_destroy_link (&source_list, hook);
308     }
309
310   G_UNLOCK (main_loop);
311 }
312
313 static gboolean
314 g_source_find_source_data (GHook        *hook,
315                            gpointer      data)
316 {
317   GSource *source = (GSource *)hook;
318
319   return (source->source_data == data);
320 }
321
322 void 
323 g_source_remove_by_source_data (gpointer source_data)
324 {
325   GHook *hook;
326
327   G_LOCK (main_loop);
328
329   hook = g_hook_find (&source_list, TRUE, 
330                       g_source_find_source_data, source_data);
331   if (hook)
332     {
333       GSource *source = (GSource *)hook;
334
335       ((GSourceFuncs *) source->hook.func)->destroy (source->source_data);
336       g_hook_destroy_link (&source_list, hook);
337     }
338
339   G_UNLOCK (main_loop);
340 }
341
342 void
343 g_get_current_time (GTimeVal *result)
344 {
345   g_return_if_fail (result != NULL);
346
347   gettimeofday ((struct timeval *) result, NULL);
348 }
349
350 /* Running the main loop */
351
352 /* HOLDS: main_loop_lock */
353 static void
354 g_main_dispatch (GTimeVal *current_time)
355 {
356   while (pending_dispatches != NULL)
357     {
358       gboolean need_destroy;
359       GSource *source = pending_dispatches->data;
360       GSList *tmp_list;
361
362       tmp_list = pending_dispatches;
363       pending_dispatches = g_slist_remove_link (pending_dispatches, pending_dispatches);
364       g_slist_free_1 (tmp_list);
365
366       if (G_HOOK_IS_VALID (source))
367         {
368           gpointer hook_data = source->hook.data;
369           gpointer source_data = source->source_data;
370           gboolean (*dispatch) (gpointer,
371                                 GTimeVal *,
372                                 gpointer);
373
374           dispatch = ((GSourceFuncs *) source->hook.func)->dispatch;
375           
376           source->hook.flags |= G_HOOK_FLAG_IN_CALL;
377
378           G_UNLOCK (main_loop);
379           need_destroy = ! dispatch (source_data,
380                                      current_time,
381                                      hook_data);
382           G_LOCK (main_loop);
383
384           source->hook.flags &= ~G_HOOK_FLAG_IN_CALL;
385           
386           if (need_destroy)
387             g_hook_destroy_link (&source_list, (GHook *) source);
388         }
389
390       g_hook_unref (&source_list, (GHook *)source);
391     }
392 }
393
394 /* Run a single iteration of the mainloop, or, if !dispatch
395  * check to see if any events need dispatching, but don't
396  * run the loop.
397  */
398 static gboolean
399 g_main_iterate (gboolean block,
400                 gboolean dispatch)
401 {
402   GHook *hook;
403   GTimeVal current_time;
404   gint nready = 0;
405   gint current_priority = 0;
406   gint timeout;
407   gboolean retval = FALSE;
408
409   g_return_val_if_fail (!block || dispatch, FALSE);
410
411   g_get_current_time (&current_time);
412
413   G_LOCK (main_loop);
414   
415   /* If recursing, finish up current dispatch, before starting over */
416   if (pending_dispatches)
417     {
418       if (dispatch)
419         g_main_dispatch (&current_time);
420       
421       G_UNLOCK (main_loop);
422       return TRUE;
423     }
424
425   /* Prepare all sources */
426
427   timeout = block ? -1 : 0;
428   
429   hook = g_hook_first_valid (&source_list, TRUE);
430   while (hook)
431     {
432       GSource *source = (GSource *)hook;
433       GHook *tmp;
434       gint source_timeout;
435
436       if ((nready > 0) && (source->priority > current_priority))
437         break;
438       if (!(hook->flags & G_SOURCE_CAN_RECURSE) && G_HOOK_IN_CALL (hook))
439         {
440           hook = g_hook_next_valid (hook, TRUE);
441           continue;
442         }
443
444       g_hook_ref (&source_list, hook);
445
446       if (((GSourceFuncs *)hook->func)->prepare (source->source_data,
447                                                  &current_time,
448                                                  &source_timeout))
449         {
450           if (!dispatch)
451             {
452               g_hook_unref (&source_list, hook);
453               G_UNLOCK (main_loop);
454               return TRUE;
455             }
456           else
457             {
458               hook->flags |= G_SOURCE_READY;
459               nready++;
460               current_priority = source->priority;
461               timeout = 0;
462             }
463         }
464       
465       if (source_timeout >= 0)
466         {
467           if (timeout < 0)
468             timeout = source_timeout;
469           else
470             timeout = MIN (timeout, source_timeout);
471         }
472
473       tmp = g_hook_next_valid (hook, TRUE);
474       
475       g_hook_unref (&source_list, hook);
476       hook = tmp;
477     }
478
479   /* poll(), if necessary */
480
481   g_main_poll (timeout, nready > 0, current_priority);
482
483   /* Check to see what sources need to be dispatched */
484
485   nready = 0;
486   
487   hook = g_hook_first_valid (&source_list, TRUE);
488   while (hook)
489     {
490       GSource *source = (GSource *)hook;
491       GHook *tmp;
492
493       if ((nready > 0) && (source->priority > current_priority))
494         break;
495       if (!(hook->flags & G_SOURCE_CAN_RECURSE) && G_HOOK_IN_CALL (hook))
496         {
497           hook = g_hook_next_valid (hook, TRUE);
498           continue;
499         }
500
501       g_hook_ref (&source_list, hook);
502
503       if ((hook->flags & G_SOURCE_READY) ||
504           ((GSourceFuncs *)hook->func)->check (source->source_data,
505                                                &current_time))
506         {
507           if (dispatch)
508             {
509               hook->flags &= ~G_SOURCE_READY;
510               g_hook_ref (&source_list, hook);
511               pending_dispatches = g_slist_prepend (pending_dispatches, source);
512               current_priority = source->priority;
513               nready++;
514             }
515           else
516             {
517               g_hook_unref (&source_list, hook);
518               G_UNLOCK (main_loop);
519               return TRUE;
520             }
521         }
522       
523       tmp = g_hook_next_valid (hook, TRUE);
524       
525       g_hook_unref (&source_list, hook);
526       hook = tmp;
527     }
528
529   /* Now invoke the callbacks */
530
531   if (pending_dispatches)
532     {
533       pending_dispatches = g_slist_reverse (pending_dispatches);
534       g_main_dispatch (&current_time);
535       retval = TRUE;
536     }
537
538   G_UNLOCK (main_loop);
539
540   return retval;
541 }
542
543 /* See if any events are pending
544  */
545 gboolean 
546 g_main_pending ()
547 {
548   return g_main_iterate (FALSE, FALSE);
549 }
550
551 /* Run a single iteration of the mainloop. If block is FALSE,
552  * will never block
553  */
554 gboolean
555 g_main_iteration (gboolean block)
556 {
557   return g_main_iterate (block, TRUE);
558 }
559
560 GMainLoop *
561 g_main_new ()
562 {
563   GMainLoop *result = g_new (GMainLoop, 1);
564   result->flag = FALSE;
565
566   return result;
567 }
568
569 void 
570 g_main_run (GMainLoop *loop)
571 {
572   loop->flag = FALSE;
573   while (!loop->flag)
574     g_main_iterate (TRUE, TRUE);
575 }
576
577 void 
578 g_main_quit (GMainLoop *loop)
579 {
580   loop->flag = TRUE;
581 }
582
583 void 
584 g_main_destroy (GMainLoop *loop)
585 {
586   g_free (loop);
587 }
588
589 /* HOLDS: main_loop_lock */
590 static void
591 g_main_poll (gint timeout, gboolean use_priority, gint priority)
592 {
593   GPollFD *fd_array = g_new (GPollFD, n_poll_records);
594   GPollRec *pollrec;
595
596   gint i;
597   gint npoll;
598
599   if (wake_up_pipe[0] < 0)
600     {
601       if (pipe (wake_up_pipe) < 0)
602         g_error ("Cannot create pipe main loop wake-up: %s\n",
603                  g_strerror(errno));
604
605       wake_up_rec.fd = wake_up_pipe[0];
606       wake_up_rec.events = G_IO_IN;
607       g_main_poll_add_unlocking (0, &wake_up_rec);
608     }
609   
610   pollrec = poll_records;
611   i = 0;
612   while (pollrec && (!use_priority || priority >= pollrec->priority))
613     {
614       fd_array[i].fd = pollrec->fd->fd;
615       fd_array[i].events = pollrec->fd->events;
616       fd_array[i].revents = 0;
617         
618       pollrec = pollrec->next;
619       i++;
620     }
621
622   poll_waiting = TRUE;
623   
624   G_UNLOCK (main_loop);
625   npoll = i;
626   (*poll_func) (fd_array, npoll, timeout);
627   G_LOCK (main_loop);
628
629   if (!poll_waiting)
630     {
631       gchar c;
632       read (wake_up_pipe[0], &c, 1);
633     }
634   else
635     poll_waiting = FALSE;
636
637   pollrec = poll_records;
638   i = 0;
639   while (i < npoll)
640     {
641       pollrec->fd->revents = fd_array[i].revents;
642       pollrec = pollrec->next;
643       i++;
644     }
645
646   g_free (fd_array);
647 }
648
649 void 
650 g_main_poll_add (gint     priority,
651                  GPollFD *fd)
652 {
653   G_LOCK (main_loop);
654   g_main_poll_add_unlocking (priority, fd);
655   G_UNLOCK (main_loop);
656 }
657
658 /* HOLDS: main_loop_lock */
659 static void 
660 g_main_poll_add_unlocking (gint     priority,
661                            GPollFD *fd)
662 {
663   GPollRec *lastrec, *pollrec, *newrec;
664
665   if (!poll_chunk)
666     poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
667
668   if (poll_free_list)
669     {
670       newrec = poll_free_list;
671       poll_free_list = newrec->next;
672     }
673   else
674     newrec = g_chunk_new (GPollRec, poll_chunk);
675
676   newrec->fd = fd;
677   newrec->priority = priority;
678
679   lastrec = NULL;
680   pollrec = poll_records;
681   while (pollrec && priority >= pollrec->priority)
682     {
683       lastrec = pollrec;
684       pollrec = pollrec->next;
685     }
686   
687   if (lastrec)
688     lastrec->next = newrec;
689   else
690     poll_records = newrec;
691
692   newrec->next = pollrec;
693
694   n_poll_records++;
695 }
696
697 void 
698 g_main_poll_remove (GPollFD *fd)
699 {
700   GPollRec *pollrec, *lastrec;
701
702   G_LOCK (main_loop);
703   
704   lastrec = NULL;
705   pollrec = poll_records;
706
707   while (pollrec)
708     {
709       if (pollrec->fd == fd)
710         {
711           if (lastrec != NULL)
712             lastrec->next = pollrec->next;
713           else
714             poll_records = pollrec->next;
715
716           pollrec->next = poll_free_list;
717           poll_free_list = pollrec;
718
719           n_poll_records--;
720           break;
721         }
722       lastrec = pollrec;
723       pollrec = pollrec->next;
724     }
725
726   G_UNLOCK (main_loop);
727 }
728
729 void 
730 g_main_set_poll_func (GPollFunc func)
731 {
732   if (func)
733     poll_func = func;
734   else
735 #ifdef HAVE_POLL
736     poll_func = (GPollFunc)poll;
737 #else
738     poll_func = (GPollFunc)g_poll;
739 #endif
740 }
741
742 /* Timeouts */
743
744 static gboolean 
745 g_timeout_prepare  (gpointer source_data, 
746                     GTimeVal *current_time,
747                     gint    *timeout)
748 {
749   glong msec;
750   GTimeoutData *data = source_data;
751
752   msec = (data->expiration.tv_sec  - current_time->tv_sec) * 1000 +
753          (data->expiration.tv_usec - current_time->tv_usec) / 1000;
754
755   *timeout = (msec <= 0) ? 0 : msec;
756
757   return (msec <= 0);
758 }
759
760 static gboolean 
761 g_timeout_check    (gpointer source_data,
762                     GTimeVal *current_time)
763 {
764   GTimeoutData *data = source_data;
765
766   return (data->expiration.tv_sec < current_time->tv_sec) ||
767          ((data->expiration.tv_sec == current_time->tv_sec) &&
768           (data->expiration.tv_usec <= current_time->tv_usec));
769 }
770
771 static gboolean
772 g_timeout_dispatch (gpointer source_data, 
773                     GTimeVal *current_time,
774                     gpointer user_data)
775 {
776   GTimeoutData *data = source_data;
777
778   if (data->callback(user_data))
779     {
780       data->expiration.tv_sec = current_time->tv_sec;
781       data->expiration.tv_usec = current_time->tv_usec + data->interval * 1000;
782       if (data->expiration.tv_usec >= 1000000)
783         {
784           data->expiration.tv_usec -= 1000000;
785           data->expiration.tv_sec++;
786         }
787       return TRUE;
788     }
789   else
790     return FALSE;
791 }
792
793 guint 
794 g_timeout_add_full (gint           priority,
795                     guint          interval, 
796                     GSourceFunc    function,
797                     gpointer       data,
798                     GDestroyNotify notify)
799 {
800   GTimeoutData *timeout_data = g_new (GTimeoutData, 1);
801
802   timeout_data->interval = interval;
803   timeout_data->callback = function;
804   g_get_current_time (&timeout_data->expiration);
805
806   timeout_data->expiration.tv_usec += timeout_data->interval * 1000;
807   if (timeout_data->expiration.tv_usec >= 1000000)
808     {
809       timeout_data->expiration.tv_usec -= 1000000;
810       timeout_data->expiration.tv_sec++;
811     }
812
813   return g_source_add (priority, FALSE, &timeout_funcs, timeout_data, data, notify);
814 }
815
816 guint 
817 g_timeout_add (guint32        interval,
818                GSourceFunc    function,
819                gpointer       data)
820 {
821   return g_timeout_add_full (0, interval, function, data, NULL);
822 }
823
824 /* Idle functions */
825
826 static gboolean 
827 g_idle_prepare  (gpointer source_data, 
828                  GTimeVal *current_time,
829                  gint     *timeout)
830 {
831   timeout = 0;
832   return TRUE;
833 }
834
835 static gboolean 
836 g_idle_check    (gpointer  source_data,
837                  GTimeVal *current_time)
838 {
839   return TRUE;
840 }
841
842 static gboolean
843 g_idle_dispatch (gpointer source_data, 
844                  GTimeVal *current_time,
845                  gpointer user_data)
846 {
847   GIdleData *data = source_data;
848
849   return (*data->callback)(user_data);
850 }
851
852 guint 
853 g_idle_add_full (gint          priority,
854                  GSourceFunc    function,
855                  gpointer       data,
856                  GDestroyNotify notify)
857 {
858   GIdleData *idle_data = g_new (GIdleData, 1);
859
860   idle_data->callback = function;
861
862   return g_source_add (priority, FALSE, &idle_funcs, idle_data, data, notify);
863 }
864
865 guint 
866 g_idle_add (GSourceFunc    function,
867             gpointer       data)
868 {
869   return g_idle_add_full (0, function, data, NULL);
870 }