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