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