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