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