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