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