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