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