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