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