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