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