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