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