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