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