Major change in API for creating sources to handle multiple main loops
[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   g_source_list_add (source, context);
756
757   tmp_list = source->poll_fds;
758   while (tmp_list)
759     {
760       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
761       tmp_list = tmp_list->next;
762     }
763
764 #ifdef G_THREADS_ENABLED
765   /* Now wake up the main loop if it is waiting in the poll() */
766   g_main_context_wakeup (context);
767 #endif
768
769   UNLOCK_CONTEXT (context);
770
771   return result;
772 }
773
774 static void
775 g_source_destroy_internal (GSource      *source,
776                            GMainContext *context,
777                            gboolean      have_lock)
778 {
779   if (!have_lock)
780     LOCK_CONTEXT (context);
781   
782   if (!SOURCE_DESTROYED (source))
783     {
784       gpointer old_cb_data;
785       GSourceCallbackFuncs *old_cb_funcs;
786       
787       source->flags &= ~G_HOOK_FLAG_ACTIVE;
788
789       old_cb_data = source->callback_data;
790       old_cb_funcs = source->callback_funcs;
791
792       source->callback_data = NULL;
793       source->callback_funcs = NULL;
794
795       if (old_cb_funcs)
796         {
797           UNLOCK_CONTEXT (context);
798           old_cb_funcs->unref (old_cb_data);
799           LOCK_CONTEXT (context);
800         }
801       
802       g_source_unref_internal (source, context, TRUE);
803     }
804
805   if (!have_lock)
806     UNLOCK_CONTEXT (context);
807 }
808
809 /**
810  * g_source_destroy:
811  * @source: a #GSource
812  * 
813  * Remove a source from its #GMainContext, if any, and mark it as
814  * destroyed.  The source cannot be subsequently added to another
815  * context.
816  **/
817 void
818 g_source_destroy (GSource *source)
819 {
820   GMainContext *context;
821   
822   g_return_if_fail (source != NULL);
823   
824   context = source->context;
825   
826   if (context)
827     g_source_destroy_internal (source, context, FALSE);
828   else
829     source->flags &= ~G_HOOK_FLAG_ACTIVE;
830 }
831
832 /**
833  * g_source_get_id:
834  * @source: a #GSource
835  * 
836  * Return the numeric ID for a particular source. The ID of a source
837  * is unique within a particular main loop context. The reverse
838  * mapping from ID to source is done by g_main_context_find_source_by_id().
839  *
840  * Return value: the ID for the source
841  **/
842 guint
843 g_source_get_id (GSource *source)
844 {
845   guint result;
846   
847   g_return_val_if_fail (source != NULL, 0);
848   g_return_val_if_fail (source->context != NULL, 0);
849
850   LOCK_CONTEXT (source->context);
851   result = source->id;
852   UNLOCK_CONTEXT (source->context);
853   
854   return result;
855 }
856
857 /**
858  * g_source_get_context:
859  * @source: a #GSource
860  * 
861  * Get the #GMainContext with which the source is associated.
862  * Calling this function on a destroyed source is an error.
863  * 
864  * Return value: the #GMainContext with which the source is associated,
865  *               or %NULL if the context has not yet been added
866  *               to a source.
867  **/
868 GMainContext *
869 g_source_get_context (GSource *source)
870 {
871   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
872
873   return source->context;
874 }
875
876 /**
877  * g_main_source_add_poll:
878  * @source:a #GSource 
879  * @fd: a #GPollFD structure holding information about a file
880  *      descriptor to watch.
881  * 
882  * Add a file descriptor to the set of file descriptors polled * for
883  * this source. This is usually combined with g_source_new() to add an
884  * event source. The event source's check function will typically test
885  * the revents field in the #GPollFD struct and return %TRUE if events need
886  * to be processed.
887  **/
888 void
889 g_source_add_poll (GSource *source,
890                    GPollFD *fd)
891 {
892   GMainContext *context;
893   
894   g_return_if_fail (source != NULL);
895   g_return_if_fail (fd != NULL);
896
897   context = source->context;
898
899   if (context)
900     LOCK_CONTEXT (context);
901   
902   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
903
904   if (context)
905     {
906       g_main_context_add_poll_unlocked (context, source->priority, fd);
907       UNLOCK_CONTEXT (context);
908     }
909 }
910
911 /**
912  * g_source_set_callback_indirect:
913  * @source: the source
914  * @callback_data: pointer to callback data "object"
915  * @callback_funcs: functions for reference counting callback_data
916  *                  and getting the callback and data
917  * 
918  * Set the callback function storing the data as a refcounted callback
919  * "object". This is used to implement g_source_set_callback_closure()
920  * and internally. Note that calling g_source_set_callback_indirect() assumes
921  * an initial reference count on @callback_data, and thus
922  * @callback_funcs->unref will eventually be called once more
923  * than @callback_funcs->ref.
924  **/
925 void
926 g_source_set_callback_indirect (GSource              *source,
927                                 gpointer              callback_data,
928                                 GSourceCallbackFuncs *callback_funcs)
929 {
930   GMainContext *context;
931   gpointer old_cb_data;
932   GSourceCallbackFuncs *old_cb_funcs;
933   
934   g_return_if_fail (source != NULL);
935   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
936
937   context = source->context;
938
939   if (context)
940     LOCK_CONTEXT (context);
941
942   old_cb_data = source->callback_data;
943   old_cb_funcs = source->callback_funcs;
944
945   source->callback_data = callback_data;
946   source->callback_funcs = callback_funcs;
947   
948   if (context)
949     UNLOCK_CONTEXT (context);
950   
951   if (old_cb_funcs)
952     old_cb_funcs->unref (old_cb_data);
953 }
954
955 static void
956 g_source_callback_ref (gpointer cb_data)
957 {
958   GSourceCallback *callback = cb_data;
959
960   callback->ref_count++;
961 }
962
963
964 static void
965 g_source_callback_unref (gpointer cb_data)
966 {
967   GSourceCallback *callback = cb_data;
968
969   callback->ref_count--;
970   if (callback->ref_count == 0)
971     {
972       if (callback->notify)
973         callback->notify (callback->data);
974     }
975 }
976
977 static void
978 g_source_callback_get (gpointer     cb_data,
979                        GSourceFunc *func,
980                        gpointer    *data)
981 {
982   GSourceCallback *callback = cb_data;
983
984   *func = callback->func;
985   *data = callback->data;
986 }
987
988 static GSourceCallbackFuncs g_source_callback_funcs = {
989   g_source_callback_ref,
990   g_source_callback_unref,
991   g_source_callback_get,
992 };
993
994 /**
995  * g_source_set_callback:
996  * @source: the source
997  * @func: a callback function
998  * @data: the data to pass to callback function
999  * @notify: a function to call when @data is no longer in use, or %NULL.
1000  * 
1001  * Set the callback function for a source.
1002  **/
1003 void
1004 g_source_set_callback (GSource        *source,
1005                        GSourceFunc     func,
1006                        gpointer        data,
1007                        GDestroyNotify  notify)
1008 {
1009   GSourceCallback *new_callback;
1010
1011   g_return_if_fail (source != NULL);
1012
1013   new_callback = g_new (GSourceCallback, 1);
1014   
1015   new_callback->func = func;
1016   new_callback->data = data;
1017   new_callback->notify = notify;
1018
1019   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1020 }
1021
1022 /**
1023  * g_source_set_priority:
1024  * @source: a #GSource
1025  * @priority: the new priority.
1026  * 
1027  * Set the priority of a source. While the main loop is being
1028  * run, a source will 
1029  **/
1030 void
1031 g_source_set_priority (GSource  *source,
1032                        gint      priority)
1033 {
1034   GSList *tmp_list;
1035   GMainContext *context;
1036   
1037   g_return_if_fail (source != NULL);
1038
1039   context = source->context;
1040
1041   if (context)
1042     LOCK_CONTEXT (context);
1043   
1044   source->priority = priority;
1045
1046   if (context)
1047     {
1048       source->next = NULL;
1049       source->prev = NULL;
1050       
1051       tmp_list = source->poll_fds;
1052       while (tmp_list)
1053         {
1054           g_main_context_remove_poll_unlocked (context, tmp_list->data);
1055           g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1056       
1057           tmp_list = tmp_list->next;
1058         }
1059       
1060       UNLOCK_CONTEXT (source->context);
1061     }
1062 }
1063
1064 /**
1065  * g_source_get_priority:
1066  * @source: a #GSource
1067  * 
1068  * Gets the priority of a surce
1069  * 
1070  * Return value: the priority of the source
1071  **/
1072 gint
1073 g_source_get_priority (GSource *source)
1074 {
1075   g_return_val_if_fail (source != NULL, 0);
1076
1077   return source->priority;
1078 }
1079
1080 /**
1081  * g_source_set_can_recurse:
1082  * @source: a #GSource
1083  * @can_recurse: whether recursion is allowed for this source
1084  * 
1085  * Sets whether a source can be called recursively. If @can_recurse is
1086  * %TRUE, then while the source is being dispatched then this source
1087  * will be processed normally. Otherwise, all processing of this
1088  * source is blocked until the dispatch function returns.
1089  **/
1090 void
1091 g_source_set_can_recurse (GSource  *source,
1092                           gboolean  can_recurse)
1093 {
1094   GMainContext *context;
1095   
1096   g_return_if_fail (source != NULL);
1097
1098   context = source->context;
1099
1100   if (context)
1101     LOCK_CONTEXT (context);
1102   
1103   if (can_recurse)
1104     source->flags |= G_SOURCE_CAN_RECURSE;
1105   else
1106     source->flags &= ~G_SOURCE_CAN_RECURSE;
1107
1108   if (context)
1109     UNLOCK_CONTEXT (context);
1110 }
1111
1112 /**
1113  * g_source_get_can_recurse:
1114  * @source: a #GSource
1115  * 
1116  * Checks whether a source is allowed to be called recursively.
1117  * see g_source_set_can_recurse.
1118  * 
1119  * Return value: whether recursion is allowed.
1120  **/
1121 gboolean
1122 g_source_get_can_recurse (GSource  *source)
1123 {
1124   g_return_val_if_fail (source != NULL, FALSE);
1125   
1126   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1127 }
1128
1129 /**
1130  * g_source_ref:
1131  * @source: a #GSource
1132  * 
1133  * Increases the reference count on a source by one.
1134  * 
1135  * Return value: @source
1136  **/
1137 GSource *
1138 g_source_ref (GSource *source)
1139 {
1140   GMainContext *context;
1141   
1142   g_return_val_if_fail (source != NULL, NULL);
1143
1144   context = source->context;
1145
1146   if (context)
1147     LOCK_CONTEXT (context);
1148
1149   source->ref_count++;
1150
1151   if (context)
1152     UNLOCK_CONTEXT (context);
1153
1154   return source;
1155 }
1156
1157 /* g_source_unref() but possible to call within context lock
1158  */
1159 static void
1160 g_source_unref_internal (GSource      *source,
1161                          GMainContext *context,
1162                          gboolean      have_lock)
1163 {
1164   gpointer cb_data = NULL;
1165   GSourceCallbackFuncs *cb_funcs = NULL;
1166   GSList *tmp_list;
1167
1168   g_return_if_fail (source != NULL);
1169   
1170   if (!have_lock && context)
1171     LOCK_CONTEXT (context);
1172
1173   source->ref_count--;
1174   if (source->ref_count == 0)
1175     {
1176       if (context && !SOURCE_DESTROYED (source))
1177         {
1178           g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1179           source->ref_count++;
1180         }
1181       else
1182         {
1183           g_source_list_remove (source, context);
1184           
1185           tmp_list = source->poll_fds;
1186           while (tmp_list)
1187             {
1188               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1189               tmp_list = tmp_list->next;
1190             }
1191         }
1192     }
1193   
1194   if (!have_lock && context)
1195     UNLOCK_CONTEXT (context);
1196
1197   if (cb_data)
1198     {
1199       if (have_lock)
1200         UNLOCK_CONTEXT (context);
1201       
1202       cb_funcs->unref (cb_data);
1203
1204       if (have_lock)
1205         LOCK_CONTEXT (context);
1206     }
1207 }
1208
1209 /**
1210  * g_source_unref:
1211  * @source: a #GSource
1212  * 
1213  * Decreases the reference count of a source by one. If the
1214  * resulting reference count is zero the source and associated
1215  * memory will be destroyed. 
1216  **/
1217 void
1218 g_source_unref (GSource *source)
1219 {
1220   g_return_if_fail (source != NULL);
1221
1222   g_source_unref_internal (source, source->context, FALSE);
1223 }
1224
1225 /**
1226  * g_main_context_find_source_by_id:
1227  * @context: a #GMainContext (if %NULL, the default context will be used)
1228  * @id: the source ID, as returned by g_source_get_id()
1229  * 
1230  * Finds a #GSource given a pair of context and ID
1231  * 
1232  * Return value: the #GSource if found, otherwise, %NULL
1233  **/
1234 GSource *
1235 g_main_context_find_source_by_id (GMainContext *context,
1236                                   guint         id)
1237 {
1238   GSource *source;
1239   
1240   g_return_val_if_fail (id > 0, FALSE);
1241
1242   if (context == NULL)
1243     context = g_main_context_default ();
1244   
1245   LOCK_CONTEXT (context);
1246   
1247   source = context->source_list;
1248   while (source)
1249     {
1250       if (!SOURCE_DESTROYED (source) &&
1251           source->id == id)
1252         break;
1253       source = source->next;
1254     }
1255
1256   UNLOCK_CONTEXT (context);
1257
1258   return source;
1259 }
1260
1261 /**
1262  * g_main_context_find_source_by_funcs_user_data:
1263  * @context: a #GMainContext (if %NULL, the default context will be used).
1264  * @funcs: the @source_funcs passed to g_source_new().
1265  * @user_data: the user data from the callback.
1266  * 
1267  * Finds a source with the given source functions and user data.  If
1268  * multiple sources exist with the same source function and user data,
1269  * the first one found will be returned.
1270  * 
1271  * Return value: the source, if one was found, otherwise %NULL
1272  **/
1273 GSource *
1274 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1275                                                GSourceFuncs *funcs,
1276                                                gpointer      user_data)
1277 {
1278   GSource *source;
1279   
1280   g_return_val_if_fail (funcs != NULL, FALSE);
1281
1282   if (context == NULL)
1283     context = g_main_context_default ();
1284   
1285   LOCK_CONTEXT (context);
1286
1287   source = context->source_list;
1288   while (source)
1289     {
1290       if (!SOURCE_DESTROYED (source) &&
1291           source->source_funcs == funcs &&
1292           source->callback_data == user_data)
1293         break;
1294       source = source->next;
1295     }
1296
1297   UNLOCK_CONTEXT (context);
1298
1299   return source;
1300 }
1301
1302 /**
1303  * g_main_context_find_source_by_user_data:
1304  * @context: a #GMainContext
1305  * @user_data: the user_data for the callback.
1306  * 
1307  * Finds a source with the given user data for the callback.  If
1308  * multiple sources exist with the same user data, the first
1309  * one found will be returned.
1310  * 
1311  * Return value: the source, if one was found, otherwise %NULL
1312  **/
1313 GSource *
1314 g_main_context_find_source_by_user_data (GMainContext *context,
1315                                          gpointer      user_data)
1316 {
1317   GSource *source;
1318   
1319   if (context == NULL)
1320     context = g_main_context_default ();
1321   
1322   LOCK_CONTEXT (context);
1323
1324   source = context->source_list;
1325   while (source)
1326     {
1327       if (!SOURCE_DESTROYED (source) &&
1328           source->callback_data == user_data)
1329         break;
1330       source = source->next;
1331     }
1332
1333   UNLOCK_CONTEXT (context);
1334
1335   return source;
1336 }
1337
1338 /**
1339  * g_source_remove:
1340  * @tag: the id of the source to remove.
1341  * 
1342  * Removes the source with the given id from the default main
1343  * context. The id of a #GSource is given by g_source_get_id(),
1344  * or will be returned by the functions g_source_attach(),
1345  * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1346  * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1347  *
1348  * See also g_source_destroy().
1349  *
1350  * Return value: %TRUE if the source was found and removed.
1351  **/
1352 gboolean
1353 g_source_remove (guint tag)
1354 {
1355   GSource *source;
1356   
1357   g_return_val_if_fail (tag > 0, FALSE);
1358
1359   source = g_main_context_find_source_by_id (NULL, tag);
1360   if (source)
1361     g_source_destroy (source);
1362
1363   return source != NULL;
1364 }
1365
1366 /**
1367  * g_source_remove_by_user_data:
1368  * @user_data: the user_data for the callback.
1369  * 
1370  * Removes a source from the default main loop context given the user
1371  * data for the callback. If multiple sources exist with the same user
1372  * data, only one will be destroyed.
1373  * 
1374  * Return value: %TRUE if a source was found and removed. 
1375  **/
1376 gboolean
1377 g_source_remove_by_user_data (gpointer user_data)
1378 {
1379   GSource *source;
1380   
1381   source = g_main_context_find_source_by_user_data (NULL, user_data);
1382   if (source)
1383     {
1384       g_source_destroy (source);
1385       return TRUE;
1386     }
1387   else
1388     return FALSE;
1389 }
1390
1391 /**
1392  * g_source_remove_by_funcs_user_data:
1393  * @funcs: The @source_funcs passed to g_source_new()
1394  * @user_data: the user data for the callback
1395  * 
1396  * Removes a source from the default main loop context given the
1397  * source functions and user data. If multiple sources exist with the
1398  * same source functions and user data, only one will be destroyed.
1399  * 
1400  * Return value: %TRUE if a source was found and removed. 
1401  **/
1402 gboolean
1403 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1404                                     gpointer      user_data)
1405 {
1406   GSource *source;
1407
1408   g_return_val_if_fail (funcs != NULL, FALSE);
1409
1410   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1411   if (source)
1412     {
1413       g_source_destroy (source);
1414       return TRUE;
1415     }
1416   else
1417     return FALSE;
1418 }
1419
1420 /**
1421  * g_get_current_time:
1422  * @result: #GTimeVal structure in which to store current time.
1423  * 
1424  * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1425  **/
1426 void
1427 g_get_current_time (GTimeVal *result)
1428 {
1429 #ifndef G_OS_WIN32
1430   struct timeval r;
1431
1432   g_return_if_fail (result != NULL);
1433
1434   /*this is required on alpha, there the timeval structs are int's
1435     not longs and a cast only would fail horribly*/
1436   gettimeofday (&r, NULL);
1437   result->tv_sec = r.tv_sec;
1438   result->tv_usec = r.tv_usec;
1439 #else
1440   /* Avoid calling time() except for the first time.
1441    * GetTickCount() should be pretty fast and low-level?
1442    * I could also use ftime() but it seems unnecessarily overheady.
1443    */
1444   static DWORD start_tick = 0;
1445   static time_t start_time;
1446   DWORD tick;
1447
1448   g_return_if_fail (result != NULL);
1449  
1450   if (start_tick == 0)
1451     {
1452       start_tick = GetTickCount ();
1453       time (&start_time);
1454     }
1455
1456   tick = GetTickCount ();
1457
1458   result->tv_sec = (tick - start_tick) / 1000 + start_time;
1459   result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1460 #endif
1461 }
1462
1463 /* Running the main loop */
1464
1465 /* HOLDS: context's lock */
1466 static void
1467 g_main_dispatch (GMainContext *context)
1468 {
1469   gint i;
1470
1471   for (i = 0; i < context->pending_dispatches->len; i++)
1472     {
1473       GSource *source = context->pending_dispatches->pdata[i];
1474
1475       context->pending_dispatches->pdata[i] = NULL;
1476       g_assert (source);
1477
1478       source->flags &= ~G_SOURCE_READY;
1479
1480       if (!SOURCE_DESTROYED (source))
1481         {
1482           gboolean was_in_call;
1483           gpointer user_data = NULL;
1484           GSourceFunc callback = NULL;
1485           GSourceCallbackFuncs *cb_funcs;
1486           gpointer cb_data;
1487           gboolean need_destroy;
1488
1489           gboolean (*dispatch) (GSource *,
1490                                 GSourceFunc,
1491                                 gpointer);
1492
1493           dispatch = source->source_funcs->dispatch;
1494           cb_funcs = source->callback_funcs;
1495           cb_data = source->callback_data;
1496
1497           if (cb_funcs)
1498             cb_funcs->ref (cb_data);
1499           
1500           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1501           source->flags |= G_HOOK_FLAG_IN_CALL;
1502
1503           UNLOCK_CONTEXT (context);
1504
1505           if (cb_funcs)
1506             cb_funcs->get (cb_data, &callback, &user_data);
1507
1508           need_destroy = ! dispatch (source,
1509                                      callback,
1510                                      user_data);
1511           LOCK_CONTEXT (context);
1512
1513           if (cb_funcs)
1514             cb_funcs->unref (cb_data);
1515
1516          if (!was_in_call)
1517             source->flags &= ~G_HOOK_FLAG_IN_CALL;
1518
1519           /* Note: this depends on the fact that we can't switch
1520            * sources from one main context to another
1521            */
1522           if (need_destroy && !SOURCE_DESTROYED (source))
1523             {
1524               g_assert (source->context == context);
1525               g_source_destroy_internal (source, context, TRUE);
1526             }
1527         }
1528       
1529       SOURCE_UNREF (source, context);
1530     }
1531
1532   g_ptr_array_set_size (context->pending_dispatches, 0);
1533 }
1534
1535 /* Holds context's lock */
1536 static inline GSource *
1537 next_valid_source (GMainContext *context,
1538                    GSource      *source)
1539 {
1540   GSource *new_source = source ? source->next : context->source_list;
1541
1542   while (new_source)
1543     {
1544       if (!SOURCE_DESTROYED (new_source))
1545         {
1546           new_source->ref_count++;
1547           break;
1548         }
1549       
1550       new_source = new_source->next;
1551     }
1552
1553   if (source)
1554     SOURCE_UNREF (source, context);
1555           
1556   return new_source;
1557 }
1558
1559
1560 /**
1561  * g_main_context_prepare:
1562  * @context: a #GMainContext
1563  * @priority: location to store priority of highest priority
1564  *            source already ready.
1565  * 
1566  * Prepares to poll sources within a main loop. The resulting information
1567  * for polling is determined by calling g_main_context_query ().
1568  * 
1569  * Return value: %TRUE if some source is ready to be dispatched
1570  *               prior to polling.
1571  **/
1572 gboolean
1573 g_main_context_prepare (GMainContext *context,
1574                         gint         *priority)
1575 {
1576   gint n_ready = 0;
1577   gint current_priority = G_MAXINT;
1578   GSource *source;
1579
1580   if (context == NULL)
1581     context = g_main_context_default ();
1582   
1583   LOCK_CONTEXT (context);
1584
1585   context->time_is_current = FALSE;
1586
1587   if (context->in_check_or_prepare)
1588     {
1589       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1590                  "prepare() member.");
1591       return FALSE;
1592     }
1593
1594 #ifdef G_THREADS_ENABLED
1595   if (context->poll_waiting)
1596     {
1597       g_warning("g_main_context_prepare(): main loop already active in another thread");
1598       UNLOCK_CONTEXT (context);
1599       return FALSE;
1600     }
1601   
1602   context->poll_waiting = TRUE;
1603 #endif G_THREADS_ENABLED  
1604
1605 #if 0
1606   /* If recursing, finish up current dispatch, before starting over */
1607   if (context->pending_dispatches)
1608     {
1609       if (dispatch)
1610         g_main_dispatch (context, &current_time);
1611       
1612       UNLOCK_CONTEXT (context);
1613       return TRUE;
1614     }
1615 #endif
1616
1617   /* If recursing, clear list of pending dispatches */
1618   g_ptr_array_set_size (context->pending_dispatches, 0);
1619   
1620   /* Prepare all sources */
1621
1622   context->timeout = -1;
1623   
1624   source = next_valid_source (context, NULL);
1625   while (source)
1626     {
1627       gint source_timeout = -1;
1628
1629       if ((n_ready > 0) && (source->priority > current_priority))
1630         {
1631           SOURCE_UNREF (source, context);
1632           break;
1633         }
1634       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1635         goto next;
1636
1637       if (!(source->flags & G_SOURCE_READY))
1638         {
1639           gboolean result;
1640           gboolean (*prepare)  (GSource  *source, 
1641                                 gint     *timeout);
1642
1643           prepare = source->source_funcs->prepare;
1644           context->in_check_or_prepare++;
1645           UNLOCK_CONTEXT (context);
1646
1647           result = (*prepare) (source, &source_timeout);
1648
1649           LOCK_CONTEXT (context);
1650           context->in_check_or_prepare--;
1651
1652           if (result)
1653             source->flags |= G_SOURCE_READY;
1654         }
1655
1656       if (source->flags & G_SOURCE_READY)
1657         {
1658           n_ready++;
1659           current_priority = source->priority;
1660           context->timeout = 0;
1661         }
1662       
1663       if (source_timeout >= 0)
1664         {
1665           if (context->timeout < 0)
1666             context->timeout = source_timeout;
1667           else
1668             context->timeout = MIN (context->timeout, source_timeout);
1669         }
1670
1671     next:
1672       source = next_valid_source (context, source);
1673     }
1674
1675   UNLOCK_CONTEXT (context);
1676   
1677   if (priority)
1678     *priority = current_priority;
1679   
1680   return (n_ready > 0);
1681 }
1682
1683 /**
1684  * g_main_context_query:
1685  * @context: a #GMainContext
1686  * @max_priority: maximum priority source to check
1687  * @timeout: location to store timeout to be used in polling
1688  * @fds: location to store #GPollFD records that need to be polled.
1689  * @n_fds: length of @fds.
1690  * 
1691  * Determines information necessary to poll this main loop.
1692  * 
1693  * Return value: 
1694  **/
1695 gint
1696 g_main_context_query (GMainContext *context,
1697                       gint          max_priority,
1698                       gint         *timeout,
1699                       GPollFD      *fds,
1700                       gint          n_fds)
1701 {
1702   gint n_poll;
1703   GPollRec *pollrec;
1704   
1705   LOCK_CONTEXT (context);
1706
1707   pollrec = context->poll_records;
1708   n_poll = 0;
1709   while (pollrec && max_priority >= pollrec->priority)
1710     {
1711       if (pollrec->fd->events)
1712         {
1713           if (n_poll < n_fds)
1714             {
1715               fds[n_poll].fd = pollrec->fd->fd;
1716               /* In direct contradiction to the Unix98 spec, IRIX runs into
1717                * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1718                * flags in the events field of the pollfd while it should
1719                * just ignoring them. So we mask them out here.
1720                */
1721               fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1722               fds[n_poll].revents = 0;
1723             }
1724           n_poll++;
1725         }
1726       
1727       pollrec = pollrec->next;
1728     }
1729
1730   context->poll_changed = FALSE;
1731
1732   if (timeout)
1733     {
1734       *timeout = context->timeout;
1735       if (timeout != 0)
1736         context->time_is_current = FALSE;
1737     }
1738   
1739   UNLOCK_CONTEXT (context);
1740
1741   return n_poll;
1742 }
1743
1744 /**
1745  * g_main_context_check:
1746  * @context: a #GMainContext
1747  * @max_priority: the maximum numerical priority of sources to check
1748  * @fds: array of #GPollFD's that was passed to the last call to
1749  *       g_main_context_query()
1750  * @n_fds: return value of g_main_context_query()
1751  * 
1752  * Pass the results of polling back to the main loop.
1753  * 
1754  * Return value: %TRUE if some sources are ready to be dispatched.
1755  **/
1756 gboolean
1757 g_main_context_check (GMainContext *context,
1758                       gint          max_priority,
1759                       GPollFD      *fds,
1760                       gint          n_fds)
1761 {
1762   GSource *source;
1763   GPollRec *pollrec;
1764   gint n_ready = 0;
1765   gint i;
1766   
1767   LOCK_CONTEXT (context);
1768
1769   if (context->in_check_or_prepare)
1770     {
1771       g_warning ("g_main_context_check() called recursively from within a source's check() or "
1772                  "prepare() member.");
1773       return FALSE;
1774     }
1775   
1776 #ifdef G_THREADS_ENABLED
1777   if (!context->poll_waiting)
1778     {
1779 #ifndef G_OS_WIN32
1780       gchar c;
1781       read (context->wake_up_pipe[0], &c, 1);
1782 #endif
1783     }
1784   else
1785     context->poll_waiting = FALSE;
1786 #endif /* G_THREADS_ENABLED */
1787
1788   /* If the set of poll file descriptors changed, bail out
1789    * and let the main loop rerun
1790    */
1791   if (context->poll_changed)
1792     return 0;
1793
1794   pollrec = context->poll_records;
1795   i = 0;
1796   while (i < n_fds)
1797     {
1798       if (pollrec->fd->events)
1799         {
1800           pollrec->fd->revents = fds[i].revents;
1801           i++;
1802         }
1803       pollrec = pollrec->next;
1804     }
1805
1806   source = next_valid_source (context, NULL);
1807   while (source)
1808     {
1809       if ((n_ready > 0) && (source->priority > max_priority))
1810         {
1811           SOURCE_UNREF (source, context);
1812           break;
1813         }
1814       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1815         goto next;
1816
1817       if (!(source->flags & G_SOURCE_READY))
1818         {
1819           gboolean result;
1820           gboolean (*check) (GSource  *source);
1821
1822           check = source->source_funcs->check;
1823           
1824           context->in_check_or_prepare++;
1825           UNLOCK_CONTEXT (context);
1826           
1827           result = (*check) (source);
1828           
1829           LOCK_CONTEXT (context);
1830           context->in_check_or_prepare--;
1831           
1832           if (result)
1833             source->flags |= G_SOURCE_READY;
1834         }
1835
1836       if (source->flags & G_SOURCE_READY)
1837         {
1838           source->ref_count++;
1839           g_ptr_array_add (context->pending_dispatches, source);
1840
1841           n_ready++;
1842         }
1843
1844     next:
1845       source = next_valid_source (context, source);
1846     }
1847
1848   UNLOCK_CONTEXT (context);
1849
1850   return n_ready > 0;
1851 }
1852
1853 /**
1854  * g_main_context_dispatch:
1855  * @context: a #GMainContext
1856  * 
1857  * Dispatch all pending sources()
1858  **/
1859 void
1860 g_main_context_dispatch (GMainContext *context)
1861 {
1862   LOCK_CONTEXT (context);
1863
1864   if (context->pending_dispatches->len > 0)
1865     {
1866       g_main_dispatch (context);
1867     }
1868
1869   UNLOCK_CONTEXT (context);
1870 }
1871
1872 static gboolean
1873 g_main_context_iterate (GMainContext *context,
1874                         gboolean      block,
1875                         gboolean      dispatch)
1876 {
1877   gint max_priority;
1878   gint timeout;
1879   gboolean some_ready;
1880   gint nfds, new_nfds;
1881   GPollFD *fds;
1882   
1883   some_ready = g_main_context_prepare (context, &max_priority);
1884
1885   do
1886     {
1887       LOCK_CONTEXT (context);
1888
1889       if (context->cached_poll_array)
1890         {
1891           nfds = context->cached_poll_array_size;
1892           fds = context->cached_poll_array;
1893           context->cached_poll_array = NULL;
1894         }
1895       else
1896         {
1897           nfds = context->cached_poll_array_size = context->n_poll_records;
1898           fds = g_new (GPollFD, nfds);
1899         }
1900
1901       UNLOCK_CONTEXT (context);
1902   
1903       new_nfds = g_main_context_query (context, max_priority,
1904                                        &timeout, fds, nfds);
1905     }
1906   while (new_nfds > nfds);
1907
1908   if (!block)
1909     timeout = 0;
1910   
1911   g_main_context_poll (context, timeout, max_priority,
1912                        fds, new_nfds);
1913
1914   g_main_context_check (context,
1915                         max_priority,
1916                         fds, new_nfds);
1917
1918   LOCK_CONTEXT (context);
1919
1920   g_assert (!context->cached_poll_array);
1921   
1922   context->cached_poll_array = fds;
1923   context->cached_poll_array_size = nfds;
1924
1925   UNLOCK_CONTEXT (context);
1926   
1927   if (dispatch)
1928     g_main_context_dispatch (context);
1929
1930   return some_ready;
1931 }
1932
1933 /**
1934  * g_main_context_pending:
1935  * @context: a #GMainContext (if %NULL, the default context will be used)
1936  *
1937  * Check if any sources have pending events for the given context.
1938  * 
1939  * Return value: %TRUE if events are pending.
1940  **/
1941 gboolean 
1942 g_main_context_pending (GMainContext *context)
1943 {
1944   if (!context)
1945     context = g_main_context_default();
1946   
1947   return g_main_context_iterate (context, FALSE, FALSE);
1948 }
1949
1950 /**
1951  * g_main_context_iteration:
1952  * @context: a #GMainContext (if %NULL, the default context will be used) 
1953  * @may_block: whether the call may block.
1954  * 
1955  * Run a single iteration for the given main loop. This involves
1956  * checking to see if any event sources are ready to be processed,
1957  * then if no events sources are ready and @may_block is %TRUE, waiting
1958  * for a source to become ready, then dispatching the highest priority
1959  * events sources that are ready. Note that even when @may_block is %TRUE,
1960  * it is still possible for g_main_context_iteration() to return
1961  * %FALSE, since the the wait may be interrupted for other
1962  * reasons than an event source becoming ready.
1963  * 
1964  * Return value: %TRUE if events were dispatched.
1965  **/
1966 gboolean
1967 g_main_context_iteration (GMainContext *context, gboolean may_block)
1968 {
1969   if (!context)
1970     context = g_main_context_default();
1971   
1972   return g_main_context_iterate (context, may_block, TRUE);
1973 }
1974
1975 /**
1976  * g_main_loop_new:
1977  * @context: a #GMainContext  (if %NULL, the default context will be used).
1978  * @is_running: set to TRUE to indicate that the loop is running. This
1979  * is not very important since calling g_main_run() will set this to
1980  * TRUE anyway.
1981  * 
1982  * Create a new #GMainLoop structure
1983  * 
1984  * Return value: 
1985  **/
1986 GMainLoop *
1987 g_main_loop_new (GMainContext *context,
1988                  gboolean      is_running)
1989 {
1990   GMainLoop *loop;
1991   
1992   if (!context)
1993     context = g_main_context_default();
1994   
1995   loop = g_new0 (GMainLoop, 1);
1996   loop->context = context;
1997   loop->is_running = is_running != FALSE;
1998
1999 #ifdef G_THREADS_ENABLED
2000   if (g_thread_supported ())
2001     loop->mutex = g_mutex_new ();
2002   else
2003     loop->mutex = NULL;
2004   loop->sem_cond = NULL;
2005 #endif G_THREADS_ENABLED  
2006
2007   return loop;
2008 }
2009
2010 /**
2011  * g_main_loop_run:
2012  * @loop: a #GMainLoop
2013  * 
2014  * Run a main loop until g_main_quit() is called on the loop.
2015  * If this is called for the thread of the loop's #GMainContext,
2016  * it will process events from the loop, otherwise it will
2017  * simply wait.
2018  **/
2019 void 
2020 g_main_loop_run (GMainLoop *loop)
2021 {
2022   g_return_if_fail (loop != NULL);
2023
2024 #ifdef G_THREADS_ENABLED
2025   if (loop->context->thread != g_thread_self ())
2026     {
2027       LOCK_LOOP (loop);
2028
2029       if (!g_thread_supported ())
2030         {
2031           g_warning ("g_main_loop_run() was called from second thread but"
2032                      "g_thread_init() was never called.");
2033         }
2034       else
2035         {
2036           if (!loop->sem_cond)
2037             loop->sem_cond = g_cond_new ();
2038           
2039           if (!loop->is_running)
2040             loop->is_running = TRUE;
2041           
2042           while (loop->is_running)
2043             g_cond_wait (loop->sem_cond, loop->mutex);
2044         }
2045         
2046       UNLOCK_LOOP (loop);
2047     }
2048   else
2049 #endif /* G_THREADS_ENABLED */    
2050     {
2051       LOCK_CONTEXT (loop->context);
2052       if (loop->context->in_check_or_prepare)
2053         {
2054           g_warning ("g_main_run(): called recursively from within a source's check() or "
2055                      "prepare() member, iteration not possible.");
2056           return;
2057         }
2058       UNLOCK_CONTEXT (loop->context);
2059       
2060       LOCK_LOOP (loop);
2061
2062       loop->is_running = TRUE;
2063       while (loop->is_running)
2064         {
2065           UNLOCK_LOOP (loop);
2066           g_main_context_iterate (loop->context, TRUE, TRUE);
2067           LOCK_LOOP (loop);
2068         }
2069       UNLOCK_LOOP (loop);
2070     }
2071 }
2072
2073 /**
2074  * g_main_loop_quit:
2075  * @loop: a #GMainLoop
2076  * 
2077  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2078  * for the loop will return.
2079  **/
2080 void 
2081 g_main_loop_quit (GMainLoop *loop)
2082 {
2083   g_return_if_fail (loop != NULL);
2084
2085   LOCK_LOOP (loop);
2086   loop->is_running = FALSE;
2087
2088   if (loop->sem_cond)
2089     g_cond_broadcast (loop->sem_cond);
2090   
2091   UNLOCK_LOOP (loop);
2092
2093   LOCK_CONTEXT (loop->context);
2094   
2095   g_main_context_wakeup (loop->context);
2096   UNLOCK_CONTEXT (loop->context);
2097 }
2098
2099 /**
2100  * g_main_loop_destroy:
2101  * @loop: a #GMainLoop
2102  * 
2103  * Destroy a #GMainLoop object and free all associated memory.
2104  * The loop must not currently be running via g_main_run().
2105  **/
2106 void 
2107 g_main_loop_destroy (GMainLoop *loop)
2108 {
2109   g_return_if_fail (loop != NULL);
2110   g_return_if_fail (!loop->is_running);
2111
2112 #ifdef G_THREADS_ENABLED
2113   g_mutex_free (loop->mutex);
2114   if (loop->sem_cond)
2115     g_cond_free (loop->sem_cond);
2116 #endif /* G_THREADS_ENABLED */  
2117
2118   g_free (loop);
2119 }
2120
2121 /**
2122  * g_main_loop_is_running:
2123  * @loop: a #GMainLoop.
2124  * 
2125  * Check to see if the main loop is currently being run via g_main_run()
2126  * 
2127  * Return value: %TRUE if the mainloop is currently being run.
2128  **/
2129 gboolean
2130 g_main_loop_is_running (GMainLoop *loop)
2131 {
2132   gboolean result;
2133   
2134   g_return_val_if_fail (loop != NULL, FALSE);
2135
2136   LOCK_LOOP (loop);
2137   result = loop->is_running;
2138   UNLOCK_LOOP (loop);
2139
2140   return result;
2141 }
2142
2143 /* HOLDS: context's lock */
2144 static void
2145 g_main_context_poll (GMainContext *context,
2146                      gint          timeout,
2147                      gint          priority,
2148                      GPollFD      *fds,
2149                      gint          n_fds)
2150 {
2151 #ifdef  G_MAIN_POLL_DEBUG
2152   GTimer *poll_timer;
2153   GPollRec *pollrec;
2154   gint i;
2155 #endif
2156
2157   GPollFunc poll_func;
2158
2159   if (n_fds || timeout != 0)
2160     {
2161 #ifdef  G_MAIN_POLL_DEBUG
2162       g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2163       poll_timer = g_timer_new ();
2164 #endif
2165
2166       LOCK_CONTEXT (context);
2167
2168       poll_func = context->poll_func;
2169       
2170       UNLOCK_CONTEXT (context);
2171       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2172         g_warning ("poll(2) failed due to: %s.",
2173                    g_strerror (errno));
2174       
2175 #ifdef  G_MAIN_POLL_DEBUG
2176       LOCK_CONTEXT (context);
2177
2178       g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2179                n_fds,
2180                timeout,
2181                g_timer_elapsed (poll_timer, NULL));
2182       g_timer_destroy (poll_timer);
2183       pollrec = context->poll_records;
2184       i = 0;
2185       while (i < n_fds)
2186         {
2187           if (pollrec->fd->events)
2188             {
2189               if (fds[i].revents)
2190                 {
2191                   g_print (" [%d:", fds[i].fd);
2192                   if (fds[i].revents & G_IO_IN)
2193                     g_print ("i");
2194                   if (fds[i].revents & G_IO_OUT)
2195                     g_print ("o");
2196                   if (fds[i].revents & G_IO_PRI)
2197                     g_print ("p");
2198                   if (fds[i].revents & G_IO_ERR)
2199                     g_print ("e");
2200                   if (fds[i].revents & G_IO_HUP)
2201                     g_print ("h");
2202                   if (fds[i].revents & G_IO_NVAL)
2203                     g_print ("n");
2204                   g_print ("]");
2205                 }
2206               i++;
2207             }
2208           pollrec = pollrec->next;
2209         }
2210       g_print ("\n");
2211       
2212       UNLOCK_CONTEXT (context);
2213 #endif
2214     } /* if (n_fds || timeout != 0) */
2215 }
2216
2217 /**
2218  * g_main_context_add_poll:
2219  * @context: a #GMainContext (or %NULL for the default context)
2220  * @fd: a #GPollFD structure holding information about a file
2221  *      descriptor to watch.
2222  * @priority: the priority for this file descriptor which should be
2223  *      the same as the priority used for g_source_attach() to ensure that the
2224  *      file descriptor is polled whenever the results may be needed.
2225  * 
2226  * Add a file descriptor to the set of file descriptors polled * for
2227  * this context. This will very seldom be used directly. Instead
2228  * a typical event source will use g_source_add_poll() instead.
2229  **/
2230 void
2231 g_main_context_add_poll (GMainContext *context,
2232                          GPollFD      *fd,
2233                          gint          priority)
2234 {
2235   if (!context)
2236     context = g_main_context_default ();
2237   
2238   LOCK_CONTEXT (context);
2239   g_main_context_add_poll_unlocked (context, priority, fd);
2240   UNLOCK_CONTEXT (context);
2241 }
2242
2243 /* HOLDS: main_loop_lock */
2244 static void 
2245 g_main_context_add_poll_unlocked (GMainContext *context,
2246                                   gint          priority,
2247                                   GPollFD      *fd)
2248 {
2249   GPollRec *lastrec, *pollrec, *newrec;
2250
2251   if (!context->poll_chunk)
2252     context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2253
2254   if (context->poll_free_list)
2255     {
2256       newrec = context->poll_free_list;
2257       context->poll_free_list = newrec->next;
2258     }
2259   else
2260     newrec = g_chunk_new (GPollRec, context->poll_chunk);
2261
2262   /* This file descriptor may be checked before we ever poll */
2263   fd->revents = 0;
2264   newrec->fd = fd;
2265   newrec->priority = priority;
2266
2267   lastrec = NULL;
2268   pollrec = context->poll_records;
2269   while (pollrec && priority >= pollrec->priority)
2270     {
2271       lastrec = pollrec;
2272       pollrec = pollrec->next;
2273     }
2274   
2275   if (lastrec)
2276     lastrec->next = newrec;
2277   else
2278     context->poll_records = newrec;
2279
2280   newrec->next = pollrec;
2281
2282   context->n_poll_records++;
2283   if (context->cached_poll_array &&
2284       context->cached_poll_array_size < context->n_poll_records)
2285     {
2286       g_free (context->cached_poll_array);
2287       context->cached_poll_array = NULL;
2288     }
2289
2290 #ifdef G_THREADS_ENABLED
2291   context->poll_changed = TRUE;
2292
2293   /* Now wake up the main loop if it is waiting in the poll() */
2294   g_main_context_wakeup (context);
2295 #endif
2296 }
2297
2298 /**
2299  * g_main_context_remove_poll:
2300  * @context:a #GMainContext 
2301  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2302  * 
2303  * Remove file descriptor from the set of file descriptors to be
2304  * polled for a particular context.
2305  **/
2306 void
2307 g_main_context_remove_poll (GMainContext *context,
2308                             GPollFD      *fd)
2309 {
2310   if (!context)
2311     context = g_main_context_default ();
2312   
2313   LOCK_CONTEXT (context);
2314
2315   g_main_context_remove_poll_unlocked (context, fd);
2316   
2317   UNLOCK_CONTEXT (context);
2318 }
2319
2320 static void
2321 g_main_context_remove_poll_unlocked (GMainContext *context,
2322                                      GPollFD      *fd)
2323 {
2324   GPollRec *pollrec, *lastrec;
2325
2326   lastrec = NULL;
2327   pollrec = context->poll_records;
2328
2329   while (pollrec)
2330     {
2331       if (pollrec->fd == fd)
2332         {
2333           if (lastrec != NULL)
2334             lastrec->next = pollrec->next;
2335           else
2336             context->poll_records = pollrec->next;
2337
2338 #ifdef ENABLE_GC_FRIENDLY
2339           pollrec->fd = NULL;  
2340 #endif /* ENABLE_GC_FRIENDLY */
2341
2342           pollrec->next = context->poll_free_list;
2343           context->poll_free_list = pollrec;
2344
2345           context->n_poll_records--;
2346           break;
2347         }
2348       lastrec = pollrec;
2349       pollrec = pollrec->next;
2350     }
2351
2352 #ifdef G_THREADS_ENABLED
2353   context->poll_changed = TRUE;
2354   
2355   /* Now wake up the main loop if it is waiting in the poll() */
2356   g_main_context_wakeup (context);
2357 #endif
2358 }
2359
2360 /**
2361  * g_source_get_current_time:
2362  * @source:  a #GSource
2363  * @timeval: #GTimeVal structure in which to store current time.
2364  * 
2365  * Gets the "current time" to be used when checking 
2366  * this source. The advantage of calling this function over
2367  * calling g_get_current_time() directly is that when 
2368  * checking multiple sources, GLib can cache a single value
2369  * instead of having to repeatedly get the system time.
2370  **/
2371 void
2372 g_source_get_current_time (GSource  *source,
2373                            GTimeVal *timeval)
2374 {
2375   GMainContext *context;
2376   
2377   g_return_if_fail (source->context != NULL);
2378  
2379   context = source->context;
2380
2381   LOCK_CONTEXT (context);
2382
2383   if (!context->time_is_current)
2384     {
2385       g_get_current_time (&context->current_time);
2386       context->time_is_current = TRUE;
2387     }
2388   
2389   *timeval = context->current_time;
2390   
2391   UNLOCK_CONTEXT (context);
2392 }
2393
2394 /**
2395  * g_main_context_set_poll_func:
2396  * @context: a #GMainContext
2397  * @func: the function to call to poll all file descriptors
2398  * 
2399  * Sets the function to use to handle polling of file descriptors. It
2400  * will be used instead of the poll() system call (or GLib's
2401  * replacement function, which is used where poll() isn't available).
2402  *
2403  * This function could possibly be used to integrate the GLib event
2404  * loop with an external event loop.
2405  **/
2406 void
2407 g_main_context_set_poll_func (GMainContext *context,
2408                               GPollFunc     func)
2409 {
2410   if (!context)
2411     context = g_main_context_default ();
2412   
2413   LOCK_CONTEXT (context);
2414   
2415   if (func)
2416     context->poll_func = func;
2417   else
2418     {
2419 #ifdef HAVE_POLL
2420       context->poll_func = (GPollFunc) poll;
2421 #else
2422       context->poll_func = (GPollFunc) g_poll;
2423 #endif
2424     }
2425
2426   UNLOCK_CONTEXT (context);
2427 }
2428
2429 #ifdef G_OS_WIN32
2430
2431 /**
2432  * g_main_context_get_poll_func:
2433  * @context: a #GMainContext
2434  * 
2435  * Gets the poll function set by g_main_context_set_poll_func()
2436  * 
2437  * Return value: the poll function
2438  **/
2439 GPollFunc
2440 g_main_context_get_poll_func (GMainContext *context)
2441 {
2442   GPollFunc *result;
2443   
2444   if (!context)
2445     context = g_main_context_default ();
2446   
2447   LOCK_CONTEXT (context);
2448   result = context->poll_func;
2449   UNLOCK_CONTEXT (context);
2450 }
2451
2452 #endif
2453
2454 /* HOLDS: context's lock */
2455 /* Wake the main loop up from a poll() */
2456 static void
2457 g_main_context_wakeup (GMainContext *context)
2458 {
2459 #ifdef G_THREADS_ENABLED
2460   if (g_thread_supported() && context->poll_waiting)
2461     {
2462       context->poll_waiting = FALSE;
2463 #ifndef G_OS_WIN32
2464       write (context->wake_up_pipe[1], "A", 1);
2465 #else
2466       ReleaseSemaphore (context->context->wake_up_semaphore, 1, NULL);
2467 #endif
2468     }
2469 #endif
2470 }
2471
2472 /* Timeouts */
2473
2474 static void
2475 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2476                           GTimeVal       *current_time)
2477 {
2478   guint seconds = timeout_source->interval / 1000;
2479   guint msecs = timeout_source->interval - seconds * 1000;
2480
2481   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2482   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2483   if (timeout_source->expiration.tv_usec >= 1000000)
2484     {
2485       timeout_source->expiration.tv_usec -= 1000000;
2486       timeout_source->expiration.tv_sec++;
2487     }
2488 }
2489
2490 static gboolean
2491 g_timeout_prepare  (GSource  *source,
2492                     gint     *timeout)
2493 {
2494   glong msec;
2495   GTimeVal current_time;
2496   
2497   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2498
2499   g_source_get_current_time (source, &current_time);
2500   
2501   msec = ((timeout_source->expiration.tv_sec  - current_time.tv_sec) * 1000 +
2502           (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2503
2504   if (msec < 0)
2505     msec = 0;
2506   else if (msec > timeout_source->interval)
2507     {
2508       /* The system time has been set backwards, so we
2509        * reset the expiration time to now + timeout_source->interval;
2510        * this at least avoids hanging for long periods of time.
2511        */
2512       g_timeout_set_expiration (timeout_source, &current_time);
2513       msec = timeout_source->interval;
2514     }
2515   
2516   *timeout = msec;
2517   
2518   return msec == 0;
2519 }
2520
2521 static gboolean 
2522 g_timeout_check (GSource  *source)
2523 {
2524   GTimeVal current_time;
2525   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2526
2527   g_source_get_current_time (source, &current_time);
2528   
2529   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2530           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2531            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2532 }
2533
2534 static gboolean
2535 g_timeout_dispatch (GSource    *source,
2536                     GSourceFunc callback,
2537                     gpointer    user_data)
2538 {
2539   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2540
2541   if (!callback)
2542     {
2543       g_warning ("Timeout source dispatched without callback\n"
2544                  "You must call g_source_set_callback().");
2545       return FALSE;
2546     }
2547  
2548   if (callback (user_data))
2549     {
2550       GTimeVal current_time;
2551
2552       g_source_get_current_time (source, &current_time);
2553       g_timeout_set_expiration (timeout_source, &current_time);
2554
2555       return TRUE;
2556     }
2557   else
2558     return FALSE;
2559 }
2560
2561 /**
2562  * g_timeout_source_new:
2563  * @interval: the timeout interval in milliseconds.
2564  * 
2565  * Create a new timeout source.
2566  *
2567  * The source will not initially be associated with any #GMainContext
2568  * and must be added to one with g_source_attach() before it will be
2569  * executed.
2570  * 
2571  * Return value: the newly create timeout source
2572  **/
2573 GSource *
2574 g_timeout_source_new (guint interval)
2575 {
2576   GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2577   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2578   GTimeVal current_time;
2579
2580   timeout_source->interval = interval;
2581
2582   g_get_current_time (&current_time);
2583   g_timeout_set_expiration (timeout_source, &current_time);
2584   
2585   return source;
2586 }
2587
2588 /**
2589  * g_timeout_add_full:
2590  * @priority: the priority of the idle source. Typically this will be in the
2591  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2592  * @interval: the time between calls to the function, in milliseconds
2593  *             (1/1000ths of a second.)
2594  * @function: function to call
2595  * @data:     data to pass to @function
2596  * @notify:   function to call when the idle is removed, or %NULL
2597  * 
2598  * Sets a function to be called at regular intervals, with the given
2599  * priority.  The function is called repeatedly until it returns
2600  * FALSE, at which point the timeout is automatically destroyed and
2601  * the function will not be called again.  The @notify function is
2602  * called when the timeout is destroyed.  The first call to the
2603  * function will be at the end of the first @interval.
2604  *
2605  * Note that timeout functions may be delayed, due to the processing of other
2606  * event sources. Thus they should not be relied on for precise timing.
2607  * After each call to the timeout function, the time of the next
2608  * timeout is recalculated based on the current time and the given interval
2609  * (it does not try to 'catch up' time lost in delays).
2610  * 
2611  * Return value: the id of event source.
2612  **/
2613 guint
2614 g_timeout_add_full (gint           priority,
2615                     guint          interval,
2616                     GSourceFunc    function,
2617                     gpointer       data,
2618                     GDestroyNotify notify)
2619 {
2620   GSource *source;
2621   
2622   g_return_val_if_fail (function != NULL, 0);
2623
2624   source = g_timeout_source_new (interval);
2625
2626   if (priority != G_PRIORITY_DEFAULT)
2627     g_source_set_priority (source, priority);
2628
2629   g_source_set_callback (source, function, data, notify);
2630   return g_source_attach (source, NULL);
2631 }
2632
2633 /**
2634  * g_timeout_add:
2635  * @interval: the time between calls to the function, in milliseconds
2636  *             (1/1000ths of a second.)
2637  * @function: function to call
2638  * @data:     data to pass to @function
2639  * 
2640  * Sets a function to be called at regular intervals, with the default
2641  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
2642  * until it returns FALSE, at which point the timeout is automatically
2643  * destroyed and the function will not be called again.  The @notify
2644  * function is called when the timeout is destroyed.  The first call
2645  * to the function will be at the end of the first @interval.
2646  *
2647  * Note that timeout functions may be delayed, due to the processing of other
2648  * event sources. Thus they should not be relied on for precise timing.
2649  * After each call to the timeout function, the time of the next
2650  * timeout is recalculated based on the current time and the given interval
2651  * (it does not try to 'catch up' time lost in delays).
2652  * 
2653  * Return value: the id of event source.
2654  **/
2655 guint 
2656 g_timeout_add (guint32        interval,
2657                GSourceFunc    function,
2658                gpointer       data)
2659 {
2660   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
2661                              interval, function, data, NULL);
2662 }
2663
2664 /* Idle functions */
2665
2666 static gboolean 
2667 g_idle_prepare  (GSource  *source,
2668                  gint     *timeout)
2669 {
2670   *timeout = 0;
2671
2672   return TRUE;
2673 }
2674
2675 static gboolean 
2676 g_idle_check    (GSource  *source)
2677 {
2678   return TRUE;
2679 }
2680
2681 static gboolean
2682 g_idle_dispatch (GSource    *source, 
2683                  GSourceFunc callback,
2684                  gpointer    user_data)
2685 {
2686   if (!callback)
2687     {
2688       g_warning ("Idle source dispatched without callback\n"
2689                  "You must call g_source_set_callback().");
2690       return FALSE;
2691     }
2692   
2693   return callback (user_data);
2694 }
2695
2696 /**
2697  * g_idle_source_new:
2698  * 
2699  * Create a new idle source.
2700  *
2701  * The source will not initially be associated with any #GMainContext
2702  * and must be added to one with g_source_attach() before it will be
2703  * executed.
2704  * 
2705  * Return value: the newly created idle source
2706  **/
2707 GSource *
2708 g_idle_source_new (void)
2709 {
2710   return g_source_new (&idle_funcs, sizeof (GSource));
2711 }
2712
2713 /**
2714  * g_idle_add_full:
2715  * @priority: the priority of the idle source. Typically this will be in the
2716  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2717  * @function: function to call
2718  * @data:     data to pass to @function
2719  * @notify:   function to call when the idle is removed, or %NULL
2720  * 
2721  * Adds a function to be called whenever there are no higher priority
2722  * events pending.  If the function returns FALSE it is automatically
2723  * removed from the list of event sources and will not be called again.
2724  * 
2725  * Return value: the id of the event source.
2726  **/
2727 guint 
2728 g_idle_add_full (gint           priority,
2729                  GSourceFunc    function,
2730                  gpointer       data,
2731                  GDestroyNotify notify)
2732 {
2733   GSource *source;
2734   
2735   g_return_val_if_fail (function != NULL, 0);
2736
2737   source = g_idle_source_new ();
2738
2739   if (priority != G_PRIORITY_DEFAULT)
2740     g_source_set_priority (source, priority);
2741
2742   g_source_set_callback (source, function, data, notify);
2743   return g_source_attach (source, NULL);
2744 }
2745
2746 /**
2747  * g_idle_add:
2748  * @function: function to call 
2749  * @data: data to pass to @function.
2750  * 
2751  * Adds a function to be called whenever there are no higher priority
2752  * events pending to the default main loop. The function is given the
2753  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
2754  * returns FALSE it is automatically removed from the list of event
2755  * sources and will not be called again.
2756  * 
2757  * Return value: the id of the event source.
2758  **/
2759 guint 
2760 g_idle_add (GSourceFunc    function,
2761             gpointer       data)
2762 {
2763   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2764 }
2765
2766 /**
2767  * g_idle_remove_by_data:
2768  * @data: the data for the idle source's callback.
2769  * 
2770  * Removes the idle function with the given data.
2771  * 
2772  * Return value: %TRUE if an idle source was found and removed.
2773  **/
2774 gboolean
2775 g_idle_remove_by_data (gpointer data)
2776 {
2777   return g_source_remove_by_funcs_user_data (&idle_funcs, data);
2778 }
2779