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