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