1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
36 /* uncomment the next line to get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
40 #include <sys/types.h>
42 #ifdef HAVE_SYS_TIME_H
44 #endif /* HAVE_SYS_TIME_H */
45 #ifdef GLIB_HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
48 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
49 #endif /* GLIB_HAVE_SYS_POLL_H */
52 #endif /* HAVE_UNISTD_H */
58 #endif /* G_OS_WIN32 */
61 #include <net/socket.h>
62 #endif /* G_OS_BEOS */
66 typedef struct _GTimeoutSource GTimeoutSource;
67 typedef struct _GPollRec GPollRec;
68 typedef struct _GSourceCallback GSourceCallback;
72 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
73 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
78 #ifdef G_THREADS_ENABLED
79 /* The following lock is used for both the list of sources
80 * and the list of poll records
86 GPtrArray *pending_dispatches;
87 gint timeout; /* Timeout for current iteration */
91 gint in_check_or_prepare;
93 GPollRec *poll_records;
94 GPollRec *poll_free_list;
95 GMemChunk *poll_chunk;
97 GPollFD *cached_poll_array;
98 gint cached_poll_array_size;
100 #ifdef G_THREADS_ENABLED
102 /* this pipe is used to wake up the main loop when a source is added.
104 gint wake_up_pipe[2];
105 #else /* G_OS_WIN32 */
106 HANDLE wake_up_semaphore;
107 #endif /* G_OS_WIN32 */
110 gboolean poll_waiting;
112 /* Flag indicating whether the set of fd's changed during a poll */
113 gboolean poll_changed;
114 #endif /* G_THREADS_ENABLED */
118 GTimeVal current_time;
119 gboolean time_is_current;
122 struct _GSourceCallback
127 GDestroyNotify notify;
132 GMainContext *context;
136 #ifdef G_THREADS_ENABLED
139 #endif /* G_THREADS_ENABLED */
142 struct _GTimeoutSource
156 #ifdef G_THREADS_ENABLED
157 #define LOCK_CONTEXT(context) g_mutex_lock(context->mutex)
158 #define UNLOCK_CONTEXT(context) g_mutex_unlock(context->mutex)
159 #define LOCK_LOOP(loop) g_mutex_lock(loop->mutex)
160 #define UNLOCK_LOOP(loop) g_mutex_unlock(loop->mutex)
162 #define LOCK_CONTEXT(context) (void)0
163 #define UNLOCK_CONTEXT(context) (void)0
164 #define LOCK_LOOP(context) (void)0
165 #define UNLOCK_LOOP(context) (void)0
168 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
170 #define SOURCE_UNREF(source, context) \
172 if ((source)->ref_count > 1) \
173 (source)->ref_count--; \
175 g_source_unref_internal ((source), (context), TRUE); \
179 /* Forward declarations */
181 static void g_source_unref_internal (GSource *source,
182 GMainContext *context,
184 static void g_source_destroy_internal (GSource *source,
185 GMainContext *context,
187 static void g_main_context_poll (GMainContext *context,
192 static void g_main_context_add_poll_unlocked (GMainContext *context,
195 static void g_main_context_remove_poll_unlocked (GMainContext *context,
197 static void g_main_context_wakeup (GMainContext *context);
199 static gboolean g_timeout_prepare (GSource *source,
201 static gboolean g_timeout_check (GSource *source);
202 static gboolean g_timeout_dispatch (GSource *source,
203 GSourceFunc callback,
205 static gboolean g_idle_prepare (GSource *source,
207 static gboolean g_idle_check (GSource *source);
208 static gboolean g_idle_dispatch (GSource *source,
209 GSourceFunc callback,
212 G_LOCK_DEFINE_STATIC (main_loop);
213 static GMainContext *default_main_context;
215 static GSourceFuncs timeout_funcs =
223 static GSourceFuncs idle_funcs =
232 /* SunOS has poll, but doesn't provide a prototype. */
233 # if defined (sun) && !defined (__SVR4)
234 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
236 #else /* !HAVE_POLL */
241 g_poll (GPollFD *fds,
245 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
246 gboolean poll_msgs = FALSE;
253 for (f = fds; f < &fds[nfds]; ++f)
256 if (f->events & G_IO_IN)
258 if (f->fd == G_WIN32_MSG_HANDLE)
262 #ifdef G_MAIN_POLL_DEBUG
263 g_print ("g_poll: waiting for %#x\n", f->fd);
265 handles[nhandles++] = (HANDLE) f->fd;
275 /* Waiting for messages, and maybe events
276 * -> First PeekMessage
278 #ifdef G_MAIN_POLL_DEBUG
279 g_print ("PeekMessage\n");
281 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
282 ready = WAIT_OBJECT_0 + nhandles;
287 /* Waiting just for messages */
288 if (timeout == INFINITE)
293 #ifdef G_MAIN_POLL_DEBUG
294 g_print ("WaitMessage\n");
297 g_warning (G_STRLOC ": WaitMessage() failed");
298 ready = WAIT_OBJECT_0 + nhandles;
300 else if (timeout == 0)
302 /* Waiting just for messages, zero timeout.
303 * If we got here, there was no message
305 ready = WAIT_TIMEOUT;
309 /* Waiting just for messages, some timeout
310 * -> Set a timer, wait for message,
311 * kill timer, use PeekMessage
313 timer = SetTimer (NULL, 0, timeout, NULL);
315 g_warning (G_STRLOC ": SetTimer() failed");
318 #ifdef G_MAIN_POLL_DEBUG
319 g_print ("WaitMessage\n");
322 KillTimer (NULL, timer);
323 #ifdef G_MAIN_POLL_DEBUG
324 g_print ("PeekMessage\n");
326 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
327 && msg.message != WM_TIMER)
328 ready = WAIT_OBJECT_0;
330 ready = WAIT_TIMEOUT;
336 /* Wait for either message or event
337 * -> Use MsgWaitForMultipleObjects
339 #ifdef G_MAIN_POLL_DEBUG
340 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
342 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
343 timeout, QS_ALLINPUT);
345 if (ready == WAIT_FAILED)
346 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
350 else if (nhandles == 0)
352 /* Wait for nothing (huh?) */
357 /* Wait for just events
358 * -> Use WaitForMultipleObjects
360 #ifdef G_MAIN_POLL_DEBUG
361 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
363 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
364 if (ready == WAIT_FAILED)
365 g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
368 #ifdef G_MAIN_POLL_DEBUG
369 g_print ("wait returns %d%s\n",
371 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
372 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
373 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
375 for (f = fds; f < &fds[nfds]; ++f)
378 if (ready == WAIT_FAILED)
380 else if (ready == WAIT_TIMEOUT)
382 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
384 for (f = fds; f < &fds[nfds]; ++f)
387 if (f->events & G_IO_IN)
388 if (f->fd == G_WIN32_MSG_HANDLE)
389 f->revents |= G_IO_IN;
392 #if TEST_WITHOUT_THIS
393 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
394 for (f = fds; f < &fds[nfds]; ++f)
396 if ((f->events & G_IO_IN)
397 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
399 f->revents |= G_IO_IN;
400 #ifdef G_MAIN_POLL_DEBUG
401 g_print ("g_poll: got event %#x\n", f->fd);
404 ResetEvent ((HANDLE) f->fd);
413 #else /* !G_OS_WIN32 */
415 /* The following implementation of poll() comes from the GNU C Library.
416 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
419 #include <string.h> /* for bzero on BSD systems */
421 #ifdef HAVE_SYS_SELECT_H
422 #include <sys/select.h>
423 #endif /* HAVE_SYS_SELECT_H */
427 #endif /* G_OS_BEOS */
430 # define SELECT_MASK fd_set
431 #else /* !NO_FD_SET */
433 typedef long fd_mask;
436 # define SELECT_MASK void
438 # define SELECT_MASK int
439 # endif /* !_IBMR2 */
440 #endif /* !NO_FD_SET */
443 g_poll (GPollFD *fds,
448 SELECT_MASK rset, wset, xset;
457 for (f = fds; f < &fds[nfds]; ++f)
460 if (f->events & G_IO_IN)
461 FD_SET (f->fd, &rset);
462 if (f->events & G_IO_OUT)
463 FD_SET (f->fd, &wset);
464 if (f->events & G_IO_PRI)
465 FD_SET (f->fd, &xset);
466 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
470 tv.tv_sec = timeout / 1000;
471 tv.tv_usec = (timeout % 1000) * 1000;
473 ready = select (maxfd + 1, &rset, &wset, &xset,
474 timeout == -1 ? NULL : &tv);
476 for (f = fds; f < &fds[nfds]; ++f)
481 if (FD_ISSET (f->fd, &rset))
482 f->revents |= G_IO_IN;
483 if (FD_ISSET (f->fd, &wset))
484 f->revents |= G_IO_OUT;
485 if (FD_ISSET (f->fd, &xset))
486 f->revents |= G_IO_PRI;
493 #endif /* !G_OS_WIN32 */
495 #endif /* !HAVE_POLL */
497 /* Called to clean up when a thread terminates
500 g_main_context_destroy (GMainContext *context)
504 /* We need the lock here only because g_source_destroy expects
505 * to be able to unlock when destroying the source's data
507 LOCK_CONTEXT (context);
508 source = context->source_list;
511 GSource *next = source->next;
512 g_source_destroy_internal (source, context, TRUE);
515 UNLOCK_CONTEXT (context);
517 #ifdef G_THREADS_ENABLED
518 g_mutex_free (context->mutex);
521 g_ptr_array_free (context->pending_dispatches, TRUE);
522 g_free (context->cached_poll_array);
524 g_mem_chunk_destroy (context->poll_chunk);
526 #ifdef G_THREADS_ENABLED
527 if (g_thread_supported())
530 close (context->wake_up_pipe[0]);
531 close (context->wake_up_pipe[1]);
533 CloseHandle (context->wake_up_semaphore);
542 * g_main_context_get:
543 * @thread: a #GThread
545 * Retrieves the main loop context for a particular thread. This
546 * will create the main context for the thread if none previously
547 * existed. The context will exist until the thread terminates.
549 * Return value: the main loop context for @thread.
552 g_main_context_get (GThread *thread)
554 static GStaticPrivate private_key = G_STATIC_PRIVATE_INIT;
555 GMainContext *context;
557 g_return_val_if_fail (thread != NULL, NULL);
559 if (g_thread_supported ())
560 context = g_static_private_get_for_thread (&private_key, thread);
562 context = default_main_context;
566 context = g_new0 (GMainContext, 1);
568 #ifdef G_THREADS_ENABLED
569 if (g_thread_supported ())
570 context->mutex = g_mutex_new();
572 context->thread = thread;
575 context->next_id = 1;
577 context->source_list = NULL;
580 context->poll_func = (GPollFunc)poll;
582 context->poll_func = g_poll;
585 context->cached_poll_array = NULL;
586 context->cached_poll_array_size = 0;
588 context->pending_dispatches = g_ptr_array_new ();
590 context->time_is_current = FALSE;
592 #ifdef G_THREADS_ENABLED
593 if (g_thread_supported ())
596 if (pipe (context->wake_up_pipe) < 0)
597 g_error ("Cannot create pipe main loop wake-up: %s\n",
600 context->wake_up_rec.fd = context->wake_up_pipe[0];
601 context->wake_up_rec.events = G_IO_IN;
602 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
604 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
605 if (context->wake_up_semaphore == NULL)
606 g_error ("Cannot create wake-up semaphore: %s",
607 g_win32_error_message (GetLastError ()));
608 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
609 context->wake_up_rec.events = G_IO_IN;
610 #ifdef G_MAIN_POLL_DEBUG
611 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
613 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
618 if (g_thread_supported ())
619 g_static_private_set_for_thread (&private_key, thread,
621 (GDestroyNotify)g_main_context_destroy);
623 default_main_context = context;
630 * g_main_context_default:
632 * Return the default main context. This is the main context used
633 * for main loop functions when a main loop is not explicitly
636 * Return value: the default main context.
639 g_main_context_default (void)
645 if (!default_main_context)
646 default_main_context = g_main_context_get (g_thread_self ());
648 G_UNLOCK (main_loop);
650 return default_main_context;
653 /* Hooks for adding to the main loop */
657 * @source_funcs: structure containing functions that implement
658 * the sources behavior.
659 * @struct_size: size of the #GSource structure to create
661 * Create a new GSource structure. The size is specified to
662 * allow creating structures derived from GSource that contain
663 * additional data. The size passed in must be at least
666 * The source will not initially be associated with any #GMainContext
667 * and must be added to one with g_source_add() before it will be
670 * Return value: the newly create #GSource
673 g_source_new (GSourceFuncs *source_funcs,
678 g_return_val_if_fail (source_funcs != NULL, NULL);
679 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
681 source = (GSource*) g_malloc0 (struct_size);
683 source->source_funcs = source_funcs;
684 source->ref_count = 1;
686 source->priority = G_PRIORITY_DEFAULT;
688 source->flags = G_HOOK_FLAG_ACTIVE;
690 /* NULL/0 initialization for all other fields */
695 /* Holds context's lock
698 g_source_list_add (GSource *source,
699 GMainContext *context)
701 GSource *tmp_source, *last_source;
704 tmp_source = context->source_list;
705 while (tmp_source && tmp_source->priority <= source->priority)
707 last_source = tmp_source;
708 tmp_source = tmp_source->next;
711 source->next = tmp_source;
713 tmp_source->prev = source;
715 source->prev = last_source;
717 last_source->next = source;
719 context->source_list = source;
722 /* Holds context's lock
725 g_source_list_remove (GSource *source,
726 GMainContext *context)
729 source->prev->next = source->next;
731 context->source_list = source->next;
734 source->next->prev = source->prev;
742 * @source: a #GSource
743 * @context: a #GMainContext (if %NULL, the default context will be used)
745 * Adds a #GSource to a @context so that it will be executed within
748 * Return value: the ID for the source within the #GMainContext
751 g_source_attach (GSource *source,
752 GMainContext *context)
757 g_return_val_if_fail (source->context == NULL, 0);
758 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
761 context = g_main_context_default ();
763 LOCK_CONTEXT (context);
765 source->context = context;
766 result = source->id = context->next_id++;
769 g_source_list_add (source, context);
771 tmp_list = source->poll_fds;
774 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
775 tmp_list = tmp_list->next;
778 #ifdef G_THREADS_ENABLED
779 /* Now wake up the main loop if it is waiting in the poll() */
780 g_main_context_wakeup (context);
783 UNLOCK_CONTEXT (context);
789 g_source_destroy_internal (GSource *source,
790 GMainContext *context,
794 LOCK_CONTEXT (context);
796 if (!SOURCE_DESTROYED (source))
799 gpointer old_cb_data;
800 GSourceCallbackFuncs *old_cb_funcs;
802 source->flags &= ~G_HOOK_FLAG_ACTIVE;
804 old_cb_data = source->callback_data;
805 old_cb_funcs = source->callback_funcs;
807 source->callback_data = NULL;
808 source->callback_funcs = NULL;
812 UNLOCK_CONTEXT (context);
813 old_cb_funcs->unref (old_cb_data);
814 LOCK_CONTEXT (context);
817 tmp_list = source->poll_fds;
820 g_main_context_remove_poll_unlocked (context, tmp_list->data);
821 tmp_list = tmp_list->next;
824 g_source_unref_internal (source, context, TRUE);
828 UNLOCK_CONTEXT (context);
833 * @source: a #GSource
835 * Remove a source from its #GMainContext, if any, and mark it as
836 * destroyed. The source cannot be subsequently added to another
840 g_source_destroy (GSource *source)
842 GMainContext *context;
844 g_return_if_fail (source != NULL);
846 context = source->context;
849 g_source_destroy_internal (source, context, FALSE);
851 source->flags &= ~G_HOOK_FLAG_ACTIVE;
856 * @source: a #GSource
858 * Return the numeric ID for a particular source. The ID of a source
859 * is unique within a particular main loop context. The reverse
860 * mapping from ID to source is done by g_main_context_find_source_by_id().
862 * Return value: the ID for the source
865 g_source_get_id (GSource *source)
869 g_return_val_if_fail (source != NULL, 0);
870 g_return_val_if_fail (source->context != NULL, 0);
872 LOCK_CONTEXT (source->context);
874 UNLOCK_CONTEXT (source->context);
880 * g_source_get_context:
881 * @source: a #GSource
883 * Get the #GMainContext with which the source is associated.
884 * Calling this function on a destroyed source is an error.
886 * Return value: the #GMainContext with which the source is associated,
887 * or %NULL if the context has not yet been added
891 g_source_get_context (GSource *source)
893 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
895 return source->context;
901 * @fd: a #GPollFD structure holding information about a file
902 * descriptor to watch.
904 * Add a file descriptor to the set of file descriptors polled for
905 * this source. This is usually combined with g_source_new() to add an
906 * event source. The event source's check function will typically test
907 * the revents field in the #GPollFD struct and return %TRUE if events need
911 g_source_add_poll (GSource *source,
914 GMainContext *context;
916 g_return_if_fail (source != NULL);
917 g_return_if_fail (fd != NULL);
918 g_return_if_fail (!SOURCE_DESTROYED (source));
920 context = source->context;
923 LOCK_CONTEXT (context);
925 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
929 g_main_context_add_poll_unlocked (context, source->priority, fd);
930 UNLOCK_CONTEXT (context);
935 * g_source_remove_poll:
937 * @fd: a #GPollFD structure previously passed to g_source_poll.
939 * Remove a file descriptor from the set of file descriptors polled for
943 g_source_remove_poll (GSource *source,
946 GMainContext *context;
948 g_return_if_fail (source != NULL);
949 g_return_if_fail (fd != NULL);
950 g_return_if_fail (!SOURCE_DESTROYED (source));
952 context = source->context;
955 LOCK_CONTEXT (context);
957 source->poll_fds = g_slist_remove (source->poll_fds, fd);
961 g_main_context_remove_poll_unlocked (context, fd);
962 UNLOCK_CONTEXT (context);
967 * g_source_set_callback_indirect:
968 * @source: the source
969 * @callback_data: pointer to callback data "object"
970 * @callback_funcs: functions for reference counting callback_data
971 * and getting the callback and data
973 * Set the callback function storing the data as a refcounted callback
974 * "object". This is used to implement g_source_set_callback_closure()
975 * and internally. Note that calling g_source_set_callback_indirect() assumes
976 * an initial reference count on @callback_data, and thus
977 * @callback_funcs->unref will eventually be called once more
978 * than @callback_funcs->ref.
981 g_source_set_callback_indirect (GSource *source,
982 gpointer callback_data,
983 GSourceCallbackFuncs *callback_funcs)
985 GMainContext *context;
986 gpointer old_cb_data;
987 GSourceCallbackFuncs *old_cb_funcs;
989 g_return_if_fail (source != NULL);
990 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
992 context = source->context;
995 LOCK_CONTEXT (context);
997 old_cb_data = source->callback_data;
998 old_cb_funcs = source->callback_funcs;
1000 source->callback_data = callback_data;
1001 source->callback_funcs = callback_funcs;
1004 UNLOCK_CONTEXT (context);
1007 old_cb_funcs->unref (old_cb_data);
1011 g_source_callback_ref (gpointer cb_data)
1013 GSourceCallback *callback = cb_data;
1015 callback->ref_count++;
1020 g_source_callback_unref (gpointer cb_data)
1022 GSourceCallback *callback = cb_data;
1024 callback->ref_count--;
1025 if (callback->ref_count == 0)
1027 if (callback->notify)
1028 callback->notify (callback->data);
1034 g_source_callback_get (gpointer cb_data,
1038 GSourceCallback *callback = cb_data;
1040 *func = callback->func;
1041 *data = callback->data;
1044 static GSourceCallbackFuncs g_source_callback_funcs = {
1045 g_source_callback_ref,
1046 g_source_callback_unref,
1047 g_source_callback_get,
1051 * g_source_set_callback:
1052 * @source: the source
1053 * @func: a callback function
1054 * @data: the data to pass to callback function
1055 * @notify: a function to call when @data is no longer in use, or %NULL.
1057 * Set the callback function for a source.
1060 g_source_set_callback (GSource *source,
1063 GDestroyNotify notify)
1065 GSourceCallback *new_callback;
1067 g_return_if_fail (source != NULL);
1069 new_callback = g_new (GSourceCallback, 1);
1071 new_callback->ref_count = 1;
1072 new_callback->func = func;
1073 new_callback->data = data;
1074 new_callback->notify = notify;
1076 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1080 * g_source_set_priority:
1081 * @source: a #GSource
1082 * @priority: the new priority.
1084 * Set the priority of a source. While the main loop is being
1085 * run, a source will
1088 g_source_set_priority (GSource *source,
1092 GMainContext *context;
1094 g_return_if_fail (source != NULL);
1096 context = source->context;
1099 LOCK_CONTEXT (context);
1101 source->priority = priority;
1105 source->next = NULL;
1106 source->prev = NULL;
1108 tmp_list = source->poll_fds;
1111 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1112 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1114 tmp_list = tmp_list->next;
1117 UNLOCK_CONTEXT (source->context);
1122 * g_source_get_priority:
1123 * @source: a #GSource
1125 * Gets the priority of a surce
1127 * Return value: the priority of the source
1130 g_source_get_priority (GSource *source)
1132 g_return_val_if_fail (source != NULL, 0);
1134 return source->priority;
1138 * g_source_set_can_recurse:
1139 * @source: a #GSource
1140 * @can_recurse: whether recursion is allowed for this source
1142 * Sets whether a source can be called recursively. If @can_recurse is
1143 * %TRUE, then while the source is being dispatched then this source
1144 * will be processed normally. Otherwise, all processing of this
1145 * source is blocked until the dispatch function returns.
1148 g_source_set_can_recurse (GSource *source,
1149 gboolean can_recurse)
1151 GMainContext *context;
1153 g_return_if_fail (source != NULL);
1155 context = source->context;
1158 LOCK_CONTEXT (context);
1161 source->flags |= G_SOURCE_CAN_RECURSE;
1163 source->flags &= ~G_SOURCE_CAN_RECURSE;
1166 UNLOCK_CONTEXT (context);
1170 * g_source_get_can_recurse:
1171 * @source: a #GSource
1173 * Checks whether a source is allowed to be called recursively.
1174 * see g_source_set_can_recurse.
1176 * Return value: whether recursion is allowed.
1179 g_source_get_can_recurse (GSource *source)
1181 g_return_val_if_fail (source != NULL, FALSE);
1183 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1188 * @source: a #GSource
1190 * Increases the reference count on a source by one.
1192 * Return value: @source
1195 g_source_ref (GSource *source)
1197 GMainContext *context;
1199 g_return_val_if_fail (source != NULL, NULL);
1201 context = source->context;
1204 LOCK_CONTEXT (context);
1206 source->ref_count++;
1209 UNLOCK_CONTEXT (context);
1214 /* g_source_unref() but possible to call within context lock
1217 g_source_unref_internal (GSource *source,
1218 GMainContext *context,
1221 gpointer old_cb_data = NULL;
1222 GSourceCallbackFuncs *old_cb_funcs = NULL;
1224 g_return_if_fail (source != NULL);
1226 if (!have_lock && context)
1227 LOCK_CONTEXT (context);
1229 source->ref_count--;
1230 if (source->ref_count == 0)
1232 old_cb_data = source->callback_data;
1233 old_cb_funcs = source->callback_funcs;
1235 source->callback_data = NULL;
1236 source->callback_funcs = NULL;
1238 if (context && !SOURCE_DESTROYED (source))
1240 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1241 source->ref_count++;
1244 g_source_list_remove (source, context);
1246 if (source->source_funcs->destroy)
1247 source->source_funcs->destroy (source);
1249 g_slist_free (source->poll_fds);
1250 source->poll_fds = NULL;
1254 if (!have_lock && context)
1255 UNLOCK_CONTEXT (context);
1260 UNLOCK_CONTEXT (context);
1262 old_cb_funcs->unref (old_cb_data);
1265 LOCK_CONTEXT (context);
1271 * @source: a #GSource
1273 * Decreases the reference count of a source by one. If the
1274 * resulting reference count is zero the source and associated
1275 * memory will be destroyed.
1278 g_source_unref (GSource *source)
1280 g_return_if_fail (source != NULL);
1282 g_source_unref_internal (source, source->context, FALSE);
1286 * g_main_context_find_source_by_id:
1287 * @context: a #GMainContext (if %NULL, the default context will be used)
1288 * @id: the source ID, as returned by g_source_get_id()
1290 * Finds a #GSource given a pair of context and ID
1292 * Return value: the #GSource if found, otherwise, %NULL
1295 g_main_context_find_source_by_id (GMainContext *context,
1300 g_return_val_if_fail (id > 0, FALSE);
1302 if (context == NULL)
1303 context = g_main_context_default ();
1305 LOCK_CONTEXT (context);
1307 source = context->source_list;
1310 if (!SOURCE_DESTROYED (source) &&
1313 source = source->next;
1316 UNLOCK_CONTEXT (context);
1322 * g_main_context_find_source_by_funcs_user_data:
1323 * @context: a #GMainContext (if %NULL, the default context will be used).
1324 * @funcs: the @source_funcs passed to g_source_new().
1325 * @user_data: the user data from the callback.
1327 * Finds a source with the given source functions and user data. If
1328 * multiple sources exist with the same source function and user data,
1329 * the first one found will be returned.
1331 * Return value: the source, if one was found, otherwise %NULL
1334 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1335 GSourceFuncs *funcs,
1340 g_return_val_if_fail (funcs != NULL, FALSE);
1342 if (context == NULL)
1343 context = g_main_context_default ();
1345 LOCK_CONTEXT (context);
1347 source = context->source_list;
1350 if (!SOURCE_DESTROYED (source) &&
1351 source->source_funcs == funcs &&
1352 source->callback_data == user_data)
1354 source = source->next;
1357 UNLOCK_CONTEXT (context);
1363 * g_main_context_find_source_by_user_data:
1364 * @context: a #GMainContext
1365 * @user_data: the user_data for the callback.
1367 * Finds a source with the given user data for the callback. If
1368 * multiple sources exist with the same user data, the first
1369 * one found will be returned.
1371 * Return value: the source, if one was found, otherwise %NULL
1374 g_main_context_find_source_by_user_data (GMainContext *context,
1379 if (context == NULL)
1380 context = g_main_context_default ();
1382 LOCK_CONTEXT (context);
1384 source = context->source_list;
1387 if (!SOURCE_DESTROYED (source) &&
1388 source->callback_data == user_data)
1390 source = source->next;
1393 UNLOCK_CONTEXT (context);
1400 * @tag: the id of the source to remove.
1402 * Removes the source with the given id from the default main
1403 * context. The id of a #GSource is given by g_source_get_id(),
1404 * or will be returned by the functions g_source_attach(),
1405 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1406 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1408 * See also g_source_destroy().
1410 * Return value: %TRUE if the source was found and removed.
1413 g_source_remove (guint tag)
1417 g_return_val_if_fail (tag > 0, FALSE);
1419 source = g_main_context_find_source_by_id (NULL, tag);
1421 g_source_destroy (source);
1423 return source != NULL;
1427 * g_source_remove_by_user_data:
1428 * @user_data: the user_data for the callback.
1430 * Removes a source from the default main loop context given the user
1431 * data for the callback. If multiple sources exist with the same user
1432 * data, only one will be destroyed.
1434 * Return value: %TRUE if a source was found and removed.
1437 g_source_remove_by_user_data (gpointer user_data)
1441 source = g_main_context_find_source_by_user_data (NULL, user_data);
1444 g_source_destroy (source);
1452 * g_source_remove_by_funcs_user_data:
1453 * @funcs: The @source_funcs passed to g_source_new()
1454 * @user_data: the user data for the callback
1456 * Removes a source from the default main loop context given the
1457 * source functions and user data. If multiple sources exist with the
1458 * same source functions and user data, only one will be destroyed.
1460 * Return value: %TRUE if a source was found and removed.
1463 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1468 g_return_val_if_fail (funcs != NULL, FALSE);
1470 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1473 g_source_destroy (source);
1481 * g_get_current_time:
1482 * @result: #GTimeVal structure in which to store current time.
1484 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1487 g_get_current_time (GTimeVal *result)
1492 g_return_if_fail (result != NULL);
1494 /*this is required on alpha, there the timeval structs are int's
1495 not longs and a cast only would fail horribly*/
1496 gettimeofday (&r, NULL);
1497 result->tv_sec = r.tv_sec;
1498 result->tv_usec = r.tv_usec;
1500 /* Avoid calling time() except for the first time.
1501 * GetTickCount() should be pretty fast and low-level?
1502 * I could also use ftime() but it seems unnecessarily overheady.
1504 static DWORD start_tick = 0;
1505 static time_t start_time;
1508 g_return_if_fail (result != NULL);
1510 if (start_tick == 0)
1512 start_tick = GetTickCount ();
1516 tick = GetTickCount ();
1518 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1519 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1523 /* Running the main loop */
1525 /* HOLDS: context's lock */
1527 g_main_dispatch (GMainContext *context)
1531 for (i = 0; i < context->pending_dispatches->len; i++)
1533 GSource *source = context->pending_dispatches->pdata[i];
1535 context->pending_dispatches->pdata[i] = NULL;
1538 source->flags &= ~G_SOURCE_READY;
1540 if (!SOURCE_DESTROYED (source))
1542 gboolean was_in_call;
1543 gpointer user_data = NULL;
1544 GSourceFunc callback = NULL;
1545 GSourceCallbackFuncs *cb_funcs;
1547 gboolean need_destroy;
1549 gboolean (*dispatch) (GSource *,
1553 dispatch = source->source_funcs->dispatch;
1554 cb_funcs = source->callback_funcs;
1555 cb_data = source->callback_data;
1558 cb_funcs->ref (cb_data);
1560 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1561 source->flags |= G_HOOK_FLAG_IN_CALL;
1563 UNLOCK_CONTEXT (context);
1566 cb_funcs->get (cb_data, &callback, &user_data);
1568 need_destroy = ! dispatch (source,
1571 LOCK_CONTEXT (context);
1574 cb_funcs->unref (cb_data);
1577 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1579 /* Note: this depends on the fact that we can't switch
1580 * sources from one main context to another
1582 if (need_destroy && !SOURCE_DESTROYED (source))
1584 g_assert (source->context == context);
1585 g_source_destroy_internal (source, context, TRUE);
1589 SOURCE_UNREF (source, context);
1592 g_ptr_array_set_size (context->pending_dispatches, 0);
1595 /* Holds context's lock */
1596 static inline GSource *
1597 next_valid_source (GMainContext *context,
1600 GSource *new_source = source ? source->next : context->source_list;
1604 if (!SOURCE_DESTROYED (new_source))
1606 new_source->ref_count++;
1610 new_source = new_source->next;
1614 SOURCE_UNREF (source, context);
1621 * g_main_context_prepare:
1622 * @context: a #GMainContext
1623 * @priority: location to store priority of highest priority
1624 * source already ready.
1626 * Prepares to poll sources within a main loop. The resulting information
1627 * for polling is determined by calling g_main_context_query ().
1629 * Return value: %TRUE if some source is ready to be dispatched
1633 g_main_context_prepare (GMainContext *context,
1637 gint current_priority = G_MAXINT;
1640 if (context == NULL)
1641 context = g_main_context_default ();
1643 LOCK_CONTEXT (context);
1645 context->time_is_current = FALSE;
1647 if (context->in_check_or_prepare)
1649 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1650 "prepare() member.");
1654 #ifdef G_THREADS_ENABLED
1655 if (context->poll_waiting)
1657 g_warning("g_main_context_prepare(): main loop already active in another thread");
1658 UNLOCK_CONTEXT (context);
1662 context->poll_waiting = TRUE;
1663 #endif /* G_THREADS_ENABLED */
1666 /* If recursing, finish up current dispatch, before starting over */
1667 if (context->pending_dispatches)
1670 g_main_dispatch (context, ¤t_time);
1672 UNLOCK_CONTEXT (context);
1677 /* If recursing, clear list of pending dispatches */
1678 g_ptr_array_set_size (context->pending_dispatches, 0);
1680 /* Prepare all sources */
1682 context->timeout = -1;
1684 source = next_valid_source (context, NULL);
1687 gint source_timeout = -1;
1689 if ((n_ready > 0) && (source->priority > current_priority))
1691 SOURCE_UNREF (source, context);
1694 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1697 if (!(source->flags & G_SOURCE_READY))
1700 gboolean (*prepare) (GSource *source,
1703 prepare = source->source_funcs->prepare;
1704 context->in_check_or_prepare++;
1705 UNLOCK_CONTEXT (context);
1707 result = (*prepare) (source, &source_timeout);
1709 LOCK_CONTEXT (context);
1710 context->in_check_or_prepare--;
1713 source->flags |= G_SOURCE_READY;
1716 if (source->flags & G_SOURCE_READY)
1719 current_priority = source->priority;
1720 context->timeout = 0;
1723 if (source_timeout >= 0)
1725 if (context->timeout < 0)
1726 context->timeout = source_timeout;
1728 context->timeout = MIN (context->timeout, source_timeout);
1732 source = next_valid_source (context, source);
1735 UNLOCK_CONTEXT (context);
1738 *priority = current_priority;
1740 return (n_ready > 0);
1744 * g_main_context_query:
1745 * @context: a #GMainContext
1746 * @max_priority: maximum priority source to check
1747 * @timeout: location to store timeout to be used in polling
1748 * @fds: location to store #GPollFD records that need to be polled.
1749 * @n_fds: length of @fds.
1751 * Determines information necessary to poll this main loop.
1756 g_main_context_query (GMainContext *context,
1765 LOCK_CONTEXT (context);
1767 pollrec = context->poll_records;
1769 while (pollrec && max_priority >= pollrec->priority)
1771 if (pollrec->fd->events)
1775 fds[n_poll].fd = pollrec->fd->fd;
1776 /* In direct contradiction to the Unix98 spec, IRIX runs into
1777 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1778 * flags in the events field of the pollfd while it should
1779 * just ignoring them. So we mask them out here.
1781 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1782 fds[n_poll].revents = 0;
1787 pollrec = pollrec->next;
1790 #ifdef G_THREADS_ENABLED
1791 context->poll_changed = FALSE;
1796 *timeout = context->timeout;
1798 context->time_is_current = FALSE;
1801 UNLOCK_CONTEXT (context);
1807 * g_main_context_check:
1808 * @context: a #GMainContext
1809 * @max_priority: the maximum numerical priority of sources to check
1810 * @fds: array of #GPollFD's that was passed to the last call to
1811 * g_main_context_query()
1812 * @n_fds: return value of g_main_context_query()
1814 * Pass the results of polling back to the main loop.
1816 * Return value: %TRUE if some sources are ready to be dispatched.
1819 g_main_context_check (GMainContext *context,
1829 LOCK_CONTEXT (context);
1831 if (context->in_check_or_prepare)
1833 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1834 "prepare() member.");
1838 #ifdef G_THREADS_ENABLED
1839 if (!context->poll_waiting)
1843 read (context->wake_up_pipe[0], &c, 1);
1847 context->poll_waiting = FALSE;
1849 /* If the set of poll file descriptors changed, bail out
1850 * and let the main loop rerun
1852 if (context->poll_changed)
1854 #endif /* G_THREADS_ENABLED */
1856 pollrec = context->poll_records;
1860 if (pollrec->fd->events)
1862 pollrec->fd->revents = fds[i].revents;
1865 pollrec = pollrec->next;
1868 source = next_valid_source (context, NULL);
1871 if ((n_ready > 0) && (source->priority > max_priority))
1873 SOURCE_UNREF (source, context);
1876 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1879 if (!(source->flags & G_SOURCE_READY))
1882 gboolean (*check) (GSource *source);
1884 check = source->source_funcs->check;
1886 context->in_check_or_prepare++;
1887 UNLOCK_CONTEXT (context);
1889 result = (*check) (source);
1891 LOCK_CONTEXT (context);
1892 context->in_check_or_prepare--;
1895 source->flags |= G_SOURCE_READY;
1898 if (source->flags & G_SOURCE_READY)
1900 source->ref_count++;
1901 g_ptr_array_add (context->pending_dispatches, source);
1907 source = next_valid_source (context, source);
1910 UNLOCK_CONTEXT (context);
1916 * g_main_context_dispatch:
1917 * @context: a #GMainContext
1919 * Dispatch all pending sources()
1922 g_main_context_dispatch (GMainContext *context)
1924 LOCK_CONTEXT (context);
1926 if (context->pending_dispatches->len > 0)
1928 g_main_dispatch (context);
1931 UNLOCK_CONTEXT (context);
1935 g_main_context_iterate (GMainContext *context,
1941 gboolean some_ready;
1942 gint nfds, new_nfds;
1945 some_ready = g_main_context_prepare (context, &max_priority);
1949 LOCK_CONTEXT (context);
1951 if (context->cached_poll_array)
1953 nfds = context->cached_poll_array_size;
1954 fds = context->cached_poll_array;
1955 context->cached_poll_array = NULL;
1959 nfds = context->cached_poll_array_size = context->n_poll_records;
1960 fds = g_new (GPollFD, nfds);
1963 UNLOCK_CONTEXT (context);
1965 new_nfds = g_main_context_query (context, max_priority,
1966 &timeout, fds, nfds);
1968 while (new_nfds > nfds);
1973 g_main_context_poll (context, timeout, max_priority,
1976 g_main_context_check (context,
1980 LOCK_CONTEXT (context);
1982 g_assert (!context->cached_poll_array);
1984 context->cached_poll_array = fds;
1985 context->cached_poll_array_size = nfds;
1987 UNLOCK_CONTEXT (context);
1990 g_main_context_dispatch (context);
1996 * g_main_context_pending:
1997 * @context: a #GMainContext (if %NULL, the default context will be used)
1999 * Check if any sources have pending events for the given context.
2001 * Return value: %TRUE if events are pending.
2004 g_main_context_pending (GMainContext *context)
2007 context = g_main_context_default();
2009 return g_main_context_iterate (context, FALSE, FALSE);
2013 * g_main_context_iteration:
2014 * @context: a #GMainContext (if %NULL, the default context will be used)
2015 * @may_block: whether the call may block.
2017 * Run a single iteration for the given main loop. This involves
2018 * checking to see if any event sources are ready to be processed,
2019 * then if no events sources are ready and @may_block is %TRUE, waiting
2020 * for a source to become ready, then dispatching the highest priority
2021 * events sources that are ready. Note that even when @may_block is %TRUE,
2022 * it is still possible for g_main_context_iteration() to return
2023 * %FALSE, since the the wait may be interrupted for other
2024 * reasons than an event source becoming ready.
2026 * Return value: %TRUE if events were dispatched.
2029 g_main_context_iteration (GMainContext *context, gboolean may_block)
2032 context = g_main_context_default();
2034 return g_main_context_iterate (context, may_block, TRUE);
2039 * @context: a #GMainContext (if %NULL, the default context will be used).
2040 * @is_running: set to TRUE to indicate that the loop is running. This
2041 * is not very important since calling g_main_run() will set this to
2044 * Create a new #GMainLoop structure
2049 g_main_loop_new (GMainContext *context,
2050 gboolean is_running)
2055 context = g_main_context_default();
2057 loop = g_new0 (GMainLoop, 1);
2058 loop->context = context;
2059 loop->is_running = is_running != FALSE;
2060 loop->ref_count = 1;
2062 #ifdef G_THREADS_ENABLED
2063 if (g_thread_supported ())
2064 loop->mutex = g_mutex_new ();
2067 loop->sem_cond = NULL;
2068 #endif /* G_THREADS_ENABLED */
2075 * @loop: a #GMainLoop
2077 * Increase the reference count on a #GMainLoop object by one.
2079 * Return value: @loop
2082 g_main_loop_ref (GMainLoop *loop)
2084 g_return_val_if_fail (loop != NULL, NULL);
2094 main_loop_destroy (GMainLoop *loop)
2096 #ifdef G_THREADS_ENABLED
2097 g_mutex_free (loop->mutex);
2099 g_cond_free (loop->sem_cond);
2100 #endif /* G_THREADS_ENABLED */
2106 * g_main_loop_unref:
2107 * @loop: a #GMainLoop
2109 * Decreases the reference count on a #GMainLoop object by one. If
2110 * the result is zero, free the loop and free all associated memory.
2113 g_main_loop_unref (GMainLoop *loop)
2115 g_return_if_fail (loop != NULL);
2116 g_return_if_fail (loop->ref_count > 0);
2121 if (loop->ref_count == 0)
2123 /* When the ref_count is 0, there can be nobody else using the
2124 * loop, so it is safe to unlock before destroying.
2127 main_loop_destroy (loop);
2135 * @loop: a #GMainLoop
2137 * Run a main loop until g_main_quit() is called on the loop.
2138 * If this is called for the thread of the loop's #GMainContext,
2139 * it will process events from the loop, otherwise it will
2143 g_main_loop_run (GMainLoop *loop)
2145 g_return_if_fail (loop != NULL);
2147 /* The assumption here is that a reference is held to the loop
2148 * until we recursively iterate
2150 #ifdef G_THREADS_ENABLED
2151 if (loop->context->thread != g_thread_self ())
2157 if (!g_thread_supported ())
2159 g_warning ("g_main_loop_run() was called from second thread but"
2160 "g_thread_init() was never called.");
2164 if (!loop->sem_cond)
2165 loop->sem_cond = g_cond_new ();
2167 if (!loop->is_running)
2168 loop->is_running = TRUE;
2170 while (loop->is_running)
2171 g_cond_wait (loop->sem_cond, loop->mutex);
2175 #endif /* G_THREADS_ENABLED */
2177 LOCK_CONTEXT (loop->context);
2178 if (loop->context->in_check_or_prepare)
2180 g_warning ("g_main_run(): called recursively from within a source's check() or "
2181 "prepare() member, iteration not possible.");
2184 UNLOCK_CONTEXT (loop->context);
2189 loop->is_running = TRUE;
2190 while (loop->is_running)
2193 g_main_context_iterate (loop->context, TRUE, TRUE);
2198 /* We inline this here rather than calling g_main_loop_unref() to
2199 * avoid an extra unlock/lock.
2202 if (loop->ref_count == 0)
2205 main_loop_destroy (loop);
2213 * @loop: a #GMainLoop
2215 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2216 * for the loop will return.
2219 g_main_loop_quit (GMainLoop *loop)
2221 g_return_if_fail (loop != NULL);
2224 loop->is_running = FALSE;
2226 #ifdef G_THREADS_ENABLED
2228 g_cond_broadcast (loop->sem_cond);
2233 LOCK_CONTEXT (loop->context);
2235 g_main_context_wakeup (loop->context);
2236 UNLOCK_CONTEXT (loop->context);
2240 * g_main_loop_is_running:
2241 * @loop: a #GMainLoop.
2243 * Check to see if the main loop is currently being run via g_main_run()
2245 * Return value: %TRUE if the mainloop is currently being run.
2248 g_main_loop_is_running (GMainLoop *loop)
2252 g_return_val_if_fail (loop != NULL, FALSE);
2255 result = loop->is_running;
2261 /* HOLDS: context's lock */
2263 g_main_context_poll (GMainContext *context,
2269 #ifdef G_MAIN_POLL_DEBUG
2275 GPollFunc poll_func;
2277 if (n_fds || timeout != 0)
2279 #ifdef G_MAIN_POLL_DEBUG
2280 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2281 poll_timer = g_timer_new ();
2284 LOCK_CONTEXT (context);
2286 poll_func = context->poll_func;
2288 UNLOCK_CONTEXT (context);
2289 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2290 g_warning ("poll(2) failed due to: %s.",
2291 g_strerror (errno));
2293 #ifdef G_MAIN_POLL_DEBUG
2294 LOCK_CONTEXT (context);
2296 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2299 g_timer_elapsed (poll_timer, NULL));
2300 g_timer_destroy (poll_timer);
2301 pollrec = context->poll_records;
2305 if (pollrec->fd->events)
2309 g_print (" [%d:", fds[i].fd);
2310 if (fds[i].revents & G_IO_IN)
2312 if (fds[i].revents & G_IO_OUT)
2314 if (fds[i].revents & G_IO_PRI)
2316 if (fds[i].revents & G_IO_ERR)
2318 if (fds[i].revents & G_IO_HUP)
2320 if (fds[i].revents & G_IO_NVAL)
2326 pollrec = pollrec->next;
2330 UNLOCK_CONTEXT (context);
2332 } /* if (n_fds || timeout != 0) */
2336 * g_main_context_add_poll:
2337 * @context: a #GMainContext (or %NULL for the default context)
2338 * @fd: a #GPollFD structure holding information about a file
2339 * descriptor to watch.
2340 * @priority: the priority for this file descriptor which should be
2341 * the same as the priority used for g_source_attach() to ensure that the
2342 * file descriptor is polled whenever the results may be needed.
2344 * Add a file descriptor to the set of file descriptors polled * for
2345 * this context. This will very seldom be used directly. Instead
2346 * a typical event source will use g_source_add_poll() instead.
2349 g_main_context_add_poll (GMainContext *context,
2354 context = g_main_context_default ();
2356 LOCK_CONTEXT (context);
2357 g_main_context_add_poll_unlocked (context, priority, fd);
2358 UNLOCK_CONTEXT (context);
2361 /* HOLDS: main_loop_lock */
2363 g_main_context_add_poll_unlocked (GMainContext *context,
2367 GPollRec *lastrec, *pollrec, *newrec;
2369 if (!context->poll_chunk)
2370 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2372 if (context->poll_free_list)
2374 newrec = context->poll_free_list;
2375 context->poll_free_list = newrec->next;
2378 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2380 /* This file descriptor may be checked before we ever poll */
2383 newrec->priority = priority;
2386 pollrec = context->poll_records;
2387 while (pollrec && priority >= pollrec->priority)
2390 pollrec = pollrec->next;
2394 lastrec->next = newrec;
2396 context->poll_records = newrec;
2398 newrec->next = pollrec;
2400 context->n_poll_records++;
2401 if (context->cached_poll_array &&
2402 context->cached_poll_array_size < context->n_poll_records)
2404 g_free (context->cached_poll_array);
2405 context->cached_poll_array = NULL;
2408 #ifdef G_THREADS_ENABLED
2409 context->poll_changed = TRUE;
2411 /* Now wake up the main loop if it is waiting in the poll() */
2412 g_main_context_wakeup (context);
2417 * g_main_context_remove_poll:
2418 * @context:a #GMainContext
2419 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2421 * Remove file descriptor from the set of file descriptors to be
2422 * polled for a particular context.
2425 g_main_context_remove_poll (GMainContext *context,
2429 context = g_main_context_default ();
2431 LOCK_CONTEXT (context);
2433 g_main_context_remove_poll_unlocked (context, fd);
2435 UNLOCK_CONTEXT (context);
2439 g_main_context_remove_poll_unlocked (GMainContext *context,
2442 GPollRec *pollrec, *lastrec;
2445 pollrec = context->poll_records;
2449 if (pollrec->fd == fd)
2451 if (lastrec != NULL)
2452 lastrec->next = pollrec->next;
2454 context->poll_records = pollrec->next;
2456 #ifdef ENABLE_GC_FRIENDLY
2458 #endif /* ENABLE_GC_FRIENDLY */
2460 pollrec->next = context->poll_free_list;
2461 context->poll_free_list = pollrec;
2463 context->n_poll_records--;
2467 pollrec = pollrec->next;
2470 #ifdef G_THREADS_ENABLED
2471 context->poll_changed = TRUE;
2473 /* Now wake up the main loop if it is waiting in the poll() */
2474 g_main_context_wakeup (context);
2479 * g_source_get_current_time:
2480 * @source: a #GSource
2481 * @timeval: #GTimeVal structure in which to store current time.
2483 * Gets the "current time" to be used when checking
2484 * this source. The advantage of calling this function over
2485 * calling g_get_current_time() directly is that when
2486 * checking multiple sources, GLib can cache a single value
2487 * instead of having to repeatedly get the system time.
2490 g_source_get_current_time (GSource *source,
2493 GMainContext *context;
2495 g_return_if_fail (source->context != NULL);
2497 context = source->context;
2499 LOCK_CONTEXT (context);
2501 if (!context->time_is_current)
2503 g_get_current_time (&context->current_time);
2504 context->time_is_current = TRUE;
2507 *timeval = context->current_time;
2509 UNLOCK_CONTEXT (context);
2513 * g_main_context_set_poll_func:
2514 * @context: a #GMainContext
2515 * @func: the function to call to poll all file descriptors
2517 * Sets the function to use to handle polling of file descriptors. It
2518 * will be used instead of the poll() system call (or GLib's
2519 * replacement function, which is used where poll() isn't available).
2521 * This function could possibly be used to integrate the GLib event
2522 * loop with an external event loop.
2525 g_main_context_set_poll_func (GMainContext *context,
2529 context = g_main_context_default ();
2531 LOCK_CONTEXT (context);
2534 context->poll_func = func;
2538 context->poll_func = (GPollFunc) poll;
2540 context->poll_func = (GPollFunc) g_poll;
2544 UNLOCK_CONTEXT (context);
2548 * g_main_context_get_poll_func:
2549 * @context: a #GMainContext
2551 * Gets the poll function set by g_main_context_set_poll_func()
2553 * Return value: the poll function
2556 g_main_context_get_poll_func (GMainContext *context)
2561 context = g_main_context_default ();
2563 LOCK_CONTEXT (context);
2564 result = context->poll_func;
2565 UNLOCK_CONTEXT (context);
2570 /* HOLDS: context's lock */
2571 /* Wake the main loop up from a poll() */
2573 g_main_context_wakeup (GMainContext *context)
2575 #ifdef G_THREADS_ENABLED
2576 if (g_thread_supported() && context->poll_waiting)
2578 context->poll_waiting = FALSE;
2580 write (context->wake_up_pipe[1], "A", 1);
2582 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2591 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2592 GTimeVal *current_time)
2594 guint seconds = timeout_source->interval / 1000;
2595 guint msecs = timeout_source->interval - seconds * 1000;
2597 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2598 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2599 if (timeout_source->expiration.tv_usec >= 1000000)
2601 timeout_source->expiration.tv_usec -= 1000000;
2602 timeout_source->expiration.tv_sec++;
2607 g_timeout_prepare (GSource *source,
2611 GTimeVal current_time;
2613 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2615 g_source_get_current_time (source, ¤t_time);
2617 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2618 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2622 else if (msec > timeout_source->interval)
2624 /* The system time has been set backwards, so we
2625 * reset the expiration time to now + timeout_source->interval;
2626 * this at least avoids hanging for long periods of time.
2628 g_timeout_set_expiration (timeout_source, ¤t_time);
2629 msec = timeout_source->interval;
2638 g_timeout_check (GSource *source)
2640 GTimeVal current_time;
2641 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2643 g_source_get_current_time (source, ¤t_time);
2645 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2646 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2647 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2651 g_timeout_dispatch (GSource *source,
2652 GSourceFunc callback,
2655 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2659 g_warning ("Timeout source dispatched without callback\n"
2660 "You must call g_source_set_callback().");
2664 if (callback (user_data))
2666 GTimeVal current_time;
2668 g_source_get_current_time (source, ¤t_time);
2669 g_timeout_set_expiration (timeout_source, ¤t_time);
2678 * g_timeout_source_new:
2679 * @interval: the timeout interval in milliseconds.
2681 * Create a new timeout source.
2683 * The source will not initially be associated with any #GMainContext
2684 * and must be added to one with g_source_attach() before it will be
2687 * Return value: the newly create timeout source
2690 g_timeout_source_new (guint interval)
2692 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2693 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2694 GTimeVal current_time;
2696 timeout_source->interval = interval;
2698 g_get_current_time (¤t_time);
2699 g_timeout_set_expiration (timeout_source, ¤t_time);
2705 * g_timeout_add_full:
2706 * @priority: the priority of the idle source. Typically this will be in the
2707 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2708 * @interval: the time between calls to the function, in milliseconds
2709 * (1/1000ths of a second.)
2710 * @function: function to call
2711 * @data: data to pass to @function
2712 * @notify: function to call when the idle is removed, or %NULL
2714 * Sets a function to be called at regular intervals, with the given
2715 * priority. The function is called repeatedly until it returns
2716 * FALSE, at which point the timeout is automatically destroyed and
2717 * the function will not be called again. The @notify function is
2718 * called when the timeout is destroyed. The first call to the
2719 * function will be at the end of the first @interval.
2721 * Note that timeout functions may be delayed, due to the processing of other
2722 * event sources. Thus they should not be relied on for precise timing.
2723 * After each call to the timeout function, the time of the next
2724 * timeout is recalculated based on the current time and the given interval
2725 * (it does not try to 'catch up' time lost in delays).
2727 * Return value: the id of event source.
2730 g_timeout_add_full (gint priority,
2732 GSourceFunc function,
2734 GDestroyNotify notify)
2739 g_return_val_if_fail (function != NULL, 0);
2741 source = g_timeout_source_new (interval);
2743 if (priority != G_PRIORITY_DEFAULT)
2744 g_source_set_priority (source, priority);
2746 g_source_set_callback (source, function, data, notify);
2747 id = g_source_attach (source, NULL);
2748 g_source_unref (source);
2755 * @interval: the time between calls to the function, in milliseconds
2756 * (1/1000ths of a second.)
2757 * @function: function to call
2758 * @data: data to pass to @function
2760 * Sets a function to be called at regular intervals, with the default
2761 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2762 * until it returns FALSE, at which point the timeout is automatically
2763 * destroyed and the function will not be called again. The @notify
2764 * function is called when the timeout is destroyed. The first call
2765 * to the function will be at the end of the first @interval.
2767 * Note that timeout functions may be delayed, due to the processing of other
2768 * event sources. Thus they should not be relied on for precise timing.
2769 * After each call to the timeout function, the time of the next
2770 * timeout is recalculated based on the current time and the given interval
2771 * (it does not try to 'catch up' time lost in delays).
2773 * Return value: the id of event source.
2776 g_timeout_add (guint32 interval,
2777 GSourceFunc function,
2780 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2781 interval, function, data, NULL);
2784 /* Idle functions */
2787 g_idle_prepare (GSource *source,
2796 g_idle_check (GSource *source)
2802 g_idle_dispatch (GSource *source,
2803 GSourceFunc callback,
2808 g_warning ("Idle source dispatched without callback\n"
2809 "You must call g_source_set_callback().");
2813 return callback (user_data);
2817 * g_idle_source_new:
2819 * Create a new idle source.
2821 * The source will not initially be associated with any #GMainContext
2822 * and must be added to one with g_source_attach() before it will be
2825 * Return value: the newly created idle source
2828 g_idle_source_new (void)
2830 return g_source_new (&idle_funcs, sizeof (GSource));
2835 * @priority: the priority of the idle source. Typically this will be in the
2836 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2837 * @function: function to call
2838 * @data: data to pass to @function
2839 * @notify: function to call when the idle is removed, or %NULL
2841 * Adds a function to be called whenever there are no higher priority
2842 * events pending. If the function returns FALSE it is automatically
2843 * removed from the list of event sources and will not be called again.
2845 * Return value: the id of the event source.
2848 g_idle_add_full (gint priority,
2849 GSourceFunc function,
2851 GDestroyNotify notify)
2856 g_return_val_if_fail (function != NULL, 0);
2858 source = g_idle_source_new ();
2860 if (priority != G_PRIORITY_DEFAULT)
2861 g_source_set_priority (source, priority);
2863 g_source_set_callback (source, function, data, notify);
2864 id = g_source_attach (source, NULL);
2865 g_source_unref (source);
2872 * @function: function to call
2873 * @data: data to pass to @function.
2875 * Adds a function to be called whenever there are no higher priority
2876 * events pending to the default main loop. The function is given the
2877 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2878 * returns FALSE it is automatically removed from the list of event
2879 * sources and will not be called again.
2881 * Return value: the id of the event source.
2884 g_idle_add (GSourceFunc function,
2887 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2891 * g_idle_remove_by_data:
2892 * @data: the data for the idle source's callback.
2894 * Removes the idle function with the given data.
2896 * Return value: %TRUE if an idle source was found and removed.
2899 g_idle_remove_by_data (gpointer data)
2901 return g_source_remove_by_funcs_user_data (&idle_funcs, data);