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