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