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, usually 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_new:
532 * @thread: a #GThread (may be NULL)
534 * This will create a main-loop context. The context will need to be destroyed
535 * via g_main_context_destroy.
537 * Return value: a new main loop context.
540 g_main_context_new(GThread *thread)
542 GMainContext *context;
544 context = g_new0 (GMainContext, 1);
546 #ifdef G_THREADS_ENABLED
547 if (g_thread_supported ())
548 context->mutex = g_mutex_new();
550 context->thread = thread;
553 context->next_id = 1;
555 context->source_list = NULL;
558 context->poll_func = (GPollFunc)poll;
560 context->poll_func = g_poll;
563 context->cached_poll_array = NULL;
564 context->cached_poll_array_size = 0;
566 context->pending_dispatches = g_ptr_array_new ();
568 context->time_is_current = FALSE;
570 #ifdef G_THREADS_ENABLED
571 if (g_thread_supported ())
574 if (pipe (context->wake_up_pipe) < 0)
575 g_error ("Cannot create pipe main loop wake-up: %s\n",
578 context->wake_up_rec.fd = context->wake_up_pipe[0];
579 context->wake_up_rec.events = G_IO_IN;
580 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
582 if ((context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
583 g_error ("Cannot create wake-up semaphore: %s", g_win32_error_message (GetLastError ()));
584 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
585 context->wake_up_rec.events = G_IO_IN;
586 #ifdef G_MAIN_POLL_DEBUG
587 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
589 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
598 * g_main_context_get:
599 * @thread: a #GThread
601 * Retrieves the main loop context for a particular thread. This
602 * will create the main context for the thread if none previously
603 * existed. The context will exist until the thread terminates.
605 * Return value: the main loop context for @thread.
608 g_main_context_get (GThread *thread)
610 static GStaticPrivate private_key = G_STATIC_PRIVATE_INIT;
611 GMainContext *context;
613 g_return_val_if_fail (thread != NULL, NULL);
615 if (g_thread_supported ())
616 context = g_static_private_get_for_thread (&private_key, thread);
618 context = default_main_context;
622 context = g_main_context_new (thread);
624 if (g_thread_supported ())
625 g_static_private_set_for_thread (&private_key, thread,
627 (GDestroyNotify)g_main_context_destroy);
629 default_main_context = context;
636 * g_main_context_default:
638 * Return the default main context. This is the main context used
639 * for main loop functions when a main loop is not explicitly
642 * Return value: the default main context.
645 g_main_context_default (void)
651 if (!default_main_context)
652 default_main_context = g_main_context_get (g_thread_self ());
654 G_UNLOCK (main_loop);
656 return default_main_context;
659 /* Hooks for adding to the main loop */
663 * @source_funcs: structure containing functions that implement
664 * the sources behavior.
665 * @struct_size: size of the #GSource structure to create
667 * Create a new GSource structure. The size is specified to
668 * allow creating structures derived from GSource that contain
669 * additional data. The size passed in must be at least
672 * The source will not initially be associated with any #GMainContext
673 * and must be added to one with g_source_add() before it will be
676 * Return value: the newly create #GSource
679 g_source_new (GSourceFuncs *source_funcs,
684 g_return_val_if_fail (source_funcs != NULL, NULL);
685 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
687 source = (GSource*) g_malloc0 (struct_size);
689 source->source_funcs = source_funcs;
690 source->ref_count = 1;
692 source->priority = G_PRIORITY_DEFAULT;
694 source->flags = G_HOOK_FLAG_ACTIVE;
696 /* NULL/0 initialization for all other fields */
701 /* Holds context's lock
704 g_source_list_add (GSource *source,
705 GMainContext *context)
707 GSource *tmp_source, *last_source;
710 tmp_source = context->source_list;
711 while (tmp_source && tmp_source->priority <= source->priority)
713 last_source = tmp_source;
714 tmp_source = tmp_source->next;
717 source->next = tmp_source;
719 tmp_source->prev = source;
721 source->prev = last_source;
723 last_source->next = source;
725 context->source_list = source;
728 /* Holds context's lock
731 g_source_list_remove (GSource *source,
732 GMainContext *context)
735 source->prev->next = source->next;
737 context->source_list = source->next;
740 source->next->prev = source->prev;
748 * @source: a #GSource
749 * @context: a #GMainContext (if %NULL, the default context will be used)
751 * Adds a #GSource to a @context so that it will be executed within
754 * Return value: the ID for the source within the #GMainContext
757 g_source_attach (GSource *source,
758 GMainContext *context)
763 g_return_val_if_fail (source->context == NULL, 0);
764 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
767 context = g_main_context_default ();
769 LOCK_CONTEXT (context);
771 source->context = context;
772 result = source->id = context->next_id++;
775 g_source_list_add (source, context);
777 tmp_list = source->poll_fds;
780 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
781 tmp_list = tmp_list->next;
784 #ifdef G_THREADS_ENABLED
785 /* Now wake up the main loop if it is waiting in the poll() */
786 g_main_context_wakeup (context);
789 UNLOCK_CONTEXT (context);
795 g_source_destroy_internal (GSource *source,
796 GMainContext *context,
800 LOCK_CONTEXT (context);
802 if (!SOURCE_DESTROYED (source))
805 gpointer old_cb_data;
806 GSourceCallbackFuncs *old_cb_funcs;
808 source->flags &= ~G_HOOK_FLAG_ACTIVE;
810 old_cb_data = source->callback_data;
811 old_cb_funcs = source->callback_funcs;
813 source->callback_data = NULL;
814 source->callback_funcs = NULL;
818 UNLOCK_CONTEXT (context);
819 old_cb_funcs->unref (old_cb_data);
820 LOCK_CONTEXT (context);
823 tmp_list = source->poll_fds;
826 g_main_context_remove_poll_unlocked (context, tmp_list->data);
827 tmp_list = tmp_list->next;
830 g_source_unref_internal (source, context, TRUE);
834 UNLOCK_CONTEXT (context);
839 * @source: a #GSource
841 * Remove a source from its #GMainContext, if any, and mark it as
842 * destroyed. The source cannot be subsequently added to another
846 g_source_destroy (GSource *source)
848 GMainContext *context;
850 g_return_if_fail (source != NULL);
852 context = source->context;
855 g_source_destroy_internal (source, context, FALSE);
857 source->flags &= ~G_HOOK_FLAG_ACTIVE;
862 * @source: a #GSource
864 * Return the numeric ID for a particular source. The ID of a source
865 * is unique within a particular main loop context. The reverse
866 * mapping from ID to source is done by g_main_context_find_source_by_id().
868 * Return value: the ID for the source
871 g_source_get_id (GSource *source)
875 g_return_val_if_fail (source != NULL, 0);
876 g_return_val_if_fail (source->context != NULL, 0);
878 LOCK_CONTEXT (source->context);
880 UNLOCK_CONTEXT (source->context);
886 * g_source_get_context:
887 * @source: a #GSource
889 * Get the #GMainContext with which the source is associated.
890 * Calling this function on a destroyed source is an error.
892 * Return value: the #GMainContext with which the source is associated,
893 * or %NULL if the context has not yet been added
897 g_source_get_context (GSource *source)
899 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
901 return source->context;
905 * g_main_source_add_poll:
907 * @fd: a #GPollFD structure holding information about a file
908 * descriptor to watch.
910 * Add a file descriptor to the set of file descriptors polled * for
911 * this source. This is usually combined with g_source_new() to add an
912 * event source. The event source's check function will typically test
913 * the revents field in the #GPollFD struct and return %TRUE if events need
917 g_source_add_poll (GSource *source,
920 GMainContext *context;
922 g_return_if_fail (source != NULL);
923 g_return_if_fail (fd != NULL);
924 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
926 context = source->context;
929 LOCK_CONTEXT (context);
931 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
935 g_main_context_add_poll_unlocked (context, source->priority, fd);
936 UNLOCK_CONTEXT (context);
941 * g_source_set_callback_indirect:
942 * @source: the source
943 * @callback_data: pointer to callback data "object"
944 * @callback_funcs: functions for reference counting callback_data
945 * and getting the callback and data
947 * Set the callback function storing the data as a refcounted callback
948 * "object". This is used to implement g_source_set_callback_closure()
949 * and internally. Note that calling g_source_set_callback_indirect() assumes
950 * an initial reference count on @callback_data, and thus
951 * @callback_funcs->unref will eventually be called once more
952 * than @callback_funcs->ref.
955 g_source_set_callback_indirect (GSource *source,
956 gpointer callback_data,
957 GSourceCallbackFuncs *callback_funcs)
959 GMainContext *context;
960 gpointer old_cb_data;
961 GSourceCallbackFuncs *old_cb_funcs;
963 g_return_if_fail (source != NULL);
964 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
966 context = source->context;
969 LOCK_CONTEXT (context);
971 old_cb_data = source->callback_data;
972 old_cb_funcs = source->callback_funcs;
974 source->callback_data = callback_data;
975 source->callback_funcs = callback_funcs;
978 UNLOCK_CONTEXT (context);
981 old_cb_funcs->unref (old_cb_data);
985 g_source_callback_ref (gpointer cb_data)
987 GSourceCallback *callback = cb_data;
989 callback->ref_count++;
994 g_source_callback_unref (gpointer cb_data)
996 GSourceCallback *callback = cb_data;
998 callback->ref_count--;
999 if (callback->ref_count == 0)
1001 if (callback->notify)
1002 callback->notify (callback->data);
1007 g_source_callback_get (gpointer cb_data,
1011 GSourceCallback *callback = cb_data;
1013 *func = callback->func;
1014 *data = callback->data;
1017 static GSourceCallbackFuncs g_source_callback_funcs = {
1018 g_source_callback_ref,
1019 g_source_callback_unref,
1020 g_source_callback_get,
1024 * g_source_set_callback:
1025 * @source: the source
1026 * @func: a callback function
1027 * @data: the data to pass to callback function
1028 * @notify: a function to call when @data is no longer in use, or %NULL.
1030 * Set the callback function for a source.
1033 g_source_set_callback (GSource *source,
1036 GDestroyNotify notify)
1038 GSourceCallback *new_callback;
1040 g_return_if_fail (source != NULL);
1042 new_callback = g_new (GSourceCallback, 1);
1044 new_callback->func = func;
1045 new_callback->data = data;
1046 new_callback->notify = notify;
1048 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1052 * g_source_set_priority:
1053 * @source: a #GSource
1054 * @priority: the new priority.
1056 * Set the priority of a source. While the main loop is being
1057 * run, a source will
1060 g_source_set_priority (GSource *source,
1064 GMainContext *context;
1066 g_return_if_fail (source != NULL);
1068 context = source->context;
1071 LOCK_CONTEXT (context);
1073 source->priority = priority;
1077 source->next = NULL;
1078 source->prev = NULL;
1080 tmp_list = source->poll_fds;
1083 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1084 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1086 tmp_list = tmp_list->next;
1089 UNLOCK_CONTEXT (source->context);
1094 * g_source_get_priority:
1095 * @source: a #GSource
1097 * Gets the priority of a surce
1099 * Return value: the priority of the source
1102 g_source_get_priority (GSource *source)
1104 g_return_val_if_fail (source != NULL, 0);
1106 return source->priority;
1110 * g_source_set_can_recurse:
1111 * @source: a #GSource
1112 * @can_recurse: whether recursion is allowed for this source
1114 * Sets whether a source can be called recursively. If @can_recurse is
1115 * %TRUE, then while the source is being dispatched then this source
1116 * will be processed normally. Otherwise, all processing of this
1117 * source is blocked until the dispatch function returns.
1120 g_source_set_can_recurse (GSource *source,
1121 gboolean can_recurse)
1123 GMainContext *context;
1125 g_return_if_fail (source != NULL);
1127 context = source->context;
1130 LOCK_CONTEXT (context);
1133 source->flags |= G_SOURCE_CAN_RECURSE;
1135 source->flags &= ~G_SOURCE_CAN_RECURSE;
1138 UNLOCK_CONTEXT (context);
1142 * g_source_get_can_recurse:
1143 * @source: a #GSource
1145 * Checks whether a source is allowed to be called recursively.
1146 * see g_source_set_can_recurse.
1148 * Return value: whether recursion is allowed.
1151 g_source_get_can_recurse (GSource *source)
1153 g_return_val_if_fail (source != NULL, FALSE);
1155 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1160 * @source: a #GSource
1162 * Increases the reference count on a source by one.
1164 * Return value: @source
1167 g_source_ref (GSource *source)
1169 GMainContext *context;
1171 g_return_val_if_fail (source != NULL, NULL);
1173 context = source->context;
1176 LOCK_CONTEXT (context);
1178 source->ref_count++;
1181 UNLOCK_CONTEXT (context);
1186 /* g_source_unref() but possible to call within context lock
1189 g_source_unref_internal (GSource *source,
1190 GMainContext *context,
1193 gpointer cb_data = NULL;
1194 GSourceCallbackFuncs *cb_funcs = NULL;
1197 g_return_if_fail (source != NULL);
1199 if (!have_lock && context)
1200 LOCK_CONTEXT (context);
1202 source->ref_count--;
1203 if (source->ref_count == 0)
1205 if (context && !SOURCE_DESTROYED (source))
1207 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1208 source->ref_count++;
1211 g_source_list_remove (source, context);
1213 if (source->source_funcs->destroy)
1214 source->source_funcs->destroy (source);
1216 g_slist_free (source->poll_fds);
1217 source->poll_fds = NULL;
1221 if (!have_lock && context)
1222 UNLOCK_CONTEXT (context);
1227 UNLOCK_CONTEXT (context);
1229 cb_funcs->unref (cb_data);
1232 LOCK_CONTEXT (context);
1238 * @source: a #GSource
1240 * Decreases the reference count of a source by one. If the
1241 * resulting reference count is zero the source and associated
1242 * memory will be destroyed.
1245 g_source_unref (GSource *source)
1247 g_return_if_fail (source != NULL);
1249 g_source_unref_internal (source, source->context, FALSE);
1253 * g_main_context_find_source_by_id:
1254 * @context: a #GMainContext (if %NULL, the default context will be used)
1255 * @id: the source ID, as returned by g_source_get_id()
1257 * Finds a #GSource given a pair of context and ID
1259 * Return value: the #GSource if found, otherwise, %NULL
1262 g_main_context_find_source_by_id (GMainContext *context,
1267 g_return_val_if_fail (id > 0, FALSE);
1269 if (context == NULL)
1270 context = g_main_context_default ();
1272 LOCK_CONTEXT (context);
1274 source = context->source_list;
1277 if (!SOURCE_DESTROYED (source) &&
1280 source = source->next;
1283 UNLOCK_CONTEXT (context);
1289 * g_main_context_find_source_by_funcs_user_data:
1290 * @context: a #GMainContext (if %NULL, the default context will be used).
1291 * @funcs: the @source_funcs passed to g_source_new().
1292 * @user_data: the user data from the callback.
1294 * Finds a source with the given source functions and user data. If
1295 * multiple sources exist with the same source function and user data,
1296 * the first one found will be returned.
1298 * Return value: the source, if one was found, otherwise %NULL
1301 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1302 GSourceFuncs *funcs,
1307 g_return_val_if_fail (funcs != NULL, FALSE);
1309 if (context == NULL)
1310 context = g_main_context_default ();
1312 LOCK_CONTEXT (context);
1314 source = context->source_list;
1317 if (!SOURCE_DESTROYED (source) &&
1318 source->source_funcs == funcs &&
1319 source->callback_data == user_data)
1321 source = source->next;
1324 UNLOCK_CONTEXT (context);
1330 * g_main_context_find_source_by_user_data:
1331 * @context: a #GMainContext
1332 * @user_data: the user_data for the callback.
1334 * Finds a source with the given user data for the callback. If
1335 * multiple sources exist with the same user data, the first
1336 * one found will be returned.
1338 * Return value: the source, if one was found, otherwise %NULL
1341 g_main_context_find_source_by_user_data (GMainContext *context,
1346 if (context == NULL)
1347 context = g_main_context_default ();
1349 LOCK_CONTEXT (context);
1351 source = context->source_list;
1354 if (!SOURCE_DESTROYED (source) &&
1355 source->callback_data == user_data)
1357 source = source->next;
1360 UNLOCK_CONTEXT (context);
1367 * @tag: the id of the source to remove.
1369 * Removes the source with the given id from the default main
1370 * context. The id of a #GSource is given by g_source_get_id(),
1371 * or will be returned by the functions g_source_attach(),
1372 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1373 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1375 * See also g_source_destroy().
1377 * Return value: %TRUE if the source was found and removed.
1380 g_source_remove (guint tag)
1384 g_return_val_if_fail (tag > 0, FALSE);
1386 source = g_main_context_find_source_by_id (NULL, tag);
1388 g_source_destroy (source);
1390 return source != NULL;
1394 * g_source_remove_by_user_data:
1395 * @user_data: the user_data for the callback.
1397 * Removes a source from the default main loop context given the user
1398 * data for the callback. If multiple sources exist with the same user
1399 * data, only one will be destroyed.
1401 * Return value: %TRUE if a source was found and removed.
1404 g_source_remove_by_user_data (gpointer user_data)
1408 source = g_main_context_find_source_by_user_data (NULL, user_data);
1411 g_source_destroy (source);
1419 * g_source_remove_by_funcs_user_data:
1420 * @funcs: The @source_funcs passed to g_source_new()
1421 * @user_data: the user data for the callback
1423 * Removes a source from the default main loop context given the
1424 * source functions and user data. If multiple sources exist with the
1425 * same source functions and user data, only one will be destroyed.
1427 * Return value: %TRUE if a source was found and removed.
1430 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1435 g_return_val_if_fail (funcs != NULL, FALSE);
1437 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1440 g_source_destroy (source);
1448 * g_get_current_time:
1449 * @result: #GTimeVal structure in which to store current time.
1451 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1454 g_get_current_time (GTimeVal *result)
1459 g_return_if_fail (result != NULL);
1461 /*this is required on alpha, there the timeval structs are int's
1462 not longs and a cast only would fail horribly*/
1463 gettimeofday (&r, NULL);
1464 result->tv_sec = r.tv_sec;
1465 result->tv_usec = r.tv_usec;
1467 /* Avoid calling time() except for the first time.
1468 * GetTickCount() should be pretty fast and low-level?
1469 * I could also use ftime() but it seems unnecessarily overheady.
1471 static DWORD start_tick = 0;
1472 static time_t start_time;
1475 g_return_if_fail (result != NULL);
1477 if (start_tick == 0)
1479 start_tick = GetTickCount ();
1483 tick = GetTickCount ();
1485 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1486 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1490 /* Running the main loop */
1492 /* HOLDS: context's lock */
1494 g_main_dispatch (GMainContext *context)
1498 for (i = 0; i < context->pending_dispatches->len; i++)
1500 GSource *source = context->pending_dispatches->pdata[i];
1502 context->pending_dispatches->pdata[i] = NULL;
1505 source->flags &= ~G_SOURCE_READY;
1507 if (!SOURCE_DESTROYED (source))
1509 gboolean was_in_call;
1510 gpointer user_data = NULL;
1511 GSourceFunc callback = NULL;
1512 GSourceCallbackFuncs *cb_funcs;
1514 gboolean need_destroy;
1516 gboolean (*dispatch) (GSource *,
1520 dispatch = source->source_funcs->dispatch;
1521 cb_funcs = source->callback_funcs;
1522 cb_data = source->callback_data;
1525 cb_funcs->ref (cb_data);
1527 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1528 source->flags |= G_HOOK_FLAG_IN_CALL;
1530 UNLOCK_CONTEXT (context);
1533 cb_funcs->get (cb_data, &callback, &user_data);
1535 need_destroy = ! dispatch (source,
1538 LOCK_CONTEXT (context);
1541 cb_funcs->unref (cb_data);
1544 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1546 /* Note: this depends on the fact that we can't switch
1547 * sources from one main context to another
1549 if (need_destroy && !SOURCE_DESTROYED (source))
1551 g_assert (source->context == context);
1552 g_source_destroy_internal (source, context, TRUE);
1556 SOURCE_UNREF (source, context);
1559 g_ptr_array_set_size (context->pending_dispatches, 0);
1562 /* Holds context's lock */
1563 static inline GSource *
1564 next_valid_source (GMainContext *context,
1567 GSource *new_source = source ? source->next : context->source_list;
1571 if (!SOURCE_DESTROYED (new_source))
1573 new_source->ref_count++;
1577 new_source = new_source->next;
1581 SOURCE_UNREF (source, context);
1588 * g_main_context_prepare:
1589 * @context: a #GMainContext
1590 * @priority: location to store priority of highest priority
1591 * source already ready.
1593 * Prepares to poll sources within a main loop. The resulting information
1594 * for polling is determined by calling g_main_context_query ().
1596 * Return value: %TRUE if some source is ready to be dispatched
1600 g_main_context_prepare (GMainContext *context,
1604 gint current_priority = G_MAXINT;
1607 if (context == NULL)
1608 context = g_main_context_default ();
1610 LOCK_CONTEXT (context);
1612 context->time_is_current = FALSE;
1614 if (context->in_check_or_prepare)
1616 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1617 "prepare() member.");
1621 #ifdef G_THREADS_ENABLED
1622 if (context->poll_waiting)
1624 g_warning("g_main_context_prepare(): main loop already active in another thread");
1625 UNLOCK_CONTEXT (context);
1629 context->poll_waiting = TRUE;
1630 #endif /* G_THREADS_ENABLED */
1633 /* If recursing, finish up current dispatch, before starting over */
1634 if (context->pending_dispatches)
1637 g_main_dispatch (context, ¤t_time);
1639 UNLOCK_CONTEXT (context);
1644 /* If recursing, clear list of pending dispatches */
1645 g_ptr_array_set_size (context->pending_dispatches, 0);
1647 /* Prepare all sources */
1649 context->timeout = -1;
1651 source = next_valid_source (context, NULL);
1654 gint source_timeout = -1;
1656 if ((n_ready > 0) && (source->priority > current_priority))
1658 SOURCE_UNREF (source, context);
1661 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1664 if (!(source->flags & G_SOURCE_READY))
1667 gboolean (*prepare) (GSource *source,
1670 prepare = source->source_funcs->prepare;
1671 context->in_check_or_prepare++;
1672 UNLOCK_CONTEXT (context);
1674 result = (*prepare) (source, &source_timeout);
1676 LOCK_CONTEXT (context);
1677 context->in_check_or_prepare--;
1680 source->flags |= G_SOURCE_READY;
1683 if (source->flags & G_SOURCE_READY)
1686 current_priority = source->priority;
1687 context->timeout = 0;
1690 if (source_timeout >= 0)
1692 if (context->timeout < 0)
1693 context->timeout = source_timeout;
1695 context->timeout = MIN (context->timeout, source_timeout);
1699 source = next_valid_source (context, source);
1702 UNLOCK_CONTEXT (context);
1705 *priority = current_priority;
1707 return (n_ready > 0);
1711 * g_main_context_query:
1712 * @context: a #GMainContext
1713 * @max_priority: maximum priority source to check
1714 * @timeout: location to store timeout to be used in polling
1715 * @fds: location to store #GPollFD records that need to be polled.
1716 * @n_fds: length of @fds.
1718 * Determines information necessary to poll this main loop.
1723 g_main_context_query (GMainContext *context,
1732 LOCK_CONTEXT (context);
1734 pollrec = context->poll_records;
1736 while (pollrec && max_priority >= pollrec->priority)
1738 if (pollrec->fd->events)
1742 fds[n_poll].fd = pollrec->fd->fd;
1743 /* In direct contradiction to the Unix98 spec, IRIX runs into
1744 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1745 * flags in the events field of the pollfd while it should
1746 * just ignoring them. So we mask them out here.
1748 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1749 fds[n_poll].revents = 0;
1754 pollrec = pollrec->next;
1757 context->poll_changed = FALSE;
1761 *timeout = context->timeout;
1763 context->time_is_current = FALSE;
1766 UNLOCK_CONTEXT (context);
1772 * g_main_context_check:
1773 * @context: a #GMainContext
1774 * @max_priority: the maximum numerical priority of sources to check
1775 * @fds: array of #GPollFD's that was passed to the last call to
1776 * g_main_context_query()
1777 * @n_fds: return value of g_main_context_query()
1779 * Pass the results of polling back to the main loop.
1781 * Return value: %TRUE if some sources are ready to be dispatched.
1784 g_main_context_check (GMainContext *context,
1794 LOCK_CONTEXT (context);
1796 if (context->in_check_or_prepare)
1798 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1799 "prepare() member.");
1803 #ifdef G_THREADS_ENABLED
1804 if (!context->poll_waiting)
1808 read (context->wake_up_pipe[0], &c, 1);
1812 context->poll_waiting = FALSE;
1813 #endif /* G_THREADS_ENABLED */
1815 /* If the set of poll file descriptors changed, bail out
1816 * and let the main loop rerun
1818 if (context->poll_changed)
1821 pollrec = context->poll_records;
1825 if (pollrec->fd->events)
1827 pollrec->fd->revents = fds[i].revents;
1830 pollrec = pollrec->next;
1833 source = next_valid_source (context, NULL);
1836 if ((n_ready > 0) && (source->priority > max_priority))
1838 SOURCE_UNREF (source, context);
1841 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1844 if (!(source->flags & G_SOURCE_READY))
1847 gboolean (*check) (GSource *source);
1849 check = source->source_funcs->check;
1851 context->in_check_or_prepare++;
1852 UNLOCK_CONTEXT (context);
1854 result = (*check) (source);
1856 LOCK_CONTEXT (context);
1857 context->in_check_or_prepare--;
1860 source->flags |= G_SOURCE_READY;
1863 if (source->flags & G_SOURCE_READY)
1865 source->ref_count++;
1866 g_ptr_array_add (context->pending_dispatches, source);
1872 source = next_valid_source (context, source);
1875 UNLOCK_CONTEXT (context);
1881 * g_main_context_dispatch:
1882 * @context: a #GMainContext
1884 * Dispatch all pending sources()
1887 g_main_context_dispatch (GMainContext *context)
1889 LOCK_CONTEXT (context);
1891 if (context->pending_dispatches->len > 0)
1893 g_main_dispatch (context);
1896 UNLOCK_CONTEXT (context);
1900 g_main_context_iterate (GMainContext *context,
1906 gboolean some_ready;
1907 gint nfds, new_nfds;
1910 some_ready = g_main_context_prepare (context, &max_priority);
1914 LOCK_CONTEXT (context);
1916 if (context->cached_poll_array)
1918 nfds = context->cached_poll_array_size;
1919 fds = context->cached_poll_array;
1920 context->cached_poll_array = NULL;
1924 nfds = context->cached_poll_array_size = context->n_poll_records;
1925 fds = g_new (GPollFD, nfds);
1928 UNLOCK_CONTEXT (context);
1930 new_nfds = g_main_context_query (context, max_priority,
1931 &timeout, fds, nfds);
1933 while (new_nfds > nfds);
1938 g_main_context_poll (context, timeout, max_priority,
1941 g_main_context_check (context,
1945 LOCK_CONTEXT (context);
1947 g_assert (!context->cached_poll_array);
1949 context->cached_poll_array = fds;
1950 context->cached_poll_array_size = nfds;
1952 UNLOCK_CONTEXT (context);
1955 g_main_context_dispatch (context);
1961 * g_main_context_pending:
1962 * @context: a #GMainContext (if %NULL, the default context will be used)
1964 * Check if any sources have pending events for the given context.
1966 * Return value: %TRUE if events are pending.
1969 g_main_context_pending (GMainContext *context)
1972 context = g_main_context_default();
1974 return g_main_context_iterate (context, FALSE, FALSE);
1978 * g_main_context_iteration:
1979 * @context: a #GMainContext (if %NULL, the default context will be used)
1980 * @may_block: whether the call may block.
1982 * Run a single iteration for the given main loop. This involves
1983 * checking to see if any event sources are ready to be processed,
1984 * then if no events sources are ready and @may_block is %TRUE, waiting
1985 * for a source to become ready, then dispatching the highest priority
1986 * events sources that are ready. Note that even when @may_block is %TRUE,
1987 * it is still possible for g_main_context_iteration() to return
1988 * %FALSE, since the the wait may be interrupted for other
1989 * reasons than an event source becoming ready.
1991 * Return value: %TRUE if events were dispatched.
1994 g_main_context_iteration (GMainContext *context, gboolean may_block)
1997 context = g_main_context_default();
1999 return g_main_context_iterate (context, may_block, TRUE);
2004 * @context: a #GMainContext (if %NULL, the default context will be used).
2005 * @is_running: set to TRUE to indicate that the loop is running. This
2006 * is not very important since calling g_main_run() will set this to
2009 * Create a new #GMainLoop structure
2014 g_main_loop_new (GMainContext *context,
2015 gboolean is_running)
2020 context = g_main_context_default();
2022 loop = g_new0 (GMainLoop, 1);
2023 loop->context = context;
2024 loop->is_running = is_running != FALSE;
2026 #ifdef G_THREADS_ENABLED
2027 if (g_thread_supported ())
2028 loop->mutex = g_mutex_new ();
2031 loop->sem_cond = NULL;
2032 #endif /* G_THREADS_ENABLED */
2039 * @loop: a #GMainLoop
2041 * Run a main loop until g_main_quit() is called on the loop.
2042 * If this is called for the thread of the loop's #GMainContext,
2043 * it will process events from the loop, otherwise it will
2047 g_main_loop_run (GMainLoop *loop)
2049 g_return_if_fail (loop != NULL);
2051 #ifdef G_THREADS_ENABLED
2052 if (loop->context->thread != g_thread_self ())
2056 if (!g_thread_supported ())
2058 g_warning ("g_main_loop_run() was called from second thread but"
2059 "g_thread_init() was never called.");
2063 if (!loop->sem_cond)
2064 loop->sem_cond = g_cond_new ();
2066 if (!loop->is_running)
2067 loop->is_running = TRUE;
2069 while (loop->is_running)
2070 g_cond_wait (loop->sem_cond, loop->mutex);
2076 #endif /* G_THREADS_ENABLED */
2078 LOCK_CONTEXT (loop->context);
2079 if (loop->context->in_check_or_prepare)
2081 g_warning ("g_main_run(): called recursively from within a source's check() or "
2082 "prepare() member, iteration not possible.");
2085 UNLOCK_CONTEXT (loop->context);
2089 loop->is_running = TRUE;
2090 while (loop->is_running)
2093 g_main_context_iterate (loop->context, TRUE, TRUE);
2102 * @loop: a #GMainLoop
2104 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2105 * for the loop will return.
2108 g_main_loop_quit (GMainLoop *loop)
2110 g_return_if_fail (loop != NULL);
2113 loop->is_running = FALSE;
2116 g_cond_broadcast (loop->sem_cond);
2120 LOCK_CONTEXT (loop->context);
2122 g_main_context_wakeup (loop->context);
2123 UNLOCK_CONTEXT (loop->context);
2127 * g_main_loop_destroy:
2128 * @loop: a #GMainLoop
2130 * Destroy a #GMainLoop object and free all associated memory.
2131 * The loop must not currently be running via g_main_run().
2134 g_main_loop_destroy (GMainLoop *loop)
2136 g_return_if_fail (loop != NULL);
2137 g_return_if_fail (!loop->is_running);
2139 #ifdef G_THREADS_ENABLED
2140 g_mutex_free (loop->mutex);
2142 g_cond_free (loop->sem_cond);
2143 #endif /* G_THREADS_ENABLED */
2149 * g_main_loop_is_running:
2150 * @loop: a #GMainLoop.
2152 * Check to see if the main loop is currently being run via g_main_run()
2154 * Return value: %TRUE if the mainloop is currently being run.
2157 g_main_loop_is_running (GMainLoop *loop)
2161 g_return_val_if_fail (loop != NULL, FALSE);
2164 result = loop->is_running;
2170 /* HOLDS: context's lock */
2172 g_main_context_poll (GMainContext *context,
2178 #ifdef G_MAIN_POLL_DEBUG
2184 GPollFunc poll_func;
2186 if (n_fds || timeout != 0)
2188 #ifdef G_MAIN_POLL_DEBUG
2189 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2190 poll_timer = g_timer_new ();
2193 LOCK_CONTEXT (context);
2195 poll_func = context->poll_func;
2197 UNLOCK_CONTEXT (context);
2198 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2199 g_warning ("poll(2) failed due to: %s.",
2200 g_strerror (errno));
2202 #ifdef G_MAIN_POLL_DEBUG
2203 LOCK_CONTEXT (context);
2205 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2208 g_timer_elapsed (poll_timer, NULL));
2209 g_timer_destroy (poll_timer);
2210 pollrec = context->poll_records;
2214 if (pollrec->fd->events)
2218 g_print (" [%d:", fds[i].fd);
2219 if (fds[i].revents & G_IO_IN)
2221 if (fds[i].revents & G_IO_OUT)
2223 if (fds[i].revents & G_IO_PRI)
2225 if (fds[i].revents & G_IO_ERR)
2227 if (fds[i].revents & G_IO_HUP)
2229 if (fds[i].revents & G_IO_NVAL)
2235 pollrec = pollrec->next;
2239 UNLOCK_CONTEXT (context);
2241 } /* if (n_fds || timeout != 0) */
2245 * g_main_context_add_poll:
2246 * @context: a #GMainContext (or %NULL for the default context)
2247 * @fd: a #GPollFD structure holding information about a file
2248 * descriptor to watch.
2249 * @priority: the priority for this file descriptor which should be
2250 * the same as the priority used for g_source_attach() to ensure that the
2251 * file descriptor is polled whenever the results may be needed.
2253 * Add a file descriptor to the set of file descriptors polled * for
2254 * this context. This will very seldom be used directly. Instead
2255 * a typical event source will use g_source_add_poll() instead.
2258 g_main_context_add_poll (GMainContext *context,
2263 context = g_main_context_default ();
2265 LOCK_CONTEXT (context);
2266 g_main_context_add_poll_unlocked (context, priority, fd);
2267 UNLOCK_CONTEXT (context);
2270 /* HOLDS: main_loop_lock */
2272 g_main_context_add_poll_unlocked (GMainContext *context,
2276 GPollRec *lastrec, *pollrec, *newrec;
2278 if (!context->poll_chunk)
2279 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2281 if (context->poll_free_list)
2283 newrec = context->poll_free_list;
2284 context->poll_free_list = newrec->next;
2287 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2289 /* This file descriptor may be checked before we ever poll */
2292 newrec->priority = priority;
2295 pollrec = context->poll_records;
2296 while (pollrec && priority >= pollrec->priority)
2299 pollrec = pollrec->next;
2303 lastrec->next = newrec;
2305 context->poll_records = newrec;
2307 newrec->next = pollrec;
2309 context->n_poll_records++;
2310 if (context->cached_poll_array &&
2311 context->cached_poll_array_size < context->n_poll_records)
2313 g_free (context->cached_poll_array);
2314 context->cached_poll_array = NULL;
2317 #ifdef G_THREADS_ENABLED
2318 context->poll_changed = TRUE;
2320 /* Now wake up the main loop if it is waiting in the poll() */
2321 g_main_context_wakeup (context);
2326 * g_main_context_remove_poll:
2327 * @context:a #GMainContext
2328 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2330 * Remove file descriptor from the set of file descriptors to be
2331 * polled for a particular context.
2334 g_main_context_remove_poll (GMainContext *context,
2338 context = g_main_context_default ();
2340 LOCK_CONTEXT (context);
2342 g_main_context_remove_poll_unlocked (context, fd);
2344 UNLOCK_CONTEXT (context);
2348 g_main_context_remove_poll_unlocked (GMainContext *context,
2351 GPollRec *pollrec, *lastrec;
2354 pollrec = context->poll_records;
2358 if (pollrec->fd == fd)
2360 if (lastrec != NULL)
2361 lastrec->next = pollrec->next;
2363 context->poll_records = pollrec->next;
2365 #ifdef ENABLE_GC_FRIENDLY
2367 #endif /* ENABLE_GC_FRIENDLY */
2369 pollrec->next = context->poll_free_list;
2370 context->poll_free_list = pollrec;
2372 context->n_poll_records--;
2376 pollrec = pollrec->next;
2379 #ifdef G_THREADS_ENABLED
2380 context->poll_changed = TRUE;
2382 /* Now wake up the main loop if it is waiting in the poll() */
2383 g_main_context_wakeup (context);
2388 * g_source_get_current_time:
2389 * @source: a #GSource
2390 * @timeval: #GTimeVal structure in which to store current time.
2392 * Gets the "current time" to be used when checking
2393 * this source. The advantage of calling this function over
2394 * calling g_get_current_time() directly is that when
2395 * checking multiple sources, GLib can cache a single value
2396 * instead of having to repeatedly get the system time.
2399 g_source_get_current_time (GSource *source,
2402 GMainContext *context;
2404 g_return_if_fail (source->context != NULL);
2406 context = source->context;
2408 LOCK_CONTEXT (context);
2410 if (!context->time_is_current)
2412 g_get_current_time (&context->current_time);
2413 context->time_is_current = TRUE;
2416 *timeval = context->current_time;
2418 UNLOCK_CONTEXT (context);
2422 * g_main_context_set_poll_func:
2423 * @context: a #GMainContext
2424 * @func: the function to call to poll all file descriptors
2426 * Sets the function to use to handle polling of file descriptors. It
2427 * will be used instead of the poll() system call (or GLib's
2428 * replacement function, which is used where poll() isn't available).
2430 * This function could possibly be used to integrate the GLib event
2431 * loop with an external event loop.
2434 g_main_context_set_poll_func (GMainContext *context,
2438 context = g_main_context_default ();
2440 LOCK_CONTEXT (context);
2443 context->poll_func = func;
2447 context->poll_func = (GPollFunc) poll;
2449 context->poll_func = (GPollFunc) g_poll;
2453 UNLOCK_CONTEXT (context);
2459 * g_main_context_get_poll_func:
2460 * @context: a #GMainContext
2462 * Gets the poll function set by g_main_context_set_poll_func()
2464 * Return value: the poll function
2467 g_main_context_get_poll_func (GMainContext *context)
2472 context = g_main_context_default ();
2474 LOCK_CONTEXT (context);
2475 result = context->poll_func;
2476 UNLOCK_CONTEXT (context);
2481 /* HOLDS: context's lock */
2482 /* Wake the main loop up from a poll() */
2484 g_main_context_wakeup (GMainContext *context)
2486 #ifdef G_THREADS_ENABLED
2487 if (g_thread_supported() && context->poll_waiting)
2489 context->poll_waiting = FALSE;
2491 write (context->wake_up_pipe[1], "A", 1);
2493 ReleaseSemaphore (context->context->wake_up_semaphore, 1, NULL);
2502 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2503 GTimeVal *current_time)
2505 guint seconds = timeout_source->interval / 1000;
2506 guint msecs = timeout_source->interval - seconds * 1000;
2508 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2509 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2510 if (timeout_source->expiration.tv_usec >= 1000000)
2512 timeout_source->expiration.tv_usec -= 1000000;
2513 timeout_source->expiration.tv_sec++;
2518 g_timeout_prepare (GSource *source,
2522 GTimeVal current_time;
2524 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2526 g_source_get_current_time (source, ¤t_time);
2528 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2529 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2533 else if (msec > timeout_source->interval)
2535 /* The system time has been set backwards, so we
2536 * reset the expiration time to now + timeout_source->interval;
2537 * this at least avoids hanging for long periods of time.
2539 g_timeout_set_expiration (timeout_source, ¤t_time);
2540 msec = timeout_source->interval;
2549 g_timeout_check (GSource *source)
2551 GTimeVal current_time;
2552 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2554 g_source_get_current_time (source, ¤t_time);
2556 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2557 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2558 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2562 g_timeout_dispatch (GSource *source,
2563 GSourceFunc callback,
2566 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2570 g_warning ("Timeout source dispatched without callback\n"
2571 "You must call g_source_set_callback().");
2575 if (callback (user_data))
2577 GTimeVal current_time;
2579 g_source_get_current_time (source, ¤t_time);
2580 g_timeout_set_expiration (timeout_source, ¤t_time);
2589 * g_timeout_source_new:
2590 * @interval: the timeout interval in milliseconds.
2592 * Create a new timeout source.
2594 * The source will not initially be associated with any #GMainContext
2595 * and must be added to one with g_source_attach() before it will be
2598 * Return value: the newly create timeout source
2601 g_timeout_source_new (guint interval)
2603 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2604 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2605 GTimeVal current_time;
2607 timeout_source->interval = interval;
2609 g_get_current_time (¤t_time);
2610 g_timeout_set_expiration (timeout_source, ¤t_time);
2616 * g_timeout_add_full:
2617 * @priority: the priority of the idle source. Typically this will be in the
2618 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2619 * @interval: the time between calls to the function, in milliseconds
2620 * (1/1000ths of a second.)
2621 * @function: function to call
2622 * @data: data to pass to @function
2623 * @notify: function to call when the idle is removed, or %NULL
2625 * Sets a function to be called at regular intervals, with the given
2626 * priority. The function is called repeatedly until it returns
2627 * FALSE, at which point the timeout is automatically destroyed and
2628 * the function will not be called again. The @notify function is
2629 * called when the timeout is destroyed. The first call to the
2630 * function will be at the end of the first @interval.
2632 * Note that timeout functions may be delayed, due to the processing of other
2633 * event sources. Thus they should not be relied on for precise timing.
2634 * After each call to the timeout function, the time of the next
2635 * timeout is recalculated based on the current time and the given interval
2636 * (it does not try to 'catch up' time lost in delays).
2638 * Return value: the id of event source.
2641 g_timeout_add_full (gint priority,
2643 GSourceFunc function,
2645 GDestroyNotify notify)
2650 g_return_val_if_fail (function != NULL, 0);
2652 source = g_timeout_source_new (interval);
2654 if (priority != G_PRIORITY_DEFAULT)
2655 g_source_set_priority (source, priority);
2657 g_source_set_callback (source, function, data, notify);
2658 id = g_source_attach (source, NULL);
2659 g_source_unref (source);
2666 * @interval: the time between calls to the function, in milliseconds
2667 * (1/1000ths of a second.)
2668 * @function: function to call
2669 * @data: data to pass to @function
2671 * Sets a function to be called at regular intervals, with the default
2672 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2673 * until it returns FALSE, at which point the timeout is automatically
2674 * destroyed and the function will not be called again. The @notify
2675 * function is called when the timeout is destroyed. The first call
2676 * to the function will be at the end of the first @interval.
2678 * Note that timeout functions may be delayed, due to the processing of other
2679 * event sources. Thus they should not be relied on for precise timing.
2680 * After each call to the timeout function, the time of the next
2681 * timeout is recalculated based on the current time and the given interval
2682 * (it does not try to 'catch up' time lost in delays).
2684 * Return value: the id of event source.
2687 g_timeout_add (guint32 interval,
2688 GSourceFunc function,
2691 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2692 interval, function, data, NULL);
2695 /* Idle functions */
2698 g_idle_prepare (GSource *source,
2707 g_idle_check (GSource *source)
2713 g_idle_dispatch (GSource *source,
2714 GSourceFunc callback,
2719 g_warning ("Idle source dispatched without callback\n"
2720 "You must call g_source_set_callback().");
2724 return callback (user_data);
2728 * g_idle_source_new:
2730 * Create a new idle source.
2732 * The source will not initially be associated with any #GMainContext
2733 * and must be added to one with g_source_attach() before it will be
2736 * Return value: the newly created idle source
2739 g_idle_source_new (void)
2741 return g_source_new (&idle_funcs, sizeof (GSource));
2746 * @priority: the priority of the idle source. Typically this will be in the
2747 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2748 * @function: function to call
2749 * @data: data to pass to @function
2750 * @notify: function to call when the idle is removed, or %NULL
2752 * Adds a function to be called whenever there are no higher priority
2753 * events pending. If the function returns FALSE it is automatically
2754 * removed from the list of event sources and will not be called again.
2756 * Return value: the id of the event source.
2759 g_idle_add_full (gint priority,
2760 GSourceFunc function,
2762 GDestroyNotify notify)
2767 g_return_val_if_fail (function != NULL, 0);
2769 source = g_idle_source_new ();
2771 if (priority != G_PRIORITY_DEFAULT)
2772 g_source_set_priority (source, priority);
2774 g_source_set_callback (source, function, data, notify);
2775 id = g_source_attach (source, NULL);
2776 g_source_unref (source);
2783 * @function: function to call
2784 * @data: data to pass to @function.
2786 * Adds a function to be called whenever there are no higher priority
2787 * events pending to the default main loop. The function is given the
2788 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2789 * returns FALSE it is automatically removed from the list of event
2790 * sources and will not be called again.
2792 * Return value: the id of the event source.
2795 g_idle_add (GSourceFunc function,
2798 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2802 * g_idle_remove_by_data:
2803 * @data: the data for the idle source's callback.
2805 * Removes the idle function with the given data.
2807 * Return value: %TRUE if an idle source was found and removed.
2810 g_idle_remove_by_data (gpointer data)
2812 return g_source_remove_by_funcs_user_data (&idle_funcs, data);