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