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