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