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