1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
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.
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.
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.
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/.
36 /* uncomment the next line to get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
40 #include <sys/types.h>
42 #ifdef HAVE_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 */
52 #endif /* HAVE_UNISTD_H */
58 #endif /* G_OS_WIN32 */
61 #include <net/socket.h>
62 #endif /* G_OS_BEOS */
66 typedef struct _GTimeoutSource GTimeoutSource;
67 typedef struct _GPollRec GPollRec;
68 typedef struct _GSourceCallback GSourceCallback;
72 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
73 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
78 #ifdef G_THREADS_ENABLED
79 /* The following lock is used for both the list of sources
80 * and the list of poll records
86 GPtrArray *pending_dispatches;
87 gint timeout; /* Timeout for current iteration */
91 gint in_check_or_prepare;
93 GPollRec *poll_records;
94 GPollRec *poll_free_list;
95 GMemChunk *poll_chunk;
97 GPollFD *cached_poll_array;
98 gint cached_poll_array_size;
100 #ifdef G_THREADS_ENABLED
102 /* this pipe is used to wake up the main loop when a source is added.
104 gint wake_up_pipe[2];
105 #else /* G_OS_WIN32 */
106 HANDLE wake_up_semaphore;
107 #endif /* G_OS_WIN32 */
110 gboolean poll_waiting;
112 /* Flag indicating whether the set of fd's changed during a poll */
113 gboolean poll_changed;
114 #endif /* G_THREADS_ENABLED */
118 GTimeVal current_time;
119 gboolean time_is_current;
122 struct _GSourceCallback
127 GDestroyNotify notify;
132 GMainContext *context;
136 #ifdef G_THREADS_ENABLED
139 #endif /* G_THREADS_ENABLED */
142 struct _GTimeoutSource
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)
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
168 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
170 #define SOURCE_UNREF(source, context) \
172 if ((source)->ref_count > 1) \
173 (source)->ref_count--; \
175 g_source_unref_internal ((source), (context), TRUE); \
179 /* Forward declarations */
181 static void g_source_unref_internal (GSource *source,
182 GMainContext *context,
184 static void g_source_destroy_internal (GSource *source,
185 GMainContext *context,
187 static void g_main_context_poll (GMainContext *context,
192 static void g_main_context_add_poll_unlocked (GMainContext *context,
195 static void g_main_context_remove_poll_unlocked (GMainContext *context,
197 static void g_main_context_wakeup (GMainContext *context);
199 static gboolean g_timeout_prepare (GSource *source,
201 static gboolean g_timeout_check (GSource *source);
202 static gboolean g_timeout_dispatch (GSource *source,
203 GSourceFunc callback,
205 static gboolean g_idle_prepare (GSource *source,
207 static gboolean g_idle_check (GSource *source);
208 static gboolean g_idle_dispatch (GSource *source,
209 GSourceFunc callback,
212 G_LOCK_DEFINE_STATIC (main_loop);
213 static GMainContext *default_main_context;
215 static GSourceFuncs timeout_funcs =
223 static GSourceFuncs idle_funcs =
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);
236 #else /* !HAVE_POLL */
241 g_poll (GPollFD *fds,
245 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
246 gboolean poll_msgs = FALSE;
253 for (f = fds; f < &fds[nfds]; ++f)
256 if (f->events & G_IO_IN)
258 if (f->fd == G_WIN32_MSG_HANDLE)
262 #ifdef G_MAIN_POLL_DEBUG
263 g_print ("g_poll: waiting for %#x\n", f->fd);
265 handles[nhandles++] = (HANDLE) f->fd;
275 /* Waiting for messages, and maybe events
276 * -> First PeekMessage
278 #ifdef G_MAIN_POLL_DEBUG
279 g_print ("PeekMessage\n");
281 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
282 ready = WAIT_OBJECT_0 + nhandles;
287 /* Waiting just for messages */
288 if (timeout == INFINITE)
293 #ifdef G_MAIN_POLL_DEBUG
294 g_print ("WaitMessage\n");
297 g_warning (G_STRLOC ": WaitMessage() failed");
298 ready = WAIT_OBJECT_0 + nhandles;
300 else if (timeout == 0)
302 /* Waiting just for messages, zero timeout.
303 * If we got here, there was no message
305 ready = WAIT_TIMEOUT;
309 /* Waiting just for messages, some timeout
310 * -> Set a timer, wait for message,
311 * kill timer, use PeekMessage
313 timer = SetTimer (NULL, 0, timeout, NULL);
315 g_warning (G_STRLOC ": SetTimer() failed");
318 #ifdef G_MAIN_POLL_DEBUG
319 g_print ("WaitMessage\n");
322 KillTimer (NULL, timer);
323 #ifdef G_MAIN_POLL_DEBUG
324 g_print ("PeekMessage\n");
326 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
327 && msg.message != WM_TIMER)
328 ready = WAIT_OBJECT_0;
330 ready = WAIT_TIMEOUT;
336 /* Wait for either message or event
337 * -> Use MsgWaitForMultipleObjects
339 #ifdef G_MAIN_POLL_DEBUG
340 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
342 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
343 timeout, QS_ALLINPUT);
345 if (ready == WAIT_FAILED)
346 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
350 else if (nhandles == 0)
352 /* Wait for nothing (huh?) */
357 /* Wait for just events
358 * -> Use WaitForMultipleObjects
360 #ifdef G_MAIN_POLL_DEBUG
361 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
363 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
364 if (ready == WAIT_FAILED)
365 g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
368 #ifdef G_MAIN_POLL_DEBUG
369 g_print ("wait returns %d%s\n",
371 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
372 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
373 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
375 for (f = fds; f < &fds[nfds]; ++f)
378 if (ready == WAIT_FAILED)
380 else if (ready == WAIT_TIMEOUT)
382 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
384 for (f = fds; f < &fds[nfds]; ++f)
387 if (f->events & G_IO_IN)
388 if (f->fd == G_WIN32_MSG_HANDLE)
389 f->revents |= G_IO_IN;
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)
396 if ((f->events & G_IO_IN)
397 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
399 f->revents |= G_IO_IN;
400 #ifdef G_MAIN_POLL_DEBUG
401 g_print ("g_poll: got event %#x\n", f->fd);
404 ResetEvent ((HANDLE) f->fd);
413 #else /* !G_OS_WIN32 */
415 /* The following implementation of poll() comes from the GNU C Library.
416 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
419 #include <string.h> /* for bzero on BSD systems */
421 #ifdef HAVE_SYS_SELECT_H
422 #include <sys/select.h>
423 #endif /* HAVE_SYS_SELECT_H */
427 #endif /* G_OS_BEOS */
430 # define SELECT_MASK fd_set
431 #else /* !NO_FD_SET */
433 typedef long fd_mask;
436 # define SELECT_MASK void
438 # define SELECT_MASK int
439 # endif /* !_IBMR2 */
440 #endif /* !NO_FD_SET */
443 g_poll (GPollFD *fds,
448 SELECT_MASK rset, wset, xset;
457 for (f = fds; f < &fds[nfds]; ++f)
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)))
470 tv.tv_sec = timeout / 1000;
471 tv.tv_usec = (timeout % 1000) * 1000;
473 ready = select (maxfd + 1, &rset, &wset, &xset,
474 timeout == -1 ? NULL : &tv);
476 for (f = fds; f < &fds[nfds]; ++f)
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;
493 #endif /* !G_OS_WIN32 */
495 #endif /* !HAVE_POLL */
497 /* Called to clean up when a thread terminates
500 g_main_context_destroy (GMainContext *context)
504 /* We need the lock here only because g_source_destroy expects
505 * to be able to unlock when destroying the source's data
507 LOCK_CONTEXT (context);
508 source = context->source_list;
511 GSource *next = source->next;
512 g_source_destroy_internal (source, context, TRUE);
515 UNLOCK_CONTEXT (context);
517 #ifdef G_THREADS_ENABLED
518 g_mutex_free (context->mutex);
521 g_ptr_array_free (context->pending_dispatches, TRUE);
522 g_free (context->cached_poll_array);
524 g_mem_chunk_destroy (context->poll_chunk);
526 #ifdef G_THREADS_ENABLED
527 if (g_thread_supported())
530 close (context->wake_up_pipe[0]);
531 close (context->wake_up_pipe[1]);
533 CloseHandle (context->wake_up_semaphore);
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;
547 GMainContext *context;
551 * g_main_context_get:
552 * @thread: a #GThread
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.
558 * Return value: the main loop context for @thread.
561 g_main_context_get (GThread *thread)
563 GRealThread *real_thread = (GRealThread*)thread;
564 GMainContext *context;
566 g_return_val_if_fail (thread != NULL, NULL);
568 if (g_thread_supported ())
569 context = real_thread->context;
571 context = default_main_context;
575 context = g_new0 (GMainContext, 1);
577 #ifdef G_THREADS_ENABLED
578 if (g_thread_supported ())
579 context->mutex = g_mutex_new();
581 context->thread = thread;
584 context->next_id = 1;
586 context->source_list = NULL;
589 context->poll_func = (GPollFunc)poll;
591 context->poll_func = g_poll;
594 context->cached_poll_array = NULL;
595 context->cached_poll_array_size = 0;
597 context->pending_dispatches = g_ptr_array_new ();
599 context->time_is_current = FALSE;
601 #ifdef G_THREADS_ENABLED
602 if (g_thread_supported ())
605 if (pipe (context->wake_up_pipe) < 0)
606 g_error ("Cannot create pipe main loop wake-up: %s\n",
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);
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);
622 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
627 if (g_thread_supported ())
628 real_thread->context = context;
630 default_main_context = context;
637 * g_main_context_default:
639 * Return the default main context. This is the main context used
640 * for main loop functions when a main loop is not explicitly
643 * Return value: the default main context.
646 g_main_context_default (void)
652 if (!default_main_context)
653 default_main_context = g_main_context_get (g_thread_self ());
655 G_UNLOCK (main_loop);
657 return default_main_context;
660 /* Hooks for adding to the main loop */
664 * @source_funcs: structure containing functions that implement
665 * the sources behavior.
666 * @struct_size: size of the #GSource structure to create
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
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
677 * Return value: the newly create #GSource
680 g_source_new (GSourceFuncs *source_funcs,
685 g_return_val_if_fail (source_funcs != NULL, NULL);
686 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
688 source = (GSource*) g_malloc0 (struct_size);
690 source->source_funcs = source_funcs;
691 source->ref_count = 1;
693 source->priority = G_PRIORITY_DEFAULT;
695 source->flags = G_HOOK_FLAG_ACTIVE;
697 /* NULL/0 initialization for all other fields */
702 /* Holds context's lock
705 g_source_list_add (GSource *source,
706 GMainContext *context)
708 GSource *tmp_source, *last_source;
711 tmp_source = context->source_list;
712 while (tmp_source && tmp_source->priority <= source->priority)
714 last_source = tmp_source;
715 tmp_source = tmp_source->next;
718 source->next = tmp_source;
720 tmp_source->prev = source;
722 source->prev = last_source;
724 last_source->next = source;
726 context->source_list = source;
729 /* Holds context's lock
732 g_source_list_remove (GSource *source,
733 GMainContext *context)
736 source->prev->next = source->next;
738 context->source_list = source->next;
741 source->next->prev = source->prev;
749 * @source: a #GSource
750 * @context: a #GMainContext (if %NULL, the default context will be used)
752 * Adds a #GSource to a @context so that it will be executed within
755 * Return value: the ID for the source within the #GMainContext
758 g_source_attach (GSource *source,
759 GMainContext *context)
764 g_return_val_if_fail (source->context == NULL, 0);
765 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
768 context = g_main_context_default ();
770 LOCK_CONTEXT (context);
772 source->context = context;
773 result = source->id = context->next_id++;
776 g_source_list_add (source, context);
778 tmp_list = source->poll_fds;
781 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
782 tmp_list = tmp_list->next;
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);
790 UNLOCK_CONTEXT (context);
796 g_source_destroy_internal (GSource *source,
797 GMainContext *context,
801 LOCK_CONTEXT (context);
803 if (!SOURCE_DESTROYED (source))
806 gpointer old_cb_data;
807 GSourceCallbackFuncs *old_cb_funcs;
809 source->flags &= ~G_HOOK_FLAG_ACTIVE;
811 old_cb_data = source->callback_data;
812 old_cb_funcs = source->callback_funcs;
814 source->callback_data = NULL;
815 source->callback_funcs = NULL;
819 UNLOCK_CONTEXT (context);
820 old_cb_funcs->unref (old_cb_data);
821 LOCK_CONTEXT (context);
824 tmp_list = source->poll_fds;
827 g_main_context_remove_poll_unlocked (context, tmp_list->data);
828 tmp_list = tmp_list->next;
831 g_source_unref_internal (source, context, TRUE);
835 UNLOCK_CONTEXT (context);
840 * @source: a #GSource
842 * Remove a source from its #GMainContext, if any, and mark it as
843 * destroyed. The source cannot be subsequently added to another
847 g_source_destroy (GSource *source)
849 GMainContext *context;
851 g_return_if_fail (source != NULL);
853 context = source->context;
856 g_source_destroy_internal (source, context, FALSE);
858 source->flags &= ~G_HOOK_FLAG_ACTIVE;
863 * @source: a #GSource
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().
869 * Return value: the ID for the source
872 g_source_get_id (GSource *source)
876 g_return_val_if_fail (source != NULL, 0);
877 g_return_val_if_fail (source->context != NULL, 0);
879 LOCK_CONTEXT (source->context);
881 UNLOCK_CONTEXT (source->context);
887 * g_source_get_context:
888 * @source: a #GSource
890 * Get the #GMainContext with which the source is associated.
891 * Calling this function on a destroyed source is an error.
893 * Return value: the #GMainContext with which the source is associated,
894 * or %NULL if the context has not yet been added
898 g_source_get_context (GSource *source)
900 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
902 return source->context;
908 * @fd: a #GPollFD structure holding information about a file
909 * descriptor to watch.
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
918 g_source_add_poll (GSource *source,
921 GMainContext *context;
923 g_return_if_fail (source != NULL);
924 g_return_if_fail (fd != NULL);
925 g_return_if_fail (!SOURCE_DESTROYED (source));
927 context = source->context;
930 LOCK_CONTEXT (context);
932 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
936 g_main_context_add_poll_unlocked (context, source->priority, fd);
937 UNLOCK_CONTEXT (context);
942 * g_source_remove_poll:
944 * @fd: a #GPollFD structure previously passed to g_source_poll.
946 * Remove a file descriptor from the set of file descriptors polled for
950 g_source_remove_poll (GSource *source,
953 GMainContext *context;
955 g_return_if_fail (source != NULL);
956 g_return_if_fail (fd != NULL);
957 g_return_if_fail (!SOURCE_DESTROYED (source));
959 context = source->context;
962 LOCK_CONTEXT (context);
964 source->poll_fds = g_slist_remove (source->poll_fds, fd);
968 g_main_context_remove_poll_unlocked (context, fd);
969 UNLOCK_CONTEXT (context);
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
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.
988 g_source_set_callback_indirect (GSource *source,
989 gpointer callback_data,
990 GSourceCallbackFuncs *callback_funcs)
992 GMainContext *context;
993 gpointer old_cb_data;
994 GSourceCallbackFuncs *old_cb_funcs;
996 g_return_if_fail (source != NULL);
997 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
999 context = source->context;
1002 LOCK_CONTEXT (context);
1004 old_cb_data = source->callback_data;
1005 old_cb_funcs = source->callback_funcs;
1007 source->callback_data = callback_data;
1008 source->callback_funcs = callback_funcs;
1011 UNLOCK_CONTEXT (context);
1014 old_cb_funcs->unref (old_cb_data);
1018 g_source_callback_ref (gpointer cb_data)
1020 GSourceCallback *callback = cb_data;
1022 callback->ref_count++;
1027 g_source_callback_unref (gpointer cb_data)
1029 GSourceCallback *callback = cb_data;
1031 callback->ref_count--;
1032 if (callback->ref_count == 0)
1034 if (callback->notify)
1035 callback->notify (callback->data);
1041 g_source_callback_get (gpointer cb_data,
1045 GSourceCallback *callback = cb_data;
1047 *func = callback->func;
1048 *data = callback->data;
1051 static GSourceCallbackFuncs g_source_callback_funcs = {
1052 g_source_callback_ref,
1053 g_source_callback_unref,
1054 g_source_callback_get,
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.
1064 * Set the callback function for a source.
1067 g_source_set_callback (GSource *source,
1070 GDestroyNotify notify)
1072 GSourceCallback *new_callback;
1074 g_return_if_fail (source != NULL);
1076 new_callback = g_new (GSourceCallback, 1);
1078 new_callback->ref_count = 1;
1079 new_callback->func = func;
1080 new_callback->data = data;
1081 new_callback->notify = notify;
1083 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1087 * g_source_set_priority:
1088 * @source: a #GSource
1089 * @priority: the new priority.
1091 * Set the priority of a source. While the main loop is being
1092 * run, a source will
1095 g_source_set_priority (GSource *source,
1099 GMainContext *context;
1101 g_return_if_fail (source != NULL);
1103 context = source->context;
1106 LOCK_CONTEXT (context);
1108 source->priority = priority;
1112 source->next = NULL;
1113 source->prev = NULL;
1115 tmp_list = source->poll_fds;
1118 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1119 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1121 tmp_list = tmp_list->next;
1124 UNLOCK_CONTEXT (source->context);
1129 * g_source_get_priority:
1130 * @source: a #GSource
1132 * Gets the priority of a surce
1134 * Return value: the priority of the source
1137 g_source_get_priority (GSource *source)
1139 g_return_val_if_fail (source != NULL, 0);
1141 return source->priority;
1145 * g_source_set_can_recurse:
1146 * @source: a #GSource
1147 * @can_recurse: whether recursion is allowed for this source
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.
1155 g_source_set_can_recurse (GSource *source,
1156 gboolean can_recurse)
1158 GMainContext *context;
1160 g_return_if_fail (source != NULL);
1162 context = source->context;
1165 LOCK_CONTEXT (context);
1168 source->flags |= G_SOURCE_CAN_RECURSE;
1170 source->flags &= ~G_SOURCE_CAN_RECURSE;
1173 UNLOCK_CONTEXT (context);
1177 * g_source_get_can_recurse:
1178 * @source: a #GSource
1180 * Checks whether a source is allowed to be called recursively.
1181 * see g_source_set_can_recurse.
1183 * Return value: whether recursion is allowed.
1186 g_source_get_can_recurse (GSource *source)
1188 g_return_val_if_fail (source != NULL, FALSE);
1190 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1195 * @source: a #GSource
1197 * Increases the reference count on a source by one.
1199 * Return value: @source
1202 g_source_ref (GSource *source)
1204 GMainContext *context;
1206 g_return_val_if_fail (source != NULL, NULL);
1208 context = source->context;
1211 LOCK_CONTEXT (context);
1213 source->ref_count++;
1216 UNLOCK_CONTEXT (context);
1221 /* g_source_unref() but possible to call within context lock
1224 g_source_unref_internal (GSource *source,
1225 GMainContext *context,
1228 gpointer old_cb_data = NULL;
1229 GSourceCallbackFuncs *old_cb_funcs = NULL;
1231 g_return_if_fail (source != NULL);
1233 if (!have_lock && context)
1234 LOCK_CONTEXT (context);
1236 source->ref_count--;
1237 if (source->ref_count == 0)
1239 old_cb_data = source->callback_data;
1240 old_cb_funcs = source->callback_funcs;
1242 source->callback_data = NULL;
1243 source->callback_funcs = NULL;
1245 if (context && !SOURCE_DESTROYED (source))
1247 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1248 source->ref_count++;
1251 g_source_list_remove (source, context);
1253 if (source->source_funcs->destroy)
1254 source->source_funcs->destroy (source);
1256 g_slist_free (source->poll_fds);
1257 source->poll_fds = NULL;
1261 if (!have_lock && context)
1262 UNLOCK_CONTEXT (context);
1267 UNLOCK_CONTEXT (context);
1269 old_cb_funcs->unref (old_cb_data);
1272 LOCK_CONTEXT (context);
1278 * @source: a #GSource
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.
1285 g_source_unref (GSource *source)
1287 g_return_if_fail (source != NULL);
1289 g_source_unref_internal (source, source->context, FALSE);
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()
1297 * Finds a #GSource given a pair of context and ID
1299 * Return value: the #GSource if found, otherwise, %NULL
1302 g_main_context_find_source_by_id (GMainContext *context,
1307 g_return_val_if_fail (id > 0, FALSE);
1309 if (context == NULL)
1310 context = g_main_context_default ();
1312 LOCK_CONTEXT (context);
1314 source = context->source_list;
1317 if (!SOURCE_DESTROYED (source) &&
1320 source = source->next;
1323 UNLOCK_CONTEXT (context);
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.
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.
1338 * Return value: the source, if one was found, otherwise %NULL
1341 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1342 GSourceFuncs *funcs,
1347 g_return_val_if_fail (funcs != NULL, FALSE);
1349 if (context == NULL)
1350 context = g_main_context_default ();
1352 LOCK_CONTEXT (context);
1354 source = context->source_list;
1357 if (!SOURCE_DESTROYED (source) &&
1358 source->source_funcs == funcs &&
1359 source->callback_data == user_data)
1361 source = source->next;
1364 UNLOCK_CONTEXT (context);
1370 * g_main_context_find_source_by_user_data:
1371 * @context: a #GMainContext
1372 * @user_data: the user_data for the callback.
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.
1378 * Return value: the source, if one was found, otherwise %NULL
1381 g_main_context_find_source_by_user_data (GMainContext *context,
1386 if (context == NULL)
1387 context = g_main_context_default ();
1389 LOCK_CONTEXT (context);
1391 source = context->source_list;
1394 if (!SOURCE_DESTROYED (source) &&
1395 source->callback_data == user_data)
1397 source = source->next;
1400 UNLOCK_CONTEXT (context);
1407 * @tag: the id of the source to remove.
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().
1415 * See also g_source_destroy().
1417 * Return value: %TRUE if the source was found and removed.
1420 g_source_remove (guint tag)
1424 g_return_val_if_fail (tag > 0, FALSE);
1426 source = g_main_context_find_source_by_id (NULL, tag);
1428 g_source_destroy (source);
1430 return source != NULL;
1434 * g_source_remove_by_user_data:
1435 * @user_data: the user_data for the callback.
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.
1441 * Return value: %TRUE if a source was found and removed.
1444 g_source_remove_by_user_data (gpointer user_data)
1448 source = g_main_context_find_source_by_user_data (NULL, user_data);
1451 g_source_destroy (source);
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
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.
1467 * Return value: %TRUE if a source was found and removed.
1470 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1475 g_return_val_if_fail (funcs != NULL, FALSE);
1477 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1480 g_source_destroy (source);
1488 * g_get_current_time:
1489 * @result: #GTimeVal structure in which to store current time.
1491 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1494 g_get_current_time (GTimeVal *result)
1499 g_return_if_fail (result != NULL);
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;
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.
1511 static DWORD start_tick = 0;
1512 static time_t start_time;
1515 g_return_if_fail (result != NULL);
1517 if (start_tick == 0)
1519 start_tick = GetTickCount ();
1523 tick = GetTickCount ();
1525 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1526 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1530 /* Running the main loop */
1532 /* HOLDS: context's lock */
1534 g_main_dispatch (GMainContext *context)
1538 for (i = 0; i < context->pending_dispatches->len; i++)
1540 GSource *source = context->pending_dispatches->pdata[i];
1542 context->pending_dispatches->pdata[i] = NULL;
1545 source->flags &= ~G_SOURCE_READY;
1547 if (!SOURCE_DESTROYED (source))
1549 gboolean was_in_call;
1550 gpointer user_data = NULL;
1551 GSourceFunc callback = NULL;
1552 GSourceCallbackFuncs *cb_funcs;
1554 gboolean need_destroy;
1556 gboolean (*dispatch) (GSource *,
1560 dispatch = source->source_funcs->dispatch;
1561 cb_funcs = source->callback_funcs;
1562 cb_data = source->callback_data;
1565 cb_funcs->ref (cb_data);
1567 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1568 source->flags |= G_HOOK_FLAG_IN_CALL;
1570 UNLOCK_CONTEXT (context);
1573 cb_funcs->get (cb_data, &callback, &user_data);
1575 need_destroy = ! dispatch (source,
1578 LOCK_CONTEXT (context);
1581 cb_funcs->unref (cb_data);
1584 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1586 /* Note: this depends on the fact that we can't switch
1587 * sources from one main context to another
1589 if (need_destroy && !SOURCE_DESTROYED (source))
1591 g_assert (source->context == context);
1592 g_source_destroy_internal (source, context, TRUE);
1596 SOURCE_UNREF (source, context);
1599 g_ptr_array_set_size (context->pending_dispatches, 0);
1602 /* Holds context's lock */
1603 static inline GSource *
1604 next_valid_source (GMainContext *context,
1607 GSource *new_source = source ? source->next : context->source_list;
1611 if (!SOURCE_DESTROYED (new_source))
1613 new_source->ref_count++;
1617 new_source = new_source->next;
1621 SOURCE_UNREF (source, context);
1628 * g_main_context_prepare:
1629 * @context: a #GMainContext
1630 * @priority: location to store priority of highest priority
1631 * source already ready.
1633 * Prepares to poll sources within a main loop. The resulting information
1634 * for polling is determined by calling g_main_context_query ().
1636 * Return value: %TRUE if some source is ready to be dispatched
1640 g_main_context_prepare (GMainContext *context,
1644 gint current_priority = G_MAXINT;
1647 if (context == NULL)
1648 context = g_main_context_default ();
1650 LOCK_CONTEXT (context);
1652 context->time_is_current = FALSE;
1654 if (context->in_check_or_prepare)
1656 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1657 "prepare() member.");
1658 UNLOCK_CONTEXT (context);
1662 #ifdef G_THREADS_ENABLED
1663 if (context->poll_waiting)
1665 g_warning("g_main_context_prepare(): main loop already active in another thread");
1666 UNLOCK_CONTEXT (context);
1670 context->poll_waiting = TRUE;
1671 #endif /* G_THREADS_ENABLED */
1674 /* If recursing, finish up current dispatch, before starting over */
1675 if (context->pending_dispatches)
1678 g_main_dispatch (context, ¤t_time);
1680 UNLOCK_CONTEXT (context);
1685 /* If recursing, clear list of pending dispatches */
1686 g_ptr_array_set_size (context->pending_dispatches, 0);
1688 /* Prepare all sources */
1690 context->timeout = -1;
1692 source = next_valid_source (context, NULL);
1695 gint source_timeout = -1;
1697 if ((n_ready > 0) && (source->priority > current_priority))
1699 SOURCE_UNREF (source, context);
1702 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1705 if (!(source->flags & G_SOURCE_READY))
1708 gboolean (*prepare) (GSource *source,
1711 prepare = source->source_funcs->prepare;
1712 context->in_check_or_prepare++;
1713 UNLOCK_CONTEXT (context);
1715 result = (*prepare) (source, &source_timeout);
1717 LOCK_CONTEXT (context);
1718 context->in_check_or_prepare--;
1721 source->flags |= G_SOURCE_READY;
1724 if (source->flags & G_SOURCE_READY)
1727 current_priority = source->priority;
1728 context->timeout = 0;
1731 if (source_timeout >= 0)
1733 if (context->timeout < 0)
1734 context->timeout = source_timeout;
1736 context->timeout = MIN (context->timeout, source_timeout);
1740 source = next_valid_source (context, source);
1743 UNLOCK_CONTEXT (context);
1746 *priority = current_priority;
1748 return (n_ready > 0);
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.
1759 * Determines information necessary to poll this main loop.
1764 g_main_context_query (GMainContext *context,
1773 LOCK_CONTEXT (context);
1775 pollrec = context->poll_records;
1777 while (pollrec && max_priority >= pollrec->priority)
1779 if (pollrec->fd->events)
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.
1789 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1790 fds[n_poll].revents = 0;
1795 pollrec = pollrec->next;
1798 #ifdef G_THREADS_ENABLED
1799 context->poll_changed = FALSE;
1804 *timeout = context->timeout;
1806 context->time_is_current = FALSE;
1809 UNLOCK_CONTEXT (context);
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()
1822 * Pass the results of polling back to the main loop.
1824 * Return value: %TRUE if some sources are ready to be dispatched.
1827 g_main_context_check (GMainContext *context,
1837 LOCK_CONTEXT (context);
1839 if (context->in_check_or_prepare)
1841 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1842 "prepare() member.");
1843 UNLOCK_CONTEXT (context);
1847 #ifdef G_THREADS_ENABLED
1848 if (!context->poll_waiting)
1852 read (context->wake_up_pipe[0], &c, 1);
1856 context->poll_waiting = FALSE;
1858 /* If the set of poll file descriptors changed, bail out
1859 * and let the main loop rerun
1861 if (context->poll_changed)
1863 UNLOCK_CONTEXT (context);
1866 #endif /* G_THREADS_ENABLED */
1868 pollrec = context->poll_records;
1872 if (pollrec->fd->events)
1874 pollrec->fd->revents = fds[i].revents;
1877 pollrec = pollrec->next;
1880 source = next_valid_source (context, NULL);
1883 if ((n_ready > 0) && (source->priority > max_priority))
1885 SOURCE_UNREF (source, context);
1888 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1891 if (!(source->flags & G_SOURCE_READY))
1894 gboolean (*check) (GSource *source);
1896 check = source->source_funcs->check;
1898 context->in_check_or_prepare++;
1899 UNLOCK_CONTEXT (context);
1901 result = (*check) (source);
1903 LOCK_CONTEXT (context);
1904 context->in_check_or_prepare--;
1907 source->flags |= G_SOURCE_READY;
1910 if (source->flags & G_SOURCE_READY)
1912 source->ref_count++;
1913 g_ptr_array_add (context->pending_dispatches, source);
1919 source = next_valid_source (context, source);
1922 UNLOCK_CONTEXT (context);
1928 * g_main_context_dispatch:
1929 * @context: a #GMainContext
1931 * Dispatch all pending sources()
1934 g_main_context_dispatch (GMainContext *context)
1936 LOCK_CONTEXT (context);
1938 if (context->pending_dispatches->len > 0)
1940 g_main_dispatch (context);
1943 UNLOCK_CONTEXT (context);
1947 g_main_context_iterate (GMainContext *context,
1953 gboolean some_ready;
1954 gint nfds, new_nfds;
1957 some_ready = g_main_context_prepare (context, &max_priority);
1961 LOCK_CONTEXT (context);
1963 if (context->cached_poll_array)
1965 nfds = context->cached_poll_array_size;
1966 fds = context->cached_poll_array;
1967 context->cached_poll_array = NULL;
1971 nfds = context->cached_poll_array_size = context->n_poll_records;
1972 fds = g_new (GPollFD, nfds);
1975 UNLOCK_CONTEXT (context);
1977 new_nfds = g_main_context_query (context, max_priority,
1978 &timeout, fds, nfds);
1980 while (new_nfds > nfds);
1985 g_main_context_poll (context, timeout, max_priority,
1988 g_main_context_check (context,
1992 LOCK_CONTEXT (context);
1994 g_assert (!context->cached_poll_array);
1996 context->cached_poll_array = fds;
1997 context->cached_poll_array_size = nfds;
1999 UNLOCK_CONTEXT (context);
2002 g_main_context_dispatch (context);
2008 * g_main_context_pending:
2009 * @context: a #GMainContext (if %NULL, the default context will be used)
2011 * Check if any sources have pending events for the given context.
2013 * Return value: %TRUE if events are pending.
2016 g_main_context_pending (GMainContext *context)
2019 context = g_main_context_default();
2021 return g_main_context_iterate (context, FALSE, FALSE);
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.
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.
2038 * Return value: %TRUE if events were dispatched.
2041 g_main_context_iteration (GMainContext *context, gboolean may_block)
2044 context = g_main_context_default();
2046 return g_main_context_iterate (context, may_block, TRUE);
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
2056 * Create a new #GMainLoop structure
2061 g_main_loop_new (GMainContext *context,
2062 gboolean is_running)
2067 context = g_main_context_default();
2069 loop = g_new0 (GMainLoop, 1);
2070 loop->context = context;
2071 loop->is_running = is_running != FALSE;
2072 loop->ref_count = 1;
2074 #ifdef G_THREADS_ENABLED
2075 if (g_thread_supported ())
2076 loop->mutex = g_mutex_new ();
2079 loop->sem_cond = NULL;
2080 #endif /* G_THREADS_ENABLED */
2087 * @loop: a #GMainLoop
2089 * Increase the reference count on a #GMainLoop object by one.
2091 * Return value: @loop
2094 g_main_loop_ref (GMainLoop *loop)
2096 g_return_val_if_fail (loop != NULL, NULL);
2106 main_loop_destroy (GMainLoop *loop)
2108 #ifdef G_THREADS_ENABLED
2109 g_mutex_free (loop->mutex);
2111 g_cond_free (loop->sem_cond);
2112 #endif /* G_THREADS_ENABLED */
2118 * g_main_loop_unref:
2119 * @loop: a #GMainLoop
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.
2125 g_main_loop_unref (GMainLoop *loop)
2127 g_return_if_fail (loop != NULL);
2128 g_return_if_fail (loop->ref_count > 0);
2133 if (loop->ref_count == 0)
2135 /* When the ref_count is 0, there can be nobody else using the
2136 * loop, so it is safe to unlock before destroying.
2139 main_loop_destroy (loop);
2147 * @loop: a #GMainLoop
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
2155 g_main_loop_run (GMainLoop *loop)
2157 g_return_if_fail (loop != NULL);
2159 /* The assumption here is that a reference is held to the loop
2160 * until we recursively iterate
2162 #ifdef G_THREADS_ENABLED
2163 if (loop->context->thread != g_thread_self ())
2169 if (!g_thread_supported ())
2171 g_warning ("g_main_loop_run() was called from second thread but"
2172 "g_thread_init() was never called.");
2176 if (!loop->sem_cond)
2177 loop->sem_cond = g_cond_new ();
2179 if (!loop->is_running)
2180 loop->is_running = TRUE;
2182 while (loop->is_running)
2183 g_cond_wait (loop->sem_cond, loop->mutex);
2187 #endif /* G_THREADS_ENABLED */
2189 LOCK_CONTEXT (loop->context);
2190 if (loop->context->in_check_or_prepare)
2192 g_warning ("g_main_run(): called recursively from within a source's check() or "
2193 "prepare() member, iteration not possible.");
2196 UNLOCK_CONTEXT (loop->context);
2201 loop->is_running = TRUE;
2202 while (loop->is_running)
2205 g_main_context_iterate (loop->context, TRUE, TRUE);
2210 /* We inline this here rather than calling g_main_loop_unref() to
2211 * avoid an extra unlock/lock.
2214 if (loop->ref_count == 0)
2217 main_loop_destroy (loop);
2225 * @loop: a #GMainLoop
2227 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2228 * for the loop will return.
2231 g_main_loop_quit (GMainLoop *loop)
2233 g_return_if_fail (loop != NULL);
2236 loop->is_running = FALSE;
2238 #ifdef G_THREADS_ENABLED
2240 g_cond_broadcast (loop->sem_cond);
2245 LOCK_CONTEXT (loop->context);
2247 g_main_context_wakeup (loop->context);
2248 UNLOCK_CONTEXT (loop->context);
2252 * g_main_loop_is_running:
2253 * @loop: a #GMainLoop.
2255 * Check to see if the main loop is currently being run via g_main_run()
2257 * Return value: %TRUE if the mainloop is currently being run.
2260 g_main_loop_is_running (GMainLoop *loop)
2264 g_return_val_if_fail (loop != NULL, FALSE);
2267 result = loop->is_running;
2273 /* HOLDS: context's lock */
2275 g_main_context_poll (GMainContext *context,
2281 #ifdef G_MAIN_POLL_DEBUG
2287 GPollFunc poll_func;
2289 if (n_fds || timeout != 0)
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 ();
2296 LOCK_CONTEXT (context);
2298 poll_func = context->poll_func;
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));
2305 #ifdef G_MAIN_POLL_DEBUG
2306 LOCK_CONTEXT (context);
2308 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2311 g_timer_elapsed (poll_timer, NULL));
2312 g_timer_destroy (poll_timer);
2313 pollrec = context->poll_records;
2317 if (pollrec->fd->events)
2321 g_print (" [%d:", fds[i].fd);
2322 if (fds[i].revents & G_IO_IN)
2324 if (fds[i].revents & G_IO_OUT)
2326 if (fds[i].revents & G_IO_PRI)
2328 if (fds[i].revents & G_IO_ERR)
2330 if (fds[i].revents & G_IO_HUP)
2332 if (fds[i].revents & G_IO_NVAL)
2338 pollrec = pollrec->next;
2342 UNLOCK_CONTEXT (context);
2344 } /* if (n_fds || timeout != 0) */
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.
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.
2361 g_main_context_add_poll (GMainContext *context,
2366 context = g_main_context_default ();
2368 LOCK_CONTEXT (context);
2369 g_main_context_add_poll_unlocked (context, priority, fd);
2370 UNLOCK_CONTEXT (context);
2373 /* HOLDS: main_loop_lock */
2375 g_main_context_add_poll_unlocked (GMainContext *context,
2379 GPollRec *lastrec, *pollrec, *newrec;
2381 if (!context->poll_chunk)
2382 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2384 if (context->poll_free_list)
2386 newrec = context->poll_free_list;
2387 context->poll_free_list = newrec->next;
2390 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2392 /* This file descriptor may be checked before we ever poll */
2395 newrec->priority = priority;
2398 pollrec = context->poll_records;
2399 while (pollrec && priority >= pollrec->priority)
2402 pollrec = pollrec->next;
2406 lastrec->next = newrec;
2408 context->poll_records = newrec;
2410 newrec->next = pollrec;
2412 context->n_poll_records++;
2413 if (context->cached_poll_array &&
2414 context->cached_poll_array_size < context->n_poll_records)
2416 g_free (context->cached_poll_array);
2417 context->cached_poll_array = NULL;
2420 #ifdef G_THREADS_ENABLED
2421 context->poll_changed = TRUE;
2423 /* Now wake up the main loop if it is waiting in the poll() */
2424 g_main_context_wakeup (context);
2429 * g_main_context_remove_poll:
2430 * @context:a #GMainContext
2431 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2433 * Remove file descriptor from the set of file descriptors to be
2434 * polled for a particular context.
2437 g_main_context_remove_poll (GMainContext *context,
2441 context = g_main_context_default ();
2443 LOCK_CONTEXT (context);
2445 g_main_context_remove_poll_unlocked (context, fd);
2447 UNLOCK_CONTEXT (context);
2451 g_main_context_remove_poll_unlocked (GMainContext *context,
2454 GPollRec *pollrec, *lastrec;
2457 pollrec = context->poll_records;
2461 if (pollrec->fd == fd)
2463 if (lastrec != NULL)
2464 lastrec->next = pollrec->next;
2466 context->poll_records = pollrec->next;
2468 #ifdef ENABLE_GC_FRIENDLY
2470 #endif /* ENABLE_GC_FRIENDLY */
2472 pollrec->next = context->poll_free_list;
2473 context->poll_free_list = pollrec;
2475 context->n_poll_records--;
2479 pollrec = pollrec->next;
2482 #ifdef G_THREADS_ENABLED
2483 context->poll_changed = TRUE;
2485 /* Now wake up the main loop if it is waiting in the poll() */
2486 g_main_context_wakeup (context);
2491 * g_source_get_current_time:
2492 * @source: a #GSource
2493 * @timeval: #GTimeVal structure in which to store current time.
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.
2502 g_source_get_current_time (GSource *source,
2505 GMainContext *context;
2507 g_return_if_fail (source->context != NULL);
2509 context = source->context;
2511 LOCK_CONTEXT (context);
2513 if (!context->time_is_current)
2515 g_get_current_time (&context->current_time);
2516 context->time_is_current = TRUE;
2519 *timeval = context->current_time;
2521 UNLOCK_CONTEXT (context);
2525 * g_main_context_set_poll_func:
2526 * @context: a #GMainContext
2527 * @func: the function to call to poll all file descriptors
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).
2533 * This function could possibly be used to integrate the GLib event
2534 * loop with an external event loop.
2537 g_main_context_set_poll_func (GMainContext *context,
2541 context = g_main_context_default ();
2543 LOCK_CONTEXT (context);
2546 context->poll_func = func;
2550 context->poll_func = (GPollFunc) poll;
2552 context->poll_func = (GPollFunc) g_poll;
2556 UNLOCK_CONTEXT (context);
2560 * g_main_context_get_poll_func:
2561 * @context: a #GMainContext
2563 * Gets the poll function set by g_main_context_set_poll_func()
2565 * Return value: the poll function
2568 g_main_context_get_poll_func (GMainContext *context)
2573 context = g_main_context_default ();
2575 LOCK_CONTEXT (context);
2576 result = context->poll_func;
2577 UNLOCK_CONTEXT (context);
2582 /* HOLDS: context's lock */
2583 /* Wake the main loop up from a poll() */
2585 g_main_context_wakeup (GMainContext *context)
2587 #ifdef G_THREADS_ENABLED
2588 if (g_thread_supported() && context->poll_waiting)
2590 context->poll_waiting = FALSE;
2592 write (context->wake_up_pipe[1], "A", 1);
2594 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2603 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2604 GTimeVal *current_time)
2606 guint seconds = timeout_source->interval / 1000;
2607 guint msecs = timeout_source->interval - seconds * 1000;
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)
2613 timeout_source->expiration.tv_usec -= 1000000;
2614 timeout_source->expiration.tv_sec++;
2619 g_timeout_prepare (GSource *source,
2623 GTimeVal current_time;
2625 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2627 g_source_get_current_time (source, ¤t_time);
2629 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2630 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2634 else if (msec > timeout_source->interval)
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.
2640 g_timeout_set_expiration (timeout_source, ¤t_time);
2641 msec = timeout_source->interval;
2650 g_timeout_check (GSource *source)
2652 GTimeVal current_time;
2653 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2655 g_source_get_current_time (source, ¤t_time);
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)));
2663 g_timeout_dispatch (GSource *source,
2664 GSourceFunc callback,
2667 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2671 g_warning ("Timeout source dispatched without callback\n"
2672 "You must call g_source_set_callback().");
2676 if (callback (user_data))
2678 GTimeVal current_time;
2680 g_source_get_current_time (source, ¤t_time);
2681 g_timeout_set_expiration (timeout_source, ¤t_time);
2690 * g_timeout_source_new:
2691 * @interval: the timeout interval in milliseconds.
2693 * Create a new timeout source.
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
2699 * Return value: the newly create timeout source
2702 g_timeout_source_new (guint interval)
2704 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2705 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2706 GTimeVal current_time;
2708 timeout_source->interval = interval;
2710 g_get_current_time (¤t_time);
2711 g_timeout_set_expiration (timeout_source, ¤t_time);
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
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.
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).
2739 * Return value: the id of event source.
2742 g_timeout_add_full (gint priority,
2744 GSourceFunc function,
2746 GDestroyNotify notify)
2751 g_return_val_if_fail (function != NULL, 0);
2753 source = g_timeout_source_new (interval);
2755 if (priority != G_PRIORITY_DEFAULT)
2756 g_source_set_priority (source, priority);
2758 g_source_set_callback (source, function, data, notify);
2759 id = g_source_attach (source, NULL);
2760 g_source_unref (source);
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
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.
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).
2785 * Return value: the id of event source.
2788 g_timeout_add (guint32 interval,
2789 GSourceFunc function,
2792 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2793 interval, function, data, NULL);
2796 /* Idle functions */
2799 g_idle_prepare (GSource *source,
2808 g_idle_check (GSource *source)
2814 g_idle_dispatch (GSource *source,
2815 GSourceFunc callback,
2820 g_warning ("Idle source dispatched without callback\n"
2821 "You must call g_source_set_callback().");
2825 return callback (user_data);
2829 * g_idle_source_new:
2831 * Create a new idle source.
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
2837 * Return value: the newly created idle source
2840 g_idle_source_new (void)
2842 return g_source_new (&idle_funcs, sizeof (GSource));
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
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.
2857 * Return value: the id of the event source.
2860 g_idle_add_full (gint priority,
2861 GSourceFunc function,
2863 GDestroyNotify notify)
2868 g_return_val_if_fail (function != NULL, 0);
2870 source = g_idle_source_new ();
2872 if (priority != G_PRIORITY_DEFAULT)
2873 g_source_set_priority (source, priority);
2875 g_source_set_callback (source, function, data, notify);
2876 id = g_source_attach (source, NULL);
2877 g_source_unref (source);
2884 * @function: function to call
2885 * @data: data to pass to @function.
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.
2893 * Return value: the id of the event source.
2896 g_idle_add (GSourceFunc function,
2899 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2903 * g_idle_remove_by_data:
2904 * @data: the data for the idle source's callback.
2906 * Removes the idle function with the given data.
2908 * Return value: %TRUE if an idle source was found and removed.
2911 g_idle_remove_by_data (gpointer data)
2913 return g_source_remove_by_funcs_user_data (&idle_funcs, data);