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