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