1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
36 /* uncomment the next line to get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
40 #include <sys/types.h>
42 #ifdef HAVE_SYS_TIME_H
44 #endif /* HAVE_SYS_TIME_H */
45 #ifdef GLIB_HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
48 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
49 #endif /* GLIB_HAVE_SYS_POLL_H */
52 #endif /* HAVE_UNISTD_H */
58 #endif /* G_OS_WIN32 */
61 #include <net/socket.h>
62 #endif /* G_OS_BEOS */
66 typedef struct _GTimeoutSource GTimeoutSource;
67 typedef struct _GPollRec GPollRec;
68 typedef struct _GSourceCallback GSourceCallback;
72 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
73 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
78 #ifdef G_THREADS_ENABLED
79 /* The following lock is used for both the list of sources
80 * and the list of poll records
86 GPtrArray *pending_dispatches;
87 gint timeout; /* Timeout for current iteration */
91 gint in_check_or_prepare;
93 GPollRec *poll_records;
94 GPollRec *poll_free_list;
95 GMemChunk *poll_chunk;
97 GPollFD *cached_poll_array;
98 gint cached_poll_array_size;
100 #ifdef G_THREADS_ENABLED
102 /* this pipe is used to wake up the main loop when a source is added.
104 gint wake_up_pipe[2];
105 #else /* G_OS_WIN32 */
106 HANDLE wake_up_semaphore;
107 #endif /* G_OS_WIN32 */
110 gboolean poll_waiting;
112 /* Flag indicating whether the set of fd's changed during a poll */
113 gboolean poll_changed;
114 #endif /* G_THREADS_ENABLED */
118 GTimeVal current_time;
119 gboolean time_is_current;
122 struct _GSourceCallback
127 GDestroyNotify notify;
132 GMainContext *context;
135 #ifdef G_THREADS_ENABLED
138 #endif /* G_THREADS_ENABLED */
141 struct _GTimeoutSource
155 #ifdef G_THREADS_ENABLED
156 #define LOCK_CONTEXT(context) g_mutex_lock(context->mutex)
157 #define UNLOCK_CONTEXT(context) g_mutex_unlock(context->mutex)
158 #define LOCK_LOOP(loop) g_mutex_lock(loop->mutex)
159 #define UNLOCK_LOOP(loop) g_mutex_unlock(loop->mutex)
161 #define LOCK_CONTEXT(context) (void)0
162 #define UNLOCK_CONTEXT(context) (void)0
163 #define LOCK_LOOP(context) (void)0
164 #define UNLOCK_LOOP(context) (void)0
167 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
169 #define SOURCE_UNREF(source, context) \
171 if ((source)->ref_count > 1) \
172 (source)->ref_count--; \
174 g_source_unref_internal ((source), (context), TRUE); \
178 /* Forward declarations */
180 static void g_source_unref_internal (GSource *source,
181 GMainContext *context,
183 static void g_source_destroy_internal (GSource *source,
184 GMainContext *context,
186 static void g_main_context_poll (GMainContext *context,
191 static void g_main_context_add_poll_unlocked (GMainContext *context,
194 static void g_main_context_remove_poll_unlocked (GMainContext *context,
196 static void g_main_context_wakeup (GMainContext *context);
198 static gboolean g_timeout_prepare (GSource *source,
200 static gboolean g_timeout_check (GSource *source);
201 static gboolean g_timeout_dispatch (GSource *source,
202 GSourceFunc callback,
204 static gboolean g_idle_prepare (GSource *source,
206 static gboolean g_idle_check (GSource *source);
207 static gboolean g_idle_dispatch (GSource *source,
208 GSourceFunc callback,
211 G_LOCK_DEFINE_STATIC (main_loop);
212 static GMainContext *default_main_context;
214 static GSourceFuncs timeout_funcs =
222 static GSourceFuncs idle_funcs =
231 /* SunOS has poll, but doesn't provide a prototype. */
232 # if defined (sun) && !defined (__SVR4)
233 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
235 #else /* !HAVE_POLL */
240 g_poll (GPollFD *fds,
244 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
245 gboolean poll_msgs = FALSE;
252 for (f = fds; f < &fds[nfds]; ++f)
255 if (f->events & G_IO_IN)
257 if (f->fd == G_WIN32_MSG_HANDLE)
261 #ifdef G_MAIN_POLL_DEBUG
262 g_print ("g_poll: waiting for %#x\n", f->fd);
264 handles[nhandles++] = (HANDLE) f->fd;
274 /* Waiting for messages, and maybe events */
277 if (timeout == INFINITE)
279 /* Waiting just for messages, infinite timeout
280 * -> Use PeekMessage, then WaitMessage
282 #ifdef G_MAIN_POLL_DEBUG
283 g_print ("PeekMessage, then WaitMessage\n");
285 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
286 ready = WAIT_OBJECT_0;
287 else if (!WaitMessage ())
288 g_warning ("g_poll: WaitMessage failed");
289 ready = WAIT_OBJECT_0;
291 else if (timeout == 0)
293 /* Waiting just for messages, zero timeout
296 #ifdef G_MAIN_POLL_DEBUG
297 g_print ("PeekMessage\n");
299 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
300 ready = WAIT_OBJECT_0;
302 ready = WAIT_TIMEOUT;
306 /* Waiting just for messages, some timeout
307 * -> First try PeekMessage, then set a timer, wait for message,
308 * kill timer, use PeekMessage
310 #ifdef G_MAIN_POLL_DEBUG
311 g_print ("PeekMessage\n");
313 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
314 ready = WAIT_OBJECT_0;
315 else if ((timer = SetTimer (NULL, 0, timeout, NULL)) == 0)
316 g_warning ("g_poll: SetTimer failed");
319 #ifdef G_MAIN_POLL_DEBUG
320 g_print ("WaitMessage\n");
323 KillTimer (NULL, timer);
324 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
325 && msg.message != WM_TIMER)
326 ready = WAIT_OBJECT_0;
328 ready = WAIT_TIMEOUT;
334 /* Wait for either message or event
335 * -> Use MsgWaitForMultipleObjects
337 #ifdef G_MAIN_POLL_DEBUG
338 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
340 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
341 timeout, QS_ALLINPUT);
343 if (ready == WAIT_FAILED)
344 g_warning ("g_poll: MsgWaitForMultipleObjects failed");
347 else if (nhandles == 0)
349 /* Wait for nothing (huh?) */
354 /* Wait for just events
355 * -> Use WaitForMultipleObjects
357 #ifdef G_MAIN_POLL_DEBUG
358 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
360 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
361 if (ready == WAIT_FAILED)
362 g_warning ("g_poll: WaitForMultipleObjects failed");
365 for (f = fds; f < &fds[nfds]; ++f)
368 if (ready == WAIT_FAILED)
370 else if (ready == WAIT_TIMEOUT)
372 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
374 for (f = fds; f < &fds[nfds]; ++f)
377 if (f->events & G_IO_IN)
378 if (f->fd == G_WIN32_MSG_HANDLE)
379 f->revents |= G_IO_IN;
382 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
383 for (f = fds; f < &fds[nfds]; ++f)
385 if ((f->events & G_IO_IN)
386 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
388 f->revents |= G_IO_IN;
389 #ifdef G_MAIN_POLL_DEBUG
390 g_print ("g_poll: got event %#x\n", f->fd);
393 ResetEvent ((HANDLE) f->fd);
398 if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
399 return ready - WAIT_OBJECT_0 + 1;
404 #else /* !G_OS_WIN32 */
406 /* The following implementation of poll() comes from the GNU C Library.
407 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
410 #include <string.h> /* for bzero on BSD systems */
412 #ifdef HAVE_SYS_SELECT_H
413 #include <sys/select.h>
414 #endif /* HAVE_SYS_SELECT_H */
418 #endif /* G_OS_BEOS */
421 # define SELECT_MASK fd_set
422 #else /* !NO_FD_SET */
424 typedef long fd_mask;
427 # define SELECT_MASK void
429 # define SELECT_MASK int
430 # endif /* !_IBMR2 */
431 #endif /* !NO_FD_SET */
434 g_poll (GPollFD *fds,
439 SELECT_MASK rset, wset, xset;
448 for (f = fds; f < &fds[nfds]; ++f)
451 if (f->events & G_IO_IN)
452 FD_SET (f->fd, &rset);
453 if (f->events & G_IO_OUT)
454 FD_SET (f->fd, &wset);
455 if (f->events & G_IO_PRI)
456 FD_SET (f->fd, &xset);
457 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
461 tv.tv_sec = timeout / 1000;
462 tv.tv_usec = (timeout % 1000) * 1000;
464 ready = select (maxfd + 1, &rset, &wset, &xset,
465 timeout == -1 ? NULL : &tv);
467 for (f = fds; f < &fds[nfds]; ++f)
472 if (FD_ISSET (f->fd, &rset))
473 f->revents |= G_IO_IN;
474 if (FD_ISSET (f->fd, &wset))
475 f->revents |= G_IO_OUT;
476 if (FD_ISSET (f->fd, &xset))
477 f->revents |= G_IO_PRI;
484 #endif /* !G_OS_WIN32 */
486 #endif /* !HAVE_POLL */
488 /* Called to clean up when a thread terminates
491 g_main_context_destroy (GMainContext *context)
495 /* We need the lock here only because g_source_destroy expects
496 * to be able to unlock when destroying the source's data
498 LOCK_CONTEXT (context);
499 source = context->source_list;
502 GSource *next = source->next;
503 g_source_destroy_internal (source, context, TRUE);
506 UNLOCK_CONTEXT (context);
508 #ifdef G_THREADS_ENABLED
509 g_mutex_free (context->mutex);
512 g_ptr_array_free (context->pending_dispatches, TRUE);
513 g_free (context->cached_poll_array);
515 g_mem_chunk_destroy (context->poll_chunk);
517 #ifdef G_THREADS_ENABLED
518 if (g_thread_supported())
521 close (context->wake_up_pipe[0]);
522 close (context->wake_up_pipe[1]);
524 CloseHandle (context->wake_up_semaphore);
533 * g_main_context_get:
534 * @thread: a #GThread
536 * Retrieves the main loop context for a particular thread. This
537 * will create the main context for the thread if none previously
538 * existed. The context will exist until the thread terminates.
540 * Return value: the main loop context for @thread.
543 g_main_context_get (GThread *thread)
545 static GStaticPrivate private_key = G_STATIC_PRIVATE_INIT;
546 GMainContext *context;
548 g_return_val_if_fail (thread != NULL, NULL);
550 if (g_thread_supported ())
551 context = g_static_private_get_for_thread (&private_key, thread);
553 context = default_main_context;
557 context = g_new0 (GMainContext, 1);
559 #ifdef G_THREADS_ENABLED
560 if (g_thread_supported ())
561 context->mutex = g_mutex_new();
563 context->thread = thread;
566 context->next_id = 1;
568 context->source_list = NULL;
571 context->poll_func = (GPollFunc)poll;
573 context->poll_func = g_poll;
576 context->cached_poll_array = NULL;
577 context->cached_poll_array_size = 0;
579 context->pending_dispatches = g_ptr_array_new ();
581 context->time_is_current = FALSE;
583 #ifdef G_THREADS_ENABLED
584 if (g_thread_supported ())
587 if (pipe (context->wake_up_pipe) < 0)
588 g_error ("Cannot create pipe main loop wake-up: %s\n",
591 context->wake_up_rec.fd = context->wake_up_pipe[0];
592 context->wake_up_rec.events = G_IO_IN;
593 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
595 if ((context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
596 g_error ("Cannot create wake-up semaphore: %s", g_win32_error_message (GetLastError ()));
597 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
598 context->wake_up_rec.events = G_IO_IN;
599 #ifdef G_MAIN_POLL_DEBUG
600 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
602 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
607 if (g_thread_supported ())
608 g_static_private_set_for_thread (&private_key, thread,
610 (GDestroyNotify)g_main_context_destroy);
612 default_main_context = context;
619 * g_main_context_default:
621 * Return the default main context. This is the main context used
622 * for main loop functions when a main loop is not explicitly
625 * Return value: the default main context.
628 g_main_context_default (void)
634 if (!default_main_context)
635 default_main_context = g_main_context_get (g_thread_self ());
637 G_UNLOCK (main_loop);
639 return default_main_context;
642 /* Hooks for adding to the main loop */
646 * @source_funcs: structure containing functions that implement
647 * the sources behavior.
648 * @struct_size: size of the #GSource structure to create
650 * Create a new GSource structure. The size is specified to
651 * allow creating structures derived from GSource that contain
652 * additional data. The size passed in must be at least
655 * The source will not initially be associated with any #GMainContext
656 * and must be added to one with g_source_add() before it will be
659 * Return value: the newly create #GSource
662 g_source_new (GSourceFuncs *source_funcs,
667 g_return_val_if_fail (source_funcs != NULL, NULL);
668 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
670 source = (GSource*) g_malloc0 (struct_size);
672 source->source_funcs = source_funcs;
673 source->ref_count = 1;
675 source->priority = G_PRIORITY_DEFAULT;
677 source->flags = G_HOOK_FLAG_ACTIVE;
679 /* NULL/0 initialization for all other fields */
684 /* Holds context's lock
687 g_source_list_add (GSource *source,
688 GMainContext *context)
690 GSource *tmp_source, *last_source;
693 tmp_source = context->source_list;
694 while (tmp_source && tmp_source->priority <= source->priority)
696 last_source = tmp_source;
697 tmp_source = tmp_source->next;
700 source->next = tmp_source;
702 tmp_source->prev = source;
704 source->prev = last_source;
706 last_source->next = source;
708 context->source_list = source;
711 /* Holds context's lock
714 g_source_list_remove (GSource *source,
715 GMainContext *context)
718 source->prev->next = source->next;
720 context->source_list = source->next;
723 source->next->prev = source->prev;
731 * @source: a #GSource
732 * @context: a #GMainContext (if %NULL, the default context will be used)
734 * Adds a #GSource to a @context so that it will be executed within
737 * Return value: the ID for the source within the #GMainContext
740 g_source_attach (GSource *source,
741 GMainContext *context)
746 g_return_val_if_fail (source->context == NULL, 0);
747 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
750 context = g_main_context_default ();
752 LOCK_CONTEXT (context);
754 source->context = context;
755 result = source->id = context->next_id++;
758 g_source_list_add (source, context);
760 tmp_list = source->poll_fds;
763 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
764 tmp_list = tmp_list->next;
767 #ifdef G_THREADS_ENABLED
768 /* Now wake up the main loop if it is waiting in the poll() */
769 g_main_context_wakeup (context);
772 UNLOCK_CONTEXT (context);
778 g_source_destroy_internal (GSource *source,
779 GMainContext *context,
783 LOCK_CONTEXT (context);
785 if (!SOURCE_DESTROYED (source))
788 gpointer old_cb_data;
789 GSourceCallbackFuncs *old_cb_funcs;
791 source->flags &= ~G_HOOK_FLAG_ACTIVE;
793 old_cb_data = source->callback_data;
794 old_cb_funcs = source->callback_funcs;
796 source->callback_data = NULL;
797 source->callback_funcs = NULL;
801 UNLOCK_CONTEXT (context);
802 old_cb_funcs->unref (old_cb_data);
803 LOCK_CONTEXT (context);
806 tmp_list = source->poll_fds;
809 g_main_context_remove_poll_unlocked (context, tmp_list->data);
810 tmp_list = tmp_list->next;
813 g_source_unref_internal (source, context, TRUE);
817 UNLOCK_CONTEXT (context);
822 * @source: a #GSource
824 * Remove a source from its #GMainContext, if any, and mark it as
825 * destroyed. The source cannot be subsequently added to another
829 g_source_destroy (GSource *source)
831 GMainContext *context;
833 g_return_if_fail (source != NULL);
835 context = source->context;
838 g_source_destroy_internal (source, context, FALSE);
840 source->flags &= ~G_HOOK_FLAG_ACTIVE;
845 * @source: a #GSource
847 * Return the numeric ID for a particular source. The ID of a source
848 * is unique within a particular main loop context. The reverse
849 * mapping from ID to source is done by g_main_context_find_source_by_id().
851 * Return value: the ID for the source
854 g_source_get_id (GSource *source)
858 g_return_val_if_fail (source != NULL, 0);
859 g_return_val_if_fail (source->context != NULL, 0);
861 LOCK_CONTEXT (source->context);
863 UNLOCK_CONTEXT (source->context);
869 * g_source_get_context:
870 * @source: a #GSource
872 * Get the #GMainContext with which the source is associated.
873 * Calling this function on a destroyed source is an error.
875 * Return value: the #GMainContext with which the source is associated,
876 * or %NULL if the context has not yet been added
880 g_source_get_context (GSource *source)
882 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
884 return source->context;
888 * g_main_source_add_poll:
890 * @fd: a #GPollFD structure holding information about a file
891 * descriptor to watch.
893 * Add a file descriptor to the set of file descriptors polled * for
894 * this source. This is usually combined with g_source_new() to add an
895 * event source. The event source's check function will typically test
896 * the revents field in the #GPollFD struct and return %TRUE if events need
900 g_source_add_poll (GSource *source,
903 GMainContext *context;
905 g_return_if_fail (source != NULL);
906 g_return_if_fail (fd != NULL);
907 g_return_if_fail (!SOURCE_DESTROYED (source));
909 context = source->context;
912 LOCK_CONTEXT (context);
914 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
918 g_main_context_add_poll_unlocked (context, source->priority, fd);
919 UNLOCK_CONTEXT (context);
924 * g_source_set_callback_indirect:
925 * @source: the source
926 * @callback_data: pointer to callback data "object"
927 * @callback_funcs: functions for reference counting callback_data
928 * and getting the callback and data
930 * Set the callback function storing the data as a refcounted callback
931 * "object". This is used to implement g_source_set_callback_closure()
932 * and internally. Note that calling g_source_set_callback_indirect() assumes
933 * an initial reference count on @callback_data, and thus
934 * @callback_funcs->unref will eventually be called once more
935 * than @callback_funcs->ref.
938 g_source_set_callback_indirect (GSource *source,
939 gpointer callback_data,
940 GSourceCallbackFuncs *callback_funcs)
942 GMainContext *context;
943 gpointer old_cb_data;
944 GSourceCallbackFuncs *old_cb_funcs;
946 g_return_if_fail (source != NULL);
947 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
949 context = source->context;
952 LOCK_CONTEXT (context);
954 old_cb_data = source->callback_data;
955 old_cb_funcs = source->callback_funcs;
957 source->callback_data = callback_data;
958 source->callback_funcs = callback_funcs;
961 UNLOCK_CONTEXT (context);
964 old_cb_funcs->unref (old_cb_data);
968 g_source_callback_ref (gpointer cb_data)
970 GSourceCallback *callback = cb_data;
972 callback->ref_count++;
977 g_source_callback_unref (gpointer cb_data)
979 GSourceCallback *callback = cb_data;
981 callback->ref_count--;
982 if (callback->ref_count == 0)
984 if (callback->notify)
985 callback->notify (callback->data);
990 g_source_callback_get (gpointer cb_data,
994 GSourceCallback *callback = cb_data;
996 *func = callback->func;
997 *data = callback->data;
1000 static GSourceCallbackFuncs g_source_callback_funcs = {
1001 g_source_callback_ref,
1002 g_source_callback_unref,
1003 g_source_callback_get,
1007 * g_source_set_callback:
1008 * @source: the source
1009 * @func: a callback function
1010 * @data: the data to pass to callback function
1011 * @notify: a function to call when @data is no longer in use, or %NULL.
1013 * Set the callback function for a source.
1016 g_source_set_callback (GSource *source,
1019 GDestroyNotify notify)
1021 GSourceCallback *new_callback;
1023 g_return_if_fail (source != NULL);
1025 new_callback = g_new (GSourceCallback, 1);
1027 new_callback->func = func;
1028 new_callback->data = data;
1029 new_callback->notify = notify;
1031 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1035 * g_source_set_priority:
1036 * @source: a #GSource
1037 * @priority: the new priority.
1039 * Set the priority of a source. While the main loop is being
1040 * run, a source will
1043 g_source_set_priority (GSource *source,
1047 GMainContext *context;
1049 g_return_if_fail (source != NULL);
1051 context = source->context;
1054 LOCK_CONTEXT (context);
1056 source->priority = priority;
1060 source->next = NULL;
1061 source->prev = NULL;
1063 tmp_list = source->poll_fds;
1066 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1067 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1069 tmp_list = tmp_list->next;
1072 UNLOCK_CONTEXT (source->context);
1077 * g_source_get_priority:
1078 * @source: a #GSource
1080 * Gets the priority of a surce
1082 * Return value: the priority of the source
1085 g_source_get_priority (GSource *source)
1087 g_return_val_if_fail (source != NULL, 0);
1089 return source->priority;
1093 * g_source_set_can_recurse:
1094 * @source: a #GSource
1095 * @can_recurse: whether recursion is allowed for this source
1097 * Sets whether a source can be called recursively. If @can_recurse is
1098 * %TRUE, then while the source is being dispatched then this source
1099 * will be processed normally. Otherwise, all processing of this
1100 * source is blocked until the dispatch function returns.
1103 g_source_set_can_recurse (GSource *source,
1104 gboolean can_recurse)
1106 GMainContext *context;
1108 g_return_if_fail (source != NULL);
1110 context = source->context;
1113 LOCK_CONTEXT (context);
1116 source->flags |= G_SOURCE_CAN_RECURSE;
1118 source->flags &= ~G_SOURCE_CAN_RECURSE;
1121 UNLOCK_CONTEXT (context);
1125 * g_source_get_can_recurse:
1126 * @source: a #GSource
1128 * Checks whether a source is allowed to be called recursively.
1129 * see g_source_set_can_recurse.
1131 * Return value: whether recursion is allowed.
1134 g_source_get_can_recurse (GSource *source)
1136 g_return_val_if_fail (source != NULL, FALSE);
1138 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1143 * @source: a #GSource
1145 * Increases the reference count on a source by one.
1147 * Return value: @source
1150 g_source_ref (GSource *source)
1152 GMainContext *context;
1154 g_return_val_if_fail (source != NULL, NULL);
1156 context = source->context;
1159 LOCK_CONTEXT (context);
1161 source->ref_count++;
1164 UNLOCK_CONTEXT (context);
1169 /* g_source_unref() but possible to call within context lock
1172 g_source_unref_internal (GSource *source,
1173 GMainContext *context,
1176 gpointer cb_data = NULL;
1177 GSourceCallbackFuncs *cb_funcs = NULL;
1180 g_return_if_fail (source != NULL);
1182 if (!have_lock && context)
1183 LOCK_CONTEXT (context);
1185 source->ref_count--;
1186 if (source->ref_count == 0)
1188 if (context && !SOURCE_DESTROYED (source))
1190 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1191 source->ref_count++;
1194 g_source_list_remove (source, context);
1196 if (source->source_funcs->destroy)
1197 source->source_funcs->destroy (source);
1199 g_slist_free (source->poll_fds);
1200 source->poll_fds = NULL;
1204 if (!have_lock && context)
1205 UNLOCK_CONTEXT (context);
1210 UNLOCK_CONTEXT (context);
1212 cb_funcs->unref (cb_data);
1215 LOCK_CONTEXT (context);
1221 * @source: a #GSource
1223 * Decreases the reference count of a source by one. If the
1224 * resulting reference count is zero the source and associated
1225 * memory will be destroyed.
1228 g_source_unref (GSource *source)
1230 g_return_if_fail (source != NULL);
1232 g_source_unref_internal (source, source->context, FALSE);
1236 * g_main_context_find_source_by_id:
1237 * @context: a #GMainContext (if %NULL, the default context will be used)
1238 * @id: the source ID, as returned by g_source_get_id()
1240 * Finds a #GSource given a pair of context and ID
1242 * Return value: the #GSource if found, otherwise, %NULL
1245 g_main_context_find_source_by_id (GMainContext *context,
1250 g_return_val_if_fail (id > 0, FALSE);
1252 if (context == NULL)
1253 context = g_main_context_default ();
1255 LOCK_CONTEXT (context);
1257 source = context->source_list;
1260 if (!SOURCE_DESTROYED (source) &&
1263 source = source->next;
1266 UNLOCK_CONTEXT (context);
1272 * g_main_context_find_source_by_funcs_user_data:
1273 * @context: a #GMainContext (if %NULL, the default context will be used).
1274 * @funcs: the @source_funcs passed to g_source_new().
1275 * @user_data: the user data from the callback.
1277 * Finds a source with the given source functions and user data. If
1278 * multiple sources exist with the same source function and user data,
1279 * the first one found will be returned.
1281 * Return value: the source, if one was found, otherwise %NULL
1284 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1285 GSourceFuncs *funcs,
1290 g_return_val_if_fail (funcs != NULL, FALSE);
1292 if (context == NULL)
1293 context = g_main_context_default ();
1295 LOCK_CONTEXT (context);
1297 source = context->source_list;
1300 if (!SOURCE_DESTROYED (source) &&
1301 source->source_funcs == funcs &&
1302 source->callback_data == user_data)
1304 source = source->next;
1307 UNLOCK_CONTEXT (context);
1313 * g_main_context_find_source_by_user_data:
1314 * @context: a #GMainContext
1315 * @user_data: the user_data for the callback.
1317 * Finds a source with the given user data for the callback. If
1318 * multiple sources exist with the same user data, the first
1319 * one found will be returned.
1321 * Return value: the source, if one was found, otherwise %NULL
1324 g_main_context_find_source_by_user_data (GMainContext *context,
1329 if (context == NULL)
1330 context = g_main_context_default ();
1332 LOCK_CONTEXT (context);
1334 source = context->source_list;
1337 if (!SOURCE_DESTROYED (source) &&
1338 source->callback_data == user_data)
1340 source = source->next;
1343 UNLOCK_CONTEXT (context);
1350 * @tag: the id of the source to remove.
1352 * Removes the source with the given id from the default main
1353 * context. The id of a #GSource is given by g_source_get_id(),
1354 * or will be returned by the functions g_source_attach(),
1355 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1356 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1358 * See also g_source_destroy().
1360 * Return value: %TRUE if the source was found and removed.
1363 g_source_remove (guint tag)
1367 g_return_val_if_fail (tag > 0, FALSE);
1369 source = g_main_context_find_source_by_id (NULL, tag);
1371 g_source_destroy (source);
1373 return source != NULL;
1377 * g_source_remove_by_user_data:
1378 * @user_data: the user_data for the callback.
1380 * Removes a source from the default main loop context given the user
1381 * data for the callback. If multiple sources exist with the same user
1382 * data, only one will be destroyed.
1384 * Return value: %TRUE if a source was found and removed.
1387 g_source_remove_by_user_data (gpointer user_data)
1391 source = g_main_context_find_source_by_user_data (NULL, user_data);
1394 g_source_destroy (source);
1402 * g_source_remove_by_funcs_user_data:
1403 * @funcs: The @source_funcs passed to g_source_new()
1404 * @user_data: the user data for the callback
1406 * Removes a source from the default main loop context given the
1407 * source functions and user data. If multiple sources exist with the
1408 * same source functions and user data, only one will be destroyed.
1410 * Return value: %TRUE if a source was found and removed.
1413 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1418 g_return_val_if_fail (funcs != NULL, FALSE);
1420 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1423 g_source_destroy (source);
1431 * g_get_current_time:
1432 * @result: #GTimeVal structure in which to store current time.
1434 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1437 g_get_current_time (GTimeVal *result)
1442 g_return_if_fail (result != NULL);
1444 /*this is required on alpha, there the timeval structs are int's
1445 not longs and a cast only would fail horribly*/
1446 gettimeofday (&r, NULL);
1447 result->tv_sec = r.tv_sec;
1448 result->tv_usec = r.tv_usec;
1450 /* Avoid calling time() except for the first time.
1451 * GetTickCount() should be pretty fast and low-level?
1452 * I could also use ftime() but it seems unnecessarily overheady.
1454 static DWORD start_tick = 0;
1455 static time_t start_time;
1458 g_return_if_fail (result != NULL);
1460 if (start_tick == 0)
1462 start_tick = GetTickCount ();
1466 tick = GetTickCount ();
1468 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1469 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1473 /* Running the main loop */
1475 /* HOLDS: context's lock */
1477 g_main_dispatch (GMainContext *context)
1481 for (i = 0; i < context->pending_dispatches->len; i++)
1483 GSource *source = context->pending_dispatches->pdata[i];
1485 context->pending_dispatches->pdata[i] = NULL;
1488 source->flags &= ~G_SOURCE_READY;
1490 if (!SOURCE_DESTROYED (source))
1492 gboolean was_in_call;
1493 gpointer user_data = NULL;
1494 GSourceFunc callback = NULL;
1495 GSourceCallbackFuncs *cb_funcs;
1497 gboolean need_destroy;
1499 gboolean (*dispatch) (GSource *,
1503 dispatch = source->source_funcs->dispatch;
1504 cb_funcs = source->callback_funcs;
1505 cb_data = source->callback_data;
1508 cb_funcs->ref (cb_data);
1510 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1511 source->flags |= G_HOOK_FLAG_IN_CALL;
1513 UNLOCK_CONTEXT (context);
1516 cb_funcs->get (cb_data, &callback, &user_data);
1518 need_destroy = ! dispatch (source,
1521 LOCK_CONTEXT (context);
1524 cb_funcs->unref (cb_data);
1527 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1529 /* Note: this depends on the fact that we can't switch
1530 * sources from one main context to another
1532 if (need_destroy && !SOURCE_DESTROYED (source))
1534 g_assert (source->context == context);
1535 g_source_destroy_internal (source, context, TRUE);
1539 SOURCE_UNREF (source, context);
1542 g_ptr_array_set_size (context->pending_dispatches, 0);
1545 /* Holds context's lock */
1546 static inline GSource *
1547 next_valid_source (GMainContext *context,
1550 GSource *new_source = source ? source->next : context->source_list;
1554 if (!SOURCE_DESTROYED (new_source))
1556 new_source->ref_count++;
1560 new_source = new_source->next;
1564 SOURCE_UNREF (source, context);
1571 * g_main_context_prepare:
1572 * @context: a #GMainContext
1573 * @priority: location to store priority of highest priority
1574 * source already ready.
1576 * Prepares to poll sources within a main loop. The resulting information
1577 * for polling is determined by calling g_main_context_query ().
1579 * Return value: %TRUE if some source is ready to be dispatched
1583 g_main_context_prepare (GMainContext *context,
1587 gint current_priority = G_MAXINT;
1590 if (context == NULL)
1591 context = g_main_context_default ();
1593 LOCK_CONTEXT (context);
1595 context->time_is_current = FALSE;
1597 if (context->in_check_or_prepare)
1599 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1600 "prepare() member.");
1604 #ifdef G_THREADS_ENABLED
1605 if (context->poll_waiting)
1607 g_warning("g_main_context_prepare(): main loop already active in another thread");
1608 UNLOCK_CONTEXT (context);
1612 context->poll_waiting = TRUE;
1613 #endif /* G_THREADS_ENABLED */
1616 /* If recursing, finish up current dispatch, before starting over */
1617 if (context->pending_dispatches)
1620 g_main_dispatch (context, ¤t_time);
1622 UNLOCK_CONTEXT (context);
1627 /* If recursing, clear list of pending dispatches */
1628 g_ptr_array_set_size (context->pending_dispatches, 0);
1630 /* Prepare all sources */
1632 context->timeout = -1;
1634 source = next_valid_source (context, NULL);
1637 gint source_timeout = -1;
1639 if ((n_ready > 0) && (source->priority > current_priority))
1641 SOURCE_UNREF (source, context);
1644 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1647 if (!(source->flags & G_SOURCE_READY))
1650 gboolean (*prepare) (GSource *source,
1653 prepare = source->source_funcs->prepare;
1654 context->in_check_or_prepare++;
1655 UNLOCK_CONTEXT (context);
1657 result = (*prepare) (source, &source_timeout);
1659 LOCK_CONTEXT (context);
1660 context->in_check_or_prepare--;
1663 source->flags |= G_SOURCE_READY;
1666 if (source->flags & G_SOURCE_READY)
1669 current_priority = source->priority;
1670 context->timeout = 0;
1673 if (source_timeout >= 0)
1675 if (context->timeout < 0)
1676 context->timeout = source_timeout;
1678 context->timeout = MIN (context->timeout, source_timeout);
1682 source = next_valid_source (context, source);
1685 UNLOCK_CONTEXT (context);
1688 *priority = current_priority;
1690 return (n_ready > 0);
1694 * g_main_context_query:
1695 * @context: a #GMainContext
1696 * @max_priority: maximum priority source to check
1697 * @timeout: location to store timeout to be used in polling
1698 * @fds: location to store #GPollFD records that need to be polled.
1699 * @n_fds: length of @fds.
1701 * Determines information necessary to poll this main loop.
1706 g_main_context_query (GMainContext *context,
1715 LOCK_CONTEXT (context);
1717 pollrec = context->poll_records;
1719 while (pollrec && max_priority >= pollrec->priority)
1721 if (pollrec->fd->events)
1725 fds[n_poll].fd = pollrec->fd->fd;
1726 /* In direct contradiction to the Unix98 spec, IRIX runs into
1727 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1728 * flags in the events field of the pollfd while it should
1729 * just ignoring them. So we mask them out here.
1731 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1732 fds[n_poll].revents = 0;
1737 pollrec = pollrec->next;
1740 #ifdef G_THREADS_ENABLED
1741 context->poll_changed = FALSE;
1746 *timeout = context->timeout;
1748 context->time_is_current = FALSE;
1751 UNLOCK_CONTEXT (context);
1757 * g_main_context_check:
1758 * @context: a #GMainContext
1759 * @max_priority: the maximum numerical priority of sources to check
1760 * @fds: array of #GPollFD's that was passed to the last call to
1761 * g_main_context_query()
1762 * @n_fds: return value of g_main_context_query()
1764 * Pass the results of polling back to the main loop.
1766 * Return value: %TRUE if some sources are ready to be dispatched.
1769 g_main_context_check (GMainContext *context,
1779 LOCK_CONTEXT (context);
1781 if (context->in_check_or_prepare)
1783 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1784 "prepare() member.");
1788 #ifdef G_THREADS_ENABLED
1789 if (!context->poll_waiting)
1793 read (context->wake_up_pipe[0], &c, 1);
1797 context->poll_waiting = FALSE;
1799 /* If the set of poll file descriptors changed, bail out
1800 * and let the main loop rerun
1802 if (context->poll_changed)
1804 #endif /* G_THREADS_ENABLED */
1806 pollrec = context->poll_records;
1810 if (pollrec->fd->events)
1812 pollrec->fd->revents = fds[i].revents;
1815 pollrec = pollrec->next;
1818 source = next_valid_source (context, NULL);
1821 if ((n_ready > 0) && (source->priority > max_priority))
1823 SOURCE_UNREF (source, context);
1826 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1829 if (!(source->flags & G_SOURCE_READY))
1832 gboolean (*check) (GSource *source);
1834 check = source->source_funcs->check;
1836 context->in_check_or_prepare++;
1837 UNLOCK_CONTEXT (context);
1839 result = (*check) (source);
1841 LOCK_CONTEXT (context);
1842 context->in_check_or_prepare--;
1845 source->flags |= G_SOURCE_READY;
1848 if (source->flags & G_SOURCE_READY)
1850 source->ref_count++;
1851 g_ptr_array_add (context->pending_dispatches, source);
1857 source = next_valid_source (context, source);
1860 UNLOCK_CONTEXT (context);
1866 * g_main_context_dispatch:
1867 * @context: a #GMainContext
1869 * Dispatch all pending sources()
1872 g_main_context_dispatch (GMainContext *context)
1874 LOCK_CONTEXT (context);
1876 if (context->pending_dispatches->len > 0)
1878 g_main_dispatch (context);
1881 UNLOCK_CONTEXT (context);
1885 g_main_context_iterate (GMainContext *context,
1891 gboolean some_ready;
1892 gint nfds, new_nfds;
1895 some_ready = g_main_context_prepare (context, &max_priority);
1899 LOCK_CONTEXT (context);
1901 if (context->cached_poll_array)
1903 nfds = context->cached_poll_array_size;
1904 fds = context->cached_poll_array;
1905 context->cached_poll_array = NULL;
1909 nfds = context->cached_poll_array_size = context->n_poll_records;
1910 fds = g_new (GPollFD, nfds);
1913 UNLOCK_CONTEXT (context);
1915 new_nfds = g_main_context_query (context, max_priority,
1916 &timeout, fds, nfds);
1918 while (new_nfds > nfds);
1923 g_main_context_poll (context, timeout, max_priority,
1926 g_main_context_check (context,
1930 LOCK_CONTEXT (context);
1932 g_assert (!context->cached_poll_array);
1934 context->cached_poll_array = fds;
1935 context->cached_poll_array_size = nfds;
1937 UNLOCK_CONTEXT (context);
1940 g_main_context_dispatch (context);
1946 * g_main_context_pending:
1947 * @context: a #GMainContext (if %NULL, the default context will be used)
1949 * Check if any sources have pending events for the given context.
1951 * Return value: %TRUE if events are pending.
1954 g_main_context_pending (GMainContext *context)
1957 context = g_main_context_default();
1959 return g_main_context_iterate (context, FALSE, FALSE);
1963 * g_main_context_iteration:
1964 * @context: a #GMainContext (if %NULL, the default context will be used)
1965 * @may_block: whether the call may block.
1967 * Run a single iteration for the given main loop. This involves
1968 * checking to see if any event sources are ready to be processed,
1969 * then if no events sources are ready and @may_block is %TRUE, waiting
1970 * for a source to become ready, then dispatching the highest priority
1971 * events sources that are ready. Note that even when @may_block is %TRUE,
1972 * it is still possible for g_main_context_iteration() to return
1973 * %FALSE, since the the wait may be interrupted for other
1974 * reasons than an event source becoming ready.
1976 * Return value: %TRUE if events were dispatched.
1979 g_main_context_iteration (GMainContext *context, gboolean may_block)
1982 context = g_main_context_default();
1984 return g_main_context_iterate (context, may_block, TRUE);
1989 * @context: a #GMainContext (if %NULL, the default context will be used).
1990 * @is_running: set to TRUE to indicate that the loop is running. This
1991 * is not very important since calling g_main_run() will set this to
1994 * Create a new #GMainLoop structure
1999 g_main_loop_new (GMainContext *context,
2000 gboolean is_running)
2005 context = g_main_context_default();
2007 loop = g_new0 (GMainLoop, 1);
2008 loop->context = context;
2009 loop->is_running = is_running != FALSE;
2011 #ifdef G_THREADS_ENABLED
2012 if (g_thread_supported ())
2013 loop->mutex = g_mutex_new ();
2016 loop->sem_cond = NULL;
2017 #endif /* G_THREADS_ENABLED */
2024 * @loop: a #GMainLoop
2026 * Run a main loop until g_main_quit() is called on the loop.
2027 * If this is called for the thread of the loop's #GMainContext,
2028 * it will process events from the loop, otherwise it will
2032 g_main_loop_run (GMainLoop *loop)
2034 g_return_if_fail (loop != NULL);
2036 #ifdef G_THREADS_ENABLED
2037 if (loop->context->thread != g_thread_self ())
2041 if (!g_thread_supported ())
2043 g_warning ("g_main_loop_run() was called from second thread but"
2044 "g_thread_init() was never called.");
2048 if (!loop->sem_cond)
2049 loop->sem_cond = g_cond_new ();
2051 if (!loop->is_running)
2052 loop->is_running = TRUE;
2054 while (loop->is_running)
2055 g_cond_wait (loop->sem_cond, loop->mutex);
2061 #endif /* G_THREADS_ENABLED */
2063 LOCK_CONTEXT (loop->context);
2064 if (loop->context->in_check_or_prepare)
2066 g_warning ("g_main_run(): called recursively from within a source's check() or "
2067 "prepare() member, iteration not possible.");
2070 UNLOCK_CONTEXT (loop->context);
2074 loop->is_running = TRUE;
2075 while (loop->is_running)
2078 g_main_context_iterate (loop->context, TRUE, TRUE);
2087 * @loop: a #GMainLoop
2089 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2090 * for the loop will return.
2093 g_main_loop_quit (GMainLoop *loop)
2095 g_return_if_fail (loop != NULL);
2098 loop->is_running = FALSE;
2100 #ifdef G_THREADS_ENABLED
2102 g_cond_broadcast (loop->sem_cond);
2107 LOCK_CONTEXT (loop->context);
2109 g_main_context_wakeup (loop->context);
2110 UNLOCK_CONTEXT (loop->context);
2114 * g_main_loop_destroy:
2115 * @loop: a #GMainLoop
2117 * Destroy a #GMainLoop object and free all associated memory.
2118 * The loop must not currently be running via g_main_run().
2121 g_main_loop_destroy (GMainLoop *loop)
2123 g_return_if_fail (loop != NULL);
2124 g_return_if_fail (!loop->is_running);
2126 #ifdef G_THREADS_ENABLED
2127 g_mutex_free (loop->mutex);
2129 g_cond_free (loop->sem_cond);
2130 #endif /* G_THREADS_ENABLED */
2136 * g_main_loop_is_running:
2137 * @loop: a #GMainLoop.
2139 * Check to see if the main loop is currently being run via g_main_run()
2141 * Return value: %TRUE if the mainloop is currently being run.
2144 g_main_loop_is_running (GMainLoop *loop)
2148 g_return_val_if_fail (loop != NULL, FALSE);
2151 result = loop->is_running;
2157 /* HOLDS: context's lock */
2159 g_main_context_poll (GMainContext *context,
2165 #ifdef G_MAIN_POLL_DEBUG
2171 GPollFunc poll_func;
2173 if (n_fds || timeout != 0)
2175 #ifdef G_MAIN_POLL_DEBUG
2176 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2177 poll_timer = g_timer_new ();
2180 LOCK_CONTEXT (context);
2182 poll_func = context->poll_func;
2184 UNLOCK_CONTEXT (context);
2185 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2186 g_warning ("poll(2) failed due to: %s.",
2187 g_strerror (errno));
2189 #ifdef G_MAIN_POLL_DEBUG
2190 LOCK_CONTEXT (context);
2192 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2195 g_timer_elapsed (poll_timer, NULL));
2196 g_timer_destroy (poll_timer);
2197 pollrec = context->poll_records;
2201 if (pollrec->fd->events)
2205 g_print (" [%d:", fds[i].fd);
2206 if (fds[i].revents & G_IO_IN)
2208 if (fds[i].revents & G_IO_OUT)
2210 if (fds[i].revents & G_IO_PRI)
2212 if (fds[i].revents & G_IO_ERR)
2214 if (fds[i].revents & G_IO_HUP)
2216 if (fds[i].revents & G_IO_NVAL)
2222 pollrec = pollrec->next;
2226 UNLOCK_CONTEXT (context);
2228 } /* if (n_fds || timeout != 0) */
2232 * g_main_context_add_poll:
2233 * @context: a #GMainContext (or %NULL for the default context)
2234 * @fd: a #GPollFD structure holding information about a file
2235 * descriptor to watch.
2236 * @priority: the priority for this file descriptor which should be
2237 * the same as the priority used for g_source_attach() to ensure that the
2238 * file descriptor is polled whenever the results may be needed.
2240 * Add a file descriptor to the set of file descriptors polled * for
2241 * this context. This will very seldom be used directly. Instead
2242 * a typical event source will use g_source_add_poll() instead.
2245 g_main_context_add_poll (GMainContext *context,
2250 context = g_main_context_default ();
2252 LOCK_CONTEXT (context);
2253 g_main_context_add_poll_unlocked (context, priority, fd);
2254 UNLOCK_CONTEXT (context);
2257 /* HOLDS: main_loop_lock */
2259 g_main_context_add_poll_unlocked (GMainContext *context,
2263 GPollRec *lastrec, *pollrec, *newrec;
2265 if (!context->poll_chunk)
2266 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2268 if (context->poll_free_list)
2270 newrec = context->poll_free_list;
2271 context->poll_free_list = newrec->next;
2274 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2276 /* This file descriptor may be checked before we ever poll */
2279 newrec->priority = priority;
2282 pollrec = context->poll_records;
2283 while (pollrec && priority >= pollrec->priority)
2286 pollrec = pollrec->next;
2290 lastrec->next = newrec;
2292 context->poll_records = newrec;
2294 newrec->next = pollrec;
2296 context->n_poll_records++;
2297 if (context->cached_poll_array &&
2298 context->cached_poll_array_size < context->n_poll_records)
2300 g_free (context->cached_poll_array);
2301 context->cached_poll_array = NULL;
2304 #ifdef G_THREADS_ENABLED
2305 context->poll_changed = TRUE;
2307 /* Now wake up the main loop if it is waiting in the poll() */
2308 g_main_context_wakeup (context);
2313 * g_main_context_remove_poll:
2314 * @context:a #GMainContext
2315 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2317 * Remove file descriptor from the set of file descriptors to be
2318 * polled for a particular context.
2321 g_main_context_remove_poll (GMainContext *context,
2325 context = g_main_context_default ();
2327 LOCK_CONTEXT (context);
2329 g_main_context_remove_poll_unlocked (context, fd);
2331 UNLOCK_CONTEXT (context);
2335 g_main_context_remove_poll_unlocked (GMainContext *context,
2338 GPollRec *pollrec, *lastrec;
2341 pollrec = context->poll_records;
2345 if (pollrec->fd == fd)
2347 if (lastrec != NULL)
2348 lastrec->next = pollrec->next;
2350 context->poll_records = pollrec->next;
2352 #ifdef ENABLE_GC_FRIENDLY
2354 #endif /* ENABLE_GC_FRIENDLY */
2356 pollrec->next = context->poll_free_list;
2357 context->poll_free_list = pollrec;
2359 context->n_poll_records--;
2363 pollrec = pollrec->next;
2366 #ifdef G_THREADS_ENABLED
2367 context->poll_changed = TRUE;
2369 /* Now wake up the main loop if it is waiting in the poll() */
2370 g_main_context_wakeup (context);
2375 * g_source_get_current_time:
2376 * @source: a #GSource
2377 * @timeval: #GTimeVal structure in which to store current time.
2379 * Gets the "current time" to be used when checking
2380 * this source. The advantage of calling this function over
2381 * calling g_get_current_time() directly is that when
2382 * checking multiple sources, GLib can cache a single value
2383 * instead of having to repeatedly get the system time.
2386 g_source_get_current_time (GSource *source,
2389 GMainContext *context;
2391 g_return_if_fail (source->context != NULL);
2393 context = source->context;
2395 LOCK_CONTEXT (context);
2397 if (!context->time_is_current)
2399 g_get_current_time (&context->current_time);
2400 context->time_is_current = TRUE;
2403 *timeval = context->current_time;
2405 UNLOCK_CONTEXT (context);
2409 * g_main_context_set_poll_func:
2410 * @context: a #GMainContext
2411 * @func: the function to call to poll all file descriptors
2413 * Sets the function to use to handle polling of file descriptors. It
2414 * will be used instead of the poll() system call (or GLib's
2415 * replacement function, which is used where poll() isn't available).
2417 * This function could possibly be used to integrate the GLib event
2418 * loop with an external event loop.
2421 g_main_context_set_poll_func (GMainContext *context,
2425 context = g_main_context_default ();
2427 LOCK_CONTEXT (context);
2430 context->poll_func = func;
2434 context->poll_func = (GPollFunc) poll;
2436 context->poll_func = (GPollFunc) g_poll;
2440 UNLOCK_CONTEXT (context);
2444 * g_main_context_get_poll_func:
2445 * @context: a #GMainContext
2447 * Gets the poll function set by g_main_context_set_poll_func()
2449 * Return value: the poll function
2452 g_main_context_get_poll_func (GMainContext *context)
2457 context = g_main_context_default ();
2459 LOCK_CONTEXT (context);
2460 result = context->poll_func;
2461 UNLOCK_CONTEXT (context);
2466 /* HOLDS: context's lock */
2467 /* Wake the main loop up from a poll() */
2469 g_main_context_wakeup (GMainContext *context)
2471 #ifdef G_THREADS_ENABLED
2472 if (g_thread_supported() && context->poll_waiting)
2474 context->poll_waiting = FALSE;
2476 write (context->wake_up_pipe[1], "A", 1);
2478 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2487 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2488 GTimeVal *current_time)
2490 guint seconds = timeout_source->interval / 1000;
2491 guint msecs = timeout_source->interval - seconds * 1000;
2493 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2494 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2495 if (timeout_source->expiration.tv_usec >= 1000000)
2497 timeout_source->expiration.tv_usec -= 1000000;
2498 timeout_source->expiration.tv_sec++;
2503 g_timeout_prepare (GSource *source,
2507 GTimeVal current_time;
2509 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2511 g_source_get_current_time (source, ¤t_time);
2513 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2514 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2518 else if (msec > timeout_source->interval)
2520 /* The system time has been set backwards, so we
2521 * reset the expiration time to now + timeout_source->interval;
2522 * this at least avoids hanging for long periods of time.
2524 g_timeout_set_expiration (timeout_source, ¤t_time);
2525 msec = timeout_source->interval;
2534 g_timeout_check (GSource *source)
2536 GTimeVal current_time;
2537 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2539 g_source_get_current_time (source, ¤t_time);
2541 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2542 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2543 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2547 g_timeout_dispatch (GSource *source,
2548 GSourceFunc callback,
2551 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2555 g_warning ("Timeout source dispatched without callback\n"
2556 "You must call g_source_set_callback().");
2560 if (callback (user_data))
2562 GTimeVal current_time;
2564 g_source_get_current_time (source, ¤t_time);
2565 g_timeout_set_expiration (timeout_source, ¤t_time);
2574 * g_timeout_source_new:
2575 * @interval: the timeout interval in milliseconds.
2577 * Create a new timeout source.
2579 * The source will not initially be associated with any #GMainContext
2580 * and must be added to one with g_source_attach() before it will be
2583 * Return value: the newly create timeout source
2586 g_timeout_source_new (guint interval)
2588 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2589 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2590 GTimeVal current_time;
2592 timeout_source->interval = interval;
2594 g_get_current_time (¤t_time);
2595 g_timeout_set_expiration (timeout_source, ¤t_time);
2601 * g_timeout_add_full:
2602 * @priority: the priority of the idle source. Typically this will be in the
2603 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2604 * @interval: the time between calls to the function, in milliseconds
2605 * (1/1000ths of a second.)
2606 * @function: function to call
2607 * @data: data to pass to @function
2608 * @notify: function to call when the idle is removed, or %NULL
2610 * Sets a function to be called at regular intervals, with the given
2611 * priority. The function is called repeatedly until it returns
2612 * FALSE, at which point the timeout is automatically destroyed and
2613 * the function will not be called again. The @notify function is
2614 * called when the timeout is destroyed. The first call to the
2615 * function will be at the end of the first @interval.
2617 * Note that timeout functions may be delayed, due to the processing of other
2618 * event sources. Thus they should not be relied on for precise timing.
2619 * After each call to the timeout function, the time of the next
2620 * timeout is recalculated based on the current time and the given interval
2621 * (it does not try to 'catch up' time lost in delays).
2623 * Return value: the id of event source.
2626 g_timeout_add_full (gint priority,
2628 GSourceFunc function,
2630 GDestroyNotify notify)
2635 g_return_val_if_fail (function != NULL, 0);
2637 source = g_timeout_source_new (interval);
2639 if (priority != G_PRIORITY_DEFAULT)
2640 g_source_set_priority (source, priority);
2642 g_source_set_callback (source, function, data, notify);
2643 id = g_source_attach (source, NULL);
2644 g_source_unref (source);
2651 * @interval: the time between calls to the function, in milliseconds
2652 * (1/1000ths of a second.)
2653 * @function: function to call
2654 * @data: data to pass to @function
2656 * Sets a function to be called at regular intervals, with the default
2657 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2658 * until it returns FALSE, at which point the timeout is automatically
2659 * destroyed and the function will not be called again. The @notify
2660 * function is called when the timeout is destroyed. The first call
2661 * to the function will be at the end of the first @interval.
2663 * Note that timeout functions may be delayed, due to the processing of other
2664 * event sources. Thus they should not be relied on for precise timing.
2665 * After each call to the timeout function, the time of the next
2666 * timeout is recalculated based on the current time and the given interval
2667 * (it does not try to 'catch up' time lost in delays).
2669 * Return value: the id of event source.
2672 g_timeout_add (guint32 interval,
2673 GSourceFunc function,
2676 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2677 interval, function, data, NULL);
2680 /* Idle functions */
2683 g_idle_prepare (GSource *source,
2692 g_idle_check (GSource *source)
2698 g_idle_dispatch (GSource *source,
2699 GSourceFunc callback,
2704 g_warning ("Idle source dispatched without callback\n"
2705 "You must call g_source_set_callback().");
2709 return callback (user_data);
2713 * g_idle_source_new:
2715 * Create a new idle source.
2717 * The source will not initially be associated with any #GMainContext
2718 * and must be added to one with g_source_attach() before it will be
2721 * Return value: the newly created idle source
2724 g_idle_source_new (void)
2726 return g_source_new (&idle_funcs, sizeof (GSource));
2731 * @priority: the priority of the idle source. Typically this will be in the
2732 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2733 * @function: function to call
2734 * @data: data to pass to @function
2735 * @notify: function to call when the idle is removed, or %NULL
2737 * Adds a function to be called whenever there are no higher priority
2738 * events pending. If the function returns FALSE it is automatically
2739 * removed from the list of event sources and will not be called again.
2741 * Return value: the id of the event source.
2744 g_idle_add_full (gint priority,
2745 GSourceFunc function,
2747 GDestroyNotify notify)
2752 g_return_val_if_fail (function != NULL, 0);
2754 source = g_idle_source_new ();
2756 if (priority != G_PRIORITY_DEFAULT)
2757 g_source_set_priority (source, priority);
2759 g_source_set_callback (source, function, data, notify);
2760 id = g_source_attach (source, NULL);
2761 g_source_unref (source);
2768 * @function: function to call
2769 * @data: data to pass to @function.
2771 * Adds a function to be called whenever there are no higher priority
2772 * events pending to the default main loop. The function is given the
2773 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2774 * returns FALSE it is automatically removed from the list of event
2775 * sources and will not be called again.
2777 * Return value: the id of the event source.
2780 g_idle_add (GSourceFunc function,
2783 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2787 * g_idle_remove_by_data:
2788 * @data: the data for the idle source's callback.
2790 * Removes the idle function with the given data.
2792 * Return value: %TRUE if an idle source was found and removed.
2795 g_idle_remove_by_data (gpointer data)
2797 return g_source_remove_by_funcs_user_data (&idle_funcs, data);