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