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