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