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