intial implementation of new API functions. Not sure if it behaves as
[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     {
1676       context->owner = self;
1677       g_assert (context->owner_count == 0);
1678     }
1679
1680   if (context->owner == self)
1681     {
1682       context->owner_count++;
1683       result = TRUE;
1684     }
1685
1686   UNLOCK_CONTEXT (context); 
1687   
1688   return result;
1689 #else /* !G_THREAD_ENABLED */
1690   return TRUE;
1691 #endif /* G_THREAD_ENABLED */
1692 }
1693
1694 /**
1695  * g_main_context_release:
1696  * @context: a #GMainContext
1697  * 
1698  * Release ownership of a context previously acquired by this thread
1699  * with g_main_context_acquire(). If the context was acquired multiple
1700  * times, the only release ownership when g_main_context_release()
1701  * is called as many times as it was acquired.
1702  **/
1703 void
1704 g_main_context_release (GMainContext *context)
1705 {
1706 #ifdef G_THREAD_ENABLED
1707   if (context == NULL)
1708     context = g_main_context_default ();
1709   
1710   LOCK_CONTEXT (context);
1711
1712   context->owner_count--;
1713   if (context->owner_count == 0)
1714     {
1715       context->owner = NULL;
1716
1717       if (context->waiters)
1718         {
1719           GMainWaiter *waiter = context->waiters->data;
1720           gboolean loop_internal_waiter =
1721             (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1722           context->waiters = g_slist_delete_link (context->waiters,
1723                                                   context->waiters);
1724           if (!loop_internal_waiter)
1725             g_mutex_lock (waiter->mutex);
1726           
1727           g_cond_signal (waiter->cond);
1728           
1729           if (!loop_internal_waiter)
1730             g_mutex_unlock (waiter->mutex);
1731         }
1732     }
1733
1734   UNLOCK_CONTEXT (context); 
1735
1736   return result;
1737 #endif /* G_THREAD_ENABLED */
1738 }
1739
1740 /**
1741  * g_main_context_wait:
1742  * @context: a #GMainContext
1743  * @cond: a condition variable
1744  * @mutex: a mutex, currently held
1745  * 
1746  * Tries to become the owner of the specified context,
1747  * as with g_main_context_acquire. But if another thread
1748  * is the owner, atomically drop @mutex and wait on
1749  * @cond until wait until that owner releases
1750  * ownership or until @cond is signaled, then
1751  * try again (once) to become the owner.
1752  * 
1753  * Return value: %TRUE if the operation succeeded, and
1754  *   this thread is now the owner of @context.
1755  **/
1756 gboolean
1757 g_main_context_wait (GMainContext *context,
1758                      GCond        *cond,
1759                      GMutex       *mutex)
1760 {
1761 #ifdef G_THREAD_ENABLED
1762   gboolean result = FALSE;
1763   GThread *self = G_THREAD_SELF;
1764   gboolean loop_internal_waiter;
1765   
1766   if (context == NULL)
1767     context = g_main_context_default ();
1768
1769   loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
1770   
1771   if (!loop_internal_waiter)
1772     LOCK_CONTEXT (context);
1773
1774   if (context->owner && context->owner != self)
1775     {
1776       GMainWaiter waiter;
1777
1778       waiter.cond = cond;
1779       waiter.mutex = mutex;
1780
1781       context->waiters = g_slist_append (context->waiters, &waiter);
1782       
1783       if (!loop_internal_waiter)
1784         UNLOCK_CONTEXT (context);
1785       g_cond_wait (cond, mutex);
1786       if (!loop_internal_waiter)      
1787         LOCK_CONTEXT (context);
1788
1789       context->waiters = g_slist_remove (context->waiters, &waiter);
1790     }
1791
1792   if (!context->owner)
1793     {
1794       context->owner = self;
1795       g_assert (context->owner_count == 0);
1796     }
1797
1798   if (context->owner == self)
1799     {
1800       context->owner_count++;
1801       result = TRUE;
1802     }
1803
1804   if (!loop_internal_waiter)
1805     UNLOCK_CONTEXT (context); 
1806   
1807   return result;
1808 #else /* !G_THREAD_ENABLED */
1809   return TRUE;
1810 #endif /* G_THREAD_ENABLED */
1811 }
1812
1813 /**
1814  * g_main_context_prepare:
1815  * @context: a #GMainContext
1816  * @priority: location to store priority of highest priority
1817  *            source already ready.
1818  * 
1819  * Prepares to poll sources within a main loop. The resulting information
1820  * for polling is determined by calling g_main_context_query ().
1821  * 
1822  * Return value: %TRUE if some source is ready to be dispatched
1823  *               prior to polling.
1824  **/
1825 gboolean
1826 g_main_context_prepare (GMainContext *context,
1827                         gint         *priority)
1828 {
1829   gint n_ready = 0;
1830   gint current_priority = G_MAXINT;
1831   GSource *source;
1832
1833   if (context == NULL)
1834     context = g_main_context_default ();
1835   
1836   LOCK_CONTEXT (context);
1837
1838   context->time_is_current = FALSE;
1839
1840   if (context->in_check_or_prepare)
1841     {
1842       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1843                  "prepare() member.");
1844       UNLOCK_CONTEXT (context);
1845       return FALSE;
1846     }
1847
1848 #ifdef G_THREADS_ENABLED
1849   if (context->poll_waiting)
1850     {
1851       g_warning("g_main_context_prepare(): main loop already active in another thread");
1852       UNLOCK_CONTEXT (context);
1853       return FALSE;
1854     }
1855   
1856   context->poll_waiting = TRUE;
1857 #endif /* G_THREADS_ENABLED */
1858
1859 #if 0
1860   /* If recursing, finish up current dispatch, before starting over */
1861   if (context->pending_dispatches)
1862     {
1863       if (dispatch)
1864         g_main_dispatch (context, &current_time);
1865       
1866       UNLOCK_CONTEXT (context);
1867       return TRUE;
1868     }
1869 #endif
1870
1871   /* If recursing, clear list of pending dispatches */
1872   g_ptr_array_set_size (context->pending_dispatches, 0);
1873   
1874   /* Prepare all sources */
1875
1876   context->timeout = -1;
1877   
1878   source = next_valid_source (context, NULL);
1879   while (source)
1880     {
1881       gint source_timeout = -1;
1882
1883       if ((n_ready > 0) && (source->priority > current_priority))
1884         {
1885           SOURCE_UNREF (source, context);
1886           break;
1887         }
1888       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1889         goto next;
1890
1891       if (!(source->flags & G_SOURCE_READY))
1892         {
1893           gboolean result;
1894           gboolean (*prepare)  (GSource  *source, 
1895                                 gint     *timeout);
1896
1897           prepare = source->source_funcs->prepare;
1898           context->in_check_or_prepare++;
1899           UNLOCK_CONTEXT (context);
1900
1901           result = (*prepare) (source, &source_timeout);
1902
1903           LOCK_CONTEXT (context);
1904           context->in_check_or_prepare--;
1905
1906           if (result)
1907             source->flags |= G_SOURCE_READY;
1908         }
1909
1910       if (source->flags & G_SOURCE_READY)
1911         {
1912           n_ready++;
1913           current_priority = source->priority;
1914           context->timeout = 0;
1915         }
1916       
1917       if (source_timeout >= 0)
1918         {
1919           if (context->timeout < 0)
1920             context->timeout = source_timeout;
1921           else
1922             context->timeout = MIN (context->timeout, source_timeout);
1923         }
1924
1925     next:
1926       source = next_valid_source (context, source);
1927     }
1928
1929   UNLOCK_CONTEXT (context);
1930   
1931   if (priority)
1932     *priority = current_priority;
1933   
1934   return (n_ready > 0);
1935 }
1936
1937 /**
1938  * g_main_context_query:
1939  * @context: a #GMainContext
1940  * @max_priority: maximum priority source to check
1941  * @timeout: location to store timeout to be used in polling
1942  * @fds: location to store #GPollFD records that need to be polled.
1943  * @n_fds: length of @fds.
1944  * 
1945  * Determines information necessary to poll this main loop.
1946  * 
1947  * Return value: 
1948  **/
1949 gint
1950 g_main_context_query (GMainContext *context,
1951                       gint          max_priority,
1952                       gint         *timeout,
1953                       GPollFD      *fds,
1954                       gint          n_fds)
1955 {
1956   gint n_poll;
1957   GPollRec *pollrec;
1958   
1959   LOCK_CONTEXT (context);
1960
1961   pollrec = context->poll_records;
1962   n_poll = 0;
1963   while (pollrec && max_priority >= pollrec->priority)
1964     {
1965       if (pollrec->fd->events)
1966         {
1967           if (n_poll < n_fds)
1968             {
1969               fds[n_poll].fd = pollrec->fd->fd;
1970               /* In direct contradiction to the Unix98 spec, IRIX runs into
1971                * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1972                * flags in the events field of the pollfd while it should
1973                * just ignoring them. So we mask them out here.
1974                */
1975               fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1976               fds[n_poll].revents = 0;
1977             }
1978           n_poll++;
1979         }
1980       
1981       pollrec = pollrec->next;
1982     }
1983
1984 #ifdef G_THREADS_ENABLED
1985   context->poll_changed = FALSE;
1986 #endif
1987   
1988   if (timeout)
1989     {
1990       *timeout = context->timeout;
1991       if (timeout != 0)
1992         context->time_is_current = FALSE;
1993     }
1994   
1995   UNLOCK_CONTEXT (context);
1996
1997   return n_poll;
1998 }
1999
2000 /**
2001  * g_main_context_check:
2002  * @context: a #GMainContext
2003  * @max_priority: the maximum numerical priority of sources to check
2004  * @fds: array of #GPollFD's that was passed to the last call to
2005  *       g_main_context_query()
2006  * @n_fds: return value of g_main_context_query()
2007  * 
2008  * Pass the results of polling back to the main loop.
2009  * 
2010  * Return value: %TRUE if some sources are ready to be dispatched.
2011  **/
2012 gboolean
2013 g_main_context_check (GMainContext *context,
2014                       gint          max_priority,
2015                       GPollFD      *fds,
2016                       gint          n_fds)
2017 {
2018   GSource *source;
2019   GPollRec *pollrec;
2020   gint n_ready = 0;
2021   gint i;
2022   
2023   LOCK_CONTEXT (context);
2024
2025   if (context->in_check_or_prepare)
2026     {
2027       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2028                  "prepare() member.");
2029       UNLOCK_CONTEXT (context);
2030       return FALSE;
2031     }
2032   
2033 #ifdef G_THREADS_ENABLED
2034   if (!context->poll_waiting)
2035     {
2036 #ifndef G_OS_WIN32
2037       gchar c;
2038       read (context->wake_up_pipe[0], &c, 1);
2039 #endif
2040     }
2041   else
2042     context->poll_waiting = FALSE;
2043
2044   /* If the set of poll file descriptors changed, bail out
2045    * and let the main loop rerun
2046    */
2047   if (context->poll_changed)
2048     {
2049       UNLOCK_CONTEXT (context);
2050       return 0;
2051     }
2052 #endif /* G_THREADS_ENABLED */
2053   
2054   pollrec = context->poll_records;
2055   i = 0;
2056   while (i < n_fds)
2057     {
2058       if (pollrec->fd->events)
2059         {
2060           pollrec->fd->revents = fds[i].revents;
2061           i++;
2062         }
2063       pollrec = pollrec->next;
2064     }
2065
2066   source = next_valid_source (context, NULL);
2067   while (source)
2068     {
2069       if ((n_ready > 0) && (source->priority > max_priority))
2070         {
2071           SOURCE_UNREF (source, context);
2072           break;
2073         }
2074       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2075         goto next;
2076
2077       if (!(source->flags & G_SOURCE_READY))
2078         {
2079           gboolean result;
2080           gboolean (*check) (GSource  *source);
2081
2082           check = source->source_funcs->check;
2083           
2084           context->in_check_or_prepare++;
2085           UNLOCK_CONTEXT (context);
2086           
2087           result = (*check) (source);
2088           
2089           LOCK_CONTEXT (context);
2090           context->in_check_or_prepare--;
2091           
2092           if (result)
2093             source->flags |= G_SOURCE_READY;
2094         }
2095
2096       if (source->flags & G_SOURCE_READY)
2097         {
2098           source->ref_count++;
2099           g_ptr_array_add (context->pending_dispatches, source);
2100
2101           n_ready++;
2102         }
2103
2104     next:
2105       source = next_valid_source (context, source);
2106     }
2107
2108   UNLOCK_CONTEXT (context);
2109
2110   return n_ready > 0;
2111 }
2112
2113 /**
2114  * g_main_context_dispatch:
2115  * @context: a #GMainContext
2116  * 
2117  * Dispatch all pending sources()
2118  **/
2119 void
2120 g_main_context_dispatch (GMainContext *context)
2121 {
2122   LOCK_CONTEXT (context);
2123
2124   if (context->pending_dispatches->len > 0)
2125     {
2126       g_main_dispatch (context);
2127     }
2128
2129   UNLOCK_CONTEXT (context);
2130 }
2131
2132 /* HOLDS context lock */
2133 static gboolean
2134 g_main_context_iterate (GMainContext *context,
2135                         gboolean      block,
2136                         gboolean      dispatch,
2137                         GThread      *self)
2138 {
2139   gint max_priority;
2140   gint timeout;
2141   gboolean some_ready;
2142   gint nfds, allocated_nfds;
2143   GPollFD *fds = NULL;
2144   
2145   UNLOCK_CONTEXT (context);
2146
2147 #ifdef G_THREADS_ENABLED
2148   if (!g_main_context_acquire (context))
2149     {
2150       gboolean got_ownership;
2151       
2152       g_return_val_if_fail (g_thread_supported (), FALSE);
2153
2154       if (!block)
2155         return FALSE;
2156
2157       LOCK_CONTEXT (context);
2158       
2159       if (!context->cond)
2160         context->cond = g_cond_new ();
2161           
2162       got_ownership = g_main_context_wait (context,
2163                                            context->cond,
2164                                            g_static_mutex_get_mutex (&context->mutex));
2165
2166       if (!got_ownership)
2167         {
2168           UNLOCK_CONTEXT (context);
2169           return FALSE;
2170         }
2171     }
2172   else
2173     LOCK_CONTEXT (context);
2174 #endif /* G_THREADS_ENABLED */
2175   
2176   if (!context->cached_poll_array)
2177     {
2178       context->cached_poll_array_size = context->n_poll_records;
2179       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2180     }
2181
2182   allocated_nfds = context->cached_poll_array_size;
2183   fds = context->cached_poll_array;
2184   
2185   UNLOCK_CONTEXT (context);
2186
2187   some_ready = g_main_context_prepare (context, &max_priority); 
2188   
2189   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
2190                                        allocated_nfds)) > allocated_nfds)
2191     {
2192       LOCK_CONTEXT (context);
2193       g_free (fds);
2194       context->cached_poll_array_size = allocated_nfds = nfds;
2195       context->cached_poll_array = fds = g_new (GPollFD, nfds);
2196       UNLOCK_CONTEXT (context);
2197     }
2198
2199   if (!block)
2200     timeout = 0;
2201   
2202   g_main_context_poll (context, timeout, max_priority, fds, nfds);
2203   
2204   g_main_context_check (context, max_priority, fds, nfds);
2205   
2206   if (dispatch)
2207     g_main_context_dispatch (context);
2208   
2209 #ifdef G_THREADS_ENABLED
2210   g_main_context_release (context);
2211 #endif /* G_THREADS_ENABLED */    
2212
2213   LOCK_CONTEXT (context);
2214
2215   return some_ready;
2216 }
2217
2218 /**
2219  * g_main_context_pending:
2220  * @context: a #GMainContext (if %NULL, the default context will be used)
2221  *
2222  * Check if any sources have pending events for the given context.
2223  * 
2224  * Return value: %TRUE if events are pending.
2225  **/
2226 gboolean 
2227 g_main_context_pending (GMainContext *context)
2228 {
2229   gboolean retval;
2230
2231   if (!context)
2232     context = g_main_context_default();
2233
2234   LOCK_CONTEXT (context);
2235   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2236   UNLOCK_CONTEXT (context);
2237   
2238   return retval;
2239 }
2240
2241 /**
2242  * g_main_context_iteration:
2243  * @context: a #GMainContext (if %NULL, the default context will be used) 
2244  * @may_block: whether the call may block.
2245  * 
2246  * Run a single iteration for the given main loop. This involves
2247  * checking to see if any event sources are ready to be processed,
2248  * then if no events sources are ready and @may_block is %TRUE, waiting
2249  * for a source to become ready, then dispatching the highest priority
2250  * events sources that are ready. Note that even when @may_block is %TRUE,
2251  * it is still possible for g_main_context_iteration() to return
2252  * %FALSE, since the the wait may be interrupted for other
2253  * reasons than an event source becoming ready.
2254  * 
2255  * Return value: %TRUE if events were dispatched.
2256  **/
2257 gboolean
2258 g_main_context_iteration (GMainContext *context, gboolean may_block)
2259 {
2260   gboolean retval;
2261
2262   if (!context)
2263     context = g_main_context_default();
2264   
2265   LOCK_CONTEXT (context);
2266   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2267   UNLOCK_CONTEXT (context);
2268   
2269   return retval;
2270 }
2271
2272 /**
2273  * g_main_loop_new:
2274  * @context: a #GMainContext  (if %NULL, the default context will be used).
2275  * @is_running: set to TRUE to indicate that the loop is running. This
2276  * is not very important since calling g_main_run() will set this to
2277  * TRUE anyway.
2278  * 
2279  * Create a new #GMainLoop structure
2280  * 
2281  * Return value: 
2282  **/
2283 GMainLoop *
2284 g_main_loop_new (GMainContext *context,
2285                  gboolean      is_running)
2286 {
2287   GMainLoop *loop;
2288   
2289   if (!context)
2290     context = g_main_context_default();
2291   
2292   g_main_context_ref (context);
2293
2294   loop = g_new0 (GMainLoop, 1);
2295   loop->context = context;
2296   loop->is_running = is_running != FALSE;
2297   loop->ref_count = 1;
2298   
2299   return loop;
2300 }
2301
2302 /**
2303  * g_main_loop_ref:
2304  * @loop: a #GMainLoop
2305  * 
2306  * Increase the reference count on a #GMainLoop object by one.
2307  * 
2308  * Return value: @loop
2309  **/
2310 GMainLoop *
2311 g_main_loop_ref (GMainLoop *loop)
2312 {
2313   g_return_val_if_fail (loop != NULL, NULL);
2314   g_return_val_if_fail (loop->ref_count > 0, NULL);
2315
2316   LOCK_CONTEXT (loop->context);
2317   loop->ref_count++;
2318   UNLOCK_CONTEXT (loop->context);
2319
2320   return loop;
2321 }
2322
2323 static void
2324 g_main_loop_unref_and_unlock (GMainLoop *loop)
2325 {
2326   loop->ref_count--;
2327   if (loop->ref_count == 0)
2328     {
2329       /* When the ref_count is 0, there can be nobody else using the
2330        * loop, so it is safe to unlock before destroying.
2331        */
2332       g_main_context_unref_and_unlock (loop->context);
2333   g_free (loop);
2334     }
2335   else
2336     UNLOCK_CONTEXT (loop->context);
2337 }
2338
2339 /**
2340  * g_main_loop_unref:
2341  * @loop: a #GMainLoop
2342  * 
2343  * Decreases the reference count on a #GMainLoop object by one. If
2344  * the result is zero, free the loop and free all associated memory.
2345  **/
2346 void
2347 g_main_loop_unref (GMainLoop *loop)
2348 {
2349   g_return_if_fail (loop != NULL);
2350   g_return_if_fail (loop->ref_count > 0);
2351
2352   LOCK_CONTEXT (loop->context);
2353   
2354   g_main_loop_unref_and_unlock (loop);
2355 }
2356
2357 /**
2358  * g_main_loop_run:
2359  * @loop: a #GMainLoop
2360  * 
2361  * Run a main loop until g_main_quit() is called on the loop.
2362  * If this is called for the thread of the loop's #GMainContext,
2363  * it will process events from the loop, otherwise it will
2364  * simply wait.
2365  **/
2366 void 
2367 g_main_loop_run (GMainLoop *loop)
2368 {
2369   GThread *self = G_THREAD_SELF;
2370
2371   g_return_if_fail (loop != NULL);
2372   g_return_if_fail (loop->ref_count > 0);
2373
2374 #ifdef G_THREADS_ENABLED
2375   if (!g_main_context_acquire (loop->context))
2376     {
2377       gboolean got_ownership = FALSE;
2378       
2379       /* Another thread owns this context */
2380       if (!g_thread_supported ())
2381         {
2382           g_warning ("g_main_loop_run() was called from second thread but"
2383                      "g_thread_init() was never called.");
2384           return;
2385         }
2386       
2387       LOCK_CONTEXT (loop->context);
2388
2389       loop->ref_count++;
2390
2391       if (!loop->is_running)
2392         loop->is_running = TRUE;
2393
2394       if (!loop->context->cond)
2395         loop->context->cond = g_cond_new ();
2396           
2397       while (loop->is_running || !got_ownership)
2398         got_ownership = g_main_context_wait (loop->context,
2399                                              loop->context->cond,
2400                                              g_static_mutex_get_mutex (&loop->context->mutex));
2401       
2402       if (!loop->is_running)
2403         {
2404           UNLOCK_CONTEXT (loop->context);
2405           if (got_ownership)
2406             g_main_context_release (loop->context);
2407           g_main_loop_unref (loop);
2408           return;
2409         }
2410
2411       g_assert (got_ownership);
2412     }
2413   else
2414     LOCK_CONTEXT (loop->context);
2415 #endif /* G_THREADS_ENABLED */ 
2416
2417   if (loop->context->in_check_or_prepare)
2418     {
2419       g_warning ("g_main_run(): called recursively from within a source's check() or "
2420                  "prepare() member, iteration not possible.");
2421       return;
2422     }
2423
2424   loop->ref_count++;
2425   loop->is_running = TRUE;
2426   while (loop->is_running)
2427     g_main_context_iterate (loop->context, TRUE, TRUE, self);
2428
2429 #ifdef G_THREADS_ENABLED
2430   g_main_context_release (loop->context);
2431 #endif /* G_THREADS_ENABLED */    
2432   
2433   g_main_loop_unref_and_unlock (loop);
2434 }
2435
2436 /**
2437  * g_main_loop_quit:
2438  * @loop: a #GMainLoop
2439  * 
2440  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2441  * for the loop will return.
2442  **/
2443 void 
2444 g_main_loop_quit (GMainLoop *loop)
2445 {
2446   g_return_if_fail (loop != NULL);
2447   g_return_if_fail (loop->ref_count > 0);
2448
2449   LOCK_CONTEXT (loop->context);
2450   loop->is_running = FALSE;
2451   g_main_context_wakeup_unlocked (loop->context);
2452
2453   if (loop->context->cond)
2454     g_cond_broadcast (loop->context->cond);
2455   UNLOCK_CONTEXT (loop->context);
2456 }
2457
2458 /**
2459  * g_main_loop_is_running:
2460  * @loop: a #GMainLoop.
2461  * 
2462  * Check to see if the main loop is currently being run via g_main_run()
2463  * 
2464  * Return value: %TRUE if the mainloop is currently being run.
2465  **/
2466 gboolean
2467 g_main_loop_is_running (GMainLoop *loop)
2468 {
2469   g_return_val_if_fail (loop != NULL, FALSE);
2470   g_return_val_if_fail (loop->ref_count > 0, FALSE);
2471
2472   return loop->is_running;
2473 }
2474
2475 /**
2476  * g_main_loop_get_context:
2477  * @loop: a #GMainLoop.
2478  * 
2479  * Returns the #GMainContext of @loop.
2480  * 
2481  * Return value: the #GMainContext of @loop
2482  **/
2483 GMainContext *
2484 g_main_loop_get_context (GMainLoop *loop)
2485 {
2486   g_return_val_if_fail (loop != NULL, NULL);
2487   g_return_val_if_fail (loop->ref_count > 0, NULL);
2488  
2489   return loop->context;
2490 }
2491
2492 /* HOLDS: context's lock */
2493 static void
2494 g_main_context_poll (GMainContext *context,
2495                      gint          timeout,
2496                      gint          priority,
2497                      GPollFD      *fds,
2498                      gint          n_fds)
2499 {
2500 #ifdef  G_MAIN_POLL_DEBUG
2501   GTimer *poll_timer;
2502   GPollRec *pollrec;
2503   gint i;
2504 #endif
2505
2506   GPollFunc poll_func;
2507
2508   if (n_fds || timeout != 0)
2509     {
2510 #ifdef  G_MAIN_POLL_DEBUG
2511       g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2512       poll_timer = g_timer_new ();
2513 #endif
2514
2515       LOCK_CONTEXT (context);
2516
2517       poll_func = context->poll_func;
2518       
2519       UNLOCK_CONTEXT (context);
2520       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2521         g_warning ("poll(2) failed due to: %s.",
2522                    g_strerror (errno));
2523       
2524 #ifdef  G_MAIN_POLL_DEBUG
2525       LOCK_CONTEXT (context);
2526
2527       g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2528                n_fds,
2529                timeout,
2530                g_timer_elapsed (poll_timer, NULL));
2531       g_timer_destroy (poll_timer);
2532       pollrec = context->poll_records;
2533       i = 0;
2534       while (i < n_fds)
2535         {
2536           if (pollrec->fd->events)
2537             {
2538               if (fds[i].revents)
2539                 {
2540                   g_print (" [%d:", fds[i].fd);
2541                   if (fds[i].revents & G_IO_IN)
2542                     g_print ("i");
2543                   if (fds[i].revents & G_IO_OUT)
2544                     g_print ("o");
2545                   if (fds[i].revents & G_IO_PRI)
2546                     g_print ("p");
2547                   if (fds[i].revents & G_IO_ERR)
2548                     g_print ("e");
2549                   if (fds[i].revents & G_IO_HUP)
2550                     g_print ("h");
2551                   if (fds[i].revents & G_IO_NVAL)
2552                     g_print ("n");
2553                   g_print ("]");
2554                 }
2555               i++;
2556             }
2557           pollrec = pollrec->next;
2558         }
2559       g_print ("\n");
2560       
2561       UNLOCK_CONTEXT (context);
2562 #endif
2563     } /* if (n_fds || timeout != 0) */
2564 }
2565
2566 /**
2567  * g_main_context_add_poll:
2568  * @context: a #GMainContext (or %NULL for the default context)
2569  * @fd: a #GPollFD structure holding information about a file
2570  *      descriptor to watch.
2571  * @priority: the priority for this file descriptor which should be
2572  *      the same as the priority used for g_source_attach() to ensure that the
2573  *      file descriptor is polled whenever the results may be needed.
2574  * 
2575  * Add a file descriptor to the set of file descriptors polled * for
2576  * this context. This will very seldom be used directly. Instead
2577  * a typical event source will use g_source_add_poll() instead.
2578  **/
2579 void
2580 g_main_context_add_poll (GMainContext *context,
2581                          GPollFD      *fd,
2582                          gint          priority)
2583 {
2584   if (!context)
2585     context = g_main_context_default ();
2586   
2587   g_return_if_fail (context->ref_count > 0);
2588   g_return_if_fail (fd);
2589
2590   LOCK_CONTEXT (context);
2591   g_main_context_add_poll_unlocked (context, priority, fd);
2592   UNLOCK_CONTEXT (context);
2593 }
2594
2595 /* HOLDS: main_loop_lock */
2596 static void 
2597 g_main_context_add_poll_unlocked (GMainContext *context,
2598                                   gint          priority,
2599                                   GPollFD      *fd)
2600 {
2601   GPollRec *lastrec, *pollrec, *newrec;
2602
2603   if (!context->poll_chunk)
2604     context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2605
2606   if (context->poll_free_list)
2607     {
2608       newrec = context->poll_free_list;
2609       context->poll_free_list = newrec->next;
2610     }
2611   else
2612     newrec = g_chunk_new (GPollRec, context->poll_chunk);
2613
2614   /* This file descriptor may be checked before we ever poll */
2615   fd->revents = 0;
2616   newrec->fd = fd;
2617   newrec->priority = priority;
2618
2619   lastrec = NULL;
2620   pollrec = context->poll_records;
2621   while (pollrec && priority >= pollrec->priority)
2622     {
2623       lastrec = pollrec;
2624       pollrec = pollrec->next;
2625     }
2626   
2627   if (lastrec)
2628     lastrec->next = newrec;
2629   else
2630     context->poll_records = newrec;
2631
2632   newrec->next = pollrec;
2633
2634   context->n_poll_records++;
2635   if (context->cached_poll_array &&
2636       context->cached_poll_array_size < context->n_poll_records)
2637     {
2638       g_free (context->cached_poll_array);
2639       context->cached_poll_array = NULL;
2640     }
2641
2642 #ifdef G_THREADS_ENABLED
2643   context->poll_changed = TRUE;
2644
2645   /* Now wake up the main loop if it is waiting in the poll() */
2646   g_main_context_wakeup_unlocked (context);
2647 #endif
2648 }
2649
2650 /**
2651  * g_main_context_remove_poll:
2652  * @context:a #GMainContext 
2653  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2654  * 
2655  * Remove file descriptor from the set of file descriptors to be
2656  * polled for a particular context.
2657  **/
2658 void
2659 g_main_context_remove_poll (GMainContext *context,
2660                             GPollFD      *fd)
2661 {
2662   if (!context)
2663     context = g_main_context_default ();
2664   
2665   g_return_if_fail (context->ref_count > 0);
2666   g_return_if_fail (fd);
2667
2668   LOCK_CONTEXT (context);
2669   g_main_context_remove_poll_unlocked (context, fd);
2670   UNLOCK_CONTEXT (context);
2671 }
2672
2673 static void
2674 g_main_context_remove_poll_unlocked (GMainContext *context,
2675                                      GPollFD      *fd)
2676 {
2677   GPollRec *pollrec, *lastrec;
2678
2679   lastrec = NULL;
2680   pollrec = context->poll_records;
2681
2682   while (pollrec)
2683     {
2684       if (pollrec->fd == fd)
2685         {
2686           if (lastrec != NULL)
2687             lastrec->next = pollrec->next;
2688           else
2689             context->poll_records = pollrec->next;
2690
2691 #ifdef ENABLE_GC_FRIENDLY
2692           pollrec->fd = NULL;  
2693 #endif /* ENABLE_GC_FRIENDLY */
2694
2695           pollrec->next = context->poll_free_list;
2696           context->poll_free_list = pollrec;
2697
2698           context->n_poll_records--;
2699           break;
2700         }
2701       lastrec = pollrec;
2702       pollrec = pollrec->next;
2703     }
2704
2705 #ifdef G_THREADS_ENABLED
2706   context->poll_changed = TRUE;
2707   
2708   /* Now wake up the main loop if it is waiting in the poll() */
2709   g_main_context_wakeup_unlocked (context);
2710 #endif
2711 }
2712
2713 /**
2714  * g_source_get_current_time:
2715  * @source:  a #GSource
2716  * @timeval: #GTimeVal structure in which to store current time.
2717  * 
2718  * Gets the "current time" to be used when checking 
2719  * this source. The advantage of calling this function over
2720  * calling g_get_current_time() directly is that when 
2721  * checking multiple sources, GLib can cache a single value
2722  * instead of having to repeatedly get the system time.
2723  **/
2724 void
2725 g_source_get_current_time (GSource  *source,
2726                            GTimeVal *timeval)
2727 {
2728   GMainContext *context;
2729   
2730   g_return_if_fail (source->context != NULL);
2731  
2732   context = source->context;
2733
2734   LOCK_CONTEXT (context);
2735
2736   if (!context->time_is_current)
2737     {
2738       g_get_current_time (&context->current_time);
2739       context->time_is_current = TRUE;
2740     }
2741   
2742   *timeval = context->current_time;
2743   
2744   UNLOCK_CONTEXT (context);
2745 }
2746
2747 /**
2748  * g_main_context_set_poll_func:
2749  * @context: a #GMainContext
2750  * @func: the function to call to poll all file descriptors
2751  * 
2752  * Sets the function to use to handle polling of file descriptors. It
2753  * will be used instead of the poll() system call (or GLib's
2754  * replacement function, which is used where poll() isn't available).
2755  *
2756  * This function could possibly be used to integrate the GLib event
2757  * loop with an external event loop.
2758  **/
2759 void
2760 g_main_context_set_poll_func (GMainContext *context,
2761                               GPollFunc     func)
2762 {
2763   if (!context)
2764     context = g_main_context_default ();
2765   
2766   g_return_if_fail (context->ref_count > 0);
2767
2768   LOCK_CONTEXT (context);
2769   
2770   if (func)
2771     context->poll_func = func;
2772   else
2773     {
2774 #ifdef HAVE_POLL
2775       context->poll_func = (GPollFunc) poll;
2776 #else
2777       context->poll_func = (GPollFunc) g_poll;
2778 #endif
2779     }
2780
2781   UNLOCK_CONTEXT (context);
2782 }
2783
2784 /**
2785  * g_main_context_get_poll_func:
2786  * @context: a #GMainContext
2787  * 
2788  * Gets the poll function set by g_main_context_set_poll_func()
2789  * 
2790  * Return value: the poll function
2791  **/
2792 GPollFunc
2793 g_main_context_get_poll_func (GMainContext *context)
2794 {
2795   GPollFunc result;
2796   
2797   if (!context)
2798     context = g_main_context_default ();
2799   
2800   g_return_val_if_fail (context->ref_count > 0, NULL);
2801
2802   LOCK_CONTEXT (context);
2803   result = context->poll_func;
2804   UNLOCK_CONTEXT (context);
2805
2806   return result;
2807 }
2808
2809 /* HOLDS: context's lock */
2810 /* Wake the main loop up from a poll() */
2811 static void
2812 g_main_context_wakeup_unlocked (GMainContext *context)
2813 {
2814 #ifdef G_THREADS_ENABLED
2815   if (g_thread_supported() && context->poll_waiting)
2816     {
2817       context->poll_waiting = FALSE;
2818 #ifndef G_OS_WIN32
2819       write (context->wake_up_pipe[1], "A", 1);
2820 #else
2821       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2822 #endif
2823     }
2824 #endif
2825 }
2826
2827 /**
2828  * g_main_context_wakeup:
2829  * @context: a #GMainContext
2830  * 
2831  * If @context is currently waiting in a poll(), interrupt
2832  * the poll(), and continue the iteration process.
2833  **/
2834 void
2835 g_main_context_wakeup (GMainContext *context)
2836 {
2837   if (!context)
2838     context = g_main_context_default ();
2839   
2840   g_return_if_fail (context->ref_count > 0);
2841
2842   LOCK_CONTEXT (context);
2843   g_main_context_wakeup_unlocked (context);
2844   UNLOCK_CONTEXT (context);
2845 }
2846
2847 /* Timeouts */
2848
2849 static void
2850 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2851                           GTimeVal       *current_time)
2852 {
2853   guint seconds = timeout_source->interval / 1000;
2854   guint msecs = timeout_source->interval - seconds * 1000;
2855
2856   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2857   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2858   if (timeout_source->expiration.tv_usec >= 1000000)
2859     {
2860       timeout_source->expiration.tv_usec -= 1000000;
2861       timeout_source->expiration.tv_sec++;
2862     }
2863 }
2864
2865 static gboolean
2866 g_timeout_prepare  (GSource  *source,
2867                     gint     *timeout)
2868 {
2869   glong sec;
2870   glong msec;
2871   GTimeVal current_time;
2872   
2873   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2874
2875   g_source_get_current_time (source, &current_time);
2876
2877   sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
2878   msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
2879
2880   /* We do the following in a rather convoluted fashion to deal with
2881    * the fact that we don't have an integral type big enough to hold
2882    * the difference of two timevals in millseconds.
2883    */
2884   if (sec < 0 || (sec == 0 && msec < 0))
2885     msec = 0;
2886   else
2887     {
2888       glong interval_sec = timeout_source->interval / 1000;
2889       glong interval_msec = timeout_source->interval % 1000;
2890
2891       if (msec < 0)
2892         {
2893           msec += 1000;
2894           sec -= 1;
2895         }
2896       
2897       if (sec > interval_sec ||
2898           (sec == interval_sec && msec > interval_msec))
2899         {
2900           /* The system time has been set backwards, so we
2901            * reset the expiration time to now + timeout_source->interval;
2902            * this at least avoids hanging for long periods of time.
2903            */
2904           g_timeout_set_expiration (timeout_source, &current_time);
2905           msec = timeout_source->interval;
2906         }
2907       else
2908         {
2909           msec += sec * 1000;
2910         }
2911     }
2912
2913   *timeout = (gint)msec;
2914   
2915   return msec == 0;
2916 }
2917
2918 static gboolean 
2919 g_timeout_check (GSource  *source)
2920 {
2921   GTimeVal current_time;
2922   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2923
2924   g_source_get_current_time (source, &current_time);
2925   
2926   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2927           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2928            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2929 }
2930
2931 static gboolean
2932 g_timeout_dispatch (GSource    *source,
2933                     GSourceFunc callback,
2934                     gpointer    user_data)
2935 {
2936   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2937
2938   if (!callback)
2939     {
2940       g_warning ("Timeout source dispatched without callback\n"
2941                  "You must call g_source_set_callback().");
2942       return FALSE;
2943     }
2944  
2945   if (callback (user_data))
2946     {
2947       GTimeVal current_time;
2948
2949       g_source_get_current_time (source, &current_time);
2950       g_timeout_set_expiration (timeout_source, &current_time);
2951
2952       return TRUE;
2953     }
2954   else
2955     return FALSE;
2956 }
2957
2958 /**
2959  * g_timeout_source_new:
2960  * @interval: the timeout interval in milliseconds.
2961  * 
2962  * Create a new timeout source.
2963  *
2964  * The source will not initially be associated with any #GMainContext
2965  * and must be added to one with g_source_attach() before it will be
2966  * executed.
2967  * 
2968  * Return value: the newly create timeout source
2969  **/
2970 GSource *
2971 g_timeout_source_new (guint interval)
2972 {
2973   GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2974   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2975   GTimeVal current_time;
2976
2977   timeout_source->interval = interval;
2978
2979   g_get_current_time (&current_time);
2980   g_timeout_set_expiration (timeout_source, &current_time);
2981   
2982   return source;
2983 }
2984
2985 /**
2986  * g_timeout_add_full:
2987  * @priority: the priority of the idle source. Typically this will be in the
2988  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2989  * @interval: the time between calls to the function, in milliseconds
2990  *             (1/1000ths of a second.)
2991  * @function: function to call
2992  * @data:     data to pass to @function
2993  * @notify:   function to call when the idle is removed, or %NULL
2994  * 
2995  * Sets a function to be called at regular intervals, with the given
2996  * priority.  The function is called repeatedly until it returns
2997  * FALSE, at which point the timeout is automatically destroyed and
2998  * the function will not be called again.  The @notify function is
2999  * called when the timeout is destroyed.  The first call to the
3000  * function will be at the end of the first @interval.
3001  *
3002  * Note that timeout functions may be delayed, due to the processing of other
3003  * event sources. Thus they should not be relied on for precise timing.
3004  * After each call to the timeout function, the time of the next
3005  * timeout is recalculated based on the current time and the given interval
3006  * (it does not try to 'catch up' time lost in delays).
3007  * 
3008  * Return value: the id of event source.
3009  **/
3010 guint
3011 g_timeout_add_full (gint           priority,
3012                     guint          interval,
3013                     GSourceFunc    function,
3014                     gpointer       data,
3015                     GDestroyNotify notify)
3016 {
3017   GSource *source;
3018   guint id;
3019   
3020   g_return_val_if_fail (function != NULL, 0);
3021
3022   source = g_timeout_source_new (interval);
3023
3024   if (priority != G_PRIORITY_DEFAULT)
3025     g_source_set_priority (source, priority);
3026
3027   g_source_set_callback (source, function, data, notify);
3028   id = g_source_attach (source, NULL);
3029   g_source_unref (source);
3030
3031   return id;
3032 }
3033
3034 /**
3035  * g_timeout_add:
3036  * @interval: the time between calls to the function, in milliseconds
3037  *             (1/1000ths of a second.)
3038  * @function: function to call
3039  * @data:     data to pass to @function
3040  * 
3041  * Sets a function to be called at regular intervals, with the default
3042  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3043  * until it returns FALSE, at which point the timeout is automatically
3044  * destroyed and the function will not be called again.  The @notify
3045  * function is called when the timeout is destroyed.  The first call
3046  * to the function will be at the end of the first @interval.
3047  *
3048  * Note that timeout functions may be delayed, due to the processing of other
3049  * event sources. Thus they should not be relied on for precise timing.
3050  * After each call to the timeout function, the time of the next
3051  * timeout is recalculated based on the current time and the given interval
3052  * (it does not try to 'catch up' time lost in delays).
3053  * 
3054  * Return value: the id of event source.
3055  **/
3056 guint 
3057 g_timeout_add (guint32        interval,
3058                GSourceFunc    function,
3059                gpointer       data)
3060 {
3061   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3062                              interval, function, data, NULL);
3063 }
3064
3065 /* Idle functions */
3066
3067 static gboolean 
3068 g_idle_prepare  (GSource  *source,
3069                  gint     *timeout)
3070 {
3071   *timeout = 0;
3072
3073   return TRUE;
3074 }
3075
3076 static gboolean 
3077 g_idle_check    (GSource  *source)
3078 {
3079   return TRUE;
3080 }
3081
3082 static gboolean
3083 g_idle_dispatch (GSource    *source, 
3084                  GSourceFunc callback,
3085                  gpointer    user_data)
3086 {
3087   if (!callback)
3088     {
3089       g_warning ("Idle source dispatched without callback\n"
3090                  "You must call g_source_set_callback().");
3091       return FALSE;
3092     }
3093   
3094   return callback (user_data);
3095 }
3096
3097 /**
3098  * g_idle_source_new:
3099  * 
3100  * Create a new idle source.
3101  *
3102  * The source will not initially be associated with any #GMainContext
3103  * and must be added to one with g_source_attach() before it will be
3104  * executed.
3105  * 
3106  * Return value: the newly created idle source
3107  **/
3108 GSource *
3109 g_idle_source_new (void)
3110 {
3111   return g_source_new (&idle_funcs, sizeof (GSource));
3112 }
3113
3114 /**
3115  * g_idle_add_full:
3116  * @priority: the priority of the idle source. Typically this will be in the
3117  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3118  * @function: function to call
3119  * @data:     data to pass to @function
3120  * @notify:   function to call when the idle is removed, or %NULL
3121  * 
3122  * Adds a function to be called whenever there are no higher priority
3123  * events pending.  If the function returns FALSE it is automatically
3124  * removed from the list of event sources and will not be called again.
3125  * 
3126  * Return value: the id of the event source.
3127  **/
3128 guint 
3129 g_idle_add_full (gint           priority,
3130                  GSourceFunc    function,
3131                  gpointer       data,
3132                  GDestroyNotify notify)
3133 {
3134   GSource *source;
3135   guint id;
3136   
3137   g_return_val_if_fail (function != NULL, 0);
3138
3139   source = g_idle_source_new ();
3140
3141   if (priority != G_PRIORITY_DEFAULT)
3142     g_source_set_priority (source, priority);
3143
3144   g_source_set_callback (source, function, data, notify);
3145   id = g_source_attach (source, NULL);
3146   g_source_unref (source);
3147
3148   return id;
3149 }
3150
3151 /**
3152  * g_idle_add:
3153  * @function: function to call 
3154  * @data: data to pass to @function.
3155  * 
3156  * Adds a function to be called whenever there are no higher priority
3157  * events pending to the default main loop. The function is given the
3158  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
3159  * returns FALSE it is automatically removed from the list of event
3160  * sources and will not be called again.
3161  * 
3162  * Return value: the id of the event source.
3163  **/
3164 guint 
3165 g_idle_add (GSourceFunc    function,
3166             gpointer       data)
3167 {
3168   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3169 }
3170
3171 /**
3172  * g_idle_remove_by_data:
3173  * @data: the data for the idle source's callback.
3174  * 
3175  * Removes the idle function with the given data.
3176  * 
3177  * Return value: %TRUE if an idle source was found and removed.
3178  **/
3179 gboolean
3180 g_idle_remove_by_data (gpointer data)
3181 {
3182   return g_source_remove_by_funcs_user_data (&idle_funcs, data);
3183 }
3184