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