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