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