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