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