switch GTimeoutSource to use monotonic 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 void
3373 g_source_get_current_time (GSource  *source,
3374                            GTimeVal *timeval)
3375 {
3376   GMainContext *context;
3377   
3378   g_return_if_fail (source->context != NULL);
3379  
3380   context = source->context;
3381
3382   LOCK_CONTEXT (context);
3383
3384   if (!context->current_time_is_fresh)
3385     {
3386       g_get_current_time (&context->current_time);
3387       context->current_time_is_fresh = TRUE;
3388     }
3389   
3390   *timeval = context->current_time;
3391   
3392   UNLOCK_CONTEXT (context);
3393 }
3394
3395 /**
3396  * g_source_get_time:
3397  * @source: a #GSource
3398  * @timespec: #GTimeSpec structure in which to store the time
3399  *
3400  * Gets the time to be used when checking this source. The advantage of
3401  * calling this function over calling g_get_monotonic_time() directly is
3402  * that when checking multiple sources, GLib can cache a single value
3403  * instead of having to repeatedly get the system monotonic time.
3404  *
3405  * The time here is the system monotonic time, if available, or some
3406  * other reasonable alternative otherwise.  See g_get_monotonic_time().
3407  *
3408  * Since: 2.28
3409  **/
3410 void
3411 g_source_get_time (GSource   *source,
3412                    GTimeSpec *timespec)
3413 {
3414   GMainContext *context;
3415   
3416   g_return_if_fail (source->context != NULL);
3417  
3418   context = source->context;
3419
3420   LOCK_CONTEXT (context);
3421
3422   if (!context->time_is_fresh)
3423     {
3424       g_get_monotonic_time (&context->time);
3425       context->time_is_fresh = TRUE;
3426     }
3427   
3428   *timespec = context->time;
3429   
3430   UNLOCK_CONTEXT (context);
3431 }
3432  
3433 /**
3434  * g_main_context_set_poll_func:
3435  * @context: a #GMainContext
3436  * @func: the function to call to poll all file descriptors
3437  * 
3438  * Sets the function to use to handle polling of file descriptors. It
3439  * will be used instead of the poll() system call 
3440  * (or GLib's replacement function, which is used where 
3441  * poll() isn't available).
3442  *
3443  * This function could possibly be used to integrate the GLib event
3444  * loop with an external event loop.
3445  **/
3446 void
3447 g_main_context_set_poll_func (GMainContext *context,
3448                               GPollFunc     func)
3449 {
3450   if (!context)
3451     context = g_main_context_default ();
3452   
3453   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3454
3455   LOCK_CONTEXT (context);
3456   
3457   if (func)
3458     context->poll_func = func;
3459   else
3460     context->poll_func = g_poll;
3461
3462   UNLOCK_CONTEXT (context);
3463 }
3464
3465 /**
3466  * g_main_context_get_poll_func:
3467  * @context: a #GMainContext
3468  * 
3469  * Gets the poll function set by g_main_context_set_poll_func().
3470  * 
3471  * Return value: the poll function
3472  **/
3473 GPollFunc
3474 g_main_context_get_poll_func (GMainContext *context)
3475 {
3476   GPollFunc result;
3477   
3478   if (!context)
3479     context = g_main_context_default ();
3480   
3481   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3482
3483   LOCK_CONTEXT (context);
3484   result = context->poll_func;
3485   UNLOCK_CONTEXT (context);
3486
3487   return result;
3488 }
3489
3490 /* HOLDS: context's lock */
3491 /* Wake the main loop up from a poll() */
3492 static void
3493 g_main_context_wakeup_unlocked (GMainContext *context)
3494 {
3495 #ifdef G_THREADS_ENABLED
3496   if (g_thread_supported() && context->poll_waiting)
3497     {
3498       context->poll_waiting = FALSE;
3499 #ifndef G_OS_WIN32
3500       write (context->wake_up_pipe[1], "A", 1);
3501 #else
3502       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3503 #endif
3504     }
3505 #endif
3506 }
3507
3508 /**
3509  * g_main_context_wakeup:
3510  * @context: a #GMainContext
3511  * 
3512  * If @context is currently waiting in a poll(), interrupt
3513  * the poll(), and continue the iteration process.
3514  **/
3515 void
3516 g_main_context_wakeup (GMainContext *context)
3517 {
3518   if (!context)
3519     context = g_main_context_default ();
3520   
3521   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3522
3523   LOCK_CONTEXT (context);
3524   g_main_context_wakeup_unlocked (context);
3525   UNLOCK_CONTEXT (context);
3526 }
3527
3528 /**
3529  * g_main_context_is_owner:
3530  * @context: a #GMainContext
3531  * 
3532  * Determines whether this thread holds the (recursive)
3533  * ownership of this #GMaincontext. This is useful to
3534  * know before waiting on another thread that may be
3535  * blocking to get ownership of @context.
3536  *
3537  * Returns: %TRUE if current thread is owner of @context.
3538  *
3539  * Since: 2.10
3540  **/
3541 gboolean
3542 g_main_context_is_owner (GMainContext *context)
3543 {
3544   gboolean is_owner;
3545
3546   if (!context)
3547     context = g_main_context_default ();
3548
3549 #ifdef G_THREADS_ENABLED
3550   LOCK_CONTEXT (context);
3551   is_owner = context->owner == G_THREAD_SELF;
3552   UNLOCK_CONTEXT (context);
3553 #else
3554   is_owner = TRUE;
3555 #endif
3556
3557   return is_owner;
3558 }
3559
3560 /* Timeouts */
3561
3562 static void
3563 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3564                           GTimeSpec      *current_time)
3565 {
3566   guint seconds = timeout_source->interval / 1000;
3567   guint msecs = timeout_source->interval - seconds * 1000;
3568
3569   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3570   timeout_source->expiration.tv_nsec = current_time->tv_nsec + msecs * 1000000;
3571   if (timeout_source->expiration.tv_nsec >= 1000000000)
3572     {
3573       timeout_source->expiration.tv_nsec -= 1000000000;
3574       timeout_source->expiration.tv_sec++;
3575     }
3576   if (timer_perturb==-1)
3577     {
3578       /*
3579        * we want a per machine/session unique 'random' value; try the dbus
3580        * address first, that has a UUID in it. If there is no dbus, use the
3581        * hostname for hashing.
3582        */
3583       const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3584       if (!session_bus_address)
3585         session_bus_address = g_getenv ("HOSTNAME");
3586       if (session_bus_address)
3587         timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3588       else
3589         timer_perturb = 0;
3590     }
3591   if (timeout_source->granularity)
3592     {
3593       gint remainder;
3594       gint gran; /* in nsecs */
3595       gint perturb;
3596
3597       gran = timeout_source->granularity * 1000000;
3598       perturb = timer_perturb % gran;
3599       /*
3600        * We want to give each machine a per machine pertubation;
3601        * shift time back first, and forward later after the rounding
3602        */
3603
3604       timeout_source->expiration.tv_nsec -= perturb;
3605       if (timeout_source->expiration.tv_nsec < 0)
3606         {
3607           timeout_source->expiration.tv_nsec += 1000000000;
3608           timeout_source->expiration.tv_sec--;
3609         }
3610
3611       remainder = timeout_source->expiration.tv_nsec % gran;
3612       if (remainder >= gran/4) /* round up */
3613         timeout_source->expiration.tv_nsec += gran;
3614       timeout_source->expiration.tv_nsec -= remainder;
3615       /* shift back */
3616       timeout_source->expiration.tv_nsec += perturb;
3617
3618       /* the rounding may have overflown tv_nsec */
3619       while (timeout_source->expiration.tv_nsec > 1000000000)
3620         {
3621           timeout_source->expiration.tv_nsec -= 1000000000;
3622           timeout_source->expiration.tv_sec++;
3623         }
3624     }
3625 }
3626
3627 static gboolean
3628 g_timeout_prepare (GSource *source,
3629                    gint    *timeout)
3630 {
3631   glong sec;
3632   glong msec;
3633   GTimeSpec now;
3634   
3635   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3636
3637   g_source_get_time (source, &now);
3638
3639   sec = timeout_source->expiration.tv_sec - now.tv_sec;
3640   msec = (timeout_source->expiration.tv_nsec - now.tv_nsec) / 1000000;
3641
3642   /* We do the following in a rather convoluted fashion to deal with
3643    * the fact that we don't have an integral type big enough to hold
3644    * the difference of two timevals in millseconds.
3645    */
3646   if (sec < 0 || (sec == 0 && msec < 0))
3647     msec = 0;
3648   else
3649     {
3650       glong interval_sec = timeout_source->interval / 1000;
3651       glong interval_msec = timeout_source->interval % 1000;
3652
3653       if (msec < 0)
3654         {
3655           msec += 1000;
3656           sec -= 1;
3657         }
3658       
3659       if (sec > interval_sec ||
3660           (sec == interval_sec && msec > interval_msec))
3661         {
3662           /* The system time has been set backwards, so we
3663            * reset the expiration time to now + timeout_source->interval;
3664            * this at least avoids hanging for long periods of time.
3665            */
3666           g_timeout_set_expiration (timeout_source, &now);
3667           msec = MIN (G_MAXINT, timeout_source->interval);
3668         }
3669       else
3670         {
3671           msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3672         }
3673     }
3674
3675   *timeout = (gint)msec;
3676   
3677   return msec == 0;
3678 }
3679
3680 static gboolean 
3681 g_timeout_check (GSource *source)
3682 {
3683   GTimeSpec now;
3684   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3685
3686   g_source_get_time (source, &now);
3687   
3688   return ((timeout_source->expiration.tv_sec < now.tv_sec) ||
3689           ((timeout_source->expiration.tv_sec == now.tv_sec) &&
3690            (timeout_source->expiration.tv_nsec <= now.tv_nsec)));
3691 }
3692
3693 static gboolean
3694 g_timeout_dispatch (GSource     *source,
3695                     GSourceFunc  callback,
3696                     gpointer     user_data)
3697 {
3698   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3699
3700   if (!callback)
3701     {
3702       g_warning ("Timeout source dispatched without callback\n"
3703                  "You must call g_source_set_callback().");
3704       return FALSE;
3705     }
3706  
3707   if (callback (user_data))
3708     {
3709       GTimeSpec now;
3710
3711       g_source_get_time (source, &now);
3712       g_timeout_set_expiration (timeout_source, &now);
3713
3714       return TRUE;
3715     }
3716   else
3717     return FALSE;
3718 }
3719
3720 /**
3721  * g_timeout_source_new:
3722  * @interval: the timeout interval in milliseconds.
3723  * 
3724  * Creates a new timeout source.
3725  *
3726  * The source will not initially be associated with any #GMainContext
3727  * and must be added to one with g_source_attach() before it will be
3728  * executed.
3729  * 
3730  * Return value: the newly-created timeout source
3731  **/
3732 GSource *
3733 g_timeout_source_new (guint interval)
3734 {
3735   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3736   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3737   GTimeSpec now;
3738
3739   timeout_source->interval = interval;
3740
3741   g_get_monotonic_time (&now);
3742   g_timeout_set_expiration (timeout_source, &now);
3743   
3744   return source;
3745 }
3746
3747 /**
3748  * g_timeout_source_new_seconds:
3749  * @interval: the timeout interval in seconds
3750  *
3751  * Creates a new timeout source.
3752  *
3753  * The source will not initially be associated with any #GMainContext
3754  * and must be added to one with g_source_attach() before it will be
3755  * executed.
3756  *
3757  * The scheduling granularity/accuracy of this timeout source will be
3758  * in seconds.
3759  *
3760  * Return value: the newly-created timeout source
3761  *
3762  * Since: 2.14  
3763  **/
3764 GSource *
3765 g_timeout_source_new_seconds (guint interval)
3766 {
3767   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3768   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3769   GTimeSpec now;
3770
3771   timeout_source->interval = 1000*interval;
3772   timeout_source->granularity = 1000;
3773
3774   g_get_monotonic_time (&now);
3775   g_timeout_set_expiration (timeout_source, &now);
3776
3777   return source;
3778 }
3779
3780
3781 /**
3782  * g_timeout_add_full:
3783  * @priority: the priority of the timeout source. Typically this will be in
3784  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3785  * @interval: the time between calls to the function, in milliseconds
3786  *             (1/1000ths of a second)
3787  * @function: function to call
3788  * @data:     data to pass to @function
3789  * @notify:   function to call when the timeout is removed, or %NULL
3790  * 
3791  * Sets a function to be called at regular intervals, with the given
3792  * priority.  The function is called repeatedly until it returns
3793  * %FALSE, at which point the timeout is automatically destroyed and
3794  * the function will not be called again.  The @notify function is
3795  * called when the timeout is destroyed.  The first call to the
3796  * function will be at the end of the first @interval.
3797  *
3798  * Note that timeout functions may be delayed, due to the processing of other
3799  * event sources. Thus they should not be relied on for precise timing.
3800  * After each call to the timeout function, the time of the next
3801  * timeout is recalculated based on the current time and the given interval
3802  * (it does not try to 'catch up' time lost in delays).
3803  *
3804  * This internally creates a main loop source using g_timeout_source_new()
3805  * and attaches it to the main loop context using g_source_attach(). You can
3806  * do these steps manually if you need greater control.
3807  * 
3808  * Return value: the ID (greater than 0) of the event source.
3809  **/
3810 guint
3811 g_timeout_add_full (gint           priority,
3812                     guint          interval,
3813                     GSourceFunc    function,
3814                     gpointer       data,
3815                     GDestroyNotify notify)
3816 {
3817   GSource *source;
3818   guint id;
3819   
3820   g_return_val_if_fail (function != NULL, 0);
3821
3822   source = g_timeout_source_new (interval);
3823
3824   if (priority != G_PRIORITY_DEFAULT)
3825     g_source_set_priority (source, priority);
3826
3827   g_source_set_callback (source, function, data, notify);
3828   id = g_source_attach (source, NULL);
3829   g_source_unref (source);
3830
3831   return id;
3832 }
3833
3834 /**
3835  * g_timeout_add:
3836  * @interval: the time between calls to the function, in milliseconds
3837  *             (1/1000ths of a second)
3838  * @function: function to call
3839  * @data:     data to pass to @function
3840  * 
3841  * Sets a function to be called at regular intervals, with the default
3842  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3843  * until it returns %FALSE, at which point the timeout is automatically
3844  * destroyed and the function will not be called again.  The first call
3845  * to the function will be at the end of the first @interval.
3846  *
3847  * Note that timeout functions may be delayed, due to the processing of other
3848  * event sources. Thus they should not be relied on for precise timing.
3849  * After each call to the timeout function, the time of the next
3850  * timeout is recalculated based on the current time and the given interval
3851  * (it does not try to 'catch up' time lost in delays).
3852  *
3853  * If you want to have a timer in the "seconds" range and do not care
3854  * about the exact time of the first call of the timer, use the
3855  * g_timeout_add_seconds() function; this function allows for more
3856  * optimizations and more efficient system power usage.
3857  *
3858  * This internally creates a main loop source using g_timeout_source_new()
3859  * and attaches it to the main loop context using g_source_attach(). You can
3860  * do these steps manually if you need greater control.
3861  * 
3862  * Return value: the ID (greater than 0) of the event source.
3863  **/
3864 guint
3865 g_timeout_add (guint32        interval,
3866                GSourceFunc    function,
3867                gpointer       data)
3868 {
3869   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3870                              interval, function, data, NULL);
3871 }
3872
3873 /**
3874  * g_timeout_add_seconds_full:
3875  * @priority: the priority of the timeout source. Typically this will be in
3876  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3877  * @interval: the time between calls to the function, in seconds
3878  * @function: function to call
3879  * @data:     data to pass to @function
3880  * @notify:   function to call when the timeout is removed, or %NULL
3881  *
3882  * Sets a function to be called at regular intervals, with @priority.
3883  * The function is called repeatedly until it returns %FALSE, at which
3884  * point the timeout is automatically destroyed and the function will
3885  * not be called again.
3886  *
3887  * Unlike g_timeout_add(), this function operates at whole second granularity.
3888  * The initial starting point of the timer is determined by the implementation
3889  * and the implementation is expected to group multiple timers together so that
3890  * they fire all at the same time.
3891  * To allow this grouping, the @interval to the first timer is rounded
3892  * and can deviate up to one second from the specified interval.
3893  * Subsequent timer iterations will generally run at the specified interval.
3894  *
3895  * Note that timeout functions may be delayed, due to the processing of other
3896  * event sources. Thus they should not be relied on for precise timing.
3897  * After each call to the timeout function, the time of the next
3898  * timeout is recalculated based on the current time and the given @interval
3899  *
3900  * If you want timing more precise than whole seconds, use g_timeout_add()
3901  * instead.
3902  *
3903  * The grouping of timers to fire at the same time results in a more power
3904  * and CPU efficient behavior so if your timer is in multiples of seconds
3905  * and you don't require the first timer exactly one second from now, the
3906  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3907  *
3908  * This internally creates a main loop source using 
3909  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3910  * using g_source_attach(). You can do these steps manually if you need 
3911  * greater control.
3912  * 
3913  * Return value: the ID (greater than 0) of the event source.
3914  *
3915  * Since: 2.14
3916  **/
3917 guint
3918 g_timeout_add_seconds_full (gint           priority,
3919                             guint32        interval,
3920                             GSourceFunc    function,
3921                             gpointer       data,
3922                             GDestroyNotify notify)
3923 {
3924   GSource *source;
3925   guint id;
3926
3927   g_return_val_if_fail (function != NULL, 0);
3928
3929   source = g_timeout_source_new_seconds (interval);
3930
3931   if (priority != G_PRIORITY_DEFAULT)
3932     g_source_set_priority (source, priority);
3933
3934   g_source_set_callback (source, function, data, notify);
3935   id = g_source_attach (source, NULL);
3936   g_source_unref (source);
3937
3938   return id;
3939 }
3940
3941 /**
3942  * g_timeout_add_seconds:
3943  * @interval: the time between calls to the function, in seconds
3944  * @function: function to call
3945  * @data: data to pass to @function
3946  *
3947  * Sets a function to be called at regular intervals with the default
3948  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3949  * it returns %FALSE, at which point the timeout is automatically destroyed
3950  * and the function will not be called again.
3951  *
3952  * This internally creates a main loop source using 
3953  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3954  * using g_source_attach(). You can do these steps manually if you need 
3955  * greater control. Also see g_timout_add_seconds_full().
3956  * 
3957  * Return value: the ID (greater than 0) of the event source.
3958  *
3959  * Since: 2.14
3960  **/
3961 guint
3962 g_timeout_add_seconds (guint       interval,
3963                        GSourceFunc function,
3964                        gpointer    data)
3965 {
3966   g_return_val_if_fail (function != NULL, 0);
3967
3968   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3969 }
3970
3971 /* Child watch functions */
3972
3973 #ifdef G_OS_WIN32
3974
3975 static gboolean
3976 g_child_watch_prepare (GSource *source,
3977                        gint    *timeout)
3978 {
3979   *timeout = -1;
3980   return FALSE;
3981 }
3982
3983
3984 static gboolean 
3985 g_child_watch_check (GSource  *source)
3986 {
3987   GChildWatchSource *child_watch_source;
3988   gboolean child_exited;
3989
3990   child_watch_source = (GChildWatchSource *) source;
3991
3992   child_exited = child_watch_source->poll.revents & G_IO_IN;
3993
3994   if (child_exited)
3995     {
3996       DWORD child_status;
3997
3998       /*
3999        * Note: We do _not_ check for the special value of STILL_ACTIVE
4000        * since we know that the process has exited and doing so runs into
4001        * problems if the child process "happens to return STILL_ACTIVE(259)"
4002        * as Microsoft's Platform SDK puts it.
4003        */
4004       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4005         {
4006           gchar *emsg = g_win32_error_message (GetLastError ());
4007           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4008           g_free (emsg);
4009
4010           child_watch_source->child_status = -1;
4011         }
4012       else
4013         child_watch_source->child_status = child_status;
4014     }
4015
4016   return child_exited;
4017 }
4018
4019 #else /* G_OS_WIN32 */
4020
4021 static gboolean
4022 check_for_child_exited (GSource *source)
4023 {
4024   GChildWatchSource *child_watch_source;
4025   gint count;
4026
4027   /* protect against another SIGCHLD in the middle of this call */
4028   count = child_watch_count;
4029
4030   child_watch_source = (GChildWatchSource *) source;
4031
4032   if (child_watch_source->child_exited)
4033     return TRUE;
4034
4035   if (child_watch_source->count < count)
4036     {
4037       gint child_status;
4038
4039       if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4040         {
4041           child_watch_source->child_status = child_status;
4042           child_watch_source->child_exited = TRUE;
4043         }
4044       child_watch_source->count = count;
4045     }
4046
4047   return child_watch_source->child_exited;
4048 }
4049
4050 static gboolean
4051 g_child_watch_prepare (GSource *source,
4052                        gint    *timeout)
4053 {
4054   *timeout = -1;
4055
4056   return check_for_child_exited (source);
4057 }
4058
4059
4060 static gboolean 
4061 g_child_watch_check (GSource  *source)
4062 {
4063   return check_for_child_exited (source);
4064 }
4065
4066 #endif /* G_OS_WIN32 */
4067
4068 static gboolean
4069 g_child_watch_dispatch (GSource    *source, 
4070                         GSourceFunc callback,
4071                         gpointer    user_data)
4072 {
4073   GChildWatchSource *child_watch_source;
4074   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4075
4076   child_watch_source = (GChildWatchSource *) source;
4077
4078   if (!callback)
4079     {
4080       g_warning ("Child watch source dispatched without callback\n"
4081                  "You must call g_source_set_callback().");
4082       return FALSE;
4083     }
4084
4085   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4086
4087   /* We never keep a child watch source around as the child is gone */
4088   return FALSE;
4089 }
4090
4091 #ifndef G_OS_WIN32
4092
4093 static void
4094 g_child_watch_signal_handler (int signum)
4095 {
4096   child_watch_count ++;
4097
4098   if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4099     {
4100       write (child_watch_wake_up_pipe[1], "B", 1);
4101     }
4102   else
4103     {
4104       /* We count on the signal interrupting the poll in the same thread.
4105        */
4106     }
4107 }
4108  
4109 static void
4110 g_child_watch_source_init_single (void)
4111 {
4112   struct sigaction action;
4113
4114   g_assert (! g_thread_supported());
4115   g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4116
4117   child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4118
4119   action.sa_handler = g_child_watch_signal_handler;
4120   sigemptyset (&action.sa_mask);
4121   action.sa_flags = SA_NOCLDSTOP;
4122   sigaction (SIGCHLD, &action, NULL);
4123 }
4124
4125 G_GNUC_NORETURN static gpointer
4126 child_watch_helper_thread (gpointer data) 
4127 {
4128   while (1)
4129     {
4130       gchar b[20];
4131       GSList *list;
4132
4133       read (child_watch_wake_up_pipe[0], b, 20);
4134
4135       /* We were woken up.  Wake up all other contexts in all other threads */
4136       G_LOCK (main_context_list);
4137       for (list = main_context_list; list; list = list->next)
4138         {
4139           GMainContext *context;
4140
4141           context = list->data;
4142           if (g_atomic_int_get (&context->ref_count) > 0)
4143             /* Due to racing conditions we can find ref_count == 0, in
4144              * that case, however, the context is still not destroyed
4145              * and no poll can be active, otherwise the ref_count
4146              * wouldn't be 0 */
4147             g_main_context_wakeup (context);
4148         }
4149       G_UNLOCK (main_context_list);
4150     }
4151 }
4152
4153 static void
4154 g_child_watch_source_init_multi_threaded (void)
4155 {
4156   GError *error = NULL;
4157   struct sigaction action;
4158
4159   g_assert (g_thread_supported());
4160
4161   if (pipe (child_watch_wake_up_pipe) < 0)
4162     g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4163   fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4164
4165   /* We create a helper thread that polls on the wakeup pipe indefinitely */
4166   /* FIXME: Think this through for races */
4167   if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4168     g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4169   child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4170  
4171   action.sa_handler = g_child_watch_signal_handler;
4172   sigemptyset (&action.sa_mask);
4173   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4174   sigaction (SIGCHLD, &action, NULL);
4175 }
4176
4177 static void
4178 g_child_watch_source_init_promote_single_to_threaded (void)
4179 {
4180   g_child_watch_source_init_multi_threaded ();
4181 }
4182
4183 static void
4184 g_child_watch_source_init (void)
4185 {
4186   if (g_thread_supported())
4187     {
4188       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4189         g_child_watch_source_init_multi_threaded ();
4190       else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4191         g_child_watch_source_init_promote_single_to_threaded ();
4192     }
4193   else
4194     {
4195       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4196         g_child_watch_source_init_single ();
4197     }
4198 }
4199
4200 #endif /* !G_OS_WIN32 */
4201
4202 /**
4203  * g_child_watch_source_new:
4204  * @pid: process to watch. On POSIX the pid of a child process. On
4205  * Windows a handle for a process (which doesn't have to be a child).
4206  * 
4207  * Creates a new child_watch source.
4208  *
4209  * The source will not initially be associated with any #GMainContext
4210  * and must be added to one with g_source_attach() before it will be
4211  * executed.
4212  * 
4213  * Note that child watch sources can only be used in conjunction with
4214  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4215  * flag is used.
4216  *
4217  * Note that on platforms where #GPid must be explicitly closed
4218  * (see g_spawn_close_pid()) @pid must not be closed while the
4219  * source is still active. Typically, you will want to call
4220  * g_spawn_close_pid() in the callback function for the source.
4221  *
4222  * Note further that using g_child_watch_source_new() is not 
4223  * compatible with calling <literal>waitpid(-1)</literal> in 
4224  * the application. Calling waitpid() for individual pids will
4225  * still work fine. 
4226  * 
4227  * Return value: the newly-created child watch source
4228  *
4229  * Since: 2.4
4230  **/
4231 GSource *
4232 g_child_watch_source_new (GPid pid)
4233 {
4234   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4235   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4236
4237 #ifdef G_OS_WIN32
4238   child_watch_source->poll.fd = (gintptr) pid;
4239   child_watch_source->poll.events = G_IO_IN;
4240
4241   g_source_add_poll (source, &child_watch_source->poll);
4242 #else /* G_OS_WIN32 */
4243   g_child_watch_source_init ();
4244 #endif /* G_OS_WIN32 */
4245
4246   child_watch_source->pid = pid;
4247
4248   return source;
4249 }
4250
4251 /**
4252  * g_child_watch_add_full:
4253  * @priority: the priority of the idle source. Typically this will be in the
4254  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4255  * @pid:      process to watch. On POSIX the pid of a child process. On
4256  * Windows a handle for a process (which doesn't have to be a child).
4257  * @function: function to call
4258  * @data:     data to pass to @function
4259  * @notify:   function to call when the idle is removed, or %NULL
4260  * 
4261  * Sets a function to be called when the child indicated by @pid 
4262  * exits, at the priority @priority.
4263  *
4264  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4265  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4266  * the spawn function for the child watching to work.
4267  * 
4268  * Note that on platforms where #GPid must be explicitly closed
4269  * (see g_spawn_close_pid()) @pid must not be closed while the
4270  * source is still active. Typically, you will want to call
4271  * g_spawn_close_pid() in the callback function for the source.
4272  * 
4273  * GLib supports only a single callback per process id.
4274  *
4275  * This internally creates a main loop source using 
4276  * g_child_watch_source_new() and attaches it to the main loop context 
4277  * using g_source_attach(). You can do these steps manually if you 
4278  * need greater control.
4279  *
4280  * Return value: the ID (greater than 0) of the event source.
4281  *
4282  * Since: 2.4
4283  **/
4284 guint
4285 g_child_watch_add_full (gint            priority,
4286                         GPid            pid,
4287                         GChildWatchFunc function,
4288                         gpointer        data,
4289                         GDestroyNotify  notify)
4290 {
4291   GSource *source;
4292   guint id;
4293   
4294   g_return_val_if_fail (function != NULL, 0);
4295
4296   source = g_child_watch_source_new (pid);
4297
4298   if (priority != G_PRIORITY_DEFAULT)
4299     g_source_set_priority (source, priority);
4300
4301   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4302   id = g_source_attach (source, NULL);
4303   g_source_unref (source);
4304
4305   return id;
4306 }
4307
4308 /**
4309  * g_child_watch_add:
4310  * @pid:      process id to watch. On POSIX the pid of a child process. On
4311  * Windows a handle for a process (which doesn't have to be a child).
4312  * @function: function to call
4313  * @data:     data to pass to @function
4314  * 
4315  * Sets a function to be called when the child indicated by @pid 
4316  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4317  * 
4318  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4319  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4320  * the spawn function for the child watching to work.
4321  * 
4322  * Note that on platforms where #GPid must be explicitly closed
4323  * (see g_spawn_close_pid()) @pid must not be closed while the
4324  * source is still active. Typically, you will want to call
4325  * g_spawn_close_pid() in the callback function for the source.
4326  *
4327  * GLib supports only a single callback per process id.
4328  *
4329  * This internally creates a main loop source using 
4330  * g_child_watch_source_new() and attaches it to the main loop context 
4331  * using g_source_attach(). You can do these steps manually if you 
4332  * need greater control.
4333  *
4334  * Return value: the ID (greater than 0) of the event source.
4335  *
4336  * Since: 2.4
4337  **/
4338 guint 
4339 g_child_watch_add (GPid            pid,
4340                    GChildWatchFunc function,
4341                    gpointer        data)
4342 {
4343   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4344 }
4345
4346
4347 /* Idle functions */
4348
4349 static gboolean 
4350 g_idle_prepare  (GSource  *source,
4351                  gint     *timeout)
4352 {
4353   *timeout = 0;
4354
4355   return TRUE;
4356 }
4357
4358 static gboolean 
4359 g_idle_check    (GSource  *source)
4360 {
4361   return TRUE;
4362 }
4363
4364 static gboolean
4365 g_idle_dispatch (GSource    *source, 
4366                  GSourceFunc callback,
4367                  gpointer    user_data)
4368 {
4369   if (!callback)
4370     {
4371       g_warning ("Idle source dispatched without callback\n"
4372                  "You must call g_source_set_callback().");
4373       return FALSE;
4374     }
4375   
4376   return callback (user_data);
4377 }
4378
4379 /**
4380  * g_idle_source_new:
4381  * 
4382  * Creates a new idle source.
4383  *
4384  * The source will not initially be associated with any #GMainContext
4385  * and must be added to one with g_source_attach() before it will be
4386  * executed. Note that the default priority for idle sources is
4387  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4388  * have a default priority of %G_PRIORITY_DEFAULT.
4389  * 
4390  * Return value: the newly-created idle source
4391  **/
4392 GSource *
4393 g_idle_source_new (void)
4394 {
4395   GSource *source;
4396
4397   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4398   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4399
4400   return source;
4401 }
4402
4403 /**
4404  * g_idle_add_full:
4405  * @priority: the priority of the idle source. Typically this will be in the
4406  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4407  * @function: function to call
4408  * @data:     data to pass to @function
4409  * @notify:   function to call when the idle is removed, or %NULL
4410  * 
4411  * Adds a function to be called whenever there are no higher priority
4412  * events pending.  If the function returns %FALSE it is automatically
4413  * removed from the list of event sources and will not be called again.
4414  * 
4415  * This internally creates a main loop source using g_idle_source_new()
4416  * and attaches it to the main loop context using g_source_attach(). 
4417  * You can do these steps manually if you need greater control.
4418  * 
4419  * Return value: the ID (greater than 0) of the event source.
4420  **/
4421 guint 
4422 g_idle_add_full (gint           priority,
4423                  GSourceFunc    function,
4424                  gpointer       data,
4425                  GDestroyNotify notify)
4426 {
4427   GSource *source;
4428   guint id;
4429   
4430   g_return_val_if_fail (function != NULL, 0);
4431
4432   source = g_idle_source_new ();
4433
4434   if (priority != G_PRIORITY_DEFAULT_IDLE)
4435     g_source_set_priority (source, priority);
4436
4437   g_source_set_callback (source, function, data, notify);
4438   id = g_source_attach (source, NULL);
4439   g_source_unref (source);
4440
4441   return id;
4442 }
4443
4444 /**
4445  * g_idle_add:
4446  * @function: function to call 
4447  * @data: data to pass to @function.
4448  * 
4449  * Adds a function to be called whenever there are no higher priority
4450  * events pending to the default main loop. The function is given the
4451  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4452  * returns %FALSE it is automatically removed from the list of event
4453  * sources and will not be called again.
4454  * 
4455  * This internally creates a main loop source using g_idle_source_new()
4456  * and attaches it to the main loop context using g_source_attach(). 
4457  * You can do these steps manually if you need greater control.
4458  * 
4459  * Return value: the ID (greater than 0) of the event source.
4460  **/
4461 guint 
4462 g_idle_add (GSourceFunc    function,
4463             gpointer       data)
4464 {
4465   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4466 }
4467
4468 /**
4469  * g_idle_remove_by_data:
4470  * @data: the data for the idle source's callback.
4471  * 
4472  * Removes the idle function with the given data.
4473  * 
4474  * Return value: %TRUE if an idle source was found and removed.
4475  **/
4476 gboolean
4477 g_idle_remove_by_data (gpointer data)
4478 {
4479   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4480 }
4481
4482 /**
4483  * g_main_context_invoke:
4484  * @context: a #GMainContext, or %NULL
4485  * @function: function to call
4486  * @data: data to pass to @function
4487  *
4488  * Invokes a function in such a way that @context is owned during the
4489  * invocation of @function.
4490  *
4491  * If @context is %NULL then the global default main context — as
4492  * returned by g_main_context_default() — is used.
4493  *
4494  * If @context is owned by the current thread, @function is called
4495  * directly.  Otherwise, if @context is the thread-default main context
4496  * of the current thread and g_main_context_acquire() succeeds, then
4497  * @function is called and g_main_context_release() is called
4498  * afterwards.
4499  *
4500  * In any other case, an idle source is created to call @function and
4501  * that source is attached to @context (presumably to be run in another
4502  * thread).  The idle source is attached with #G_PRIORITY_DEFAULT
4503  * priority.  If you want a different priority, use
4504  * g_main_context_invoke_full().
4505  *
4506  * Note that, as with normal idle functions, @function should probably
4507  * return %FALSE.  If it returns %TRUE, it will be continuously run in a
4508  * loop (and may prevent this call from returning).
4509  *
4510  * Since: 2.28
4511  **/
4512 void
4513 g_main_context_invoke (GMainContext *context,
4514                        GSourceFunc   function,
4515                        gpointer      data)
4516 {
4517   g_main_context_invoke_full (context,
4518                               G_PRIORITY_DEFAULT,
4519                               function, data, NULL);
4520 }
4521
4522 /**
4523  * g_main_context_invoke_full:
4524  * @context: a #GMainContext, or %NULL
4525  * @priority: the priority at which to run @function
4526  * @function: function to call
4527  * @data: data to pass to @function
4528  * @notify: a function to call when @data is no longer in use, or %NULL.
4529  *
4530  * Invokes a function in such a way that @context is owned during the
4531  * invocation of @function.
4532  *
4533  * This function is the same as g_main_context_invoke() except that it
4534  * lets you specify the priority incase @function ends up being
4535  * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4536  *
4537  * @notify should not assume that it is called from any particular
4538  * thread or with any particular context acquired.
4539  *
4540  * Since: 2.28
4541  **/
4542 void
4543 g_main_context_invoke_full (GMainContext   *context,
4544                             gint            priority,
4545                             GSourceFunc     function,
4546                             gpointer        data,
4547                             GDestroyNotify  notify)
4548 {
4549   g_return_if_fail (function != NULL);
4550
4551   if (!context)
4552     context = g_main_context_default ();
4553
4554   if (g_main_context_is_owner (context))
4555     {
4556       while (function (data));
4557       if (notify != NULL)
4558         notify (data);
4559     }
4560
4561   else
4562     {
4563       GMainContext *thread_default;
4564
4565       thread_default = g_main_context_get_thread_default ();
4566
4567       if (!thread_default)
4568         thread_default = g_main_context_default ();
4569
4570       if (thread_default == context && g_main_context_acquire (context))
4571         {
4572           while (function (data));
4573
4574           g_main_context_release (context);
4575
4576           if (notify != NULL)
4577             notify (data);
4578         }
4579       else
4580         {
4581           GSource *source;
4582
4583           source = g_idle_source_new ();
4584           g_source_set_priority (source, priority);
4585           g_source_set_callback (source, function, data, notify);
4586           g_source_attach (source, context);
4587           g_source_unref (source);
4588         }
4589     }
4590 }