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