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