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++;
755 g_source_list_add (source, context);
757 tmp_list = source->poll_fds;
760 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
761 tmp_list = tmp_list->next;
764 #ifdef G_THREADS_ENABLED
765 /* Now wake up the main loop if it is waiting in the poll() */
766 g_main_context_wakeup (context);
769 UNLOCK_CONTEXT (context);
775 g_source_destroy_internal (GSource *source,
776 GMainContext *context,
780 LOCK_CONTEXT (context);
782 if (!SOURCE_DESTROYED (source))
784 gpointer old_cb_data;
785 GSourceCallbackFuncs *old_cb_funcs;
787 source->flags &= ~G_HOOK_FLAG_ACTIVE;
789 old_cb_data = source->callback_data;
790 old_cb_funcs = source->callback_funcs;
792 source->callback_data = NULL;
793 source->callback_funcs = NULL;
797 UNLOCK_CONTEXT (context);
798 old_cb_funcs->unref (old_cb_data);
799 LOCK_CONTEXT (context);
802 g_source_unref_internal (source, context, TRUE);
806 UNLOCK_CONTEXT (context);
811 * @source: a #GSource
813 * Remove a source from its #GMainContext, if any, and mark it as
814 * destroyed. The source cannot be subsequently added to another
818 g_source_destroy (GSource *source)
820 GMainContext *context;
822 g_return_if_fail (source != NULL);
824 context = source->context;
827 g_source_destroy_internal (source, context, FALSE);
829 source->flags &= ~G_HOOK_FLAG_ACTIVE;
834 * @source: a #GSource
836 * Return the numeric ID for a particular source. The ID of a source
837 * is unique within a particular main loop context. The reverse
838 * mapping from ID to source is done by g_main_context_find_source_by_id().
840 * Return value: the ID for the source
843 g_source_get_id (GSource *source)
847 g_return_val_if_fail (source != NULL, 0);
848 g_return_val_if_fail (source->context != NULL, 0);
850 LOCK_CONTEXT (source->context);
852 UNLOCK_CONTEXT (source->context);
858 * g_source_get_context:
859 * @source: a #GSource
861 * Get the #GMainContext with which the source is associated.
862 * Calling this function on a destroyed source is an error.
864 * Return value: the #GMainContext with which the source is associated,
865 * or %NULL if the context has not yet been added
869 g_source_get_context (GSource *source)
871 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
873 return source->context;
877 * g_main_source_add_poll:
879 * @fd: a #GPollFD structure holding information about a file
880 * descriptor to watch.
882 * Add a file descriptor to the set of file descriptors polled * for
883 * this source. This is usually combined with g_source_new() to add an
884 * event source. The event source's check function will typically test
885 * the revents field in the #GPollFD struct and return %TRUE if events need
889 g_source_add_poll (GSource *source,
892 GMainContext *context;
894 g_return_if_fail (source != NULL);
895 g_return_if_fail (fd != NULL);
897 context = source->context;
900 LOCK_CONTEXT (context);
902 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
906 g_main_context_add_poll_unlocked (context, source->priority, fd);
907 UNLOCK_CONTEXT (context);
912 * g_source_set_callback_indirect:
913 * @source: the source
914 * @callback_data: pointer to callback data "object"
915 * @callback_funcs: functions for reference counting callback_data
916 * and getting the callback and data
918 * Set the callback function storing the data as a refcounted callback
919 * "object". This is used to implement g_source_set_callback_closure()
920 * and internally. Note that calling g_source_set_callback_indirect() assumes
921 * an initial reference count on @callback_data, and thus
922 * @callback_funcs->unref will eventually be called once more
923 * than @callback_funcs->ref.
926 g_source_set_callback_indirect (GSource *source,
927 gpointer callback_data,
928 GSourceCallbackFuncs *callback_funcs)
930 GMainContext *context;
931 gpointer old_cb_data;
932 GSourceCallbackFuncs *old_cb_funcs;
934 g_return_if_fail (source != NULL);
935 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
937 context = source->context;
940 LOCK_CONTEXT (context);
942 old_cb_data = source->callback_data;
943 old_cb_funcs = source->callback_funcs;
945 source->callback_data = callback_data;
946 source->callback_funcs = callback_funcs;
949 UNLOCK_CONTEXT (context);
952 old_cb_funcs->unref (old_cb_data);
956 g_source_callback_ref (gpointer cb_data)
958 GSourceCallback *callback = cb_data;
960 callback->ref_count++;
965 g_source_callback_unref (gpointer cb_data)
967 GSourceCallback *callback = cb_data;
969 callback->ref_count--;
970 if (callback->ref_count == 0)
972 if (callback->notify)
973 callback->notify (callback->data);
978 g_source_callback_get (gpointer cb_data,
982 GSourceCallback *callback = cb_data;
984 *func = callback->func;
985 *data = callback->data;
988 static GSourceCallbackFuncs g_source_callback_funcs = {
989 g_source_callback_ref,
990 g_source_callback_unref,
991 g_source_callback_get,
995 * g_source_set_callback:
996 * @source: the source
997 * @func: a callback function
998 * @data: the data to pass to callback function
999 * @notify: a function to call when @data is no longer in use, or %NULL.
1001 * Set the callback function for a source.
1004 g_source_set_callback (GSource *source,
1007 GDestroyNotify notify)
1009 GSourceCallback *new_callback;
1011 g_return_if_fail (source != NULL);
1013 new_callback = g_new (GSourceCallback, 1);
1015 new_callback->func = func;
1016 new_callback->data = data;
1017 new_callback->notify = notify;
1019 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1023 * g_source_set_priority:
1024 * @source: a #GSource
1025 * @priority: the new priority.
1027 * Set the priority of a source. While the main loop is being
1028 * run, a source will
1031 g_source_set_priority (GSource *source,
1035 GMainContext *context;
1037 g_return_if_fail (source != NULL);
1039 context = source->context;
1042 LOCK_CONTEXT (context);
1044 source->priority = priority;
1048 source->next = NULL;
1049 source->prev = NULL;
1051 tmp_list = source->poll_fds;
1054 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1055 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1057 tmp_list = tmp_list->next;
1060 UNLOCK_CONTEXT (source->context);
1065 * g_source_get_priority:
1066 * @source: a #GSource
1068 * Gets the priority of a surce
1070 * Return value: the priority of the source
1073 g_source_get_priority (GSource *source)
1075 g_return_val_if_fail (source != NULL, 0);
1077 return source->priority;
1081 * g_source_set_can_recurse:
1082 * @source: a #GSource
1083 * @can_recurse: whether recursion is allowed for this source
1085 * Sets whether a source can be called recursively. If @can_recurse is
1086 * %TRUE, then while the source is being dispatched then this source
1087 * will be processed normally. Otherwise, all processing of this
1088 * source is blocked until the dispatch function returns.
1091 g_source_set_can_recurse (GSource *source,
1092 gboolean can_recurse)
1094 GMainContext *context;
1096 g_return_if_fail (source != NULL);
1098 context = source->context;
1101 LOCK_CONTEXT (context);
1104 source->flags |= G_SOURCE_CAN_RECURSE;
1106 source->flags &= ~G_SOURCE_CAN_RECURSE;
1109 UNLOCK_CONTEXT (context);
1113 * g_source_get_can_recurse:
1114 * @source: a #GSource
1116 * Checks whether a source is allowed to be called recursively.
1117 * see g_source_set_can_recurse.
1119 * Return value: whether recursion is allowed.
1122 g_source_get_can_recurse (GSource *source)
1124 g_return_val_if_fail (source != NULL, FALSE);
1126 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1131 * @source: a #GSource
1133 * Increases the reference count on a source by one.
1135 * Return value: @source
1138 g_source_ref (GSource *source)
1140 GMainContext *context;
1142 g_return_val_if_fail (source != NULL, NULL);
1144 context = source->context;
1147 LOCK_CONTEXT (context);
1149 source->ref_count++;
1152 UNLOCK_CONTEXT (context);
1157 /* g_source_unref() but possible to call within context lock
1160 g_source_unref_internal (GSource *source,
1161 GMainContext *context,
1164 gpointer cb_data = NULL;
1165 GSourceCallbackFuncs *cb_funcs = NULL;
1168 g_return_if_fail (source != NULL);
1170 if (!have_lock && context)
1171 LOCK_CONTEXT (context);
1173 source->ref_count--;
1174 if (source->ref_count == 0)
1176 if (context && !SOURCE_DESTROYED (source))
1178 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1179 source->ref_count++;
1183 g_source_list_remove (source, context);
1185 tmp_list = source->poll_fds;
1188 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1189 tmp_list = tmp_list->next;
1194 if (!have_lock && context)
1195 UNLOCK_CONTEXT (context);
1200 UNLOCK_CONTEXT (context);
1202 cb_funcs->unref (cb_data);
1205 LOCK_CONTEXT (context);
1211 * @source: a #GSource
1213 * Decreases the reference count of a source by one. If the
1214 * resulting reference count is zero the source and associated
1215 * memory will be destroyed.
1218 g_source_unref (GSource *source)
1220 g_return_if_fail (source != NULL);
1222 g_source_unref_internal (source, source->context, FALSE);
1226 * g_main_context_find_source_by_id:
1227 * @context: a #GMainContext (if %NULL, the default context will be used)
1228 * @id: the source ID, as returned by g_source_get_id()
1230 * Finds a #GSource given a pair of context and ID
1232 * Return value: the #GSource if found, otherwise, %NULL
1235 g_main_context_find_source_by_id (GMainContext *context,
1240 g_return_val_if_fail (id > 0, FALSE);
1242 if (context == NULL)
1243 context = g_main_context_default ();
1245 LOCK_CONTEXT (context);
1247 source = context->source_list;
1250 if (!SOURCE_DESTROYED (source) &&
1253 source = source->next;
1256 UNLOCK_CONTEXT (context);
1262 * g_main_context_find_source_by_funcs_user_data:
1263 * @context: a #GMainContext (if %NULL, the default context will be used).
1264 * @funcs: the @source_funcs passed to g_source_new().
1265 * @user_data: the user data from the callback.
1267 * Finds a source with the given source functions and user data. If
1268 * multiple sources exist with the same source function and user data,
1269 * the first one found will be returned.
1271 * Return value: the source, if one was found, otherwise %NULL
1274 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1275 GSourceFuncs *funcs,
1280 g_return_val_if_fail (funcs != NULL, FALSE);
1282 if (context == NULL)
1283 context = g_main_context_default ();
1285 LOCK_CONTEXT (context);
1287 source = context->source_list;
1290 if (!SOURCE_DESTROYED (source) &&
1291 source->source_funcs == funcs &&
1292 source->callback_data == user_data)
1294 source = source->next;
1297 UNLOCK_CONTEXT (context);
1303 * g_main_context_find_source_by_user_data:
1304 * @context: a #GMainContext
1305 * @user_data: the user_data for the callback.
1307 * Finds a source with the given user data for the callback. If
1308 * multiple sources exist with the same user data, the first
1309 * one found will be returned.
1311 * Return value: the source, if one was found, otherwise %NULL
1314 g_main_context_find_source_by_user_data (GMainContext *context,
1319 if (context == NULL)
1320 context = g_main_context_default ();
1322 LOCK_CONTEXT (context);
1324 source = context->source_list;
1327 if (!SOURCE_DESTROYED (source) &&
1328 source->callback_data == user_data)
1330 source = source->next;
1333 UNLOCK_CONTEXT (context);
1340 * @tag: the id of the source to remove.
1342 * Removes the source with the given id from the default main
1343 * context. The id of a #GSource is given by g_source_get_id(),
1344 * or will be returned by the functions g_source_attach(),
1345 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1346 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1348 * See also g_source_destroy().
1350 * Return value: %TRUE if the source was found and removed.
1353 g_source_remove (guint tag)
1357 g_return_val_if_fail (tag > 0, FALSE);
1359 source = g_main_context_find_source_by_id (NULL, tag);
1361 g_source_destroy (source);
1363 return source != NULL;
1367 * g_source_remove_by_user_data:
1368 * @user_data: the user_data for the callback.
1370 * Removes a source from the default main loop context given the user
1371 * data for the callback. If multiple sources exist with the same user
1372 * data, only one will be destroyed.
1374 * Return value: %TRUE if a source was found and removed.
1377 g_source_remove_by_user_data (gpointer user_data)
1381 source = g_main_context_find_source_by_user_data (NULL, user_data);
1384 g_source_destroy (source);
1392 * g_source_remove_by_funcs_user_data:
1393 * @funcs: The @source_funcs passed to g_source_new()
1394 * @user_data: the user data for the callback
1396 * Removes a source from the default main loop context given the
1397 * source functions and user data. If multiple sources exist with the
1398 * same source functions and user data, only one will be destroyed.
1400 * Return value: %TRUE if a source was found and removed.
1403 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1408 g_return_val_if_fail (funcs != NULL, FALSE);
1410 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1413 g_source_destroy (source);
1421 * g_get_current_time:
1422 * @result: #GTimeVal structure in which to store current time.
1424 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1427 g_get_current_time (GTimeVal *result)
1432 g_return_if_fail (result != NULL);
1434 /*this is required on alpha, there the timeval structs are int's
1435 not longs and a cast only would fail horribly*/
1436 gettimeofday (&r, NULL);
1437 result->tv_sec = r.tv_sec;
1438 result->tv_usec = r.tv_usec;
1440 /* Avoid calling time() except for the first time.
1441 * GetTickCount() should be pretty fast and low-level?
1442 * I could also use ftime() but it seems unnecessarily overheady.
1444 static DWORD start_tick = 0;
1445 static time_t start_time;
1448 g_return_if_fail (result != NULL);
1450 if (start_tick == 0)
1452 start_tick = GetTickCount ();
1456 tick = GetTickCount ();
1458 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1459 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1463 /* Running the main loop */
1465 /* HOLDS: context's lock */
1467 g_main_dispatch (GMainContext *context)
1471 for (i = 0; i < context->pending_dispatches->len; i++)
1473 GSource *source = context->pending_dispatches->pdata[i];
1475 context->pending_dispatches->pdata[i] = NULL;
1478 source->flags &= ~G_SOURCE_READY;
1480 if (!SOURCE_DESTROYED (source))
1482 gboolean was_in_call;
1483 gpointer user_data = NULL;
1484 GSourceFunc callback = NULL;
1485 GSourceCallbackFuncs *cb_funcs;
1487 gboolean need_destroy;
1489 gboolean (*dispatch) (GSource *,
1493 dispatch = source->source_funcs->dispatch;
1494 cb_funcs = source->callback_funcs;
1495 cb_data = source->callback_data;
1498 cb_funcs->ref (cb_data);
1500 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1501 source->flags |= G_HOOK_FLAG_IN_CALL;
1503 UNLOCK_CONTEXT (context);
1506 cb_funcs->get (cb_data, &callback, &user_data);
1508 need_destroy = ! dispatch (source,
1511 LOCK_CONTEXT (context);
1514 cb_funcs->unref (cb_data);
1517 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1519 /* Note: this depends on the fact that we can't switch
1520 * sources from one main context to another
1522 if (need_destroy && !SOURCE_DESTROYED (source))
1524 g_assert (source->context == context);
1525 g_source_destroy_internal (source, context, TRUE);
1529 SOURCE_UNREF (source, context);
1532 g_ptr_array_set_size (context->pending_dispatches, 0);
1535 /* Holds context's lock */
1536 static inline GSource *
1537 next_valid_source (GMainContext *context,
1540 GSource *new_source = source ? source->next : context->source_list;
1544 if (!SOURCE_DESTROYED (new_source))
1546 new_source->ref_count++;
1550 new_source = new_source->next;
1554 SOURCE_UNREF (source, context);
1561 * g_main_context_prepare:
1562 * @context: a #GMainContext
1563 * @priority: location to store priority of highest priority
1564 * source already ready.
1566 * Prepares to poll sources within a main loop. The resulting information
1567 * for polling is determined by calling g_main_context_query ().
1569 * Return value: %TRUE if some source is ready to be dispatched
1573 g_main_context_prepare (GMainContext *context,
1577 gint current_priority = G_MAXINT;
1580 if (context == NULL)
1581 context = g_main_context_default ();
1583 LOCK_CONTEXT (context);
1585 context->time_is_current = FALSE;
1587 if (context->in_check_or_prepare)
1589 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1590 "prepare() member.");
1594 #ifdef G_THREADS_ENABLED
1595 if (context->poll_waiting)
1597 g_warning("g_main_context_prepare(): main loop already active in another thread");
1598 UNLOCK_CONTEXT (context);
1602 context->poll_waiting = TRUE;
1603 #endif G_THREADS_ENABLED
1606 /* If recursing, finish up current dispatch, before starting over */
1607 if (context->pending_dispatches)
1610 g_main_dispatch (context, ¤t_time);
1612 UNLOCK_CONTEXT (context);
1617 /* If recursing, clear list of pending dispatches */
1618 g_ptr_array_set_size (context->pending_dispatches, 0);
1620 /* Prepare all sources */
1622 context->timeout = -1;
1624 source = next_valid_source (context, NULL);
1627 gint source_timeout = -1;
1629 if ((n_ready > 0) && (source->priority > current_priority))
1631 SOURCE_UNREF (source, context);
1634 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1637 if (!(source->flags & G_SOURCE_READY))
1640 gboolean (*prepare) (GSource *source,
1643 prepare = source->source_funcs->prepare;
1644 context->in_check_or_prepare++;
1645 UNLOCK_CONTEXT (context);
1647 result = (*prepare) (source, &source_timeout);
1649 LOCK_CONTEXT (context);
1650 context->in_check_or_prepare--;
1653 source->flags |= G_SOURCE_READY;
1656 if (source->flags & G_SOURCE_READY)
1659 current_priority = source->priority;
1660 context->timeout = 0;
1663 if (source_timeout >= 0)
1665 if (context->timeout < 0)
1666 context->timeout = source_timeout;
1668 context->timeout = MIN (context->timeout, source_timeout);
1672 source = next_valid_source (context, source);
1675 UNLOCK_CONTEXT (context);
1678 *priority = current_priority;
1680 return (n_ready > 0);
1684 * g_main_context_query:
1685 * @context: a #GMainContext
1686 * @max_priority: maximum priority source to check
1687 * @timeout: location to store timeout to be used in polling
1688 * @fds: location to store #GPollFD records that need to be polled.
1689 * @n_fds: length of @fds.
1691 * Determines information necessary to poll this main loop.
1696 g_main_context_query (GMainContext *context,
1705 LOCK_CONTEXT (context);
1707 pollrec = context->poll_records;
1709 while (pollrec && max_priority >= pollrec->priority)
1711 if (pollrec->fd->events)
1715 fds[n_poll].fd = pollrec->fd->fd;
1716 /* In direct contradiction to the Unix98 spec, IRIX runs into
1717 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1718 * flags in the events field of the pollfd while it should
1719 * just ignoring them. So we mask them out here.
1721 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1722 fds[n_poll].revents = 0;
1727 pollrec = pollrec->next;
1730 context->poll_changed = FALSE;
1734 *timeout = context->timeout;
1736 context->time_is_current = FALSE;
1739 UNLOCK_CONTEXT (context);
1745 * g_main_context_check:
1746 * @context: a #GMainContext
1747 * @max_priority: the maximum numerical priority of sources to check
1748 * @fds: array of #GPollFD's that was passed to the last call to
1749 * g_main_context_query()
1750 * @n_fds: return value of g_main_context_query()
1752 * Pass the results of polling back to the main loop.
1754 * Return value: %TRUE if some sources are ready to be dispatched.
1757 g_main_context_check (GMainContext *context,
1767 LOCK_CONTEXT (context);
1769 if (context->in_check_or_prepare)
1771 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1772 "prepare() member.");
1776 #ifdef G_THREADS_ENABLED
1777 if (!context->poll_waiting)
1781 read (context->wake_up_pipe[0], &c, 1);
1785 context->poll_waiting = FALSE;
1786 #endif /* G_THREADS_ENABLED */
1788 /* If the set of poll file descriptors changed, bail out
1789 * and let the main loop rerun
1791 if (context->poll_changed)
1794 pollrec = context->poll_records;
1798 if (pollrec->fd->events)
1800 pollrec->fd->revents = fds[i].revents;
1803 pollrec = pollrec->next;
1806 source = next_valid_source (context, NULL);
1809 if ((n_ready > 0) && (source->priority > max_priority))
1811 SOURCE_UNREF (source, context);
1814 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1817 if (!(source->flags & G_SOURCE_READY))
1820 gboolean (*check) (GSource *source);
1822 check = source->source_funcs->check;
1824 context->in_check_or_prepare++;
1825 UNLOCK_CONTEXT (context);
1827 result = (*check) (source);
1829 LOCK_CONTEXT (context);
1830 context->in_check_or_prepare--;
1833 source->flags |= G_SOURCE_READY;
1836 if (source->flags & G_SOURCE_READY)
1838 source->ref_count++;
1839 g_ptr_array_add (context->pending_dispatches, source);
1845 source = next_valid_source (context, source);
1848 UNLOCK_CONTEXT (context);
1854 * g_main_context_dispatch:
1855 * @context: a #GMainContext
1857 * Dispatch all pending sources()
1860 g_main_context_dispatch (GMainContext *context)
1862 LOCK_CONTEXT (context);
1864 if (context->pending_dispatches->len > 0)
1866 g_main_dispatch (context);
1869 UNLOCK_CONTEXT (context);
1873 g_main_context_iterate (GMainContext *context,
1879 gboolean some_ready;
1880 gint nfds, new_nfds;
1883 some_ready = g_main_context_prepare (context, &max_priority);
1887 LOCK_CONTEXT (context);
1889 if (context->cached_poll_array)
1891 nfds = context->cached_poll_array_size;
1892 fds = context->cached_poll_array;
1893 context->cached_poll_array = NULL;
1897 nfds = context->cached_poll_array_size = context->n_poll_records;
1898 fds = g_new (GPollFD, nfds);
1901 UNLOCK_CONTEXT (context);
1903 new_nfds = g_main_context_query (context, max_priority,
1904 &timeout, fds, nfds);
1906 while (new_nfds > nfds);
1911 g_main_context_poll (context, timeout, max_priority,
1914 g_main_context_check (context,
1918 LOCK_CONTEXT (context);
1920 g_assert (!context->cached_poll_array);
1922 context->cached_poll_array = fds;
1923 context->cached_poll_array_size = nfds;
1925 UNLOCK_CONTEXT (context);
1928 g_main_context_dispatch (context);
1934 * g_main_context_pending:
1935 * @context: a #GMainContext (if %NULL, the default context will be used)
1937 * Check if any sources have pending events for the given context.
1939 * Return value: %TRUE if events are pending.
1942 g_main_context_pending (GMainContext *context)
1945 context = g_main_context_default();
1947 return g_main_context_iterate (context, FALSE, FALSE);
1951 * g_main_context_iteration:
1952 * @context: a #GMainContext (if %NULL, the default context will be used)
1953 * @may_block: whether the call may block.
1955 * Run a single iteration for the given main loop. This involves
1956 * checking to see if any event sources are ready to be processed,
1957 * then if no events sources are ready and @may_block is %TRUE, waiting
1958 * for a source to become ready, then dispatching the highest priority
1959 * events sources that are ready. Note that even when @may_block is %TRUE,
1960 * it is still possible for g_main_context_iteration() to return
1961 * %FALSE, since the the wait may be interrupted for other
1962 * reasons than an event source becoming ready.
1964 * Return value: %TRUE if events were dispatched.
1967 g_main_context_iteration (GMainContext *context, gboolean may_block)
1970 context = g_main_context_default();
1972 return g_main_context_iterate (context, may_block, TRUE);
1977 * @context: a #GMainContext (if %NULL, the default context will be used).
1978 * @is_running: set to TRUE to indicate that the loop is running. This
1979 * is not very important since calling g_main_run() will set this to
1982 * Create a new #GMainLoop structure
1987 g_main_loop_new (GMainContext *context,
1988 gboolean is_running)
1993 context = g_main_context_default();
1995 loop = g_new0 (GMainLoop, 1);
1996 loop->context = context;
1997 loop->is_running = is_running != FALSE;
1999 #ifdef G_THREADS_ENABLED
2000 if (g_thread_supported ())
2001 loop->mutex = g_mutex_new ();
2004 loop->sem_cond = NULL;
2005 #endif G_THREADS_ENABLED
2012 * @loop: a #GMainLoop
2014 * Run a main loop until g_main_quit() is called on the loop.
2015 * If this is called for the thread of the loop's #GMainContext,
2016 * it will process events from the loop, otherwise it will
2020 g_main_loop_run (GMainLoop *loop)
2022 g_return_if_fail (loop != NULL);
2024 #ifdef G_THREADS_ENABLED
2025 if (loop->context->thread != g_thread_self ())
2029 if (!g_thread_supported ())
2031 g_warning ("g_main_loop_run() was called from second thread but"
2032 "g_thread_init() was never called.");
2036 if (!loop->sem_cond)
2037 loop->sem_cond = g_cond_new ();
2039 if (!loop->is_running)
2040 loop->is_running = TRUE;
2042 while (loop->is_running)
2043 g_cond_wait (loop->sem_cond, loop->mutex);
2049 #endif /* G_THREADS_ENABLED */
2051 LOCK_CONTEXT (loop->context);
2052 if (loop->context->in_check_or_prepare)
2054 g_warning ("g_main_run(): called recursively from within a source's check() or "
2055 "prepare() member, iteration not possible.");
2058 UNLOCK_CONTEXT (loop->context);
2062 loop->is_running = TRUE;
2063 while (loop->is_running)
2066 g_main_context_iterate (loop->context, TRUE, TRUE);
2075 * @loop: a #GMainLoop
2077 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2078 * for the loop will return.
2081 g_main_loop_quit (GMainLoop *loop)
2083 g_return_if_fail (loop != NULL);
2086 loop->is_running = FALSE;
2089 g_cond_broadcast (loop->sem_cond);
2093 LOCK_CONTEXT (loop->context);
2095 g_main_context_wakeup (loop->context);
2096 UNLOCK_CONTEXT (loop->context);
2100 * g_main_loop_destroy:
2101 * @loop: a #GMainLoop
2103 * Destroy a #GMainLoop object and free all associated memory.
2104 * The loop must not currently be running via g_main_run().
2107 g_main_loop_destroy (GMainLoop *loop)
2109 g_return_if_fail (loop != NULL);
2110 g_return_if_fail (!loop->is_running);
2112 #ifdef G_THREADS_ENABLED
2113 g_mutex_free (loop->mutex);
2115 g_cond_free (loop->sem_cond);
2116 #endif /* G_THREADS_ENABLED */
2122 * g_main_loop_is_running:
2123 * @loop: a #GMainLoop.
2125 * Check to see if the main loop is currently being run via g_main_run()
2127 * Return value: %TRUE if the mainloop is currently being run.
2130 g_main_loop_is_running (GMainLoop *loop)
2134 g_return_val_if_fail (loop != NULL, FALSE);
2137 result = loop->is_running;
2143 /* HOLDS: context's lock */
2145 g_main_context_poll (GMainContext *context,
2151 #ifdef G_MAIN_POLL_DEBUG
2157 GPollFunc poll_func;
2159 if (n_fds || timeout != 0)
2161 #ifdef G_MAIN_POLL_DEBUG
2162 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2163 poll_timer = g_timer_new ();
2166 LOCK_CONTEXT (context);
2168 poll_func = context->poll_func;
2170 UNLOCK_CONTEXT (context);
2171 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2172 g_warning ("poll(2) failed due to: %s.",
2173 g_strerror (errno));
2175 #ifdef G_MAIN_POLL_DEBUG
2176 LOCK_CONTEXT (context);
2178 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2181 g_timer_elapsed (poll_timer, NULL));
2182 g_timer_destroy (poll_timer);
2183 pollrec = context->poll_records;
2187 if (pollrec->fd->events)
2191 g_print (" [%d:", fds[i].fd);
2192 if (fds[i].revents & G_IO_IN)
2194 if (fds[i].revents & G_IO_OUT)
2196 if (fds[i].revents & G_IO_PRI)
2198 if (fds[i].revents & G_IO_ERR)
2200 if (fds[i].revents & G_IO_HUP)
2202 if (fds[i].revents & G_IO_NVAL)
2208 pollrec = pollrec->next;
2212 UNLOCK_CONTEXT (context);
2214 } /* if (n_fds || timeout != 0) */
2218 * g_main_context_add_poll:
2219 * @context: a #GMainContext (or %NULL for the default context)
2220 * @fd: a #GPollFD structure holding information about a file
2221 * descriptor to watch.
2222 * @priority: the priority for this file descriptor which should be
2223 * the same as the priority used for g_source_attach() to ensure that the
2224 * file descriptor is polled whenever the results may be needed.
2226 * Add a file descriptor to the set of file descriptors polled * for
2227 * this context. This will very seldom be used directly. Instead
2228 * a typical event source will use g_source_add_poll() instead.
2231 g_main_context_add_poll (GMainContext *context,
2236 context = g_main_context_default ();
2238 LOCK_CONTEXT (context);
2239 g_main_context_add_poll_unlocked (context, priority, fd);
2240 UNLOCK_CONTEXT (context);
2243 /* HOLDS: main_loop_lock */
2245 g_main_context_add_poll_unlocked (GMainContext *context,
2249 GPollRec *lastrec, *pollrec, *newrec;
2251 if (!context->poll_chunk)
2252 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2254 if (context->poll_free_list)
2256 newrec = context->poll_free_list;
2257 context->poll_free_list = newrec->next;
2260 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2262 /* This file descriptor may be checked before we ever poll */
2265 newrec->priority = priority;
2268 pollrec = context->poll_records;
2269 while (pollrec && priority >= pollrec->priority)
2272 pollrec = pollrec->next;
2276 lastrec->next = newrec;
2278 context->poll_records = newrec;
2280 newrec->next = pollrec;
2282 context->n_poll_records++;
2283 if (context->cached_poll_array &&
2284 context->cached_poll_array_size < context->n_poll_records)
2286 g_free (context->cached_poll_array);
2287 context->cached_poll_array = NULL;
2290 #ifdef G_THREADS_ENABLED
2291 context->poll_changed = TRUE;
2293 /* Now wake up the main loop if it is waiting in the poll() */
2294 g_main_context_wakeup (context);
2299 * g_main_context_remove_poll:
2300 * @context:a #GMainContext
2301 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2303 * Remove file descriptor from the set of file descriptors to be
2304 * polled for a particular context.
2307 g_main_context_remove_poll (GMainContext *context,
2311 context = g_main_context_default ();
2313 LOCK_CONTEXT (context);
2315 g_main_context_remove_poll_unlocked (context, fd);
2317 UNLOCK_CONTEXT (context);
2321 g_main_context_remove_poll_unlocked (GMainContext *context,
2324 GPollRec *pollrec, *lastrec;
2327 pollrec = context->poll_records;
2331 if (pollrec->fd == fd)
2333 if (lastrec != NULL)
2334 lastrec->next = pollrec->next;
2336 context->poll_records = pollrec->next;
2338 #ifdef ENABLE_GC_FRIENDLY
2340 #endif /* ENABLE_GC_FRIENDLY */
2342 pollrec->next = context->poll_free_list;
2343 context->poll_free_list = pollrec;
2345 context->n_poll_records--;
2349 pollrec = pollrec->next;
2352 #ifdef G_THREADS_ENABLED
2353 context->poll_changed = TRUE;
2355 /* Now wake up the main loop if it is waiting in the poll() */
2356 g_main_context_wakeup (context);
2361 * g_source_get_current_time:
2362 * @source: a #GSource
2363 * @timeval: #GTimeVal structure in which to store current time.
2365 * Gets the "current time" to be used when checking
2366 * this source. The advantage of calling this function over
2367 * calling g_get_current_time() directly is that when
2368 * checking multiple sources, GLib can cache a single value
2369 * instead of having to repeatedly get the system time.
2372 g_source_get_current_time (GSource *source,
2375 GMainContext *context;
2377 g_return_if_fail (source->context != NULL);
2379 context = source->context;
2381 LOCK_CONTEXT (context);
2383 if (!context->time_is_current)
2385 g_get_current_time (&context->current_time);
2386 context->time_is_current = TRUE;
2389 *timeval = context->current_time;
2391 UNLOCK_CONTEXT (context);
2395 * g_main_context_set_poll_func:
2396 * @context: a #GMainContext
2397 * @func: the function to call to poll all file descriptors
2399 * Sets the function to use to handle polling of file descriptors. It
2400 * will be used instead of the poll() system call (or GLib's
2401 * replacement function, which is used where poll() isn't available).
2403 * This function could possibly be used to integrate the GLib event
2404 * loop with an external event loop.
2407 g_main_context_set_poll_func (GMainContext *context,
2411 context = g_main_context_default ();
2413 LOCK_CONTEXT (context);
2416 context->poll_func = func;
2420 context->poll_func = (GPollFunc) poll;
2422 context->poll_func = (GPollFunc) g_poll;
2426 UNLOCK_CONTEXT (context);
2432 * g_main_context_get_poll_func:
2433 * @context: a #GMainContext
2435 * Gets the poll function set by g_main_context_set_poll_func()
2437 * Return value: the poll function
2440 g_main_context_get_poll_func (GMainContext *context)
2445 context = g_main_context_default ();
2447 LOCK_CONTEXT (context);
2448 result = context->poll_func;
2449 UNLOCK_CONTEXT (context);
2454 /* HOLDS: context's lock */
2455 /* Wake the main loop up from a poll() */
2457 g_main_context_wakeup (GMainContext *context)
2459 #ifdef G_THREADS_ENABLED
2460 if (g_thread_supported() && context->poll_waiting)
2462 context->poll_waiting = FALSE;
2464 write (context->wake_up_pipe[1], "A", 1);
2466 ReleaseSemaphore (context->context->wake_up_semaphore, 1, NULL);
2475 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2476 GTimeVal *current_time)
2478 guint seconds = timeout_source->interval / 1000;
2479 guint msecs = timeout_source->interval - seconds * 1000;
2481 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2482 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2483 if (timeout_source->expiration.tv_usec >= 1000000)
2485 timeout_source->expiration.tv_usec -= 1000000;
2486 timeout_source->expiration.tv_sec++;
2491 g_timeout_prepare (GSource *source,
2495 GTimeVal current_time;
2497 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2499 g_source_get_current_time (source, ¤t_time);
2501 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2502 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2506 else if (msec > timeout_source->interval)
2508 /* The system time has been set backwards, so we
2509 * reset the expiration time to now + timeout_source->interval;
2510 * this at least avoids hanging for long periods of time.
2512 g_timeout_set_expiration (timeout_source, ¤t_time);
2513 msec = timeout_source->interval;
2522 g_timeout_check (GSource *source)
2524 GTimeVal current_time;
2525 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2527 g_source_get_current_time (source, ¤t_time);
2529 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2530 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2531 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2535 g_timeout_dispatch (GSource *source,
2536 GSourceFunc callback,
2539 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2543 g_warning ("Timeout source dispatched without callback\n"
2544 "You must call g_source_set_callback().");
2548 if (callback (user_data))
2550 GTimeVal current_time;
2552 g_source_get_current_time (source, ¤t_time);
2553 g_timeout_set_expiration (timeout_source, ¤t_time);
2562 * g_timeout_source_new:
2563 * @interval: the timeout interval in milliseconds.
2565 * Create a new timeout source.
2567 * The source will not initially be associated with any #GMainContext
2568 * and must be added to one with g_source_attach() before it will be
2571 * Return value: the newly create timeout source
2574 g_timeout_source_new (guint interval)
2576 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2577 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2578 GTimeVal current_time;
2580 timeout_source->interval = interval;
2582 g_get_current_time (¤t_time);
2583 g_timeout_set_expiration (timeout_source, ¤t_time);
2589 * g_timeout_add_full:
2590 * @priority: the priority of the idle source. Typically this will be in the
2591 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2592 * @interval: the time between calls to the function, in milliseconds
2593 * (1/1000ths of a second.)
2594 * @function: function to call
2595 * @data: data to pass to @function
2596 * @notify: function to call when the idle is removed, or %NULL
2598 * Sets a function to be called at regular intervals, with the given
2599 * priority. The function is called repeatedly until it returns
2600 * FALSE, at which point the timeout is automatically destroyed and
2601 * the function will not be called again. The @notify function is
2602 * called when the timeout is destroyed. The first call to the
2603 * function will be at the end of the first @interval.
2605 * Note that timeout functions may be delayed, due to the processing of other
2606 * event sources. Thus they should not be relied on for precise timing.
2607 * After each call to the timeout function, the time of the next
2608 * timeout is recalculated based on the current time and the given interval
2609 * (it does not try to 'catch up' time lost in delays).
2611 * Return value: the id of event source.
2614 g_timeout_add_full (gint priority,
2616 GSourceFunc function,
2618 GDestroyNotify notify)
2622 g_return_val_if_fail (function != NULL, 0);
2624 source = g_timeout_source_new (interval);
2626 if (priority != G_PRIORITY_DEFAULT)
2627 g_source_set_priority (source, priority);
2629 g_source_set_callback (source, function, data, notify);
2630 return g_source_attach (source, NULL);
2635 * @interval: the time between calls to the function, in milliseconds
2636 * (1/1000ths of a second.)
2637 * @function: function to call
2638 * @data: data to pass to @function
2640 * Sets a function to be called at regular intervals, with the default
2641 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2642 * until it returns FALSE, at which point the timeout is automatically
2643 * destroyed and the function will not be called again. The @notify
2644 * function is called when the timeout is destroyed. The first call
2645 * to the function will be at the end of the first @interval.
2647 * Note that timeout functions may be delayed, due to the processing of other
2648 * event sources. Thus they should not be relied on for precise timing.
2649 * After each call to the timeout function, the time of the next
2650 * timeout is recalculated based on the current time and the given interval
2651 * (it does not try to 'catch up' time lost in delays).
2653 * Return value: the id of event source.
2656 g_timeout_add (guint32 interval,
2657 GSourceFunc function,
2660 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2661 interval, function, data, NULL);
2664 /* Idle functions */
2667 g_idle_prepare (GSource *source,
2676 g_idle_check (GSource *source)
2682 g_idle_dispatch (GSource *source,
2683 GSourceFunc callback,
2688 g_warning ("Idle source dispatched without callback\n"
2689 "You must call g_source_set_callback().");
2693 return callback (user_data);
2697 * g_idle_source_new:
2699 * Create a new idle source.
2701 * The source will not initially be associated with any #GMainContext
2702 * and must be added to one with g_source_attach() before it will be
2705 * Return value: the newly created idle source
2708 g_idle_source_new (void)
2710 return g_source_new (&idle_funcs, sizeof (GSource));
2715 * @priority: the priority of the idle source. Typically this will be in the
2716 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2717 * @function: function to call
2718 * @data: data to pass to @function
2719 * @notify: function to call when the idle is removed, or %NULL
2721 * Adds a function to be called whenever there are no higher priority
2722 * events pending. If the function returns FALSE it is automatically
2723 * removed from the list of event sources and will not be called again.
2725 * Return value: the id of the event source.
2728 g_idle_add_full (gint priority,
2729 GSourceFunc function,
2731 GDestroyNotify notify)
2735 g_return_val_if_fail (function != NULL, 0);
2737 source = g_idle_source_new ();
2739 if (priority != G_PRIORITY_DEFAULT)
2740 g_source_set_priority (source, priority);
2742 g_source_set_callback (source, function, data, notify);
2743 return g_source_attach (source, NULL);
2748 * @function: function to call
2749 * @data: data to pass to @function.
2751 * Adds a function to be called whenever there are no higher priority
2752 * events pending to the default main loop. The function is given the
2753 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2754 * returns FALSE it is automatically removed from the list of event
2755 * sources and will not be called again.
2757 * Return value: the id of the event source.
2760 g_idle_add (GSourceFunc function,
2763 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2767 * g_idle_remove_by_data:
2768 * @data: the data for the idle source's callback.
2770 * Removes the idle function with the given data.
2772 * Return value: %TRUE if an idle source was found and removed.
2775 g_idle_remove_by_data (gpointer data)
2777 return g_source_remove_by_funcs_user_data (&idle_funcs, data);