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