Fix mispelling in help output. (#53952, Skip Montanaro)
[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       UNLOCK_CONTEXT (context);
1659       return FALSE;
1660     }
1661
1662 #ifdef G_THREADS_ENABLED
1663   if (context->poll_waiting)
1664     {
1665       g_warning("g_main_context_prepare(): main loop already active in another thread");
1666       UNLOCK_CONTEXT (context);
1667       return FALSE;
1668     }
1669   
1670   context->poll_waiting = TRUE;
1671 #endif /* G_THREADS_ENABLED */
1672
1673 #if 0
1674   /* If recursing, finish up current dispatch, before starting over */
1675   if (context->pending_dispatches)
1676     {
1677       if (dispatch)
1678         g_main_dispatch (context, &current_time);
1679       
1680       UNLOCK_CONTEXT (context);
1681       return TRUE;
1682     }
1683 #endif
1684
1685   /* If recursing, clear list of pending dispatches */
1686   g_ptr_array_set_size (context->pending_dispatches, 0);
1687   
1688   /* Prepare all sources */
1689
1690   context->timeout = -1;
1691   
1692   source = next_valid_source (context, NULL);
1693   while (source)
1694     {
1695       gint source_timeout = -1;
1696
1697       if ((n_ready > 0) && (source->priority > current_priority))
1698         {
1699           SOURCE_UNREF (source, context);
1700           break;
1701         }
1702       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1703         goto next;
1704
1705       if (!(source->flags & G_SOURCE_READY))
1706         {
1707           gboolean result;
1708           gboolean (*prepare)  (GSource  *source, 
1709                                 gint     *timeout);
1710
1711           prepare = source->source_funcs->prepare;
1712           context->in_check_or_prepare++;
1713           UNLOCK_CONTEXT (context);
1714
1715           result = (*prepare) (source, &source_timeout);
1716
1717           LOCK_CONTEXT (context);
1718           context->in_check_or_prepare--;
1719
1720           if (result)
1721             source->flags |= G_SOURCE_READY;
1722         }
1723
1724       if (source->flags & G_SOURCE_READY)
1725         {
1726           n_ready++;
1727           current_priority = source->priority;
1728           context->timeout = 0;
1729         }
1730       
1731       if (source_timeout >= 0)
1732         {
1733           if (context->timeout < 0)
1734             context->timeout = source_timeout;
1735           else
1736             context->timeout = MIN (context->timeout, source_timeout);
1737         }
1738
1739     next:
1740       source = next_valid_source (context, source);
1741     }
1742
1743   UNLOCK_CONTEXT (context);
1744   
1745   if (priority)
1746     *priority = current_priority;
1747   
1748   return (n_ready > 0);
1749 }
1750
1751 /**
1752  * g_main_context_query:
1753  * @context: a #GMainContext
1754  * @max_priority: maximum priority source to check
1755  * @timeout: location to store timeout to be used in polling
1756  * @fds: location to store #GPollFD records that need to be polled.
1757  * @n_fds: length of @fds.
1758  * 
1759  * Determines information necessary to poll this main loop.
1760  * 
1761  * Return value: 
1762  **/
1763 gint
1764 g_main_context_query (GMainContext *context,
1765                       gint          max_priority,
1766                       gint         *timeout,
1767                       GPollFD      *fds,
1768                       gint          n_fds)
1769 {
1770   gint n_poll;
1771   GPollRec *pollrec;
1772   
1773   LOCK_CONTEXT (context);
1774
1775   pollrec = context->poll_records;
1776   n_poll = 0;
1777   while (pollrec && max_priority >= pollrec->priority)
1778     {
1779       if (pollrec->fd->events)
1780         {
1781           if (n_poll < n_fds)
1782             {
1783               fds[n_poll].fd = pollrec->fd->fd;
1784               /* In direct contradiction to the Unix98 spec, IRIX runs into
1785                * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1786                * flags in the events field of the pollfd while it should
1787                * just ignoring them. So we mask them out here.
1788                */
1789               fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1790               fds[n_poll].revents = 0;
1791             }
1792           n_poll++;
1793         }
1794       
1795       pollrec = pollrec->next;
1796     }
1797
1798 #ifdef G_THREADS_ENABLED
1799   context->poll_changed = FALSE;
1800 #endif
1801   
1802   if (timeout)
1803     {
1804       *timeout = context->timeout;
1805       if (timeout != 0)
1806         context->time_is_current = FALSE;
1807     }
1808   
1809   UNLOCK_CONTEXT (context);
1810
1811   return n_poll;
1812 }
1813
1814 /**
1815  * g_main_context_check:
1816  * @context: a #GMainContext
1817  * @max_priority: the maximum numerical priority of sources to check
1818  * @fds: array of #GPollFD's that was passed to the last call to
1819  *       g_main_context_query()
1820  * @n_fds: return value of g_main_context_query()
1821  * 
1822  * Pass the results of polling back to the main loop.
1823  * 
1824  * Return value: %TRUE if some sources are ready to be dispatched.
1825  **/
1826 gboolean
1827 g_main_context_check (GMainContext *context,
1828                       gint          max_priority,
1829                       GPollFD      *fds,
1830                       gint          n_fds)
1831 {
1832   GSource *source;
1833   GPollRec *pollrec;
1834   gint n_ready = 0;
1835   gint i;
1836   
1837   LOCK_CONTEXT (context);
1838
1839   if (context->in_check_or_prepare)
1840     {
1841       g_warning ("g_main_context_check() called recursively from within a source's check() or "
1842                  "prepare() member.");
1843       UNLOCK_CONTEXT (context);
1844       return FALSE;
1845     }
1846   
1847 #ifdef G_THREADS_ENABLED
1848   if (!context->poll_waiting)
1849     {
1850 #ifndef G_OS_WIN32
1851       gchar c;
1852       read (context->wake_up_pipe[0], &c, 1);
1853 #endif
1854     }
1855   else
1856     context->poll_waiting = FALSE;
1857
1858   /* If the set of poll file descriptors changed, bail out
1859    * and let the main loop rerun
1860    */
1861   if (context->poll_changed)
1862     {
1863       UNLOCK_CONTEXT (context);
1864       return 0;
1865     }
1866 #endif /* G_THREADS_ENABLED */
1867   
1868   pollrec = context->poll_records;
1869   i = 0;
1870   while (i < n_fds)
1871     {
1872       if (pollrec->fd->events)
1873         {
1874           pollrec->fd->revents = fds[i].revents;
1875           i++;
1876         }
1877       pollrec = pollrec->next;
1878     }
1879
1880   source = next_valid_source (context, NULL);
1881   while (source)
1882     {
1883       if ((n_ready > 0) && (source->priority > max_priority))
1884         {
1885           SOURCE_UNREF (source, context);
1886           break;
1887         }
1888       if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1889         goto next;
1890
1891       if (!(source->flags & G_SOURCE_READY))
1892         {
1893           gboolean result;
1894           gboolean (*check) (GSource  *source);
1895
1896           check = source->source_funcs->check;
1897           
1898           context->in_check_or_prepare++;
1899           UNLOCK_CONTEXT (context);
1900           
1901           result = (*check) (source);
1902           
1903           LOCK_CONTEXT (context);
1904           context->in_check_or_prepare--;
1905           
1906           if (result)
1907             source->flags |= G_SOURCE_READY;
1908         }
1909
1910       if (source->flags & G_SOURCE_READY)
1911         {
1912           source->ref_count++;
1913           g_ptr_array_add (context->pending_dispatches, source);
1914
1915           n_ready++;
1916         }
1917
1918     next:
1919       source = next_valid_source (context, source);
1920     }
1921
1922   UNLOCK_CONTEXT (context);
1923
1924   return n_ready > 0;
1925 }
1926
1927 /**
1928  * g_main_context_dispatch:
1929  * @context: a #GMainContext
1930  * 
1931  * Dispatch all pending sources()
1932  **/
1933 void
1934 g_main_context_dispatch (GMainContext *context)
1935 {
1936   LOCK_CONTEXT (context);
1937
1938   if (context->pending_dispatches->len > 0)
1939     {
1940       g_main_dispatch (context);
1941     }
1942
1943   UNLOCK_CONTEXT (context);
1944 }
1945
1946 static gboolean
1947 g_main_context_iterate (GMainContext *context,
1948                         gboolean      block,
1949                         gboolean      dispatch)
1950 {
1951   gint max_priority;
1952   gint timeout;
1953   gboolean some_ready;
1954   gint nfds, new_nfds;
1955   GPollFD *fds;
1956   
1957   some_ready = g_main_context_prepare (context, &max_priority);
1958
1959   do
1960     {
1961       LOCK_CONTEXT (context);
1962
1963       if (context->cached_poll_array)
1964         {
1965           nfds = context->cached_poll_array_size;
1966           fds = context->cached_poll_array;
1967           context->cached_poll_array = NULL;
1968         }
1969       else
1970         {
1971           nfds = context->cached_poll_array_size = context->n_poll_records;
1972           fds = g_new (GPollFD, nfds);
1973         }
1974
1975       UNLOCK_CONTEXT (context);
1976   
1977       new_nfds = g_main_context_query (context, max_priority,
1978                                        &timeout, fds, nfds);
1979     }
1980   while (new_nfds > nfds);
1981
1982   if (!block)
1983     timeout = 0;
1984   
1985   g_main_context_poll (context, timeout, max_priority,
1986                        fds, new_nfds);
1987
1988   g_main_context_check (context,
1989                         max_priority,
1990                         fds, new_nfds);
1991
1992   LOCK_CONTEXT (context);
1993
1994   g_assert (!context->cached_poll_array);
1995   
1996   context->cached_poll_array = fds;
1997   context->cached_poll_array_size = nfds;
1998
1999   UNLOCK_CONTEXT (context);
2000   
2001   if (dispatch)
2002     g_main_context_dispatch (context);
2003
2004   return some_ready;
2005 }
2006
2007 /**
2008  * g_main_context_pending:
2009  * @context: a #GMainContext (if %NULL, the default context will be used)
2010  *
2011  * Check if any sources have pending events for the given context.
2012  * 
2013  * Return value: %TRUE if events are pending.
2014  **/
2015 gboolean 
2016 g_main_context_pending (GMainContext *context)
2017 {
2018   if (!context)
2019     context = g_main_context_default();
2020   
2021   return g_main_context_iterate (context, FALSE, FALSE);
2022 }
2023
2024 /**
2025  * g_main_context_iteration:
2026  * @context: a #GMainContext (if %NULL, the default context will be used) 
2027  * @may_block: whether the call may block.
2028  * 
2029  * Run a single iteration for the given main loop. This involves
2030  * checking to see if any event sources are ready to be processed,
2031  * then if no events sources are ready and @may_block is %TRUE, waiting
2032  * for a source to become ready, then dispatching the highest priority
2033  * events sources that are ready. Note that even when @may_block is %TRUE,
2034  * it is still possible for g_main_context_iteration() to return
2035  * %FALSE, since the the wait may be interrupted for other
2036  * reasons than an event source becoming ready.
2037  * 
2038  * Return value: %TRUE if events were dispatched.
2039  **/
2040 gboolean
2041 g_main_context_iteration (GMainContext *context, gboolean may_block)
2042 {
2043   if (!context)
2044     context = g_main_context_default();
2045   
2046   return g_main_context_iterate (context, may_block, TRUE);
2047 }
2048
2049 /**
2050  * g_main_loop_new:
2051  * @context: a #GMainContext  (if %NULL, the default context will be used).
2052  * @is_running: set to TRUE to indicate that the loop is running. This
2053  * is not very important since calling g_main_run() will set this to
2054  * TRUE anyway.
2055  * 
2056  * Create a new #GMainLoop structure
2057  * 
2058  * Return value: 
2059  **/
2060 GMainLoop *
2061 g_main_loop_new (GMainContext *context,
2062                  gboolean      is_running)
2063 {
2064   GMainLoop *loop;
2065   
2066   if (!context)
2067     context = g_main_context_default();
2068   
2069   loop = g_new0 (GMainLoop, 1);
2070   loop->context = context;
2071   loop->is_running = is_running != FALSE;
2072   loop->ref_count = 1;
2073   
2074 #ifdef G_THREADS_ENABLED
2075   if (g_thread_supported ())
2076     loop->mutex = g_mutex_new ();
2077   else
2078     loop->mutex = NULL;
2079   loop->sem_cond = NULL;
2080 #endif /* G_THREADS_ENABLED */
2081
2082   return loop;
2083 }
2084
2085 /**
2086  * g_main_loop_ref:
2087  * @loop: a #GMainLoop
2088  * 
2089  * Increase the reference count on a #GMainLoop object by one.
2090  * 
2091  * Return value: @loop
2092  **/
2093 GMainLoop *
2094 g_main_loop_ref (GMainLoop *loop)
2095 {
2096   g_return_val_if_fail (loop != NULL, NULL);
2097
2098   LOCK_LOOP (loop);
2099   loop->ref_count++;
2100   UNLOCK_LOOP (loop);
2101
2102   return loop;
2103 }
2104
2105 static void
2106 main_loop_destroy (GMainLoop *loop)
2107 {
2108 #ifdef G_THREADS_ENABLED
2109   g_mutex_free (loop->mutex);
2110   if (loop->sem_cond)
2111     g_cond_free (loop->sem_cond);
2112 #endif /* G_THREADS_ENABLED */  
2113   
2114   g_free (loop);
2115 }
2116
2117 /**
2118  * g_main_loop_unref:
2119  * @loop: a #GMainLoop
2120  * 
2121  * Decreases the reference count on a #GMainLoop object by one. If
2122  * the result is zero, free the loop and free all associated memory.
2123  **/
2124 void
2125 g_main_loop_unref (GMainLoop *loop)
2126 {
2127   g_return_if_fail (loop != NULL);
2128   g_return_if_fail (loop->ref_count > 0);
2129
2130   LOCK_LOOP (loop);
2131   
2132   loop->ref_count--;
2133   if (loop->ref_count == 0)
2134     {
2135       /* When the ref_count is 0, there can be nobody else using the
2136        * loop, so it is safe to unlock before destroying.
2137        */
2138       UNLOCK_LOOP (loop);
2139       main_loop_destroy (loop);
2140     }
2141   else
2142     UNLOCK_LOOP (loop);
2143 }
2144
2145 /**
2146  * g_main_loop_run:
2147  * @loop: a #GMainLoop
2148  * 
2149  * Run a main loop until g_main_quit() is called on the loop.
2150  * If this is called for the thread of the loop's #GMainContext,
2151  * it will process events from the loop, otherwise it will
2152  * simply wait.
2153  **/
2154 void 
2155 g_main_loop_run (GMainLoop *loop)
2156 {
2157   g_return_if_fail (loop != NULL);
2158
2159   /* The assumption here is that a reference is held to the loop
2160    * until we recursively iterate
2161    */
2162 #ifdef G_THREADS_ENABLED
2163   if (loop->context->thread != g_thread_self ())
2164     {
2165       LOCK_LOOP (loop);
2166
2167       loop->ref_count++;
2168       
2169       if (!g_thread_supported ())
2170         {
2171           g_warning ("g_main_loop_run() was called from second thread but"
2172                      "g_thread_init() was never called.");
2173         }
2174       else
2175         {
2176           if (!loop->sem_cond)
2177             loop->sem_cond = g_cond_new ();
2178           
2179           if (!loop->is_running)
2180             loop->is_running = TRUE;
2181           
2182           while (loop->is_running)
2183             g_cond_wait (loop->sem_cond, loop->mutex);
2184         }
2185     }
2186   else
2187 #endif /* G_THREADS_ENABLED */    
2188     {
2189       LOCK_CONTEXT (loop->context);
2190       if (loop->context->in_check_or_prepare)
2191         {
2192           g_warning ("g_main_run(): called recursively from within a source's check() or "
2193                      "prepare() member, iteration not possible.");
2194           return;
2195         }
2196       UNLOCK_CONTEXT (loop->context);
2197       
2198       LOCK_LOOP (loop);
2199
2200       loop->ref_count++;
2201       loop->is_running = TRUE;
2202       while (loop->is_running)
2203         {
2204           UNLOCK_LOOP (loop);
2205           g_main_context_iterate (loop->context, TRUE, TRUE);
2206           LOCK_LOOP (loop);
2207         }
2208     }
2209
2210   /* We inline this here rather than calling g_main_loop_unref() to
2211    * avoid an extra unlock/lock.
2212    */
2213   loop->ref_count--;
2214   if (loop->ref_count == 0)
2215     {
2216       UNLOCK_LOOP (loop);
2217       main_loop_destroy (loop);
2218     }
2219   else
2220     UNLOCK_LOOP (loop);
2221 }
2222
2223 /**
2224  * g_main_loop_quit:
2225  * @loop: a #GMainLoop
2226  * 
2227  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2228  * for the loop will return.
2229  **/
2230 void 
2231 g_main_loop_quit (GMainLoop *loop)
2232 {
2233   g_return_if_fail (loop != NULL);
2234
2235   LOCK_LOOP (loop);
2236   loop->is_running = FALSE;
2237
2238 #ifdef G_THREADS_ENABLED
2239   if (loop->sem_cond)
2240     g_cond_broadcast (loop->sem_cond);
2241 #endif
2242   
2243   UNLOCK_LOOP (loop);
2244
2245   LOCK_CONTEXT (loop->context);
2246   
2247   g_main_context_wakeup (loop->context);
2248   UNLOCK_CONTEXT (loop->context);
2249 }
2250
2251 /**
2252  * g_main_loop_is_running:
2253  * @loop: a #GMainLoop.
2254  * 
2255  * Check to see if the main loop is currently being run via g_main_run()
2256  * 
2257  * Return value: %TRUE if the mainloop is currently being run.
2258  **/
2259 gboolean
2260 g_main_loop_is_running (GMainLoop *loop)
2261 {
2262   gboolean result;
2263   
2264   g_return_val_if_fail (loop != NULL, FALSE);
2265
2266   LOCK_LOOP (loop);
2267   result = loop->is_running;
2268   UNLOCK_LOOP (loop);
2269
2270   return result;
2271 }
2272
2273 /* HOLDS: context's lock */
2274 static void
2275 g_main_context_poll (GMainContext *context,
2276                      gint          timeout,
2277                      gint          priority,
2278                      GPollFD      *fds,
2279                      gint          n_fds)
2280 {
2281 #ifdef  G_MAIN_POLL_DEBUG
2282   GTimer *poll_timer;
2283   GPollRec *pollrec;
2284   gint i;
2285 #endif
2286
2287   GPollFunc poll_func;
2288
2289   if (n_fds || timeout != 0)
2290     {
2291 #ifdef  G_MAIN_POLL_DEBUG
2292       g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2293       poll_timer = g_timer_new ();
2294 #endif
2295
2296       LOCK_CONTEXT (context);
2297
2298       poll_func = context->poll_func;
2299       
2300       UNLOCK_CONTEXT (context);
2301       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2302         g_warning ("poll(2) failed due to: %s.",
2303                    g_strerror (errno));
2304       
2305 #ifdef  G_MAIN_POLL_DEBUG
2306       LOCK_CONTEXT (context);
2307
2308       g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2309                n_fds,
2310                timeout,
2311                g_timer_elapsed (poll_timer, NULL));
2312       g_timer_destroy (poll_timer);
2313       pollrec = context->poll_records;
2314       i = 0;
2315       while (i < n_fds)
2316         {
2317           if (pollrec->fd->events)
2318             {
2319               if (fds[i].revents)
2320                 {
2321                   g_print (" [%d:", fds[i].fd);
2322                   if (fds[i].revents & G_IO_IN)
2323                     g_print ("i");
2324                   if (fds[i].revents & G_IO_OUT)
2325                     g_print ("o");
2326                   if (fds[i].revents & G_IO_PRI)
2327                     g_print ("p");
2328                   if (fds[i].revents & G_IO_ERR)
2329                     g_print ("e");
2330                   if (fds[i].revents & G_IO_HUP)
2331                     g_print ("h");
2332                   if (fds[i].revents & G_IO_NVAL)
2333                     g_print ("n");
2334                   g_print ("]");
2335                 }
2336               i++;
2337             }
2338           pollrec = pollrec->next;
2339         }
2340       g_print ("\n");
2341       
2342       UNLOCK_CONTEXT (context);
2343 #endif
2344     } /* if (n_fds || timeout != 0) */
2345 }
2346
2347 /**
2348  * g_main_context_add_poll:
2349  * @context: a #GMainContext (or %NULL for the default context)
2350  * @fd: a #GPollFD structure holding information about a file
2351  *      descriptor to watch.
2352  * @priority: the priority for this file descriptor which should be
2353  *      the same as the priority used for g_source_attach() to ensure that the
2354  *      file descriptor is polled whenever the results may be needed.
2355  * 
2356  * Add a file descriptor to the set of file descriptors polled * for
2357  * this context. This will very seldom be used directly. Instead
2358  * a typical event source will use g_source_add_poll() instead.
2359  **/
2360 void
2361 g_main_context_add_poll (GMainContext *context,
2362                          GPollFD      *fd,
2363                          gint          priority)
2364 {
2365   if (!context)
2366     context = g_main_context_default ();
2367   
2368   LOCK_CONTEXT (context);
2369   g_main_context_add_poll_unlocked (context, priority, fd);
2370   UNLOCK_CONTEXT (context);
2371 }
2372
2373 /* HOLDS: main_loop_lock */
2374 static void 
2375 g_main_context_add_poll_unlocked (GMainContext *context,
2376                                   gint          priority,
2377                                   GPollFD      *fd)
2378 {
2379   GPollRec *lastrec, *pollrec, *newrec;
2380
2381   if (!context->poll_chunk)
2382     context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2383
2384   if (context->poll_free_list)
2385     {
2386       newrec = context->poll_free_list;
2387       context->poll_free_list = newrec->next;
2388     }
2389   else
2390     newrec = g_chunk_new (GPollRec, context->poll_chunk);
2391
2392   /* This file descriptor may be checked before we ever poll */
2393   fd->revents = 0;
2394   newrec->fd = fd;
2395   newrec->priority = priority;
2396
2397   lastrec = NULL;
2398   pollrec = context->poll_records;
2399   while (pollrec && priority >= pollrec->priority)
2400     {
2401       lastrec = pollrec;
2402       pollrec = pollrec->next;
2403     }
2404   
2405   if (lastrec)
2406     lastrec->next = newrec;
2407   else
2408     context->poll_records = newrec;
2409
2410   newrec->next = pollrec;
2411
2412   context->n_poll_records++;
2413   if (context->cached_poll_array &&
2414       context->cached_poll_array_size < context->n_poll_records)
2415     {
2416       g_free (context->cached_poll_array);
2417       context->cached_poll_array = NULL;
2418     }
2419
2420 #ifdef G_THREADS_ENABLED
2421   context->poll_changed = TRUE;
2422
2423   /* Now wake up the main loop if it is waiting in the poll() */
2424   g_main_context_wakeup (context);
2425 #endif
2426 }
2427
2428 /**
2429  * g_main_context_remove_poll:
2430  * @context:a #GMainContext 
2431  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2432  * 
2433  * Remove file descriptor from the set of file descriptors to be
2434  * polled for a particular context.
2435  **/
2436 void
2437 g_main_context_remove_poll (GMainContext *context,
2438                             GPollFD      *fd)
2439 {
2440   if (!context)
2441     context = g_main_context_default ();
2442   
2443   LOCK_CONTEXT (context);
2444
2445   g_main_context_remove_poll_unlocked (context, fd);
2446   
2447   UNLOCK_CONTEXT (context);
2448 }
2449
2450 static void
2451 g_main_context_remove_poll_unlocked (GMainContext *context,
2452                                      GPollFD      *fd)
2453 {
2454   GPollRec *pollrec, *lastrec;
2455
2456   lastrec = NULL;
2457   pollrec = context->poll_records;
2458
2459   while (pollrec)
2460     {
2461       if (pollrec->fd == fd)
2462         {
2463           if (lastrec != NULL)
2464             lastrec->next = pollrec->next;
2465           else
2466             context->poll_records = pollrec->next;
2467
2468 #ifdef ENABLE_GC_FRIENDLY
2469           pollrec->fd = NULL;  
2470 #endif /* ENABLE_GC_FRIENDLY */
2471
2472           pollrec->next = context->poll_free_list;
2473           context->poll_free_list = pollrec;
2474
2475           context->n_poll_records--;
2476           break;
2477         }
2478       lastrec = pollrec;
2479       pollrec = pollrec->next;
2480     }
2481
2482 #ifdef G_THREADS_ENABLED
2483   context->poll_changed = TRUE;
2484   
2485   /* Now wake up the main loop if it is waiting in the poll() */
2486   g_main_context_wakeup (context);
2487 #endif
2488 }
2489
2490 /**
2491  * g_source_get_current_time:
2492  * @source:  a #GSource
2493  * @timeval: #GTimeVal structure in which to store current time.
2494  * 
2495  * Gets the "current time" to be used when checking 
2496  * this source. The advantage of calling this function over
2497  * calling g_get_current_time() directly is that when 
2498  * checking multiple sources, GLib can cache a single value
2499  * instead of having to repeatedly get the system time.
2500  **/
2501 void
2502 g_source_get_current_time (GSource  *source,
2503                            GTimeVal *timeval)
2504 {
2505   GMainContext *context;
2506   
2507   g_return_if_fail (source->context != NULL);
2508  
2509   context = source->context;
2510
2511   LOCK_CONTEXT (context);
2512
2513   if (!context->time_is_current)
2514     {
2515       g_get_current_time (&context->current_time);
2516       context->time_is_current = TRUE;
2517     }
2518   
2519   *timeval = context->current_time;
2520   
2521   UNLOCK_CONTEXT (context);
2522 }
2523
2524 /**
2525  * g_main_context_set_poll_func:
2526  * @context: a #GMainContext
2527  * @func: the function to call to poll all file descriptors
2528  * 
2529  * Sets the function to use to handle polling of file descriptors. It
2530  * will be used instead of the poll() system call (or GLib's
2531  * replacement function, which is used where poll() isn't available).
2532  *
2533  * This function could possibly be used to integrate the GLib event
2534  * loop with an external event loop.
2535  **/
2536 void
2537 g_main_context_set_poll_func (GMainContext *context,
2538                               GPollFunc     func)
2539 {
2540   if (!context)
2541     context = g_main_context_default ();
2542   
2543   LOCK_CONTEXT (context);
2544   
2545   if (func)
2546     context->poll_func = func;
2547   else
2548     {
2549 #ifdef HAVE_POLL
2550       context->poll_func = (GPollFunc) poll;
2551 #else
2552       context->poll_func = (GPollFunc) g_poll;
2553 #endif
2554     }
2555
2556   UNLOCK_CONTEXT (context);
2557 }
2558
2559 /**
2560  * g_main_context_get_poll_func:
2561  * @context: a #GMainContext
2562  * 
2563  * Gets the poll function set by g_main_context_set_poll_func()
2564  * 
2565  * Return value: the poll function
2566  **/
2567 GPollFunc
2568 g_main_context_get_poll_func (GMainContext *context)
2569 {
2570   GPollFunc result;
2571   
2572   if (!context)
2573     context = g_main_context_default ();
2574   
2575   LOCK_CONTEXT (context);
2576   result = context->poll_func;
2577   UNLOCK_CONTEXT (context);
2578
2579   return result;
2580 }
2581
2582 /* HOLDS: context's lock */
2583 /* Wake the main loop up from a poll() */
2584 static void
2585 g_main_context_wakeup (GMainContext *context)
2586 {
2587 #ifdef G_THREADS_ENABLED
2588   if (g_thread_supported() && context->poll_waiting)
2589     {
2590       context->poll_waiting = FALSE;
2591 #ifndef G_OS_WIN32
2592       write (context->wake_up_pipe[1], "A", 1);
2593 #else
2594       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2595 #endif
2596     }
2597 #endif
2598 }
2599
2600 /* Timeouts */
2601
2602 static void
2603 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2604                           GTimeVal       *current_time)
2605 {
2606   guint seconds = timeout_source->interval / 1000;
2607   guint msecs = timeout_source->interval - seconds * 1000;
2608
2609   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2610   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2611   if (timeout_source->expiration.tv_usec >= 1000000)
2612     {
2613       timeout_source->expiration.tv_usec -= 1000000;
2614       timeout_source->expiration.tv_sec++;
2615     }
2616 }
2617
2618 static gboolean
2619 g_timeout_prepare  (GSource  *source,
2620                     gint     *timeout)
2621 {
2622   glong msec;
2623   GTimeVal current_time;
2624   
2625   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2626
2627   g_source_get_current_time (source, &current_time);
2628   
2629   msec = ((timeout_source->expiration.tv_sec  - current_time.tv_sec) * 1000 +
2630           (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2631
2632   if (msec < 0)
2633     msec = 0;
2634   else if (msec > timeout_source->interval)
2635     {
2636       /* The system time has been set backwards, so we
2637        * reset the expiration time to now + timeout_source->interval;
2638        * this at least avoids hanging for long periods of time.
2639        */
2640       g_timeout_set_expiration (timeout_source, &current_time);
2641       msec = timeout_source->interval;
2642     }
2643   
2644   *timeout = msec;
2645   
2646   return msec == 0;
2647 }
2648
2649 static gboolean 
2650 g_timeout_check (GSource  *source)
2651 {
2652   GTimeVal current_time;
2653   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2654
2655   g_source_get_current_time (source, &current_time);
2656   
2657   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2658           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2659            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2660 }
2661
2662 static gboolean
2663 g_timeout_dispatch (GSource    *source,
2664                     GSourceFunc callback,
2665                     gpointer    user_data)
2666 {
2667   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2668
2669   if (!callback)
2670     {
2671       g_warning ("Timeout source dispatched without callback\n"
2672                  "You must call g_source_set_callback().");
2673       return FALSE;
2674     }
2675  
2676   if (callback (user_data))
2677     {
2678       GTimeVal current_time;
2679
2680       g_source_get_current_time (source, &current_time);
2681       g_timeout_set_expiration (timeout_source, &current_time);
2682
2683       return TRUE;
2684     }
2685   else
2686     return FALSE;
2687 }
2688
2689 /**
2690  * g_timeout_source_new:
2691  * @interval: the timeout interval in milliseconds.
2692  * 
2693  * Create a new timeout source.
2694  *
2695  * The source will not initially be associated with any #GMainContext
2696  * and must be added to one with g_source_attach() before it will be
2697  * executed.
2698  * 
2699  * Return value: the newly create timeout source
2700  **/
2701 GSource *
2702 g_timeout_source_new (guint interval)
2703 {
2704   GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2705   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2706   GTimeVal current_time;
2707
2708   timeout_source->interval = interval;
2709
2710   g_get_current_time (&current_time);
2711   g_timeout_set_expiration (timeout_source, &current_time);
2712   
2713   return source;
2714 }
2715
2716 /**
2717  * g_timeout_add_full:
2718  * @priority: the priority of the idle source. Typically this will be in the
2719  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2720  * @interval: the time between calls to the function, in milliseconds
2721  *             (1/1000ths of a second.)
2722  * @function: function to call
2723  * @data:     data to pass to @function
2724  * @notify:   function to call when the idle is removed, or %NULL
2725  * 
2726  * Sets a function to be called at regular intervals, with the given
2727  * priority.  The function is called repeatedly until it returns
2728  * FALSE, at which point the timeout is automatically destroyed and
2729  * the function will not be called again.  The @notify function is
2730  * called when the timeout is destroyed.  The first call to the
2731  * function will be at the end of the first @interval.
2732  *
2733  * Note that timeout functions may be delayed, due to the processing of other
2734  * event sources. Thus they should not be relied on for precise timing.
2735  * After each call to the timeout function, the time of the next
2736  * timeout is recalculated based on the current time and the given interval
2737  * (it does not try to 'catch up' time lost in delays).
2738  * 
2739  * Return value: the id of event source.
2740  **/
2741 guint
2742 g_timeout_add_full (gint           priority,
2743                     guint          interval,
2744                     GSourceFunc    function,
2745                     gpointer       data,
2746                     GDestroyNotify notify)
2747 {
2748   GSource *source;
2749   guint id;
2750   
2751   g_return_val_if_fail (function != NULL, 0);
2752
2753   source = g_timeout_source_new (interval);
2754
2755   if (priority != G_PRIORITY_DEFAULT)
2756     g_source_set_priority (source, priority);
2757
2758   g_source_set_callback (source, function, data, notify);
2759   id = g_source_attach (source, NULL);
2760   g_source_unref (source);
2761
2762   return id;
2763 }
2764
2765 /**
2766  * g_timeout_add:
2767  * @interval: the time between calls to the function, in milliseconds
2768  *             (1/1000ths of a second.)
2769  * @function: function to call
2770  * @data:     data to pass to @function
2771  * 
2772  * Sets a function to be called at regular intervals, with the default
2773  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
2774  * until it returns FALSE, at which point the timeout is automatically
2775  * destroyed and the function will not be called again.  The @notify
2776  * function is called when the timeout is destroyed.  The first call
2777  * to the function will be at the end of the first @interval.
2778  *
2779  * Note that timeout functions may be delayed, due to the processing of other
2780  * event sources. Thus they should not be relied on for precise timing.
2781  * After each call to the timeout function, the time of the next
2782  * timeout is recalculated based on the current time and the given interval
2783  * (it does not try to 'catch up' time lost in delays).
2784  * 
2785  * Return value: the id of event source.
2786  **/
2787 guint 
2788 g_timeout_add (guint32        interval,
2789                GSourceFunc    function,
2790                gpointer       data)
2791 {
2792   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
2793                              interval, function, data, NULL);
2794 }
2795
2796 /* Idle functions */
2797
2798 static gboolean 
2799 g_idle_prepare  (GSource  *source,
2800                  gint     *timeout)
2801 {
2802   *timeout = 0;
2803
2804   return TRUE;
2805 }
2806
2807 static gboolean 
2808 g_idle_check    (GSource  *source)
2809 {
2810   return TRUE;
2811 }
2812
2813 static gboolean
2814 g_idle_dispatch (GSource    *source, 
2815                  GSourceFunc callback,
2816                  gpointer    user_data)
2817 {
2818   if (!callback)
2819     {
2820       g_warning ("Idle source dispatched without callback\n"
2821                  "You must call g_source_set_callback().");
2822       return FALSE;
2823     }
2824   
2825   return callback (user_data);
2826 }
2827
2828 /**
2829  * g_idle_source_new:
2830  * 
2831  * Create a new idle source.
2832  *
2833  * The source will not initially be associated with any #GMainContext
2834  * and must be added to one with g_source_attach() before it will be
2835  * executed.
2836  * 
2837  * Return value: the newly created idle source
2838  **/
2839 GSource *
2840 g_idle_source_new (void)
2841 {
2842   return g_source_new (&idle_funcs, sizeof (GSource));
2843 }
2844
2845 /**
2846  * g_idle_add_full:
2847  * @priority: the priority of the idle source. Typically this will be in the
2848  *            range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2849  * @function: function to call
2850  * @data:     data to pass to @function
2851  * @notify:   function to call when the idle is removed, or %NULL
2852  * 
2853  * Adds a function to be called whenever there are no higher priority
2854  * events pending.  If the function returns FALSE it is automatically
2855  * removed from the list of event sources and will not be called again.
2856  * 
2857  * Return value: the id of the event source.
2858  **/
2859 guint 
2860 g_idle_add_full (gint           priority,
2861                  GSourceFunc    function,
2862                  gpointer       data,
2863                  GDestroyNotify notify)
2864 {
2865   GSource *source;
2866   guint id;
2867   
2868   g_return_val_if_fail (function != NULL, 0);
2869
2870   source = g_idle_source_new ();
2871
2872   if (priority != G_PRIORITY_DEFAULT)
2873     g_source_set_priority (source, priority);
2874
2875   g_source_set_callback (source, function, data, notify);
2876   id = g_source_attach (source, NULL);
2877   g_source_unref (source);
2878
2879   return id;
2880 }
2881
2882 /**
2883  * g_idle_add:
2884  * @function: function to call 
2885  * @data: data to pass to @function.
2886  * 
2887  * Adds a function to be called whenever there are no higher priority
2888  * events pending to the default main loop. The function is given the
2889  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
2890  * returns FALSE it is automatically removed from the list of event
2891  * sources and will not be called again.
2892  * 
2893  * Return value: the id of the event source.
2894  **/
2895 guint 
2896 g_idle_add (GSourceFunc    function,
2897             gpointer       data)
2898 {
2899   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2900 }
2901
2902 /**
2903  * g_idle_remove_by_data:
2904  * @data: the data for the idle source's callback.
2905  * 
2906  * Removes the idle function with the given data.
2907  * 
2908  * Return value: %TRUE if an idle source was found and removed.
2909  **/
2910 gboolean
2911 g_idle_remove_by_data (gpointer data)
2912 {
2913   return g_source_remove_by_funcs_user_data (&idle_funcs, data);
2914 }
2915