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