added g_list_nth_prev() which walks ->prev instead of ->next.
[platform/upstream/glib.git] / 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 <sys/types.h>
41 #include <time.h>
42 #ifdef HAVE_SYS_TIME_H
43 #include <sys/time.h>
44 #endif /* HAVE_SYS_TIME_H */
45 #ifdef GLIB_HAVE_SYS_POLL_H
46 #  include <sys/poll.h>
47 #  undef events  /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
48 #  undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
49 #endif /* GLIB_HAVE_SYS_POLL_H */
50 #ifdef HAVE_UNISTD_H
51 #include <unistd.h>
52 #endif /* HAVE_UNISTD_H */
53 #include <errno.h>
54
55 #ifdef G_OS_WIN32
56 #define STRICT
57 #include <windows.h>
58 #endif /* G_OS_WIN32 */
59
60 #ifdef G_OS_BEOS
61 #include <net/socket.h>
62 #endif /* G_OS_BEOS */
63
64 /* Types */
65
66 typedef struct _GTimeoutSource GTimeoutSource;
67 typedef struct _GPollRec GPollRec;
68 typedef struct _GSourceCallback GSourceCallback;
69
70 typedef enum
71 {
72   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
73   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
74 } GSourceFlags;
75
76 struct _GMainContext
77 {
78 #ifdef G_THREADS_ENABLED
79   /* The following lock is used for both the list of sources
80    * and the list of poll records
81    */
82   GMutex *mutex;
83   GThread *thread;
84 #endif  
85
86   GPtrArray *pending_dispatches;
87   gint timeout;                 /* Timeout for current iteration */
88
89   guint next_id;
90   GSource *source_list;
91   gint in_check_or_prepare;
92
93   GPollRec *poll_records;
94   GPollRec *poll_free_list;
95   GMemChunk *poll_chunk;
96   guint n_poll_records;
97   GPollFD *cached_poll_array;
98   gint cached_poll_array_size;
99
100 #ifdef G_THREADS_ENABLED  
101 #ifndef G_OS_WIN32
102 /* this pipe is used to wake up the main loop when a source is added.
103  */
104   gint wake_up_pipe[2];
105 #else /* G_OS_WIN32 */
106   HANDLE wake_up_semaphore;
107 #endif /* G_OS_WIN32 */
108
109   GPollFD wake_up_rec;
110   gboolean poll_waiting;
111
112 /* Flag indicating whether the set of fd's changed during a poll */
113   gboolean poll_changed;
114 #endif /* G_THREADS_ENABLED */
115
116   GPollFunc poll_func;
117
118   GTimeVal current_time;
119   gboolean time_is_current;
120 };
121
122 struct _GSourceCallback
123 {
124   guint ref_count;
125   GSourceFunc func;
126   gpointer    data;
127   GDestroyNotify notify;
128 };
129
130 struct _GMainLoop
131 {
132   GMainContext *context;
133   gboolean is_running;
134   guint ref_count;
135
136 #ifdef G_THREADS_ENABLED
137   GMutex *mutex;
138   GCond *sem_cond;
139 #endif /* G_THREADS_ENABLED */
140 };
141
142 struct _GTimeoutSource
143 {
144   GSource     source;
145   GTimeVal    expiration;
146   gint        interval;
147 };
148
149 struct _GPollRec
150 {
151   gint priority;
152   GPollFD *fd;
153   GPollRec *next;
154 };
155
156 #ifdef G_THREADS_ENABLED
157 #define LOCK_CONTEXT(context) g_mutex_lock(context->mutex)
158 #define UNLOCK_CONTEXT(context) g_mutex_unlock(context->mutex)
159 #define LOCK_LOOP(loop) g_mutex_lock(loop->mutex)
160 #define UNLOCK_LOOP(loop) g_mutex_unlock(loop->mutex)
161 #else
162 #define LOCK_CONTEXT(context) (void)0
163 #define UNLOCK_CONTEXT(context) (void)0
164 #define LOCK_LOOP(context) (void)0
165 #define UNLOCK_LOOP(context) (void)0
166 #endif
167
168 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
169
170 #define SOURCE_UNREF(source, context)                       \
171    G_STMT_START {                                           \
172     if ((source)->ref_count > 1)                            \
173       (source)->ref_count--;                                \
174     else                                                    \
175       g_source_unref_internal ((source), (context), TRUE);  \
176    } G_STMT_END
177
178
179 /* Forward declarations */
180
181 static void g_source_unref_internal             (GSource      *source,
182                                                  GMainContext *context,
183                                                  gboolean      have_lock);
184 static void g_source_destroy_internal           (GSource      *source,
185                                                  GMainContext *context,
186                                                  gboolean      have_lock);
187 static void g_main_context_poll                 (GMainContext *context,
188                                                  gint          timeout,
189                                                  gint          priority,
190                                                  GPollFD      *fds,
191                                                  gint          n_fds);
192 static void g_main_context_add_poll_unlocked    (GMainContext *context,
193                                                  gint          priority,
194                                                  GPollFD      *fd);
195 static void g_main_context_remove_poll_unlocked (GMainContext *context,
196                                                  GPollFD      *fd);
197 static void g_main_context_wakeup               (GMainContext *context);
198
199 static gboolean g_timeout_prepare  (GSource     *source,
200                                     gint        *timeout);
201 static gboolean g_timeout_check    (GSource     *source);
202 static gboolean g_timeout_dispatch (GSource     *source,
203                                     GSourceFunc  callback,
204                                     gpointer     user_data);
205 static gboolean g_idle_prepare     (GSource     *source,
206                                     gint        *timeout);
207 static gboolean g_idle_check       (GSource     *source);
208 static gboolean g_idle_dispatch    (GSource     *source,
209                                     GSourceFunc  callback,
210                                     gpointer     user_data);
211
212 G_LOCK_DEFINE_STATIC (main_loop);
213 static GMainContext *default_main_context;
214
215 static GSourceFuncs timeout_funcs =
216 {
217   g_timeout_prepare,
218   g_timeout_check,
219   g_timeout_dispatch,
220   NULL
221 };
222
223 static GSourceFuncs idle_funcs =
224 {
225   g_idle_prepare,
226   g_idle_check,
227   g_idle_dispatch,
228   NULL
229 };
230
231 #ifdef HAVE_POLL
232 /* SunOS has poll, but doesn't provide a prototype. */
233 #  if defined (sun) && !defined (__SVR4)
234 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
235 #  endif  /* !sun */
236 #else   /* !HAVE_POLL */
237
238 #ifdef G_OS_WIN32
239
240 static gint
241 g_poll (GPollFD *fds,
242         guint    nfds,
243         gint     timeout)
244 {
245   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
246   gboolean poll_msgs = FALSE;
247   GPollFD *f;
248   DWORD ready;
249   MSG msg;
250   UINT timer;
251   gint nhandles = 0;
252
253   for (f = fds; f < &fds[nfds]; ++f)
254     if (f->fd >= 0)
255       {
256         if (f->events & G_IO_IN)
257           {
258             if (f->fd == G_WIN32_MSG_HANDLE)
259               poll_msgs = TRUE;
260             else
261               {
262 #ifdef G_MAIN_POLL_DEBUG
263                 g_print ("g_poll: waiting for %#x\n", f->fd);
264 #endif
265                 handles[nhandles++] = (HANDLE) f->fd;
266               }
267           }
268       }
269
270   if (timeout == -1)
271     timeout = INFINITE;
272
273   if (poll_msgs)
274     {
275       /* Waiting for messages, and maybe events
276        * -> First PeekMessage
277        */
278 #ifdef G_MAIN_POLL_DEBUG
279       g_print ("PeekMessage\n");
280 #endif
281       if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
282         ready = WAIT_OBJECT_0 + nhandles;
283       else
284         {
285           if (nhandles == 0)
286             {
287               /* Waiting just for messages */
288               if (timeout == INFINITE)
289                 {
290                   /* Infinite timeout
291                    * -> WaitMessage
292                    */
293 #ifdef G_MAIN_POLL_DEBUG
294                   g_print ("WaitMessage\n");
295 #endif
296                   if (!WaitMessage ())
297                     g_warning (G_STRLOC ": WaitMessage() failed");
298                   ready = WAIT_OBJECT_0 + nhandles;
299                 }
300               else if (timeout == 0)
301                 {
302                   /* Waiting just for messages, zero timeout.
303                    * If we got here, there was no message
304                    */
305                   ready = WAIT_TIMEOUT;
306                 }
307               else
308                 {
309                   /* Waiting just for messages, some timeout
310                    * -> Set a timer, wait for message,
311                    * kill timer, use PeekMessage
312                    */
313                   timer = SetTimer (NULL, 0, timeout, NULL);
314                   if (timer == 0)
315                     g_warning (G_STRLOC ": SetTimer() failed");
316                   else
317                     {
318 #ifdef G_MAIN_POLL_DEBUG
319                       g_print ("WaitMessage\n");
320 #endif
321                       WaitMessage ();
322                       KillTimer (NULL, timer);
323 #ifdef G_MAIN_POLL_DEBUG
324                       g_print ("PeekMessage\n");
325 #endif
326                       if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
327                           && msg.message != WM_TIMER)
328                         ready = WAIT_OBJECT_0;
329                       else
330                         ready = WAIT_TIMEOUT;
331                     }
332                 }
333             }
334           else
335             {
336               /* Wait for either message or event
337                * -> Use MsgWaitForMultipleObjects
338                */
339 #ifdef G_MAIN_POLL_DEBUG
340               g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
341 #endif
342               ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
343                                                  timeout, QS_ALLINPUT);
344
345               if (ready == WAIT_FAILED)
346                 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
347             }
348         }
349     }
350   else if (nhandles == 0)
351     {
352       /* Wait for nothing (huh?) */
353       return 0;
354     }
355   else
356     {
357       /* Wait for just events
358        * -> Use WaitForMultipleObjects
359        */
360 #ifdef G_MAIN_POLL_DEBUG
361       g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
362 #endif
363       ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
364       if (ready == WAIT_FAILED)
365         g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
366     }
367
368 #ifdef G_MAIN_POLL_DEBUG
369   g_print ("wait returns %d%s\n",
370            ready,
371            (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
372             (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
373              (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
374 #endif
375   for (f = fds; f < &fds[nfds]; ++f)
376     f->revents = 0;
377
378   if (ready == WAIT_FAILED)
379     return -1;
380   else if (ready == WAIT_TIMEOUT)
381     return 0;
382   else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
383     {
384       for (f = fds; f < &fds[nfds]; ++f)
385         if (f->fd >= 0)
386           {
387             if (f->events & G_IO_IN)
388               if (f->fd == G_WIN32_MSG_HANDLE)
389                 f->revents |= G_IO_IN;
390           }
391     }
392 #if TEST_WITHOUT_THIS
393   else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
394     for (f = fds; f < &fds[nfds]; ++f)
395       {
396         if ((f->events & G_IO_IN)
397             && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
398           {
399             f->revents |= G_IO_IN;
400 #ifdef G_MAIN_POLL_DEBUG
401             g_print ("g_poll: got event %#x\n", f->fd);
402 #endif
403 #if 0
404             ResetEvent ((HANDLE) f->fd);
405 #endif
406           }
407       }
408 #endif
409     
410   return 1;
411 }
412
413 #else  /* !G_OS_WIN32 */
414
415 /* The following implementation of poll() comes from the GNU C Library.
416  * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
417  */
418
419 #include <string.h> /* for bzero on BSD systems */
420
421 #ifdef HAVE_SYS_SELECT_H
422 #include <sys/select.h>
423 #endif /* HAVE_SYS_SELECT_H */
424
425 #ifdef G_OS_BEOS
426 #undef NO_FD_SET
427 #endif /* G_OS_BEOS */
428
429 #ifndef NO_FD_SET
430 #  define SELECT_MASK fd_set
431 #else /* !NO_FD_SET */
432 #  ifndef _AIX
433 typedef long fd_mask;
434 #  endif /* _AIX */
435 #  ifdef _IBMR2
436 #    define SELECT_MASK void
437 #  else /* !_IBMR2 */
438 #    define SELECT_MASK int
439 #  endif /* !_IBMR2 */
440 #endif /* !NO_FD_SET */
441
442 static gint 
443 g_poll (GPollFD *fds,
444         guint    nfds,
445         gint     timeout)
446 {
447   struct timeval tv;
448   SELECT_MASK rset, wset, xset;
449   GPollFD *f;
450   int ready;
451   int maxfd = 0;
452
453   FD_ZERO (&rset);
454   FD_ZERO (&wset);
455   FD_ZERO (&xset);
456
457   for (f = fds; f < &fds[nfds]; ++f)
458     if (f->fd >= 0)
459       {
460         if (f->events & G_IO_IN)
461           FD_SET (f->fd, &rset);
462         if (f->events & G_IO_OUT)
463           FD_SET (f->fd, &wset);
464         if (f->events & G_IO_PRI)
465           FD_SET (f->fd, &xset);
466         if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
467           maxfd = f->fd;
468       }
469
470   tv.tv_sec = timeout / 1000;
471   tv.tv_usec = (timeout % 1000) * 1000;
472
473   ready = select (maxfd + 1, &rset, &wset, &xset,
474                   timeout == -1 ? NULL : &tv);
475   if (ready > 0)
476     for (f = fds; f < &fds[nfds]; ++f)
477       {
478         f->revents = 0;
479         if (f->fd >= 0)
480           {
481             if (FD_ISSET (f->fd, &rset))
482               f->revents |= G_IO_IN;
483             if (FD_ISSET (f->fd, &wset))
484               f->revents |= G_IO_OUT;
485             if (FD_ISSET (f->fd, &xset))
486               f->revents |= G_IO_PRI;
487           }
488       }
489
490   return ready;
491 }
492
493 #endif /* !G_OS_WIN32 */
494
495 #endif  /* !HAVE_POLL */
496
497 /* Called to clean up when a thread terminates
498  */
499 void
500 g_main_context_destroy (GMainContext *context)
501 {
502   GSource *source;
503
504   /* We need the lock here only because g_source_destroy expects
505    * to be able to unlock when destroying the source's data
506    */
507   LOCK_CONTEXT (context);
508   source = context->source_list;
509   while (source)
510     {
511       GSource *next = source->next;
512       g_source_destroy_internal (source, context, TRUE);
513       source = next;
514     }
515   UNLOCK_CONTEXT (context);
516
517 #ifdef G_THREADS_ENABLED  
518   g_mutex_free (context->mutex);
519 #endif
520
521   g_ptr_array_free (context->pending_dispatches, TRUE);
522   g_free (context->cached_poll_array);
523   
524   g_mem_chunk_destroy (context->poll_chunk);
525
526 #ifdef G_THREADS_ENABLED
527   if (g_thread_supported())
528     {
529 #ifndef G_OS_WIN32
530       close (context->wake_up_pipe[0]);
531       close (context->wake_up_pipe[1]);
532 #else
533       CloseHandle (context->wake_up_semaphore);
534 #endif
535     }
536 #endif
537   
538   g_free (context);
539 }
540
541 /* This is an imcomplete (only the members up till context) version of
542  * GRealThread from gthread.h. Keep them in sync */
543 typedef struct _GRealThread GRealThread;
544 struct  _GRealThread
545 {
546   GThread thread;
547   GThreadFunc func;
548   gpointer arg;
549   gpointer private_data;
550   GMainContext *context;
551 };
552
553 /**
554  * g_main_context_get:
555  * @thread: a #GThread
556  * 
557  * Retrieves the main loop context for a particular thread. This
558  * will create the main context for the thread if none previously
559  * existed. The context will exist until the thread terminates.
560  * 
561  * Return value: the main loop context for @thread.
562  **/
563 GMainContext *
564 g_main_context_get (GThread *thread)
565 {
566   GRealThread *real_thread = (GRealThread*)thread;
567   GMainContext *context;
568
569   g_return_val_if_fail (thread != NULL, NULL);
570
571   if (g_thread_supported ())
572     context = real_thread->context;
573   else
574     context = default_main_context;
575
576   if (!context)
577     {
578       context = g_new0 (GMainContext, 1);
579
580 #ifdef G_THREADS_ENABLED
581       if (g_thread_supported ())
582         context->mutex = g_mutex_new();
583
584       context->thread = thread;
585 #endif
586       
587       context->next_id = 1;
588       
589       context->source_list = NULL;
590
591 #if HAVE_POLL
592       context->poll_func = (GPollFunc)poll;
593 #else
594       context->poll_func = g_poll;
595 #endif
596
597       context->cached_poll_array = NULL;
598       context->cached_poll_array_size = 0;
599       
600       context->pending_dispatches = g_ptr_array_new ();
601       
602       context->time_is_current = FALSE;
603
604 #ifdef G_THREADS_ENABLED
605       if (g_thread_supported ())
606         {
607 #ifndef G_OS_WIN32
608           if (pipe (context->wake_up_pipe) < 0)
609             g_error ("Cannot create pipe main loop wake-up: %s\n",
610                      g_strerror (errno));
611           
612           context->wake_up_rec.fd = context->wake_up_pipe[0];
613           context->wake_up_rec.events = G_IO_IN;
614           g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
615 #else
616           context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
617           if (context->wake_up_semaphore == NULL)
618             g_error ("Cannot create wake-up semaphore: %s",
619                      g_win32_error_message (GetLastError ()));
620           context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
621           context->wake_up_rec.events = G_IO_IN;
622 #ifdef G_MAIN_POLL_DEBUG
623           g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
624 #endif
625           g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
626 #endif
627         }
628 #endif
629
630       if (g_thread_supported ())
631         real_thread->context = context;
632       else
633         default_main_context = context;
634     }
635
636   return context;
637 }
638
639 /**
640  * g_main_context_default:
641  * 
642  * Return the default main context. This is the main context used
643  * for main loop functions when a main loop is not explicitly
644  * specified.
645  * 
646  * Return value: the default main context.
647  **/
648 GMainContext *
649 g_main_context_default (void)
650 {
651   /* Slow, but safe */
652   
653   G_LOCK (main_loop);
654
655   if (!default_main_context)
656     default_main_context = g_main_context_get (g_thread_self ());
657
658   G_UNLOCK (main_loop);
659
660   return default_main_context;
661 }
662
663 /* Hooks for adding to the main loop */
664
665 /**
666  * g_source_new:
667  * @source_funcs: structure containing functions that implement
668  *                the sources behavior.
669  * @struct_size: size of the #GSource structure to create
670  * 
671  * Create a new GSource structure. The size is specified to
672  * allow creating structures derived from GSource that contain
673  * additional data. The size passed in must be at least
674  * sizeof(GSource).
675  * 
676  * The source will not initially be associated with any #GMainContext
677  * and must be added to one with g_source_add() before it will be
678  * executed.
679  * 
680  * Return value: the newly create #GSource
681  **/
682 GSource *
683 g_source_new (GSourceFuncs *source_funcs,
684               guint         struct_size)
685 {
686   GSource *source;
687
688   g_return_val_if_fail (source_funcs != NULL, NULL);
689   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
690   
691   source = (GSource*) g_malloc0 (struct_size);
692
693   source->source_funcs = source_funcs;
694   source->ref_count = 1;
695   
696   source->priority = G_PRIORITY_DEFAULT;
697
698   source->flags = G_HOOK_FLAG_ACTIVE;
699
700   /* NULL/0 initialization for all other fields */
701   
702   return source;
703 }
704
705 /* Holds context's lock
706  */
707 static void
708 g_source_list_add (GSource      *source,
709                    GMainContext *context)
710 {
711   GSource *tmp_source, *last_source;
712   
713   last_source = NULL;
714   tmp_source = context->source_list;
715   while (tmp_source && tmp_source->priority <= source->priority)
716     {
717       last_source = tmp_source;
718       tmp_source = tmp_source->next;
719     }
720
721   source->next = tmp_source;
722   if (tmp_source)
723     tmp_source->prev = source;
724   
725   source->prev = last_source;
726   if (last_source)
727     last_source->next = source;
728   else
729     context->source_list = source;
730 }
731
732 /* Holds context's lock
733  */
734 static void
735 g_source_list_remove (GSource      *source,
736                       GMainContext *context)
737 {
738   if (source->prev)
739     source->prev->next = source->next;
740   else
741     context->source_list = source->next;
742
743   if (source->next)
744     source->next->prev = source->prev;
745
746   source->prev = NULL;
747   source->next = NULL;
748 }
749
750 /**
751  * g_source_attach:
752  * @source: a #GSource
753  * @context: a #GMainContext (if %NULL, the default context will be used)
754  * 
755  * Adds a #GSource to a @context so that it will be executed within
756  * that context.
757  *
758  * Return value: the ID for the source within the #GMainContext
759  **/
760 guint
761 g_source_attach (GSource      *source,
762                  GMainContext *context)
763 {
764   guint result = 0;
765   GSList *tmp_list;
766
767   g_return_val_if_fail (source->context == NULL, 0);
768   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
769   
770   if (!context)
771     context = g_main_context_default ();
772
773   LOCK_CONTEXT (context);
774
775   source->context = context;
776   result = source->id = context->next_id++;
777
778   source->ref_count++;
779   g_source_list_add (source, context);
780
781   tmp_list = source->poll_fds;
782   while (tmp_list)
783     {
784       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
785       tmp_list = tmp_list->next;
786     }
787
788 #ifdef G_THREADS_ENABLED
789   /* Now wake up the main loop if it is waiting in the poll() */
790   g_main_context_wakeup (context);
791 #endif
792
793   UNLOCK_CONTEXT (context);
794
795   return result;
796 }
797
798 static void
799 g_source_destroy_internal (GSource      *source,
800                            GMainContext *context,
801                            gboolean      have_lock)
802 {
803   if (!have_lock)
804     LOCK_CONTEXT (context);
805   
806   if (!SOURCE_DESTROYED (source))
807     {
808       GSList *tmp_list;
809       gpointer old_cb_data;
810       GSourceCallbackFuncs *old_cb_funcs;
811       
812       source->flags &= ~G_HOOK_FLAG_ACTIVE;
813
814       old_cb_data = source->callback_data;
815       old_cb_funcs = source->callback_funcs;
816
817       source->callback_data = NULL;
818       source->callback_funcs = NULL;
819
820       if (old_cb_funcs)
821         {
822           UNLOCK_CONTEXT (context);
823           old_cb_funcs->unref (old_cb_data);
824           LOCK_CONTEXT (context);
825         }
826       
827       tmp_list = source->poll_fds;
828       while (tmp_list)
829         {
830           g_main_context_remove_poll_unlocked (context, tmp_list->data);
831           tmp_list = tmp_list->next;
832         }
833       
834       g_source_unref_internal (source, context, TRUE);
835     }
836
837   if (!have_lock)
838     UNLOCK_CONTEXT (context);
839 }
840
841 /**
842  * g_source_destroy:
843  * @source: a #GSource
844  * 
845  * Remove a source from its #GMainContext, if any, and mark it as
846  * destroyed.  The source cannot be subsequently added to another
847  * context.
848  **/
849 void
850 g_source_destroy (GSource *source)
851 {
852   GMainContext *context;
853   
854   g_return_if_fail (source != NULL);
855   
856   context = source->context;
857   
858   if (context)
859     g_source_destroy_internal (source, context, FALSE);
860   else
861     source->flags &= ~G_HOOK_FLAG_ACTIVE;
862 }
863
864 /**
865  * g_source_get_id:
866  * @source: a #GSource
867  * 
868  * Return the numeric ID for a particular source. The ID of a source
869  * is unique within a particular main loop context. The reverse
870  * mapping from ID to source is done by g_main_context_find_source_by_id().
871  *
872  * Return value: the ID for the source
873  **/
874 guint
875 g_source_get_id (GSource *source)
876 {
877   guint result;
878   
879   g_return_val_if_fail (source != NULL, 0);
880   g_return_val_if_fail (source->context != NULL, 0);
881
882   LOCK_CONTEXT (source->context);
883   result = source->id;
884   UNLOCK_CONTEXT (source->context);
885   
886   return result;
887 }
888
889 /**
890  * g_source_get_context:
891  * @source: a #GSource
892  * 
893  * Get the #GMainContext with which the source is associated.
894  * Calling this function on a destroyed source is an error.
895  * 
896  * Return value: the #GMainContext with which the source is associated,
897  *               or %NULL if the context has not yet been added
898  *               to a source.
899  **/
900 GMainContext *
901 g_source_get_context (GSource *source)
902 {
903   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
904
905   return source->context;
906 }
907
908 /**
909  * g_source_add_poll:
910  * @source:a #GSource 
911  * @fd: a #GPollFD structure holding information about a file
912  *      descriptor to watch.
913  * 
914  * Add a file descriptor to the set of file descriptors polled for
915  * this source. This is usually combined with g_source_new() to add an
916  * event source. The event source's check function will typically test
917  * the revents field in the #GPollFD struct and return %TRUE if events need
918  * to be processed.
919  **/
920 void
921 g_source_add_poll (GSource *source,
922                    GPollFD *fd)
923 {
924   GMainContext *context;
925   
926   g_return_if_fail (source != NULL);
927   g_return_if_fail (fd != NULL);
928   g_return_if_fail (!SOURCE_DESTROYED (source));
929   
930   context = source->context;
931
932   if (context)
933     LOCK_CONTEXT (context);
934   
935   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
936
937   if (context)
938     {
939       g_main_context_add_poll_unlocked (context, source->priority, fd);
940       UNLOCK_CONTEXT (context);
941     }
942 }
943
944 /**
945  * g_source_remove_poll:
946  * @source:a #GSource 
947  * @fd: a #GPollFD structure previously passed to g_source_poll.
948  * 
949  * Remove a file descriptor from the set of file descriptors polled for
950  * this source. 
951  **/
952 void
953 g_source_remove_poll (GSource *source,
954                       GPollFD *fd)
955 {
956   GMainContext *context;
957   
958   g_return_if_fail (source != NULL);
959   g_return_if_fail (fd != NULL);
960   g_return_if_fail (!SOURCE_DESTROYED (source));
961   
962   context = source->context;
963
964   if (context)
965     LOCK_CONTEXT (context);
966   
967   source->poll_fds = g_slist_remove (source->poll_fds, fd);
968
969   if (context)
970     {
971       g_main_context_remove_poll_unlocked (context, fd);
972       UNLOCK_CONTEXT (context);
973     }
974 }
975
976 /**
977  * g_source_set_callback_indirect:
978  * @source: the source
979  * @callback_data: pointer to callback data "object"
980  * @callback_funcs: functions for reference counting callback_data
981  *                  and getting the callback and data
982  * 
983  * Set the callback function storing the data as a refcounted callback
984  * "object". This is used to implement g_source_set_callback_closure()
985  * and internally. Note that calling g_source_set_callback_indirect() assumes
986  * an initial reference count on @callback_data, and thus
987  * @callback_funcs->unref will eventually be called once more
988  * than @callback_funcs->ref.
989  **/
990 void
991 g_source_set_callback_indirect (GSource              *source,
992                                 gpointer              callback_data,
993                                 GSourceCallbackFuncs *callback_funcs)
994 {
995   GMainContext *context;
996   gpointer old_cb_data;
997   GSourceCallbackFuncs *old_cb_funcs;
998   
999   g_return_if_fail (source != NULL);
1000   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1001
1002   context = source->context;
1003
1004   if (context)
1005     LOCK_CONTEXT (context);
1006
1007   old_cb_data = source->callback_data;
1008   old_cb_funcs = source->callback_funcs;
1009
1010   source->callback_data = callback_data;
1011   source->callback_funcs = callback_funcs;
1012   
1013   if (context)
1014     UNLOCK_CONTEXT (context);
1015   
1016   if (old_cb_funcs)
1017     old_cb_funcs->unref (old_cb_data);
1018 }
1019
1020 static void
1021 g_source_callback_ref (gpointer cb_data)
1022 {
1023   GSourceCallback *callback = cb_data;
1024
1025   callback->ref_count++;
1026 }
1027
1028
1029 static void
1030 g_source_callback_unref (gpointer cb_data)
1031 {
1032   GSourceCallback *callback = cb_data;
1033
1034   callback->ref_count--;
1035   if (callback->ref_count == 0)
1036     {
1037       if (callback->notify)
1038         callback->notify (callback->data);
1039       g_free (callback);
1040     }
1041 }
1042
1043 static void
1044 g_source_callback_get (gpointer     cb_data,
1045                        GSourceFunc *func,
1046                        gpointer    *data)
1047 {
1048   GSourceCallback *callback = cb_data;
1049
1050   *func = callback->func;
1051   *data = callback->data;
1052 }
1053
1054 static GSourceCallbackFuncs g_source_callback_funcs = {
1055   g_source_callback_ref,
1056   g_source_callback_unref,
1057   g_source_callback_get,
1058 };
1059
1060 /**
1061  * g_source_set_callback:
1062  * @source: the source
1063  * @func: a callback function
1064  * @data: the data to pass to callback function
1065  * @notify: a function to call when @data is no longer in use, or %NULL.
1066  * 
1067  * Set the callback function for a source.
1068  **/
1069 void
1070 g_source_set_callback (GSource        *source,
1071                        GSourceFunc     func,
1072                        gpointer        data,
1073                        GDestroyNotify  notify)
1074 {
1075   GSourceCallback *new_callback;
1076
1077   g_return_if_fail (source != NULL);
1078
1079   new_callback = g_new (GSourceCallback, 1);
1080
1081   new_callback->ref_count = 1;
1082   new_callback->func = func;
1083   new_callback->data = data;
1084   new_callback->notify = notify;
1085
1086   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1087 }
1088
1089 /**
1090  * g_source_set_priority:
1091  * @source: a #GSource
1092  * @priority: the new priority.
1093  * 
1094  * Set the priority of a source. While the main loop is being
1095  * run, a source will 
1096  **/
1097 void
1098 g_source_set_priority (GSource  *source,
1099                        gint      priority)
1100 {
1101   GSList *tmp_list;
1102   GMainContext *context;
1103   
1104   g_return_if_fail (source != NULL);
1105
1106   context = source->context;
1107
1108   if (context)
1109     LOCK_CONTEXT (context);
1110   
1111   source->priority = priority;
1112
1113   if (context)
1114     {
1115       source->next = NULL;
1116       source->prev = NULL;
1117       
1118       tmp_list = source->poll_fds;
1119       while (tmp_list)
1120         {
1121           g_main_context_remove_poll_unlocked (context, tmp_list->data);
1122           g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1123       
1124           tmp_list = tmp_list->next;
1125         }
1126       
1127       UNLOCK_CONTEXT (source->context);
1128     }
1129 }
1130
1131 /**
1132  * g_source_get_priority:
1133  * @source: a #GSource
1134  * 
1135  * Gets the priority of a surce
1136  * 
1137  * Return value: the priority of the source
1138  **/
1139 gint
1140 g_source_get_priority (GSource *source)
1141 {
1142   g_return_val_if_fail (source != NULL, 0);
1143
1144   return source->priority;
1145 }
1146
1147 /**
1148  * g_source_set_can_recurse:
1149  * @source: a #GSource
1150  * @can_recurse: whether recursion is allowed for this source
1151  * 
1152  * Sets whether a source can be called recursively. If @can_recurse is
1153  * %TRUE, then while the source is being dispatched then this source
1154  * will be processed normally. Otherwise, all processing of this
1155  * source is blocked until the dispatch function returns.
1156  **/
1157 void
1158 g_source_set_can_recurse (GSource  *source,
1159                           gboolean  can_recurse)
1160 {
1161   GMainContext *context;
1162   
1163   g_return_if_fail (source != NULL);
1164
1165   context = source->context;
1166
1167   if (context)
1168     LOCK_CONTEXT (context);
1169   
1170   if (can_recurse)
1171     source->flags |= G_SOURCE_CAN_RECURSE;
1172   else
1173     source->flags &= ~G_SOURCE_CAN_RECURSE;
1174
1175   if (context)
1176     UNLOCK_CONTEXT (context);
1177 }
1178
1179 /**
1180  * g_source_get_can_recurse:
1181  * @source: a #GSource
1182  * 
1183  * Checks whether a source is allowed to be called recursively.
1184  * see g_source_set_can_recurse.
1185  * 
1186  * Return value: whether recursion is allowed.
1187  **/
1188 gboolean
1189 g_source_get_can_recurse (GSource  *source)
1190 {
1191   g_return_val_if_fail (source != NULL, FALSE);
1192   
1193   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1194 }
1195
1196 /**
1197  * g_source_ref:
1198  * @source: a #GSource
1199  * 
1200  * Increases the reference count on a source by one.
1201  * 
1202  * Return value: @source
1203  **/
1204 GSource *
1205 g_source_ref (GSource *source)
1206 {
1207   GMainContext *context;
1208   
1209   g_return_val_if_fail (source != NULL, NULL);
1210
1211   context = source->context;
1212
1213   if (context)
1214     LOCK_CONTEXT (context);
1215
1216   source->ref_count++;
1217
1218   if (context)
1219     UNLOCK_CONTEXT (context);
1220
1221   return source;
1222 }
1223
1224 /* g_source_unref() but possible to call within context lock
1225  */
1226 static void
1227 g_source_unref_internal (GSource      *source,
1228                          GMainContext *context,
1229                          gboolean      have_lock)
1230 {
1231   gpointer old_cb_data = NULL;
1232   GSourceCallbackFuncs *old_cb_funcs = NULL;
1233
1234   g_return_if_fail (source != NULL);
1235   
1236   if (!have_lock && context)
1237     LOCK_CONTEXT (context);
1238
1239   source->ref_count--;
1240   if (source->ref_count == 0)
1241     {
1242       old_cb_data = source->callback_data;
1243       old_cb_funcs = source->callback_funcs;
1244
1245       source->callback_data = NULL;
1246       source->callback_funcs = NULL;
1247
1248       if (context && !SOURCE_DESTROYED (source))
1249         {
1250           g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1251           source->ref_count++;
1252         }
1253       else if (context)
1254         g_source_list_remove (source, context);
1255
1256       if (source->source_funcs->destroy)
1257         source->source_funcs->destroy (source);
1258       
1259       g_slist_free (source->poll_fds);
1260       source->poll_fds = NULL;
1261       g_free (source);
1262     }
1263   
1264   if (!have_lock && context)
1265     UNLOCK_CONTEXT (context);
1266
1267   if (old_cb_funcs)
1268     {
1269       if (have_lock)
1270         UNLOCK_CONTEXT (context);
1271       
1272       old_cb_funcs->unref (old_cb_data);
1273
1274       if (have_lock)
1275         LOCK_CONTEXT (context);
1276     }
1277 }
1278
1279 /**
1280  * g_source_unref:
1281  * @source: a #GSource
1282  * 
1283  * Decreases the reference count of a source by one. If the
1284  * resulting reference count is zero the source and associated
1285  * memory will be destroyed. 
1286  **/
1287 void
1288 g_source_unref (GSource *source)
1289 {
1290   g_return_if_fail (source != NULL);
1291
1292   g_source_unref_internal (source, source->context, FALSE);
1293 }
1294
1295 /**
1296  * g_main_context_find_source_by_id:
1297  * @context: a #GMainContext (if %NULL, the default context will be used)
1298  * @id: the source ID, as returned by g_source_get_id()
1299  * 
1300  * Finds a #GSource given a pair of context and ID
1301  * 
1302  * Return value: the #GSource if found, otherwise, %NULL
1303  **/
1304 GSource *
1305 g_main_context_find_source_by_id (GMainContext *context,
1306                                   guint         id)
1307 {
1308   GSource *source;
1309   
1310   g_return_val_if_fail (id > 0, FALSE);
1311
1312   if (context == NULL)
1313     context = g_main_context_default ();
1314   
1315   LOCK_CONTEXT (context);
1316   
1317   source = context->source_list;
1318   while (source)
1319     {
1320       if (!SOURCE_DESTROYED (source) &&
1321           source->id == id)
1322         break;
1323       source = source->next;
1324     }
1325
1326   UNLOCK_CONTEXT (context);
1327
1328   return source;
1329 }
1330
1331 /**
1332  * g_main_context_find_source_by_funcs_user_data:
1333  * @context: a #GMainContext (if %NULL, the default context will be used).
1334  * @funcs: the @source_funcs passed to g_source_new().
1335  * @user_data: the user data from the callback.
1336  * 
1337  * Finds a source with the given source functions and user data.  If
1338  * multiple sources exist with the same source function and user data,
1339  * the first one found will be returned.
1340  * 
1341  * Return value: the source, if one was found, otherwise %NULL
1342  **/
1343 GSource *
1344 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1345                                                GSourceFuncs *funcs,
1346                                                gpointer      user_data)
1347 {
1348   GSource *source;
1349   
1350   g_return_val_if_fail (funcs != NULL, FALSE);
1351
1352   if (context == NULL)
1353     context = g_main_context_default ();
1354   
1355   LOCK_CONTEXT (context);
1356
1357   source = context->source_list;
1358   while (source)
1359     {
1360       if (!SOURCE_DESTROYED (source) &&
1361           source->source_funcs == funcs &&
1362           source->callback_data == user_data)
1363         break;
1364       source = source->next;
1365     }
1366
1367   UNLOCK_CONTEXT (context);
1368
1369   return source;
1370 }
1371
1372 /**
1373  * g_main_context_find_source_by_user_data:
1374  * @context: a #GMainContext
1375  * @user_data: the user_data for the callback.
1376  * 
1377  * Finds a source with the given user data for the callback.  If
1378  * multiple sources exist with the same user data, the first
1379  * one found will be returned.
1380  * 
1381  * Return value: the source, if one was found, otherwise %NULL
1382  **/
1383 GSource *
1384 g_main_context_find_source_by_user_data (GMainContext *context,
1385                                          gpointer      user_data)
1386 {
1387   GSource *source;
1388   
1389   if (context == NULL)
1390     context = g_main_context_default ();
1391   
1392   LOCK_CONTEXT (context);
1393
1394   source = context->source_list;
1395   while (source)
1396     {
1397       if (!SOURCE_DESTROYED (source) &&
1398           source->callback_data == user_data)
1399         break;
1400       source = source->next;
1401     }
1402
1403   UNLOCK_CONTEXT (context);
1404
1405   return source;
1406 }
1407
1408 /**
1409  * g_source_remove:
1410  * @tag: the id of the source to remove.
1411  * 
1412  * Removes the source with the given id from the default main
1413  * context. The id of a #GSource is given by g_source_get_id(),
1414  * or will be returned by the functions g_source_attach(),
1415  * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1416  * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1417  *
1418  * See also g_source_destroy().
1419  *
1420  * Return value: %TRUE if the source was found and removed.
1421  **/
1422 gboolean
1423 g_source_remove (guint tag)
1424 {
1425   GSource *source;
1426   
1427   g_return_val_if_fail (tag > 0, FALSE);
1428
1429   source = g_main_context_find_source_by_id (NULL, tag);
1430   if (source)
1431     g_source_destroy (source);
1432
1433   return source != NULL;
1434 }
1435
1436 /**
1437  * g_source_remove_by_user_data:
1438  * @user_data: the user_data for the callback.
1439  * 
1440  * Removes a source from the default main loop context given the user
1441  * data for the callback. If multiple sources exist with the same user
1442  * data, only one will be destroyed.
1443  * 
1444  * Return value: %TRUE if a source was found and removed. 
1445  **/
1446 gboolean
1447 g_source_remove_by_user_data (gpointer user_data)
1448 {
1449   GSource *source;
1450   
1451   source = g_main_context_find_source_by_user_data (NULL, user_data);
1452   if (source)
1453     {
1454       g_source_destroy (source);
1455       return TRUE;
1456     }
1457   else
1458     return FALSE;
1459 }
1460
1461 /**
1462  * g_source_remove_by_funcs_user_data:
1463  * @funcs: The @source_funcs passed to g_source_new()
1464  * @user_data: the user data for the callback
1465  * 
1466  * Removes a source from the default main loop context given the
1467  * source functions and user data. If multiple sources exist with the
1468  * same source functions and user data, only one will be destroyed.
1469  * 
1470  * Return value: %TRUE if a source was found and removed. 
1471  **/
1472 gboolean
1473 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1474                                     gpointer      user_data)
1475 {
1476   GSource *source;
1477
1478   g_return_val_if_fail (funcs != NULL, FALSE);
1479
1480   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1481   if (source)
1482     {
1483       g_source_destroy (source);
1484       return TRUE;
1485     }
1486   else
1487     return FALSE;
1488 }
1489
1490 /**
1491  * g_get_current_time:
1492  * @result: #GTimeVal structure in which to store current time.
1493  * 
1494  * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1495  **/
1496 void
1497 g_get_current_time (GTimeVal *result)
1498 {
1499 #ifndef G_OS_WIN32
1500   struct timeval r;
1501
1502   g_return_if_fail (result != NULL);
1503
1504   /*this is required on alpha, there the timeval structs are int's
1505     not longs and a cast only would fail horribly*/
1506   gettimeofday (&r, NULL);
1507   result->tv_sec = r.tv_sec;
1508   result->tv_usec = r.tv_usec;
1509 #else
1510   /* Avoid calling time() except for the first time.
1511    * GetTickCount() should be pretty fast and low-level?
1512    * I could also use ftime() but it seems unnecessarily overheady.
1513    */
1514   static DWORD start_tick = 0;
1515   static time_t start_time;
1516   DWORD tick;
1517
1518   g_return_if_fail (result != NULL);
1519  
1520   if (start_tick == 0)
1521     {
1522       start_tick = GetTickCount ();
1523       time (&start_time);
1524     }
1525
1526   tick = GetTickCount ();
1527
1528   result->tv_sec = (tick - start_tick) / 1000 + start_time;
1529   result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1530 #endif
1531 }
1532
1533 /* Running the main loop */
1534
1535 /* HOLDS: context's lock */
1536 static void
1537 g_main_dispatch (GMainContext *context)
1538 {
1539   gint i;
1540
1541   for (i = 0; i < context->pending_dispatches->len; i++)
1542     {
1543       GSource *source = context->pending_dispatches->pdata[i];
1544
1545       context->pending_dispatches->pdata[i] = NULL;
1546       g_assert (source);
1547
1548       source->flags &= ~G_SOURCE_READY;
1549
1550       if (!SOURCE_DESTROYED (source))
1551         {
1552           gboolean was_in_call;
1553           gpointer user_data = NULL;
1554           GSourceFunc callback = NULL;
1555           GSourceCallbackFuncs *cb_funcs;
1556           gpointer cb_data;
1557           gboolean need_destroy;
1558
1559           gboolean (*dispatch) (GSource *,
1560                                 GSourceFunc,
1561                                 gpointer);
1562
1563           dispatch = source->source_funcs->dispatch;
1564           cb_funcs = source->callback_funcs;
1565           cb_data = source->callback_data;
1566
1567           if (cb_funcs)
1568             cb_funcs->ref (cb_data);
1569           
1570           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1571           source->flags |= G_HOOK_FLAG_IN_CALL;
1572
1573           UNLOCK_CONTEXT (context);
1574
1575           if (cb_funcs)
1576             cb_funcs->get (cb_data, &callback, &user_data);
1577
1578           need_destroy = ! dispatch (source,
1579                                      callback,
1580                                      user_data);
1581           LOCK_CONTEXT (context);
1582
1583           if (cb_funcs)
1584             cb_funcs->unref (cb_data);
1585
1586          if (!was_in_call)
1587             source->flags &= ~G_HOOK_FLAG_IN_CALL;
1588
1589           /* Note: this depends on the fact that we can't switch
1590            * sources from one main context to another
1591            */
1592           if (need_destroy && !SOURCE_DESTROYED (source))
1593             {
1594               g_assert (source->context == context);
1595               g_source_destroy_internal (source, context, TRUE);
1596             }
1597         }
1598       
1599       SOURCE_UNREF (source, context);
1600     }
1601
1602   g_ptr_array_set_size (context->pending_dispatches, 0);
1603 }
1604
1605 /* Holds context's lock */
1606 static inline GSource *
1607 next_valid_source (GMainContext *context,
1608                    GSource      *source)
1609 {
1610   GSource *new_source = source ? source->next : context->source_list;
1611
1612   while (new_source)
1613     {
1614       if (!SOURCE_DESTROYED (new_source))
1615         {
1616           new_source->ref_count++;
1617           break;
1618         }
1619       
1620       new_source = new_source->next;
1621     }
1622
1623   if (source)
1624     SOURCE_UNREF (source, context);
1625           
1626   return new_source;
1627 }
1628
1629
1630 /**
1631  * g_main_context_prepare:
1632  * @context: a #GMainContext
1633  * @priority: location to store priority of highest priority
1634  *            source already ready.
1635  * 
1636  * Prepares to poll sources within a main loop. The resulting information
1637  * for polling is determined by calling g_main_context_query ().
1638  * 
1639  * Return value: %TRUE if some source is ready to be dispatched
1640  *               prior to polling.
1641  **/
1642 gboolean
1643 g_main_context_prepare (GMainContext *context,
1644                         gint         *priority)
1645 {
1646   gint n_ready = 0;
1647   gint current_priority = G_MAXINT;
1648   GSource *source;
1649
1650   if (context == NULL)
1651     context = g_main_context_default ();
1652   
1653   LOCK_CONTEXT (context);
1654
1655   context->time_is_current = FALSE;
1656
1657   if (context->in_check_or_prepare)
1658     {
1659       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1660                  "prepare() member.");
1661       return FALSE;
1662     }
1663
1664 #ifdef G_THREADS_ENABLED
1665   if (context->poll_waiting)
1666     {
1667       g_warning("g_main_context_prepare(): main loop already active in another thread");
1668       UNLOCK_CONTEXT (context);
1669       return FALSE;
1670     }
1671   
1672   context->poll_waiting = TRUE;
1673 #endif /* G_THREADS_ENABLED */
1674
1675 #if 0
1676   /* If recursing, finish up current dispatch, before starting over */
1677   if (context->pending_dispatches)
1678     {
1679       if (dispatch)
1680         g_main_dispatch (context, &current_time);
1681       
1682       UNLOCK_CONTEXT (context);
1683       return TRUE;
1684     }
1685 #endif
1686
1687   /* If recursing, clear list of pending dispatches */
1688   g_ptr_array_set_size (context->pending_dispatches, 0);
1689   
1690   /* Prepare all sources */
1691
1692   context->timeout = -1;
1693   
1694   source = next_valid_source (context, NULL);
1695   while (source)
1696     {
1697       gint source_timeout = -1;
1698
1699       if ((n_ready > 0) && (source->priority > current_priority))
1700         {
1701           SOURCE_UNREF (source, context);
1702           break;
1703         }
1704       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1705         goto next;
1706
1707       if (!(source->flags & G_SOURCE_READY))
1708         {
1709           gboolean result;
1710           gboolean (*prepare)  (GSource  *source, 
1711                                 gint     *timeout);
1712
1713           prepare = source->source_funcs->prepare;
1714           context->in_check_or_prepare++;
1715           UNLOCK_CONTEXT (context);
1716
1717           result = (*prepare) (source, &source_timeout);
1718
1719           LOCK_CONTEXT (context);
1720           context->in_check_or_prepare--;
1721
1722           if (result)
1723             source->flags |= G_SOURCE_READY;
1724         }
1725
1726       if (source->flags & G_SOURCE_READY)
1727         {
1728           n_ready++;
1729           current_priority = source->priority;
1730           context->timeout = 0;
1731         }
1732       
1733       if (source_timeout >= 0)
1734         {
1735           if (context->timeout < 0)
1736             context->timeout = source_timeout;
1737           else
1738             context->timeout = MIN (context->timeout, source_timeout);
1739         }
1740
1741     next:
1742       source = next_valid_source (context, source);
1743     }
1744
1745   UNLOCK_CONTEXT (context);
1746   
1747   if (priority)
1748     *priority = current_priority;
1749   
1750   return (n_ready > 0);
1751 }
1752
1753 /**
1754  * g_main_context_query:
1755  * @context: a #GMainContext
1756  * @max_priority: maximum priority source to check
1757  * @timeout: location to store timeout to be used in polling
1758  * @fds: location to store #GPollFD records that need to be polled.
1759  * @n_fds: length of @fds.
1760  * 
1761  * Determines information necessary to poll this main loop.
1762  * 
1763  * Return value: 
1764  **/
1765 gint
1766 g_main_context_query (GMainContext *context,
1767                       gint          max_priority,
1768                       gint         *timeout,
1769                       GPollFD      *fds,
1770                       gint          n_fds)
1771 {
1772   gint n_poll;
1773   GPollRec *pollrec;
1774   
1775   LOCK_CONTEXT (context);
1776
1777   pollrec = context->poll_records;
1778   n_poll = 0;
1779   while (pollrec && max_priority >= pollrec->priority)
1780     {
1781       if (pollrec->fd->events)
1782         {
1783           if (n_poll < n_fds)
1784             {
1785               fds[n_poll].fd = pollrec->fd->fd;
1786               /* In direct contradiction to the Unix98 spec, IRIX runs into
1787                * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1788                * flags in the events field of the pollfd while it should
1789                * just ignoring them. So we mask them out here.
1790                */
1791               fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1792               fds[n_poll].revents = 0;
1793             }
1794           n_poll++;
1795         }
1796       
1797       pollrec = pollrec->next;
1798     }
1799
1800 #ifdef G_THREADS_ENABLED
1801   context->poll_changed = FALSE;
1802 #endif
1803   
1804   if (timeout)
1805     {
1806       *timeout = context->timeout;
1807       if (timeout != 0)
1808         context->time_is_current = FALSE;
1809     }
1810   
1811   UNLOCK_CONTEXT (context);
1812
1813   return n_poll;
1814 }
1815
1816 /**
1817  * g_main_context_check:
1818  * @context: a #GMainContext
1819  * @max_priority: the maximum numerical priority of sources to check
1820  * @fds: array of #GPollFD's that was passed to the last call to
1821  *       g_main_context_query()
1822  * @n_fds: return value of g_main_context_query()
1823  * 
1824  * Pass the results of polling back to the main loop.
1825  * 
1826  * Return value: %TRUE if some sources are ready to be dispatched.
1827  **/
1828 gboolean
1829 g_main_context_check (GMainContext *context,
1830                       gint          max_priority,
1831                       GPollFD      *fds,
1832                       gint          n_fds)
1833 {
1834   GSource *source;
1835   GPollRec *pollrec;
1836   gint n_ready = 0;
1837   gint i;
1838   
1839   LOCK_CONTEXT (context);
1840
1841   if (context->in_check_or_prepare)
1842     {
1843       g_warning ("g_main_context_check() called recursively from within a source's check() or "
1844                  "prepare() member.");
1845       return FALSE;
1846     }
1847   
1848 #ifdef G_THREADS_ENABLED
1849   if (!context->poll_waiting)
1850     {
1851 #ifndef G_OS_WIN32
1852       gchar c;
1853       read (context->wake_up_pipe[0], &c, 1);
1854 #endif
1855     }
1856   else
1857     context->poll_waiting = FALSE;
1858
1859   /* If the set of poll file descriptors changed, bail out
1860    * and let the main loop rerun
1861    */
1862   if (context->poll_changed)
1863     return 0;
1864 #endif /* G_THREADS_ENABLED */
1865   
1866   pollrec = context->poll_records;
1867   i = 0;
1868   while (i < n_fds)
1869     {
1870       if (pollrec->fd->events)
1871         {
1872           pollrec->fd->revents = fds[i].revents;
1873           i++;
1874         }
1875       pollrec = pollrec->next;
1876     }
1877
1878   source = next_valid_source (context, NULL);
1879   while (source)
1880     {
1881       if ((n_ready > 0) && (source->priority > max_priority))
1882         {
1883           SOURCE_UNREF (source, context);
1884           break;
1885         }
1886       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1887         goto next;
1888
1889       if (!(source->flags & G_SOURCE_READY))
1890         {
1891           gboolean result;
1892           gboolean (*check) (GSource  *source);
1893
1894           check = source->source_funcs->check;
1895           
1896           context->in_check_or_prepare++;
1897           UNLOCK_CONTEXT (context);
1898           
1899           result = (*check) (source);
1900           
1901           LOCK_CONTEXT (context);
1902           context->in_check_or_prepare--;
1903           
1904           if (result)
1905             source->flags |= G_SOURCE_READY;
1906         }
1907
1908       if (source->flags & G_SOURCE_READY)
1909         {
1910           source->ref_count++;
1911           g_ptr_array_add (context->pending_dispatches, source);
1912
1913           n_ready++;
1914         }
1915
1916     next:
1917       source = next_valid_source (context, source);
1918     }
1919
1920   UNLOCK_CONTEXT (context);
1921
1922   return n_ready > 0;
1923 }
1924
1925 /**
1926  * g_main_context_dispatch:
1927  * @context: a #GMainContext
1928  * 
1929  * Dispatch all pending sources()
1930  **/
1931 void
1932 g_main_context_dispatch (GMainContext *context)
1933 {
1934   LOCK_CONTEXT (context);
1935
1936   if (context->pending_dispatches->len > 0)
1937     {
1938       g_main_dispatch (context);
1939     }
1940
1941   UNLOCK_CONTEXT (context);
1942 }
1943
1944 static gboolean
1945 g_main_context_iterate (GMainContext *context,
1946                         gboolean      block,
1947                         gboolean      dispatch)
1948 {
1949   gint max_priority;
1950   gint timeout;
1951   gboolean some_ready;
1952   gint nfds, new_nfds;
1953   GPollFD *fds;
1954   
1955   some_ready = g_main_context_prepare (context, &max_priority);
1956
1957   do
1958     {
1959       LOCK_CONTEXT (context);
1960
1961       if (context->cached_poll_array)
1962         {
1963           nfds = context->cached_poll_array_size;
1964           fds = context->cached_poll_array;
1965           context->cached_poll_array = NULL;
1966         }
1967       else
1968         {
1969           nfds = context->cached_poll_array_size = context->n_poll_records;
1970           fds = g_new (GPollFD, nfds);
1971         }
1972
1973       UNLOCK_CONTEXT (context);
1974   
1975       new_nfds = g_main_context_query (context, max_priority,
1976                                        &timeout, fds, nfds);
1977     }
1978   while (new_nfds > nfds);
1979
1980   if (!block)
1981     timeout = 0;
1982   
1983   g_main_context_poll (context, timeout, max_priority,
1984                        fds, new_nfds);
1985
1986   g_main_context_check (context,
1987                         max_priority,
1988                         fds, new_nfds);
1989
1990   LOCK_CONTEXT (context);
1991
1992   g_assert (!context->cached_poll_array);
1993   
1994   context->cached_poll_array = fds;
1995   context->cached_poll_array_size = nfds;
1996
1997   UNLOCK_CONTEXT (context);
1998   
1999   if (dispatch)
2000     g_main_context_dispatch (context);
2001
2002   return some_ready;
2003 }
2004
2005 /**
2006  * g_main_context_pending:
2007  * @context: a #GMainContext (if %NULL, the default context will be used)
2008  *
2009  * Check if any sources have pending events for the given context.
2010  * 
2011  * Return value: %TRUE if events are pending.
2012  **/
2013 gboolean 
2014 g_main_context_pending (GMainContext *context)
2015 {
2016   if (!context)
2017     context = g_main_context_default();
2018   
2019   return g_main_context_iterate (context, FALSE, FALSE);
2020 }
2021
2022 /**
2023  * g_main_context_iteration:
2024  * @context: a #GMainContext (if %NULL, the default context will be used) 
2025  * @may_block: whether the call may block.
2026  * 
2027  * Run a single iteration for the given main loop. This involves
2028  * checking to see if any event sources are ready to be processed,
2029  * then if no events sources are ready and @may_block is %TRUE, waiting
2030  * for a source to become ready, then dispatching the highest priority
2031  * events sources that are ready. Note that even when @may_block is %TRUE,
2032  * it is still possible for g_main_context_iteration() to return
2033  * %FALSE, since the the wait may be interrupted for other
2034  * reasons than an event source becoming ready.
2035  * 
2036  * Return value: %TRUE if events were dispatched.
2037  **/
2038 gboolean
2039 g_main_context_iteration (GMainContext *context, gboolean may_block)
2040 {
2041   if (!context)
2042     context = g_main_context_default();
2043   
2044   return g_main_context_iterate (context, may_block, TRUE);
2045 }
2046
2047 /**
2048  * g_main_loop_new:
2049  * @context: a #GMainContext  (if %NULL, the default context will be used).
2050  * @is_running: set to TRUE to indicate that the loop is running. This
2051  * is not very important since calling g_main_run() will set this to
2052  * TRUE anyway.
2053  * 
2054  * Create a new #GMainLoop structure
2055  * 
2056  * Return value: 
2057  **/
2058 GMainLoop *
2059 g_main_loop_new (GMainContext *context,
2060                  gboolean      is_running)
2061 {
2062   GMainLoop *loop;
2063   
2064   if (!context)
2065     context = g_main_context_default();
2066   
2067   loop = g_new0 (GMainLoop, 1);
2068   loop->context = context;
2069   loop->is_running = is_running != FALSE;
2070   loop->ref_count = 1;
2071   
2072 #ifdef G_THREADS_ENABLED
2073   if (g_thread_supported ())
2074     loop->mutex = g_mutex_new ();
2075   else
2076     loop->mutex = NULL;
2077   loop->sem_cond = NULL;
2078 #endif /* G_THREADS_ENABLED */
2079
2080   return loop;
2081 }
2082
2083 /**
2084  * g_main_loop_ref:
2085  * @loop: a #GMainLoop
2086  * 
2087  * Increase the reference count on a #GMainLoop object by one.
2088  * 
2089  * Return value: @loop
2090  **/
2091 GMainLoop *
2092 g_main_loop_ref (GMainLoop *loop)
2093 {
2094   g_return_val_if_fail (loop != NULL, NULL);
2095
2096   LOCK_LOOP (loop);
2097   loop->ref_count++;
2098   UNLOCK_LOOP (loop);
2099
2100   return loop;
2101 }
2102
2103 static void
2104 main_loop_destroy (GMainLoop *loop)
2105 {
2106 #ifdef G_THREADS_ENABLED
2107   g_mutex_free (loop->mutex);
2108   if (loop->sem_cond)
2109     g_cond_free (loop->sem_cond);
2110 #endif /* G_THREADS_ENABLED */  
2111   
2112   g_free (loop);
2113 }
2114
2115 /**
2116  * g_main_loop_unref:
2117  * @loop: a #GMainLoop
2118  * 
2119  * Decreases the reference count on a #GMainLoop object by one. If
2120  * the result is zero, free the loop and free all associated memory.
2121  **/
2122 void
2123 g_main_loop_unref (GMainLoop *loop)
2124 {
2125   g_return_if_fail (loop != NULL);
2126   g_return_if_fail (loop->ref_count > 0);
2127
2128   LOCK_LOOP (loop);
2129   
2130   loop->ref_count--;
2131   if (loop->ref_count == 0)
2132     {
2133       /* When the ref_count is 0, there can be nobody else using the
2134        * loop, so it is safe to unlock before destroying.
2135        */
2136       UNLOCK_LOOP (loop);
2137       main_loop_destroy (loop);
2138     }
2139   else
2140     UNLOCK_LOOP (loop);
2141 }
2142
2143 /**
2144  * g_main_loop_run:
2145  * @loop: a #GMainLoop
2146  * 
2147  * Run a main loop until g_main_quit() is called on the loop.
2148  * If this is called for the thread of the loop's #GMainContext,
2149  * it will process events from the loop, otherwise it will
2150  * simply wait.
2151  **/
2152 void 
2153 g_main_loop_run (GMainLoop *loop)
2154 {
2155   g_return_if_fail (loop != NULL);
2156
2157   /* The assumption here is that a reference is held to the loop
2158    * until we recursively iterate
2159    */
2160 #ifdef G_THREADS_ENABLED
2161   if (loop->context->thread != g_thread_self ())
2162     {
2163       LOCK_LOOP (loop);
2164
2165       loop->ref_count++;
2166       
2167       if (!g_thread_supported ())
2168         {
2169           g_warning ("g_main_loop_run() was called from second thread but"
2170                      "g_thread_init() was never called.");
2171         }
2172       else
2173         {
2174           if (!loop->sem_cond)
2175             loop->sem_cond = g_cond_new ();
2176           
2177           if (!loop->is_running)
2178             loop->is_running = TRUE;
2179           
2180           while (loop->is_running)
2181             g_cond_wait (loop->sem_cond, loop->mutex);
2182         }
2183     }
2184   else
2185 #endif /* G_THREADS_ENABLED */    
2186     {
2187       LOCK_CONTEXT (loop->context);
2188       if (loop->context->in_check_or_prepare)
2189         {
2190           g_warning ("g_main_run(): called recursively from within a source's check() or "
2191                      "prepare() member, iteration not possible.");
2192           return;
2193         }
2194       UNLOCK_CONTEXT (loop->context);
2195       
2196       LOCK_LOOP (loop);
2197
2198       loop->ref_count++;
2199       loop->is_running = TRUE;
2200       while (loop->is_running)
2201         {
2202           UNLOCK_LOOP (loop);
2203           g_main_context_iterate (loop->context, TRUE, TRUE);
2204           LOCK_LOOP (loop);
2205         }
2206     }
2207
2208   /* We inline this here rather than calling g_main_loop_unref() to
2209    * avoid an extra unlock/lock.
2210    */
2211   loop->ref_count--;
2212   if (loop->ref_count == 0)
2213     {
2214       UNLOCK_LOOP (loop);
2215       main_loop_destroy (loop);
2216     }
2217   else
2218     UNLOCK_LOOP (loop);
2219 }
2220
2221 /**
2222  * g_main_loop_quit:
2223  * @loop: a #GMainLoop
2224  * 
2225  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2226  * for the loop will return.
2227  **/
2228 void 
2229 g_main_loop_quit (GMainLoop *loop)
2230 {
2231   g_return_if_fail (loop != NULL);
2232
2233   LOCK_LOOP (loop);
2234   loop->is_running = FALSE;
2235
2236 #ifdef G_THREADS_ENABLED
2237   if (loop->sem_cond)
2238     g_cond_broadcast (loop->sem_cond);
2239 #endif
2240   
2241   UNLOCK_LOOP (loop);
2242
2243   LOCK_CONTEXT (loop->context);
2244   
2245   g_main_context_wakeup (loop->context);
2246   UNLOCK_CONTEXT (loop->context);
2247 }
2248
2249 /**
2250  * g_main_loop_is_running:
2251  * @loop: a #GMainLoop.
2252  * 
2253  * Check to see if the main loop is currently being run via g_main_run()
2254  * 
2255  * Return value: %TRUE if the mainloop is currently being run.
2256  **/
2257 gboolean
2258 g_main_loop_is_running (GMainLoop *loop)
2259 {
2260   gboolean result;
2261   
2262   g_return_val_if_fail (loop != NULL, FALSE);
2263
2264   LOCK_LOOP (loop);
2265   result = loop->is_running;
2266   UNLOCK_LOOP (loop);
2267
2268   return result;
2269 }
2270
2271 /* HOLDS: context's lock */
2272 static void
2273 g_main_context_poll (GMainContext *context,
2274                      gint          timeout,
2275                      gint          priority,
2276                      GPollFD      *fds,
2277                      gint          n_fds)
2278 {
2279 #ifdef  G_MAIN_POLL_DEBUG
2280   GTimer *poll_timer;
2281   GPollRec *pollrec;
2282   gint i;
2283 #endif
2284
2285   GPollFunc poll_func;
2286
2287   if (n_fds || timeout != 0)
2288     {
2289 #ifdef  G_MAIN_POLL_DEBUG
2290       g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2291       poll_timer = g_timer_new ();
2292 #endif
2293
2294       LOCK_CONTEXT (context);
2295
2296       poll_func = context->poll_func;
2297       
2298       UNLOCK_CONTEXT (context);
2299       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2300         g_warning ("poll(2) failed due to: %s.",
2301                    g_strerror (errno));
2302       
2303 #ifdef  G_MAIN_POLL_DEBUG
2304       LOCK_CONTEXT (context);
2305
2306       g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2307                n_fds,
2308                timeout,
2309                g_timer_elapsed (poll_timer, NULL));
2310       g_timer_destroy (poll_timer);
2311       pollrec = context->poll_records;
2312       i = 0;
2313       while (i < n_fds)
2314         {
2315           if (pollrec->fd->events)
2316             {
2317               if (fds[i].revents)
2318                 {
2319                   g_print (" [%d:", fds[i].fd);
2320                   if (fds[i].revents & G_IO_IN)
2321                     g_print ("i");
2322                   if (fds[i].revents & G_IO_OUT)
2323                     g_print ("o");
2324                   if (fds[i].revents & G_IO_PRI)
2325                     g_print ("p");
2326                   if (fds[i].revents & G_IO_ERR)
2327                     g_print ("e");
2328                   if (fds[i].revents & G_IO_HUP)
2329                     g_print ("h");
2330                   if (fds[i].revents & G_IO_NVAL)
2331                     g_print ("n");
2332                   g_print ("]");
2333                 }
2334               i++;
2335             }
2336           pollrec = pollrec->next;
2337         }
2338       g_print ("\n");
2339       
2340       UNLOCK_CONTEXT (context);
2341 #endif
2342     } /* if (n_fds || timeout != 0) */
2343 }
2344
2345 /**
2346  * g_main_context_add_poll:
2347  * @context: a #GMainContext (or %NULL for the default context)
2348  * @fd: a #GPollFD structure holding information about a file
2349  *      descriptor to watch.
2350  * @priority: the priority for this file descriptor which should be
2351  *      the same as the priority used for g_source_attach() to ensure that the
2352  *      file descriptor is polled whenever the results may be needed.
2353  * 
2354  * Add a file descriptor to the set of file descriptors polled * for
2355  * this context. This will very seldom be used directly. Instead
2356  * a typical event source will use g_source_add_poll() instead.
2357  **/
2358 void
2359 g_main_context_add_poll (GMainContext *context,
2360                          GPollFD      *fd,
2361                          gint          priority)
2362 {
2363   if (!context)
2364     context = g_main_context_default ();
2365   
2366   LOCK_CONTEXT (context);
2367   g_main_context_add_poll_unlocked (context, priority, fd);
2368   UNLOCK_CONTEXT (context);
2369 }
2370
2371 /* HOLDS: main_loop_lock */
2372 static void 
2373 g_main_context_add_poll_unlocked (GMainContext *context,
2374                                   gint          priority,
2375                                   GPollFD      *fd)
2376 {
2377   GPollRec *lastrec, *pollrec, *newrec;
2378
2379   if (!context->poll_chunk)
2380     context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2381
2382   if (context->poll_free_list)
2383     {
2384       newrec = context->poll_free_list;
2385       context->poll_free_list = newrec->next;
2386     }
2387   else
2388     newrec = g_chunk_new (GPollRec, context->poll_chunk);
2389
2390   /* This file descriptor may be checked before we ever poll */
2391   fd->revents = 0;
2392   newrec->fd = fd;
2393   newrec->priority = priority;
2394
2395   lastrec = NULL;
2396   pollrec = context->poll_records;
2397   while (pollrec && priority >= pollrec->priority)
2398     {
2399       lastrec = pollrec;
2400       pollrec = pollrec->next;
2401     }
2402   
2403   if (lastrec)
2404     lastrec->next = newrec;
2405   else
2406     context->poll_records = newrec;
2407
2408   newrec->next = pollrec;
2409
2410   context->n_poll_records++;
2411   if (context->cached_poll_array &&
2412       context->cached_poll_array_size < context->n_poll_records)
2413     {
2414       g_free (context->cached_poll_array);
2415       context->cached_poll_array = NULL;
2416     }
2417
2418 #ifdef G_THREADS_ENABLED
2419   context->poll_changed = TRUE;
2420
2421   /* Now wake up the main loop if it is waiting in the poll() */
2422   g_main_context_wakeup (context);
2423 #endif
2424 }
2425
2426 /**
2427  * g_main_context_remove_poll:
2428  * @context:a #GMainContext 
2429  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2430  * 
2431  * Remove file descriptor from the set of file descriptors to be
2432  * polled for a particular context.
2433  **/
2434 void
2435 g_main_context_remove_poll (GMainContext *context,
2436                             GPollFD      *fd)
2437 {
2438   if (!context)
2439     context = g_main_context_default ();
2440   
2441   LOCK_CONTEXT (context);
2442
2443   g_main_context_remove_poll_unlocked (context, fd);
2444   
2445   UNLOCK_CONTEXT (context);
2446 }
2447
2448 static void
2449 g_main_context_remove_poll_unlocked (GMainContext *context,
2450                                      GPollFD      *fd)
2451 {
2452   GPollRec *pollrec, *lastrec;
2453
2454   lastrec = NULL;
2455   pollrec = context->poll_records;
2456
2457   while (pollrec)
2458     {
2459       if (pollrec->fd == fd)
2460         {
2461           if (lastrec != NULL)
2462             lastrec->next = pollrec->next;
2463           else
2464             context->poll_records = pollrec->next;
2465
2466 #ifdef ENABLE_GC_FRIENDLY
2467           pollrec->fd = NULL;  
2468 #endif /* ENABLE_GC_FRIENDLY */
2469
2470           pollrec->next = context->poll_free_list;
2471           context->poll_free_list = pollrec;
2472
2473           context->n_poll_records--;
2474           break;
2475         }
2476       lastrec = pollrec;
2477       pollrec = pollrec->next;
2478     }
2479
2480 #ifdef G_THREADS_ENABLED
2481   context->poll_changed = TRUE;
2482   
2483   /* Now wake up the main loop if it is waiting in the poll() */
2484   g_main_context_wakeup (context);
2485 #endif
2486 }
2487
2488 /**
2489  * g_source_get_current_time:
2490  * @source:  a #GSource
2491  * @timeval: #GTimeVal structure in which to store current time.
2492  * 
2493  * Gets the "current time" to be used when checking 
2494  * this source. The advantage of calling this function over
2495  * calling g_get_current_time() directly is that when 
2496  * checking multiple sources, GLib can cache a single value
2497  * instead of having to repeatedly get the system time.
2498  **/
2499 void
2500 g_source_get_current_time (GSource  *source,
2501                            GTimeVal *timeval)
2502 {
2503   GMainContext *context;
2504   
2505   g_return_if_fail (source->context != NULL);
2506  
2507   context = source->context;
2508
2509   LOCK_CONTEXT (context);
2510
2511   if (!context->time_is_current)
2512     {
2513       g_get_current_time (&context->current_time);
2514       context->time_is_current = TRUE;
2515     }
2516   
2517   *timeval = context->current_time;
2518   
2519   UNLOCK_CONTEXT (context);
2520 }
2521
2522 /**
2523  * g_main_context_set_poll_func:
2524  * @context: a #GMainContext
2525  * @func: the function to call to poll all file descriptors
2526  * 
2527  * Sets the function to use to handle polling of file descriptors. It
2528  * will be used instead of the poll() system call (or GLib's
2529  * replacement function, which is used where poll() isn't available).
2530  *
2531  * This function could possibly be used to integrate the GLib event
2532  * loop with an external event loop.
2533  **/
2534 void
2535 g_main_context_set_poll_func (GMainContext *context,
2536                               GPollFunc     func)
2537 {
2538   if (!context)
2539     context = g_main_context_default ();
2540   
2541   LOCK_CONTEXT (context);
2542   
2543   if (func)
2544     context->poll_func = func;
2545   else
2546     {
2547 #ifdef HAVE_POLL
2548       context->poll_func = (GPollFunc) poll;
2549 #else
2550       context->poll_func = (GPollFunc) g_poll;
2551 #endif
2552     }
2553
2554   UNLOCK_CONTEXT (context);
2555 }
2556
2557 /**
2558  * g_main_context_get_poll_func:
2559  * @context: a #GMainContext
2560  * 
2561  * Gets the poll function set by g_main_context_set_poll_func()
2562  * 
2563  * Return value: the poll function
2564  **/
2565 GPollFunc
2566 g_main_context_get_poll_func (GMainContext *context)
2567 {
2568   GPollFunc result;
2569   
2570   if (!context)
2571     context = g_main_context_default ();
2572   
2573   LOCK_CONTEXT (context);
2574   result = context->poll_func;
2575   UNLOCK_CONTEXT (context);
2576
2577   return result;
2578 }
2579
2580 /* HOLDS: context's lock */
2581 /* Wake the main loop up from a poll() */
2582 static void
2583 g_main_context_wakeup (GMainContext *context)
2584 {
2585 #ifdef G_THREADS_ENABLED
2586   if (g_thread_supported() && context->poll_waiting)
2587     {
2588       context->poll_waiting = FALSE;
2589 #ifndef G_OS_WIN32
2590       write (context->wake_up_pipe[1], "A", 1);
2591 #else
2592       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2593 #endif
2594     }
2595 #endif
2596 }
2597
2598 /* Timeouts */
2599
2600 static void
2601 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2602                           GTimeVal       *current_time)
2603 {
2604   guint seconds = timeout_source->interval / 1000;
2605   guint msecs = timeout_source->interval - seconds * 1000;
2606
2607   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2608   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2609   if (timeout_source->expiration.tv_usec >= 1000000)
2610     {
2611       timeout_source->expiration.tv_usec -= 1000000;
2612       timeout_source->expiration.tv_sec++;
2613     }
2614 }
2615
2616 static gboolean
2617 g_timeout_prepare  (GSource  *source,
2618                     gint     *timeout)
2619 {
2620   glong msec;
2621   GTimeVal current_time;
2622   
2623   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2624
2625   g_source_get_current_time (source, &current_time);
2626   
2627   msec = ((timeout_source->expiration.tv_sec  - current_time.tv_sec) * 1000 +
2628           (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2629
2630   if (msec < 0)
2631     msec = 0;
2632   else if (msec > timeout_source->interval)
2633     {
2634       /* The system time has been set backwards, so we
2635        * reset the expiration time to now + timeout_source->interval;
2636        * this at least avoids hanging for long periods of time.
2637        */
2638       g_timeout_set_expiration (timeout_source, &current_time);
2639       msec = timeout_source->interval;
2640     }
2641   
2642   *timeout = msec;
2643   
2644   return msec == 0;
2645 }
2646
2647 static gboolean 
2648 g_timeout_check (GSource  *source)
2649 {
2650   GTimeVal current_time;
2651   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2652
2653   g_source_get_current_time (source, &current_time);
2654   
2655   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2656           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2657            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2658 }
2659
2660 static gboolean
2661 g_timeout_dispatch (GSource    *source,
2662                     GSourceFunc callback,
2663                     gpointer    user_data)
2664 {
2665   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2666
2667   if (!callback)
2668     {
2669       g_warning ("Timeout source dispatched without callback\n"
2670                  "You must call g_source_set_callback().");
2671       return FALSE;
2672     }
2673  
2674   if (callback (user_data))
2675     {
2676       GTimeVal current_time;
2677
2678       g_source_get_current_time (source, &current_time);
2679       g_timeout_set_expiration (timeout_source, &current_time);
2680
2681       return TRUE;
2682     }
2683   else
2684     return FALSE;
2685 }
2686
2687 /**
2688  * g_timeout_source_new:
2689  * @interval: the timeout interval in milliseconds.
2690  * 
2691  * Create a new timeout source.
2692  *
2693  * The source will not initially be associated with any #GMainContext
2694  * and must be added to one with g_source_attach() before it will be
2695  * executed.
2696  * 
2697  * Return value: the newly create timeout source
2698  **/
2699 GSource *
2700 g_timeout_source_new (guint interval)
2701 {
2702   GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2703   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2704   GTimeVal current_time;
2705
2706   timeout_source->interval = interval;
2707
2708   g_get_current_time (&current_time);
2709   g_timeout_set_expiration (timeout_source, &current_time);
2710   
2711   return source;
2712 }
2713
2714 /**
2715  * g_timeout_add_full:
2716  * @priority: the priority of the idle source. Typically this will be in the
2717  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2718  * @interval: the time between calls to the function, in milliseconds
2719  *             (1/1000ths of a second.)
2720  * @function: function to call
2721  * @data:     data to pass to @function
2722  * @notify:   function to call when the idle is removed, or %NULL
2723  * 
2724  * Sets a function to be called at regular intervals, with the given
2725  * priority.  The function is called repeatedly until it returns
2726  * FALSE, at which point the timeout is automatically destroyed and
2727  * the function will not be called again.  The @notify function is
2728  * called when the timeout is destroyed.  The first call to the
2729  * function will be at the end of the first @interval.
2730  *
2731  * Note that timeout functions may be delayed, due to the processing of other
2732  * event sources. Thus they should not be relied on for precise timing.
2733  * After each call to the timeout function, the time of the next
2734  * timeout is recalculated based on the current time and the given interval
2735  * (it does not try to 'catch up' time lost in delays).
2736  * 
2737  * Return value: the id of event source.
2738  **/
2739 guint
2740 g_timeout_add_full (gint           priority,
2741                     guint          interval,
2742                     GSourceFunc    function,
2743                     gpointer       data,
2744                     GDestroyNotify notify)
2745 {
2746   GSource *source;
2747   guint id;
2748   
2749   g_return_val_if_fail (function != NULL, 0);
2750
2751   source = g_timeout_source_new (interval);
2752
2753   if (priority != G_PRIORITY_DEFAULT)
2754     g_source_set_priority (source, priority);
2755
2756   g_source_set_callback (source, function, data, notify);
2757   id = g_source_attach (source, NULL);
2758   g_source_unref (source);
2759
2760   return id;
2761 }
2762
2763 /**
2764  * g_timeout_add:
2765  * @interval: the time between calls to the function, in milliseconds
2766  *             (1/1000ths of a second.)
2767  * @function: function to call
2768  * @data:     data to pass to @function
2769  * 
2770  * Sets a function to be called at regular intervals, with the default
2771  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
2772  * until it returns FALSE, at which point the timeout is automatically
2773  * destroyed and the function will not be called again.  The @notify
2774  * function is called when the timeout is destroyed.  The first call
2775  * to the function will be at the end of the first @interval.
2776  *
2777  * Note that timeout functions may be delayed, due to the processing of other
2778  * event sources. Thus they should not be relied on for precise timing.
2779  * After each call to the timeout function, the time of the next
2780  * timeout is recalculated based on the current time and the given interval
2781  * (it does not try to 'catch up' time lost in delays).
2782  * 
2783  * Return value: the id of event source.
2784  **/
2785 guint 
2786 g_timeout_add (guint32        interval,
2787                GSourceFunc    function,
2788                gpointer       data)
2789 {
2790   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
2791                              interval, function, data, NULL);
2792 }
2793
2794 /* Idle functions */
2795
2796 static gboolean 
2797 g_idle_prepare  (GSource  *source,
2798                  gint     *timeout)
2799 {
2800   *timeout = 0;
2801
2802   return TRUE;
2803 }
2804
2805 static gboolean 
2806 g_idle_check    (GSource  *source)
2807 {
2808   return TRUE;
2809 }
2810
2811 static gboolean
2812 g_idle_dispatch (GSource    *source, 
2813                  GSourceFunc callback,
2814                  gpointer    user_data)
2815 {
2816   if (!callback)
2817     {
2818       g_warning ("Idle source dispatched without callback\n"
2819                  "You must call g_source_set_callback().");
2820       return FALSE;
2821     }
2822   
2823   return callback (user_data);
2824 }
2825
2826 /**
2827  * g_idle_source_new:
2828  * 
2829  * Create a new idle source.
2830  *
2831  * The source will not initially be associated with any #GMainContext
2832  * and must be added to one with g_source_attach() before it will be
2833  * executed.
2834  * 
2835  * Return value: the newly created idle source
2836  **/
2837 GSource *
2838 g_idle_source_new (void)
2839 {
2840   return g_source_new (&idle_funcs, sizeof (GSource));
2841 }
2842
2843 /**
2844  * g_idle_add_full:
2845  * @priority: the priority of the idle source. Typically this will be in the
2846  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2847  * @function: function to call
2848  * @data:     data to pass to @function
2849  * @notify:   function to call when the idle is removed, or %NULL
2850  * 
2851  * Adds a function to be called whenever there are no higher priority
2852  * events pending.  If the function returns FALSE it is automatically
2853  * removed from the list of event sources and will not be called again.
2854  * 
2855  * Return value: the id of the event source.
2856  **/
2857 guint 
2858 g_idle_add_full (gint           priority,
2859                  GSourceFunc    function,
2860                  gpointer       data,
2861                  GDestroyNotify notify)
2862 {
2863   GSource *source;
2864   guint id;
2865   
2866   g_return_val_if_fail (function != NULL, 0);
2867
2868   source = g_idle_source_new ();
2869
2870   if (priority != G_PRIORITY_DEFAULT)
2871     g_source_set_priority (source, priority);
2872
2873   g_source_set_callback (source, function, data, notify);
2874   id = g_source_attach (source, NULL);
2875   g_source_unref (source);
2876
2877   return id;
2878 }
2879
2880 /**
2881  * g_idle_add:
2882  * @function: function to call 
2883  * @data: data to pass to @function.
2884  * 
2885  * Adds a function to be called whenever there are no higher priority
2886  * events pending to the default main loop. The function is given the
2887  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
2888  * returns FALSE it is automatically removed from the list of event
2889  * sources and will not be called again.
2890  * 
2891  * Return value: the id of the event source.
2892  **/
2893 guint 
2894 g_idle_add (GSourceFunc    function,
2895             gpointer       data)
2896 {
2897   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2898 }
2899
2900 /**
2901  * g_idle_remove_by_data:
2902  * @data: the data for the idle source's callback.
2903  * 
2904  * Removes the idle function with the given data.
2905  * 
2906  * Return value: %TRUE if an idle source was found and removed.
2907  **/
2908 gboolean
2909 g_idle_remove_by_data (gpointer data)
2910 {
2911   return g_source_remove_by_funcs_user_data (&idle_funcs, data);
2912 }
2913