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