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;
135 #ifdef G_THREADS_ENABLED
138 #endif /* G_THREADS_ENABLED */
141 struct _GTimeoutSource
155 #ifdef G_THREADS_ENABLED
156 #define LOCK_CONTEXT(context) g_mutex_lock(context->mutex)
157 #define UNLOCK_CONTEXT(context) g_mutex_unlock(context->mutex)
158 #define LOCK_LOOP(loop) g_mutex_lock(loop->mutex)
159 #define UNLOCK_LOOP(loop) g_mutex_unlock(loop->mutex)
161 #define LOCK_CONTEXT(context) (void)0
162 #define UNLOCK_CONTEXT(context) (void)0
163 #define LOCK_LOOP(context) (void)0
164 #define UNLOCK_LOOP(context) (void)0
167 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
169 #define SOURCE_UNREF(source, context) \
171 if ((source)->ref_count > 1) \
172 (source)->ref_count--; \
174 g_source_unref_internal ((source), (context), TRUE); \
178 /* Forward declarations */
180 static void g_source_unref_internal (GSource *source,
181 GMainContext *context,
183 static void g_source_destroy_internal (GSource *source,
184 GMainContext *context,
186 static void g_main_context_poll (GMainContext *context,
191 static void g_main_context_add_poll_unlocked (GMainContext *context,
194 static void g_main_context_remove_poll_unlocked (GMainContext *context,
196 static void g_main_context_wakeup (GMainContext *context);
198 static gboolean g_timeout_prepare (GSource *source,
200 static gboolean g_timeout_check (GSource *source);
201 static gboolean g_timeout_dispatch (GSource *source,
202 GSourceFunc callback,
204 static gboolean g_idle_prepare (GSource *source,
206 static gboolean g_idle_check (GSource *source);
207 static gboolean g_idle_dispatch (GSource *source,
208 GSourceFunc callback,
211 G_LOCK_DEFINE_STATIC (main_loop);
212 static GMainContext *default_main_context;
214 static GSourceFuncs timeout_funcs =
222 static GSourceFuncs idle_funcs =
231 /* SunOS has poll, but doesn't provide a prototype. */
232 # if defined (sun) && !defined (__SVR4)
233 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
235 #else /* !HAVE_POLL */
240 g_poll (GPollFD *fds,
244 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
245 gboolean poll_msgs = FALSE;
252 for (f = fds; f < &fds[nfds]; ++f)
255 if (f->events & G_IO_IN)
257 if (f->fd == G_WIN32_MSG_HANDLE)
261 #ifdef G_MAIN_POLL_DEBUG
262 g_print ("g_poll: waiting for %#x\n", f->fd);
264 handles[nhandles++] = (HANDLE) f->fd;
274 /* Waiting for messages, and maybe events */
277 if (timeout == INFINITE)
279 /* Waiting just for messages, infinite timeout
280 * -> Use PeekMessage, then WaitMessage
282 #ifdef G_MAIN_POLL_DEBUG
283 g_print ("PeekMessage, then WaitMessage\n");
285 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
286 ready = WAIT_OBJECT_0;
287 else if (!WaitMessage ())
288 g_warning ("g_poll: WaitMessage failed");
289 ready = WAIT_OBJECT_0;
291 else if (timeout == 0)
293 /* Waiting just for messages, zero timeout
296 #ifdef G_MAIN_POLL_DEBUG
297 g_print ("PeekMessage\n");
299 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
300 ready = WAIT_OBJECT_0;
302 ready = WAIT_TIMEOUT;
306 /* Waiting just for messages, some timeout
307 * -> First try PeekMessage, then set a timer, wait for message,
308 * kill timer, use PeekMessage
310 #ifdef G_MAIN_POLL_DEBUG
311 g_print ("PeekMessage\n");
313 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
314 ready = WAIT_OBJECT_0;
315 else if ((timer = SetTimer (NULL, 0, timeout, NULL)) == 0)
316 g_warning ("g_poll: SetTimer failed");
319 #ifdef G_MAIN_POLL_DEBUG
320 g_print ("WaitMessage\n");
323 KillTimer (NULL, timer);
324 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
325 && msg.message != WM_TIMER)
326 ready = WAIT_OBJECT_0;
328 ready = WAIT_TIMEOUT;
334 /* Wait for either message or event
335 * -> Use MsgWaitForMultipleObjects
337 #ifdef G_MAIN_POLL_DEBUG
338 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
340 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
341 timeout, QS_ALLINPUT);
343 if (ready == WAIT_FAILED)
344 g_warning ("g_poll: MsgWaitForMultipleObjects failed");
347 else if (nhandles == 0)
349 /* Wait for nothing (huh?) */
354 /* Wait for just events
355 * -> Use WaitForMultipleObjects
357 #ifdef G_MAIN_POLL_DEBUG
358 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
360 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
361 if (ready == WAIT_FAILED)
362 g_warning ("g_poll: WaitForMultipleObjects failed");
365 for (f = fds; f < &fds[nfds]; ++f)
368 if (ready == WAIT_FAILED)
370 else if (ready == WAIT_TIMEOUT)
372 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
374 for (f = fds; f < &fds[nfds]; ++f)
377 if (f->events & G_IO_IN)
378 if (f->fd == G_WIN32_MSG_HANDLE)
379 f->revents |= G_IO_IN;
382 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
383 for (f = fds; f < &fds[nfds]; ++f)
385 if ((f->events & G_IO_IN)
386 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
388 f->revents |= G_IO_IN;
389 #ifdef G_MAIN_POLL_DEBUG
390 g_print ("g_poll: got event %#x\n", f->fd);
393 ResetEvent ((HANDLE) f->fd);
398 if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
399 return ready - WAIT_OBJECT_0 + 1;
404 #else /* !G_OS_WIN32 */
406 /* The following implementation of poll() comes from the GNU C Library.
407 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
410 #include <string.h> /* for bzero on BSD systems */
412 #ifdef HAVE_SYS_SELECT_H
413 #include <sys/select.h>
414 #endif /* HAVE_SYS_SELECT_H */
418 #endif /* G_OS_BEOS */
421 # define SELECT_MASK fd_set
422 #else /* !NO_FD_SET */
424 typedef long fd_mask;
427 # define SELECT_MASK void
429 # define SELECT_MASK int
430 # endif /* !_IBMR2 */
431 #endif /* !NO_FD_SET */
434 g_poll (GPollFD *fds,
439 SELECT_MASK rset, wset, xset;
448 for (f = fds; f < &fds[nfds]; ++f)
451 if (f->events & G_IO_IN)
452 FD_SET (f->fd, &rset);
453 if (f->events & G_IO_OUT)
454 FD_SET (f->fd, &wset);
455 if (f->events & G_IO_PRI)
456 FD_SET (f->fd, &xset);
457 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
461 tv.tv_sec = timeout / 1000;
462 tv.tv_usec = (timeout % 1000) * 1000;
464 ready = select (maxfd + 1, &rset, &wset, &xset,
465 timeout == -1 ? NULL : &tv);
467 for (f = fds; f < &fds[nfds]; ++f)
472 if (FD_ISSET (f->fd, &rset))
473 f->revents |= G_IO_IN;
474 if (FD_ISSET (f->fd, &wset))
475 f->revents |= G_IO_OUT;
476 if (FD_ISSET (f->fd, &xset))
477 f->revents |= G_IO_PRI;
484 #endif /* !G_OS_WIN32 */
486 #endif /* !HAVE_POLL */
488 /* Called to clean up when a thread terminates
491 g_main_context_destroy (GMainContext *context)
495 /* We need the lock here only because g_source_destroy expects
496 * to be able to unlock when destroying the source's data
498 LOCK_CONTEXT (context);
499 source = context->source_list;
502 GSource *next = source->next;
503 g_source_destroy_internal (source, context, TRUE);
506 UNLOCK_CONTEXT (context);
508 #ifdef G_THREADS_ENABLED
509 g_mutex_free (context->mutex);
512 g_ptr_array_free (context->pending_dispatches, TRUE);
513 g_free (context->cached_poll_array);
515 g_mem_chunk_destroy (context->poll_chunk);
517 if (g_thread_supported())
520 close (context->wake_up_pipe[0]);
521 close (context->wake_up_pipe[1]);
523 CloseHandle (context->wake_up_semaphore);
531 * g_main_context_get:
532 * @thread: a #GThread
534 * Retrieves the main loop context for a particular thread. This
535 * will create the main context for the thread if none previously
536 * existed. The context will exist until the thread terminates.
538 * Return value: the main loop context for @thread.
541 g_main_context_get (GThread *thread)
543 static GStaticPrivate private_key = G_STATIC_PRIVATE_INIT;
544 GMainContext *context;
546 g_return_val_if_fail (thread != NULL, NULL);
548 if (g_thread_supported ())
549 context = g_static_private_get_for_thread (&private_key, thread);
551 context = default_main_context;
555 context = g_new0 (GMainContext, 1);
557 #ifdef G_THREADS_ENABLED
558 if (g_thread_supported ())
559 context->mutex = g_mutex_new();
561 context->thread = thread;
564 context->next_id = 1;
566 context->source_list = NULL;
569 context->poll_func = (GPollFunc)poll;
571 context->poll_func = g_poll;
574 context->cached_poll_array = NULL;
575 context->cached_poll_array_size = 0;
577 context->pending_dispatches = g_ptr_array_new ();
579 context->time_is_current = FALSE;
581 #ifdef G_THREADS_ENABLED
582 if (g_thread_supported ())
585 if (pipe (context->wake_up_pipe) < 0)
586 g_error ("Cannot create pipe main loop wake-up: %s\n",
589 context->wake_up_rec.fd = context->wake_up_pipe[0];
590 context->wake_up_rec.events = G_IO_IN;
591 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
593 if ((context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
594 g_error ("Cannot create wake-up semaphore: %s", g_win32_error_message (GetLastError ()));
595 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
596 context->wake_up_rec.events = G_IO_IN;
597 #ifdef G_MAIN_POLL_DEBUG
598 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
600 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
605 if (g_thread_supported ())
606 g_static_private_set_for_thread (&private_key, thread,
608 (GDestroyNotify)g_main_context_destroy);
610 default_main_context = context;
617 * g_main_context_default:
619 * Return the default main context. This is the main context used
620 * for main loop functions when a main loop is not explicitly
623 * Return value: the default main context.
626 g_main_context_default (void)
632 if (!default_main_context)
633 default_main_context = g_main_context_get (g_thread_self ());
635 G_UNLOCK (main_loop);
637 return default_main_context;
640 /* Hooks for adding to the main loop */
644 * @source_funcs: structure containing functions that implement
645 * the sources behavior.
646 * @struct_size: size of the #GSource structure to create
648 * Create a new GSource structure. The size is specified to
649 * allow creating structures derived from GSource that contain
650 * additional data. The size passed in must be at least
653 * The source will not initially be associated with any #GMainContext
654 * and must be added to one with g_source_add() before it will be
657 * Return value: the newly create #GSource
660 g_source_new (GSourceFuncs *source_funcs,
665 g_return_val_if_fail (source_funcs != NULL, NULL);
666 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
668 source = (GSource*) g_malloc0 (struct_size);
670 source->source_funcs = source_funcs;
671 source->ref_count = 1;
673 source->priority = G_PRIORITY_DEFAULT;
675 source->flags = G_HOOK_FLAG_ACTIVE;
677 /* NULL/0 initialization for all other fields */
682 /* Holds context's lock
685 g_source_list_add (GSource *source,
686 GMainContext *context)
688 GSource *tmp_source, *last_source;
691 tmp_source = context->source_list;
692 while (tmp_source && tmp_source->priority <= source->priority)
694 last_source = tmp_source;
695 tmp_source = tmp_source->next;
698 source->next = tmp_source;
700 tmp_source->prev = source;
702 source->prev = last_source;
704 last_source->next = source;
706 context->source_list = source;
709 /* Holds context's lock
712 g_source_list_remove (GSource *source,
713 GMainContext *context)
716 source->prev->next = source->next;
718 context->source_list = source->next;
721 source->next->prev = source->prev;
729 * @source: a #GSource
730 * @context: a #GMainContext (if %NULL, the default context will be used)
732 * Adds a #GSource to a @context so that it will be executed within
735 * Return value: the ID for the source within the #GMainContext
738 g_source_attach (GSource *source,
739 GMainContext *context)
744 g_return_val_if_fail (source->context == NULL, 0);
745 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
748 context = g_main_context_default ();
750 LOCK_CONTEXT (context);
752 source->context = context;
753 result = source->id = context->next_id++;
756 g_source_list_add (source, context);
758 tmp_list = source->poll_fds;
761 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
762 tmp_list = tmp_list->next;
765 #ifdef G_THREADS_ENABLED
766 /* Now wake up the main loop if it is waiting in the poll() */
767 g_main_context_wakeup (context);
770 UNLOCK_CONTEXT (context);
776 g_source_destroy_internal (GSource *source,
777 GMainContext *context,
781 LOCK_CONTEXT (context);
783 if (!SOURCE_DESTROYED (source))
785 gpointer old_cb_data;
786 GSourceCallbackFuncs *old_cb_funcs;
788 source->flags &= ~G_HOOK_FLAG_ACTIVE;
790 old_cb_data = source->callback_data;
791 old_cb_funcs = source->callback_funcs;
793 source->callback_data = NULL;
794 source->callback_funcs = NULL;
798 UNLOCK_CONTEXT (context);
799 old_cb_funcs->unref (old_cb_data);
800 LOCK_CONTEXT (context);
803 g_source_unref_internal (source, context, TRUE);
807 UNLOCK_CONTEXT (context);
812 * @source: a #GSource
814 * Remove a source from its #GMainContext, if any, and mark it as
815 * destroyed. The source cannot be subsequently added to another
819 g_source_destroy (GSource *source)
821 GMainContext *context;
823 g_return_if_fail (source != NULL);
825 context = source->context;
828 g_source_destroy_internal (source, context, FALSE);
830 source->flags &= ~G_HOOK_FLAG_ACTIVE;
835 * @source: a #GSource
837 * Return the numeric ID for a particular source. The ID of a source
838 * is unique within a particular main loop context. The reverse
839 * mapping from ID to source is done by g_main_context_find_source_by_id().
841 * Return value: the ID for the source
844 g_source_get_id (GSource *source)
848 g_return_val_if_fail (source != NULL, 0);
849 g_return_val_if_fail (source->context != NULL, 0);
851 LOCK_CONTEXT (source->context);
853 UNLOCK_CONTEXT (source->context);
859 * g_source_get_context:
860 * @source: a #GSource
862 * Get the #GMainContext with which the source is associated.
863 * Calling this function on a destroyed source is an error.
865 * Return value: the #GMainContext with which the source is associated,
866 * or %NULL if the context has not yet been added
870 g_source_get_context (GSource *source)
872 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
874 return source->context;
878 * g_main_source_add_poll:
880 * @fd: a #GPollFD structure holding information about a file
881 * descriptor to watch.
883 * Add a file descriptor to the set of file descriptors polled * for
884 * this source. This is usually combined with g_source_new() to add an
885 * event source. The event source's check function will typically test
886 * the revents field in the #GPollFD struct and return %TRUE if events need
890 g_source_add_poll (GSource *source,
893 GMainContext *context;
895 g_return_if_fail (source != NULL);
896 g_return_if_fail (fd != NULL);
898 context = source->context;
901 LOCK_CONTEXT (context);
903 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
907 g_main_context_add_poll_unlocked (context, source->priority, fd);
908 UNLOCK_CONTEXT (context);
913 * g_source_set_callback_indirect:
914 * @source: the source
915 * @callback_data: pointer to callback data "object"
916 * @callback_funcs: functions for reference counting callback_data
917 * and getting the callback and data
919 * Set the callback function storing the data as a refcounted callback
920 * "object". This is used to implement g_source_set_callback_closure()
921 * and internally. Note that calling g_source_set_callback_indirect() assumes
922 * an initial reference count on @callback_data, and thus
923 * @callback_funcs->unref will eventually be called once more
924 * than @callback_funcs->ref.
927 g_source_set_callback_indirect (GSource *source,
928 gpointer callback_data,
929 GSourceCallbackFuncs *callback_funcs)
931 GMainContext *context;
932 gpointer old_cb_data;
933 GSourceCallbackFuncs *old_cb_funcs;
935 g_return_if_fail (source != NULL);
936 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
938 context = source->context;
941 LOCK_CONTEXT (context);
943 old_cb_data = source->callback_data;
944 old_cb_funcs = source->callback_funcs;
946 source->callback_data = callback_data;
947 source->callback_funcs = callback_funcs;
950 UNLOCK_CONTEXT (context);
953 old_cb_funcs->unref (old_cb_data);
957 g_source_callback_ref (gpointer cb_data)
959 GSourceCallback *callback = cb_data;
961 callback->ref_count++;
966 g_source_callback_unref (gpointer cb_data)
968 GSourceCallback *callback = cb_data;
970 callback->ref_count--;
971 if (callback->ref_count == 0)
973 if (callback->notify)
974 callback->notify (callback->data);
979 g_source_callback_get (gpointer cb_data,
983 GSourceCallback *callback = cb_data;
985 *func = callback->func;
986 *data = callback->data;
989 static GSourceCallbackFuncs g_source_callback_funcs = {
990 g_source_callback_ref,
991 g_source_callback_unref,
992 g_source_callback_get,
996 * g_source_set_callback:
997 * @source: the source
998 * @func: a callback function
999 * @data: the data to pass to callback function
1000 * @notify: a function to call when @data is no longer in use, or %NULL.
1002 * Set the callback function for a source.
1005 g_source_set_callback (GSource *source,
1008 GDestroyNotify notify)
1010 GSourceCallback *new_callback;
1012 g_return_if_fail (source != NULL);
1014 new_callback = g_new (GSourceCallback, 1);
1016 new_callback->func = func;
1017 new_callback->data = data;
1018 new_callback->notify = notify;
1020 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1024 * g_source_set_priority:
1025 * @source: a #GSource
1026 * @priority: the new priority.
1028 * Set the priority of a source. While the main loop is being
1029 * run, a source will
1032 g_source_set_priority (GSource *source,
1036 GMainContext *context;
1038 g_return_if_fail (source != NULL);
1040 context = source->context;
1043 LOCK_CONTEXT (context);
1045 source->priority = priority;
1049 source->next = NULL;
1050 source->prev = NULL;
1052 tmp_list = source->poll_fds;
1055 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1056 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1058 tmp_list = tmp_list->next;
1061 UNLOCK_CONTEXT (source->context);
1066 * g_source_get_priority:
1067 * @source: a #GSource
1069 * Gets the priority of a surce
1071 * Return value: the priority of the source
1074 g_source_get_priority (GSource *source)
1076 g_return_val_if_fail (source != NULL, 0);
1078 return source->priority;
1082 * g_source_set_can_recurse:
1083 * @source: a #GSource
1084 * @can_recurse: whether recursion is allowed for this source
1086 * Sets whether a source can be called recursively. If @can_recurse is
1087 * %TRUE, then while the source is being dispatched then this source
1088 * will be processed normally. Otherwise, all processing of this
1089 * source is blocked until the dispatch function returns.
1092 g_source_set_can_recurse (GSource *source,
1093 gboolean can_recurse)
1095 GMainContext *context;
1097 g_return_if_fail (source != NULL);
1099 context = source->context;
1102 LOCK_CONTEXT (context);
1105 source->flags |= G_SOURCE_CAN_RECURSE;
1107 source->flags &= ~G_SOURCE_CAN_RECURSE;
1110 UNLOCK_CONTEXT (context);
1114 * g_source_get_can_recurse:
1115 * @source: a #GSource
1117 * Checks whether a source is allowed to be called recursively.
1118 * see g_source_set_can_recurse.
1120 * Return value: whether recursion is allowed.
1123 g_source_get_can_recurse (GSource *source)
1125 g_return_val_if_fail (source != NULL, FALSE);
1127 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1132 * @source: a #GSource
1134 * Increases the reference count on a source by one.
1136 * Return value: @source
1139 g_source_ref (GSource *source)
1141 GMainContext *context;
1143 g_return_val_if_fail (source != NULL, NULL);
1145 context = source->context;
1148 LOCK_CONTEXT (context);
1150 source->ref_count++;
1153 UNLOCK_CONTEXT (context);
1158 /* g_source_unref() but possible to call within context lock
1161 g_source_unref_internal (GSource *source,
1162 GMainContext *context,
1165 gpointer cb_data = NULL;
1166 GSourceCallbackFuncs *cb_funcs = NULL;
1169 g_return_if_fail (source != NULL);
1171 if (!have_lock && context)
1172 LOCK_CONTEXT (context);
1174 source->ref_count--;
1175 if (source->ref_count == 0)
1177 if (context && !SOURCE_DESTROYED (source))
1179 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1180 source->ref_count++;
1184 g_source_list_remove (source, context);
1186 tmp_list = source->poll_fds;
1189 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1190 tmp_list = tmp_list->next;
1195 if (!have_lock && context)
1196 UNLOCK_CONTEXT (context);
1201 UNLOCK_CONTEXT (context);
1203 cb_funcs->unref (cb_data);
1206 LOCK_CONTEXT (context);
1212 * @source: a #GSource
1214 * Decreases the reference count of a source by one. If the
1215 * resulting reference count is zero the source and associated
1216 * memory will be destroyed.
1219 g_source_unref (GSource *source)
1221 g_return_if_fail (source != NULL);
1223 g_source_unref_internal (source, source->context, FALSE);
1227 * g_main_context_find_source_by_id:
1228 * @context: a #GMainContext (if %NULL, the default context will be used)
1229 * @id: the source ID, as returned by g_source_get_id()
1231 * Finds a #GSource given a pair of context and ID
1233 * Return value: the #GSource if found, otherwise, %NULL
1236 g_main_context_find_source_by_id (GMainContext *context,
1241 g_return_val_if_fail (id > 0, FALSE);
1243 if (context == NULL)
1244 context = g_main_context_default ();
1246 LOCK_CONTEXT (context);
1248 source = context->source_list;
1251 if (!SOURCE_DESTROYED (source) &&
1254 source = source->next;
1257 UNLOCK_CONTEXT (context);
1263 * g_main_context_find_source_by_funcs_user_data:
1264 * @context: a #GMainContext (if %NULL, the default context will be used).
1265 * @funcs: the @source_funcs passed to g_source_new().
1266 * @user_data: the user data from the callback.
1268 * Finds a source with the given source functions and user data. If
1269 * multiple sources exist with the same source function and user data,
1270 * the first one found will be returned.
1272 * Return value: the source, if one was found, otherwise %NULL
1275 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1276 GSourceFuncs *funcs,
1281 g_return_val_if_fail (funcs != NULL, FALSE);
1283 if (context == NULL)
1284 context = g_main_context_default ();
1286 LOCK_CONTEXT (context);
1288 source = context->source_list;
1291 if (!SOURCE_DESTROYED (source) &&
1292 source->source_funcs == funcs &&
1293 source->callback_data == user_data)
1295 source = source->next;
1298 UNLOCK_CONTEXT (context);
1304 * g_main_context_find_source_by_user_data:
1305 * @context: a #GMainContext
1306 * @user_data: the user_data for the callback.
1308 * Finds a source with the given user data for the callback. If
1309 * multiple sources exist with the same user data, the first
1310 * one found will be returned.
1312 * Return value: the source, if one was found, otherwise %NULL
1315 g_main_context_find_source_by_user_data (GMainContext *context,
1320 if (context == NULL)
1321 context = g_main_context_default ();
1323 LOCK_CONTEXT (context);
1325 source = context->source_list;
1328 if (!SOURCE_DESTROYED (source) &&
1329 source->callback_data == user_data)
1331 source = source->next;
1334 UNLOCK_CONTEXT (context);
1341 * @tag: the id of the source to remove.
1343 * Removes the source with the given id from the default main
1344 * context. The id of a #GSource is given by g_source_get_id(),
1345 * or will be returned by the functions g_source_attach(),
1346 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1347 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1349 * See also g_source_destroy().
1351 * Return value: %TRUE if the source was found and removed.
1354 g_source_remove (guint tag)
1358 g_return_val_if_fail (tag > 0, FALSE);
1360 source = g_main_context_find_source_by_id (NULL, tag);
1362 g_source_destroy (source);
1364 return source != NULL;
1368 * g_source_remove_by_user_data:
1369 * @user_data: the user_data for the callback.
1371 * Removes a source from the default main loop context given the user
1372 * data for the callback. If multiple sources exist with the same user
1373 * data, only one will be destroyed.
1375 * Return value: %TRUE if a source was found and removed.
1378 g_source_remove_by_user_data (gpointer user_data)
1382 source = g_main_context_find_source_by_user_data (NULL, user_data);
1385 g_source_destroy (source);
1393 * g_source_remove_by_funcs_user_data:
1394 * @funcs: The @source_funcs passed to g_source_new()
1395 * @user_data: the user data for the callback
1397 * Removes a source from the default main loop context given the
1398 * source functions and user data. If multiple sources exist with the
1399 * same source functions and user data, only one will be destroyed.
1401 * Return value: %TRUE if a source was found and removed.
1404 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1409 g_return_val_if_fail (funcs != NULL, FALSE);
1411 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1414 g_source_destroy (source);
1422 * g_get_current_time:
1423 * @result: #GTimeVal structure in which to store current time.
1425 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1428 g_get_current_time (GTimeVal *result)
1433 g_return_if_fail (result != NULL);
1435 /*this is required on alpha, there the timeval structs are int's
1436 not longs and a cast only would fail horribly*/
1437 gettimeofday (&r, NULL);
1438 result->tv_sec = r.tv_sec;
1439 result->tv_usec = r.tv_usec;
1441 /* Avoid calling time() except for the first time.
1442 * GetTickCount() should be pretty fast and low-level?
1443 * I could also use ftime() but it seems unnecessarily overheady.
1445 static DWORD start_tick = 0;
1446 static time_t start_time;
1449 g_return_if_fail (result != NULL);
1451 if (start_tick == 0)
1453 start_tick = GetTickCount ();
1457 tick = GetTickCount ();
1459 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1460 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1464 /* Running the main loop */
1466 /* HOLDS: context's lock */
1468 g_main_dispatch (GMainContext *context)
1472 for (i = 0; i < context->pending_dispatches->len; i++)
1474 GSource *source = context->pending_dispatches->pdata[i];
1476 context->pending_dispatches->pdata[i] = NULL;
1479 source->flags &= ~G_SOURCE_READY;
1481 if (!SOURCE_DESTROYED (source))
1483 gboolean was_in_call;
1484 gpointer user_data = NULL;
1485 GSourceFunc callback = NULL;
1486 GSourceCallbackFuncs *cb_funcs;
1488 gboolean need_destroy;
1490 gboolean (*dispatch) (GSource *,
1494 dispatch = source->source_funcs->dispatch;
1495 cb_funcs = source->callback_funcs;
1496 cb_data = source->callback_data;
1499 cb_funcs->ref (cb_data);
1501 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1502 source->flags |= G_HOOK_FLAG_IN_CALL;
1504 UNLOCK_CONTEXT (context);
1507 cb_funcs->get (cb_data, &callback, &user_data);
1509 need_destroy = ! dispatch (source,
1512 LOCK_CONTEXT (context);
1515 cb_funcs->unref (cb_data);
1518 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1520 /* Note: this depends on the fact that we can't switch
1521 * sources from one main context to another
1523 if (need_destroy && !SOURCE_DESTROYED (source))
1525 g_assert (source->context == context);
1526 g_source_destroy_internal (source, context, TRUE);
1530 SOURCE_UNREF (source, context);
1533 g_ptr_array_set_size (context->pending_dispatches, 0);
1536 /* Holds context's lock */
1537 static inline GSource *
1538 next_valid_source (GMainContext *context,
1541 GSource *new_source = source ? source->next : context->source_list;
1545 if (!SOURCE_DESTROYED (new_source))
1547 new_source->ref_count++;
1551 new_source = new_source->next;
1555 SOURCE_UNREF (source, context);
1562 * g_main_context_prepare:
1563 * @context: a #GMainContext
1564 * @priority: location to store priority of highest priority
1565 * source already ready.
1567 * Prepares to poll sources within a main loop. The resulting information
1568 * for polling is determined by calling g_main_context_query ().
1570 * Return value: %TRUE if some source is ready to be dispatched
1574 g_main_context_prepare (GMainContext *context,
1578 gint current_priority = G_MAXINT;
1581 if (context == NULL)
1582 context = g_main_context_default ();
1584 LOCK_CONTEXT (context);
1586 context->time_is_current = FALSE;
1588 if (context->in_check_or_prepare)
1590 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1591 "prepare() member.");
1595 #ifdef G_THREADS_ENABLED
1596 if (context->poll_waiting)
1598 g_warning("g_main_context_prepare(): main loop already active in another thread");
1599 UNLOCK_CONTEXT (context);
1603 context->poll_waiting = TRUE;
1604 #endif /* G_THREADS_ENABLED */
1607 /* If recursing, finish up current dispatch, before starting over */
1608 if (context->pending_dispatches)
1611 g_main_dispatch (context, ¤t_time);
1613 UNLOCK_CONTEXT (context);
1618 /* If recursing, clear list of pending dispatches */
1619 g_ptr_array_set_size (context->pending_dispatches, 0);
1621 /* Prepare all sources */
1623 context->timeout = -1;
1625 source = next_valid_source (context, NULL);
1628 gint source_timeout = -1;
1630 if ((n_ready > 0) && (source->priority > current_priority))
1632 SOURCE_UNREF (source, context);
1635 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1638 if (!(source->flags & G_SOURCE_READY))
1641 gboolean (*prepare) (GSource *source,
1644 prepare = source->source_funcs->prepare;
1645 context->in_check_or_prepare++;
1646 UNLOCK_CONTEXT (context);
1648 result = (*prepare) (source, &source_timeout);
1650 LOCK_CONTEXT (context);
1651 context->in_check_or_prepare--;
1654 source->flags |= G_SOURCE_READY;
1657 if (source->flags & G_SOURCE_READY)
1660 current_priority = source->priority;
1661 context->timeout = 0;
1664 if (source_timeout >= 0)
1666 if (context->timeout < 0)
1667 context->timeout = source_timeout;
1669 context->timeout = MIN (context->timeout, source_timeout);
1673 source = next_valid_source (context, source);
1676 UNLOCK_CONTEXT (context);
1679 *priority = current_priority;
1681 return (n_ready > 0);
1685 * g_main_context_query:
1686 * @context: a #GMainContext
1687 * @max_priority: maximum priority source to check
1688 * @timeout: location to store timeout to be used in polling
1689 * @fds: location to store #GPollFD records that need to be polled.
1690 * @n_fds: length of @fds.
1692 * Determines information necessary to poll this main loop.
1697 g_main_context_query (GMainContext *context,
1706 LOCK_CONTEXT (context);
1708 pollrec = context->poll_records;
1710 while (pollrec && max_priority >= pollrec->priority)
1712 if (pollrec->fd->events)
1716 fds[n_poll].fd = pollrec->fd->fd;
1717 /* In direct contradiction to the Unix98 spec, IRIX runs into
1718 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1719 * flags in the events field of the pollfd while it should
1720 * just ignoring them. So we mask them out here.
1722 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1723 fds[n_poll].revents = 0;
1728 pollrec = pollrec->next;
1731 context->poll_changed = FALSE;
1735 *timeout = context->timeout;
1737 context->time_is_current = FALSE;
1740 UNLOCK_CONTEXT (context);
1746 * g_main_context_check:
1747 * @context: a #GMainContext
1748 * @max_priority: the maximum numerical priority of sources to check
1749 * @fds: array of #GPollFD's that was passed to the last call to
1750 * g_main_context_query()
1751 * @n_fds: return value of g_main_context_query()
1753 * Pass the results of polling back to the main loop.
1755 * Return value: %TRUE if some sources are ready to be dispatched.
1758 g_main_context_check (GMainContext *context,
1768 LOCK_CONTEXT (context);
1770 if (context->in_check_or_prepare)
1772 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1773 "prepare() member.");
1777 #ifdef G_THREADS_ENABLED
1778 if (!context->poll_waiting)
1782 read (context->wake_up_pipe[0], &c, 1);
1786 context->poll_waiting = FALSE;
1787 #endif /* G_THREADS_ENABLED */
1789 /* If the set of poll file descriptors changed, bail out
1790 * and let the main loop rerun
1792 if (context->poll_changed)
1795 pollrec = context->poll_records;
1799 if (pollrec->fd->events)
1801 pollrec->fd->revents = fds[i].revents;
1804 pollrec = pollrec->next;
1807 source = next_valid_source (context, NULL);
1810 if ((n_ready > 0) && (source->priority > max_priority))
1812 SOURCE_UNREF (source, context);
1815 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1818 if (!(source->flags & G_SOURCE_READY))
1821 gboolean (*check) (GSource *source);
1823 check = source->source_funcs->check;
1825 context->in_check_or_prepare++;
1826 UNLOCK_CONTEXT (context);
1828 result = (*check) (source);
1830 LOCK_CONTEXT (context);
1831 context->in_check_or_prepare--;
1834 source->flags |= G_SOURCE_READY;
1837 if (source->flags & G_SOURCE_READY)
1839 source->ref_count++;
1840 g_ptr_array_add (context->pending_dispatches, source);
1846 source = next_valid_source (context, source);
1849 UNLOCK_CONTEXT (context);
1855 * g_main_context_dispatch:
1856 * @context: a #GMainContext
1858 * Dispatch all pending sources()
1861 g_main_context_dispatch (GMainContext *context)
1863 LOCK_CONTEXT (context);
1865 if (context->pending_dispatches->len > 0)
1867 g_main_dispatch (context);
1870 UNLOCK_CONTEXT (context);
1874 g_main_context_iterate (GMainContext *context,
1880 gboolean some_ready;
1881 gint nfds, new_nfds;
1884 some_ready = g_main_context_prepare (context, &max_priority);
1888 LOCK_CONTEXT (context);
1890 if (context->cached_poll_array)
1892 nfds = context->cached_poll_array_size;
1893 fds = context->cached_poll_array;
1894 context->cached_poll_array = NULL;
1898 nfds = context->cached_poll_array_size = context->n_poll_records;
1899 fds = g_new (GPollFD, nfds);
1902 UNLOCK_CONTEXT (context);
1904 new_nfds = g_main_context_query (context, max_priority,
1905 &timeout, fds, nfds);
1907 while (new_nfds > nfds);
1912 g_main_context_poll (context, timeout, max_priority,
1915 g_main_context_check (context,
1919 LOCK_CONTEXT (context);
1921 g_assert (!context->cached_poll_array);
1923 context->cached_poll_array = fds;
1924 context->cached_poll_array_size = nfds;
1926 UNLOCK_CONTEXT (context);
1929 g_main_context_dispatch (context);
1935 * g_main_context_pending:
1936 * @context: a #GMainContext (if %NULL, the default context will be used)
1938 * Check if any sources have pending events for the given context.
1940 * Return value: %TRUE if events are pending.
1943 g_main_context_pending (GMainContext *context)
1946 context = g_main_context_default();
1948 return g_main_context_iterate (context, FALSE, FALSE);
1952 * g_main_context_iteration:
1953 * @context: a #GMainContext (if %NULL, the default context will be used)
1954 * @may_block: whether the call may block.
1956 * Run a single iteration for the given main loop. This involves
1957 * checking to see if any event sources are ready to be processed,
1958 * then if no events sources are ready and @may_block is %TRUE, waiting
1959 * for a source to become ready, then dispatching the highest priority
1960 * events sources that are ready. Note that even when @may_block is %TRUE,
1961 * it is still possible for g_main_context_iteration() to return
1962 * %FALSE, since the the wait may be interrupted for other
1963 * reasons than an event source becoming ready.
1965 * Return value: %TRUE if events were dispatched.
1968 g_main_context_iteration (GMainContext *context, gboolean may_block)
1971 context = g_main_context_default();
1973 return g_main_context_iterate (context, may_block, TRUE);
1978 * @context: a #GMainContext (if %NULL, the default context will be used).
1979 * @is_running: set to TRUE to indicate that the loop is running. This
1980 * is not very important since calling g_main_run() will set this to
1983 * Create a new #GMainLoop structure
1988 g_main_loop_new (GMainContext *context,
1989 gboolean is_running)
1994 context = g_main_context_default();
1996 loop = g_new0 (GMainLoop, 1);
1997 loop->context = context;
1998 loop->is_running = is_running != FALSE;
2000 #ifdef G_THREADS_ENABLED
2001 if (g_thread_supported ())
2002 loop->mutex = g_mutex_new ();
2005 loop->sem_cond = NULL;
2006 #endif /* G_THREADS_ENABLED */
2013 * @loop: a #GMainLoop
2015 * Run a main loop until g_main_quit() is called on the loop.
2016 * If this is called for the thread of the loop's #GMainContext,
2017 * it will process events from the loop, otherwise it will
2021 g_main_loop_run (GMainLoop *loop)
2023 g_return_if_fail (loop != NULL);
2025 #ifdef G_THREADS_ENABLED
2026 if (loop->context->thread != g_thread_self ())
2030 if (!g_thread_supported ())
2032 g_warning ("g_main_loop_run() was called from second thread but"
2033 "g_thread_init() was never called.");
2037 if (!loop->sem_cond)
2038 loop->sem_cond = g_cond_new ();
2040 if (!loop->is_running)
2041 loop->is_running = TRUE;
2043 while (loop->is_running)
2044 g_cond_wait (loop->sem_cond, loop->mutex);
2050 #endif /* G_THREADS_ENABLED */
2052 LOCK_CONTEXT (loop->context);
2053 if (loop->context->in_check_or_prepare)
2055 g_warning ("g_main_run(): called recursively from within a source's check() or "
2056 "prepare() member, iteration not possible.");
2059 UNLOCK_CONTEXT (loop->context);
2063 loop->is_running = TRUE;
2064 while (loop->is_running)
2067 g_main_context_iterate (loop->context, TRUE, TRUE);
2076 * @loop: a #GMainLoop
2078 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2079 * for the loop will return.
2082 g_main_loop_quit (GMainLoop *loop)
2084 g_return_if_fail (loop != NULL);
2087 loop->is_running = FALSE;
2090 g_cond_broadcast (loop->sem_cond);
2094 LOCK_CONTEXT (loop->context);
2096 g_main_context_wakeup (loop->context);
2097 UNLOCK_CONTEXT (loop->context);
2101 * g_main_loop_destroy:
2102 * @loop: a #GMainLoop
2104 * Destroy a #GMainLoop object and free all associated memory.
2105 * The loop must not currently be running via g_main_run().
2108 g_main_loop_destroy (GMainLoop *loop)
2110 g_return_if_fail (loop != NULL);
2111 g_return_if_fail (!loop->is_running);
2113 #ifdef G_THREADS_ENABLED
2114 g_mutex_free (loop->mutex);
2116 g_cond_free (loop->sem_cond);
2117 #endif /* G_THREADS_ENABLED */
2123 * g_main_loop_is_running:
2124 * @loop: a #GMainLoop.
2126 * Check to see if the main loop is currently being run via g_main_run()
2128 * Return value: %TRUE if the mainloop is currently being run.
2131 g_main_loop_is_running (GMainLoop *loop)
2135 g_return_val_if_fail (loop != NULL, FALSE);
2138 result = loop->is_running;
2144 /* HOLDS: context's lock */
2146 g_main_context_poll (GMainContext *context,
2152 #ifdef G_MAIN_POLL_DEBUG
2158 GPollFunc poll_func;
2160 if (n_fds || timeout != 0)
2162 #ifdef G_MAIN_POLL_DEBUG
2163 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2164 poll_timer = g_timer_new ();
2167 LOCK_CONTEXT (context);
2169 poll_func = context->poll_func;
2171 UNLOCK_CONTEXT (context);
2172 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2173 g_warning ("poll(2) failed due to: %s.",
2174 g_strerror (errno));
2176 #ifdef G_MAIN_POLL_DEBUG
2177 LOCK_CONTEXT (context);
2179 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2182 g_timer_elapsed (poll_timer, NULL));
2183 g_timer_destroy (poll_timer);
2184 pollrec = context->poll_records;
2188 if (pollrec->fd->events)
2192 g_print (" [%d:", fds[i].fd);
2193 if (fds[i].revents & G_IO_IN)
2195 if (fds[i].revents & G_IO_OUT)
2197 if (fds[i].revents & G_IO_PRI)
2199 if (fds[i].revents & G_IO_ERR)
2201 if (fds[i].revents & G_IO_HUP)
2203 if (fds[i].revents & G_IO_NVAL)
2209 pollrec = pollrec->next;
2213 UNLOCK_CONTEXT (context);
2215 } /* if (n_fds || timeout != 0) */
2219 * g_main_context_add_poll:
2220 * @context: a #GMainContext (or %NULL for the default context)
2221 * @fd: a #GPollFD structure holding information about a file
2222 * descriptor to watch.
2223 * @priority: the priority for this file descriptor which should be
2224 * the same as the priority used for g_source_attach() to ensure that the
2225 * file descriptor is polled whenever the results may be needed.
2227 * Add a file descriptor to the set of file descriptors polled * for
2228 * this context. This will very seldom be used directly. Instead
2229 * a typical event source will use g_source_add_poll() instead.
2232 g_main_context_add_poll (GMainContext *context,
2237 context = g_main_context_default ();
2239 LOCK_CONTEXT (context);
2240 g_main_context_add_poll_unlocked (context, priority, fd);
2241 UNLOCK_CONTEXT (context);
2244 /* HOLDS: main_loop_lock */
2246 g_main_context_add_poll_unlocked (GMainContext *context,
2250 GPollRec *lastrec, *pollrec, *newrec;
2252 if (!context->poll_chunk)
2253 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2255 if (context->poll_free_list)
2257 newrec = context->poll_free_list;
2258 context->poll_free_list = newrec->next;
2261 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2263 /* This file descriptor may be checked before we ever poll */
2266 newrec->priority = priority;
2269 pollrec = context->poll_records;
2270 while (pollrec && priority >= pollrec->priority)
2273 pollrec = pollrec->next;
2277 lastrec->next = newrec;
2279 context->poll_records = newrec;
2281 newrec->next = pollrec;
2283 context->n_poll_records++;
2284 if (context->cached_poll_array &&
2285 context->cached_poll_array_size < context->n_poll_records)
2287 g_free (context->cached_poll_array);
2288 context->cached_poll_array = NULL;
2291 #ifdef G_THREADS_ENABLED
2292 context->poll_changed = TRUE;
2294 /* Now wake up the main loop if it is waiting in the poll() */
2295 g_main_context_wakeup (context);
2300 * g_main_context_remove_poll:
2301 * @context:a #GMainContext
2302 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2304 * Remove file descriptor from the set of file descriptors to be
2305 * polled for a particular context.
2308 g_main_context_remove_poll (GMainContext *context,
2312 context = g_main_context_default ();
2314 LOCK_CONTEXT (context);
2316 g_main_context_remove_poll_unlocked (context, fd);
2318 UNLOCK_CONTEXT (context);
2322 g_main_context_remove_poll_unlocked (GMainContext *context,
2325 GPollRec *pollrec, *lastrec;
2328 pollrec = context->poll_records;
2332 if (pollrec->fd == fd)
2334 if (lastrec != NULL)
2335 lastrec->next = pollrec->next;
2337 context->poll_records = pollrec->next;
2339 #ifdef ENABLE_GC_FRIENDLY
2341 #endif /* ENABLE_GC_FRIENDLY */
2343 pollrec->next = context->poll_free_list;
2344 context->poll_free_list = pollrec;
2346 context->n_poll_records--;
2350 pollrec = pollrec->next;
2353 #ifdef G_THREADS_ENABLED
2354 context->poll_changed = TRUE;
2356 /* Now wake up the main loop if it is waiting in the poll() */
2357 g_main_context_wakeup (context);
2362 * g_source_get_current_time:
2363 * @source: a #GSource
2364 * @timeval: #GTimeVal structure in which to store current time.
2366 * Gets the "current time" to be used when checking
2367 * this source. The advantage of calling this function over
2368 * calling g_get_current_time() directly is that when
2369 * checking multiple sources, GLib can cache a single value
2370 * instead of having to repeatedly get the system time.
2373 g_source_get_current_time (GSource *source,
2376 GMainContext *context;
2378 g_return_if_fail (source->context != NULL);
2380 context = source->context;
2382 LOCK_CONTEXT (context);
2384 if (!context->time_is_current)
2386 g_get_current_time (&context->current_time);
2387 context->time_is_current = TRUE;
2390 *timeval = context->current_time;
2392 UNLOCK_CONTEXT (context);
2396 * g_main_context_set_poll_func:
2397 * @context: a #GMainContext
2398 * @func: the function to call to poll all file descriptors
2400 * Sets the function to use to handle polling of file descriptors. It
2401 * will be used instead of the poll() system call (or GLib's
2402 * replacement function, which is used where poll() isn't available).
2404 * This function could possibly be used to integrate the GLib event
2405 * loop with an external event loop.
2408 g_main_context_set_poll_func (GMainContext *context,
2412 context = g_main_context_default ();
2414 LOCK_CONTEXT (context);
2417 context->poll_func = func;
2421 context->poll_func = (GPollFunc) poll;
2423 context->poll_func = (GPollFunc) g_poll;
2427 UNLOCK_CONTEXT (context);
2433 * g_main_context_get_poll_func:
2434 * @context: a #GMainContext
2436 * Gets the poll function set by g_main_context_set_poll_func()
2438 * Return value: the poll function
2441 g_main_context_get_poll_func (GMainContext *context)
2446 context = g_main_context_default ();
2448 LOCK_CONTEXT (context);
2449 result = context->poll_func;
2450 UNLOCK_CONTEXT (context);
2455 /* HOLDS: context's lock */
2456 /* Wake the main loop up from a poll() */
2458 g_main_context_wakeup (GMainContext *context)
2460 #ifdef G_THREADS_ENABLED
2461 if (g_thread_supported() && context->poll_waiting)
2463 context->poll_waiting = FALSE;
2465 write (context->wake_up_pipe[1], "A", 1);
2467 ReleaseSemaphore (context->context->wake_up_semaphore, 1, NULL);
2476 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2477 GTimeVal *current_time)
2479 guint seconds = timeout_source->interval / 1000;
2480 guint msecs = timeout_source->interval - seconds * 1000;
2482 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2483 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2484 if (timeout_source->expiration.tv_usec >= 1000000)
2486 timeout_source->expiration.tv_usec -= 1000000;
2487 timeout_source->expiration.tv_sec++;
2492 g_timeout_prepare (GSource *source,
2496 GTimeVal current_time;
2498 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2500 g_source_get_current_time (source, ¤t_time);
2502 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2503 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2507 else if (msec > timeout_source->interval)
2509 /* The system time has been set backwards, so we
2510 * reset the expiration time to now + timeout_source->interval;
2511 * this at least avoids hanging for long periods of time.
2513 g_timeout_set_expiration (timeout_source, ¤t_time);
2514 msec = timeout_source->interval;
2523 g_timeout_check (GSource *source)
2525 GTimeVal current_time;
2526 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2528 g_source_get_current_time (source, ¤t_time);
2530 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2531 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2532 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2536 g_timeout_dispatch (GSource *source,
2537 GSourceFunc callback,
2540 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2544 g_warning ("Timeout source dispatched without callback\n"
2545 "You must call g_source_set_callback().");
2549 if (callback (user_data))
2551 GTimeVal current_time;
2553 g_source_get_current_time (source, ¤t_time);
2554 g_timeout_set_expiration (timeout_source, ¤t_time);
2563 * g_timeout_source_new:
2564 * @interval: the timeout interval in milliseconds.
2566 * Create a new timeout source.
2568 * The source will not initially be associated with any #GMainContext
2569 * and must be added to one with g_source_attach() before it will be
2572 * Return value: the newly create timeout source
2575 g_timeout_source_new (guint interval)
2577 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2578 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2579 GTimeVal current_time;
2581 timeout_source->interval = interval;
2583 g_get_current_time (¤t_time);
2584 g_timeout_set_expiration (timeout_source, ¤t_time);
2590 * g_timeout_add_full:
2591 * @priority: the priority of the idle source. Typically this will be in the
2592 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2593 * @interval: the time between calls to the function, in milliseconds
2594 * (1/1000ths of a second.)
2595 * @function: function to call
2596 * @data: data to pass to @function
2597 * @notify: function to call when the idle is removed, or %NULL
2599 * Sets a function to be called at regular intervals, with the given
2600 * priority. The function is called repeatedly until it returns
2601 * FALSE, at which point the timeout is automatically destroyed and
2602 * the function will not be called again. The @notify function is
2603 * called when the timeout is destroyed. The first call to the
2604 * function will be at the end of the first @interval.
2606 * Note that timeout functions may be delayed, due to the processing of other
2607 * event sources. Thus they should not be relied on for precise timing.
2608 * After each call to the timeout function, the time of the next
2609 * timeout is recalculated based on the current time and the given interval
2610 * (it does not try to 'catch up' time lost in delays).
2612 * Return value: the id of event source.
2615 g_timeout_add_full (gint priority,
2617 GSourceFunc function,
2619 GDestroyNotify notify)
2624 g_return_val_if_fail (function != NULL, 0);
2626 source = g_timeout_source_new (interval);
2628 if (priority != G_PRIORITY_DEFAULT)
2629 g_source_set_priority (source, priority);
2631 g_source_set_callback (source, function, data, notify);
2632 id = g_source_attach (source, NULL);
2633 g_source_unref (source);
2640 * @interval: the time between calls to the function, in milliseconds
2641 * (1/1000ths of a second.)
2642 * @function: function to call
2643 * @data: data to pass to @function
2645 * Sets a function to be called at regular intervals, with the default
2646 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2647 * until it returns FALSE, at which point the timeout is automatically
2648 * destroyed and the function will not be called again. The @notify
2649 * function is called when the timeout is destroyed. The first call
2650 * to the function will be at the end of the first @interval.
2652 * Note that timeout functions may be delayed, due to the processing of other
2653 * event sources. Thus they should not be relied on for precise timing.
2654 * After each call to the timeout function, the time of the next
2655 * timeout is recalculated based on the current time and the given interval
2656 * (it does not try to 'catch up' time lost in delays).
2658 * Return value: the id of event source.
2661 g_timeout_add (guint32 interval,
2662 GSourceFunc function,
2665 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2666 interval, function, data, NULL);
2669 /* Idle functions */
2672 g_idle_prepare (GSource *source,
2681 g_idle_check (GSource *source)
2687 g_idle_dispatch (GSource *source,
2688 GSourceFunc callback,
2693 g_warning ("Idle source dispatched without callback\n"
2694 "You must call g_source_set_callback().");
2698 return callback (user_data);
2702 * g_idle_source_new:
2704 * Create a new idle source.
2706 * The source will not initially be associated with any #GMainContext
2707 * and must be added to one with g_source_attach() before it will be
2710 * Return value: the newly created idle source
2713 g_idle_source_new (void)
2715 return g_source_new (&idle_funcs, sizeof (GSource));
2720 * @priority: the priority of the idle source. Typically this will be in the
2721 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
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 * Adds a function to be called whenever there are no higher priority
2727 * events pending. If the function returns FALSE it is automatically
2728 * removed from the list of event sources and will not be called again.
2730 * Return value: the id of the event source.
2733 g_idle_add_full (gint priority,
2734 GSourceFunc function,
2736 GDestroyNotify notify)
2741 g_return_val_if_fail (function != NULL, 0);
2743 source = g_idle_source_new ();
2745 if (priority != G_PRIORITY_DEFAULT)
2746 g_source_set_priority (source, priority);
2748 g_source_set_callback (source, function, data, notify);
2749 id = g_source_attach (source, NULL);
2750 g_source_unref (source);
2757 * @function: function to call
2758 * @data: data to pass to @function.
2760 * Adds a function to be called whenever there are no higher priority
2761 * events pending to the default main loop. The function is given the
2762 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2763 * returns FALSE it is automatically removed from the list of event
2764 * sources and will not be called again.
2766 * Return value: the id of the event source.
2769 g_idle_add (GSourceFunc function,
2772 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2776 * g_idle_remove_by_data:
2777 * @data: the data for the idle source's callback.
2779 * Removes the idle function with the given data.
2781 * Return value: %TRUE if an idle source was found and removed.
2784 g_idle_remove_by_data (gpointer data)
2786 return g_source_remove_by_funcs_user_data (&idle_funcs, data);