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