Fix embarrassing bug: I was passing an incorrect third parameter to
[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 Lesser 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  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser 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  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
28  */
29
30 /* 
31  * MT safe
32  */
33
34 #include "config.h"
35
36 /* Uncomment the next line to enable debugging printouts if the
37  * environment variable G_MAIN_POLL_DEBUG is set to some value.
38  */
39 /* #define G_MAIN_POLL_DEBUG */
40
41 #ifdef _WIN32
42 /* Always enable debugging printout on Windows, as it is more often
43  * needed there...
44  */
45 #define G_MAIN_POLL_DEBUG
46 #endif
47
48 #include "glib.h"
49 #include "gthreadprivate.h"
50 #include <signal.h>
51 #include <sys/types.h>
52 #include <time.h>
53 #include <stdlib.h>
54 #ifdef HAVE_SYS_TIME_H
55 #include <sys/time.h>
56 #endif /* HAVE_SYS_TIME_H */
57 #ifdef GLIB_HAVE_SYS_POLL_H
58 #  include <sys/poll.h>
59 #  undef events  /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
60 #  undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
61
62 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
63  * so we prefer our own poll emulation.
64  */
65 #if defined(_POLL_EMUL_H_) || defined(BROKEN_POLL)
66 #undef HAVE_POLL
67 #endif
68    
69 #endif /* GLIB_HAVE_SYS_POLL_H */
70 #ifdef HAVE_UNISTD_H
71 #include <unistd.h>
72 #endif /* HAVE_UNISTD_H */
73 #include <errno.h>
74
75 #ifdef G_OS_WIN32
76 #define STRICT
77 #include <windows.h>
78 #endif /* G_OS_WIN32 */
79
80 #ifdef G_OS_BEOS
81 #include <sys/socket.h>
82 #include <sys/wait.h>
83 #endif /* G_OS_BEOS */
84
85 #ifdef G_OS_UNIX
86 #include <fcntl.h>
87 #include <sys/wait.h>
88 #endif
89
90 #include "galias.h"
91
92 #ifdef G_OS_WIN32
93 #ifdef _WIN64
94 #define GPOLLFD_FORMAT "%#I64x"
95 #else
96 #define GPOLLFD_FORMAT "%#x"
97 #endif
98 #else
99 #define GPOLLFD_FORMAT "%d"
100 #endif
101
102 /* Types */
103
104 typedef struct _GTimeoutSource GTimeoutSource;
105 typedef struct _GChildWatchSource GChildWatchSource;
106 typedef struct _GPollRec GPollRec;
107 typedef struct _GSourceCallback GSourceCallback;
108
109 typedef enum
110 {
111   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
112   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
113 } GSourceFlags;
114
115 #ifdef G_THREADS_ENABLED
116 typedef struct _GMainWaiter GMainWaiter;
117
118 struct _GMainWaiter
119 {
120   GCond *cond;
121   GMutex *mutex;
122 };
123 #endif  
124
125 typedef struct _GMainDispatch GMainDispatch;
126
127 struct _GMainDispatch
128 {
129   gint depth;
130   GSList *dispatching_sources; /* stack of current sources */
131 };
132
133 #ifdef G_MAIN_POLL_DEBUG
134 static gboolean g_main_poll_debug = FALSE;
135 #endif
136
137 struct _GMainContext
138 {
139 #ifdef G_THREADS_ENABLED
140   /* The following lock is used for both the list of sources
141    * and the list of poll records
142    */
143   GStaticMutex mutex;
144   GCond *cond;
145   GThread *owner;
146   guint owner_count;
147   GSList *waiters;
148 #endif  
149
150   gint ref_count;
151
152   GPtrArray *pending_dispatches;
153   gint timeout;                 /* Timeout for current iteration */
154
155   guint next_id;
156   GSource *source_list;
157   gint in_check_or_prepare;
158
159   GPollRec *poll_records;
160   guint n_poll_records;
161   GPollFD *cached_poll_array;
162   guint cached_poll_array_size;
163
164 #ifdef G_THREADS_ENABLED  
165 #ifndef G_OS_WIN32
166 /* this pipe is used to wake up the main loop when a source is added.
167  */
168   gint wake_up_pipe[2];
169 #else /* G_OS_WIN32 */
170   HANDLE wake_up_semaphore;
171 #endif /* G_OS_WIN32 */
172
173   GPollFD wake_up_rec;
174   gboolean poll_waiting;
175
176 /* Flag indicating whether the set of fd's changed during a poll */
177   gboolean poll_changed;
178 #endif /* G_THREADS_ENABLED */
179
180   GPollFunc poll_func;
181
182   GTimeVal current_time;
183   gboolean time_is_current;
184 };
185
186 struct _GSourceCallback
187 {
188   guint ref_count;
189   GSourceFunc func;
190   gpointer    data;
191   GDestroyNotify notify;
192 };
193
194 struct _GMainLoop
195 {
196   GMainContext *context;
197   gboolean is_running;
198   gint ref_count;
199 };
200
201 struct _GTimeoutSource
202 {
203   GSource     source;
204   GTimeVal    expiration;
205   guint       interval;
206   guint       granularity;
207 };
208
209 struct _GChildWatchSource
210 {
211   GSource     source;
212   GPid        pid;
213   gint        child_status;
214 #ifdef G_OS_WIN32
215   GPollFD     poll;
216 #else /* G_OS_WIN32 */
217   gint        count;
218   gboolean    child_exited;
219 #endif /* G_OS_WIN32 */
220 };
221
222 struct _GPollRec
223 {
224   GPollFD *fd;
225   GPollRec *next;
226   gint priority;
227 };
228
229 #ifdef G_THREADS_ENABLED
230 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
231 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
232 #define G_THREAD_SELF g_thread_self ()
233 #else
234 #define LOCK_CONTEXT(context) (void)0
235 #define UNLOCK_CONTEXT(context) (void)0
236 #define G_THREAD_SELF NULL
237 #endif
238
239 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
240 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
241                                 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
242
243 #define SOURCE_UNREF(source, context)                       \
244    G_STMT_START {                                           \
245     if ((source)->ref_count > 1)                            \
246       (source)->ref_count--;                                \
247     else                                                    \
248       g_source_unref_internal ((source), (context), TRUE);  \
249    } G_STMT_END
250
251
252 /* Forward declarations */
253
254 static void g_source_unref_internal             (GSource      *source,
255                                                  GMainContext *context,
256                                                  gboolean      have_lock);
257 static void g_source_destroy_internal           (GSource      *source,
258                                                  GMainContext *context,
259                                                  gboolean      have_lock);
260 static void g_main_context_poll                 (GMainContext *context,
261                                                  gint          timeout,
262                                                  gint          priority,
263                                                  GPollFD      *fds,
264                                                  gint          n_fds);
265 static void g_main_context_add_poll_unlocked    (GMainContext *context,
266                                                  gint          priority,
267                                                  GPollFD      *fd);
268 static void g_main_context_remove_poll_unlocked (GMainContext *context,
269                                                  GPollFD      *fd);
270 static void g_main_context_wakeup_unlocked      (GMainContext *context);
271
272 static gboolean g_timeout_prepare  (GSource     *source,
273                                     gint        *timeout);
274 static gboolean g_timeout_check    (GSource     *source);
275 static gboolean g_timeout_dispatch (GSource     *source,
276                                     GSourceFunc  callback,
277                                     gpointer     user_data);
278 static gboolean g_child_watch_prepare  (GSource     *source,
279                                         gint        *timeout);
280 static gboolean g_child_watch_check    (GSource     *source);
281 static gboolean g_child_watch_dispatch (GSource     *source,
282                                         GSourceFunc  callback,
283                                         gpointer     user_data);
284 static gboolean g_idle_prepare     (GSource     *source,
285                                     gint        *timeout);
286 static gboolean g_idle_check       (GSource     *source);
287 static gboolean g_idle_dispatch    (GSource     *source,
288                                     GSourceFunc  callback,
289                                     gpointer     user_data);
290
291 G_LOCK_DEFINE_STATIC (main_loop);
292 static GMainContext *default_main_context;
293 static GSList *main_contexts_without_pipe = NULL;
294
295 #ifndef G_OS_WIN32
296 /* Child status monitoring code */
297 enum {
298   CHILD_WATCH_UNINITIALIZED,
299   CHILD_WATCH_INITIALIZED_SINGLE,
300   CHILD_WATCH_INITIALIZED_THREADED
301 };
302 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
303 static gint child_watch_count = 1;
304 static gint child_watch_wake_up_pipe[2] = {0, 0};
305 #endif /* !G_OS_WIN32 */
306 G_LOCK_DEFINE_STATIC (main_context_list);
307 static GSList *main_context_list = NULL;
308
309 static gint timer_perturb = -1;
310
311 GSourceFuncs g_timeout_funcs =
312 {
313   g_timeout_prepare,
314   g_timeout_check,
315   g_timeout_dispatch,
316   NULL
317 };
318
319 GSourceFuncs g_child_watch_funcs =
320 {
321   g_child_watch_prepare,
322   g_child_watch_check,
323   g_child_watch_dispatch,
324   NULL
325 };
326
327 GSourceFuncs g_idle_funcs =
328 {
329   g_idle_prepare,
330   g_idle_check,
331   g_idle_dispatch,
332   NULL
333 };
334
335 #ifdef HAVE_POLL
336 /* SunOS has poll, but doesn't provide a prototype. */
337 #  if defined (sun) && !defined (__SVR4)
338 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
339 #  endif  /* !sun */
340 #else   /* !HAVE_POLL */
341
342 #ifdef G_OS_WIN32
343
344 static int
345 poll_rest (gboolean  poll_msgs,
346            HANDLE   *handles,
347            gint      nhandles,
348            GPollFD  *fds,
349            guint     nfds,
350            gint      timeout)
351 {
352   DWORD ready;
353   GPollFD *f;
354   int recursed_result;
355
356   if (poll_msgs)
357     {
358       /* Wait for either messages or handles
359        * -> Use MsgWaitForMultipleObjectsEx
360        */
361       if (g_main_poll_debug)
362         g_print ("  MsgWaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
363
364       ready = MsgWaitForMultipleObjectsEx (nhandles, handles, timeout,
365                                            QS_ALLINPUT, MWMO_ALERTABLE);
366
367       if (ready == WAIT_FAILED)
368         {
369           gchar *emsg = g_win32_error_message (GetLastError ());
370           g_warning ("MsgWaitForMultipleObjectsEx failed: %s", emsg);
371           g_free (emsg);
372         }
373     }
374   else if (nhandles == 0)
375     {
376       /* No handles to wait for, just the timeout */
377       if (timeout == INFINITE)
378         ready = WAIT_FAILED;
379       else
380         {
381           SleepEx (timeout, TRUE);
382           ready = WAIT_TIMEOUT;
383         }
384     }
385   else
386     {
387       /* Wait for just handles
388        * -> Use WaitForMultipleObjectsEx
389        */
390       if (g_main_poll_debug)
391         g_print ("  WaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
392
393       ready = WaitForMultipleObjectsEx (nhandles, handles, FALSE, timeout, TRUE);
394       if (ready == WAIT_FAILED)
395         {
396           gchar *emsg = g_win32_error_message (GetLastError ());
397           g_warning ("WaitForMultipleObjectsEx failed: %s", emsg);
398           g_free (emsg);
399         }
400     }
401
402   if (g_main_poll_debug)
403     g_print ("  wait returns %ld%s\n",
404              ready,
405              (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
406               (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
407                (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
408
409   if (ready == WAIT_FAILED)
410     return -1;
411   else if (ready == WAIT_TIMEOUT ||
412            ready == WAIT_IO_COMPLETION)
413     return 0;
414   else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
415     {
416       for (f = fds; f < &fds[nfds]; ++f)
417         if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN)
418           f->revents |= G_IO_IN;
419
420       /* If we have a timeout, or no handles to poll, be satisfied
421        * with just noticing we have messages waiting.
422        */
423       if (timeout != 0 || nhandles == 0)
424         return 1;
425
426       /* If no timeout and handles to poll, recurse to poll them,
427        * too.
428        */
429       recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
430       return (recursed_result == -1) ? -1 : 1 + recursed_result;
431     }
432   else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
433     {
434       for (f = fds; f < &fds[nfds]; ++f)
435         {
436           if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0])
437             {
438               f->revents = f->events;
439               if (g_main_poll_debug)
440                 g_print ("  got event %p\n", (HANDLE) f->fd);
441             }
442         }
443
444       /* If no timeout and polling several handles, recurse to poll
445        * the rest of them.
446        */
447       if (timeout == 0 && nhandles > 1)
448         {
449           /* Remove the handle that fired */
450           int i;
451           if (ready < nhandles - 1)
452             for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++)
453               handles[i-1] = handles[i];
454           nhandles--;
455           recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
456           return (recursed_result == -1) ? -1 : 1 + recursed_result;
457         }
458       return 1;
459     }
460     
461   return 0;
462 }
463
464
465 static gint
466 g_poll (GPollFD *fds,
467         guint    nfds,
468         gint     timeout)
469 {
470   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
471   gboolean poll_msgs = FALSE;
472   GPollFD *f;
473   gint nhandles = 0;
474   int retval;
475
476   if (g_main_poll_debug)
477     g_print ("g_poll: waiting for");
478
479   for (f = fds; f < &fds[nfds]; ++f)
480     if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN))
481       {
482         if (g_main_poll_debug && !poll_msgs)
483           g_print (" MSG");
484         poll_msgs = TRUE;
485       }
486     else if (f->fd > 0)
487       {
488         /* Don't add the same handle several times into the array, as
489          * docs say that is not allowed, even if it actually does seem
490          * to work.
491          */
492         gint i;
493
494         for (i = 0; i < nhandles; i++)
495           if (handles[i] == (HANDLE) f->fd)
496             break;
497
498         if (i == nhandles)
499           {
500             if (nhandles == MAXIMUM_WAIT_OBJECTS)
501               {
502                 g_warning ("Too many handles to wait for!\n");
503                 break;
504               }
505             else
506               {
507                 if (g_main_poll_debug)
508                   g_print (" %p", (HANDLE) f->fd);
509                 handles[nhandles++] = (HANDLE) f->fd;
510               }
511           }
512       }
513
514   if (g_main_poll_debug)
515     g_print ("\n");
516
517   for (f = fds; f < &fds[nfds]; ++f)
518     f->revents = 0;
519
520   if (timeout == -1)
521     timeout = INFINITE;
522
523   /* Polling for several things? */
524   if (nhandles > 1 || (nhandles > 0 && poll_msgs))
525     {
526       /* First check if one or several of them are immediately
527        * available
528        */
529       retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, 0);
530
531       /* If not, and we have a significant timeout, poll again with
532        * timeout then. Note that this will return indication for only
533        * one event, or only for messages. We ignore timeouts less than
534        * ten milliseconds as they are mostly pointless on Windows, the
535        * MsgWaitForMultipleObjectsEx() call will timeout right away
536        * anyway.
537        */
538       if (retval == 0 && (timeout == INFINITE || timeout >= 10))
539         retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
540     }
541   else
542     {
543       /* Just polling for one thing, so no need to check first if
544        * available immediately
545        */
546       retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
547     }
548
549   if (retval == -1)
550     for (f = fds; f < &fds[nfds]; ++f)
551       f->revents = 0;
552
553   return retval;
554 }
555
556 #else  /* !G_OS_WIN32 */
557
558 /* The following implementation of poll() comes from the GNU C Library.
559  * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
560  */
561
562 #include <string.h> /* for bzero on BSD systems */
563
564 #ifdef HAVE_SYS_SELECT_H
565 #include <sys/select.h>
566 #endif /* HAVE_SYS_SELECT_H */
567
568 #ifdef G_OS_BEOS
569 #undef NO_FD_SET
570 #endif /* G_OS_BEOS */
571
572 #ifndef NO_FD_SET
573 #  define SELECT_MASK fd_set
574 #else /* !NO_FD_SET */
575 #  ifndef _AIX
576 typedef long fd_mask;
577 #  endif /* _AIX */
578 #  ifdef _IBMR2
579 #    define SELECT_MASK void
580 #  else /* !_IBMR2 */
581 #    define SELECT_MASK int
582 #  endif /* !_IBMR2 */
583 #endif /* !NO_FD_SET */
584
585 static gint 
586 g_poll (GPollFD *fds,
587         guint    nfds,
588         gint     timeout)
589 {
590   struct timeval tv;
591   SELECT_MASK rset, wset, xset;
592   GPollFD *f;
593   int ready;
594   int maxfd = 0;
595
596   FD_ZERO (&rset);
597   FD_ZERO (&wset);
598   FD_ZERO (&xset);
599
600   for (f = fds; f < &fds[nfds]; ++f)
601     if (f->fd >= 0)
602       {
603         if (f->events & G_IO_IN)
604           FD_SET (f->fd, &rset);
605         if (f->events & G_IO_OUT)
606           FD_SET (f->fd, &wset);
607         if (f->events & G_IO_PRI)
608           FD_SET (f->fd, &xset);
609         if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
610           maxfd = f->fd;
611       }
612
613   tv.tv_sec = timeout / 1000;
614   tv.tv_usec = (timeout % 1000) * 1000;
615
616   ready = select (maxfd + 1, &rset, &wset, &xset,
617                   timeout == -1 ? NULL : &tv);
618   if (ready > 0)
619     for (f = fds; f < &fds[nfds]; ++f)
620       {
621         f->revents = 0;
622         if (f->fd >= 0)
623           {
624             if (FD_ISSET (f->fd, &rset))
625               f->revents |= G_IO_IN;
626             if (FD_ISSET (f->fd, &wset))
627               f->revents |= G_IO_OUT;
628             if (FD_ISSET (f->fd, &xset))
629               f->revents |= G_IO_PRI;
630           }
631       }
632
633   return ready;
634 }
635
636 #endif /* !G_OS_WIN32 */
637
638 #endif  /* !HAVE_POLL */
639
640 /**
641  * g_main_context_ref:
642  * @context: a #GMainContext
643  * 
644  * Increases the reference count on a #GMainContext object by one.
645  *
646  * Returns: the @context that was passed in (since 2.6)
647  **/
648 GMainContext *
649 g_main_context_ref (GMainContext *context)
650 {
651   g_return_val_if_fail (context != NULL, NULL);
652   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL); 
653
654   g_atomic_int_inc (&context->ref_count);
655
656   return context;
657 }
658
659 static inline void
660 poll_rec_list_free (GMainContext *context,
661                     GPollRec     *list)
662 {
663   g_slice_free_chain (GPollRec, list, next);
664 }
665
666 /**
667  * g_main_context_unref:
668  * @context: a #GMainContext
669  * 
670  * Decreases the reference count on a #GMainContext object by one. If
671  * the result is zero, free the context and free all associated memory.
672  **/
673 void
674 g_main_context_unref (GMainContext *context)
675 {
676   GSource *source;
677   g_return_if_fail (context != NULL);
678   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0); 
679
680   if (!g_atomic_int_dec_and_test (&context->ref_count))
681     return;
682
683   G_LOCK (main_context_list);
684   main_context_list = g_slist_remove (main_context_list, context);
685   G_UNLOCK (main_context_list);
686
687   source = context->source_list;
688   while (source)
689     {
690       GSource *next = source->next;
691       g_source_destroy_internal (source, context, FALSE);
692       source = next;
693     }
694
695 #ifdef G_THREADS_ENABLED  
696   g_static_mutex_free (&context->mutex);
697 #endif
698
699   g_ptr_array_free (context->pending_dispatches, TRUE);
700   g_free (context->cached_poll_array);
701
702   poll_rec_list_free (context, context->poll_records);
703   
704 #ifdef G_THREADS_ENABLED
705   if (g_thread_supported())
706     {
707 #ifndef G_OS_WIN32
708       close (context->wake_up_pipe[0]);
709       close (context->wake_up_pipe[1]);
710 #else
711       CloseHandle (context->wake_up_semaphore);
712 #endif
713     } 
714   else
715     main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe, 
716                                                  context);
717
718   if (context->cond != NULL)
719     g_cond_free (context->cond);
720 #endif
721   
722   g_free (context);
723 }
724
725 #ifdef G_THREADS_ENABLED
726 static void 
727 g_main_context_init_pipe (GMainContext *context)
728 {
729 # ifndef G_OS_WIN32
730   if (context->wake_up_pipe[0] != -1)
731     return;
732   if (pipe (context->wake_up_pipe) < 0)
733     g_error ("Cannot create pipe main loop wake-up: %s\n",
734              g_strerror (errno));
735  
736   fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
737   fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
738
739   context->wake_up_rec.fd = context->wake_up_pipe[0];
740   context->wake_up_rec.events = G_IO_IN;
741 # else
742   if (context->wake_up_semaphore != NULL)
743     return;
744   context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
745   if (context->wake_up_semaphore == NULL)
746     g_error ("Cannot create wake-up semaphore: %s",
747              g_win32_error_message (GetLastError ()));
748   context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
749   context->wake_up_rec.events = G_IO_IN;
750
751   if (g_main_poll_debug)
752     g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
753 # endif
754   g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
755 }
756
757 void
758 _g_main_thread_init (void)
759 {
760   GSList *curr = main_contexts_without_pipe;
761   while (curr)
762     {
763       g_main_context_init_pipe ((GMainContext *)curr->data);
764       curr = curr->next;
765     }
766   g_slist_free (main_contexts_without_pipe);
767   main_contexts_without_pipe = NULL;  
768 }
769 #endif /* G_THREADS_ENABLED */
770
771 /**
772  * g_main_context_new:
773  * 
774  * Creates a new #GMainContext structure.
775  * 
776  * Return value: the new #GMainContext
777  **/
778 GMainContext *
779 g_main_context_new (void)
780 {
781   GMainContext *context = g_new0 (GMainContext, 1);
782
783 #ifdef G_MAIN_POLL_DEBUG
784   {
785     static gboolean beenhere = FALSE;
786
787     if (!beenhere)
788       {
789         if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
790           g_main_poll_debug = TRUE;
791         beenhere = TRUE;
792       }
793   }
794 #endif
795
796 #ifdef G_THREADS_ENABLED
797   g_static_mutex_init (&context->mutex);
798
799   context->owner = NULL;
800   context->waiters = NULL;
801
802 # ifndef G_OS_WIN32
803   context->wake_up_pipe[0] = -1;
804   context->wake_up_pipe[1] = -1;
805 # else
806   context->wake_up_semaphore = NULL;
807 # endif
808 #endif
809
810   context->ref_count = 1;
811
812   context->next_id = 1;
813   
814   context->source_list = NULL;
815   
816 #if HAVE_POLL
817   context->poll_func = (GPollFunc)poll;
818 #else
819   context->poll_func = g_poll;
820 #endif
821   
822   context->cached_poll_array = NULL;
823   context->cached_poll_array_size = 0;
824   
825   context->pending_dispatches = g_ptr_array_new ();
826   
827   context->time_is_current = FALSE;
828   
829 #ifdef G_THREADS_ENABLED
830   if (g_thread_supported ())
831     g_main_context_init_pipe (context);
832   else
833     main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe, 
834                                                   context);
835 #endif
836
837   G_LOCK (main_context_list);
838   main_context_list = g_slist_append (main_context_list, context);
839
840 #ifdef G_MAIN_POLL_DEBUG
841   if (g_main_poll_debug)
842     g_print ("created context=%p\n", context);
843 #endif
844
845   G_UNLOCK (main_context_list);
846
847   return context;
848 }
849
850 /**
851  * g_main_context_default:
852  * 
853  * Returns the default main context. This is the main context used
854  * for main loop functions when a main loop is not explicitly
855  * specified.
856  * 
857  * Return value: the default main context.
858  **/
859 GMainContext *
860 g_main_context_default (void)
861 {
862   /* Slow, but safe */
863   
864   G_LOCK (main_loop);
865
866   if (!default_main_context)
867     {
868       default_main_context = g_main_context_new ();
869 #ifdef G_MAIN_POLL_DEBUG
870       if (g_main_poll_debug)
871         g_print ("default context=%p\n", default_main_context);
872 #endif
873     }
874
875   G_UNLOCK (main_loop);
876
877   return default_main_context;
878 }
879
880 /* Hooks for adding to the main loop */
881
882 /**
883  * g_source_new:
884  * @source_funcs: structure containing functions that implement
885  *                the sources behavior.
886  * @struct_size: size of the #GSource structure to create.
887  * 
888  * Creates a new #GSource structure. The size is specified to
889  * allow creating structures derived from #GSource that contain
890  * additional data. The size passed in must be at least
891  * <literal>sizeof (GSource)</literal>.
892  * 
893  * The source will not initially be associated with any #GMainContext
894  * and must be added to one with g_source_attach() before it will be
895  * executed.
896  * 
897  * Return value: the newly-created #GSource.
898  **/
899 GSource *
900 g_source_new (GSourceFuncs *source_funcs,
901               guint         struct_size)
902 {
903   GSource *source;
904
905   g_return_val_if_fail (source_funcs != NULL, NULL);
906   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
907   
908   source = (GSource*) g_malloc0 (struct_size);
909
910   source->source_funcs = source_funcs;
911   source->ref_count = 1;
912   
913   source->priority = G_PRIORITY_DEFAULT;
914
915   source->flags = G_HOOK_FLAG_ACTIVE;
916
917   /* NULL/0 initialization for all other fields */
918   
919   return source;
920 }
921
922 /* Holds context's lock
923  */
924 static void
925 g_source_list_add (GSource      *source,
926                    GMainContext *context)
927 {
928   GSource *tmp_source, *last_source;
929   
930   last_source = NULL;
931   tmp_source = context->source_list;
932   while (tmp_source && tmp_source->priority <= source->priority)
933     {
934       last_source = tmp_source;
935       tmp_source = tmp_source->next;
936     }
937
938   source->next = tmp_source;
939   if (tmp_source)
940     tmp_source->prev = source;
941   
942   source->prev = last_source;
943   if (last_source)
944     last_source->next = source;
945   else
946     context->source_list = source;
947 }
948
949 /* Holds context's lock
950  */
951 static void
952 g_source_list_remove (GSource      *source,
953                       GMainContext *context)
954 {
955   if (source->prev)
956     source->prev->next = source->next;
957   else
958     context->source_list = source->next;
959
960   if (source->next)
961     source->next->prev = source->prev;
962
963   source->prev = NULL;
964   source->next = NULL;
965 }
966
967 /**
968  * g_source_attach:
969  * @source: a #GSource
970  * @context: a #GMainContext (if %NULL, the default context will be used)
971  * 
972  * Adds a #GSource to a @context so that it will be executed within
973  * that context.
974  *
975  * Return value: the ID (greater than 0) for the source within the 
976  *   #GMainContext. 
977  **/
978 guint
979 g_source_attach (GSource      *source,
980                  GMainContext *context)
981 {
982   guint result = 0;
983   GSList *tmp_list;
984
985   g_return_val_if_fail (source->context == NULL, 0);
986   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
987   
988   if (!context)
989     context = g_main_context_default ();
990
991   LOCK_CONTEXT (context);
992
993   source->context = context;
994   result = source->source_id = context->next_id++;
995
996   source->ref_count++;
997   g_source_list_add (source, context);
998
999   tmp_list = source->poll_fds;
1000   while (tmp_list)
1001     {
1002       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1003       tmp_list = tmp_list->next;
1004     }
1005
1006 #ifdef G_THREADS_ENABLED
1007   /* Now wake up the main loop if it is waiting in the poll() */
1008   g_main_context_wakeup_unlocked (context);
1009 #endif
1010
1011   UNLOCK_CONTEXT (context);
1012
1013   return result;
1014 }
1015
1016 static void
1017 g_source_destroy_internal (GSource      *source,
1018                            GMainContext *context,
1019                            gboolean      have_lock)
1020 {
1021   if (!have_lock)
1022     LOCK_CONTEXT (context);
1023   
1024   if (!SOURCE_DESTROYED (source))
1025     {
1026       GSList *tmp_list;
1027       gpointer old_cb_data;
1028       GSourceCallbackFuncs *old_cb_funcs;
1029       
1030       source->flags &= ~G_HOOK_FLAG_ACTIVE;
1031
1032       old_cb_data = source->callback_data;
1033       old_cb_funcs = source->callback_funcs;
1034
1035       source->callback_data = NULL;
1036       source->callback_funcs = NULL;
1037
1038       if (old_cb_funcs)
1039         {
1040           UNLOCK_CONTEXT (context);
1041           old_cb_funcs->unref (old_cb_data);
1042           LOCK_CONTEXT (context);
1043         }
1044
1045       if (!SOURCE_BLOCKED (source))
1046         {
1047           tmp_list = source->poll_fds;
1048           while (tmp_list)
1049             {
1050               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1051               tmp_list = tmp_list->next;
1052             }
1053         }
1054           
1055       g_source_unref_internal (source, context, TRUE);
1056     }
1057
1058   if (!have_lock)
1059     UNLOCK_CONTEXT (context);
1060 }
1061
1062 /**
1063  * g_source_destroy:
1064  * @source: a #GSource
1065  * 
1066  * Removes a source from its #GMainContext, if any, and mark it as
1067  * destroyed.  The source cannot be subsequently added to another
1068  * context.
1069  **/
1070 void
1071 g_source_destroy (GSource *source)
1072 {
1073   GMainContext *context;
1074   
1075   g_return_if_fail (source != NULL);
1076   
1077   context = source->context;
1078   
1079   if (context)
1080     g_source_destroy_internal (source, context, FALSE);
1081   else
1082     source->flags &= ~G_HOOK_FLAG_ACTIVE;
1083 }
1084
1085 /**
1086  * g_source_get_id:
1087  * @source: a #GSource
1088  * 
1089  * Returns the numeric ID for a particular source. The ID of a source
1090  * is a positive integer which is unique within a particular main loop 
1091  * context. The reverse
1092  * mapping from ID to source is done by g_main_context_find_source_by_id().
1093  *
1094  * Return value: the ID (greater than 0) for the source
1095  **/
1096 guint
1097 g_source_get_id (GSource *source)
1098 {
1099   guint result;
1100   
1101   g_return_val_if_fail (source != NULL, 0);
1102   g_return_val_if_fail (source->context != NULL, 0);
1103
1104   LOCK_CONTEXT (source->context);
1105   result = source->source_id;
1106   UNLOCK_CONTEXT (source->context);
1107   
1108   return result;
1109 }
1110
1111 /**
1112  * g_source_get_context:
1113  * @source: a #GSource
1114  * 
1115  * Gets the #GMainContext with which the source is associated.
1116  * Calling this function on a destroyed source is an error.
1117  * 
1118  * Return value: the #GMainContext with which the source is associated,
1119  *               or %NULL if the context has not yet been added
1120  *               to a source.
1121  **/
1122 GMainContext *
1123 g_source_get_context (GSource *source)
1124 {
1125   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1126
1127   return source->context;
1128 }
1129
1130 /**
1131  * g_source_add_poll:
1132  * @source:a #GSource 
1133  * @fd: a #GPollFD structure holding information about a file
1134  *      descriptor to watch.
1135  * 
1136  * Adds a file descriptor to the set of file descriptors polled for
1137  * this source. This is usually combined with g_source_new() to add an
1138  * event source. The event source's check function will typically test
1139  * the @revents field in the #GPollFD struct and return %TRUE if events need
1140  * to be processed.
1141  **/
1142 void
1143 g_source_add_poll (GSource *source,
1144                    GPollFD *fd)
1145 {
1146   GMainContext *context;
1147   
1148   g_return_if_fail (source != NULL);
1149   g_return_if_fail (fd != NULL);
1150   g_return_if_fail (!SOURCE_DESTROYED (source));
1151   
1152   context = source->context;
1153
1154   if (context)
1155     LOCK_CONTEXT (context);
1156   
1157   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1158
1159   if (context)
1160     {
1161       if (!SOURCE_BLOCKED (source))
1162         g_main_context_add_poll_unlocked (context, source->priority, fd);
1163       UNLOCK_CONTEXT (context);
1164     }
1165 }
1166
1167 /**
1168  * g_source_remove_poll:
1169  * @source:a #GSource 
1170  * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1171  * 
1172  * Removes a file descriptor from the set of file descriptors polled for
1173  * this source. 
1174  **/
1175 void
1176 g_source_remove_poll (GSource *source,
1177                       GPollFD *fd)
1178 {
1179   GMainContext *context;
1180   
1181   g_return_if_fail (source != NULL);
1182   g_return_if_fail (fd != NULL);
1183   g_return_if_fail (!SOURCE_DESTROYED (source));
1184   
1185   context = source->context;
1186
1187   if (context)
1188     LOCK_CONTEXT (context);
1189   
1190   source->poll_fds = g_slist_remove (source->poll_fds, fd);
1191
1192   if (context)
1193     {
1194       if (!SOURCE_BLOCKED (source))
1195         g_main_context_remove_poll_unlocked (context, fd);
1196       UNLOCK_CONTEXT (context);
1197     }
1198 }
1199
1200 /**
1201  * g_source_set_callback_indirect:
1202  * @source: the source
1203  * @callback_data: pointer to callback data "object"
1204  * @callback_funcs: functions for reference counting @callback_data
1205  *                  and getting the callback and data
1206  * 
1207  * Sets the callback function storing the data as a refcounted callback
1208  * "object". This is used internally. Note that calling 
1209  * g_source_set_callback_indirect() assumes
1210  * an initial reference count on @callback_data, and thus
1211  * @callback_funcs->unref will eventually be called once more
1212  * than @callback_funcs->ref.
1213  **/
1214 void
1215 g_source_set_callback_indirect (GSource              *source,
1216                                 gpointer              callback_data,
1217                                 GSourceCallbackFuncs *callback_funcs)
1218 {
1219   GMainContext *context;
1220   gpointer old_cb_data;
1221   GSourceCallbackFuncs *old_cb_funcs;
1222   
1223   g_return_if_fail (source != NULL);
1224   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1225
1226   context = source->context;
1227
1228   if (context)
1229     LOCK_CONTEXT (context);
1230
1231   old_cb_data = source->callback_data;
1232   old_cb_funcs = source->callback_funcs;
1233
1234   source->callback_data = callback_data;
1235   source->callback_funcs = callback_funcs;
1236   
1237   if (context)
1238     UNLOCK_CONTEXT (context);
1239   
1240   if (old_cb_funcs)
1241     old_cb_funcs->unref (old_cb_data);
1242 }
1243
1244 static void
1245 g_source_callback_ref (gpointer cb_data)
1246 {
1247   GSourceCallback *callback = cb_data;
1248
1249   callback->ref_count++;
1250 }
1251
1252
1253 static void
1254 g_source_callback_unref (gpointer cb_data)
1255 {
1256   GSourceCallback *callback = cb_data;
1257
1258   callback->ref_count--;
1259   if (callback->ref_count == 0)
1260     {
1261       if (callback->notify)
1262         callback->notify (callback->data);
1263       g_free (callback);
1264     }
1265 }
1266
1267 static void
1268 g_source_callback_get (gpointer     cb_data,
1269                        GSource     *source, 
1270                        GSourceFunc *func,
1271                        gpointer    *data)
1272 {
1273   GSourceCallback *callback = cb_data;
1274
1275   *func = callback->func;
1276   *data = callback->data;
1277 }
1278
1279 static GSourceCallbackFuncs g_source_callback_funcs = {
1280   g_source_callback_ref,
1281   g_source_callback_unref,
1282   g_source_callback_get,
1283 };
1284
1285 /**
1286  * g_source_set_callback:
1287  * @source: the source
1288  * @func: a callback function
1289  * @data: the data to pass to callback function
1290  * @notify: a function to call when @data is no longer in use, or %NULL.
1291  * 
1292  * Sets the callback function for a source. The callback for a source is
1293  * called from the source's dispatch function.
1294  *
1295  * The exact type of @func depends on the type of source; ie. you
1296  * should not count on @func being called with @data as its first
1297  * parameter.
1298  * 
1299  * Typically, you won't use this function. Instead use functions specific
1300  * to the type of source you are using.
1301  **/
1302 void
1303 g_source_set_callback (GSource        *source,
1304                        GSourceFunc     func,
1305                        gpointer        data,
1306                        GDestroyNotify  notify)
1307 {
1308   GSourceCallback *new_callback;
1309
1310   g_return_if_fail (source != NULL);
1311
1312   new_callback = g_new (GSourceCallback, 1);
1313
1314   new_callback->ref_count = 1;
1315   new_callback->func = func;
1316   new_callback->data = data;
1317   new_callback->notify = notify;
1318
1319   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1320 }
1321
1322
1323 /**
1324  * g_source_set_funcs:
1325  * @source: a #GSource
1326  * @funcs: the new #GSourceFuncs
1327  * 
1328  * Sets the source functions (can be used to override 
1329  * default implementations) of an unattached source.
1330  * 
1331  * Since: 2.12
1332  */
1333 void
1334 g_source_set_funcs (GSource     *source,
1335                    GSourceFuncs *funcs)
1336 {
1337   g_return_if_fail (source != NULL);
1338   g_return_if_fail (source->context == NULL);
1339   g_return_if_fail (source->ref_count > 0);
1340   g_return_if_fail (funcs != NULL);
1341
1342   source->source_funcs = funcs;
1343 }
1344
1345 /**
1346  * g_source_set_priority:
1347  * @source: a #GSource
1348  * @priority: the new priority.
1349  * 
1350  * Sets the priority of a source. While the main loop is being
1351  * run, a source will be dispatched if it is ready to be dispatched and no sources 
1352  * at a higher (numerically smaller) priority are ready to be dispatched.
1353  **/
1354 void
1355 g_source_set_priority (GSource  *source,
1356                        gint      priority)
1357 {
1358   GSList *tmp_list;
1359   GMainContext *context;
1360   
1361   g_return_if_fail (source != NULL);
1362
1363   context = source->context;
1364
1365   if (context)
1366     LOCK_CONTEXT (context);
1367   
1368   source->priority = priority;
1369
1370   if (context)
1371     {
1372       /* Remove the source from the context's source and then
1373        * add it back so it is sorted in the correct plcae
1374        */
1375       g_source_list_remove (source, source->context);
1376       g_source_list_add (source, source->context);
1377
1378       if (!SOURCE_BLOCKED (source))
1379         {
1380           tmp_list = source->poll_fds;
1381           while (tmp_list)
1382             {
1383               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1384               g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1385               
1386               tmp_list = tmp_list->next;
1387             }
1388         }
1389       
1390       UNLOCK_CONTEXT (source->context);
1391     }
1392 }
1393
1394 /**
1395  * g_source_get_priority:
1396  * @source: a #GSource
1397  * 
1398  * Gets the priority of a source.
1399  * 
1400  * Return value: the priority of the source
1401  **/
1402 gint
1403 g_source_get_priority (GSource *source)
1404 {
1405   g_return_val_if_fail (source != NULL, 0);
1406
1407   return source->priority;
1408 }
1409
1410 /**
1411  * g_source_set_can_recurse:
1412  * @source: a #GSource
1413  * @can_recurse: whether recursion is allowed for this source
1414  * 
1415  * Sets whether a source can be called recursively. If @can_recurse is
1416  * %TRUE, then while the source is being dispatched then this source
1417  * will be processed normally. Otherwise, all processing of this
1418  * source is blocked until the dispatch function returns.
1419  **/
1420 void
1421 g_source_set_can_recurse (GSource  *source,
1422                           gboolean  can_recurse)
1423 {
1424   GMainContext *context;
1425   
1426   g_return_if_fail (source != NULL);
1427
1428   context = source->context;
1429
1430   if (context)
1431     LOCK_CONTEXT (context);
1432   
1433   if (can_recurse)
1434     source->flags |= G_SOURCE_CAN_RECURSE;
1435   else
1436     source->flags &= ~G_SOURCE_CAN_RECURSE;
1437
1438   if (context)
1439     UNLOCK_CONTEXT (context);
1440 }
1441
1442 /**
1443  * g_source_get_can_recurse:
1444  * @source: a #GSource
1445  * 
1446  * Checks whether a source is allowed to be called recursively.
1447  * see g_source_set_can_recurse().
1448  * 
1449  * Return value: whether recursion is allowed.
1450  **/
1451 gboolean
1452 g_source_get_can_recurse (GSource  *source)
1453 {
1454   g_return_val_if_fail (source != NULL, FALSE);
1455   
1456   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1457 }
1458
1459 /**
1460  * g_source_ref:
1461  * @source: a #GSource
1462  * 
1463  * Increases the reference count on a source by one.
1464  * 
1465  * Return value: @source
1466  **/
1467 GSource *
1468 g_source_ref (GSource *source)
1469 {
1470   GMainContext *context;
1471   
1472   g_return_val_if_fail (source != NULL, NULL);
1473
1474   context = source->context;
1475
1476   if (context)
1477     LOCK_CONTEXT (context);
1478
1479   source->ref_count++;
1480
1481   if (context)
1482     UNLOCK_CONTEXT (context);
1483
1484   return source;
1485 }
1486
1487 /* g_source_unref() but possible to call within context lock
1488  */
1489 static void
1490 g_source_unref_internal (GSource      *source,
1491                          GMainContext *context,
1492                          gboolean      have_lock)
1493 {
1494   gpointer old_cb_data = NULL;
1495   GSourceCallbackFuncs *old_cb_funcs = NULL;
1496
1497   g_return_if_fail (source != NULL);
1498   
1499   if (!have_lock && context)
1500     LOCK_CONTEXT (context);
1501
1502   source->ref_count--;
1503   if (source->ref_count == 0)
1504     {
1505       old_cb_data = source->callback_data;
1506       old_cb_funcs = source->callback_funcs;
1507
1508       source->callback_data = NULL;
1509       source->callback_funcs = NULL;
1510
1511       if (context && !SOURCE_DESTROYED (source))
1512         {
1513           g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1514           source->ref_count++;
1515         }
1516       else if (context)
1517         g_source_list_remove (source, context);
1518
1519       if (source->source_funcs->finalize)
1520         source->source_funcs->finalize (source);
1521       
1522       g_slist_free (source->poll_fds);
1523       source->poll_fds = NULL;
1524       g_free (source);
1525     }
1526   
1527   if (!have_lock && context)
1528     UNLOCK_CONTEXT (context);
1529
1530   if (old_cb_funcs)
1531     {
1532       if (have_lock)
1533         UNLOCK_CONTEXT (context);
1534       
1535       old_cb_funcs->unref (old_cb_data);
1536
1537       if (have_lock)
1538         LOCK_CONTEXT (context);
1539     }
1540 }
1541
1542 /**
1543  * g_source_unref:
1544  * @source: a #GSource
1545  * 
1546  * Decreases the reference count of a source by one. If the
1547  * resulting reference count is zero the source and associated
1548  * memory will be destroyed. 
1549  **/
1550 void
1551 g_source_unref (GSource *source)
1552 {
1553   g_return_if_fail (source != NULL);
1554
1555   g_source_unref_internal (source, source->context, FALSE);
1556 }
1557
1558 /**
1559  * g_main_context_find_source_by_id:
1560  * @context: a #GMainContext (if %NULL, the default context will be used)
1561  * @source_id: the source ID, as returned by g_source_get_id(). 
1562  * 
1563  * Finds a #GSource given a pair of context and ID.
1564  * 
1565  * Return value: the #GSource if found, otherwise, %NULL
1566  **/
1567 GSource *
1568 g_main_context_find_source_by_id (GMainContext *context,
1569                                   guint         source_id)
1570 {
1571   GSource *source;
1572   
1573   g_return_val_if_fail (source_id > 0, NULL);
1574
1575   if (context == NULL)
1576     context = g_main_context_default ();
1577   
1578   LOCK_CONTEXT (context);
1579   
1580   source = context->source_list;
1581   while (source)
1582     {
1583       if (!SOURCE_DESTROYED (source) &&
1584           source->source_id == source_id)
1585         break;
1586       source = source->next;
1587     }
1588
1589   UNLOCK_CONTEXT (context);
1590
1591   return source;
1592 }
1593
1594 /**
1595  * g_main_context_find_source_by_funcs_user_data:
1596  * @context: a #GMainContext (if %NULL, the default context will be used).
1597  * @funcs: the @source_funcs passed to g_source_new().
1598  * @user_data: the user data from the callback.
1599  * 
1600  * Finds a source with the given source functions and user data.  If
1601  * multiple sources exist with the same source function and user data,
1602  * the first one found will be returned.
1603  * 
1604  * Return value: the source, if one was found, otherwise %NULL
1605  **/
1606 GSource *
1607 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1608                                                GSourceFuncs *funcs,
1609                                                gpointer      user_data)
1610 {
1611   GSource *source;
1612   
1613   g_return_val_if_fail (funcs != NULL, NULL);
1614
1615   if (context == NULL)
1616     context = g_main_context_default ();
1617   
1618   LOCK_CONTEXT (context);
1619
1620   source = context->source_list;
1621   while (source)
1622     {
1623       if (!SOURCE_DESTROYED (source) &&
1624           source->source_funcs == funcs &&
1625           source->callback_funcs)
1626         {
1627           GSourceFunc callback;
1628           gpointer callback_data;
1629
1630           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1631           
1632           if (callback_data == user_data)
1633             break;
1634         }
1635       source = source->next;
1636     }
1637
1638   UNLOCK_CONTEXT (context);
1639
1640   return source;
1641 }
1642
1643 /**
1644  * g_main_context_find_source_by_user_data:
1645  * @context: a #GMainContext
1646  * @user_data: the user_data for the callback.
1647  * 
1648  * Finds a source with the given user data for the callback.  If
1649  * multiple sources exist with the same user data, the first
1650  * one found will be returned.
1651  * 
1652  * Return value: the source, if one was found, otherwise %NULL
1653  **/
1654 GSource *
1655 g_main_context_find_source_by_user_data (GMainContext *context,
1656                                          gpointer      user_data)
1657 {
1658   GSource *source;
1659   
1660   if (context == NULL)
1661     context = g_main_context_default ();
1662   
1663   LOCK_CONTEXT (context);
1664
1665   source = context->source_list;
1666   while (source)
1667     {
1668       if (!SOURCE_DESTROYED (source) &&
1669           source->callback_funcs)
1670         {
1671           GSourceFunc callback;
1672           gpointer callback_data = NULL;
1673
1674           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1675
1676           if (callback_data == user_data)
1677             break;
1678         }
1679       source = source->next;
1680     }
1681
1682   UNLOCK_CONTEXT (context);
1683
1684   return source;
1685 }
1686
1687 /**
1688  * g_source_remove:
1689  * @tag: the ID of the source to remove.
1690  * 
1691  * Removes the source with the given id from the default main context. 
1692  * The id of
1693  * a #GSource is given by g_source_get_id(), or will be returned by the
1694  * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1695  * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1696  * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1697  *
1698  * See also g_source_destroy().
1699  *
1700  * Return value: %TRUE if the source was found and removed.
1701  **/
1702 gboolean
1703 g_source_remove (guint tag)
1704 {
1705   GSource *source;
1706   
1707   g_return_val_if_fail (tag > 0, FALSE);
1708
1709   source = g_main_context_find_source_by_id (NULL, tag);
1710   if (source)
1711     g_source_destroy (source);
1712
1713   return source != NULL;
1714 }
1715
1716 /**
1717  * g_source_remove_by_user_data:
1718  * @user_data: the user_data for the callback.
1719  * 
1720  * Removes a source from the default main loop context given the user
1721  * data for the callback. If multiple sources exist with the same user
1722  * data, only one will be destroyed.
1723  * 
1724  * Return value: %TRUE if a source was found and removed. 
1725  **/
1726 gboolean
1727 g_source_remove_by_user_data (gpointer user_data)
1728 {
1729   GSource *source;
1730   
1731   source = g_main_context_find_source_by_user_data (NULL, user_data);
1732   if (source)
1733     {
1734       g_source_destroy (source);
1735       return TRUE;
1736     }
1737   else
1738     return FALSE;
1739 }
1740
1741 /**
1742  * g_source_remove_by_funcs_user_data:
1743  * @funcs: The @source_funcs passed to g_source_new()
1744  * @user_data: the user data for the callback
1745  * 
1746  * Removes a source from the default main loop context given the
1747  * source functions and user data. If multiple sources exist with the
1748  * same source functions and user data, only one will be destroyed.
1749  * 
1750  * Return value: %TRUE if a source was found and removed. 
1751  **/
1752 gboolean
1753 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1754                                     gpointer      user_data)
1755 {
1756   GSource *source;
1757
1758   g_return_val_if_fail (funcs != NULL, FALSE);
1759
1760   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1761   if (source)
1762     {
1763       g_source_destroy (source);
1764       return TRUE;
1765     }
1766   else
1767     return FALSE;
1768 }
1769
1770 /**
1771  * g_get_current_time:
1772  * @result: #GTimeVal structure in which to store current time.
1773  * 
1774  * Equivalent to the UNIX gettimeofday() function, but portable.
1775  **/
1776 void
1777 g_get_current_time (GTimeVal *result)
1778 {
1779 #ifndef G_OS_WIN32
1780   struct timeval r;
1781
1782   g_return_if_fail (result != NULL);
1783
1784   /*this is required on alpha, there the timeval structs are int's
1785     not longs and a cast only would fail horribly*/
1786   gettimeofday (&r, NULL);
1787   result->tv_sec = r.tv_sec;
1788   result->tv_usec = r.tv_usec;
1789 #else
1790   FILETIME ft;
1791   guint64 time64;
1792
1793   g_return_if_fail (result != NULL);
1794
1795   GetSystemTimeAsFileTime (&ft);
1796   memmove (&time64, &ft, sizeof (FILETIME));
1797
1798   /* Convert from 100s of nanoseconds since 1601-01-01
1799    * to Unix epoch. Yes, this is Y2038 unsafe.
1800    */
1801   time64 -= G_GINT64_CONSTANT (116444736000000000);
1802   time64 /= 10;
1803
1804   result->tv_sec = time64 / 1000000;
1805   result->tv_usec = time64 % 1000000;
1806 #endif
1807 }
1808
1809 static void
1810 g_main_dispatch_free (gpointer dispatch)
1811 {
1812   g_slice_free (GMainDispatch, dispatch);
1813 }
1814
1815 /* Running the main loop */
1816
1817 static GMainDispatch *
1818 get_dispatch (void)
1819 {
1820   static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1821   GMainDispatch *dispatch = g_static_private_get (&depth_private);
1822   if (!dispatch)
1823     {
1824       dispatch = g_slice_new0 (GMainDispatch);
1825       g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1826     }
1827
1828   return dispatch;
1829 }
1830
1831 /**
1832  * g_main_depth:
1833  *
1834  * Returns the depth of the stack of calls to
1835  * g_main_context_dispatch() on any #GMainContext in the current thread.
1836  *  That is, when called from the toplevel, it gives 0. When
1837  * called from within a callback from g_main_context_iteration()
1838  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
1839  * a callback to a recursive call to g_main_context_iterate(),
1840  * it returns 2. And so forth.
1841  *
1842  * This function is useful in a situation like the following:
1843  * Imagine an extremely simple "garbage collected" system.
1844  *
1845  * |[
1846  * static GList *free_list;
1847  * 
1848  * gpointer
1849  * allocate_memory (gsize size)
1850  * { 
1851  *   gpointer result = g_malloc (size);
1852  *   free_list = g_list_prepend (free_list, result);
1853  *   return result;
1854  * }
1855  * 
1856  * void
1857  * free_allocated_memory (void)
1858  * {
1859  *   GList *l;
1860  *   for (l = free_list; l; l = l->next);
1861  *     g_free (l->data);
1862  *   g_list_free (free_list);
1863  *   free_list = NULL;
1864  *  }
1865  * 
1866  * [...]
1867  * 
1868  * while (TRUE); 
1869  *  {
1870  *    g_main_context_iteration (NULL, TRUE);
1871  *    free_allocated_memory();
1872  *   }
1873  * ]|
1874  *
1875  * This works from an application, however, if you want to do the same
1876  * thing from a library, it gets more difficult, since you no longer
1877  * control the main loop. You might think you can simply use an idle
1878  * function to make the call to free_allocated_memory(), but that
1879  * doesn't work, since the idle function could be called from a
1880  * recursive callback. This can be fixed by using g_main_depth()
1881  *
1882  * |[
1883  * gpointer
1884  * allocate_memory (gsize size)
1885  * { 
1886  *   FreeListBlock *block = g_new (FreeListBlock, 1);
1887  *   block->mem = g_malloc (size);
1888  *   block->depth = g_main_depth ();   
1889  *   free_list = g_list_prepend (free_list, block);
1890  *   return block->mem;
1891  * }
1892  * 
1893  * void
1894  * free_allocated_memory (void)
1895  * {
1896  *   GList *l;
1897  *   
1898  *   int depth = g_main_depth ();
1899  *   for (l = free_list; l; );
1900  *     {
1901  *       GList *next = l->next;
1902  *       FreeListBlock *block = l->data;
1903  *       if (block->depth > depth)
1904  *         {
1905  *           g_free (block->mem);
1906  *           g_free (block);
1907  *           free_list = g_list_delete_link (free_list, l);
1908  *         }
1909  *               
1910  *       l = next;
1911  *     }
1912  *   }
1913  * ]|
1914  *
1915  * There is a temptation to use g_main_depth() to solve
1916  * problems with reentrancy. For instance, while waiting for data
1917  * to be received from the network in response to a menu item,
1918  * the menu item might be selected again. It might seem that
1919  * one could make the menu item's callback return immediately
1920  * and do nothing if g_main_depth() returns a value greater than 1.
1921  * However, this should be avoided since the user then sees selecting
1922  * the menu item do nothing. Furthermore, you'll find yourself adding
1923  * these checks all over your code, since there are doubtless many,
1924  * many things that the user could do. Instead, you can use the
1925  * following techniques:
1926  *
1927  * <orderedlist>
1928  *  <listitem>
1929  *   <para>
1930  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
1931  *     the user from interacting with elements while the main
1932  *     loop is recursing.
1933  *   </para>
1934  *  </listitem>
1935  *  <listitem>
1936  *   <para>
1937  *     Avoid main loop recursion in situations where you can't handle
1938  *     arbitrary  callbacks. Instead, structure your code so that you
1939  *     simply return to the main loop and then get called again when
1940  *     there is more work to do.
1941  *   </para>
1942  *  </listitem>
1943  * </orderedlist>
1944  * 
1945  * Return value: The main loop recursion level in the current thread
1946  **/
1947 int
1948 g_main_depth (void)
1949 {
1950   GMainDispatch *dispatch = get_dispatch ();
1951   return dispatch->depth;
1952 }
1953
1954 /**
1955  * g_main_current_source:
1956  *
1957  * Returns the currently firing source for this thread.
1958  * 
1959  * Return value: The currently firing source or %NULL.
1960  *
1961  * Since: 2.12
1962  */
1963 GSource *
1964 g_main_current_source (void)
1965 {
1966   GMainDispatch *dispatch = get_dispatch ();
1967   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1968 }
1969
1970 /**
1971  * g_source_is_destroyed:
1972  * @source: a #GSource
1973  *
1974  * Returns whether @source has been destroyed.
1975  *
1976  * This is important when you operate upon your objects 
1977  * from within idle handlers, but may have freed the object 
1978  * before the dispatch of your idle handler.
1979  *
1980  * |[
1981  * static gboolean 
1982  * idle_callback (gpointer data)
1983  * {
1984  *   SomeWidget *self = data;
1985  *    
1986  *   GDK_THREADS_ENTER (<!-- -->);
1987  *   /<!-- -->* do stuff with self *<!-- -->/
1988  *   self->idle_id = 0;
1989  *   GDK_THREADS_LEAVE (<!-- -->);
1990  *    
1991  *   return FALSE;
1992  * }
1993  *  
1994  * static void 
1995  * some_widget_do_stuff_later (SomeWidget *self)
1996  * {
1997  *   self->idle_id = g_idle_add (idle_callback, self);
1998  * }
1999  *  
2000  * static void 
2001  * some_widget_finalize (GObject *object)
2002  * {
2003  *   SomeWidget *self = SOME_WIDGET (object);
2004  *    
2005  *   if (self->idle_id)
2006  *     g_source_remove (self->idle_id);
2007  *    
2008  *   G_OBJECT_CLASS (parent_class)->finalize (object);
2009  * }
2010  * ]|
2011  *
2012  * This will fail in a multi-threaded application if the 
2013  * widget is destroyed before the idle handler fires due 
2014  * to the use after free in the callback. A solution, to 
2015  * this particular problem, is to check to if the source
2016  * has already been destroy within the callback.
2017  *
2018  * |[
2019  * static gboolean 
2020  * idle_callback (gpointer data)
2021  * {
2022  *   SomeWidget *self = data;
2023  *   
2024  *   GDK_THREADS_ENTER ();
2025  *   if (!g_source_is_destroyed (g_main_current_source ()))
2026  *     {
2027  *       /<!-- -->* do stuff with self *<!-- -->/
2028  *     }
2029  *   GDK_THREADS_LEAVE ();
2030  *   
2031  *   return FALSE;
2032  * }
2033  * ]|
2034  *
2035  * Return value: %TRUE if the source has been destroyed
2036  *
2037  * Since: 2.12
2038  */
2039 gboolean
2040 g_source_is_destroyed (GSource *source)
2041 {
2042   return SOURCE_DESTROYED (source);
2043 }
2044
2045
2046 /* Temporarily remove all this source's file descriptors from the
2047  * poll(), so that if data comes available for one of the file descriptors
2048  * we don't continually spin in the poll()
2049  */
2050 /* HOLDS: source->context's lock */
2051 static void
2052 block_source (GSource *source)
2053 {
2054   GSList *tmp_list;
2055
2056   g_return_if_fail (!SOURCE_BLOCKED (source));
2057
2058   tmp_list = source->poll_fds;
2059   while (tmp_list)
2060     {
2061       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2062       tmp_list = tmp_list->next;
2063     }
2064 }
2065
2066 /* HOLDS: source->context's lock */
2067 static void
2068 unblock_source (GSource *source)
2069 {
2070   GSList *tmp_list;
2071   
2072   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2073   g_return_if_fail (!SOURCE_DESTROYED (source));
2074   
2075   tmp_list = source->poll_fds;
2076   while (tmp_list)
2077     {
2078       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2079       tmp_list = tmp_list->next;
2080     }
2081 }
2082
2083 /* HOLDS: context's lock */
2084 static void
2085 g_main_dispatch (GMainContext *context)
2086 {
2087   GMainDispatch *current = get_dispatch ();
2088   guint i;
2089
2090   for (i = 0; i < context->pending_dispatches->len; i++)
2091     {
2092       GSource *source = context->pending_dispatches->pdata[i];
2093
2094       context->pending_dispatches->pdata[i] = NULL;
2095       g_assert (source);
2096
2097       source->flags &= ~G_SOURCE_READY;
2098
2099       if (!SOURCE_DESTROYED (source))
2100         {
2101           gboolean was_in_call;
2102           gpointer user_data = NULL;
2103           GSourceFunc callback = NULL;
2104           GSourceCallbackFuncs *cb_funcs;
2105           gpointer cb_data;
2106           gboolean need_destroy;
2107
2108           gboolean (*dispatch) (GSource *,
2109                                 GSourceFunc,
2110                                 gpointer);
2111           GSList current_source_link;
2112
2113           dispatch = source->source_funcs->dispatch;
2114           cb_funcs = source->callback_funcs;
2115           cb_data = source->callback_data;
2116
2117           if (cb_funcs)
2118             cb_funcs->ref (cb_data);
2119           
2120           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2121             block_source (source);
2122           
2123           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2124           source->flags |= G_HOOK_FLAG_IN_CALL;
2125
2126           if (cb_funcs)
2127             cb_funcs->get (cb_data, source, &callback, &user_data);
2128
2129           UNLOCK_CONTEXT (context);
2130
2131           current->depth++;
2132           /* The on-stack allocation of the GSList is unconventional, but
2133            * we know that the lifetime of the link is bounded to this
2134            * function as the link is kept in a thread specific list and
2135            * not manipulated outside of this function and its descendants.
2136            * Avoiding the overhead of a g_slist_alloc() is useful as many
2137            * applications do little more than dispatch events.
2138            *
2139            * This is a performance hack - do not revert to g_slist_prepend()!
2140            */
2141           current_source_link.data = source;
2142           current_source_link.next = current->dispatching_sources;
2143           current->dispatching_sources = &current_source_link;
2144           need_destroy = ! dispatch (source,
2145                                      callback,
2146                                      user_data);
2147           g_assert (current->dispatching_sources == &current_source_link);
2148           current->dispatching_sources = current_source_link.next;
2149           current->depth--;
2150           
2151           if (cb_funcs)
2152             cb_funcs->unref (cb_data);
2153
2154           LOCK_CONTEXT (context);
2155           
2156           if (!was_in_call)
2157             source->flags &= ~G_HOOK_FLAG_IN_CALL;
2158
2159           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2160               !SOURCE_DESTROYED (source))
2161             unblock_source (source);
2162           
2163           /* Note: this depends on the fact that we can't switch
2164            * sources from one main context to another
2165            */
2166           if (need_destroy && !SOURCE_DESTROYED (source))
2167             {
2168               g_assert (source->context == context);
2169               g_source_destroy_internal (source, context, TRUE);
2170             }
2171         }
2172       
2173       SOURCE_UNREF (source, context);
2174     }
2175
2176   g_ptr_array_set_size (context->pending_dispatches, 0);
2177 }
2178
2179 /* Holds context's lock */
2180 static inline GSource *
2181 next_valid_source (GMainContext *context,
2182                    GSource      *source)
2183 {
2184   GSource *new_source = source ? source->next : context->source_list;
2185
2186   while (new_source)
2187     {
2188       if (!SOURCE_DESTROYED (new_source))
2189         {
2190           new_source->ref_count++;
2191           break;
2192         }
2193       
2194       new_source = new_source->next;
2195     }
2196
2197   if (source)
2198     SOURCE_UNREF (source, context);
2199           
2200   return new_source;
2201 }
2202
2203 /**
2204  * g_main_context_acquire:
2205  * @context: a #GMainContext
2206  * 
2207  * Tries to become the owner of the specified context.
2208  * If some other thread is the owner of the context,
2209  * returns %FALSE immediately. Ownership is properly
2210  * recursive: the owner can require ownership again
2211  * and will release ownership when g_main_context_release()
2212  * is called as many times as g_main_context_acquire().
2213  *
2214  * You must be the owner of a context before you
2215  * can call g_main_context_prepare(), g_main_context_query(),
2216  * g_main_context_check(), g_main_context_dispatch().
2217  * 
2218  * Return value: %TRUE if the operation succeeded, and
2219  *   this thread is now the owner of @context.
2220  **/
2221 gboolean 
2222 g_main_context_acquire (GMainContext *context)
2223 {
2224 #ifdef G_THREADS_ENABLED
2225   gboolean result = FALSE;
2226   GThread *self = G_THREAD_SELF;
2227
2228   if (context == NULL)
2229     context = g_main_context_default ();
2230   
2231   LOCK_CONTEXT (context);
2232
2233   if (!context->owner)
2234     {
2235       context->owner = self;
2236       g_assert (context->owner_count == 0);
2237     }
2238
2239   if (context->owner == self)
2240     {
2241       context->owner_count++;
2242       result = TRUE;
2243     }
2244
2245   UNLOCK_CONTEXT (context); 
2246   
2247   return result;
2248 #else /* !G_THREADS_ENABLED */
2249   return TRUE;
2250 #endif /* G_THREADS_ENABLED */
2251 }
2252
2253 /**
2254  * g_main_context_release:
2255  * @context: a #GMainContext
2256  * 
2257  * Releases ownership of a context previously acquired by this thread
2258  * with g_main_context_acquire(). If the context was acquired multiple
2259  * times, the ownership will be released only when g_main_context_release()
2260  * is called as many times as it was acquired.
2261  **/
2262 void
2263 g_main_context_release (GMainContext *context)
2264 {
2265 #ifdef G_THREADS_ENABLED
2266   if (context == NULL)
2267     context = g_main_context_default ();
2268   
2269   LOCK_CONTEXT (context);
2270
2271   context->owner_count--;
2272   if (context->owner_count == 0)
2273     {
2274       context->owner = NULL;
2275
2276       if (context->waiters)
2277         {
2278           GMainWaiter *waiter = context->waiters->data;
2279           gboolean loop_internal_waiter =
2280             (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2281           context->waiters = g_slist_delete_link (context->waiters,
2282                                                   context->waiters);
2283           if (!loop_internal_waiter)
2284             g_mutex_lock (waiter->mutex);
2285           
2286           g_cond_signal (waiter->cond);
2287           
2288           if (!loop_internal_waiter)
2289             g_mutex_unlock (waiter->mutex);
2290         }
2291     }
2292
2293   UNLOCK_CONTEXT (context); 
2294 #endif /* G_THREADS_ENABLED */
2295 }
2296
2297 /**
2298  * g_main_context_wait:
2299  * @context: a #GMainContext
2300  * @cond: a condition variable
2301  * @mutex: a mutex, currently held
2302  * 
2303  * Tries to become the owner of the specified context,
2304  * as with g_main_context_acquire(). But if another thread
2305  * is the owner, atomically drop @mutex and wait on @cond until 
2306  * that owner releases ownership or until @cond is signaled, then
2307  * try again (once) to become the owner.
2308  * 
2309  * Return value: %TRUE if the operation succeeded, and
2310  *   this thread is now the owner of @context.
2311  **/
2312 gboolean
2313 g_main_context_wait (GMainContext *context,
2314                      GCond        *cond,
2315                      GMutex       *mutex)
2316 {
2317 #ifdef G_THREADS_ENABLED
2318   gboolean result = FALSE;
2319   GThread *self = G_THREAD_SELF;
2320   gboolean loop_internal_waiter;
2321   
2322   if (context == NULL)
2323     context = g_main_context_default ();
2324
2325   loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2326   
2327   if (!loop_internal_waiter)
2328     LOCK_CONTEXT (context);
2329
2330   if (context->owner && context->owner != self)
2331     {
2332       GMainWaiter waiter;
2333
2334       waiter.cond = cond;
2335       waiter.mutex = mutex;
2336
2337       context->waiters = g_slist_append (context->waiters, &waiter);
2338       
2339       if (!loop_internal_waiter)
2340         UNLOCK_CONTEXT (context);
2341       g_cond_wait (cond, mutex);
2342       if (!loop_internal_waiter)      
2343         LOCK_CONTEXT (context);
2344
2345       context->waiters = g_slist_remove (context->waiters, &waiter);
2346     }
2347
2348   if (!context->owner)
2349     {
2350       context->owner = self;
2351       g_assert (context->owner_count == 0);
2352     }
2353
2354   if (context->owner == self)
2355     {
2356       context->owner_count++;
2357       result = TRUE;
2358     }
2359
2360   if (!loop_internal_waiter)
2361     UNLOCK_CONTEXT (context); 
2362   
2363   return result;
2364 #else /* !G_THREADS_ENABLED */
2365   return TRUE;
2366 #endif /* G_THREADS_ENABLED */
2367 }
2368
2369 /**
2370  * g_main_context_prepare:
2371  * @context: a #GMainContext
2372  * @priority: location to store priority of highest priority
2373  *            source already ready.
2374  * 
2375  * Prepares to poll sources within a main loop. The resulting information
2376  * for polling is determined by calling g_main_context_query ().
2377  * 
2378  * Return value: %TRUE if some source is ready to be dispatched
2379  *               prior to polling.
2380  **/
2381 gboolean
2382 g_main_context_prepare (GMainContext *context,
2383                         gint         *priority)
2384 {
2385   gint i;
2386   gint n_ready = 0;
2387   gint current_priority = G_MAXINT;
2388   GSource *source;
2389
2390   if (context == NULL)
2391     context = g_main_context_default ();
2392   
2393   LOCK_CONTEXT (context);
2394
2395   context->time_is_current = FALSE;
2396
2397   if (context->in_check_or_prepare)
2398     {
2399       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2400                  "prepare() member.");
2401       UNLOCK_CONTEXT (context);
2402       return FALSE;
2403     }
2404
2405 #ifdef G_THREADS_ENABLED
2406   if (context->poll_waiting)
2407     {
2408       g_warning("g_main_context_prepare(): main loop already active in another thread");
2409       UNLOCK_CONTEXT (context);
2410       return FALSE;
2411     }
2412   
2413   context->poll_waiting = TRUE;
2414 #endif /* G_THREADS_ENABLED */
2415
2416 #if 0
2417   /* If recursing, finish up current dispatch, before starting over */
2418   if (context->pending_dispatches)
2419     {
2420       if (dispatch)
2421         g_main_dispatch (context, &current_time);
2422       
2423       UNLOCK_CONTEXT (context);
2424       return TRUE;
2425     }
2426 #endif
2427
2428   /* If recursing, clear list of pending dispatches */
2429
2430   for (i = 0; i < context->pending_dispatches->len; i++)
2431     {
2432       if (context->pending_dispatches->pdata[i])
2433         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2434     }
2435   g_ptr_array_set_size (context->pending_dispatches, 0);
2436   
2437   /* Prepare all sources */
2438
2439   context->timeout = -1;
2440   
2441   source = next_valid_source (context, NULL);
2442   while (source)
2443     {
2444       gint source_timeout = -1;
2445
2446       if ((n_ready > 0) && (source->priority > current_priority))
2447         {
2448           SOURCE_UNREF (source, context);
2449           break;
2450         }
2451       if (SOURCE_BLOCKED (source))
2452         goto next;
2453
2454       if (!(source->flags & G_SOURCE_READY))
2455         {
2456           gboolean result;
2457           gboolean (*prepare)  (GSource  *source, 
2458                                 gint     *timeout);
2459
2460           prepare = source->source_funcs->prepare;
2461           context->in_check_or_prepare++;
2462           UNLOCK_CONTEXT (context);
2463
2464           result = (*prepare) (source, &source_timeout);
2465
2466           LOCK_CONTEXT (context);
2467           context->in_check_or_prepare--;
2468
2469           if (result)
2470             source->flags |= G_SOURCE_READY;
2471         }
2472
2473       if (source->flags & G_SOURCE_READY)
2474         {
2475           n_ready++;
2476           current_priority = source->priority;
2477           context->timeout = 0;
2478         }
2479       
2480       if (source_timeout >= 0)
2481         {
2482           if (context->timeout < 0)
2483             context->timeout = source_timeout;
2484           else
2485             context->timeout = MIN (context->timeout, source_timeout);
2486         }
2487
2488     next:
2489       source = next_valid_source (context, source);
2490     }
2491
2492   UNLOCK_CONTEXT (context);
2493   
2494   if (priority)
2495     *priority = current_priority;
2496   
2497   return (n_ready > 0);
2498 }
2499
2500 /**
2501  * g_main_context_query:
2502  * @context: a #GMainContext
2503  * @max_priority: maximum priority source to check
2504  * @timeout_: location to store timeout to be used in polling
2505  * @fds: location to store #GPollFD records that need to be polled.
2506  * @n_fds: length of @fds.
2507  * 
2508  * Determines information necessary to poll this main loop.
2509  * 
2510  * Return value: the number of records actually stored in @fds,
2511  *   or, if more than @n_fds records need to be stored, the number
2512  *   of records that need to be stored.
2513  **/
2514 gint
2515 g_main_context_query (GMainContext *context,
2516                       gint          max_priority,
2517                       gint         *timeout,
2518                       GPollFD      *fds,
2519                       gint          n_fds)
2520 {
2521   gint n_poll;
2522   GPollRec *pollrec;
2523   
2524   LOCK_CONTEXT (context);
2525
2526   pollrec = context->poll_records;
2527   n_poll = 0;
2528   while (pollrec && max_priority >= pollrec->priority)
2529     {
2530       /* We need to include entries with fd->events == 0 in the array because
2531        * otherwise if the application changes fd->events behind our back and 
2532        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2533        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2534        * this API, but it occurs in practice.) */
2535       if (n_poll < n_fds)
2536         {
2537           fds[n_poll].fd = pollrec->fd->fd;
2538           /* In direct contradiction to the Unix98 spec, IRIX runs into
2539            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2540            * flags in the events field of the pollfd while it should
2541            * just ignoring them. So we mask them out here.
2542            */
2543           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2544           fds[n_poll].revents = 0;
2545         }
2546
2547       pollrec = pollrec->next;
2548       n_poll++;
2549     }
2550
2551 #ifdef G_THREADS_ENABLED
2552   context->poll_changed = FALSE;
2553 #endif
2554   
2555   if (timeout)
2556     {
2557       *timeout = context->timeout;
2558       if (*timeout != 0)
2559         context->time_is_current = FALSE;
2560     }
2561   
2562   UNLOCK_CONTEXT (context);
2563
2564   return n_poll;
2565 }
2566
2567 /**
2568  * g_main_context_check:
2569  * @context: a #GMainContext
2570  * @max_priority: the maximum numerical priority of sources to check
2571  * @fds: array of #GPollFD's that was passed to the last call to
2572  *       g_main_context_query()
2573  * @n_fds: return value of g_main_context_query()
2574  * 
2575  * Passes the results of polling back to the main loop.
2576  * 
2577  * Return value: %TRUE if some sources are ready to be dispatched.
2578  **/
2579 gboolean
2580 g_main_context_check (GMainContext *context,
2581                       gint          max_priority,
2582                       GPollFD      *fds,
2583                       gint          n_fds)
2584 {
2585   GSource *source;
2586   GPollRec *pollrec;
2587   gint n_ready = 0;
2588   gint i;
2589    
2590   LOCK_CONTEXT (context);
2591
2592   if (context->in_check_or_prepare)
2593     {
2594       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2595                  "prepare() member.");
2596       UNLOCK_CONTEXT (context);
2597       return FALSE;
2598     }
2599   
2600 #ifdef G_THREADS_ENABLED
2601   if (!context->poll_waiting)
2602     {
2603 #ifndef G_OS_WIN32
2604       gchar a;
2605       read (context->wake_up_pipe[0], &a, 1);
2606 #endif
2607     }
2608   else
2609     context->poll_waiting = FALSE;
2610
2611   /* If the set of poll file descriptors changed, bail out
2612    * and let the main loop rerun
2613    */
2614   if (context->poll_changed)
2615     {
2616       UNLOCK_CONTEXT (context);
2617       return FALSE;
2618     }
2619 #endif /* G_THREADS_ENABLED */
2620   
2621   pollrec = context->poll_records;
2622   i = 0;
2623   while (i < n_fds)
2624     {
2625       if (pollrec->fd->events)
2626         pollrec->fd->revents = fds[i].revents;
2627
2628       pollrec = pollrec->next;
2629       i++;
2630     }
2631
2632   source = next_valid_source (context, NULL);
2633   while (source)
2634     {
2635       if ((n_ready > 0) && (source->priority > max_priority))
2636         {
2637           SOURCE_UNREF (source, context);
2638           break;
2639         }
2640       if (SOURCE_BLOCKED (source))
2641         goto next;
2642
2643       if (!(source->flags & G_SOURCE_READY))
2644         {
2645           gboolean result;
2646           gboolean (*check) (GSource  *source);
2647
2648           check = source->source_funcs->check;
2649           
2650           context->in_check_or_prepare++;
2651           UNLOCK_CONTEXT (context);
2652           
2653           result = (*check) (source);
2654           
2655           LOCK_CONTEXT (context);
2656           context->in_check_or_prepare--;
2657           
2658           if (result)
2659             source->flags |= G_SOURCE_READY;
2660         }
2661
2662       if (source->flags & G_SOURCE_READY)
2663         {
2664           source->ref_count++;
2665           g_ptr_array_add (context->pending_dispatches, source);
2666
2667           n_ready++;
2668
2669           /* never dispatch sources with less priority than the first
2670            * one we choose to dispatch
2671            */
2672           max_priority = source->priority;
2673         }
2674
2675     next:
2676       source = next_valid_source (context, source);
2677     }
2678
2679   UNLOCK_CONTEXT (context);
2680
2681   return n_ready > 0;
2682 }
2683
2684 /**
2685  * g_main_context_dispatch:
2686  * @context: a #GMainContext
2687  * 
2688  * Dispatches all pending sources.
2689  **/
2690 void
2691 g_main_context_dispatch (GMainContext *context)
2692 {
2693   LOCK_CONTEXT (context);
2694
2695   if (context->pending_dispatches->len > 0)
2696     {
2697       g_main_dispatch (context);
2698     }
2699
2700   UNLOCK_CONTEXT (context);
2701 }
2702
2703 /* HOLDS context lock */
2704 static gboolean
2705 g_main_context_iterate (GMainContext *context,
2706                         gboolean      block,
2707                         gboolean      dispatch,
2708                         GThread      *self)
2709 {
2710   gint max_priority;
2711   gint timeout;
2712   gboolean some_ready;
2713   gint nfds, allocated_nfds;
2714   GPollFD *fds = NULL;
2715   
2716   UNLOCK_CONTEXT (context);
2717
2718 #ifdef G_THREADS_ENABLED
2719   if (!g_main_context_acquire (context))
2720     {
2721       gboolean got_ownership;
2722       
2723       g_return_val_if_fail (g_thread_supported (), FALSE);
2724
2725       if (!block)
2726         return FALSE;
2727
2728       LOCK_CONTEXT (context);
2729       
2730       if (!context->cond)
2731         context->cond = g_cond_new ();
2732           
2733       got_ownership = g_main_context_wait (context,
2734                                            context->cond,
2735                                            g_static_mutex_get_mutex (&context->mutex));
2736
2737       if (!got_ownership)
2738         {
2739           UNLOCK_CONTEXT (context);
2740           return FALSE;
2741         }
2742     }
2743   else
2744     LOCK_CONTEXT (context);
2745 #endif /* G_THREADS_ENABLED */
2746   
2747   if (!context->cached_poll_array)
2748     {
2749       context->cached_poll_array_size = context->n_poll_records;
2750       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2751     }
2752
2753   allocated_nfds = context->cached_poll_array_size;
2754   fds = context->cached_poll_array;
2755   
2756   UNLOCK_CONTEXT (context);
2757
2758   g_main_context_prepare (context, &max_priority); 
2759   
2760   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
2761                                        allocated_nfds)) > allocated_nfds)
2762     {
2763       LOCK_CONTEXT (context);
2764       g_free (fds);
2765       context->cached_poll_array_size = allocated_nfds = nfds;
2766       context->cached_poll_array = fds = g_new (GPollFD, nfds);
2767       UNLOCK_CONTEXT (context);
2768     }
2769
2770   if (!block)
2771     timeout = 0;
2772   
2773   g_main_context_poll (context, timeout, max_priority, fds, nfds);
2774   
2775   some_ready = g_main_context_check (context, max_priority, fds, nfds);
2776   
2777   if (dispatch)
2778     g_main_context_dispatch (context);
2779   
2780 #ifdef G_THREADS_ENABLED
2781   g_main_context_release (context);
2782 #endif /* G_THREADS_ENABLED */    
2783
2784   LOCK_CONTEXT (context);
2785
2786   return some_ready;
2787 }
2788
2789 /**
2790  * g_main_context_pending:
2791  * @context: a #GMainContext (if %NULL, the default context will be used)
2792  *
2793  * Checks if any sources have pending events for the given context.
2794  * 
2795  * Return value: %TRUE if events are pending.
2796  **/
2797 gboolean 
2798 g_main_context_pending (GMainContext *context)
2799 {
2800   gboolean retval;
2801
2802   if (!context)
2803     context = g_main_context_default();
2804
2805   LOCK_CONTEXT (context);
2806   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2807   UNLOCK_CONTEXT (context);
2808   
2809   return retval;
2810 }
2811
2812 /**
2813  * g_main_context_iteration:
2814  * @context: a #GMainContext (if %NULL, the default context will be used) 
2815  * @may_block: whether the call may block.
2816  * 
2817  * Runs a single iteration for the given main loop. This involves
2818  * checking to see if any event sources are ready to be processed,
2819  * then if no events sources are ready and @may_block is %TRUE, waiting
2820  * for a source to become ready, then dispatching the highest priority
2821  * events sources that are ready. Otherwise, if @may_block is %FALSE 
2822  * sources are not waited to become ready, only those highest priority 
2823  * events sources will be dispatched (if any), that are ready at this 
2824  * given moment without further waiting.
2825  *
2826  * Note that even when @may_block is %TRUE, it is still possible for 
2827  * g_main_context_iteration() to return %FALSE, since the the wait may 
2828  * be interrupted for other reasons than an event source becoming ready.
2829  * 
2830  * Return value: %TRUE if events were dispatched.
2831  **/
2832 gboolean
2833 g_main_context_iteration (GMainContext *context, gboolean may_block)
2834 {
2835   gboolean retval;
2836
2837   if (!context)
2838     context = g_main_context_default();
2839   
2840   LOCK_CONTEXT (context);
2841   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2842   UNLOCK_CONTEXT (context);
2843   
2844   return retval;
2845 }
2846
2847 /**
2848  * g_main_loop_new:
2849  * @context: a #GMainContext  (if %NULL, the default context will be used).
2850  * @is_running: set to %TRUE to indicate that the loop is running. This
2851  * is not very important since calling g_main_loop_run() will set this to
2852  * %TRUE anyway.
2853  * 
2854  * Creates a new #GMainLoop structure.
2855  * 
2856  * Return value: a new #GMainLoop.
2857  **/
2858 GMainLoop *
2859 g_main_loop_new (GMainContext *context,
2860                  gboolean      is_running)
2861 {
2862   GMainLoop *loop;
2863
2864   if (!context)
2865     context = g_main_context_default();
2866   
2867   g_main_context_ref (context);
2868
2869   loop = g_new0 (GMainLoop, 1);
2870   loop->context = context;
2871   loop->is_running = is_running != FALSE;
2872   loop->ref_count = 1;
2873   
2874   return loop;
2875 }
2876
2877 /**
2878  * g_main_loop_ref:
2879  * @loop: a #GMainLoop
2880  * 
2881  * Increases the reference count on a #GMainLoop object by one.
2882  * 
2883  * Return value: @loop
2884  **/
2885 GMainLoop *
2886 g_main_loop_ref (GMainLoop *loop)
2887 {
2888   g_return_val_if_fail (loop != NULL, NULL);
2889   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2890
2891   g_atomic_int_inc (&loop->ref_count);
2892
2893   return loop;
2894 }
2895
2896 /**
2897  * g_main_loop_unref:
2898  * @loop: a #GMainLoop
2899  * 
2900  * Decreases the reference count on a #GMainLoop object by one. If
2901  * the result is zero, free the loop and free all associated memory.
2902  **/
2903 void
2904 g_main_loop_unref (GMainLoop *loop)
2905 {
2906   g_return_if_fail (loop != NULL);
2907   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2908
2909   if (!g_atomic_int_dec_and_test (&loop->ref_count))
2910     return;
2911
2912   g_main_context_unref (loop->context);
2913   g_free (loop);
2914 }
2915
2916 /**
2917  * g_main_loop_run:
2918  * @loop: a #GMainLoop
2919  * 
2920  * Runs a main loop until g_main_loop_quit() is called on the loop.
2921  * If this is called for the thread of the loop's #GMainContext,
2922  * it will process events from the loop, otherwise it will
2923  * simply wait.
2924  **/
2925 void 
2926 g_main_loop_run (GMainLoop *loop)
2927 {
2928   GThread *self = G_THREAD_SELF;
2929
2930   g_return_if_fail (loop != NULL);
2931   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2932
2933 #ifdef G_THREADS_ENABLED
2934   if (!g_main_context_acquire (loop->context))
2935     {
2936       gboolean got_ownership = FALSE;
2937       
2938       /* Another thread owns this context */
2939       if (!g_thread_supported ())
2940         {
2941           g_warning ("g_main_loop_run() was called from second thread but "
2942                      "g_thread_init() was never called.");
2943           return;
2944         }
2945       
2946       LOCK_CONTEXT (loop->context);
2947
2948       g_atomic_int_inc (&loop->ref_count);
2949
2950       if (!loop->is_running)
2951         loop->is_running = TRUE;
2952
2953       if (!loop->context->cond)
2954         loop->context->cond = g_cond_new ();
2955           
2956       while (loop->is_running && !got_ownership)
2957         got_ownership = g_main_context_wait (loop->context,
2958                                              loop->context->cond,
2959                                              g_static_mutex_get_mutex (&loop->context->mutex));
2960       
2961       if (!loop->is_running)
2962         {
2963           UNLOCK_CONTEXT (loop->context);
2964           if (got_ownership)
2965             g_main_context_release (loop->context);
2966           g_main_loop_unref (loop);
2967           return;
2968         }
2969
2970       g_assert (got_ownership);
2971     }
2972   else
2973     LOCK_CONTEXT (loop->context);
2974 #endif /* G_THREADS_ENABLED */ 
2975
2976   if (loop->context->in_check_or_prepare)
2977     {
2978       g_warning ("g_main_loop_run(): called recursively from within a source's "
2979                  "check() or prepare() member, iteration not possible.");
2980       return;
2981     }
2982
2983   g_atomic_int_inc (&loop->ref_count);
2984   loop->is_running = TRUE;
2985   while (loop->is_running)
2986     g_main_context_iterate (loop->context, TRUE, TRUE, self);
2987
2988   UNLOCK_CONTEXT (loop->context);
2989   
2990 #ifdef G_THREADS_ENABLED
2991   g_main_context_release (loop->context);
2992 #endif /* G_THREADS_ENABLED */    
2993   
2994   g_main_loop_unref (loop);
2995 }
2996
2997 /**
2998  * g_main_loop_quit:
2999  * @loop: a #GMainLoop
3000  * 
3001  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3002  * for the loop will return. 
3003  *
3004  * Note that sources that have already been dispatched when 
3005  * g_main_loop_quit() is called will still be executed.
3006  **/
3007 void 
3008 g_main_loop_quit (GMainLoop *loop)
3009 {
3010   g_return_if_fail (loop != NULL);
3011   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3012
3013   LOCK_CONTEXT (loop->context);
3014   loop->is_running = FALSE;
3015   g_main_context_wakeup_unlocked (loop->context);
3016
3017 #ifdef G_THREADS_ENABLED
3018   if (loop->context->cond)
3019     g_cond_broadcast (loop->context->cond);
3020 #endif /* G_THREADS_ENABLED */
3021
3022   UNLOCK_CONTEXT (loop->context);
3023 }
3024
3025 /**
3026  * g_main_loop_is_running:
3027  * @loop: a #GMainLoop.
3028  * 
3029  * Checks to see if the main loop is currently being run via g_main_loop_run().
3030  * 
3031  * Return value: %TRUE if the mainloop is currently being run.
3032  **/
3033 gboolean
3034 g_main_loop_is_running (GMainLoop *loop)
3035 {
3036   g_return_val_if_fail (loop != NULL, FALSE);
3037   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3038
3039   return loop->is_running;
3040 }
3041
3042 /**
3043  * g_main_loop_get_context:
3044  * @loop: a #GMainLoop.
3045  * 
3046  * Returns the #GMainContext of @loop.
3047  * 
3048  * Return value: the #GMainContext of @loop
3049  **/
3050 GMainContext *
3051 g_main_loop_get_context (GMainLoop *loop)
3052 {
3053   g_return_val_if_fail (loop != NULL, NULL);
3054   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3055  
3056   return loop->context;
3057 }
3058
3059 /* HOLDS: context's lock */
3060 static void
3061 g_main_context_poll (GMainContext *context,
3062                      gint          timeout,
3063                      gint          priority,
3064                      GPollFD      *fds,
3065                      gint          n_fds)
3066 {
3067 #ifdef  G_MAIN_POLL_DEBUG
3068   GTimer *poll_timer;
3069   GPollRec *pollrec;
3070   gint i;
3071 #endif
3072
3073   GPollFunc poll_func;
3074
3075   if (n_fds || timeout != 0)
3076     {
3077 #ifdef  G_MAIN_POLL_DEBUG
3078       if (g_main_poll_debug)
3079         {
3080           g_print ("polling context=%p n=%d timeout=%d\n",
3081                    context, n_fds, timeout);
3082           poll_timer = g_timer_new ();
3083         }
3084 #endif
3085
3086       LOCK_CONTEXT (context);
3087
3088       poll_func = context->poll_func;
3089       
3090       UNLOCK_CONTEXT (context);
3091       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3092         {
3093 #ifndef G_OS_WIN32
3094           g_warning ("poll(2) failed due to: %s.",
3095                      g_strerror (errno));
3096 #else
3097           /* If g_poll () returns -1, it has already called g_warning() */
3098 #endif
3099         }
3100       
3101 #ifdef  G_MAIN_POLL_DEBUG
3102       if (g_main_poll_debug)
3103         {
3104           LOCK_CONTEXT (context);
3105
3106           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3107                    n_fds,
3108                    timeout,
3109                    g_timer_elapsed (poll_timer, NULL));
3110           g_timer_destroy (poll_timer);
3111           pollrec = context->poll_records;
3112
3113           while (pollrec != NULL)
3114             {
3115               i = 0;
3116               while (i < n_fds)
3117                 {
3118                   if (fds[i].fd == pollrec->fd->fd &&
3119                       pollrec->fd->events &&
3120                       fds[i].revents)
3121                     {
3122                       g_print (" [" GPOLLFD_FORMAT " :", fds[i].fd);
3123                       if (fds[i].revents & G_IO_IN)
3124                         g_print ("i");
3125                       if (fds[i].revents & G_IO_OUT)
3126                         g_print ("o");
3127                       if (fds[i].revents & G_IO_PRI)
3128                         g_print ("p");
3129                       if (fds[i].revents & G_IO_ERR)
3130                         g_print ("e");
3131                       if (fds[i].revents & G_IO_HUP)
3132                         g_print ("h");
3133                       if (fds[i].revents & G_IO_NVAL)
3134                         g_print ("n");
3135                       g_print ("]");
3136                     }
3137                   i++;
3138                 }
3139               pollrec = pollrec->next;
3140             }
3141           g_print ("\n");
3142
3143           UNLOCK_CONTEXT (context);
3144         }
3145 #endif
3146     } /* if (n_fds || timeout != 0) */
3147 }
3148
3149 /**
3150  * g_main_context_add_poll:
3151  * @context: a #GMainContext (or %NULL for the default context)
3152  * @fd: a #GPollFD structure holding information about a file
3153  *      descriptor to watch.
3154  * @priority: the priority for this file descriptor which should be
3155  *      the same as the priority used for g_source_attach() to ensure that the
3156  *      file descriptor is polled whenever the results may be needed.
3157  * 
3158  * Adds a file descriptor to the set of file descriptors polled for
3159  * this context. This will very seldomly be used directly. Instead
3160  * a typical event source will use g_source_add_poll() instead.
3161  **/
3162 void
3163 g_main_context_add_poll (GMainContext *context,
3164                          GPollFD      *fd,
3165                          gint          priority)
3166 {
3167   if (!context)
3168     context = g_main_context_default ();
3169   
3170   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3171   g_return_if_fail (fd);
3172
3173   LOCK_CONTEXT (context);
3174   g_main_context_add_poll_unlocked (context, priority, fd);
3175   UNLOCK_CONTEXT (context);
3176 }
3177
3178 /* HOLDS: main_loop_lock */
3179 static void 
3180 g_main_context_add_poll_unlocked (GMainContext *context,
3181                                   gint          priority,
3182                                   GPollFD      *fd)
3183 {
3184   GPollRec *lastrec, *pollrec;
3185   GPollRec *newrec = g_slice_new (GPollRec);
3186
3187   /* This file descriptor may be checked before we ever poll */
3188   fd->revents = 0;
3189   newrec->fd = fd;
3190   newrec->priority = priority;
3191
3192   lastrec = NULL;
3193   pollrec = context->poll_records;
3194   while (pollrec && priority >= pollrec->priority)
3195     {
3196       lastrec = pollrec;
3197       pollrec = pollrec->next;
3198     }
3199   
3200   if (lastrec)
3201     lastrec->next = newrec;
3202   else
3203     context->poll_records = newrec;
3204
3205   newrec->next = pollrec;
3206
3207   context->n_poll_records++;
3208
3209 #ifdef G_THREADS_ENABLED
3210   context->poll_changed = TRUE;
3211
3212   /* Now wake up the main loop if it is waiting in the poll() */
3213   g_main_context_wakeup_unlocked (context);
3214 #endif
3215 }
3216
3217 /**
3218  * g_main_context_remove_poll:
3219  * @context:a #GMainContext 
3220  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3221  * 
3222  * Removes file descriptor from the set of file descriptors to be
3223  * polled for a particular context.
3224  **/
3225 void
3226 g_main_context_remove_poll (GMainContext *context,
3227                             GPollFD      *fd)
3228 {
3229   if (!context)
3230     context = g_main_context_default ();
3231   
3232   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3233   g_return_if_fail (fd);
3234
3235   LOCK_CONTEXT (context);
3236   g_main_context_remove_poll_unlocked (context, fd);
3237   UNLOCK_CONTEXT (context);
3238 }
3239
3240 static void
3241 g_main_context_remove_poll_unlocked (GMainContext *context,
3242                                      GPollFD      *fd)
3243 {
3244   GPollRec *pollrec, *lastrec;
3245
3246   lastrec = NULL;
3247   pollrec = context->poll_records;
3248
3249   while (pollrec)
3250     {
3251       if (pollrec->fd == fd)
3252         {
3253           if (lastrec != NULL)
3254             lastrec->next = pollrec->next;
3255           else
3256             context->poll_records = pollrec->next;
3257
3258           g_slice_free (GPollRec, pollrec);
3259
3260           context->n_poll_records--;
3261           break;
3262         }
3263       lastrec = pollrec;
3264       pollrec = pollrec->next;
3265     }
3266
3267 #ifdef G_THREADS_ENABLED
3268   context->poll_changed = TRUE;
3269   
3270   /* Now wake up the main loop if it is waiting in the poll() */
3271   g_main_context_wakeup_unlocked (context);
3272 #endif
3273 }
3274
3275 /**
3276  * g_source_get_current_time:
3277  * @source:  a #GSource
3278  * @timeval: #GTimeVal structure in which to store current time.
3279  * 
3280  * Gets the "current time" to be used when checking 
3281  * this source. The advantage of calling this function over
3282  * calling g_get_current_time() directly is that when 
3283  * checking multiple sources, GLib can cache a single value
3284  * instead of having to repeatedly get the system time.
3285  **/
3286 void
3287 g_source_get_current_time (GSource  *source,
3288                            GTimeVal *timeval)
3289 {
3290   GMainContext *context;
3291   
3292   g_return_if_fail (source->context != NULL);
3293  
3294   context = source->context;
3295
3296   LOCK_CONTEXT (context);
3297
3298   if (!context->time_is_current)
3299     {
3300       g_get_current_time (&context->current_time);
3301       context->time_is_current = TRUE;
3302     }
3303   
3304   *timeval = context->current_time;
3305   
3306   UNLOCK_CONTEXT (context);
3307 }
3308
3309 /**
3310  * g_main_context_set_poll_func:
3311  * @context: a #GMainContext
3312  * @func: the function to call to poll all file descriptors
3313  * 
3314  * Sets the function to use to handle polling of file descriptors. It
3315  * will be used instead of the poll() system call 
3316  * (or GLib's replacement function, which is used where 
3317  * poll() isn't available).
3318  *
3319  * This function could possibly be used to integrate the GLib event
3320  * loop with an external event loop.
3321  **/
3322 void
3323 g_main_context_set_poll_func (GMainContext *context,
3324                               GPollFunc     func)
3325 {
3326   if (!context)
3327     context = g_main_context_default ();
3328   
3329   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3330
3331   LOCK_CONTEXT (context);
3332   
3333   if (func)
3334     context->poll_func = func;
3335   else
3336     {
3337 #ifdef HAVE_POLL
3338       context->poll_func = (GPollFunc) poll;
3339 #else
3340       context->poll_func = (GPollFunc) g_poll;
3341 #endif
3342     }
3343
3344   UNLOCK_CONTEXT (context);
3345 }
3346
3347 /**
3348  * g_main_context_get_poll_func:
3349  * @context: a #GMainContext
3350  * 
3351  * Gets the poll function set by g_main_context_set_poll_func().
3352  * 
3353  * Return value: the poll function
3354  **/
3355 GPollFunc
3356 g_main_context_get_poll_func (GMainContext *context)
3357 {
3358   GPollFunc result;
3359   
3360   if (!context)
3361     context = g_main_context_default ();
3362   
3363   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3364
3365   LOCK_CONTEXT (context);
3366   result = context->poll_func;
3367   UNLOCK_CONTEXT (context);
3368
3369   return result;
3370 }
3371
3372 /* HOLDS: context's lock */
3373 /* Wake the main loop up from a poll() */
3374 static void
3375 g_main_context_wakeup_unlocked (GMainContext *context)
3376 {
3377 #ifdef G_THREADS_ENABLED
3378   if (g_thread_supported() && context->poll_waiting)
3379     {
3380       context->poll_waiting = FALSE;
3381 #ifndef G_OS_WIN32
3382       write (context->wake_up_pipe[1], "A", 1);
3383 #else
3384       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3385 #endif
3386     }
3387 #endif
3388 }
3389
3390 /**
3391  * g_main_context_wakeup:
3392  * @context: a #GMainContext
3393  * 
3394  * If @context is currently waiting in a poll(), interrupt
3395  * the poll(), and continue the iteration process.
3396  **/
3397 void
3398 g_main_context_wakeup (GMainContext *context)
3399 {
3400   if (!context)
3401     context = g_main_context_default ();
3402   
3403   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3404
3405   LOCK_CONTEXT (context);
3406   g_main_context_wakeup_unlocked (context);
3407   UNLOCK_CONTEXT (context);
3408 }
3409
3410 /**
3411  * g_main_context_is_owner:
3412  * @context: a #GMainContext
3413  * 
3414  * Determines whether this thread holds the (recursive)
3415  * ownership of this #GMaincontext. This is useful to
3416  * know before waiting on another thread that may be
3417  * blocking to get ownership of @context.
3418  *
3419  * Returns: %TRUE if current thread is owner of @context.
3420  *
3421  * Since: 2.10
3422  **/
3423 gboolean
3424 g_main_context_is_owner (GMainContext *context)
3425 {
3426   gboolean is_owner;
3427
3428   if (!context)
3429     context = g_main_context_default ();
3430
3431 #ifdef G_THREADS_ENABLED
3432   LOCK_CONTEXT (context);
3433   is_owner = context->owner == G_THREAD_SELF;
3434   UNLOCK_CONTEXT (context);
3435 #else
3436   is_owner = TRUE;
3437 #endif
3438
3439   return is_owner;
3440 }
3441
3442 /* Timeouts */
3443
3444 static void
3445 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3446                           GTimeVal       *current_time)
3447 {
3448   guint seconds = timeout_source->interval / 1000;
3449   guint msecs = timeout_source->interval - seconds * 1000;
3450
3451   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3452   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3453   if (timeout_source->expiration.tv_usec >= 1000000)
3454     {
3455       timeout_source->expiration.tv_usec -= 1000000;
3456       timeout_source->expiration.tv_sec++;
3457     }
3458   if (timer_perturb==-1)
3459     {
3460       /*
3461        * we want a per machine/session unique 'random' value; try the dbus
3462        * address first, that has a UUID in it. If there is no dbus, use the
3463        * hostname for hashing.
3464        */
3465       const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3466       if (!session_bus_address)
3467         session_bus_address = g_getenv ("HOSTNAME");
3468       if (session_bus_address)
3469         timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3470       else
3471         timer_perturb = 0;
3472     }
3473   if (timeout_source->granularity)
3474     {
3475       gint remainder;
3476       gint gran; /* in usecs */
3477       gint perturb;
3478
3479       gran = timeout_source->granularity * 1000;
3480       perturb = timer_perturb % gran;
3481       /*
3482        * We want to give each machine a per machine pertubation;
3483        * shift time back first, and forward later after the rounding
3484        */
3485
3486       timeout_source->expiration.tv_usec -= perturb;
3487       if (timeout_source->expiration.tv_usec < 0)
3488         {
3489           timeout_source->expiration.tv_usec += 1000000;
3490           timeout_source->expiration.tv_sec--;
3491         }
3492
3493       remainder = timeout_source->expiration.tv_usec % gran;
3494       if (remainder >= gran/4) /* round up */
3495         timeout_source->expiration.tv_usec += gran;
3496       timeout_source->expiration.tv_usec -= remainder;
3497       /* shift back */
3498       timeout_source->expiration.tv_usec += perturb;
3499
3500       /* the rounding may have overflown tv_usec */
3501       while (timeout_source->expiration.tv_usec > 1000000)
3502         {
3503           timeout_source->expiration.tv_usec -= 1000000;
3504           timeout_source->expiration.tv_sec++;
3505         }
3506     }
3507 }
3508
3509 static gboolean
3510 g_timeout_prepare (GSource *source,
3511                    gint    *timeout)
3512 {
3513   glong sec;
3514   glong msec;
3515   GTimeVal current_time;
3516   
3517   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3518
3519   g_source_get_current_time (source, &current_time);
3520
3521   sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3522   msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3523
3524   /* We do the following in a rather convoluted fashion to deal with
3525    * the fact that we don't have an integral type big enough to hold
3526    * the difference of two timevals in millseconds.
3527    */
3528   if (sec < 0 || (sec == 0 && msec < 0))
3529     msec = 0;
3530   else
3531     {
3532       glong interval_sec = timeout_source->interval / 1000;
3533       glong interval_msec = timeout_source->interval % 1000;
3534
3535       if (msec < 0)
3536         {
3537           msec += 1000;
3538           sec -= 1;
3539         }
3540       
3541       if (sec > interval_sec ||
3542           (sec == interval_sec && msec > interval_msec))
3543         {
3544           /* The system time has been set backwards, so we
3545            * reset the expiration time to now + timeout_source->interval;
3546            * this at least avoids hanging for long periods of time.
3547            */
3548           g_timeout_set_expiration (timeout_source, &current_time);
3549           msec = MIN (G_MAXINT, timeout_source->interval);
3550         }
3551       else
3552         {
3553           msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3554         }
3555     }
3556
3557   *timeout = (gint)msec;
3558   
3559   return msec == 0;
3560 }
3561
3562 static gboolean 
3563 g_timeout_check (GSource *source)
3564 {
3565   GTimeVal current_time;
3566   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3567
3568   g_source_get_current_time (source, &current_time);
3569   
3570   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3571           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3572            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3573 }
3574
3575 static gboolean
3576 g_timeout_dispatch (GSource     *source,
3577                     GSourceFunc  callback,
3578                     gpointer     user_data)
3579 {
3580   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3581
3582   if (!callback)
3583     {
3584       g_warning ("Timeout source dispatched without callback\n"
3585                  "You must call g_source_set_callback().");
3586       return FALSE;
3587     }
3588  
3589   if (callback (user_data))
3590     {
3591       GTimeVal current_time;
3592
3593       g_source_get_current_time (source, &current_time);
3594       g_timeout_set_expiration (timeout_source, &current_time);
3595
3596       return TRUE;
3597     }
3598   else
3599     return FALSE;
3600 }
3601
3602 /**
3603  * g_timeout_source_new:
3604  * @interval: the timeout interval in milliseconds.
3605  * 
3606  * Creates a new timeout source.
3607  *
3608  * The source will not initially be associated with any #GMainContext
3609  * and must be added to one with g_source_attach() before it will be
3610  * executed.
3611  * 
3612  * Return value: the newly-created timeout source
3613  **/
3614 GSource *
3615 g_timeout_source_new (guint interval)
3616 {
3617   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3618   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3619   GTimeVal current_time;
3620
3621   timeout_source->interval = interval;
3622
3623   g_get_current_time (&current_time);
3624   g_timeout_set_expiration (timeout_source, &current_time);
3625   
3626   return source;
3627 }
3628
3629 /**
3630  * g_timeout_source_new_seconds:
3631  * @interval: the timeout interval in seconds
3632  *
3633  * Creates a new timeout source.
3634  *
3635  * The source will not initially be associated with any #GMainContext
3636  * and must be added to one with g_source_attach() before it will be
3637  * executed.
3638  *
3639  * The scheduling granularity/accuracy of this timeout source will be
3640  * in seconds.
3641  *
3642  * Return value: the newly-created timeout source
3643  *
3644  * Since: 2.14  
3645  **/
3646 GSource *
3647 g_timeout_source_new_seconds (guint interval)
3648 {
3649   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3650   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3651   GTimeVal current_time;
3652
3653   timeout_source->interval = 1000*interval;
3654   timeout_source->granularity = 1000;
3655
3656   g_get_current_time (&current_time);
3657   g_timeout_set_expiration (timeout_source, &current_time);
3658
3659   return source;
3660 }
3661
3662
3663 /**
3664  * g_timeout_add_full:
3665  * @priority: the priority of the timeout source. Typically this will be in
3666  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3667  * @interval: the time between calls to the function, in milliseconds
3668  *             (1/1000ths of a second)
3669  * @function: function to call
3670  * @data:     data to pass to @function
3671  * @notify:   function to call when the timeout is removed, or %NULL
3672  * 
3673  * Sets a function to be called at regular intervals, with the given
3674  * priority.  The function is called repeatedly until it returns
3675  * %FALSE, at which point the timeout is automatically destroyed and
3676  * the function will not be called again.  The @notify function is
3677  * called when the timeout is destroyed.  The first call to the
3678  * function will be at the end of the first @interval.
3679  *
3680  * Note that timeout functions may be delayed, due to the processing of other
3681  * event sources. Thus they should not be relied on for precise timing.
3682  * After each call to the timeout function, the time of the next
3683  * timeout is recalculated based on the current time and the given interval
3684  * (it does not try to 'catch up' time lost in delays).
3685  * 
3686  * Return value: the ID (greater than 0) of the event source.
3687  **/
3688 guint
3689 g_timeout_add_full (gint           priority,
3690                     guint          interval,
3691                     GSourceFunc    function,
3692                     gpointer       data,
3693                     GDestroyNotify notify)
3694 {
3695   GSource *source;
3696   guint id;
3697   
3698   g_return_val_if_fail (function != NULL, 0);
3699
3700   source = g_timeout_source_new (interval);
3701
3702   if (priority != G_PRIORITY_DEFAULT)
3703     g_source_set_priority (source, priority);
3704
3705   g_source_set_callback (source, function, data, notify);
3706   id = g_source_attach (source, NULL);
3707   g_source_unref (source);
3708
3709   return id;
3710 }
3711
3712 /**
3713  * g_timeout_add:
3714  * @interval: the time between calls to the function, in milliseconds
3715  *             (1/1000ths of a second)
3716  * @function: function to call
3717  * @data:     data to pass to @function
3718  * 
3719  * Sets a function to be called at regular intervals, with the default
3720  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3721  * until it returns %FALSE, at which point the timeout is automatically
3722  * destroyed and the function will not be called again.  The first call
3723  * to the function will be at the end of the first @interval.
3724  *
3725  * Note that timeout functions may be delayed, due to the processing of other
3726  * event sources. Thus they should not be relied on for precise timing.
3727  * After each call to the timeout function, the time of the next
3728  * timeout is recalculated based on the current time and the given interval
3729  * (it does not try to 'catch up' time lost in delays).
3730  *
3731  * If you want to have a timer in the "seconds" range and do not care
3732  * about the exact time of the first call of the timer, use the
3733  * g_timeout_add_seconds() function; this function allows for more
3734  * optimizations and more efficient system power usage.
3735  *
3736  * Return value: the ID (greater than 0) of the event source.
3737  **/
3738 guint
3739 g_timeout_add (guint32        interval,
3740                GSourceFunc    function,
3741                gpointer       data)
3742 {
3743   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3744                              interval, function, data, NULL);
3745 }
3746
3747 /**
3748  * g_timeout_add_seconds_full:
3749  * @priority: the priority of the timeout source. Typically this will be in
3750  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3751  * @interval: the time between calls to the function, in seconds
3752  * @function: function to call
3753  * @data:     data to pass to @function
3754  * @notify:   function to call when the timeout is removed, or %NULL
3755  *
3756  * Sets a function to be called at regular intervals, with @priority.
3757  * The function is called repeatedly until it returns %FALSE, at which
3758  * point the timeout is automatically destroyed and the function will
3759  * not be called again.
3760  *
3761  * Unlike g_timeout_add(), this function operates at whole second granularity.
3762  * The initial starting point of the timer is determined by the implementation
3763  * and the implementation is expected to group multiple timers together so that
3764  * they fire all at the same time.
3765  * To allow this grouping, the @interval to the first timer is rounded
3766  * and can deviate up to one second from the specified interval.
3767  * Subsequent timer iterations will generally run at the specified interval.
3768  *
3769  * Note that timeout functions may be delayed, due to the processing of other
3770  * event sources. Thus they should not be relied on for precise timing.
3771  * After each call to the timeout function, the time of the next
3772  * timeout is recalculated based on the current time and the given @interval
3773  *
3774  * If you want timing more precise than whole seconds, use g_timeout_add()
3775  * instead.
3776  *
3777  * The grouping of timers to fire at the same time results in a more power
3778  * and CPU efficient behavior so if your timer is in multiples of seconds
3779  * and you don't require the first timer exactly one second from now, the
3780  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3781  *
3782  * Return value: the ID (greater than 0) of the event source.
3783  *
3784  * Since: 2.14
3785  **/
3786 guint
3787 g_timeout_add_seconds_full (gint           priority,
3788                             guint32        interval,
3789                             GSourceFunc    function,
3790                             gpointer       data,
3791                             GDestroyNotify notify)
3792 {
3793   GSource *source;
3794   guint id;
3795
3796   g_return_val_if_fail (function != NULL, 0);
3797
3798   source = g_timeout_source_new_seconds (interval);
3799
3800   if (priority != G_PRIORITY_DEFAULT)
3801     g_source_set_priority (source, priority);
3802
3803   g_source_set_callback (source, function, data, notify);
3804   id = g_source_attach (source, NULL);
3805   g_source_unref (source);
3806
3807   return id;
3808 }
3809
3810 /**
3811  * g_timeout_add_seconds:
3812  * @interval: the time between calls to the function, in seconds
3813  * @function: function to call
3814  * @data: data to pass to @function
3815  *
3816  * Sets a function to be called at regular intervals with the default
3817  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3818  * it returns %FALSE, at which point the timeout is automatically destroyed
3819  * and the function will not be called again.
3820  *
3821  * See g_timeout_add_seconds_full() for the differences between
3822  * g_timeout_add() and g_timeout_add_seconds().
3823  *
3824  * Return value: the ID (greater than 0) of the event source.
3825  *
3826  * Since: 2.14
3827  **/
3828 guint
3829 g_timeout_add_seconds (guint       interval,
3830                        GSourceFunc function,
3831                        gpointer    data)
3832 {
3833   g_return_val_if_fail (function != NULL, 0);
3834
3835   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3836 }
3837
3838 /* Child watch functions */
3839
3840 #ifdef G_OS_WIN32
3841
3842 static gboolean
3843 g_child_watch_prepare (GSource *source,
3844                        gint    *timeout)
3845 {
3846   *timeout = -1;
3847   return FALSE;
3848 }
3849
3850
3851 static gboolean 
3852 g_child_watch_check (GSource  *source)
3853 {
3854   GChildWatchSource *child_watch_source;
3855   gboolean child_exited;
3856
3857   child_watch_source = (GChildWatchSource *) source;
3858
3859   child_exited = child_watch_source->poll.revents & G_IO_IN;
3860
3861   if (child_exited)
3862     {
3863       DWORD child_status;
3864
3865       /*
3866        * Note: We do _not_ check for the special value of STILL_ACTIVE
3867        * since we know that the process has exited and doing so runs into
3868        * problems if the child process "happens to return STILL_ACTIVE(259)"
3869        * as Microsoft's Platform SDK puts it.
3870        */
3871       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3872         {
3873           gchar *emsg = g_win32_error_message (GetLastError ());
3874           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3875           g_free (emsg);
3876
3877           child_watch_source->child_status = -1;
3878         }
3879       else
3880         child_watch_source->child_status = child_status;
3881     }
3882
3883   return child_exited;
3884 }
3885
3886 #else /* G_OS_WIN32 */
3887
3888 static gboolean
3889 check_for_child_exited (GSource *source)
3890 {
3891   GChildWatchSource *child_watch_source;
3892   gint count;
3893
3894   /* protect against another SIGCHLD in the middle of this call */
3895   count = child_watch_count;
3896
3897   child_watch_source = (GChildWatchSource *) source;
3898
3899   if (child_watch_source->child_exited)
3900     return TRUE;
3901
3902   if (child_watch_source->count < count)
3903     {
3904       gint child_status;
3905
3906       if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3907         {
3908           child_watch_source->child_status = child_status;
3909           child_watch_source->child_exited = TRUE;
3910         }
3911       child_watch_source->count = count;
3912     }
3913
3914   return child_watch_source->child_exited;
3915 }
3916
3917 static gboolean
3918 g_child_watch_prepare (GSource *source,
3919                        gint    *timeout)
3920 {
3921   *timeout = -1;
3922
3923   return check_for_child_exited (source);
3924 }
3925
3926
3927 static gboolean 
3928 g_child_watch_check (GSource  *source)
3929 {
3930   return check_for_child_exited (source);
3931 }
3932
3933 #endif /* G_OS_WIN32 */
3934
3935 static gboolean
3936 g_child_watch_dispatch (GSource    *source, 
3937                         GSourceFunc callback,
3938                         gpointer    user_data)
3939 {
3940   GChildWatchSource *child_watch_source;
3941   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3942
3943   child_watch_source = (GChildWatchSource *) source;
3944
3945   if (!callback)
3946     {
3947       g_warning ("Child watch source dispatched without callback\n"
3948                  "You must call g_source_set_callback().");
3949       return FALSE;
3950     }
3951
3952   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3953
3954   /* We never keep a child watch source around as the child is gone */
3955   return FALSE;
3956 }
3957
3958 #ifndef G_OS_WIN32
3959
3960 static void
3961 g_child_watch_signal_handler (int signum)
3962 {
3963   child_watch_count ++;
3964
3965   if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3966     {
3967       write (child_watch_wake_up_pipe[1], "B", 1);
3968     }
3969   else
3970     {
3971       /* We count on the signal interrupting the poll in the same thread.
3972        */
3973     }
3974 }
3975  
3976 static void
3977 g_child_watch_source_init_single (void)
3978 {
3979   struct sigaction action;
3980
3981   g_assert (! g_thread_supported());
3982   g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3983
3984   child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3985
3986   action.sa_handler = g_child_watch_signal_handler;
3987   sigemptyset (&action.sa_mask);
3988   action.sa_flags = SA_NOCLDSTOP;
3989   sigaction (SIGCHLD, &action, NULL);
3990 }
3991
3992 static gpointer
3993 child_watch_helper_thread (gpointer data)
3994 {
3995   while (1)
3996     {
3997       gchar b[20];
3998       GSList *list;
3999
4000       read (child_watch_wake_up_pipe[0], b, 20);
4001
4002       /* We were woken up.  Wake up all other contexts in all other threads */
4003       G_LOCK (main_context_list);
4004       for (list = main_context_list; list; list = list->next)
4005         {
4006           GMainContext *context;
4007
4008           context = list->data;
4009           if (g_atomic_int_get (&context->ref_count) > 0)
4010             /* Due to racing conditions we can find ref_count == 0, in
4011              * that case, however, the context is still not destroyed
4012              * and no poll can be active, otherwise the ref_count
4013              * wouldn't be 0 */
4014             g_main_context_wakeup (context);
4015         }
4016       G_UNLOCK (main_context_list);
4017     }
4018
4019   return NULL;
4020 }
4021
4022 static void
4023 g_child_watch_source_init_multi_threaded (void)
4024 {
4025   GError *error = NULL;
4026   struct sigaction action;
4027
4028   g_assert (g_thread_supported());
4029
4030   if (pipe (child_watch_wake_up_pipe) < 0)
4031     g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4032   fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4033
4034   /* We create a helper thread that polls on the wakeup pipe indefinitely */
4035   /* FIXME: Think this through for races */
4036   if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4037     g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4038   child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4039  
4040   action.sa_handler = g_child_watch_signal_handler;
4041   sigemptyset (&action.sa_mask);
4042   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4043   sigaction (SIGCHLD, &action, NULL);
4044 }
4045
4046 static void
4047 g_child_watch_source_init_promote_single_to_threaded (void)
4048 {
4049   g_child_watch_source_init_multi_threaded ();
4050 }
4051
4052 static void
4053 g_child_watch_source_init (void)
4054 {
4055   if (g_thread_supported())
4056     {
4057       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4058         g_child_watch_source_init_multi_threaded ();
4059       else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4060         g_child_watch_source_init_promote_single_to_threaded ();
4061     }
4062   else
4063     {
4064       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4065         g_child_watch_source_init_single ();
4066     }
4067 }
4068
4069 #endif /* !G_OS_WIN32 */
4070
4071 /**
4072  * g_child_watch_source_new:
4073  * @pid: process to watch. On POSIX the pid of a child process. On
4074  * Windows a handle for a process (which doesn't have to be a child).
4075  * 
4076  * Creates a new child_watch source.
4077  *
4078  * The source will not initially be associated with any #GMainContext
4079  * and must be added to one with g_source_attach() before it will be
4080  * executed.
4081  * 
4082  * Note that child watch sources can only be used in conjunction with
4083  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4084  * flag is used.
4085  *
4086  * Note that on platforms where #GPid must be explicitly closed
4087  * (see g_spawn_close_pid()) @pid must not be closed while the
4088  * source is still active. Typically, you will want to call
4089  * g_spawn_close_pid() in the callback function for the source.
4090  *
4091  * Note further that using g_child_watch_source_new() is not 
4092  * compatible with calling <literal>waitpid(-1)</literal> in 
4093  * the application. Calling waitpid() for individual pids will
4094  * still work fine. 
4095  * 
4096  * Return value: the newly-created child watch source
4097  *
4098  * Since: 2.4
4099  **/
4100 GSource *
4101 g_child_watch_source_new (GPid pid)
4102 {
4103   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4104   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4105
4106 #ifdef G_OS_WIN32
4107   child_watch_source->poll.fd = (gintptr) pid;
4108   child_watch_source->poll.events = G_IO_IN;
4109
4110   g_source_add_poll (source, &child_watch_source->poll);
4111 #else /* G_OS_WIN32 */
4112   g_child_watch_source_init ();
4113 #endif /* G_OS_WIN32 */
4114
4115   child_watch_source->pid = pid;
4116
4117   return source;
4118 }
4119
4120 /**
4121  * g_child_watch_add_full:
4122  * @priority: the priority of the idle source. Typically this will be in the
4123  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4124  * @pid:      process to watch. On POSIX the pid of a child process. On
4125  * Windows a handle for a process (which doesn't have to be a child).
4126  * @function: function to call
4127  * @data:     data to pass to @function
4128  * @notify:   function to call when the idle is removed, or %NULL
4129  * 
4130  * Sets a function to be called when the child indicated by @pid 
4131  * exits, at the priority @priority.
4132  *
4133  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4134  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4135  * the spawn function for the child watching to work.
4136  * 
4137  * Note that on platforms where #GPid must be explicitly closed
4138  * (see g_spawn_close_pid()) @pid must not be closed while the
4139  * source is still active. Typically, you will want to call
4140  * g_spawn_close_pid() in the callback function for the source.
4141  * 
4142  * GLib supports only a single callback per process id.
4143  *
4144  * Return value: the ID (greater than 0) of the event source.
4145  *
4146  * Since: 2.4
4147  **/
4148 guint
4149 g_child_watch_add_full (gint            priority,
4150                         GPid            pid,
4151                         GChildWatchFunc function,
4152                         gpointer        data,
4153                         GDestroyNotify  notify)
4154 {
4155   GSource *source;
4156   guint id;
4157   
4158   g_return_val_if_fail (function != NULL, 0);
4159
4160   source = g_child_watch_source_new (pid);
4161
4162   if (priority != G_PRIORITY_DEFAULT)
4163     g_source_set_priority (source, priority);
4164
4165   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4166   id = g_source_attach (source, NULL);
4167   g_source_unref (source);
4168
4169   return id;
4170 }
4171
4172 /**
4173  * g_child_watch_add:
4174  * @pid:      process id to watch. On POSIX the pid of a child process. On
4175  * Windows a handle for a process (which doesn't have to be a child).
4176  * @function: function to call
4177  * @data:     data to pass to @function
4178  * 
4179  * Sets a function to be called when the child indicated by @pid 
4180  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4181  * 
4182  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4183  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4184  * the spawn function for the child watching to work.
4185  * 
4186  * Note that on platforms where #GPid must be explicitly closed
4187  * (see g_spawn_close_pid()) @pid must not be closed while the
4188  * source is still active. Typically, you will want to call
4189  * g_spawn_close_pid() in the callback function for the source.
4190  *
4191  * GLib supports only a single callback per process id.
4192  *
4193  * Return value: the ID (greater than 0) of the event source.
4194  *
4195  * Since: 2.4
4196  **/
4197 guint 
4198 g_child_watch_add (GPid            pid,
4199                    GChildWatchFunc function,
4200                    gpointer        data)
4201 {
4202   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4203 }
4204
4205
4206 /* Idle functions */
4207
4208 static gboolean 
4209 g_idle_prepare  (GSource  *source,
4210                  gint     *timeout)
4211 {
4212   *timeout = 0;
4213
4214   return TRUE;
4215 }
4216
4217 static gboolean 
4218 g_idle_check    (GSource  *source)
4219 {
4220   return TRUE;
4221 }
4222
4223 static gboolean
4224 g_idle_dispatch (GSource    *source, 
4225                  GSourceFunc callback,
4226                  gpointer    user_data)
4227 {
4228   if (!callback)
4229     {
4230       g_warning ("Idle source dispatched without callback\n"
4231                  "You must call g_source_set_callback().");
4232       return FALSE;
4233     }
4234   
4235   return callback (user_data);
4236 }
4237
4238 /**
4239  * g_idle_source_new:
4240  * 
4241  * Creates a new idle source.
4242  *
4243  * The source will not initially be associated with any #GMainContext
4244  * and must be added to one with g_source_attach() before it will be
4245  * executed. Note that the default priority for idle sources is
4246  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4247  * have a default priority of %G_PRIORITY_DEFAULT.
4248  * 
4249  * Return value: the newly-created idle source
4250  **/
4251 GSource *
4252 g_idle_source_new (void)
4253 {
4254   GSource *source;
4255
4256   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4257   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4258
4259   return source;
4260 }
4261
4262 /**
4263  * g_idle_add_full:
4264  * @priority: the priority of the idle source. Typically this will be in the
4265  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4266  * @function: function to call
4267  * @data:     data to pass to @function
4268  * @notify:   function to call when the idle is removed, or %NULL
4269  * 
4270  * Adds a function to be called whenever there are no higher priority
4271  * events pending.  If the function returns %FALSE it is automatically
4272  * removed from the list of event sources and will not be called again.
4273  * 
4274  * Return value: the ID (greater than 0) of the event source.
4275  **/
4276 guint 
4277 g_idle_add_full (gint           priority,
4278                  GSourceFunc    function,
4279                  gpointer       data,
4280                  GDestroyNotify notify)
4281 {
4282   GSource *source;
4283   guint id;
4284   
4285   g_return_val_if_fail (function != NULL, 0);
4286
4287   source = g_idle_source_new ();
4288
4289   if (priority != G_PRIORITY_DEFAULT_IDLE)
4290     g_source_set_priority (source, priority);
4291
4292   g_source_set_callback (source, function, data, notify);
4293   id = g_source_attach (source, NULL);
4294   g_source_unref (source);
4295
4296   return id;
4297 }
4298
4299 /**
4300  * g_idle_add:
4301  * @function: function to call 
4302  * @data: data to pass to @function.
4303  * 
4304  * Adds a function to be called whenever there are no higher priority
4305  * events pending to the default main loop. The function is given the
4306  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4307  * returns %FALSE it is automatically removed from the list of event
4308  * sources and will not be called again.
4309  * 
4310  * Return value: the ID (greater than 0) of the event source.
4311  **/
4312 guint 
4313 g_idle_add (GSourceFunc    function,
4314             gpointer       data)
4315 {
4316   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4317 }
4318
4319 /**
4320  * g_idle_remove_by_data:
4321  * @data: the data for the idle source's callback.
4322  * 
4323  * Removes the idle function with the given data.
4324  * 
4325  * Return value: %TRUE if an idle source was found and removed.
4326  **/
4327 gboolean
4328 g_idle_remove_by_data (gpointer data)
4329 {
4330   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4331 }
4332
4333 #define __G_MAIN_C__
4334 #include "galiasdef.c"