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))
786 gpointer old_cb_data;
787 GSourceCallbackFuncs *old_cb_funcs;
789 source->flags &= ~G_HOOK_FLAG_ACTIVE;
791 old_cb_data = source->callback_data;
792 old_cb_funcs = source->callback_funcs;
794 source->callback_data = NULL;
795 source->callback_funcs = NULL;
799 UNLOCK_CONTEXT (context);
800 old_cb_funcs->unref (old_cb_data);
801 LOCK_CONTEXT (context);
804 tmp_list = source->poll_fds;
807 g_main_context_remove_poll_unlocked (context, tmp_list->data);
808 tmp_list = tmp_list->next;
811 g_source_unref_internal (source, context, TRUE);
815 UNLOCK_CONTEXT (context);
820 * @source: a #GSource
822 * Remove a source from its #GMainContext, if any, and mark it as
823 * destroyed. The source cannot be subsequently added to another
827 g_source_destroy (GSource *source)
829 GMainContext *context;
831 g_return_if_fail (source != NULL);
833 context = source->context;
836 g_source_destroy_internal (source, context, FALSE);
838 source->flags &= ~G_HOOK_FLAG_ACTIVE;
843 * @source: a #GSource
845 * Return the numeric ID for a particular source. The ID of a source
846 * is unique within a particular main loop context. The reverse
847 * mapping from ID to source is done by g_main_context_find_source_by_id().
849 * Return value: the ID for the source
852 g_source_get_id (GSource *source)
856 g_return_val_if_fail (source != NULL, 0);
857 g_return_val_if_fail (source->context != NULL, 0);
859 LOCK_CONTEXT (source->context);
861 UNLOCK_CONTEXT (source->context);
867 * g_source_get_context:
868 * @source: a #GSource
870 * Get the #GMainContext with which the source is associated.
871 * Calling this function on a destroyed source is an error.
873 * Return value: the #GMainContext with which the source is associated,
874 * or %NULL if the context has not yet been added
878 g_source_get_context (GSource *source)
880 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
882 return source->context;
886 * g_main_source_add_poll:
888 * @fd: a #GPollFD structure holding information about a file
889 * descriptor to watch.
891 * Add a file descriptor to the set of file descriptors polled * for
892 * this source. This is usually combined with g_source_new() to add an
893 * event source. The event source's check function will typically test
894 * the revents field in the #GPollFD struct and return %TRUE if events need
898 g_source_add_poll (GSource *source,
901 GMainContext *context;
903 g_return_if_fail (source != NULL);
904 g_return_if_fail (fd != NULL);
905 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
907 context = source->context;
910 LOCK_CONTEXT (context);
912 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
916 g_main_context_add_poll_unlocked (context, source->priority, fd);
917 UNLOCK_CONTEXT (context);
922 * g_source_set_callback_indirect:
923 * @source: the source
924 * @callback_data: pointer to callback data "object"
925 * @callback_funcs: functions for reference counting callback_data
926 * and getting the callback and data
928 * Set the callback function storing the data as a refcounted callback
929 * "object". This is used to implement g_source_set_callback_closure()
930 * and internally. Note that calling g_source_set_callback_indirect() assumes
931 * an initial reference count on @callback_data, and thus
932 * @callback_funcs->unref will eventually be called once more
933 * than @callback_funcs->ref.
936 g_source_set_callback_indirect (GSource *source,
937 gpointer callback_data,
938 GSourceCallbackFuncs *callback_funcs)
940 GMainContext *context;
941 gpointer old_cb_data;
942 GSourceCallbackFuncs *old_cb_funcs;
944 g_return_if_fail (source != NULL);
945 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
947 context = source->context;
950 LOCK_CONTEXT (context);
952 old_cb_data = source->callback_data;
953 old_cb_funcs = source->callback_funcs;
955 source->callback_data = callback_data;
956 source->callback_funcs = callback_funcs;
959 UNLOCK_CONTEXT (context);
962 old_cb_funcs->unref (old_cb_data);
966 g_source_callback_ref (gpointer cb_data)
968 GSourceCallback *callback = cb_data;
970 callback->ref_count++;
975 g_source_callback_unref (gpointer cb_data)
977 GSourceCallback *callback = cb_data;
979 callback->ref_count--;
980 if (callback->ref_count == 0)
982 if (callback->notify)
983 callback->notify (callback->data);
988 g_source_callback_get (gpointer cb_data,
992 GSourceCallback *callback = cb_data;
994 *func = callback->func;
995 *data = callback->data;
998 static GSourceCallbackFuncs g_source_callback_funcs = {
999 g_source_callback_ref,
1000 g_source_callback_unref,
1001 g_source_callback_get,
1005 * g_source_set_callback:
1006 * @source: the source
1007 * @func: a callback function
1008 * @data: the data to pass to callback function
1009 * @notify: a function to call when @data is no longer in use, or %NULL.
1011 * Set the callback function for a source.
1014 g_source_set_callback (GSource *source,
1017 GDestroyNotify notify)
1019 GSourceCallback *new_callback;
1021 g_return_if_fail (source != NULL);
1023 new_callback = g_new (GSourceCallback, 1);
1025 new_callback->func = func;
1026 new_callback->data = data;
1027 new_callback->notify = notify;
1029 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1033 * g_source_set_priority:
1034 * @source: a #GSource
1035 * @priority: the new priority.
1037 * Set the priority of a source. While the main loop is being
1038 * run, a source will
1041 g_source_set_priority (GSource *source,
1045 GMainContext *context;
1047 g_return_if_fail (source != NULL);
1049 context = source->context;
1052 LOCK_CONTEXT (context);
1054 source->priority = priority;
1058 source->next = NULL;
1059 source->prev = NULL;
1061 tmp_list = source->poll_fds;
1064 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1065 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1067 tmp_list = tmp_list->next;
1070 UNLOCK_CONTEXT (source->context);
1075 * g_source_get_priority:
1076 * @source: a #GSource
1078 * Gets the priority of a surce
1080 * Return value: the priority of the source
1083 g_source_get_priority (GSource *source)
1085 g_return_val_if_fail (source != NULL, 0);
1087 return source->priority;
1091 * g_source_set_can_recurse:
1092 * @source: a #GSource
1093 * @can_recurse: whether recursion is allowed for this source
1095 * Sets whether a source can be called recursively. If @can_recurse is
1096 * %TRUE, then while the source is being dispatched then this source
1097 * will be processed normally. Otherwise, all processing of this
1098 * source is blocked until the dispatch function returns.
1101 g_source_set_can_recurse (GSource *source,
1102 gboolean can_recurse)
1104 GMainContext *context;
1106 g_return_if_fail (source != NULL);
1108 context = source->context;
1111 LOCK_CONTEXT (context);
1114 source->flags |= G_SOURCE_CAN_RECURSE;
1116 source->flags &= ~G_SOURCE_CAN_RECURSE;
1119 UNLOCK_CONTEXT (context);
1123 * g_source_get_can_recurse:
1124 * @source: a #GSource
1126 * Checks whether a source is allowed to be called recursively.
1127 * see g_source_set_can_recurse.
1129 * Return value: whether recursion is allowed.
1132 g_source_get_can_recurse (GSource *source)
1134 g_return_val_if_fail (source != NULL, FALSE);
1136 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1141 * @source: a #GSource
1143 * Increases the reference count on a source by one.
1145 * Return value: @source
1148 g_source_ref (GSource *source)
1150 GMainContext *context;
1152 g_return_val_if_fail (source != NULL, NULL);
1154 context = source->context;
1157 LOCK_CONTEXT (context);
1159 source->ref_count++;
1162 UNLOCK_CONTEXT (context);
1167 /* g_source_unref() but possible to call within context lock
1170 g_source_unref_internal (GSource *source,
1171 GMainContext *context,
1174 gpointer cb_data = NULL;
1175 GSourceCallbackFuncs *cb_funcs = NULL;
1178 g_return_if_fail (source != NULL);
1180 if (!have_lock && context)
1181 LOCK_CONTEXT (context);
1183 source->ref_count--;
1184 if (source->ref_count == 0)
1186 if (context && !SOURCE_DESTROYED (source))
1188 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1189 source->ref_count++;
1192 g_source_list_remove (source, context);
1194 if (source->source_funcs->destroy)
1195 source->source_funcs->destroy (source);
1197 g_slist_free (source->poll_fds);
1198 source->poll_fds = NULL;
1202 if (!have_lock && context)
1203 UNLOCK_CONTEXT (context);
1208 UNLOCK_CONTEXT (context);
1210 cb_funcs->unref (cb_data);
1213 LOCK_CONTEXT (context);
1219 * @source: a #GSource
1221 * Decreases the reference count of a source by one. If the
1222 * resulting reference count is zero the source and associated
1223 * memory will be destroyed.
1226 g_source_unref (GSource *source)
1228 g_return_if_fail (source != NULL);
1230 g_source_unref_internal (source, source->context, FALSE);
1234 * g_main_context_find_source_by_id:
1235 * @context: a #GMainContext (if %NULL, the default context will be used)
1236 * @id: the source ID, as returned by g_source_get_id()
1238 * Finds a #GSource given a pair of context and ID
1240 * Return value: the #GSource if found, otherwise, %NULL
1243 g_main_context_find_source_by_id (GMainContext *context,
1248 g_return_val_if_fail (id > 0, FALSE);
1250 if (context == NULL)
1251 context = g_main_context_default ();
1253 LOCK_CONTEXT (context);
1255 source = context->source_list;
1258 if (!SOURCE_DESTROYED (source) &&
1261 source = source->next;
1264 UNLOCK_CONTEXT (context);
1270 * g_main_context_find_source_by_funcs_user_data:
1271 * @context: a #GMainContext (if %NULL, the default context will be used).
1272 * @funcs: the @source_funcs passed to g_source_new().
1273 * @user_data: the user data from the callback.
1275 * Finds a source with the given source functions and user data. If
1276 * multiple sources exist with the same source function and user data,
1277 * the first one found will be returned.
1279 * Return value: the source, if one was found, otherwise %NULL
1282 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1283 GSourceFuncs *funcs,
1288 g_return_val_if_fail (funcs != NULL, FALSE);
1290 if (context == NULL)
1291 context = g_main_context_default ();
1293 LOCK_CONTEXT (context);
1295 source = context->source_list;
1298 if (!SOURCE_DESTROYED (source) &&
1299 source->source_funcs == funcs &&
1300 source->callback_data == user_data)
1302 source = source->next;
1305 UNLOCK_CONTEXT (context);
1311 * g_main_context_find_source_by_user_data:
1312 * @context: a #GMainContext
1313 * @user_data: the user_data for the callback.
1315 * Finds a source with the given user data for the callback. If
1316 * multiple sources exist with the same user data, the first
1317 * one found will be returned.
1319 * Return value: the source, if one was found, otherwise %NULL
1322 g_main_context_find_source_by_user_data (GMainContext *context,
1327 if (context == NULL)
1328 context = g_main_context_default ();
1330 LOCK_CONTEXT (context);
1332 source = context->source_list;
1335 if (!SOURCE_DESTROYED (source) &&
1336 source->callback_data == user_data)
1338 source = source->next;
1341 UNLOCK_CONTEXT (context);
1348 * @tag: the id of the source to remove.
1350 * Removes the source with the given id from the default main
1351 * context. The id of a #GSource is given by g_source_get_id(),
1352 * or will be returned by the functions g_source_attach(),
1353 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1354 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1356 * See also g_source_destroy().
1358 * Return value: %TRUE if the source was found and removed.
1361 g_source_remove (guint tag)
1365 g_return_val_if_fail (tag > 0, FALSE);
1367 source = g_main_context_find_source_by_id (NULL, tag);
1369 g_source_destroy (source);
1371 return source != NULL;
1375 * g_source_remove_by_user_data:
1376 * @user_data: the user_data for the callback.
1378 * Removes a source from the default main loop context given the user
1379 * data for the callback. If multiple sources exist with the same user
1380 * data, only one will be destroyed.
1382 * Return value: %TRUE if a source was found and removed.
1385 g_source_remove_by_user_data (gpointer user_data)
1389 source = g_main_context_find_source_by_user_data (NULL, user_data);
1392 g_source_destroy (source);
1400 * g_source_remove_by_funcs_user_data:
1401 * @funcs: The @source_funcs passed to g_source_new()
1402 * @user_data: the user data for the callback
1404 * Removes a source from the default main loop context given the
1405 * source functions and user data. If multiple sources exist with the
1406 * same source functions and user data, only one will be destroyed.
1408 * Return value: %TRUE if a source was found and removed.
1411 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1416 g_return_val_if_fail (funcs != NULL, FALSE);
1418 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1421 g_source_destroy (source);
1429 * g_get_current_time:
1430 * @result: #GTimeVal structure in which to store current time.
1432 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1435 g_get_current_time (GTimeVal *result)
1440 g_return_if_fail (result != NULL);
1442 /*this is required on alpha, there the timeval structs are int's
1443 not longs and a cast only would fail horribly*/
1444 gettimeofday (&r, NULL);
1445 result->tv_sec = r.tv_sec;
1446 result->tv_usec = r.tv_usec;
1448 /* Avoid calling time() except for the first time.
1449 * GetTickCount() should be pretty fast and low-level?
1450 * I could also use ftime() but it seems unnecessarily overheady.
1452 static DWORD start_tick = 0;
1453 static time_t start_time;
1456 g_return_if_fail (result != NULL);
1458 if (start_tick == 0)
1460 start_tick = GetTickCount ();
1464 tick = GetTickCount ();
1466 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1467 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1471 /* Running the main loop */
1473 /* HOLDS: context's lock */
1475 g_main_dispatch (GMainContext *context)
1479 for (i = 0; i < context->pending_dispatches->len; i++)
1481 GSource *source = context->pending_dispatches->pdata[i];
1483 context->pending_dispatches->pdata[i] = NULL;
1486 source->flags &= ~G_SOURCE_READY;
1488 if (!SOURCE_DESTROYED (source))
1490 gboolean was_in_call;
1491 gpointer user_data = NULL;
1492 GSourceFunc callback = NULL;
1493 GSourceCallbackFuncs *cb_funcs;
1495 gboolean need_destroy;
1497 gboolean (*dispatch) (GSource *,
1501 dispatch = source->source_funcs->dispatch;
1502 cb_funcs = source->callback_funcs;
1503 cb_data = source->callback_data;
1506 cb_funcs->ref (cb_data);
1508 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1509 source->flags |= G_HOOK_FLAG_IN_CALL;
1511 UNLOCK_CONTEXT (context);
1514 cb_funcs->get (cb_data, &callback, &user_data);
1516 need_destroy = ! dispatch (source,
1519 LOCK_CONTEXT (context);
1522 cb_funcs->unref (cb_data);
1525 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1527 /* Note: this depends on the fact that we can't switch
1528 * sources from one main context to another
1530 if (need_destroy && !SOURCE_DESTROYED (source))
1532 g_assert (source->context == context);
1533 g_source_destroy_internal (source, context, TRUE);
1537 SOURCE_UNREF (source, context);
1540 g_ptr_array_set_size (context->pending_dispatches, 0);
1543 /* Holds context's lock */
1544 static inline GSource *
1545 next_valid_source (GMainContext *context,
1548 GSource *new_source = source ? source->next : context->source_list;
1552 if (!SOURCE_DESTROYED (new_source))
1554 new_source->ref_count++;
1558 new_source = new_source->next;
1562 SOURCE_UNREF (source, context);
1569 * g_main_context_prepare:
1570 * @context: a #GMainContext
1571 * @priority: location to store priority of highest priority
1572 * source already ready.
1574 * Prepares to poll sources within a main loop. The resulting information
1575 * for polling is determined by calling g_main_context_query ().
1577 * Return value: %TRUE if some source is ready to be dispatched
1581 g_main_context_prepare (GMainContext *context,
1585 gint current_priority = G_MAXINT;
1588 if (context == NULL)
1589 context = g_main_context_default ();
1591 LOCK_CONTEXT (context);
1593 context->time_is_current = FALSE;
1595 if (context->in_check_or_prepare)
1597 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1598 "prepare() member.");
1602 #ifdef G_THREADS_ENABLED
1603 if (context->poll_waiting)
1605 g_warning("g_main_context_prepare(): main loop already active in another thread");
1606 UNLOCK_CONTEXT (context);
1610 context->poll_waiting = TRUE;
1611 #endif /* G_THREADS_ENABLED */
1614 /* If recursing, finish up current dispatch, before starting over */
1615 if (context->pending_dispatches)
1618 g_main_dispatch (context, ¤t_time);
1620 UNLOCK_CONTEXT (context);
1625 /* If recursing, clear list of pending dispatches */
1626 g_ptr_array_set_size (context->pending_dispatches, 0);
1628 /* Prepare all sources */
1630 context->timeout = -1;
1632 source = next_valid_source (context, NULL);
1635 gint source_timeout = -1;
1637 if ((n_ready > 0) && (source->priority > current_priority))
1639 SOURCE_UNREF (source, context);
1642 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1645 if (!(source->flags & G_SOURCE_READY))
1648 gboolean (*prepare) (GSource *source,
1651 prepare = source->source_funcs->prepare;
1652 context->in_check_or_prepare++;
1653 UNLOCK_CONTEXT (context);
1655 result = (*prepare) (source, &source_timeout);
1657 LOCK_CONTEXT (context);
1658 context->in_check_or_prepare--;
1661 source->flags |= G_SOURCE_READY;
1664 if (source->flags & G_SOURCE_READY)
1667 current_priority = source->priority;
1668 context->timeout = 0;
1671 if (source_timeout >= 0)
1673 if (context->timeout < 0)
1674 context->timeout = source_timeout;
1676 context->timeout = MIN (context->timeout, source_timeout);
1680 source = next_valid_source (context, source);
1683 UNLOCK_CONTEXT (context);
1686 *priority = current_priority;
1688 return (n_ready > 0);
1692 * g_main_context_query:
1693 * @context: a #GMainContext
1694 * @max_priority: maximum priority source to check
1695 * @timeout: location to store timeout to be used in polling
1696 * @fds: location to store #GPollFD records that need to be polled.
1697 * @n_fds: length of @fds.
1699 * Determines information necessary to poll this main loop.
1704 g_main_context_query (GMainContext *context,
1713 LOCK_CONTEXT (context);
1715 pollrec = context->poll_records;
1717 while (pollrec && max_priority >= pollrec->priority)
1719 if (pollrec->fd->events)
1723 fds[n_poll].fd = pollrec->fd->fd;
1724 /* In direct contradiction to the Unix98 spec, IRIX runs into
1725 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1726 * flags in the events field of the pollfd while it should
1727 * just ignoring them. So we mask them out here.
1729 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1730 fds[n_poll].revents = 0;
1735 pollrec = pollrec->next;
1738 context->poll_changed = FALSE;
1742 *timeout = context->timeout;
1744 context->time_is_current = FALSE;
1747 UNLOCK_CONTEXT (context);
1753 * g_main_context_check:
1754 * @context: a #GMainContext
1755 * @max_priority: the maximum numerical priority of sources to check
1756 * @fds: array of #GPollFD's that was passed to the last call to
1757 * g_main_context_query()
1758 * @n_fds: return value of g_main_context_query()
1760 * Pass the results of polling back to the main loop.
1762 * Return value: %TRUE if some sources are ready to be dispatched.
1765 g_main_context_check (GMainContext *context,
1775 LOCK_CONTEXT (context);
1777 if (context->in_check_or_prepare)
1779 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1780 "prepare() member.");
1784 #ifdef G_THREADS_ENABLED
1785 if (!context->poll_waiting)
1789 read (context->wake_up_pipe[0], &c, 1);
1793 context->poll_waiting = FALSE;
1794 #endif /* G_THREADS_ENABLED */
1796 /* If the set of poll file descriptors changed, bail out
1797 * and let the main loop rerun
1799 if (context->poll_changed)
1802 pollrec = context->poll_records;
1806 if (pollrec->fd->events)
1808 pollrec->fd->revents = fds[i].revents;
1811 pollrec = pollrec->next;
1814 source = next_valid_source (context, NULL);
1817 if ((n_ready > 0) && (source->priority > max_priority))
1819 SOURCE_UNREF (source, context);
1822 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1825 if (!(source->flags & G_SOURCE_READY))
1828 gboolean (*check) (GSource *source);
1830 check = source->source_funcs->check;
1832 context->in_check_or_prepare++;
1833 UNLOCK_CONTEXT (context);
1835 result = (*check) (source);
1837 LOCK_CONTEXT (context);
1838 context->in_check_or_prepare--;
1841 source->flags |= G_SOURCE_READY;
1844 if (source->flags & G_SOURCE_READY)
1846 source->ref_count++;
1847 g_ptr_array_add (context->pending_dispatches, source);
1853 source = next_valid_source (context, source);
1856 UNLOCK_CONTEXT (context);
1862 * g_main_context_dispatch:
1863 * @context: a #GMainContext
1865 * Dispatch all pending sources()
1868 g_main_context_dispatch (GMainContext *context)
1870 LOCK_CONTEXT (context);
1872 if (context->pending_dispatches->len > 0)
1874 g_main_dispatch (context);
1877 UNLOCK_CONTEXT (context);
1881 g_main_context_iterate (GMainContext *context,
1887 gboolean some_ready;
1888 gint nfds, new_nfds;
1891 some_ready = g_main_context_prepare (context, &max_priority);
1895 LOCK_CONTEXT (context);
1897 if (context->cached_poll_array)
1899 nfds = context->cached_poll_array_size;
1900 fds = context->cached_poll_array;
1901 context->cached_poll_array = NULL;
1905 nfds = context->cached_poll_array_size = context->n_poll_records;
1906 fds = g_new (GPollFD, nfds);
1909 UNLOCK_CONTEXT (context);
1911 new_nfds = g_main_context_query (context, max_priority,
1912 &timeout, fds, nfds);
1914 while (new_nfds > nfds);
1919 g_main_context_poll (context, timeout, max_priority,
1922 g_main_context_check (context,
1926 LOCK_CONTEXT (context);
1928 g_assert (!context->cached_poll_array);
1930 context->cached_poll_array = fds;
1931 context->cached_poll_array_size = nfds;
1933 UNLOCK_CONTEXT (context);
1936 g_main_context_dispatch (context);
1942 * g_main_context_pending:
1943 * @context: a #GMainContext (if %NULL, the default context will be used)
1945 * Check if any sources have pending events for the given context.
1947 * Return value: %TRUE if events are pending.
1950 g_main_context_pending (GMainContext *context)
1953 context = g_main_context_default();
1955 return g_main_context_iterate (context, FALSE, FALSE);
1959 * g_main_context_iteration:
1960 * @context: a #GMainContext (if %NULL, the default context will be used)
1961 * @may_block: whether the call may block.
1963 * Run a single iteration for the given main loop. This involves
1964 * checking to see if any event sources are ready to be processed,
1965 * then if no events sources are ready and @may_block is %TRUE, waiting
1966 * for a source to become ready, then dispatching the highest priority
1967 * events sources that are ready. Note that even when @may_block is %TRUE,
1968 * it is still possible for g_main_context_iteration() to return
1969 * %FALSE, since the the wait may be interrupted for other
1970 * reasons than an event source becoming ready.
1972 * Return value: %TRUE if events were dispatched.
1975 g_main_context_iteration (GMainContext *context, gboolean may_block)
1978 context = g_main_context_default();
1980 return g_main_context_iterate (context, may_block, TRUE);
1985 * @context: a #GMainContext (if %NULL, the default context will be used).
1986 * @is_running: set to TRUE to indicate that the loop is running. This
1987 * is not very important since calling g_main_run() will set this to
1990 * Create a new #GMainLoop structure
1995 g_main_loop_new (GMainContext *context,
1996 gboolean is_running)
2001 context = g_main_context_default();
2003 loop = g_new0 (GMainLoop, 1);
2004 loop->context = context;
2005 loop->is_running = is_running != FALSE;
2007 #ifdef G_THREADS_ENABLED
2008 if (g_thread_supported ())
2009 loop->mutex = g_mutex_new ();
2012 loop->sem_cond = NULL;
2013 #endif /* G_THREADS_ENABLED */
2020 * @loop: a #GMainLoop
2022 * Run a main loop until g_main_quit() is called on the loop.
2023 * If this is called for the thread of the loop's #GMainContext,
2024 * it will process events from the loop, otherwise it will
2028 g_main_loop_run (GMainLoop *loop)
2030 g_return_if_fail (loop != NULL);
2032 #ifdef G_THREADS_ENABLED
2033 if (loop->context->thread != g_thread_self ())
2037 if (!g_thread_supported ())
2039 g_warning ("g_main_loop_run() was called from second thread but"
2040 "g_thread_init() was never called.");
2044 if (!loop->sem_cond)
2045 loop->sem_cond = g_cond_new ();
2047 if (!loop->is_running)
2048 loop->is_running = TRUE;
2050 while (loop->is_running)
2051 g_cond_wait (loop->sem_cond, loop->mutex);
2057 #endif /* G_THREADS_ENABLED */
2059 LOCK_CONTEXT (loop->context);
2060 if (loop->context->in_check_or_prepare)
2062 g_warning ("g_main_run(): called recursively from within a source's check() or "
2063 "prepare() member, iteration not possible.");
2066 UNLOCK_CONTEXT (loop->context);
2070 loop->is_running = TRUE;
2071 while (loop->is_running)
2074 g_main_context_iterate (loop->context, TRUE, TRUE);
2083 * @loop: a #GMainLoop
2085 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2086 * for the loop will return.
2089 g_main_loop_quit (GMainLoop *loop)
2091 g_return_if_fail (loop != NULL);
2094 loop->is_running = FALSE;
2097 g_cond_broadcast (loop->sem_cond);
2101 LOCK_CONTEXT (loop->context);
2103 g_main_context_wakeup (loop->context);
2104 UNLOCK_CONTEXT (loop->context);
2108 * g_main_loop_destroy:
2109 * @loop: a #GMainLoop
2111 * Destroy a #GMainLoop object and free all associated memory.
2112 * The loop must not currently be running via g_main_run().
2115 g_main_loop_destroy (GMainLoop *loop)
2117 g_return_if_fail (loop != NULL);
2118 g_return_if_fail (!loop->is_running);
2120 #ifdef G_THREADS_ENABLED
2121 g_mutex_free (loop->mutex);
2123 g_cond_free (loop->sem_cond);
2124 #endif /* G_THREADS_ENABLED */
2130 * g_main_loop_is_running:
2131 * @loop: a #GMainLoop.
2133 * Check to see if the main loop is currently being run via g_main_run()
2135 * Return value: %TRUE if the mainloop is currently being run.
2138 g_main_loop_is_running (GMainLoop *loop)
2142 g_return_val_if_fail (loop != NULL, FALSE);
2145 result = loop->is_running;
2151 /* HOLDS: context's lock */
2153 g_main_context_poll (GMainContext *context,
2159 #ifdef G_MAIN_POLL_DEBUG
2165 GPollFunc poll_func;
2167 if (n_fds || timeout != 0)
2169 #ifdef G_MAIN_POLL_DEBUG
2170 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2171 poll_timer = g_timer_new ();
2174 LOCK_CONTEXT (context);
2176 poll_func = context->poll_func;
2178 UNLOCK_CONTEXT (context);
2179 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2180 g_warning ("poll(2) failed due to: %s.",
2181 g_strerror (errno));
2183 #ifdef G_MAIN_POLL_DEBUG
2184 LOCK_CONTEXT (context);
2186 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2189 g_timer_elapsed (poll_timer, NULL));
2190 g_timer_destroy (poll_timer);
2191 pollrec = context->poll_records;
2195 if (pollrec->fd->events)
2199 g_print (" [%d:", fds[i].fd);
2200 if (fds[i].revents & G_IO_IN)
2202 if (fds[i].revents & G_IO_OUT)
2204 if (fds[i].revents & G_IO_PRI)
2206 if (fds[i].revents & G_IO_ERR)
2208 if (fds[i].revents & G_IO_HUP)
2210 if (fds[i].revents & G_IO_NVAL)
2216 pollrec = pollrec->next;
2220 UNLOCK_CONTEXT (context);
2222 } /* if (n_fds || timeout != 0) */
2226 * g_main_context_add_poll:
2227 * @context: a #GMainContext (or %NULL for the default context)
2228 * @fd: a #GPollFD structure holding information about a file
2229 * descriptor to watch.
2230 * @priority: the priority for this file descriptor which should be
2231 * the same as the priority used for g_source_attach() to ensure that the
2232 * file descriptor is polled whenever the results may be needed.
2234 * Add a file descriptor to the set of file descriptors polled * for
2235 * this context. This will very seldom be used directly. Instead
2236 * a typical event source will use g_source_add_poll() instead.
2239 g_main_context_add_poll (GMainContext *context,
2244 context = g_main_context_default ();
2246 LOCK_CONTEXT (context);
2247 g_main_context_add_poll_unlocked (context, priority, fd);
2248 UNLOCK_CONTEXT (context);
2251 /* HOLDS: main_loop_lock */
2253 g_main_context_add_poll_unlocked (GMainContext *context,
2257 GPollRec *lastrec, *pollrec, *newrec;
2259 if (!context->poll_chunk)
2260 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2262 if (context->poll_free_list)
2264 newrec = context->poll_free_list;
2265 context->poll_free_list = newrec->next;
2268 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2270 /* This file descriptor may be checked before we ever poll */
2273 newrec->priority = priority;
2276 pollrec = context->poll_records;
2277 while (pollrec && priority >= pollrec->priority)
2280 pollrec = pollrec->next;
2284 lastrec->next = newrec;
2286 context->poll_records = newrec;
2288 newrec->next = pollrec;
2290 context->n_poll_records++;
2291 if (context->cached_poll_array &&
2292 context->cached_poll_array_size < context->n_poll_records)
2294 g_free (context->cached_poll_array);
2295 context->cached_poll_array = NULL;
2298 #ifdef G_THREADS_ENABLED
2299 context->poll_changed = TRUE;
2301 /* Now wake up the main loop if it is waiting in the poll() */
2302 g_main_context_wakeup (context);
2307 * g_main_context_remove_poll:
2308 * @context:a #GMainContext
2309 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2311 * Remove file descriptor from the set of file descriptors to be
2312 * polled for a particular context.
2315 g_main_context_remove_poll (GMainContext *context,
2319 context = g_main_context_default ();
2321 LOCK_CONTEXT (context);
2323 g_main_context_remove_poll_unlocked (context, fd);
2325 UNLOCK_CONTEXT (context);
2329 g_main_context_remove_poll_unlocked (GMainContext *context,
2332 GPollRec *pollrec, *lastrec;
2335 pollrec = context->poll_records;
2339 if (pollrec->fd == fd)
2341 if (lastrec != NULL)
2342 lastrec->next = pollrec->next;
2344 context->poll_records = pollrec->next;
2346 #ifdef ENABLE_GC_FRIENDLY
2348 #endif /* ENABLE_GC_FRIENDLY */
2350 pollrec->next = context->poll_free_list;
2351 context->poll_free_list = pollrec;
2353 context->n_poll_records--;
2357 pollrec = pollrec->next;
2360 #ifdef G_THREADS_ENABLED
2361 context->poll_changed = TRUE;
2363 /* Now wake up the main loop if it is waiting in the poll() */
2364 g_main_context_wakeup (context);
2369 * g_source_get_current_time:
2370 * @source: a #GSource
2371 * @timeval: #GTimeVal structure in which to store current time.
2373 * Gets the "current time" to be used when checking
2374 * this source. The advantage of calling this function over
2375 * calling g_get_current_time() directly is that when
2376 * checking multiple sources, GLib can cache a single value
2377 * instead of having to repeatedly get the system time.
2380 g_source_get_current_time (GSource *source,
2383 GMainContext *context;
2385 g_return_if_fail (source->context != NULL);
2387 context = source->context;
2389 LOCK_CONTEXT (context);
2391 if (!context->time_is_current)
2393 g_get_current_time (&context->current_time);
2394 context->time_is_current = TRUE;
2397 *timeval = context->current_time;
2399 UNLOCK_CONTEXT (context);
2403 * g_main_context_set_poll_func:
2404 * @context: a #GMainContext
2405 * @func: the function to call to poll all file descriptors
2407 * Sets the function to use to handle polling of file descriptors. It
2408 * will be used instead of the poll() system call (or GLib's
2409 * replacement function, which is used where poll() isn't available).
2411 * This function could possibly be used to integrate the GLib event
2412 * loop with an external event loop.
2415 g_main_context_set_poll_func (GMainContext *context,
2419 context = g_main_context_default ();
2421 LOCK_CONTEXT (context);
2424 context->poll_func = func;
2428 context->poll_func = (GPollFunc) poll;
2430 context->poll_func = (GPollFunc) g_poll;
2434 UNLOCK_CONTEXT (context);
2440 * g_main_context_get_poll_func:
2441 * @context: a #GMainContext
2443 * Gets the poll function set by g_main_context_set_poll_func()
2445 * Return value: the poll function
2448 g_main_context_get_poll_func (GMainContext *context)
2453 context = g_main_context_default ();
2455 LOCK_CONTEXT (context);
2456 result = context->poll_func;
2457 UNLOCK_CONTEXT (context);
2462 /* HOLDS: context's lock */
2463 /* Wake the main loop up from a poll() */
2465 g_main_context_wakeup (GMainContext *context)
2467 #ifdef G_THREADS_ENABLED
2468 if (g_thread_supported() && context->poll_waiting)
2470 context->poll_waiting = FALSE;
2472 write (context->wake_up_pipe[1], "A", 1);
2474 ReleaseSemaphore (context->context->wake_up_semaphore, 1, NULL);
2483 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2484 GTimeVal *current_time)
2486 guint seconds = timeout_source->interval / 1000;
2487 guint msecs = timeout_source->interval - seconds * 1000;
2489 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2490 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2491 if (timeout_source->expiration.tv_usec >= 1000000)
2493 timeout_source->expiration.tv_usec -= 1000000;
2494 timeout_source->expiration.tv_sec++;
2499 g_timeout_prepare (GSource *source,
2503 GTimeVal current_time;
2505 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2507 g_source_get_current_time (source, ¤t_time);
2509 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2510 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2514 else if (msec > timeout_source->interval)
2516 /* The system time has been set backwards, so we
2517 * reset the expiration time to now + timeout_source->interval;
2518 * this at least avoids hanging for long periods of time.
2520 g_timeout_set_expiration (timeout_source, ¤t_time);
2521 msec = timeout_source->interval;
2530 g_timeout_check (GSource *source)
2532 GTimeVal current_time;
2533 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2535 g_source_get_current_time (source, ¤t_time);
2537 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2538 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2539 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2543 g_timeout_dispatch (GSource *source,
2544 GSourceFunc callback,
2547 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2551 g_warning ("Timeout source dispatched without callback\n"
2552 "You must call g_source_set_callback().");
2556 if (callback (user_data))
2558 GTimeVal current_time;
2560 g_source_get_current_time (source, ¤t_time);
2561 g_timeout_set_expiration (timeout_source, ¤t_time);
2570 * g_timeout_source_new:
2571 * @interval: the timeout interval in milliseconds.
2573 * Create a new timeout source.
2575 * The source will not initially be associated with any #GMainContext
2576 * and must be added to one with g_source_attach() before it will be
2579 * Return value: the newly create timeout source
2582 g_timeout_source_new (guint interval)
2584 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2585 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2586 GTimeVal current_time;
2588 timeout_source->interval = interval;
2590 g_get_current_time (¤t_time);
2591 g_timeout_set_expiration (timeout_source, ¤t_time);
2597 * g_timeout_add_full:
2598 * @priority: the priority of the idle source. Typically this will be in the
2599 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2600 * @interval: the time between calls to the function, in milliseconds
2601 * (1/1000ths of a second.)
2602 * @function: function to call
2603 * @data: data to pass to @function
2604 * @notify: function to call when the idle is removed, or %NULL
2606 * Sets a function to be called at regular intervals, with the given
2607 * priority. The function is called repeatedly until it returns
2608 * FALSE, at which point the timeout is automatically destroyed and
2609 * the function will not be called again. The @notify function is
2610 * called when the timeout is destroyed. The first call to the
2611 * function will be at the end of the first @interval.
2613 * Note that timeout functions may be delayed, due to the processing of other
2614 * event sources. Thus they should not be relied on for precise timing.
2615 * After each call to the timeout function, the time of the next
2616 * timeout is recalculated based on the current time and the given interval
2617 * (it does not try to 'catch up' time lost in delays).
2619 * Return value: the id of event source.
2622 g_timeout_add_full (gint priority,
2624 GSourceFunc function,
2626 GDestroyNotify notify)
2631 g_return_val_if_fail (function != NULL, 0);
2633 source = g_timeout_source_new (interval);
2635 if (priority != G_PRIORITY_DEFAULT)
2636 g_source_set_priority (source, priority);
2638 g_source_set_callback (source, function, data, notify);
2639 id = g_source_attach (source, NULL);
2640 g_source_unref (source);
2647 * @interval: the time between calls to the function, in milliseconds
2648 * (1/1000ths of a second.)
2649 * @function: function to call
2650 * @data: data to pass to @function
2652 * Sets a function to be called at regular intervals, with the default
2653 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2654 * until it returns FALSE, at which point the timeout is automatically
2655 * destroyed and the function will not be called again. The @notify
2656 * function is called when the timeout is destroyed. The first call
2657 * to the function will be at the end of the first @interval.
2659 * Note that timeout functions may be delayed, due to the processing of other
2660 * event sources. Thus they should not be relied on for precise timing.
2661 * After each call to the timeout function, the time of the next
2662 * timeout is recalculated based on the current time and the given interval
2663 * (it does not try to 'catch up' time lost in delays).
2665 * Return value: the id of event source.
2668 g_timeout_add (guint32 interval,
2669 GSourceFunc function,
2672 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2673 interval, function, data, NULL);
2676 /* Idle functions */
2679 g_idle_prepare (GSource *source,
2688 g_idle_check (GSource *source)
2694 g_idle_dispatch (GSource *source,
2695 GSourceFunc callback,
2700 g_warning ("Idle source dispatched without callback\n"
2701 "You must call g_source_set_callback().");
2705 return callback (user_data);
2709 * g_idle_source_new:
2711 * Create a new idle source.
2713 * The source will not initially be associated with any #GMainContext
2714 * and must be added to one with g_source_attach() before it will be
2717 * Return value: the newly created idle source
2720 g_idle_source_new (void)
2722 return g_source_new (&idle_funcs, sizeof (GSource));
2727 * @priority: the priority of the idle source. Typically this will be in the
2728 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2729 * @function: function to call
2730 * @data: data to pass to @function
2731 * @notify: function to call when the idle is removed, or %NULL
2733 * Adds a function to be called whenever there are no higher priority
2734 * events pending. If the function returns FALSE it is automatically
2735 * removed from the list of event sources and will not be called again.
2737 * Return value: the id of the event source.
2740 g_idle_add_full (gint priority,
2741 GSourceFunc function,
2743 GDestroyNotify notify)
2748 g_return_val_if_fail (function != NULL, 0);
2750 source = g_idle_source_new ();
2752 if (priority != G_PRIORITY_DEFAULT)
2753 g_source_set_priority (source, priority);
2755 g_source_set_callback (source, function, data, notify);
2756 id = g_source_attach (source, NULL);
2757 g_source_unref (source);
2764 * @function: function to call
2765 * @data: data to pass to @function.
2767 * Adds a function to be called whenever there are no higher priority
2768 * events pending to the default main loop. The function is given the
2769 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2770 * returns FALSE it is automatically removed from the list of event
2771 * sources and will not be called again.
2773 * Return value: the id of the event source.
2776 g_idle_add (GSourceFunc function,
2779 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2783 * g_idle_remove_by_data:
2784 * @data: the data for the idle source's callback.
2786 * Removes the idle function with the given data.
2788 * Return value: %TRUE if an idle source was found and removed.
2791 g_idle_remove_by_data (gpointer data)
2793 return g_source_remove_by_funcs_user_data (&idle_funcs, data);