Add g_get_real_time() for wall-clock int64 micros
[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   GTimeVal current_time;
270   gboolean current_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->current_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         source->source_funcs->finalize (source);
1524
1525       g_free (source->name);
1526       source->name = NULL;
1527
1528       g_slist_free (source->poll_fds);
1529       source->poll_fds = NULL;
1530       g_free (source);
1531     }
1532   
1533   if (!have_lock && context)
1534     UNLOCK_CONTEXT (context);
1535
1536   if (old_cb_funcs)
1537     {
1538       if (have_lock)
1539         UNLOCK_CONTEXT (context);
1540       
1541       old_cb_funcs->unref (old_cb_data);
1542
1543       if (have_lock)
1544         LOCK_CONTEXT (context);
1545     }
1546 }
1547
1548 /**
1549  * g_source_unref:
1550  * @source: a #GSource
1551  * 
1552  * Decreases the reference count of a source by one. If the
1553  * resulting reference count is zero the source and associated
1554  * memory will be destroyed. 
1555  **/
1556 void
1557 g_source_unref (GSource *source)
1558 {
1559   g_return_if_fail (source != NULL);
1560
1561   g_source_unref_internal (source, source->context, FALSE);
1562 }
1563
1564 /**
1565  * g_main_context_find_source_by_id:
1566  * @context: a #GMainContext (if %NULL, the default context will be used)
1567  * @source_id: the source ID, as returned by g_source_get_id(). 
1568  * 
1569  * Finds a #GSource given a pair of context and ID.
1570  * 
1571  * Return value: the #GSource if found, otherwise, %NULL
1572  **/
1573 GSource *
1574 g_main_context_find_source_by_id (GMainContext *context,
1575                                   guint         source_id)
1576 {
1577   GSource *source;
1578   
1579   g_return_val_if_fail (source_id > 0, NULL);
1580
1581   if (context == NULL)
1582     context = g_main_context_default ();
1583   
1584   LOCK_CONTEXT (context);
1585   
1586   source = context->source_list;
1587   while (source)
1588     {
1589       if (!SOURCE_DESTROYED (source) &&
1590           source->source_id == source_id)
1591         break;
1592       source = source->next;
1593     }
1594
1595   UNLOCK_CONTEXT (context);
1596
1597   return source;
1598 }
1599
1600 /**
1601  * g_main_context_find_source_by_funcs_user_data:
1602  * @context: a #GMainContext (if %NULL, the default context will be used).
1603  * @funcs: the @source_funcs passed to g_source_new().
1604  * @user_data: the user data from the callback.
1605  * 
1606  * Finds a source with the given source functions and user data.  If
1607  * multiple sources exist with the same source function and user data,
1608  * the first one found will be returned.
1609  * 
1610  * Return value: the source, if one was found, otherwise %NULL
1611  **/
1612 GSource *
1613 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1614                                                GSourceFuncs *funcs,
1615                                                gpointer      user_data)
1616 {
1617   GSource *source;
1618   
1619   g_return_val_if_fail (funcs != NULL, NULL);
1620
1621   if (context == NULL)
1622     context = g_main_context_default ();
1623   
1624   LOCK_CONTEXT (context);
1625
1626   source = context->source_list;
1627   while (source)
1628     {
1629       if (!SOURCE_DESTROYED (source) &&
1630           source->source_funcs == funcs &&
1631           source->callback_funcs)
1632         {
1633           GSourceFunc callback;
1634           gpointer callback_data;
1635
1636           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1637           
1638           if (callback_data == user_data)
1639             break;
1640         }
1641       source = source->next;
1642     }
1643
1644   UNLOCK_CONTEXT (context);
1645
1646   return source;
1647 }
1648
1649 /**
1650  * g_main_context_find_source_by_user_data:
1651  * @context: a #GMainContext
1652  * @user_data: the user_data for the callback.
1653  * 
1654  * Finds a source with the given user data for the callback.  If
1655  * multiple sources exist with the same user data, the first
1656  * one found will be returned.
1657  * 
1658  * Return value: the source, if one was found, otherwise %NULL
1659  **/
1660 GSource *
1661 g_main_context_find_source_by_user_data (GMainContext *context,
1662                                          gpointer      user_data)
1663 {
1664   GSource *source;
1665   
1666   if (context == NULL)
1667     context = g_main_context_default ();
1668   
1669   LOCK_CONTEXT (context);
1670
1671   source = context->source_list;
1672   while (source)
1673     {
1674       if (!SOURCE_DESTROYED (source) &&
1675           source->callback_funcs)
1676         {
1677           GSourceFunc callback;
1678           gpointer callback_data = NULL;
1679
1680           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1681
1682           if (callback_data == user_data)
1683             break;
1684         }
1685       source = source->next;
1686     }
1687
1688   UNLOCK_CONTEXT (context);
1689
1690   return source;
1691 }
1692
1693 /**
1694  * g_source_remove:
1695  * @tag: the ID of the source to remove.
1696  * 
1697  * Removes the source with the given id from the default main context. 
1698  * The id of
1699  * a #GSource is given by g_source_get_id(), or will be returned by the
1700  * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1701  * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1702  * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1703  *
1704  * See also g_source_destroy(). You must use g_source_destroy() for sources
1705  * added to a non-default main context.
1706  *
1707  * Return value: %TRUE if the source was found and removed.
1708  **/
1709 gboolean
1710 g_source_remove (guint tag)
1711 {
1712   GSource *source;
1713   
1714   g_return_val_if_fail (tag > 0, FALSE);
1715
1716   source = g_main_context_find_source_by_id (NULL, tag);
1717   if (source)
1718     g_source_destroy (source);
1719
1720   return source != NULL;
1721 }
1722
1723 /**
1724  * g_source_remove_by_user_data:
1725  * @user_data: the user_data for the callback.
1726  * 
1727  * Removes a source from the default main loop context given the user
1728  * data for the callback. If multiple sources exist with the same user
1729  * data, only one will be destroyed.
1730  * 
1731  * Return value: %TRUE if a source was found and removed. 
1732  **/
1733 gboolean
1734 g_source_remove_by_user_data (gpointer user_data)
1735 {
1736   GSource *source;
1737   
1738   source = g_main_context_find_source_by_user_data (NULL, user_data);
1739   if (source)
1740     {
1741       g_source_destroy (source);
1742       return TRUE;
1743     }
1744   else
1745     return FALSE;
1746 }
1747
1748 /**
1749  * g_source_remove_by_funcs_user_data:
1750  * @funcs: The @source_funcs passed to g_source_new()
1751  * @user_data: the user data for the callback
1752  * 
1753  * Removes a source from the default main loop context given the
1754  * source functions and user data. If multiple sources exist with the
1755  * same source functions and user data, only one will be destroyed.
1756  * 
1757  * Return value: %TRUE if a source was found and removed. 
1758  **/
1759 gboolean
1760 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1761                                     gpointer      user_data)
1762 {
1763   GSource *source;
1764
1765   g_return_val_if_fail (funcs != NULL, FALSE);
1766
1767   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1768   if (source)
1769     {
1770       g_source_destroy (source);
1771       return TRUE;
1772     }
1773   else
1774     return FALSE;
1775 }
1776
1777 /**
1778  * g_get_current_time:
1779  * @result: #GTimeVal structure in which to store current time.
1780  *
1781  * Equivalent to the UNIX gettimeofday() function, but portable.
1782  *
1783  * You may find g_get_real_time() to be more convenient.
1784  **/
1785 void
1786 g_get_current_time (GTimeVal *result)
1787 {
1788 #ifndef G_OS_WIN32
1789   struct timeval r;
1790
1791   g_return_if_fail (result != NULL);
1792
1793   /*this is required on alpha, there the timeval structs are int's
1794     not longs and a cast only would fail horribly*/
1795   gettimeofday (&r, NULL);
1796   result->tv_sec = r.tv_sec;
1797   result->tv_usec = r.tv_usec;
1798 #else
1799   FILETIME ft;
1800   guint64 time64;
1801
1802   g_return_if_fail (result != NULL);
1803
1804   GetSystemTimeAsFileTime (&ft);
1805   memmove (&time64, &ft, sizeof (FILETIME));
1806
1807   /* Convert from 100s of nanoseconds since 1601-01-01
1808    * to Unix epoch. Yes, this is Y2038 unsafe.
1809    */
1810   time64 -= G_GINT64_CONSTANT (116444736000000000);
1811   time64 /= 10;
1812
1813   result->tv_sec = time64 / 1000000;
1814   result->tv_usec = time64 % 1000000;
1815 #endif
1816 }
1817
1818 /**
1819  * g_get_real_time:
1820  *
1821  * Queries the system wall-clock time.
1822  *
1823  * This call is functionally equivalent to g_get_current_time() except
1824  * that the return value is often more convenient than dealing with a
1825  * #GTimeVal.
1826  *
1827  * You should only use this call if you are actually interested in the real
1828  * wall-clock time.  g_get_monotonic_time() is probably more useful for
1829  * measuring intervals.
1830  *
1831  * Returns: the number of microseconds since January 1, 1970 UTC.
1832  *
1833  * Since: 2.28
1834  **/
1835 gint64
1836 g_get_real_time (void)
1837 {
1838   GTimeVal tv;
1839
1840   g_get_current_time (&tv);
1841
1842   return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1843 }
1844
1845 /**
1846  * g_get_monotonic_time:
1847  *
1848  * Queries the system monotonic time, if available.
1849  *
1850  * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1851  * is a very shallow wrapper for that.  Otherwise, we make a best effort
1852  * that probably involves returning the wall clock time (with at least
1853  * microsecond accuracy, subject to the limitations of the OS kernel).
1854  *
1855  * Note that, on Windows, "limitations of the OS kernel" is a rather
1856  * substantial statement.  Depending on the configuration of the system,
1857  * the wall clock time is updated as infrequently as 64 times a second
1858  * (which is approximately every 16ms).
1859  *
1860  * Returns: the monotonic time, in microseconds
1861  *
1862  * Since: 2.28
1863  **/
1864 gint64
1865 g_get_monotonic_time (void)
1866 {
1867 #ifdef HAVE_CLOCK_GETTIME
1868   /* librt clock_gettime() is our first choice */
1869   {
1870     static int clockid = CLOCK_REALTIME;
1871     struct timespec ts;
1872
1873 #ifdef HAVE_MONOTONIC_CLOCK
1874     /* We have to check if we actually have monotonic clock support.
1875      *
1876      * There is no thread safety issue here since there is no harm if we
1877      * check twice.
1878      */
1879     {
1880       static gboolean checked;
1881
1882       if G_UNLIKELY (!checked)
1883         {
1884           if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
1885             clockid = CLOCK_MONOTONIC;
1886           checked = TRUE;
1887         }
1888     }
1889 #endif
1890
1891     clock_gettime (clockid, &ts);
1892
1893     /* In theory monotonic time can have any epoch.
1894      *
1895      * glib presently assumes the following:
1896      *
1897      *   1) The epoch comes some time after the birth of Jesus of Nazareth, but
1898      *      not more than 10000 years later.
1899      *
1900      *   2) The current time also falls sometime within this range.
1901      *
1902      * These two reasonable assumptions leave us with a maximum deviation from
1903      * the epoch of 10000 years, or 315569520000000000 seconds.
1904      *
1905      * If we restrict ourselves to this range then the number of microseconds
1906      * will always fit well inside the constraints of a int64 (by a factor of
1907      * about 29).
1908      *
1909      * If you actually hit the following assertion, probably you should file a
1910      * bug against your operating system for being excessively silly.
1911      **/
1912     g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
1913               ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
1914
1915     return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
1916   }
1917 #else
1918   /* It may look like we are discarding accuracy on Windows (since its
1919    * current time is expressed in 100s of nanoseconds) but according to
1920    * many sources, the time is only updated 64 times per second, so
1921    * microsecond accuracy is more than enough.
1922    */
1923   {
1924     GTimeVal tv;
1925
1926     g_get_current_time (&tv);
1927
1928     return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1929   }
1930 #endif
1931 }
1932
1933 static void
1934 g_main_dispatch_free (gpointer dispatch)
1935 {
1936   g_slice_free (GMainDispatch, dispatch);
1937 }
1938
1939 /* Running the main loop */
1940
1941 static GMainDispatch *
1942 get_dispatch (void)
1943 {
1944   static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1945   GMainDispatch *dispatch = g_static_private_get (&depth_private);
1946   if (!dispatch)
1947     {
1948       dispatch = g_slice_new0 (GMainDispatch);
1949       g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1950     }
1951
1952   return dispatch;
1953 }
1954
1955 /**
1956  * g_main_depth:
1957  *
1958  * Returns the depth of the stack of calls to
1959  * g_main_context_dispatch() on any #GMainContext in the current thread.
1960  *  That is, when called from the toplevel, it gives 0. When
1961  * called from within a callback from g_main_context_iteration()
1962  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
1963  * a callback to a recursive call to g_main_context_iterate(),
1964  * it returns 2. And so forth.
1965  *
1966  * This function is useful in a situation like the following:
1967  * Imagine an extremely simple "garbage collected" system.
1968  *
1969  * |[
1970  * static GList *free_list;
1971  * 
1972  * gpointer
1973  * allocate_memory (gsize size)
1974  * { 
1975  *   gpointer result = g_malloc (size);
1976  *   free_list = g_list_prepend (free_list, result);
1977  *   return result;
1978  * }
1979  * 
1980  * void
1981  * free_allocated_memory (void)
1982  * {
1983  *   GList *l;
1984  *   for (l = free_list; l; l = l->next);
1985  *     g_free (l->data);
1986  *   g_list_free (free_list);
1987  *   free_list = NULL;
1988  *  }
1989  * 
1990  * [...]
1991  * 
1992  * while (TRUE); 
1993  *  {
1994  *    g_main_context_iteration (NULL, TRUE);
1995  *    free_allocated_memory();
1996  *   }
1997  * ]|
1998  *
1999  * This works from an application, however, if you want to do the same
2000  * thing from a library, it gets more difficult, since you no longer
2001  * control the main loop. You might think you can simply use an idle
2002  * function to make the call to free_allocated_memory(), but that
2003  * doesn't work, since the idle function could be called from a
2004  * recursive callback. This can be fixed by using g_main_depth()
2005  *
2006  * |[
2007  * gpointer
2008  * allocate_memory (gsize size)
2009  * { 
2010  *   FreeListBlock *block = g_new (FreeListBlock, 1);
2011  *   block->mem = g_malloc (size);
2012  *   block->depth = g_main_depth ();   
2013  *   free_list = g_list_prepend (free_list, block);
2014  *   return block->mem;
2015  * }
2016  * 
2017  * void
2018  * free_allocated_memory (void)
2019  * {
2020  *   GList *l;
2021  *   
2022  *   int depth = g_main_depth ();
2023  *   for (l = free_list; l; );
2024  *     {
2025  *       GList *next = l->next;
2026  *       FreeListBlock *block = l->data;
2027  *       if (block->depth > depth)
2028  *         {
2029  *           g_free (block->mem);
2030  *           g_free (block);
2031  *           free_list = g_list_delete_link (free_list, l);
2032  *         }
2033  *               
2034  *       l = next;
2035  *     }
2036  *   }
2037  * ]|
2038  *
2039  * There is a temptation to use g_main_depth() to solve
2040  * problems with reentrancy. For instance, while waiting for data
2041  * to be received from the network in response to a menu item,
2042  * the menu item might be selected again. It might seem that
2043  * one could make the menu item's callback return immediately
2044  * and do nothing if g_main_depth() returns a value greater than 1.
2045  * However, this should be avoided since the user then sees selecting
2046  * the menu item do nothing. Furthermore, you'll find yourself adding
2047  * these checks all over your code, since there are doubtless many,
2048  * many things that the user could do. Instead, you can use the
2049  * following techniques:
2050  *
2051  * <orderedlist>
2052  *  <listitem>
2053  *   <para>
2054  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
2055  *     the user from interacting with elements while the main
2056  *     loop is recursing.
2057  *   </para>
2058  *  </listitem>
2059  *  <listitem>
2060  *   <para>
2061  *     Avoid main loop recursion in situations where you can't handle
2062  *     arbitrary  callbacks. Instead, structure your code so that you
2063  *     simply return to the main loop and then get called again when
2064  *     there is more work to do.
2065  *   </para>
2066  *  </listitem>
2067  * </orderedlist>
2068  * 
2069  * Return value: The main loop recursion level in the current thread
2070  **/
2071 int
2072 g_main_depth (void)
2073 {
2074   GMainDispatch *dispatch = get_dispatch ();
2075   return dispatch->depth;
2076 }
2077
2078 /**
2079  * g_main_current_source:
2080  *
2081  * Returns the currently firing source for this thread.
2082  * 
2083  * Return value: The currently firing source or %NULL.
2084  *
2085  * Since: 2.12
2086  */
2087 GSource *
2088 g_main_current_source (void)
2089 {
2090   GMainDispatch *dispatch = get_dispatch ();
2091   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2092 }
2093
2094 /**
2095  * g_source_is_destroyed:
2096  * @source: a #GSource
2097  *
2098  * Returns whether @source has been destroyed.
2099  *
2100  * This is important when you operate upon your objects 
2101  * from within idle handlers, but may have freed the object 
2102  * before the dispatch of your idle handler.
2103  *
2104  * |[
2105  * static gboolean 
2106  * idle_callback (gpointer data)
2107  * {
2108  *   SomeWidget *self = data;
2109  *    
2110  *   GDK_THREADS_ENTER (<!-- -->);
2111  *   /<!-- -->* do stuff with self *<!-- -->/
2112  *   self->idle_id = 0;
2113  *   GDK_THREADS_LEAVE (<!-- -->);
2114  *    
2115  *   return FALSE;
2116  * }
2117  *  
2118  * static void 
2119  * some_widget_do_stuff_later (SomeWidget *self)
2120  * {
2121  *   self->idle_id = g_idle_add (idle_callback, self);
2122  * }
2123  *  
2124  * static void 
2125  * some_widget_finalize (GObject *object)
2126  * {
2127  *   SomeWidget *self = SOME_WIDGET (object);
2128  *    
2129  *   if (self->idle_id)
2130  *     g_source_remove (self->idle_id);
2131  *    
2132  *   G_OBJECT_CLASS (parent_class)->finalize (object);
2133  * }
2134  * ]|
2135  *
2136  * This will fail in a multi-threaded application if the 
2137  * widget is destroyed before the idle handler fires due 
2138  * to the use after free in the callback. A solution, to 
2139  * this particular problem, is to check to if the source
2140  * has already been destroy within the callback.
2141  *
2142  * |[
2143  * static gboolean 
2144  * idle_callback (gpointer data)
2145  * {
2146  *   SomeWidget *self = data;
2147  *   
2148  *   GDK_THREADS_ENTER ();
2149  *   if (!g_source_is_destroyed (g_main_current_source ()))
2150  *     {
2151  *       /<!-- -->* do stuff with self *<!-- -->/
2152  *     }
2153  *   GDK_THREADS_LEAVE ();
2154  *   
2155  *   return FALSE;
2156  * }
2157  * ]|
2158  *
2159  * Return value: %TRUE if the source has been destroyed
2160  *
2161  * Since: 2.12
2162  */
2163 gboolean
2164 g_source_is_destroyed (GSource *source)
2165 {
2166   return SOURCE_DESTROYED (source);
2167 }
2168
2169 /* Temporarily remove all this source's file descriptors from the
2170  * poll(), so that if data comes available for one of the file descriptors
2171  * we don't continually spin in the poll()
2172  */
2173 /* HOLDS: source->context's lock */
2174 static void
2175 block_source (GSource *source)
2176 {
2177   GSList *tmp_list;
2178
2179   g_return_if_fail (!SOURCE_BLOCKED (source));
2180
2181   tmp_list = source->poll_fds;
2182   while (tmp_list)
2183     {
2184       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2185       tmp_list = tmp_list->next;
2186     }
2187 }
2188
2189 /* HOLDS: source->context's lock */
2190 static void
2191 unblock_source (GSource *source)
2192 {
2193   GSList *tmp_list;
2194   
2195   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2196   g_return_if_fail (!SOURCE_DESTROYED (source));
2197   
2198   tmp_list = source->poll_fds;
2199   while (tmp_list)
2200     {
2201       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2202       tmp_list = tmp_list->next;
2203     }
2204 }
2205
2206 /* HOLDS: context's lock */
2207 static void
2208 g_main_dispatch (GMainContext *context)
2209 {
2210   GMainDispatch *current = get_dispatch ();
2211   guint i;
2212
2213   for (i = 0; i < context->pending_dispatches->len; i++)
2214     {
2215       GSource *source = context->pending_dispatches->pdata[i];
2216
2217       context->pending_dispatches->pdata[i] = NULL;
2218       g_assert (source);
2219
2220       source->flags &= ~G_SOURCE_READY;
2221
2222       if (!SOURCE_DESTROYED (source))
2223         {
2224           gboolean was_in_call;
2225           gpointer user_data = NULL;
2226           GSourceFunc callback = NULL;
2227           GSourceCallbackFuncs *cb_funcs;
2228           gpointer cb_data;
2229           gboolean need_destroy;
2230
2231           gboolean (*dispatch) (GSource *,
2232                                 GSourceFunc,
2233                                 gpointer);
2234           GSList current_source_link;
2235
2236           dispatch = source->source_funcs->dispatch;
2237           cb_funcs = source->callback_funcs;
2238           cb_data = source->callback_data;
2239
2240           if (cb_funcs)
2241             cb_funcs->ref (cb_data);
2242           
2243           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2244             block_source (source);
2245           
2246           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2247           source->flags |= G_HOOK_FLAG_IN_CALL;
2248
2249           if (cb_funcs)
2250             cb_funcs->get (cb_data, source, &callback, &user_data);
2251
2252           UNLOCK_CONTEXT (context);
2253
2254           current->depth++;
2255           /* The on-stack allocation of the GSList is unconventional, but
2256            * we know that the lifetime of the link is bounded to this
2257            * function as the link is kept in a thread specific list and
2258            * not manipulated outside of this function and its descendants.
2259            * Avoiding the overhead of a g_slist_alloc() is useful as many
2260            * applications do little more than dispatch events.
2261            *
2262            * This is a performance hack - do not revert to g_slist_prepend()!
2263            */
2264           current_source_link.data = source;
2265           current_source_link.next = current->dispatching_sources;
2266           current->dispatching_sources = &current_source_link;
2267           need_destroy = ! dispatch (source,
2268                                      callback,
2269                                      user_data);
2270           g_assert (current->dispatching_sources == &current_source_link);
2271           current->dispatching_sources = current_source_link.next;
2272           current->depth--;
2273           
2274           if (cb_funcs)
2275             cb_funcs->unref (cb_data);
2276
2277           LOCK_CONTEXT (context);
2278           
2279           if (!was_in_call)
2280             source->flags &= ~G_HOOK_FLAG_IN_CALL;
2281
2282           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2283               !SOURCE_DESTROYED (source))
2284             unblock_source (source);
2285           
2286           /* Note: this depends on the fact that we can't switch
2287            * sources from one main context to another
2288            */
2289           if (need_destroy && !SOURCE_DESTROYED (source))
2290             {
2291               g_assert (source->context == context);
2292               g_source_destroy_internal (source, context, TRUE);
2293             }
2294         }
2295       
2296       SOURCE_UNREF (source, context);
2297     }
2298
2299   g_ptr_array_set_size (context->pending_dispatches, 0);
2300 }
2301
2302 /* Holds context's lock */
2303 static inline GSource *
2304 next_valid_source (GMainContext *context,
2305                    GSource      *source)
2306 {
2307   GSource *new_source = source ? source->next : context->source_list;
2308
2309   while (new_source)
2310     {
2311       if (!SOURCE_DESTROYED (new_source))
2312         {
2313           new_source->ref_count++;
2314           break;
2315         }
2316       
2317       new_source = new_source->next;
2318     }
2319
2320   if (source)
2321     SOURCE_UNREF (source, context);
2322           
2323   return new_source;
2324 }
2325
2326 /**
2327  * g_main_context_acquire:
2328  * @context: a #GMainContext
2329  * 
2330  * Tries to become the owner of the specified context.
2331  * If some other thread is the owner of the context,
2332  * returns %FALSE immediately. Ownership is properly
2333  * recursive: the owner can require ownership again
2334  * and will release ownership when g_main_context_release()
2335  * is called as many times as g_main_context_acquire().
2336  *
2337  * You must be the owner of a context before you
2338  * can call g_main_context_prepare(), g_main_context_query(),
2339  * g_main_context_check(), g_main_context_dispatch().
2340  * 
2341  * Return value: %TRUE if the operation succeeded, and
2342  *   this thread is now the owner of @context.
2343  **/
2344 gboolean 
2345 g_main_context_acquire (GMainContext *context)
2346 {
2347 #ifdef G_THREADS_ENABLED
2348   gboolean result = FALSE;
2349   GThread *self = G_THREAD_SELF;
2350
2351   if (context == NULL)
2352     context = g_main_context_default ();
2353   
2354   LOCK_CONTEXT (context);
2355
2356   if (!context->owner)
2357     {
2358       context->owner = self;
2359       g_assert (context->owner_count == 0);
2360     }
2361
2362   if (context->owner == self)
2363     {
2364       context->owner_count++;
2365       result = TRUE;
2366     }
2367
2368   UNLOCK_CONTEXT (context); 
2369   
2370   return result;
2371 #else /* !G_THREADS_ENABLED */
2372   return TRUE;
2373 #endif /* G_THREADS_ENABLED */
2374 }
2375
2376 /**
2377  * g_main_context_release:
2378  * @context: a #GMainContext
2379  * 
2380  * Releases ownership of a context previously acquired by this thread
2381  * with g_main_context_acquire(). If the context was acquired multiple
2382  * times, the ownership will be released only when g_main_context_release()
2383  * is called as many times as it was acquired.
2384  **/
2385 void
2386 g_main_context_release (GMainContext *context)
2387 {
2388 #ifdef G_THREADS_ENABLED
2389   if (context == NULL)
2390     context = g_main_context_default ();
2391   
2392   LOCK_CONTEXT (context);
2393
2394   context->owner_count--;
2395   if (context->owner_count == 0)
2396     {
2397       context->owner = NULL;
2398
2399       if (context->waiters)
2400         {
2401           GMainWaiter *waiter = context->waiters->data;
2402           gboolean loop_internal_waiter =
2403             (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2404           context->waiters = g_slist_delete_link (context->waiters,
2405                                                   context->waiters);
2406           if (!loop_internal_waiter)
2407             g_mutex_lock (waiter->mutex);
2408           
2409           g_cond_signal (waiter->cond);
2410           
2411           if (!loop_internal_waiter)
2412             g_mutex_unlock (waiter->mutex);
2413         }
2414     }
2415
2416   UNLOCK_CONTEXT (context); 
2417 #endif /* G_THREADS_ENABLED */
2418 }
2419
2420 /**
2421  * g_main_context_wait:
2422  * @context: a #GMainContext
2423  * @cond: a condition variable
2424  * @mutex: a mutex, currently held
2425  * 
2426  * Tries to become the owner of the specified context,
2427  * as with g_main_context_acquire(). But if another thread
2428  * is the owner, atomically drop @mutex and wait on @cond until 
2429  * that owner releases ownership or until @cond is signaled, then
2430  * try again (once) to become the owner.
2431  * 
2432  * Return value: %TRUE if the operation succeeded, and
2433  *   this thread is now the owner of @context.
2434  **/
2435 gboolean
2436 g_main_context_wait (GMainContext *context,
2437                      GCond        *cond,
2438                      GMutex       *mutex)
2439 {
2440 #ifdef G_THREADS_ENABLED
2441   gboolean result = FALSE;
2442   GThread *self = G_THREAD_SELF;
2443   gboolean loop_internal_waiter;
2444   
2445   if (context == NULL)
2446     context = g_main_context_default ();
2447
2448   loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2449   
2450   if (!loop_internal_waiter)
2451     LOCK_CONTEXT (context);
2452
2453   if (context->owner && context->owner != self)
2454     {
2455       GMainWaiter waiter;
2456
2457       waiter.cond = cond;
2458       waiter.mutex = mutex;
2459
2460       context->waiters = g_slist_append (context->waiters, &waiter);
2461       
2462       if (!loop_internal_waiter)
2463         UNLOCK_CONTEXT (context);
2464       g_cond_wait (cond, mutex);
2465       if (!loop_internal_waiter)      
2466         LOCK_CONTEXT (context);
2467
2468       context->waiters = g_slist_remove (context->waiters, &waiter);
2469     }
2470
2471   if (!context->owner)
2472     {
2473       context->owner = self;
2474       g_assert (context->owner_count == 0);
2475     }
2476
2477   if (context->owner == self)
2478     {
2479       context->owner_count++;
2480       result = TRUE;
2481     }
2482
2483   if (!loop_internal_waiter)
2484     UNLOCK_CONTEXT (context); 
2485   
2486   return result;
2487 #else /* !G_THREADS_ENABLED */
2488   return TRUE;
2489 #endif /* G_THREADS_ENABLED */
2490 }
2491
2492 /**
2493  * g_main_context_prepare:
2494  * @context: a #GMainContext
2495  * @priority: location to store priority of highest priority
2496  *            source already ready.
2497  * 
2498  * Prepares to poll sources within a main loop. The resulting information
2499  * for polling is determined by calling g_main_context_query ().
2500  * 
2501  * Return value: %TRUE if some source is ready to be dispatched
2502  *               prior to polling.
2503  **/
2504 gboolean
2505 g_main_context_prepare (GMainContext *context,
2506                         gint         *priority)
2507 {
2508   gint i;
2509   gint n_ready = 0;
2510   gint current_priority = G_MAXINT;
2511   GSource *source;
2512
2513   if (context == NULL)
2514     context = g_main_context_default ();
2515   
2516   LOCK_CONTEXT (context);
2517
2518   context->time_is_fresh = FALSE;
2519   context->current_time_is_fresh = FALSE;
2520
2521   if (context->in_check_or_prepare)
2522     {
2523       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2524                  "prepare() member.");
2525       UNLOCK_CONTEXT (context);
2526       return FALSE;
2527     }
2528
2529 #ifdef G_THREADS_ENABLED
2530   if (context->poll_waiting)
2531     {
2532       g_warning("g_main_context_prepare(): main loop already active in another thread");
2533       UNLOCK_CONTEXT (context);
2534       return FALSE;
2535     }
2536   
2537   context->poll_waiting = TRUE;
2538 #endif /* G_THREADS_ENABLED */
2539
2540 #if 0
2541   /* If recursing, finish up current dispatch, before starting over */
2542   if (context->pending_dispatches)
2543     {
2544       if (dispatch)
2545         g_main_dispatch (context, &current_time);
2546       
2547       UNLOCK_CONTEXT (context);
2548       return TRUE;
2549     }
2550 #endif
2551
2552   /* If recursing, clear list of pending dispatches */
2553
2554   for (i = 0; i < context->pending_dispatches->len; i++)
2555     {
2556       if (context->pending_dispatches->pdata[i])
2557         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2558     }
2559   g_ptr_array_set_size (context->pending_dispatches, 0);
2560   
2561   /* Prepare all sources */
2562
2563   context->timeout = -1;
2564   
2565   source = next_valid_source (context, NULL);
2566   while (source)
2567     {
2568       gint source_timeout = -1;
2569
2570       if ((n_ready > 0) && (source->priority > current_priority))
2571         {
2572           SOURCE_UNREF (source, context);
2573           break;
2574         }
2575       if (SOURCE_BLOCKED (source))
2576         goto next;
2577
2578       if (!(source->flags & G_SOURCE_READY))
2579         {
2580           gboolean result;
2581           gboolean (*prepare)  (GSource  *source, 
2582                                 gint     *timeout);
2583
2584           prepare = source->source_funcs->prepare;
2585           context->in_check_or_prepare++;
2586           UNLOCK_CONTEXT (context);
2587
2588           result = (*prepare) (source, &source_timeout);
2589
2590           LOCK_CONTEXT (context);
2591           context->in_check_or_prepare--;
2592
2593           if (result)
2594             source->flags |= G_SOURCE_READY;
2595         }
2596
2597       if (source->flags & G_SOURCE_READY)
2598         {
2599           n_ready++;
2600           current_priority = source->priority;
2601           context->timeout = 0;
2602         }
2603       
2604       if (source_timeout >= 0)
2605         {
2606           if (context->timeout < 0)
2607             context->timeout = source_timeout;
2608           else
2609             context->timeout = MIN (context->timeout, source_timeout);
2610         }
2611
2612     next:
2613       source = next_valid_source (context, source);
2614     }
2615
2616   UNLOCK_CONTEXT (context);
2617   
2618   if (priority)
2619     *priority = current_priority;
2620   
2621   return (n_ready > 0);
2622 }
2623
2624 /**
2625  * g_main_context_query:
2626  * @context: a #GMainContext
2627  * @max_priority: maximum priority source to check
2628  * @timeout_: location to store timeout to be used in polling
2629  * @fds: location to store #GPollFD records that need to be polled.
2630  * @n_fds: length of @fds.
2631  * 
2632  * Determines information necessary to poll this main loop.
2633  * 
2634  * Return value: the number of records actually stored in @fds,
2635  *   or, if more than @n_fds records need to be stored, the number
2636  *   of records that need to be stored.
2637  **/
2638 gint
2639 g_main_context_query (GMainContext *context,
2640                       gint          max_priority,
2641                       gint         *timeout,
2642                       GPollFD      *fds,
2643                       gint          n_fds)
2644 {
2645   gint n_poll;
2646   GPollRec *pollrec;
2647   
2648   LOCK_CONTEXT (context);
2649
2650   pollrec = context->poll_records;
2651   n_poll = 0;
2652   while (pollrec && max_priority >= pollrec->priority)
2653     {
2654       /* We need to include entries with fd->events == 0 in the array because
2655        * otherwise if the application changes fd->events behind our back and 
2656        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2657        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2658        * this API, but it occurs in practice.) */
2659       if (n_poll < n_fds)
2660         {
2661           fds[n_poll].fd = pollrec->fd->fd;
2662           /* In direct contradiction to the Unix98 spec, IRIX runs into
2663            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2664            * flags in the events field of the pollfd while it should
2665            * just ignoring them. So we mask them out here.
2666            */
2667           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2668           fds[n_poll].revents = 0;
2669         }
2670
2671       pollrec = pollrec->next;
2672       n_poll++;
2673     }
2674
2675 #ifdef G_THREADS_ENABLED
2676   context->poll_changed = FALSE;
2677 #endif
2678   
2679   if (timeout)
2680     {
2681       *timeout = context->timeout;
2682       if (*timeout != 0)
2683         {
2684           context->time_is_fresh = FALSE;
2685           context->current_time_is_fresh = FALSE;
2686         }
2687     }
2688   
2689   UNLOCK_CONTEXT (context);
2690
2691   return n_poll;
2692 }
2693
2694 /**
2695  * g_main_context_check:
2696  * @context: a #GMainContext
2697  * @max_priority: the maximum numerical priority of sources to check
2698  * @fds: array of #GPollFD's that was passed to the last call to
2699  *       g_main_context_query()
2700  * @n_fds: return value of g_main_context_query()
2701  * 
2702  * Passes the results of polling back to the main loop.
2703  * 
2704  * Return value: %TRUE if some sources are ready to be dispatched.
2705  **/
2706 gboolean
2707 g_main_context_check (GMainContext *context,
2708                       gint          max_priority,
2709                       GPollFD      *fds,
2710                       gint          n_fds)
2711 {
2712   GSource *source;
2713   GPollRec *pollrec;
2714   gint n_ready = 0;
2715   gint i;
2716    
2717   LOCK_CONTEXT (context);
2718
2719   if (context->in_check_or_prepare)
2720     {
2721       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2722                  "prepare() member.");
2723       UNLOCK_CONTEXT (context);
2724       return FALSE;
2725     }
2726   
2727 #ifdef G_THREADS_ENABLED
2728   if (!context->poll_waiting)
2729     {
2730 #ifndef G_OS_WIN32
2731       gchar a;
2732       read (context->wake_up_pipe[0], &a, 1);
2733 #endif
2734     }
2735   else
2736     context->poll_waiting = FALSE;
2737
2738   /* If the set of poll file descriptors changed, bail out
2739    * and let the main loop rerun
2740    */
2741   if (context->poll_changed)
2742     {
2743       UNLOCK_CONTEXT (context);
2744       return FALSE;
2745     }
2746 #endif /* G_THREADS_ENABLED */
2747   
2748   pollrec = context->poll_records;
2749   i = 0;
2750   while (i < n_fds)
2751     {
2752       if (pollrec->fd->events)
2753         pollrec->fd->revents = fds[i].revents;
2754
2755       pollrec = pollrec->next;
2756       i++;
2757     }
2758
2759   source = next_valid_source (context, NULL);
2760   while (source)
2761     {
2762       if ((n_ready > 0) && (source->priority > max_priority))
2763         {
2764           SOURCE_UNREF (source, context);
2765           break;
2766         }
2767       if (SOURCE_BLOCKED (source))
2768         goto next;
2769
2770       if (!(source->flags & G_SOURCE_READY))
2771         {
2772           gboolean result;
2773           gboolean (*check) (GSource  *source);
2774
2775           check = source->source_funcs->check;
2776           
2777           context->in_check_or_prepare++;
2778           UNLOCK_CONTEXT (context);
2779           
2780           result = (*check) (source);
2781           
2782           LOCK_CONTEXT (context);
2783           context->in_check_or_prepare--;
2784           
2785           if (result)
2786             source->flags |= G_SOURCE_READY;
2787         }
2788
2789       if (source->flags & G_SOURCE_READY)
2790         {
2791           source->ref_count++;
2792           g_ptr_array_add (context->pending_dispatches, source);
2793
2794           n_ready++;
2795
2796           /* never dispatch sources with less priority than the first
2797            * one we choose to dispatch
2798            */
2799           max_priority = source->priority;
2800         }
2801
2802     next:
2803       source = next_valid_source (context, source);
2804     }
2805
2806   UNLOCK_CONTEXT (context);
2807
2808   return n_ready > 0;
2809 }
2810
2811 /**
2812  * g_main_context_dispatch:
2813  * @context: a #GMainContext
2814  * 
2815  * Dispatches all pending sources.
2816  **/
2817 void
2818 g_main_context_dispatch (GMainContext *context)
2819 {
2820   LOCK_CONTEXT (context);
2821
2822   if (context->pending_dispatches->len > 0)
2823     {
2824       g_main_dispatch (context);
2825     }
2826
2827   UNLOCK_CONTEXT (context);
2828 }
2829
2830 /* HOLDS context lock */
2831 static gboolean
2832 g_main_context_iterate (GMainContext *context,
2833                         gboolean      block,
2834                         gboolean      dispatch,
2835                         GThread      *self)
2836 {
2837   gint max_priority;
2838   gint timeout;
2839   gboolean some_ready;
2840   gint nfds, allocated_nfds;
2841   GPollFD *fds = NULL;
2842
2843   UNLOCK_CONTEXT (context);
2844
2845 #ifdef G_THREADS_ENABLED
2846   if (!g_main_context_acquire (context))
2847     {
2848       gboolean got_ownership;
2849
2850       LOCK_CONTEXT (context);
2851
2852       g_return_val_if_fail (g_thread_supported (), FALSE);
2853
2854       if (!block)
2855         return FALSE;
2856
2857       if (!context->cond)
2858         context->cond = g_cond_new ();
2859
2860       got_ownership = g_main_context_wait (context,
2861                                            context->cond,
2862                                            g_static_mutex_get_mutex (&context->mutex));
2863
2864       if (!got_ownership)
2865         return FALSE;
2866     }
2867   else
2868     LOCK_CONTEXT (context);
2869 #endif /* G_THREADS_ENABLED */
2870   
2871   if (!context->cached_poll_array)
2872     {
2873       context->cached_poll_array_size = context->n_poll_records;
2874       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2875     }
2876
2877   allocated_nfds = context->cached_poll_array_size;
2878   fds = context->cached_poll_array;
2879   
2880   UNLOCK_CONTEXT (context);
2881
2882   g_main_context_prepare (context, &max_priority); 
2883   
2884   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
2885                                        allocated_nfds)) > allocated_nfds)
2886     {
2887       LOCK_CONTEXT (context);
2888       g_free (fds);
2889       context->cached_poll_array_size = allocated_nfds = nfds;
2890       context->cached_poll_array = fds = g_new (GPollFD, nfds);
2891       UNLOCK_CONTEXT (context);
2892     }
2893
2894   if (!block)
2895     timeout = 0;
2896   
2897   g_main_context_poll (context, timeout, max_priority, fds, nfds);
2898   
2899   some_ready = g_main_context_check (context, max_priority, fds, nfds);
2900   
2901   if (dispatch)
2902     g_main_context_dispatch (context);
2903   
2904 #ifdef G_THREADS_ENABLED
2905   g_main_context_release (context);
2906 #endif /* G_THREADS_ENABLED */    
2907
2908   LOCK_CONTEXT (context);
2909
2910   return some_ready;
2911 }
2912
2913 /**
2914  * g_main_context_pending:
2915  * @context: a #GMainContext (if %NULL, the default context will be used)
2916  *
2917  * Checks if any sources have pending events for the given context.
2918  * 
2919  * Return value: %TRUE if events are pending.
2920  **/
2921 gboolean 
2922 g_main_context_pending (GMainContext *context)
2923 {
2924   gboolean retval;
2925
2926   if (!context)
2927     context = g_main_context_default();
2928
2929   LOCK_CONTEXT (context);
2930   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2931   UNLOCK_CONTEXT (context);
2932   
2933   return retval;
2934 }
2935
2936 /**
2937  * g_main_context_iteration:
2938  * @context: a #GMainContext (if %NULL, the default context will be used) 
2939  * @may_block: whether the call may block.
2940  * 
2941  * Runs a single iteration for the given main loop. This involves
2942  * checking to see if any event sources are ready to be processed,
2943  * then if no events sources are ready and @may_block is %TRUE, waiting
2944  * for a source to become ready, then dispatching the highest priority
2945  * events sources that are ready. Otherwise, if @may_block is %FALSE 
2946  * sources are not waited to become ready, only those highest priority 
2947  * events sources will be dispatched (if any), that are ready at this 
2948  * given moment without further waiting.
2949  *
2950  * Note that even when @may_block is %TRUE, it is still possible for 
2951  * g_main_context_iteration() to return %FALSE, since the the wait may 
2952  * be interrupted for other reasons than an event source becoming ready.
2953  * 
2954  * Return value: %TRUE if events were dispatched.
2955  **/
2956 gboolean
2957 g_main_context_iteration (GMainContext *context, gboolean may_block)
2958 {
2959   gboolean retval;
2960
2961   if (!context)
2962     context = g_main_context_default();
2963   
2964   LOCK_CONTEXT (context);
2965   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2966   UNLOCK_CONTEXT (context);
2967   
2968   return retval;
2969 }
2970
2971 /**
2972  * g_main_loop_new:
2973  * @context: a #GMainContext  (if %NULL, the default context will be used).
2974  * @is_running: set to %TRUE to indicate that the loop is running. This
2975  * is not very important since calling g_main_loop_run() will set this to
2976  * %TRUE anyway.
2977  * 
2978  * Creates a new #GMainLoop structure.
2979  * 
2980  * Return value: a new #GMainLoop.
2981  **/
2982 GMainLoop *
2983 g_main_loop_new (GMainContext *context,
2984                  gboolean      is_running)
2985 {
2986   GMainLoop *loop;
2987
2988   if (!context)
2989     context = g_main_context_default();
2990   
2991   g_main_context_ref (context);
2992
2993   loop = g_new0 (GMainLoop, 1);
2994   loop->context = context;
2995   loop->is_running = is_running != FALSE;
2996   loop->ref_count = 1;
2997   
2998   return loop;
2999 }
3000
3001 /**
3002  * g_main_loop_ref:
3003  * @loop: a #GMainLoop
3004  * 
3005  * Increases the reference count on a #GMainLoop object by one.
3006  * 
3007  * Return value: @loop
3008  **/
3009 GMainLoop *
3010 g_main_loop_ref (GMainLoop *loop)
3011 {
3012   g_return_val_if_fail (loop != NULL, NULL);
3013   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3014
3015   g_atomic_int_inc (&loop->ref_count);
3016
3017   return loop;
3018 }
3019
3020 /**
3021  * g_main_loop_unref:
3022  * @loop: a #GMainLoop
3023  * 
3024  * Decreases the reference count on a #GMainLoop object by one. If
3025  * the result is zero, free the loop and free all associated memory.
3026  **/
3027 void
3028 g_main_loop_unref (GMainLoop *loop)
3029 {
3030   g_return_if_fail (loop != NULL);
3031   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3032
3033   if (!g_atomic_int_dec_and_test (&loop->ref_count))
3034     return;
3035
3036   g_main_context_unref (loop->context);
3037   g_free (loop);
3038 }
3039
3040 /**
3041  * g_main_loop_run:
3042  * @loop: a #GMainLoop
3043  * 
3044  * Runs a main loop until g_main_loop_quit() is called on the loop.
3045  * If this is called for the thread of the loop's #GMainContext,
3046  * it will process events from the loop, otherwise it will
3047  * simply wait.
3048  **/
3049 void 
3050 g_main_loop_run (GMainLoop *loop)
3051 {
3052   GThread *self = G_THREAD_SELF;
3053
3054   g_return_if_fail (loop != NULL);
3055   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3056
3057 #ifdef G_THREADS_ENABLED
3058   if (!g_main_context_acquire (loop->context))
3059     {
3060       gboolean got_ownership = FALSE;
3061       
3062       /* Another thread owns this context */
3063       if (!g_thread_supported ())
3064         {
3065           g_warning ("g_main_loop_run() was called from second thread but "
3066                      "g_thread_init() was never called.");
3067           return;
3068         }
3069       
3070       LOCK_CONTEXT (loop->context);
3071
3072       g_atomic_int_inc (&loop->ref_count);
3073
3074       if (!loop->is_running)
3075         loop->is_running = TRUE;
3076
3077       if (!loop->context->cond)
3078         loop->context->cond = g_cond_new ();
3079           
3080       while (loop->is_running && !got_ownership)
3081         got_ownership = g_main_context_wait (loop->context,
3082                                              loop->context->cond,
3083                                              g_static_mutex_get_mutex (&loop->context->mutex));
3084       
3085       if (!loop->is_running)
3086         {
3087           UNLOCK_CONTEXT (loop->context);
3088           if (got_ownership)
3089             g_main_context_release (loop->context);
3090           g_main_loop_unref (loop);
3091           return;
3092         }
3093
3094       g_assert (got_ownership);
3095     }
3096   else
3097     LOCK_CONTEXT (loop->context);
3098 #endif /* G_THREADS_ENABLED */ 
3099
3100   if (loop->context->in_check_or_prepare)
3101     {
3102       g_warning ("g_main_loop_run(): called recursively from within a source's "
3103                  "check() or prepare() member, iteration not possible.");
3104       return;
3105     }
3106
3107   g_atomic_int_inc (&loop->ref_count);
3108   loop->is_running = TRUE;
3109   while (loop->is_running)
3110     g_main_context_iterate (loop->context, TRUE, TRUE, self);
3111
3112   UNLOCK_CONTEXT (loop->context);
3113   
3114 #ifdef G_THREADS_ENABLED
3115   g_main_context_release (loop->context);
3116 #endif /* G_THREADS_ENABLED */    
3117   
3118   g_main_loop_unref (loop);
3119 }
3120
3121 /**
3122  * g_main_loop_quit:
3123  * @loop: a #GMainLoop
3124  * 
3125  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3126  * for the loop will return. 
3127  *
3128  * Note that sources that have already been dispatched when 
3129  * g_main_loop_quit() is called will still be executed.
3130  **/
3131 void 
3132 g_main_loop_quit (GMainLoop *loop)
3133 {
3134   g_return_if_fail (loop != NULL);
3135   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3136
3137   LOCK_CONTEXT (loop->context);
3138   loop->is_running = FALSE;
3139   g_main_context_wakeup_unlocked (loop->context);
3140
3141 #ifdef G_THREADS_ENABLED
3142   if (loop->context->cond)
3143     g_cond_broadcast (loop->context->cond);
3144 #endif /* G_THREADS_ENABLED */
3145
3146   UNLOCK_CONTEXT (loop->context);
3147 }
3148
3149 /**
3150  * g_main_loop_is_running:
3151  * @loop: a #GMainLoop.
3152  * 
3153  * Checks to see if the main loop is currently being run via g_main_loop_run().
3154  * 
3155  * Return value: %TRUE if the mainloop is currently being run.
3156  **/
3157 gboolean
3158 g_main_loop_is_running (GMainLoop *loop)
3159 {
3160   g_return_val_if_fail (loop != NULL, FALSE);
3161   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3162
3163   return loop->is_running;
3164 }
3165
3166 /**
3167  * g_main_loop_get_context:
3168  * @loop: a #GMainLoop.
3169  * 
3170  * Returns the #GMainContext of @loop.
3171  * 
3172  * Return value: the #GMainContext of @loop
3173  **/
3174 GMainContext *
3175 g_main_loop_get_context (GMainLoop *loop)
3176 {
3177   g_return_val_if_fail (loop != NULL, NULL);
3178   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3179  
3180   return loop->context;
3181 }
3182
3183 /* HOLDS: context's lock */
3184 static void
3185 g_main_context_poll (GMainContext *context,
3186                      gint          timeout,
3187                      gint          priority,
3188                      GPollFD      *fds,
3189                      gint          n_fds)
3190 {
3191 #ifdef  G_MAIN_POLL_DEBUG
3192   GTimer *poll_timer;
3193   GPollRec *pollrec;
3194   gint i;
3195 #endif
3196
3197   GPollFunc poll_func;
3198
3199   if (n_fds || timeout != 0)
3200     {
3201 #ifdef  G_MAIN_POLL_DEBUG
3202       if (_g_main_poll_debug)
3203         {
3204           g_print ("polling context=%p n=%d timeout=%d\n",
3205                    context, n_fds, timeout);
3206           poll_timer = g_timer_new ();
3207         }
3208 #endif
3209
3210       LOCK_CONTEXT (context);
3211
3212       poll_func = context->poll_func;
3213       
3214       UNLOCK_CONTEXT (context);
3215       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3216         {
3217 #ifndef G_OS_WIN32
3218           g_warning ("poll(2) failed due to: %s.",
3219                      g_strerror (errno));
3220 #else
3221           /* If g_poll () returns -1, it has already called g_warning() */
3222 #endif
3223         }
3224       
3225 #ifdef  G_MAIN_POLL_DEBUG
3226       if (_g_main_poll_debug)
3227         {
3228           LOCK_CONTEXT (context);
3229
3230           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3231                    n_fds,
3232                    timeout,
3233                    g_timer_elapsed (poll_timer, NULL));
3234           g_timer_destroy (poll_timer);
3235           pollrec = context->poll_records;
3236
3237           while (pollrec != NULL)
3238             {
3239               i = 0;
3240               while (i < n_fds)
3241                 {
3242                   if (fds[i].fd == pollrec->fd->fd &&
3243                       pollrec->fd->events &&
3244                       fds[i].revents)
3245                     {
3246                       g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3247                       if (fds[i].revents & G_IO_IN)
3248                         g_print ("i");
3249                       if (fds[i].revents & G_IO_OUT)
3250                         g_print ("o");
3251                       if (fds[i].revents & G_IO_PRI)
3252                         g_print ("p");
3253                       if (fds[i].revents & G_IO_ERR)
3254                         g_print ("e");
3255                       if (fds[i].revents & G_IO_HUP)
3256                         g_print ("h");
3257                       if (fds[i].revents & G_IO_NVAL)
3258                         g_print ("n");
3259                       g_print ("]");
3260                     }
3261                   i++;
3262                 }
3263               pollrec = pollrec->next;
3264             }
3265           g_print ("\n");
3266
3267           UNLOCK_CONTEXT (context);
3268         }
3269 #endif
3270     } /* if (n_fds || timeout != 0) */
3271 }
3272
3273 /**
3274  * g_main_context_add_poll:
3275  * @context: a #GMainContext (or %NULL for the default context)
3276  * @fd: a #GPollFD structure holding information about a file
3277  *      descriptor to watch.
3278  * @priority: the priority for this file descriptor which should be
3279  *      the same as the priority used for g_source_attach() to ensure that the
3280  *      file descriptor is polled whenever the results may be needed.
3281  * 
3282  * Adds a file descriptor to the set of file descriptors polled for
3283  * this context. This will very seldomly be used directly. Instead
3284  * a typical event source will use g_source_add_poll() instead.
3285  **/
3286 void
3287 g_main_context_add_poll (GMainContext *context,
3288                          GPollFD      *fd,
3289                          gint          priority)
3290 {
3291   if (!context)
3292     context = g_main_context_default ();
3293   
3294   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3295   g_return_if_fail (fd);
3296
3297   LOCK_CONTEXT (context);
3298   g_main_context_add_poll_unlocked (context, priority, fd);
3299   UNLOCK_CONTEXT (context);
3300 }
3301
3302 /* HOLDS: main_loop_lock */
3303 static void 
3304 g_main_context_add_poll_unlocked (GMainContext *context,
3305                                   gint          priority,
3306                                   GPollFD      *fd)
3307 {
3308   GPollRec *lastrec, *pollrec;
3309   GPollRec *newrec = g_slice_new (GPollRec);
3310
3311   /* This file descriptor may be checked before we ever poll */
3312   fd->revents = 0;
3313   newrec->fd = fd;
3314   newrec->priority = priority;
3315
3316   lastrec = NULL;
3317   pollrec = context->poll_records;
3318   while (pollrec && priority >= pollrec->priority)
3319     {
3320       lastrec = pollrec;
3321       pollrec = pollrec->next;
3322     }
3323   
3324   if (lastrec)
3325     lastrec->next = newrec;
3326   else
3327     context->poll_records = newrec;
3328
3329   newrec->next = pollrec;
3330
3331   context->n_poll_records++;
3332
3333 #ifdef G_THREADS_ENABLED
3334   context->poll_changed = TRUE;
3335
3336   /* Now wake up the main loop if it is waiting in the poll() */
3337   g_main_context_wakeup_unlocked (context);
3338 #endif
3339 }
3340
3341 /**
3342  * g_main_context_remove_poll:
3343  * @context:a #GMainContext 
3344  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3345  * 
3346  * Removes file descriptor from the set of file descriptors to be
3347  * polled for a particular context.
3348  **/
3349 void
3350 g_main_context_remove_poll (GMainContext *context,
3351                             GPollFD      *fd)
3352 {
3353   if (!context)
3354     context = g_main_context_default ();
3355   
3356   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3357   g_return_if_fail (fd);
3358
3359   LOCK_CONTEXT (context);
3360   g_main_context_remove_poll_unlocked (context, fd);
3361   UNLOCK_CONTEXT (context);
3362 }
3363
3364 static void
3365 g_main_context_remove_poll_unlocked (GMainContext *context,
3366                                      GPollFD      *fd)
3367 {
3368   GPollRec *pollrec, *lastrec;
3369
3370   lastrec = NULL;
3371   pollrec = context->poll_records;
3372
3373   while (pollrec)
3374     {
3375       if (pollrec->fd == fd)
3376         {
3377           if (lastrec != NULL)
3378             lastrec->next = pollrec->next;
3379           else
3380             context->poll_records = pollrec->next;
3381
3382           g_slice_free (GPollRec, pollrec);
3383
3384           context->n_poll_records--;
3385           break;
3386         }
3387       lastrec = pollrec;
3388       pollrec = pollrec->next;
3389     }
3390
3391 #ifdef G_THREADS_ENABLED
3392   context->poll_changed = TRUE;
3393   
3394   /* Now wake up the main loop if it is waiting in the poll() */
3395   g_main_context_wakeup_unlocked (context);
3396 #endif
3397 }
3398
3399 /**
3400  * g_source_get_current_time:
3401  * @source:  a #GSource
3402  * @timeval: #GTimeVal structure in which to store current time.
3403  * 
3404  * Gets the "current time" to be used when checking 
3405  * this source. The advantage of calling this function over
3406  * calling g_get_current_time() directly is that when 
3407  * checking multiple sources, GLib can cache a single value
3408  * instead of having to repeatedly get the system time.
3409  *
3410  * Deprecated: 2.28: use g_source_get_time() instead
3411  **/
3412 void
3413 g_source_get_current_time (GSource  *source,
3414                            GTimeVal *timeval)
3415 {
3416   GMainContext *context;
3417   
3418   g_return_if_fail (source->context != NULL);
3419  
3420   context = source->context;
3421
3422   LOCK_CONTEXT (context);
3423
3424   if (!context->current_time_is_fresh)
3425     {
3426       g_get_current_time (&context->current_time);
3427       context->current_time_is_fresh = TRUE;
3428     }
3429   
3430   *timeval = context->current_time;
3431   
3432   UNLOCK_CONTEXT (context);
3433 }
3434
3435 /**
3436  * g_source_get_time:
3437  * @source: a #GSource
3438  *
3439  * Gets the time to be used when checking this source. The advantage of
3440  * calling this function over calling g_get_monotonic_time() directly is
3441  * that when checking multiple sources, GLib can cache a single value
3442  * instead of having to repeatedly get the system monotonic time.
3443  *
3444  * The time here is the system monotonic time, if available, or some
3445  * other reasonable alternative otherwise.  See g_get_monotonic_time().
3446  *
3447  * Returns: the monotonic time in microseconds
3448  *
3449  * Since: 2.28
3450  **/
3451 gint64
3452 g_source_get_time (GSource *source)
3453 {
3454   GMainContext *context;
3455   gint64 result;
3456
3457   g_return_val_if_fail (source->context != NULL, 0);
3458
3459   context = source->context;
3460
3461   LOCK_CONTEXT (context);
3462
3463   if (!context->time_is_fresh)
3464     {
3465       context->time = g_get_monotonic_time ();
3466       context->time_is_fresh = TRUE;
3467     }
3468
3469   result = context->time;
3470
3471   UNLOCK_CONTEXT (context);
3472
3473   return result;
3474 }
3475
3476 /**
3477  * g_main_context_set_poll_func:
3478  * @context: a #GMainContext
3479  * @func: the function to call to poll all file descriptors
3480  * 
3481  * Sets the function to use to handle polling of file descriptors. It
3482  * will be used instead of the poll() system call 
3483  * (or GLib's replacement function, which is used where 
3484  * poll() isn't available).
3485  *
3486  * This function could possibly be used to integrate the GLib event
3487  * loop with an external event loop.
3488  **/
3489 void
3490 g_main_context_set_poll_func (GMainContext *context,
3491                               GPollFunc     func)
3492 {
3493   if (!context)
3494     context = g_main_context_default ();
3495   
3496   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3497
3498   LOCK_CONTEXT (context);
3499   
3500   if (func)
3501     context->poll_func = func;
3502   else
3503     context->poll_func = g_poll;
3504
3505   UNLOCK_CONTEXT (context);
3506 }
3507
3508 /**
3509  * g_main_context_get_poll_func:
3510  * @context: a #GMainContext
3511  * 
3512  * Gets the poll function set by g_main_context_set_poll_func().
3513  * 
3514  * Return value: the poll function
3515  **/
3516 GPollFunc
3517 g_main_context_get_poll_func (GMainContext *context)
3518 {
3519   GPollFunc result;
3520   
3521   if (!context)
3522     context = g_main_context_default ();
3523   
3524   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3525
3526   LOCK_CONTEXT (context);
3527   result = context->poll_func;
3528   UNLOCK_CONTEXT (context);
3529
3530   return result;
3531 }
3532
3533 /* HOLDS: context's lock */
3534 /* Wake the main loop up from a poll() */
3535 static void
3536 g_main_context_wakeup_unlocked (GMainContext *context)
3537 {
3538 #ifdef G_THREADS_ENABLED
3539   if (g_thread_supported() && context->poll_waiting)
3540     {
3541       context->poll_waiting = FALSE;
3542 #ifndef G_OS_WIN32
3543       write (context->wake_up_pipe[1], "A", 1);
3544 #else
3545       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3546 #endif
3547     }
3548 #endif
3549 }
3550
3551 /**
3552  * g_main_context_wakeup:
3553  * @context: a #GMainContext
3554  * 
3555  * If @context is currently waiting in a poll(), interrupt
3556  * the poll(), and continue the iteration process.
3557  **/
3558 void
3559 g_main_context_wakeup (GMainContext *context)
3560 {
3561   if (!context)
3562     context = g_main_context_default ();
3563   
3564   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3565
3566   LOCK_CONTEXT (context);
3567   g_main_context_wakeup_unlocked (context);
3568   UNLOCK_CONTEXT (context);
3569 }
3570
3571 /**
3572  * g_main_context_is_owner:
3573  * @context: a #GMainContext
3574  * 
3575  * Determines whether this thread holds the (recursive)
3576  * ownership of this #GMaincontext. This is useful to
3577  * know before waiting on another thread that may be
3578  * blocking to get ownership of @context.
3579  *
3580  * Returns: %TRUE if current thread is owner of @context.
3581  *
3582  * Since: 2.10
3583  **/
3584 gboolean
3585 g_main_context_is_owner (GMainContext *context)
3586 {
3587   gboolean is_owner;
3588
3589   if (!context)
3590     context = g_main_context_default ();
3591
3592 #ifdef G_THREADS_ENABLED
3593   LOCK_CONTEXT (context);
3594   is_owner = context->owner == G_THREAD_SELF;
3595   UNLOCK_CONTEXT (context);
3596 #else
3597   is_owner = TRUE;
3598 #endif
3599
3600   return is_owner;
3601 }
3602
3603 /* Timeouts */
3604
3605 static void
3606 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3607                           gint64          current_time)
3608 {
3609   timeout_source->expiration = current_time + timeout_source->interval * 1000;
3610
3611   if (timeout_source->seconds)
3612     {
3613       static gint timer_perturb = -1;
3614
3615       if (timer_perturb == -1)
3616         {
3617           /*
3618            * we want a per machine/session unique 'random' value; try the dbus
3619            * address first, that has a UUID in it. If there is no dbus, use the
3620            * hostname for hashing.
3621            */
3622           const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3623           if (!session_bus_address)
3624             session_bus_address = g_getenv ("HOSTNAME");
3625           if (session_bus_address)
3626             timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3627           else
3628             timer_perturb = 0;
3629         }
3630
3631       /* We want the microseconds part of the timeout to land on the
3632        * 'timer_perturb' mark, but we need to make sure we don't try to
3633        * set the timeout in the past.  We do this by ensuring that we
3634        * always only *increase* the expiration time by adding a full
3635        * second in the case that the microsecond portion decreases.
3636        */
3637       if (timer_perturb < timeout_source->expiration % 1000000)
3638         timeout_source->expiration += 1000000;
3639
3640       timeout_source->expiration =
3641         ((timeout_source->expiration / 1000000) * 1000000) + timer_perturb;
3642     }
3643 }
3644
3645 static gboolean
3646 g_timeout_prepare (GSource *source,
3647                    gint    *timeout)
3648 {
3649   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3650   gint64 now = g_source_get_time (source);
3651
3652   if (now < timeout_source->expiration)
3653     {
3654       /* Round up to ensure that we don't try again too early */
3655       *timeout = (timeout_source->expiration - now + 999) / 1000;
3656       return FALSE;
3657     }
3658
3659   *timeout = 0;
3660   return TRUE;
3661 }
3662
3663 static gboolean 
3664 g_timeout_check (GSource *source)
3665 {
3666   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3667   gint64 now = g_source_get_time (source);
3668
3669   return timeout_source->expiration <= now;
3670 }
3671
3672 static gboolean
3673 g_timeout_dispatch (GSource     *source,
3674                     GSourceFunc  callback,
3675                     gpointer     user_data)
3676 {
3677   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3678   gboolean again;
3679
3680   if (!callback)
3681     {
3682       g_warning ("Timeout source dispatched without callback\n"
3683                  "You must call g_source_set_callback().");
3684       return FALSE;
3685     }
3686
3687   again = callback (user_data);
3688
3689   if (again)
3690     g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3691
3692   return again;
3693 }
3694
3695 /**
3696  * g_timeout_source_new:
3697  * @interval: the timeout interval in milliseconds.
3698  * 
3699  * Creates a new timeout source.
3700  *
3701  * The source will not initially be associated with any #GMainContext
3702  * and must be added to one with g_source_attach() before it will be
3703  * executed.
3704  * 
3705  * Return value: the newly-created timeout source
3706  **/
3707 GSource *
3708 g_timeout_source_new (guint interval)
3709 {
3710   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3711   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3712
3713   timeout_source->interval = interval;
3714   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3715
3716   return source;
3717 }
3718
3719 /**
3720  * g_timeout_source_new_seconds:
3721  * @interval: the timeout interval in seconds
3722  *
3723  * Creates a new timeout source.
3724  *
3725  * The source will not initially be associated with any #GMainContext
3726  * and must be added to one with g_source_attach() before it will be
3727  * executed.
3728  *
3729  * The scheduling granularity/accuracy of this timeout source will be
3730  * in seconds.
3731  *
3732  * Return value: the newly-created timeout source
3733  *
3734  * Since: 2.14  
3735  **/
3736 GSource *
3737 g_timeout_source_new_seconds (guint interval)
3738 {
3739   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3740   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3741
3742   timeout_source->interval = 1000 * interval;
3743   timeout_source->seconds = TRUE;
3744
3745   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3746
3747   return source;
3748 }
3749
3750
3751 /**
3752  * g_timeout_add_full:
3753  * @priority: the priority of the timeout source. Typically this will be in
3754  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3755  * @interval: the time between calls to the function, in milliseconds
3756  *             (1/1000ths of a second)
3757  * @function: function to call
3758  * @data:     data to pass to @function
3759  * @notify:   function to call when the timeout is removed, or %NULL
3760  * 
3761  * Sets a function to be called at regular intervals, with the given
3762  * priority.  The function is called repeatedly until it returns
3763  * %FALSE, at which point the timeout is automatically destroyed and
3764  * the function will not be called again.  The @notify function is
3765  * called when the timeout is destroyed.  The first call to the
3766  * function will be at the end of the first @interval.
3767  *
3768  * Note that timeout functions may be delayed, due to the processing of other
3769  * event sources. Thus they should not be relied on for precise timing.
3770  * After each call to the timeout function, the time of the next
3771  * timeout is recalculated based on the current time and the given interval
3772  * (it does not try to 'catch up' time lost in delays).
3773  *
3774  * This internally creates a main loop source using g_timeout_source_new()
3775  * and attaches it to the main loop context using g_source_attach(). You can
3776  * do these steps manually if you need greater control.
3777  * 
3778  * Return value: the ID (greater than 0) of the event source.
3779  **/
3780 guint
3781 g_timeout_add_full (gint           priority,
3782                     guint          interval,
3783                     GSourceFunc    function,
3784                     gpointer       data,
3785                     GDestroyNotify notify)
3786 {
3787   GSource *source;
3788   guint id;
3789   
3790   g_return_val_if_fail (function != NULL, 0);
3791
3792   source = g_timeout_source_new (interval);
3793
3794   if (priority != G_PRIORITY_DEFAULT)
3795     g_source_set_priority (source, priority);
3796
3797   g_source_set_callback (source, function, data, notify);
3798   id = g_source_attach (source, NULL);
3799   g_source_unref (source);
3800
3801   return id;
3802 }
3803
3804 /**
3805  * g_timeout_add:
3806  * @interval: the time between calls to the function, in milliseconds
3807  *             (1/1000ths of a second)
3808  * @function: function to call
3809  * @data:     data to pass to @function
3810  * 
3811  * Sets a function to be called at regular intervals, with the default
3812  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3813  * until it returns %FALSE, at which point the timeout is automatically
3814  * destroyed and the function will not be called again.  The first call
3815  * to the function will be at the end of the first @interval.
3816  *
3817  * Note that timeout functions may be delayed, due to the processing of other
3818  * event sources. Thus they should not be relied on for precise timing.
3819  * After each call to the timeout function, the time of the next
3820  * timeout is recalculated based on the current time and the given interval
3821  * (it does not try to 'catch up' time lost in delays).
3822  *
3823  * If you want to have a timer in the "seconds" range and do not care
3824  * about the exact time of the first call of the timer, use the
3825  * g_timeout_add_seconds() function; this function allows for more
3826  * optimizations and more efficient system power usage.
3827  *
3828  * This internally creates a main loop source using g_timeout_source_new()
3829  * and attaches it to the main loop context using g_source_attach(). You can
3830  * do these steps manually if you need greater control.
3831  * 
3832  * Return value: the ID (greater than 0) of the event source.
3833  **/
3834 guint
3835 g_timeout_add (guint32        interval,
3836                GSourceFunc    function,
3837                gpointer       data)
3838 {
3839   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3840                              interval, function, data, NULL);
3841 }
3842
3843 /**
3844  * g_timeout_add_seconds_full:
3845  * @priority: the priority of the timeout source. Typically this will be in
3846  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3847  * @interval: the time between calls to the function, in seconds
3848  * @function: function to call
3849  * @data:     data to pass to @function
3850  * @notify:   function to call when the timeout is removed, or %NULL
3851  *
3852  * Sets a function to be called at regular intervals, with @priority.
3853  * The function is called repeatedly until it returns %FALSE, at which
3854  * point the timeout is automatically destroyed and the function will
3855  * not be called again.
3856  *
3857  * Unlike g_timeout_add(), this function operates at whole second granularity.
3858  * The initial starting point of the timer is determined by the implementation
3859  * and the implementation is expected to group multiple timers together so that
3860  * they fire all at the same time.
3861  * To allow this grouping, the @interval to the first timer is rounded
3862  * and can deviate up to one second from the specified interval.
3863  * Subsequent timer iterations will generally run at the specified interval.
3864  *
3865  * Note that timeout functions may be delayed, due to the processing of other
3866  * event sources. Thus they should not be relied on for precise timing.
3867  * After each call to the timeout function, the time of the next
3868  * timeout is recalculated based on the current time and the given @interval
3869  *
3870  * If you want timing more precise than whole seconds, use g_timeout_add()
3871  * instead.
3872  *
3873  * The grouping of timers to fire at the same time results in a more power
3874  * and CPU efficient behavior so if your timer is in multiples of seconds
3875  * and you don't require the first timer exactly one second from now, the
3876  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3877  *
3878  * This internally creates a main loop source using 
3879  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3880  * using g_source_attach(). You can do these steps manually if you need 
3881  * greater control.
3882  * 
3883  * Return value: the ID (greater than 0) of the event source.
3884  *
3885  * Since: 2.14
3886  **/
3887 guint
3888 g_timeout_add_seconds_full (gint           priority,
3889                             guint32        interval,
3890                             GSourceFunc    function,
3891                             gpointer       data,
3892                             GDestroyNotify notify)
3893 {
3894   GSource *source;
3895   guint id;
3896
3897   g_return_val_if_fail (function != NULL, 0);
3898
3899   source = g_timeout_source_new_seconds (interval);
3900
3901   if (priority != G_PRIORITY_DEFAULT)
3902     g_source_set_priority (source, priority);
3903
3904   g_source_set_callback (source, function, data, notify);
3905   id = g_source_attach (source, NULL);
3906   g_source_unref (source);
3907
3908   return id;
3909 }
3910
3911 /**
3912  * g_timeout_add_seconds:
3913  * @interval: the time between calls to the function, in seconds
3914  * @function: function to call
3915  * @data: data to pass to @function
3916  *
3917  * Sets a function to be called at regular intervals with the default
3918  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3919  * it returns %FALSE, at which point the timeout is automatically destroyed
3920  * and the function will not be called again.
3921  *
3922  * This internally creates a main loop source using 
3923  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3924  * using g_source_attach(). You can do these steps manually if you need 
3925  * greater control. Also see g_timout_add_seconds_full().
3926  * 
3927  * Return value: the ID (greater than 0) of the event source.
3928  *
3929  * Since: 2.14
3930  **/
3931 guint
3932 g_timeout_add_seconds (guint       interval,
3933                        GSourceFunc function,
3934                        gpointer    data)
3935 {
3936   g_return_val_if_fail (function != NULL, 0);
3937
3938   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3939 }
3940
3941 /* Child watch functions */
3942
3943 #ifdef G_OS_WIN32
3944
3945 static gboolean
3946 g_child_watch_prepare (GSource *source,
3947                        gint    *timeout)
3948 {
3949   *timeout = -1;
3950   return FALSE;
3951 }
3952
3953
3954 static gboolean 
3955 g_child_watch_check (GSource  *source)
3956 {
3957   GChildWatchSource *child_watch_source;
3958   gboolean child_exited;
3959
3960   child_watch_source = (GChildWatchSource *) source;
3961
3962   child_exited = child_watch_source->poll.revents & G_IO_IN;
3963
3964   if (child_exited)
3965     {
3966       DWORD child_status;
3967
3968       /*
3969        * Note: We do _not_ check for the special value of STILL_ACTIVE
3970        * since we know that the process has exited and doing so runs into
3971        * problems if the child process "happens to return STILL_ACTIVE(259)"
3972        * as Microsoft's Platform SDK puts it.
3973        */
3974       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3975         {
3976           gchar *emsg = g_win32_error_message (GetLastError ());
3977           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3978           g_free (emsg);
3979
3980           child_watch_source->child_status = -1;
3981         }
3982       else
3983         child_watch_source->child_status = child_status;
3984     }
3985
3986   return child_exited;
3987 }
3988
3989 #else /* G_OS_WIN32 */
3990
3991 static gboolean
3992 check_for_child_exited (GSource *source)
3993 {
3994   GChildWatchSource *child_watch_source;
3995   gint count;
3996
3997   /* protect against another SIGCHLD in the middle of this call */
3998   count = child_watch_count;
3999
4000   child_watch_source = (GChildWatchSource *) source;
4001
4002   if (child_watch_source->child_exited)
4003     return TRUE;
4004
4005   if (child_watch_source->count < count)
4006     {
4007       gint child_status;
4008
4009       if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4010         {
4011           child_watch_source->child_status = child_status;
4012           child_watch_source->child_exited = TRUE;
4013         }
4014       child_watch_source->count = count;
4015     }
4016
4017   return child_watch_source->child_exited;
4018 }
4019
4020 static gboolean
4021 g_child_watch_prepare (GSource *source,
4022                        gint    *timeout)
4023 {
4024   *timeout = -1;
4025
4026   return check_for_child_exited (source);
4027 }
4028
4029
4030 static gboolean 
4031 g_child_watch_check (GSource  *source)
4032 {
4033   return check_for_child_exited (source);
4034 }
4035
4036 #endif /* G_OS_WIN32 */
4037
4038 static gboolean
4039 g_child_watch_dispatch (GSource    *source, 
4040                         GSourceFunc callback,
4041                         gpointer    user_data)
4042 {
4043   GChildWatchSource *child_watch_source;
4044   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4045
4046   child_watch_source = (GChildWatchSource *) source;
4047
4048   if (!callback)
4049     {
4050       g_warning ("Child watch source dispatched without callback\n"
4051                  "You must call g_source_set_callback().");
4052       return FALSE;
4053     }
4054
4055   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4056
4057   /* We never keep a child watch source around as the child is gone */
4058   return FALSE;
4059 }
4060
4061 #ifndef G_OS_WIN32
4062
4063 static void
4064 g_child_watch_signal_handler (int signum)
4065 {
4066   child_watch_count ++;
4067
4068   if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4069     {
4070       write (child_watch_wake_up_pipe[1], "B", 1);
4071     }
4072   else
4073     {
4074       /* We count on the signal interrupting the poll in the same thread.
4075        */
4076     }
4077 }
4078  
4079 static void
4080 g_child_watch_source_init_single (void)
4081 {
4082   struct sigaction action;
4083
4084   g_assert (! g_thread_supported());
4085   g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4086
4087   child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4088
4089   action.sa_handler = g_child_watch_signal_handler;
4090   sigemptyset (&action.sa_mask);
4091   action.sa_flags = SA_NOCLDSTOP;
4092   sigaction (SIGCHLD, &action, NULL);
4093 }
4094
4095 G_GNUC_NORETURN static gpointer
4096 child_watch_helper_thread (gpointer data) 
4097 {
4098   while (1)
4099     {
4100       gchar b[20];
4101       GSList *list;
4102
4103       read (child_watch_wake_up_pipe[0], b, 20);
4104
4105       /* We were woken up.  Wake up all other contexts in all other threads */
4106       G_LOCK (main_context_list);
4107       for (list = main_context_list; list; list = list->next)
4108         {
4109           GMainContext *context;
4110
4111           context = list->data;
4112           if (g_atomic_int_get (&context->ref_count) > 0)
4113             /* Due to racing conditions we can find ref_count == 0, in
4114              * that case, however, the context is still not destroyed
4115              * and no poll can be active, otherwise the ref_count
4116              * wouldn't be 0 */
4117             g_main_context_wakeup (context);
4118         }
4119       G_UNLOCK (main_context_list);
4120     }
4121 }
4122
4123 static void
4124 g_child_watch_source_init_multi_threaded (void)
4125 {
4126   GError *error = NULL;
4127   struct sigaction action;
4128
4129   g_assert (g_thread_supported());
4130
4131   if (pipe (child_watch_wake_up_pipe) < 0)
4132     g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4133   fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4134
4135   /* We create a helper thread that polls on the wakeup pipe indefinitely */
4136   /* FIXME: Think this through for races */
4137   if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4138     g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4139   child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4140  
4141   action.sa_handler = g_child_watch_signal_handler;
4142   sigemptyset (&action.sa_mask);
4143   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4144   sigaction (SIGCHLD, &action, NULL);
4145 }
4146
4147 static void
4148 g_child_watch_source_init_promote_single_to_threaded (void)
4149 {
4150   g_child_watch_source_init_multi_threaded ();
4151 }
4152
4153 static void
4154 g_child_watch_source_init (void)
4155 {
4156   if (g_thread_supported())
4157     {
4158       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4159         g_child_watch_source_init_multi_threaded ();
4160       else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4161         g_child_watch_source_init_promote_single_to_threaded ();
4162     }
4163   else
4164     {
4165       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4166         g_child_watch_source_init_single ();
4167     }
4168 }
4169
4170 #endif /* !G_OS_WIN32 */
4171
4172 /**
4173  * g_child_watch_source_new:
4174  * @pid: process to watch. On POSIX the pid of a child process. On
4175  * Windows a handle for a process (which doesn't have to be a child).
4176  * 
4177  * Creates a new child_watch source.
4178  *
4179  * The source will not initially be associated with any #GMainContext
4180  * and must be added to one with g_source_attach() before it will be
4181  * executed.
4182  * 
4183  * Note that child watch sources can only be used in conjunction with
4184  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4185  * flag is used.
4186  *
4187  * Note that on platforms where #GPid must be explicitly closed
4188  * (see g_spawn_close_pid()) @pid must not be closed while the
4189  * source is still active. Typically, you will want to call
4190  * g_spawn_close_pid() in the callback function for the source.
4191  *
4192  * Note further that using g_child_watch_source_new() is not 
4193  * compatible with calling <literal>waitpid(-1)</literal> in 
4194  * the application. Calling waitpid() for individual pids will
4195  * still work fine. 
4196  * 
4197  * Return value: the newly-created child watch source
4198  *
4199  * Since: 2.4
4200  **/
4201 GSource *
4202 g_child_watch_source_new (GPid pid)
4203 {
4204   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4205   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4206
4207 #ifdef G_OS_WIN32
4208   child_watch_source->poll.fd = (gintptr) pid;
4209   child_watch_source->poll.events = G_IO_IN;
4210
4211   g_source_add_poll (source, &child_watch_source->poll);
4212 #else /* G_OS_WIN32 */
4213   g_child_watch_source_init ();
4214 #endif /* G_OS_WIN32 */
4215
4216   child_watch_source->pid = pid;
4217
4218   return source;
4219 }
4220
4221 /**
4222  * g_child_watch_add_full:
4223  * @priority: the priority of the idle source. Typically this will be in the
4224  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4225  * @pid:      process to watch. On POSIX the pid of a child process. On
4226  * Windows a handle for a process (which doesn't have to be a child).
4227  * @function: function to call
4228  * @data:     data to pass to @function
4229  * @notify:   function to call when the idle is removed, or %NULL
4230  * 
4231  * Sets a function to be called when the child indicated by @pid 
4232  * exits, at the priority @priority.
4233  *
4234  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4235  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4236  * the spawn function for the child watching to work.
4237  * 
4238  * Note that on platforms where #GPid must be explicitly closed
4239  * (see g_spawn_close_pid()) @pid must not be closed while the
4240  * source is still active. Typically, you will want to call
4241  * g_spawn_close_pid() in the callback function for the source.
4242  * 
4243  * GLib supports only a single callback per process id.
4244  *
4245  * This internally creates a main loop source using 
4246  * g_child_watch_source_new() and attaches it to the main loop context 
4247  * using g_source_attach(). You can do these steps manually if you 
4248  * need greater control.
4249  *
4250  * Return value: the ID (greater than 0) of the event source.
4251  *
4252  * Since: 2.4
4253  **/
4254 guint
4255 g_child_watch_add_full (gint            priority,
4256                         GPid            pid,
4257                         GChildWatchFunc function,
4258                         gpointer        data,
4259                         GDestroyNotify  notify)
4260 {
4261   GSource *source;
4262   guint id;
4263   
4264   g_return_val_if_fail (function != NULL, 0);
4265
4266   source = g_child_watch_source_new (pid);
4267
4268   if (priority != G_PRIORITY_DEFAULT)
4269     g_source_set_priority (source, priority);
4270
4271   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4272   id = g_source_attach (source, NULL);
4273   g_source_unref (source);
4274
4275   return id;
4276 }
4277
4278 /**
4279  * g_child_watch_add:
4280  * @pid:      process id to watch. On POSIX the pid of a child process. On
4281  * Windows a handle for a process (which doesn't have to be a child).
4282  * @function: function to call
4283  * @data:     data to pass to @function
4284  * 
4285  * Sets a function to be called when the child indicated by @pid 
4286  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4287  * 
4288  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4289  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4290  * the spawn function for the child watching to work.
4291  * 
4292  * Note that on platforms where #GPid must be explicitly closed
4293  * (see g_spawn_close_pid()) @pid must not be closed while the
4294  * source is still active. Typically, you will want to call
4295  * g_spawn_close_pid() in the callback function for the source.
4296  *
4297  * GLib supports only a single callback per process id.
4298  *
4299  * This internally creates a main loop source using 
4300  * g_child_watch_source_new() and attaches it to the main loop context 
4301  * using g_source_attach(). You can do these steps manually if you 
4302  * need greater control.
4303  *
4304  * Return value: the ID (greater than 0) of the event source.
4305  *
4306  * Since: 2.4
4307  **/
4308 guint 
4309 g_child_watch_add (GPid            pid,
4310                    GChildWatchFunc function,
4311                    gpointer        data)
4312 {
4313   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4314 }
4315
4316
4317 /* Idle functions */
4318
4319 static gboolean 
4320 g_idle_prepare  (GSource  *source,
4321                  gint     *timeout)
4322 {
4323   *timeout = 0;
4324
4325   return TRUE;
4326 }
4327
4328 static gboolean 
4329 g_idle_check    (GSource  *source)
4330 {
4331   return TRUE;
4332 }
4333
4334 static gboolean
4335 g_idle_dispatch (GSource    *source, 
4336                  GSourceFunc callback,
4337                  gpointer    user_data)
4338 {
4339   if (!callback)
4340     {
4341       g_warning ("Idle source dispatched without callback\n"
4342                  "You must call g_source_set_callback().");
4343       return FALSE;
4344     }
4345   
4346   return callback (user_data);
4347 }
4348
4349 /**
4350  * g_idle_source_new:
4351  * 
4352  * Creates a new idle source.
4353  *
4354  * The source will not initially be associated with any #GMainContext
4355  * and must be added to one with g_source_attach() before it will be
4356  * executed. Note that the default priority for idle sources is
4357  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4358  * have a default priority of %G_PRIORITY_DEFAULT.
4359  * 
4360  * Return value: the newly-created idle source
4361  **/
4362 GSource *
4363 g_idle_source_new (void)
4364 {
4365   GSource *source;
4366
4367   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4368   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4369
4370   return source;
4371 }
4372
4373 /**
4374  * g_idle_add_full:
4375  * @priority: the priority of the idle source. Typically this will be in the
4376  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4377  * @function: function to call
4378  * @data:     data to pass to @function
4379  * @notify:   function to call when the idle is removed, or %NULL
4380  * 
4381  * Adds a function to be called whenever there are no higher priority
4382  * events pending.  If the function returns %FALSE it is automatically
4383  * removed from the list of event sources and will not be called again.
4384  * 
4385  * This internally creates a main loop source using g_idle_source_new()
4386  * and attaches it to the main loop context using g_source_attach(). 
4387  * You can do these steps manually if you need greater control.
4388  * 
4389  * Return value: the ID (greater than 0) of the event source.
4390  **/
4391 guint 
4392 g_idle_add_full (gint           priority,
4393                  GSourceFunc    function,
4394                  gpointer       data,
4395                  GDestroyNotify notify)
4396 {
4397   GSource *source;
4398   guint id;
4399   
4400   g_return_val_if_fail (function != NULL, 0);
4401
4402   source = g_idle_source_new ();
4403
4404   if (priority != G_PRIORITY_DEFAULT_IDLE)
4405     g_source_set_priority (source, priority);
4406
4407   g_source_set_callback (source, function, data, notify);
4408   id = g_source_attach (source, NULL);
4409   g_source_unref (source);
4410
4411   return id;
4412 }
4413
4414 /**
4415  * g_idle_add:
4416  * @function: function to call 
4417  * @data: data to pass to @function.
4418  * 
4419  * Adds a function to be called whenever there are no higher priority
4420  * events pending to the default main loop. The function is given the
4421  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4422  * returns %FALSE it is automatically removed from the list of event
4423  * sources and will not be called again.
4424  * 
4425  * This internally creates a main loop source using g_idle_source_new()
4426  * and attaches it to the main loop context using g_source_attach(). 
4427  * You can do these steps manually if you need greater control.
4428  * 
4429  * Return value: the ID (greater than 0) of the event source.
4430  **/
4431 guint 
4432 g_idle_add (GSourceFunc    function,
4433             gpointer       data)
4434 {
4435   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4436 }
4437
4438 /**
4439  * g_idle_remove_by_data:
4440  * @data: the data for the idle source's callback.
4441  * 
4442  * Removes the idle function with the given data.
4443  * 
4444  * Return value: %TRUE if an idle source was found and removed.
4445  **/
4446 gboolean
4447 g_idle_remove_by_data (gpointer data)
4448 {
4449   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4450 }
4451
4452 /**
4453  * g_main_context_invoke:
4454  * @context: a #GMainContext, or %NULL
4455  * @function: function to call
4456  * @data: data to pass to @function
4457  *
4458  * Invokes a function in such a way that @context is owned during the
4459  * invocation of @function.
4460  *
4461  * If @context is %NULL then the global default main context — as
4462  * returned by g_main_context_default() — is used.
4463  *
4464  * If @context is owned by the current thread, @function is called
4465  * directly.  Otherwise, if @context is the thread-default main context
4466  * of the current thread and g_main_context_acquire() succeeds, then
4467  * @function is called and g_main_context_release() is called
4468  * afterwards.
4469  *
4470  * In any other case, an idle source is created to call @function and
4471  * that source is attached to @context (presumably to be run in another
4472  * thread).  The idle source is attached with #G_PRIORITY_DEFAULT
4473  * priority.  If you want a different priority, use
4474  * g_main_context_invoke_full().
4475  *
4476  * Note that, as with normal idle functions, @function should probably
4477  * return %FALSE.  If it returns %TRUE, it will be continuously run in a
4478  * loop (and may prevent this call from returning).
4479  *
4480  * Since: 2.28
4481  **/
4482 void
4483 g_main_context_invoke (GMainContext *context,
4484                        GSourceFunc   function,
4485                        gpointer      data)
4486 {
4487   g_main_context_invoke_full (context,
4488                               G_PRIORITY_DEFAULT,
4489                               function, data, NULL);
4490 }
4491
4492 /**
4493  * g_main_context_invoke_full:
4494  * @context: a #GMainContext, or %NULL
4495  * @priority: the priority at which to run @function
4496  * @function: function to call
4497  * @data: data to pass to @function
4498  * @notify: a function to call when @data is no longer in use, or %NULL.
4499  *
4500  * Invokes a function in such a way that @context is owned during the
4501  * invocation of @function.
4502  *
4503  * This function is the same as g_main_context_invoke() except that it
4504  * lets you specify the priority incase @function ends up being
4505  * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4506  *
4507  * @notify should not assume that it is called from any particular
4508  * thread or with any particular context acquired.
4509  *
4510  * Since: 2.28
4511  **/
4512 void
4513 g_main_context_invoke_full (GMainContext   *context,
4514                             gint            priority,
4515                             GSourceFunc     function,
4516                             gpointer        data,
4517                             GDestroyNotify  notify)
4518 {
4519   g_return_if_fail (function != NULL);
4520
4521   if (!context)
4522     context = g_main_context_default ();
4523
4524   if (g_main_context_is_owner (context))
4525     {
4526       while (function (data));
4527       if (notify != NULL)
4528         notify (data);
4529     }
4530
4531   else
4532     {
4533       GMainContext *thread_default;
4534
4535       thread_default = g_main_context_get_thread_default ();
4536
4537       if (!thread_default)
4538         thread_default = g_main_context_default ();
4539
4540       if (thread_default == context && g_main_context_acquire (context))
4541         {
4542           while (function (data));
4543
4544           g_main_context_release (context);
4545
4546           if (notify != NULL)
4547             notify (data);
4548         }
4549       else
4550         {
4551           GSource *source;
4552
4553           source = g_idle_source_new ();
4554           g_source_set_priority (source, priority);
4555           g_source_set_callback (source, function, data, notify);
4556           g_source_attach (source, context);
4557           g_source_unref (source);
4558         }
4559     }
4560 }