Don't put anything after an #endif. Likewise.
[platform/upstream/glib.git] / 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 <sys/types.h>
41 #include <time.h>
42 #ifdef HAVE_SYS_TIME_H
43 #include <sys/time.h>
44 #endif /* HAVE_SYS_TIME_H */
45 #ifdef GLIB_HAVE_SYS_POLL_H
46 #  include <sys/poll.h>
47 #  undef events  /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
48 #  undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
49 #endif /* GLIB_HAVE_SYS_POLL_H */
50 #ifdef HAVE_UNISTD_H
51 #include <unistd.h>
52 #endif /* HAVE_UNISTD_H */
53 #include <errno.h>
54
55 #ifdef G_OS_WIN32
56 #define STRICT
57 #include <windows.h>
58 #endif /* G_OS_WIN32 */
59
60 #ifdef G_OS_BEOS
61 #include <net/socket.h>
62 #endif /* G_OS_BEOS */
63
64 /* Types */
65
66 typedef struct _GTimeoutSource GTimeoutSource;
67 typedef struct _GPollRec GPollRec;
68 typedef struct _GSourceCallback GSourceCallback;
69
70 typedef enum
71 {
72   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
73   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
74 } GSourceFlags;
75
76 struct _GMainContext
77 {
78 #ifdef G_THREADS_ENABLED
79   /* The following lock is used for both the list of sources
80    * and the list of poll records
81    */
82   GMutex *mutex;
83   GThread *thread;
84 #endif  
85
86   GPtrArray *pending_dispatches;
87   gint timeout;                 /* Timeout for current iteration */
88
89   guint next_id;
90   GSource *source_list;
91   gint in_check_or_prepare;
92
93   GPollRec *poll_records;
94   GPollRec *poll_free_list;
95   GMemChunk *poll_chunk;
96   guint n_poll_records;
97   GPollFD *cached_poll_array;
98   gint cached_poll_array_size;
99
100 #ifdef G_THREADS_ENABLED  
101 #ifndef G_OS_WIN32
102 /* this pipe is used to wake up the main loop when a source is added.
103  */
104   gint wake_up_pipe[2];
105 #else /* G_OS_WIN32 */
106   HANDLE wake_up_semaphore;
107 #endif /* G_OS_WIN32 */
108
109   GPollFD wake_up_rec;
110   gboolean poll_waiting;
111
112 /* Flag indicating whether the set of fd's changed during a poll */
113   gboolean poll_changed;
114 #endif /* G_THREADS_ENABLED */
115
116   GPollFunc poll_func;
117
118   GTimeVal current_time;
119   gboolean time_is_current;
120 };
121
122 struct _GSourceCallback
123 {
124   guint ref_count;
125   GSourceFunc func;
126   gpointer    data;
127   GDestroyNotify notify;
128 };
129
130 struct _GMainLoop
131 {
132   GMainContext *context;
133   gboolean is_running;
134
135 #ifdef G_THREADS_ENABLED
136   GMutex *mutex;
137   GCond *sem_cond;
138 #endif /* G_THREADS_ENABLED */
139 };
140
141 struct _GTimeoutSource
142 {
143   GSource     source;
144   GTimeVal    expiration;
145   gint        interval;
146 };
147
148 struct _GPollRec
149 {
150   gint priority;
151   GPollFD *fd;
152   GPollRec *next;
153 };
154
155 #ifdef G_THREADS_ENABLED
156 #define LOCK_CONTEXT(context) g_mutex_lock(context->mutex)
157 #define UNLOCK_CONTEXT(context) g_mutex_unlock(context->mutex)
158 #define LOCK_LOOP(loop) g_mutex_lock(loop->mutex)
159 #define UNLOCK_LOOP(loop) g_mutex_unlock(loop->mutex)
160 #else
161 #define LOCK_CONTEXT(context) (void)0
162 #define UNLOCK_CONTEXT(context) (void)0
163 #define LOCK_LOOP(context) (void)0
164 #define UNLOCK_LOOP(context) (void)0
165 #endif
166
167 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
168
169 #define SOURCE_UNREF(source, context)                       \
170    G_STMT_START {                                           \
171     if ((source)->ref_count > 1)                            \
172       (source)->ref_count--;                                \
173     else                                                    \
174       g_source_unref_internal ((source), (context), TRUE);  \
175    } G_STMT_END
176
177
178 /* Forward declarations */
179
180 static void g_source_unref_internal             (GSource      *source,
181                                                  GMainContext *context,
182                                                  gboolean      have_lock);
183 static void g_source_destroy_internal           (GSource      *source,
184                                                  GMainContext *context,
185                                                  gboolean      have_lock);
186 static void g_main_context_poll                 (GMainContext *context,
187                                                  gint          timeout,
188                                                  gint          priority,
189                                                  GPollFD      *fds,
190                                                  gint          n_fds);
191 static void g_main_context_add_poll_unlocked    (GMainContext *context,
192                                                  gint          priority,
193                                                  GPollFD      *fd);
194 static void g_main_context_remove_poll_unlocked (GMainContext *context,
195                                                  GPollFD      *fd);
196 static void g_main_context_wakeup               (GMainContext *context);
197
198 static gboolean g_timeout_prepare  (GSource     *source,
199                                     gint        *timeout);
200 static gboolean g_timeout_check    (GSource     *source);
201 static gboolean g_timeout_dispatch (GSource     *source,
202                                     GSourceFunc  callback,
203                                     gpointer     user_data);
204 static gboolean g_idle_prepare     (GSource     *source,
205                                     gint        *timeout);
206 static gboolean g_idle_check       (GSource     *source);
207 static gboolean g_idle_dispatch    (GSource     *source,
208                                     GSourceFunc  callback,
209                                     gpointer     user_data);
210
211 G_LOCK_DEFINE_STATIC (main_loop);
212 static GMainContext *default_main_context;
213
214 static GSourceFuncs timeout_funcs =
215 {
216   g_timeout_prepare,
217   g_timeout_check,
218   g_timeout_dispatch,
219   NULL
220 };
221
222 static GSourceFuncs idle_funcs =
223 {
224   g_idle_prepare,
225   g_idle_check,
226   g_idle_dispatch,
227   NULL
228 };
229
230 #ifdef HAVE_POLL
231 /* SunOS has poll, but doesn't provide a prototype. */
232 #  if defined (sun) && !defined (__SVR4)
233 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
234 #  endif  /* !sun */
235 #else   /* !HAVE_POLL */
236
237 #ifdef G_OS_WIN32
238
239 static gint
240 g_poll (GPollFD *fds,
241         guint    nfds,
242         gint     timeout)
243 {
244   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
245   gboolean poll_msgs = FALSE;
246   GPollFD *f;
247   DWORD ready;
248   MSG msg;
249   UINT timer;
250   gint nhandles = 0;
251
252   for (f = fds; f < &fds[nfds]; ++f)
253     if (f->fd >= 0)
254       {
255         if (f->events & G_IO_IN)
256           {
257             if (f->fd == G_WIN32_MSG_HANDLE)
258               poll_msgs = TRUE;
259             else
260               {
261 #ifdef G_MAIN_POLL_DEBUG
262                 g_print ("g_poll: waiting for %#x\n", f->fd);
263 #endif
264                 handles[nhandles++] = (HANDLE) f->fd;
265               }
266           }
267       }
268
269   if (timeout == -1)
270     timeout = INFINITE;
271
272   if (poll_msgs)
273     {
274       /* Waiting for messages, and maybe events */
275       if (nhandles == 0)
276         {
277           if (timeout == INFINITE)
278             {
279               /* Waiting just for messages, infinite timeout
280                * -> Use PeekMessage, then WaitMessage
281                */
282 #ifdef G_MAIN_POLL_DEBUG
283               g_print ("PeekMessage, then WaitMessage\n");
284 #endif
285               if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
286                 ready = WAIT_OBJECT_0;
287               else if (!WaitMessage ())
288                 g_warning ("g_poll: WaitMessage failed");
289               ready = WAIT_OBJECT_0;
290             }
291           else if (timeout == 0)
292             {
293               /* Waiting just for messages, zero timeout
294                * -> Use PeekMessage
295                */
296 #ifdef G_MAIN_POLL_DEBUG
297               g_print ("PeekMessage\n");
298 #endif
299               if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
300                 ready = WAIT_OBJECT_0;
301               else
302                 ready = WAIT_TIMEOUT;
303             }
304           else
305             {
306               /* Waiting just for messages, some timeout
307                * -> First try PeekMessage, then set a timer, wait for message,
308                * kill timer, use PeekMessage
309                */
310 #ifdef G_MAIN_POLL_DEBUG
311               g_print ("PeekMessage\n");
312 #endif
313               if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
314                 ready = WAIT_OBJECT_0;
315               else if ((timer = SetTimer (NULL, 0, timeout, NULL)) == 0)
316                 g_warning ("g_poll: SetTimer failed");
317               else
318                 {
319 #ifdef G_MAIN_POLL_DEBUG
320                   g_print ("WaitMessage\n");
321 #endif
322                   WaitMessage ();
323                   KillTimer (NULL, timer);
324                   if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
325                       && msg.message != WM_TIMER)
326                     ready = WAIT_OBJECT_0;
327                   else
328                     ready = WAIT_TIMEOUT;
329                 }
330             }
331         }
332       else
333         {
334           /* Wait for either message or event
335            * -> Use MsgWaitForMultipleObjects
336            */
337 #ifdef G_MAIN_POLL_DEBUG
338           g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
339 #endif
340           ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
341                                              timeout, QS_ALLINPUT);
342
343           if (ready == WAIT_FAILED)
344             g_warning ("g_poll: MsgWaitForMultipleObjects failed");
345         }
346     }
347   else if (nhandles == 0)
348     {
349       /* Wait for nothing (huh?) */
350       return 0;
351     }
352   else
353     {
354       /* Wait for just events
355        * -> Use WaitForMultipleObjects
356        */
357 #ifdef G_MAIN_POLL_DEBUG
358       g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
359 #endif
360       ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
361       if (ready == WAIT_FAILED)
362         g_warning ("g_poll: WaitForMultipleObjects failed");
363     }
364
365   for (f = fds; f < &fds[nfds]; ++f)
366     f->revents = 0;
367
368   if (ready == WAIT_FAILED)
369     return -1;
370   else if (ready == WAIT_TIMEOUT)
371     return 0;
372   else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
373     {
374       for (f = fds; f < &fds[nfds]; ++f)
375         if (f->fd >= 0)
376           {
377             if (f->events & G_IO_IN)
378               if (f->fd == G_WIN32_MSG_HANDLE)
379                 f->revents |= G_IO_IN;
380           }
381     }
382   else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
383     for (f = fds; f < &fds[nfds]; ++f)
384       {
385         if ((f->events & G_IO_IN)
386             && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
387           {
388             f->revents |= G_IO_IN;
389 #ifdef G_MAIN_POLL_DEBUG
390             g_print ("g_poll: got event %#x\n", f->fd);
391 #endif
392 #if 0
393             ResetEvent ((HANDLE) f->fd);
394 #endif
395           }
396       }
397     
398   if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
399     return ready - WAIT_OBJECT_0 + 1;
400   else
401     return 0;
402 }
403
404 #else  /* !G_OS_WIN32 */
405
406 /* The following implementation of poll() comes from the GNU C Library.
407  * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
408  */
409
410 #include <string.h> /* for bzero on BSD systems */
411
412 #ifdef HAVE_SYS_SELECT_H
413 #include <sys/select.h>
414 #endif /* HAVE_SYS_SELECT_H */
415
416 #ifdef G_OS_BEOS
417 #undef NO_FD_SET
418 #endif /* G_OS_BEOS */
419
420 #ifndef NO_FD_SET
421 #  define SELECT_MASK fd_set
422 #else /* !NO_FD_SET */
423 #  ifndef _AIX
424 typedef long fd_mask;
425 #  endif /* _AIX */
426 #  ifdef _IBMR2
427 #    define SELECT_MASK void
428 #  else /* !_IBMR2 */
429 #    define SELECT_MASK int
430 #  endif /* !_IBMR2 */
431 #endif /* !NO_FD_SET */
432
433 static gint 
434 g_poll (GPollFD *fds,
435         guint    nfds,
436         gint     timeout)
437 {
438   struct timeval tv;
439   SELECT_MASK rset, wset, xset;
440   GPollFD *f;
441   int ready;
442   int maxfd = 0;
443
444   FD_ZERO (&rset);
445   FD_ZERO (&wset);
446   FD_ZERO (&xset);
447
448   for (f = fds; f < &fds[nfds]; ++f)
449     if (f->fd >= 0)
450       {
451         if (f->events & G_IO_IN)
452           FD_SET (f->fd, &rset);
453         if (f->events & G_IO_OUT)
454           FD_SET (f->fd, &wset);
455         if (f->events & G_IO_PRI)
456           FD_SET (f->fd, &xset);
457         if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
458           maxfd = f->fd;
459       }
460
461   tv.tv_sec = timeout / 1000;
462   tv.tv_usec = (timeout % 1000) * 1000;
463
464   ready = select (maxfd + 1, &rset, &wset, &xset,
465                   timeout == -1 ? NULL : &tv);
466   if (ready > 0)
467     for (f = fds; f < &fds[nfds]; ++f)
468       {
469         f->revents = 0;
470         if (f->fd >= 0)
471           {
472             if (FD_ISSET (f->fd, &rset))
473               f->revents |= G_IO_IN;
474             if (FD_ISSET (f->fd, &wset))
475               f->revents |= G_IO_OUT;
476             if (FD_ISSET (f->fd, &xset))
477               f->revents |= G_IO_PRI;
478           }
479       }
480
481   return ready;
482 }
483
484 #endif /* !G_OS_WIN32 */
485
486 #endif  /* !HAVE_POLL */
487
488 /* Called to clean up when a thread terminates
489  */
490 static void
491 g_main_context_destroy (GMainContext *context)
492 {
493   GSource *source;
494
495   /* We need the lock here only because g_source_destroy expects
496    * to be able to unlock when destroying the source's data
497    */
498   LOCK_CONTEXT (context);
499   source = context->source_list;
500   while (source)
501     {
502       GSource *next = source->next;
503       g_source_destroy_internal (source, context, TRUE);
504       source = next;
505     }
506   UNLOCK_CONTEXT (context);
507
508 #ifdef G_THREADS_ENABLED  
509   g_mutex_free (context->mutex);
510 #endif
511
512   g_ptr_array_free (context->pending_dispatches, TRUE);
513   g_free (context->cached_poll_array);
514   
515   g_mem_chunk_destroy (context->poll_chunk);
516
517   if (g_thread_supported())
518     {
519 #ifndef G_OS_WIN32
520       close (context->wake_up_pipe[0]);
521       close (context->wake_up_pipe[1]);
522 #else
523       CloseHandle (context->wake_up_semaphore);
524 #endif
525     }
526   
527   g_free (context);
528 }
529
530 /**
531  * g_main_context_get:
532  * @thread: a #GThread
533  * 
534  * Retrieves the main loop context for a particular thread. This
535  * will create the main context for the thread if none previously
536  * existed. The context will exist until the thread terminates.
537  * 
538  * Return value: the main loop context for @thread.
539  **/
540 GMainContext *
541 g_main_context_get (GThread *thread)
542 {
543   static GStaticPrivate private_key = G_STATIC_PRIVATE_INIT;
544   GMainContext *context;
545
546   g_return_val_if_fail (thread != NULL, NULL);
547
548   if (g_thread_supported ())
549     context = g_static_private_get_for_thread (&private_key, thread);
550   else
551     context = default_main_context;
552
553   if (!context)
554     {
555       context = g_new0 (GMainContext, 1);
556
557 #ifdef G_THREADS_ENABLED
558       if (g_thread_supported ())
559         context->mutex = g_mutex_new();
560
561       context->thread = thread;
562 #endif
563       
564       context->next_id = 1;
565       
566       context->source_list = NULL;
567
568 #if HAVE_POLL
569       context->poll_func = (GPollFunc)poll;
570 #else
571       context->poll_func = g_poll;
572 #endif
573
574       context->cached_poll_array = NULL;
575       context->cached_poll_array_size = 0;
576       
577       context->pending_dispatches = g_ptr_array_new ();
578       
579       context->time_is_current = FALSE;
580
581 #ifdef G_THREADS_ENABLED
582       if (g_thread_supported ())
583         {
584 #ifndef G_OS_WIN32
585           if (pipe (context->wake_up_pipe) < 0)
586             g_error ("Cannot create pipe main loop wake-up: %s\n",
587                      g_strerror (errno));
588           
589           context->wake_up_rec.fd = context->wake_up_pipe[0];
590           context->wake_up_rec.events = G_IO_IN;
591           g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
592 #else
593           if ((context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
594             g_error ("Cannot create wake-up semaphore: %s", g_win32_error_message (GetLastError ()));
595           context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
596           context->wake_up_rec.events = G_IO_IN;
597 #ifdef G_MAIN_POLL_DEBUG
598           g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
599 #endif
600           g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
601 #endif
602         }
603 #endif
604
605       if (g_thread_supported ())
606         g_static_private_set_for_thread (&private_key, thread,
607                                          context,
608                                          (GDestroyNotify)g_main_context_destroy);
609       else
610         default_main_context = context;
611     }
612
613   return context;
614 }
615
616 /**
617  * g_main_context_default:
618  * 
619  * Return the default main context. This is the main context used
620  * for main loop functions when a main loop is not explicitly
621  * specified.
622  * 
623  * Return value: the default main context.
624  **/
625 GMainContext *
626 g_main_context_default (void)
627 {
628   /* Slow, but safe */
629   
630   G_LOCK (main_loop);
631
632   if (!default_main_context)
633     default_main_context = g_main_context_get (g_thread_self ());
634
635   G_UNLOCK (main_loop);
636
637   return default_main_context;
638 }
639
640 /* Hooks for adding to the main loop */
641
642 /**
643  * g_source_new:
644  * @source_funcs: structure containing functions that implement
645  *                the sources behavior.
646  * @struct_size: size of the #GSource structure to create
647  * 
648  * Create a new GSource structure. The size is specified to
649  * allow creating structures derived from GSource that contain
650  * additional data. The size passed in must be at least
651  * sizeof(GSource).
652  * 
653  * The source will not initially be associated with any #GMainContext
654  * and must be added to one with g_source_add() before it will be
655  * executed.
656  * 
657  * Return value: the newly create #GSource
658  **/
659 GSource *
660 g_source_new (GSourceFuncs *source_funcs,
661               guint         struct_size)
662 {
663   GSource *source;
664
665   g_return_val_if_fail (source_funcs != NULL, NULL);
666   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
667   
668   source = (GSource*) g_malloc0 (struct_size);
669
670   source->source_funcs = source_funcs;
671   source->ref_count = 1;
672   
673   source->priority = G_PRIORITY_DEFAULT;
674
675   source->flags = G_HOOK_FLAG_ACTIVE;
676
677   /* NULL/0 initialization for all other fields */
678   
679   return source;
680 }
681
682 /* Holds context's lock
683  */
684 static void
685 g_source_list_add (GSource      *source,
686                    GMainContext *context)
687 {
688   GSource *tmp_source, *last_source;
689   
690   last_source = NULL;
691   tmp_source = context->source_list;
692   while (tmp_source && tmp_source->priority <= source->priority)
693     {
694       last_source = tmp_source;
695       tmp_source = tmp_source->next;
696     }
697
698   source->next = tmp_source;
699   if (tmp_source)
700     tmp_source->prev = source;
701   
702   source->prev = last_source;
703   if (last_source)
704     last_source->next = source;
705   else
706     context->source_list = source;
707 }
708
709 /* Holds context's lock
710  */
711 static void
712 g_source_list_remove (GSource      *source,
713                       GMainContext *context)
714 {
715   if (source->prev)
716     source->prev->next = source->next;
717   else
718     context->source_list = source->next;
719
720   if (source->next)
721     source->next->prev = source->prev;
722
723   source->prev = NULL;
724   source->next = NULL;
725 }
726
727 /**
728  * g_source_attach:
729  * @source: a #GSource
730  * @context: a #GMainContext (if %NULL, the default context will be used)
731  * 
732  * Adds a #GSource to a @context so that it will be executed within
733  * that context.
734  *
735  * Return value: the ID for the source within the #GMainContext
736  **/
737 guint
738 g_source_attach (GSource      *source,
739                  GMainContext *context)
740 {
741   guint result = 0;
742   GSList *tmp_list;
743
744   g_return_val_if_fail (source->context == NULL, 0);
745   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
746   
747   if (!context)
748     context = g_main_context_default ();
749
750   LOCK_CONTEXT (context);
751
752   source->context = context;
753   result = source->id = context->next_id++;
754
755   source->ref_count++;
756   g_source_list_add (source, context);
757
758   tmp_list = source->poll_fds;
759   while (tmp_list)
760     {
761       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
762       tmp_list = tmp_list->next;
763     }
764
765 #ifdef G_THREADS_ENABLED
766   /* Now wake up the main loop if it is waiting in the poll() */
767   g_main_context_wakeup (context);
768 #endif
769
770   UNLOCK_CONTEXT (context);
771
772   return result;
773 }
774
775 static void
776 g_source_destroy_internal (GSource      *source,
777                            GMainContext *context,
778                            gboolean      have_lock)
779 {
780   if (!have_lock)
781     LOCK_CONTEXT (context);
782   
783   if (!SOURCE_DESTROYED (source))
784     {
785       gpointer old_cb_data;
786       GSourceCallbackFuncs *old_cb_funcs;
787       
788       source->flags &= ~G_HOOK_FLAG_ACTIVE;
789
790       old_cb_data = source->callback_data;
791       old_cb_funcs = source->callback_funcs;
792
793       source->callback_data = NULL;
794       source->callback_funcs = NULL;
795
796       if (old_cb_funcs)
797         {
798           UNLOCK_CONTEXT (context);
799           old_cb_funcs->unref (old_cb_data);
800           LOCK_CONTEXT (context);
801         }
802       
803       g_source_unref_internal (source, context, TRUE);
804     }
805
806   if (!have_lock)
807     UNLOCK_CONTEXT (context);
808 }
809
810 /**
811  * g_source_destroy:
812  * @source: a #GSource
813  * 
814  * Remove a source from its #GMainContext, if any, and mark it as
815  * destroyed.  The source cannot be subsequently added to another
816  * context.
817  **/
818 void
819 g_source_destroy (GSource *source)
820 {
821   GMainContext *context;
822   
823   g_return_if_fail (source != NULL);
824   
825   context = source->context;
826   
827   if (context)
828     g_source_destroy_internal (source, context, FALSE);
829   else
830     source->flags &= ~G_HOOK_FLAG_ACTIVE;
831 }
832
833 /**
834  * g_source_get_id:
835  * @source: a #GSource
836  * 
837  * Return the numeric ID for a particular source. The ID of a source
838  * is unique within a particular main loop context. The reverse
839  * mapping from ID to source is done by g_main_context_find_source_by_id().
840  *
841  * Return value: the ID for the source
842  **/
843 guint
844 g_source_get_id (GSource *source)
845 {
846   guint result;
847   
848   g_return_val_if_fail (source != NULL, 0);
849   g_return_val_if_fail (source->context != NULL, 0);
850
851   LOCK_CONTEXT (source->context);
852   result = source->id;
853   UNLOCK_CONTEXT (source->context);
854   
855   return result;
856 }
857
858 /**
859  * g_source_get_context:
860  * @source: a #GSource
861  * 
862  * Get the #GMainContext with which the source is associated.
863  * Calling this function on a destroyed source is an error.
864  * 
865  * Return value: the #GMainContext with which the source is associated,
866  *               or %NULL if the context has not yet been added
867  *               to a source.
868  **/
869 GMainContext *
870 g_source_get_context (GSource *source)
871 {
872   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
873
874   return source->context;
875 }
876
877 /**
878  * g_main_source_add_poll:
879  * @source:a #GSource 
880  * @fd: a #GPollFD structure holding information about a file
881  *      descriptor to watch.
882  * 
883  * Add a file descriptor to the set of file descriptors polled * for
884  * this source. This is usually combined with g_source_new() to add an
885  * event source. The event source's check function will typically test
886  * the revents field in the #GPollFD struct and return %TRUE if events need
887  * to be processed.
888  **/
889 void
890 g_source_add_poll (GSource *source,
891                    GPollFD *fd)
892 {
893   GMainContext *context;
894   
895   g_return_if_fail (source != NULL);
896   g_return_if_fail (fd != NULL);
897
898   context = source->context;
899
900   if (context)
901     LOCK_CONTEXT (context);
902   
903   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
904
905   if (context)
906     {
907       g_main_context_add_poll_unlocked (context, source->priority, fd);
908       UNLOCK_CONTEXT (context);
909     }
910 }
911
912 /**
913  * g_source_set_callback_indirect:
914  * @source: the source
915  * @callback_data: pointer to callback data "object"
916  * @callback_funcs: functions for reference counting callback_data
917  *                  and getting the callback and data
918  * 
919  * Set the callback function storing the data as a refcounted callback
920  * "object". This is used to implement g_source_set_callback_closure()
921  * and internally. Note that calling g_source_set_callback_indirect() assumes
922  * an initial reference count on @callback_data, and thus
923  * @callback_funcs->unref will eventually be called once more
924  * than @callback_funcs->ref.
925  **/
926 void
927 g_source_set_callback_indirect (GSource              *source,
928                                 gpointer              callback_data,
929                                 GSourceCallbackFuncs *callback_funcs)
930 {
931   GMainContext *context;
932   gpointer old_cb_data;
933   GSourceCallbackFuncs *old_cb_funcs;
934   
935   g_return_if_fail (source != NULL);
936   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
937
938   context = source->context;
939
940   if (context)
941     LOCK_CONTEXT (context);
942
943   old_cb_data = source->callback_data;
944   old_cb_funcs = source->callback_funcs;
945
946   source->callback_data = callback_data;
947   source->callback_funcs = callback_funcs;
948   
949   if (context)
950     UNLOCK_CONTEXT (context);
951   
952   if (old_cb_funcs)
953     old_cb_funcs->unref (old_cb_data);
954 }
955
956 static void
957 g_source_callback_ref (gpointer cb_data)
958 {
959   GSourceCallback *callback = cb_data;
960
961   callback->ref_count++;
962 }
963
964
965 static void
966 g_source_callback_unref (gpointer cb_data)
967 {
968   GSourceCallback *callback = cb_data;
969
970   callback->ref_count--;
971   if (callback->ref_count == 0)
972     {
973       if (callback->notify)
974         callback->notify (callback->data);
975     }
976 }
977
978 static void
979 g_source_callback_get (gpointer     cb_data,
980                        GSourceFunc *func,
981                        gpointer    *data)
982 {
983   GSourceCallback *callback = cb_data;
984
985   *func = callback->func;
986   *data = callback->data;
987 }
988
989 static GSourceCallbackFuncs g_source_callback_funcs = {
990   g_source_callback_ref,
991   g_source_callback_unref,
992   g_source_callback_get,
993 };
994
995 /**
996  * g_source_set_callback:
997  * @source: the source
998  * @func: a callback function
999  * @data: the data to pass to callback function
1000  * @notify: a function to call when @data is no longer in use, or %NULL.
1001  * 
1002  * Set the callback function for a source.
1003  **/
1004 void
1005 g_source_set_callback (GSource        *source,
1006                        GSourceFunc     func,
1007                        gpointer        data,
1008                        GDestroyNotify  notify)
1009 {
1010   GSourceCallback *new_callback;
1011
1012   g_return_if_fail (source != NULL);
1013
1014   new_callback = g_new (GSourceCallback, 1);
1015   
1016   new_callback->func = func;
1017   new_callback->data = data;
1018   new_callback->notify = notify;
1019
1020   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1021 }
1022
1023 /**
1024  * g_source_set_priority:
1025  * @source: a #GSource
1026  * @priority: the new priority.
1027  * 
1028  * Set the priority of a source. While the main loop is being
1029  * run, a source will 
1030  **/
1031 void
1032 g_source_set_priority (GSource  *source,
1033                        gint      priority)
1034 {
1035   GSList *tmp_list;
1036   GMainContext *context;
1037   
1038   g_return_if_fail (source != NULL);
1039
1040   context = source->context;
1041
1042   if (context)
1043     LOCK_CONTEXT (context);
1044   
1045   source->priority = priority;
1046
1047   if (context)
1048     {
1049       source->next = NULL;
1050       source->prev = NULL;
1051       
1052       tmp_list = source->poll_fds;
1053       while (tmp_list)
1054         {
1055           g_main_context_remove_poll_unlocked (context, tmp_list->data);
1056           g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1057       
1058           tmp_list = tmp_list->next;
1059         }
1060       
1061       UNLOCK_CONTEXT (source->context);
1062     }
1063 }
1064
1065 /**
1066  * g_source_get_priority:
1067  * @source: a #GSource
1068  * 
1069  * Gets the priority of a surce
1070  * 
1071  * Return value: the priority of the source
1072  **/
1073 gint
1074 g_source_get_priority (GSource *source)
1075 {
1076   g_return_val_if_fail (source != NULL, 0);
1077
1078   return source->priority;
1079 }
1080
1081 /**
1082  * g_source_set_can_recurse:
1083  * @source: a #GSource
1084  * @can_recurse: whether recursion is allowed for this source
1085  * 
1086  * Sets whether a source can be called recursively. If @can_recurse is
1087  * %TRUE, then while the source is being dispatched then this source
1088  * will be processed normally. Otherwise, all processing of this
1089  * source is blocked until the dispatch function returns.
1090  **/
1091 void
1092 g_source_set_can_recurse (GSource  *source,
1093                           gboolean  can_recurse)
1094 {
1095   GMainContext *context;
1096   
1097   g_return_if_fail (source != NULL);
1098
1099   context = source->context;
1100
1101   if (context)
1102     LOCK_CONTEXT (context);
1103   
1104   if (can_recurse)
1105     source->flags |= G_SOURCE_CAN_RECURSE;
1106   else
1107     source->flags &= ~G_SOURCE_CAN_RECURSE;
1108
1109   if (context)
1110     UNLOCK_CONTEXT (context);
1111 }
1112
1113 /**
1114  * g_source_get_can_recurse:
1115  * @source: a #GSource
1116  * 
1117  * Checks whether a source is allowed to be called recursively.
1118  * see g_source_set_can_recurse.
1119  * 
1120  * Return value: whether recursion is allowed.
1121  **/
1122 gboolean
1123 g_source_get_can_recurse (GSource  *source)
1124 {
1125   g_return_val_if_fail (source != NULL, FALSE);
1126   
1127   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1128 }
1129
1130 /**
1131  * g_source_ref:
1132  * @source: a #GSource
1133  * 
1134  * Increases the reference count on a source by one.
1135  * 
1136  * Return value: @source
1137  **/
1138 GSource *
1139 g_source_ref (GSource *source)
1140 {
1141   GMainContext *context;
1142   
1143   g_return_val_if_fail (source != NULL, NULL);
1144
1145   context = source->context;
1146
1147   if (context)
1148     LOCK_CONTEXT (context);
1149
1150   source->ref_count++;
1151
1152   if (context)
1153     UNLOCK_CONTEXT (context);
1154
1155   return source;
1156 }
1157
1158 /* g_source_unref() but possible to call within context lock
1159  */
1160 static void
1161 g_source_unref_internal (GSource      *source,
1162                          GMainContext *context,
1163                          gboolean      have_lock)
1164 {
1165   gpointer cb_data = NULL;
1166   GSourceCallbackFuncs *cb_funcs = NULL;
1167   GSList *tmp_list;
1168
1169   g_return_if_fail (source != NULL);
1170   
1171   if (!have_lock && context)
1172     LOCK_CONTEXT (context);
1173
1174   source->ref_count--;
1175   if (source->ref_count == 0)
1176     {
1177       if (context && !SOURCE_DESTROYED (source))
1178         {
1179           g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1180           source->ref_count++;
1181         }
1182       else
1183         {
1184           g_source_list_remove (source, context);
1185           
1186           tmp_list = source->poll_fds;
1187           while (tmp_list)
1188             {
1189               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1190               tmp_list = tmp_list->next;
1191             }
1192         }
1193     }
1194   
1195   if (!have_lock && context)
1196     UNLOCK_CONTEXT (context);
1197
1198   if (cb_data)
1199     {
1200       if (have_lock)
1201         UNLOCK_CONTEXT (context);
1202       
1203       cb_funcs->unref (cb_data);
1204
1205       if (have_lock)
1206         LOCK_CONTEXT (context);
1207     }
1208 }
1209
1210 /**
1211  * g_source_unref:
1212  * @source: a #GSource
1213  * 
1214  * Decreases the reference count of a source by one. If the
1215  * resulting reference count is zero the source and associated
1216  * memory will be destroyed. 
1217  **/
1218 void
1219 g_source_unref (GSource *source)
1220 {
1221   g_return_if_fail (source != NULL);
1222
1223   g_source_unref_internal (source, source->context, FALSE);
1224 }
1225
1226 /**
1227  * g_main_context_find_source_by_id:
1228  * @context: a #GMainContext (if %NULL, the default context will be used)
1229  * @id: the source ID, as returned by g_source_get_id()
1230  * 
1231  * Finds a #GSource given a pair of context and ID
1232  * 
1233  * Return value: the #GSource if found, otherwise, %NULL
1234  **/
1235 GSource *
1236 g_main_context_find_source_by_id (GMainContext *context,
1237                                   guint         id)
1238 {
1239   GSource *source;
1240   
1241   g_return_val_if_fail (id > 0, FALSE);
1242
1243   if (context == NULL)
1244     context = g_main_context_default ();
1245   
1246   LOCK_CONTEXT (context);
1247   
1248   source = context->source_list;
1249   while (source)
1250     {
1251       if (!SOURCE_DESTROYED (source) &&
1252           source->id == id)
1253         break;
1254       source = source->next;
1255     }
1256
1257   UNLOCK_CONTEXT (context);
1258
1259   return source;
1260 }
1261
1262 /**
1263  * g_main_context_find_source_by_funcs_user_data:
1264  * @context: a #GMainContext (if %NULL, the default context will be used).
1265  * @funcs: the @source_funcs passed to g_source_new().
1266  * @user_data: the user data from the callback.
1267  * 
1268  * Finds a source with the given source functions and user data.  If
1269  * multiple sources exist with the same source function and user data,
1270  * the first one found will be returned.
1271  * 
1272  * Return value: the source, if one was found, otherwise %NULL
1273  **/
1274 GSource *
1275 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1276                                                GSourceFuncs *funcs,
1277                                                gpointer      user_data)
1278 {
1279   GSource *source;
1280   
1281   g_return_val_if_fail (funcs != NULL, FALSE);
1282
1283   if (context == NULL)
1284     context = g_main_context_default ();
1285   
1286   LOCK_CONTEXT (context);
1287
1288   source = context->source_list;
1289   while (source)
1290     {
1291       if (!SOURCE_DESTROYED (source) &&
1292           source->source_funcs == funcs &&
1293           source->callback_data == user_data)
1294         break;
1295       source = source->next;
1296     }
1297
1298   UNLOCK_CONTEXT (context);
1299
1300   return source;
1301 }
1302
1303 /**
1304  * g_main_context_find_source_by_user_data:
1305  * @context: a #GMainContext
1306  * @user_data: the user_data for the callback.
1307  * 
1308  * Finds a source with the given user data for the callback.  If
1309  * multiple sources exist with the same user data, the first
1310  * one found will be returned.
1311  * 
1312  * Return value: the source, if one was found, otherwise %NULL
1313  **/
1314 GSource *
1315 g_main_context_find_source_by_user_data (GMainContext *context,
1316                                          gpointer      user_data)
1317 {
1318   GSource *source;
1319   
1320   if (context == NULL)
1321     context = g_main_context_default ();
1322   
1323   LOCK_CONTEXT (context);
1324
1325   source = context->source_list;
1326   while (source)
1327     {
1328       if (!SOURCE_DESTROYED (source) &&
1329           source->callback_data == user_data)
1330         break;
1331       source = source->next;
1332     }
1333
1334   UNLOCK_CONTEXT (context);
1335
1336   return source;
1337 }
1338
1339 /**
1340  * g_source_remove:
1341  * @tag: the id of the source to remove.
1342  * 
1343  * Removes the source with the given id from the default main
1344  * context. The id of a #GSource is given by g_source_get_id(),
1345  * or will be returned by the functions g_source_attach(),
1346  * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1347  * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1348  *
1349  * See also g_source_destroy().
1350  *
1351  * Return value: %TRUE if the source was found and removed.
1352  **/
1353 gboolean
1354 g_source_remove (guint tag)
1355 {
1356   GSource *source;
1357   
1358   g_return_val_if_fail (tag > 0, FALSE);
1359
1360   source = g_main_context_find_source_by_id (NULL, tag);
1361   if (source)
1362     g_source_destroy (source);
1363
1364   return source != NULL;
1365 }
1366
1367 /**
1368  * g_source_remove_by_user_data:
1369  * @user_data: the user_data for the callback.
1370  * 
1371  * Removes a source from the default main loop context given the user
1372  * data for the callback. If multiple sources exist with the same user
1373  * data, only one will be destroyed.
1374  * 
1375  * Return value: %TRUE if a source was found and removed. 
1376  **/
1377 gboolean
1378 g_source_remove_by_user_data (gpointer user_data)
1379 {
1380   GSource *source;
1381   
1382   source = g_main_context_find_source_by_user_data (NULL, user_data);
1383   if (source)
1384     {
1385       g_source_destroy (source);
1386       return TRUE;
1387     }
1388   else
1389     return FALSE;
1390 }
1391
1392 /**
1393  * g_source_remove_by_funcs_user_data:
1394  * @funcs: The @source_funcs passed to g_source_new()
1395  * @user_data: the user data for the callback
1396  * 
1397  * Removes a source from the default main loop context given the
1398  * source functions and user data. If multiple sources exist with the
1399  * same source functions and user data, only one will be destroyed.
1400  * 
1401  * Return value: %TRUE if a source was found and removed. 
1402  **/
1403 gboolean
1404 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1405                                     gpointer      user_data)
1406 {
1407   GSource *source;
1408
1409   g_return_val_if_fail (funcs != NULL, FALSE);
1410
1411   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1412   if (source)
1413     {
1414       g_source_destroy (source);
1415       return TRUE;
1416     }
1417   else
1418     return FALSE;
1419 }
1420
1421 /**
1422  * g_get_current_time:
1423  * @result: #GTimeVal structure in which to store current time.
1424  * 
1425  * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1426  **/
1427 void
1428 g_get_current_time (GTimeVal *result)
1429 {
1430 #ifndef G_OS_WIN32
1431   struct timeval r;
1432
1433   g_return_if_fail (result != NULL);
1434
1435   /*this is required on alpha, there the timeval structs are int's
1436     not longs and a cast only would fail horribly*/
1437   gettimeofday (&r, NULL);
1438   result->tv_sec = r.tv_sec;
1439   result->tv_usec = r.tv_usec;
1440 #else
1441   /* Avoid calling time() except for the first time.
1442    * GetTickCount() should be pretty fast and low-level?
1443    * I could also use ftime() but it seems unnecessarily overheady.
1444    */
1445   static DWORD start_tick = 0;
1446   static time_t start_time;
1447   DWORD tick;
1448
1449   g_return_if_fail (result != NULL);
1450  
1451   if (start_tick == 0)
1452     {
1453       start_tick = GetTickCount ();
1454       time (&start_time);
1455     }
1456
1457   tick = GetTickCount ();
1458
1459   result->tv_sec = (tick - start_tick) / 1000 + start_time;
1460   result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1461 #endif
1462 }
1463
1464 /* Running the main loop */
1465
1466 /* HOLDS: context's lock */
1467 static void
1468 g_main_dispatch (GMainContext *context)
1469 {
1470   gint i;
1471
1472   for (i = 0; i < context->pending_dispatches->len; i++)
1473     {
1474       GSource *source = context->pending_dispatches->pdata[i];
1475
1476       context->pending_dispatches->pdata[i] = NULL;
1477       g_assert (source);
1478
1479       source->flags &= ~G_SOURCE_READY;
1480
1481       if (!SOURCE_DESTROYED (source))
1482         {
1483           gboolean was_in_call;
1484           gpointer user_data = NULL;
1485           GSourceFunc callback = NULL;
1486           GSourceCallbackFuncs *cb_funcs;
1487           gpointer cb_data;
1488           gboolean need_destroy;
1489
1490           gboolean (*dispatch) (GSource *,
1491                                 GSourceFunc,
1492                                 gpointer);
1493
1494           dispatch = source->source_funcs->dispatch;
1495           cb_funcs = source->callback_funcs;
1496           cb_data = source->callback_data;
1497
1498           if (cb_funcs)
1499             cb_funcs->ref (cb_data);
1500           
1501           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1502           source->flags |= G_HOOK_FLAG_IN_CALL;
1503
1504           UNLOCK_CONTEXT (context);
1505
1506           if (cb_funcs)
1507             cb_funcs->get (cb_data, &callback, &user_data);
1508
1509           need_destroy = ! dispatch (source,
1510                                      callback,
1511                                      user_data);
1512           LOCK_CONTEXT (context);
1513
1514           if (cb_funcs)
1515             cb_funcs->unref (cb_data);
1516
1517          if (!was_in_call)
1518             source->flags &= ~G_HOOK_FLAG_IN_CALL;
1519
1520           /* Note: this depends on the fact that we can't switch
1521            * sources from one main context to another
1522            */
1523           if (need_destroy && !SOURCE_DESTROYED (source))
1524             {
1525               g_assert (source->context == context);
1526               g_source_destroy_internal (source, context, TRUE);
1527             }
1528         }
1529       
1530       SOURCE_UNREF (source, context);
1531     }
1532
1533   g_ptr_array_set_size (context->pending_dispatches, 0);
1534 }
1535
1536 /* Holds context's lock */
1537 static inline GSource *
1538 next_valid_source (GMainContext *context,
1539                    GSource      *source)
1540 {
1541   GSource *new_source = source ? source->next : context->source_list;
1542
1543   while (new_source)
1544     {
1545       if (!SOURCE_DESTROYED (new_source))
1546         {
1547           new_source->ref_count++;
1548           break;
1549         }
1550       
1551       new_source = new_source->next;
1552     }
1553
1554   if (source)
1555     SOURCE_UNREF (source, context);
1556           
1557   return new_source;
1558 }
1559
1560
1561 /**
1562  * g_main_context_prepare:
1563  * @context: a #GMainContext
1564  * @priority: location to store priority of highest priority
1565  *            source already ready.
1566  * 
1567  * Prepares to poll sources within a main loop. The resulting information
1568  * for polling is determined by calling g_main_context_query ().
1569  * 
1570  * Return value: %TRUE if some source is ready to be dispatched
1571  *               prior to polling.
1572  **/
1573 gboolean
1574 g_main_context_prepare (GMainContext *context,
1575                         gint         *priority)
1576 {
1577   gint n_ready = 0;
1578   gint current_priority = G_MAXINT;
1579   GSource *source;
1580
1581   if (context == NULL)
1582     context = g_main_context_default ();
1583   
1584   LOCK_CONTEXT (context);
1585
1586   context->time_is_current = FALSE;
1587
1588   if (context->in_check_or_prepare)
1589     {
1590       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1591                  "prepare() member.");
1592       return FALSE;
1593     }
1594
1595 #ifdef G_THREADS_ENABLED
1596   if (context->poll_waiting)
1597     {
1598       g_warning("g_main_context_prepare(): main loop already active in another thread");
1599       UNLOCK_CONTEXT (context);
1600       return FALSE;
1601     }
1602   
1603   context->poll_waiting = TRUE;
1604 #endif /* G_THREADS_ENABLED */
1605
1606 #if 0
1607   /* If recursing, finish up current dispatch, before starting over */
1608   if (context->pending_dispatches)
1609     {
1610       if (dispatch)
1611         g_main_dispatch (context, &current_time);
1612       
1613       UNLOCK_CONTEXT (context);
1614       return TRUE;
1615     }
1616 #endif
1617
1618   /* If recursing, clear list of pending dispatches */
1619   g_ptr_array_set_size (context->pending_dispatches, 0);
1620   
1621   /* Prepare all sources */
1622
1623   context->timeout = -1;
1624   
1625   source = next_valid_source (context, NULL);
1626   while (source)
1627     {
1628       gint source_timeout = -1;
1629
1630       if ((n_ready > 0) && (source->priority > current_priority))
1631         {
1632           SOURCE_UNREF (source, context);
1633           break;
1634         }
1635       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1636         goto next;
1637
1638       if (!(source->flags & G_SOURCE_READY))
1639         {
1640           gboolean result;
1641           gboolean (*prepare)  (GSource  *source, 
1642                                 gint     *timeout);
1643
1644           prepare = source->source_funcs->prepare;
1645           context->in_check_or_prepare++;
1646           UNLOCK_CONTEXT (context);
1647
1648           result = (*prepare) (source, &source_timeout);
1649
1650           LOCK_CONTEXT (context);
1651           context->in_check_or_prepare--;
1652
1653           if (result)
1654             source->flags |= G_SOURCE_READY;
1655         }
1656
1657       if (source->flags & G_SOURCE_READY)
1658         {
1659           n_ready++;
1660           current_priority = source->priority;
1661           context->timeout = 0;
1662         }
1663       
1664       if (source_timeout >= 0)
1665         {
1666           if (context->timeout < 0)
1667             context->timeout = source_timeout;
1668           else
1669             context->timeout = MIN (context->timeout, source_timeout);
1670         }
1671
1672     next:
1673       source = next_valid_source (context, source);
1674     }
1675
1676   UNLOCK_CONTEXT (context);
1677   
1678   if (priority)
1679     *priority = current_priority;
1680   
1681   return (n_ready > 0);
1682 }
1683
1684 /**
1685  * g_main_context_query:
1686  * @context: a #GMainContext
1687  * @max_priority: maximum priority source to check
1688  * @timeout: location to store timeout to be used in polling
1689  * @fds: location to store #GPollFD records that need to be polled.
1690  * @n_fds: length of @fds.
1691  * 
1692  * Determines information necessary to poll this main loop.
1693  * 
1694  * Return value: 
1695  **/
1696 gint
1697 g_main_context_query (GMainContext *context,
1698                       gint          max_priority,
1699                       gint         *timeout,
1700                       GPollFD      *fds,
1701                       gint          n_fds)
1702 {
1703   gint n_poll;
1704   GPollRec *pollrec;
1705   
1706   LOCK_CONTEXT (context);
1707
1708   pollrec = context->poll_records;
1709   n_poll = 0;
1710   while (pollrec && max_priority >= pollrec->priority)
1711     {
1712       if (pollrec->fd->events)
1713         {
1714           if (n_poll < n_fds)
1715             {
1716               fds[n_poll].fd = pollrec->fd->fd;
1717               /* In direct contradiction to the Unix98 spec, IRIX runs into
1718                * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1719                * flags in the events field of the pollfd while it should
1720                * just ignoring them. So we mask them out here.
1721                */
1722               fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1723               fds[n_poll].revents = 0;
1724             }
1725           n_poll++;
1726         }
1727       
1728       pollrec = pollrec->next;
1729     }
1730
1731   context->poll_changed = FALSE;
1732
1733   if (timeout)
1734     {
1735       *timeout = context->timeout;
1736       if (timeout != 0)
1737         context->time_is_current = FALSE;
1738     }
1739   
1740   UNLOCK_CONTEXT (context);
1741
1742   return n_poll;
1743 }
1744
1745 /**
1746  * g_main_context_check:
1747  * @context: a #GMainContext
1748  * @max_priority: the maximum numerical priority of sources to check
1749  * @fds: array of #GPollFD's that was passed to the last call to
1750  *       g_main_context_query()
1751  * @n_fds: return value of g_main_context_query()
1752  * 
1753  * Pass the results of polling back to the main loop.
1754  * 
1755  * Return value: %TRUE if some sources are ready to be dispatched.
1756  **/
1757 gboolean
1758 g_main_context_check (GMainContext *context,
1759                       gint          max_priority,
1760                       GPollFD      *fds,
1761                       gint          n_fds)
1762 {
1763   GSource *source;
1764   GPollRec *pollrec;
1765   gint n_ready = 0;
1766   gint i;
1767   
1768   LOCK_CONTEXT (context);
1769
1770   if (context->in_check_or_prepare)
1771     {
1772       g_warning ("g_main_context_check() called recursively from within a source's check() or "
1773                  "prepare() member.");
1774       return FALSE;
1775     }
1776   
1777 #ifdef G_THREADS_ENABLED
1778   if (!context->poll_waiting)
1779     {
1780 #ifndef G_OS_WIN32
1781       gchar c;
1782       read (context->wake_up_pipe[0], &c, 1);
1783 #endif
1784     }
1785   else
1786     context->poll_waiting = FALSE;
1787 #endif /* G_THREADS_ENABLED */
1788
1789   /* If the set of poll file descriptors changed, bail out
1790    * and let the main loop rerun
1791    */
1792   if (context->poll_changed)
1793     return 0;
1794
1795   pollrec = context->poll_records;
1796   i = 0;
1797   while (i < n_fds)
1798     {
1799       if (pollrec->fd->events)
1800         {
1801           pollrec->fd->revents = fds[i].revents;
1802           i++;
1803         }
1804       pollrec = pollrec->next;
1805     }
1806
1807   source = next_valid_source (context, NULL);
1808   while (source)
1809     {
1810       if ((n_ready > 0) && (source->priority > max_priority))
1811         {
1812           SOURCE_UNREF (source, context);
1813           break;
1814         }
1815       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1816         goto next;
1817
1818       if (!(source->flags & G_SOURCE_READY))
1819         {
1820           gboolean result;
1821           gboolean (*check) (GSource  *source);
1822
1823           check = source->source_funcs->check;
1824           
1825           context->in_check_or_prepare++;
1826           UNLOCK_CONTEXT (context);
1827           
1828           result = (*check) (source);
1829           
1830           LOCK_CONTEXT (context);
1831           context->in_check_or_prepare--;
1832           
1833           if (result)
1834             source->flags |= G_SOURCE_READY;
1835         }
1836
1837       if (source->flags & G_SOURCE_READY)
1838         {
1839           source->ref_count++;
1840           g_ptr_array_add (context->pending_dispatches, source);
1841
1842           n_ready++;
1843         }
1844
1845     next:
1846       source = next_valid_source (context, source);
1847     }
1848
1849   UNLOCK_CONTEXT (context);
1850
1851   return n_ready > 0;
1852 }
1853
1854 /**
1855  * g_main_context_dispatch:
1856  * @context: a #GMainContext
1857  * 
1858  * Dispatch all pending sources()
1859  **/
1860 void
1861 g_main_context_dispatch (GMainContext *context)
1862 {
1863   LOCK_CONTEXT (context);
1864
1865   if (context->pending_dispatches->len > 0)
1866     {
1867       g_main_dispatch (context);
1868     }
1869
1870   UNLOCK_CONTEXT (context);
1871 }
1872
1873 static gboolean
1874 g_main_context_iterate (GMainContext *context,
1875                         gboolean      block,
1876                         gboolean      dispatch)
1877 {
1878   gint max_priority;
1879   gint timeout;
1880   gboolean some_ready;
1881   gint nfds, new_nfds;
1882   GPollFD *fds;
1883   
1884   some_ready = g_main_context_prepare (context, &max_priority);
1885
1886   do
1887     {
1888       LOCK_CONTEXT (context);
1889
1890       if (context->cached_poll_array)
1891         {
1892           nfds = context->cached_poll_array_size;
1893           fds = context->cached_poll_array;
1894           context->cached_poll_array = NULL;
1895         }
1896       else
1897         {
1898           nfds = context->cached_poll_array_size = context->n_poll_records;
1899           fds = g_new (GPollFD, nfds);
1900         }
1901
1902       UNLOCK_CONTEXT (context);
1903   
1904       new_nfds = g_main_context_query (context, max_priority,
1905                                        &timeout, fds, nfds);
1906     }
1907   while (new_nfds > nfds);
1908
1909   if (!block)
1910     timeout = 0;
1911   
1912   g_main_context_poll (context, timeout, max_priority,
1913                        fds, new_nfds);
1914
1915   g_main_context_check (context,
1916                         max_priority,
1917                         fds, new_nfds);
1918
1919   LOCK_CONTEXT (context);
1920
1921   g_assert (!context->cached_poll_array);
1922   
1923   context->cached_poll_array = fds;
1924   context->cached_poll_array_size = nfds;
1925
1926   UNLOCK_CONTEXT (context);
1927   
1928   if (dispatch)
1929     g_main_context_dispatch (context);
1930
1931   return some_ready;
1932 }
1933
1934 /**
1935  * g_main_context_pending:
1936  * @context: a #GMainContext (if %NULL, the default context will be used)
1937  *
1938  * Check if any sources have pending events for the given context.
1939  * 
1940  * Return value: %TRUE if events are pending.
1941  **/
1942 gboolean 
1943 g_main_context_pending (GMainContext *context)
1944 {
1945   if (!context)
1946     context = g_main_context_default();
1947   
1948   return g_main_context_iterate (context, FALSE, FALSE);
1949 }
1950
1951 /**
1952  * g_main_context_iteration:
1953  * @context: a #GMainContext (if %NULL, the default context will be used) 
1954  * @may_block: whether the call may block.
1955  * 
1956  * Run a single iteration for the given main loop. This involves
1957  * checking to see if any event sources are ready to be processed,
1958  * then if no events sources are ready and @may_block is %TRUE, waiting
1959  * for a source to become ready, then dispatching the highest priority
1960  * events sources that are ready. Note that even when @may_block is %TRUE,
1961  * it is still possible for g_main_context_iteration() to return
1962  * %FALSE, since the the wait may be interrupted for other
1963  * reasons than an event source becoming ready.
1964  * 
1965  * Return value: %TRUE if events were dispatched.
1966  **/
1967 gboolean
1968 g_main_context_iteration (GMainContext *context, gboolean may_block)
1969 {
1970   if (!context)
1971     context = g_main_context_default();
1972   
1973   return g_main_context_iterate (context, may_block, TRUE);
1974 }
1975
1976 /**
1977  * g_main_loop_new:
1978  * @context: a #GMainContext  (if %NULL, the default context will be used).
1979  * @is_running: set to TRUE to indicate that the loop is running. This
1980  * is not very important since calling g_main_run() will set this to
1981  * TRUE anyway.
1982  * 
1983  * Create a new #GMainLoop structure
1984  * 
1985  * Return value: 
1986  **/
1987 GMainLoop *
1988 g_main_loop_new (GMainContext *context,
1989                  gboolean      is_running)
1990 {
1991   GMainLoop *loop;
1992   
1993   if (!context)
1994     context = g_main_context_default();
1995   
1996   loop = g_new0 (GMainLoop, 1);
1997   loop->context = context;
1998   loop->is_running = is_running != FALSE;
1999
2000 #ifdef G_THREADS_ENABLED
2001   if (g_thread_supported ())
2002     loop->mutex = g_mutex_new ();
2003   else
2004     loop->mutex = NULL;
2005   loop->sem_cond = NULL;
2006 #endif /* G_THREADS_ENABLED */
2007
2008   return loop;
2009 }
2010
2011 /**
2012  * g_main_loop_run:
2013  * @loop: a #GMainLoop
2014  * 
2015  * Run a main loop until g_main_quit() is called on the loop.
2016  * If this is called for the thread of the loop's #GMainContext,
2017  * it will process events from the loop, otherwise it will
2018  * simply wait.
2019  **/
2020 void 
2021 g_main_loop_run (GMainLoop *loop)
2022 {
2023   g_return_if_fail (loop != NULL);
2024
2025 #ifdef G_THREADS_ENABLED
2026   if (loop->context->thread != g_thread_self ())
2027     {
2028       LOCK_LOOP (loop);
2029
2030       if (!g_thread_supported ())
2031         {
2032           g_warning ("g_main_loop_run() was called from second thread but"
2033                      "g_thread_init() was never called.");
2034         }
2035       else
2036         {
2037           if (!loop->sem_cond)
2038             loop->sem_cond = g_cond_new ();
2039           
2040           if (!loop->is_running)
2041             loop->is_running = TRUE;
2042           
2043           while (loop->is_running)
2044             g_cond_wait (loop->sem_cond, loop->mutex);
2045         }
2046         
2047       UNLOCK_LOOP (loop);
2048     }
2049   else
2050 #endif /* G_THREADS_ENABLED */    
2051     {
2052       LOCK_CONTEXT (loop->context);
2053       if (loop->context->in_check_or_prepare)
2054         {
2055           g_warning ("g_main_run(): called recursively from within a source's check() or "
2056                      "prepare() member, iteration not possible.");
2057           return;
2058         }
2059       UNLOCK_CONTEXT (loop->context);
2060       
2061       LOCK_LOOP (loop);
2062
2063       loop->is_running = TRUE;
2064       while (loop->is_running)
2065         {
2066           UNLOCK_LOOP (loop);
2067           g_main_context_iterate (loop->context, TRUE, TRUE);
2068           LOCK_LOOP (loop);
2069         }
2070       UNLOCK_LOOP (loop);
2071     }
2072 }
2073
2074 /**
2075  * g_main_loop_quit:
2076  * @loop: a #GMainLoop
2077  * 
2078  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2079  * for the loop will return.
2080  **/
2081 void 
2082 g_main_loop_quit (GMainLoop *loop)
2083 {
2084   g_return_if_fail (loop != NULL);
2085
2086   LOCK_LOOP (loop);
2087   loop->is_running = FALSE;
2088
2089   if (loop->sem_cond)
2090     g_cond_broadcast (loop->sem_cond);
2091   
2092   UNLOCK_LOOP (loop);
2093
2094   LOCK_CONTEXT (loop->context);
2095   
2096   g_main_context_wakeup (loop->context);
2097   UNLOCK_CONTEXT (loop->context);
2098 }
2099
2100 /**
2101  * g_main_loop_destroy:
2102  * @loop: a #GMainLoop
2103  * 
2104  * Destroy a #GMainLoop object and free all associated memory.
2105  * The loop must not currently be running via g_main_run().
2106  **/
2107 void 
2108 g_main_loop_destroy (GMainLoop *loop)
2109 {
2110   g_return_if_fail (loop != NULL);
2111   g_return_if_fail (!loop->is_running);
2112
2113 #ifdef G_THREADS_ENABLED
2114   g_mutex_free (loop->mutex);
2115   if (loop->sem_cond)
2116     g_cond_free (loop->sem_cond);
2117 #endif /* G_THREADS_ENABLED */  
2118
2119   g_free (loop);
2120 }
2121
2122 /**
2123  * g_main_loop_is_running:
2124  * @loop: a #GMainLoop.
2125  * 
2126  * Check to see if the main loop is currently being run via g_main_run()
2127  * 
2128  * Return value: %TRUE if the mainloop is currently being run.
2129  **/
2130 gboolean
2131 g_main_loop_is_running (GMainLoop *loop)
2132 {
2133   gboolean result;
2134   
2135   g_return_val_if_fail (loop != NULL, FALSE);
2136
2137   LOCK_LOOP (loop);
2138   result = loop->is_running;
2139   UNLOCK_LOOP (loop);
2140
2141   return result;
2142 }
2143
2144 /* HOLDS: context's lock */
2145 static void
2146 g_main_context_poll (GMainContext *context,
2147                      gint          timeout,
2148                      gint          priority,
2149                      GPollFD      *fds,
2150                      gint          n_fds)
2151 {
2152 #ifdef  G_MAIN_POLL_DEBUG
2153   GTimer *poll_timer;
2154   GPollRec *pollrec;
2155   gint i;
2156 #endif
2157
2158   GPollFunc poll_func;
2159
2160   if (n_fds || timeout != 0)
2161     {
2162 #ifdef  G_MAIN_POLL_DEBUG
2163       g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2164       poll_timer = g_timer_new ();
2165 #endif
2166
2167       LOCK_CONTEXT (context);
2168
2169       poll_func = context->poll_func;
2170       
2171       UNLOCK_CONTEXT (context);
2172       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2173         g_warning ("poll(2) failed due to: %s.",
2174                    g_strerror (errno));
2175       
2176 #ifdef  G_MAIN_POLL_DEBUG
2177       LOCK_CONTEXT (context);
2178
2179       g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2180                n_fds,
2181                timeout,
2182                g_timer_elapsed (poll_timer, NULL));
2183       g_timer_destroy (poll_timer);
2184       pollrec = context->poll_records;
2185       i = 0;
2186       while (i < n_fds)
2187         {
2188           if (pollrec->fd->events)
2189             {
2190               if (fds[i].revents)
2191                 {
2192                   g_print (" [%d:", fds[i].fd);
2193                   if (fds[i].revents & G_IO_IN)
2194                     g_print ("i");
2195                   if (fds[i].revents & G_IO_OUT)
2196                     g_print ("o");
2197                   if (fds[i].revents & G_IO_PRI)
2198                     g_print ("p");
2199                   if (fds[i].revents & G_IO_ERR)
2200                     g_print ("e");
2201                   if (fds[i].revents & G_IO_HUP)
2202                     g_print ("h");
2203                   if (fds[i].revents & G_IO_NVAL)
2204                     g_print ("n");
2205                   g_print ("]");
2206                 }
2207               i++;
2208             }
2209           pollrec = pollrec->next;
2210         }
2211       g_print ("\n");
2212       
2213       UNLOCK_CONTEXT (context);
2214 #endif
2215     } /* if (n_fds || timeout != 0) */
2216 }
2217
2218 /**
2219  * g_main_context_add_poll:
2220  * @context: a #GMainContext (or %NULL for the default context)
2221  * @fd: a #GPollFD structure holding information about a file
2222  *      descriptor to watch.
2223  * @priority: the priority for this file descriptor which should be
2224  *      the same as the priority used for g_source_attach() to ensure that the
2225  *      file descriptor is polled whenever the results may be needed.
2226  * 
2227  * Add a file descriptor to the set of file descriptors polled * for
2228  * this context. This will very seldom be used directly. Instead
2229  * a typical event source will use g_source_add_poll() instead.
2230  **/
2231 void
2232 g_main_context_add_poll (GMainContext *context,
2233                          GPollFD      *fd,
2234                          gint          priority)
2235 {
2236   if (!context)
2237     context = g_main_context_default ();
2238   
2239   LOCK_CONTEXT (context);
2240   g_main_context_add_poll_unlocked (context, priority, fd);
2241   UNLOCK_CONTEXT (context);
2242 }
2243
2244 /* HOLDS: main_loop_lock */
2245 static void 
2246 g_main_context_add_poll_unlocked (GMainContext *context,
2247                                   gint          priority,
2248                                   GPollFD      *fd)
2249 {
2250   GPollRec *lastrec, *pollrec, *newrec;
2251
2252   if (!context->poll_chunk)
2253     context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2254
2255   if (context->poll_free_list)
2256     {
2257       newrec = context->poll_free_list;
2258       context->poll_free_list = newrec->next;
2259     }
2260   else
2261     newrec = g_chunk_new (GPollRec, context->poll_chunk);
2262
2263   /* This file descriptor may be checked before we ever poll */
2264   fd->revents = 0;
2265   newrec->fd = fd;
2266   newrec->priority = priority;
2267
2268   lastrec = NULL;
2269   pollrec = context->poll_records;
2270   while (pollrec && priority >= pollrec->priority)
2271     {
2272       lastrec = pollrec;
2273       pollrec = pollrec->next;
2274     }
2275   
2276   if (lastrec)
2277     lastrec->next = newrec;
2278   else
2279     context->poll_records = newrec;
2280
2281   newrec->next = pollrec;
2282
2283   context->n_poll_records++;
2284   if (context->cached_poll_array &&
2285       context->cached_poll_array_size < context->n_poll_records)
2286     {
2287       g_free (context->cached_poll_array);
2288       context->cached_poll_array = NULL;
2289     }
2290
2291 #ifdef G_THREADS_ENABLED
2292   context->poll_changed = TRUE;
2293
2294   /* Now wake up the main loop if it is waiting in the poll() */
2295   g_main_context_wakeup (context);
2296 #endif
2297 }
2298
2299 /**
2300  * g_main_context_remove_poll:
2301  * @context:a #GMainContext 
2302  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2303  * 
2304  * Remove file descriptor from the set of file descriptors to be
2305  * polled for a particular context.
2306  **/
2307 void
2308 g_main_context_remove_poll (GMainContext *context,
2309                             GPollFD      *fd)
2310 {
2311   if (!context)
2312     context = g_main_context_default ();
2313   
2314   LOCK_CONTEXT (context);
2315
2316   g_main_context_remove_poll_unlocked (context, fd);
2317   
2318   UNLOCK_CONTEXT (context);
2319 }
2320
2321 static void
2322 g_main_context_remove_poll_unlocked (GMainContext *context,
2323                                      GPollFD      *fd)
2324 {
2325   GPollRec *pollrec, *lastrec;
2326
2327   lastrec = NULL;
2328   pollrec = context->poll_records;
2329
2330   while (pollrec)
2331     {
2332       if (pollrec->fd == fd)
2333         {
2334           if (lastrec != NULL)
2335             lastrec->next = pollrec->next;
2336           else
2337             context->poll_records = pollrec->next;
2338
2339 #ifdef ENABLE_GC_FRIENDLY
2340           pollrec->fd = NULL;  
2341 #endif /* ENABLE_GC_FRIENDLY */
2342
2343           pollrec->next = context->poll_free_list;
2344           context->poll_free_list = pollrec;
2345
2346           context->n_poll_records--;
2347           break;
2348         }
2349       lastrec = pollrec;
2350       pollrec = pollrec->next;
2351     }
2352
2353 #ifdef G_THREADS_ENABLED
2354   context->poll_changed = TRUE;
2355   
2356   /* Now wake up the main loop if it is waiting in the poll() */
2357   g_main_context_wakeup (context);
2358 #endif
2359 }
2360
2361 /**
2362  * g_source_get_current_time:
2363  * @source:  a #GSource
2364  * @timeval: #GTimeVal structure in which to store current time.
2365  * 
2366  * Gets the "current time" to be used when checking 
2367  * this source. The advantage of calling this function over
2368  * calling g_get_current_time() directly is that when 
2369  * checking multiple sources, GLib can cache a single value
2370  * instead of having to repeatedly get the system time.
2371  **/
2372 void
2373 g_source_get_current_time (GSource  *source,
2374                            GTimeVal *timeval)
2375 {
2376   GMainContext *context;
2377   
2378   g_return_if_fail (source->context != NULL);
2379  
2380   context = source->context;
2381
2382   LOCK_CONTEXT (context);
2383
2384   if (!context->time_is_current)
2385     {
2386       g_get_current_time (&context->current_time);
2387       context->time_is_current = TRUE;
2388     }
2389   
2390   *timeval = context->current_time;
2391   
2392   UNLOCK_CONTEXT (context);
2393 }
2394
2395 /**
2396  * g_main_context_set_poll_func:
2397  * @context: a #GMainContext
2398  * @func: the function to call to poll all file descriptors
2399  * 
2400  * Sets the function to use to handle polling of file descriptors. It
2401  * will be used instead of the poll() system call (or GLib's
2402  * replacement function, which is used where poll() isn't available).
2403  *
2404  * This function could possibly be used to integrate the GLib event
2405  * loop with an external event loop.
2406  **/
2407 void
2408 g_main_context_set_poll_func (GMainContext *context,
2409                               GPollFunc     func)
2410 {
2411   if (!context)
2412     context = g_main_context_default ();
2413   
2414   LOCK_CONTEXT (context);
2415   
2416   if (func)
2417     context->poll_func = func;
2418   else
2419     {
2420 #ifdef HAVE_POLL
2421       context->poll_func = (GPollFunc) poll;
2422 #else
2423       context->poll_func = (GPollFunc) g_poll;
2424 #endif
2425     }
2426
2427   UNLOCK_CONTEXT (context);
2428 }
2429
2430 #ifdef G_OS_WIN32
2431
2432 /**
2433  * g_main_context_get_poll_func:
2434  * @context: a #GMainContext
2435  * 
2436  * Gets the poll function set by g_main_context_set_poll_func()
2437  * 
2438  * Return value: the poll function
2439  **/
2440 GPollFunc
2441 g_main_context_get_poll_func (GMainContext *context)
2442 {
2443   GPollFunc *result;
2444   
2445   if (!context)
2446     context = g_main_context_default ();
2447   
2448   LOCK_CONTEXT (context);
2449   result = context->poll_func;
2450   UNLOCK_CONTEXT (context);
2451 }
2452
2453 #endif
2454
2455 /* HOLDS: context's lock */
2456 /* Wake the main loop up from a poll() */
2457 static void
2458 g_main_context_wakeup (GMainContext *context)
2459 {
2460 #ifdef G_THREADS_ENABLED
2461   if (g_thread_supported() && context->poll_waiting)
2462     {
2463       context->poll_waiting = FALSE;
2464 #ifndef G_OS_WIN32
2465       write (context->wake_up_pipe[1], "A", 1);
2466 #else
2467       ReleaseSemaphore (context->context->wake_up_semaphore, 1, NULL);
2468 #endif
2469     }
2470 #endif
2471 }
2472
2473 /* Timeouts */
2474
2475 static void
2476 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2477                           GTimeVal       *current_time)
2478 {
2479   guint seconds = timeout_source->interval / 1000;
2480   guint msecs = timeout_source->interval - seconds * 1000;
2481
2482   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2483   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2484   if (timeout_source->expiration.tv_usec >= 1000000)
2485     {
2486       timeout_source->expiration.tv_usec -= 1000000;
2487       timeout_source->expiration.tv_sec++;
2488     }
2489 }
2490
2491 static gboolean
2492 g_timeout_prepare  (GSource  *source,
2493                     gint     *timeout)
2494 {
2495   glong msec;
2496   GTimeVal current_time;
2497   
2498   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2499
2500   g_source_get_current_time (source, &current_time);
2501   
2502   msec = ((timeout_source->expiration.tv_sec  - current_time.tv_sec) * 1000 +
2503           (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2504
2505   if (msec < 0)
2506     msec = 0;
2507   else if (msec > timeout_source->interval)
2508     {
2509       /* The system time has been set backwards, so we
2510        * reset the expiration time to now + timeout_source->interval;
2511        * this at least avoids hanging for long periods of time.
2512        */
2513       g_timeout_set_expiration (timeout_source, &current_time);
2514       msec = timeout_source->interval;
2515     }
2516   
2517   *timeout = msec;
2518   
2519   return msec == 0;
2520 }
2521
2522 static gboolean 
2523 g_timeout_check (GSource  *source)
2524 {
2525   GTimeVal current_time;
2526   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2527
2528   g_source_get_current_time (source, &current_time);
2529   
2530   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2531           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2532            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2533 }
2534
2535 static gboolean
2536 g_timeout_dispatch (GSource    *source,
2537                     GSourceFunc callback,
2538                     gpointer    user_data)
2539 {
2540   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2541
2542   if (!callback)
2543     {
2544       g_warning ("Timeout source dispatched without callback\n"
2545                  "You must call g_source_set_callback().");
2546       return FALSE;
2547     }
2548  
2549   if (callback (user_data))
2550     {
2551       GTimeVal current_time;
2552
2553       g_source_get_current_time (source, &current_time);
2554       g_timeout_set_expiration (timeout_source, &current_time);
2555
2556       return TRUE;
2557     }
2558   else
2559     return FALSE;
2560 }
2561
2562 /**
2563  * g_timeout_source_new:
2564  * @interval: the timeout interval in milliseconds.
2565  * 
2566  * Create a new timeout source.
2567  *
2568  * The source will not initially be associated with any #GMainContext
2569  * and must be added to one with g_source_attach() before it will be
2570  * executed.
2571  * 
2572  * Return value: the newly create timeout source
2573  **/
2574 GSource *
2575 g_timeout_source_new (guint interval)
2576 {
2577   GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2578   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2579   GTimeVal current_time;
2580
2581   timeout_source->interval = interval;
2582
2583   g_get_current_time (&current_time);
2584   g_timeout_set_expiration (timeout_source, &current_time);
2585   
2586   return source;
2587 }
2588
2589 /**
2590  * g_timeout_add_full:
2591  * @priority: the priority of the idle source. Typically this will be in the
2592  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2593  * @interval: the time between calls to the function, in milliseconds
2594  *             (1/1000ths of a second.)
2595  * @function: function to call
2596  * @data:     data to pass to @function
2597  * @notify:   function to call when the idle is removed, or %NULL
2598  * 
2599  * Sets a function to be called at regular intervals, with the given
2600  * priority.  The function is called repeatedly until it returns
2601  * FALSE, at which point the timeout is automatically destroyed and
2602  * the function will not be called again.  The @notify function is
2603  * called when the timeout is destroyed.  The first call to the
2604  * function will be at the end of the first @interval.
2605  *
2606  * Note that timeout functions may be delayed, due to the processing of other
2607  * event sources. Thus they should not be relied on for precise timing.
2608  * After each call to the timeout function, the time of the next
2609  * timeout is recalculated based on the current time and the given interval
2610  * (it does not try to 'catch up' time lost in delays).
2611  * 
2612  * Return value: the id of event source.
2613  **/
2614 guint
2615 g_timeout_add_full (gint           priority,
2616                     guint          interval,
2617                     GSourceFunc    function,
2618                     gpointer       data,
2619                     GDestroyNotify notify)
2620 {
2621   GSource *source;
2622   guint id;
2623   
2624   g_return_val_if_fail (function != NULL, 0);
2625
2626   source = g_timeout_source_new (interval);
2627
2628   if (priority != G_PRIORITY_DEFAULT)
2629     g_source_set_priority (source, priority);
2630
2631   g_source_set_callback (source, function, data, notify);
2632   id = g_source_attach (source, NULL);
2633   g_source_unref (source);
2634
2635   return id;
2636 }
2637
2638 /**
2639  * g_timeout_add:
2640  * @interval: the time between calls to the function, in milliseconds
2641  *             (1/1000ths of a second.)
2642  * @function: function to call
2643  * @data:     data to pass to @function
2644  * 
2645  * Sets a function to be called at regular intervals, with the default
2646  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
2647  * until it returns FALSE, at which point the timeout is automatically
2648  * destroyed and the function will not be called again.  The @notify
2649  * function is called when the timeout is destroyed.  The first call
2650  * to the function will be at the end of the first @interval.
2651  *
2652  * Note that timeout functions may be delayed, due to the processing of other
2653  * event sources. Thus they should not be relied on for precise timing.
2654  * After each call to the timeout function, the time of the next
2655  * timeout is recalculated based on the current time and the given interval
2656  * (it does not try to 'catch up' time lost in delays).
2657  * 
2658  * Return value: the id of event source.
2659  **/
2660 guint 
2661 g_timeout_add (guint32        interval,
2662                GSourceFunc    function,
2663                gpointer       data)
2664 {
2665   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
2666                              interval, function, data, NULL);
2667 }
2668
2669 /* Idle functions */
2670
2671 static gboolean 
2672 g_idle_prepare  (GSource  *source,
2673                  gint     *timeout)
2674 {
2675   *timeout = 0;
2676
2677   return TRUE;
2678 }
2679
2680 static gboolean 
2681 g_idle_check    (GSource  *source)
2682 {
2683   return TRUE;
2684 }
2685
2686 static gboolean
2687 g_idle_dispatch (GSource    *source, 
2688                  GSourceFunc callback,
2689                  gpointer    user_data)
2690 {
2691   if (!callback)
2692     {
2693       g_warning ("Idle source dispatched without callback\n"
2694                  "You must call g_source_set_callback().");
2695       return FALSE;
2696     }
2697   
2698   return callback (user_data);
2699 }
2700
2701 /**
2702  * g_idle_source_new:
2703  * 
2704  * Create a new idle source.
2705  *
2706  * The source will not initially be associated with any #GMainContext
2707  * and must be added to one with g_source_attach() before it will be
2708  * executed.
2709  * 
2710  * Return value: the newly created idle source
2711  **/
2712 GSource *
2713 g_idle_source_new (void)
2714 {
2715   return g_source_new (&idle_funcs, sizeof (GSource));
2716 }
2717
2718 /**
2719  * g_idle_add_full:
2720  * @priority: the priority of the idle source. Typically this will be in the
2721  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2722  * @function: function to call
2723  * @data:     data to pass to @function
2724  * @notify:   function to call when the idle is removed, or %NULL
2725  * 
2726  * Adds a function to be called whenever there are no higher priority
2727  * events pending.  If the function returns FALSE it is automatically
2728  * removed from the list of event sources and will not be called again.
2729  * 
2730  * Return value: the id of the event source.
2731  **/
2732 guint 
2733 g_idle_add_full (gint           priority,
2734                  GSourceFunc    function,
2735                  gpointer       data,
2736                  GDestroyNotify notify)
2737 {
2738   GSource *source;
2739   guint id;
2740   
2741   g_return_val_if_fail (function != NULL, 0);
2742
2743   source = g_idle_source_new ();
2744
2745   if (priority != G_PRIORITY_DEFAULT)
2746     g_source_set_priority (source, priority);
2747
2748   g_source_set_callback (source, function, data, notify);
2749   id = g_source_attach (source, NULL);
2750   g_source_unref (source);
2751
2752   return id;
2753 }
2754
2755 /**
2756  * g_idle_add:
2757  * @function: function to call 
2758  * @data: data to pass to @function.
2759  * 
2760  * Adds a function to be called whenever there are no higher priority
2761  * events pending to the default main loop. The function is given the
2762  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
2763  * returns FALSE it is automatically removed from the list of event
2764  * sources and will not be called again.
2765  * 
2766  * Return value: the id of the event source.
2767  **/
2768 guint 
2769 g_idle_add (GSourceFunc    function,
2770             gpointer       data)
2771 {
2772   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2773 }
2774
2775 /**
2776  * g_idle_remove_by_data:
2777  * @data: the data for the idle source's callback.
2778  * 
2779  * Removes the idle function with the given data.
2780  * 
2781  * Return value: %TRUE if an idle source was found and removed.
2782  **/
2783 gboolean
2784 g_idle_remove_by_data (gpointer data)
2785 {
2786   return g_source_remove_by_funcs_user_data (&idle_funcs, data);
2787 }
2788