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