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