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 old_cb_data = NULL;
1177 GSourceCallbackFuncs *old_cb_funcs = NULL;
1179 g_return_if_fail (source != NULL);
1181 if (!have_lock && context)
1182 LOCK_CONTEXT (context);
1184 source->ref_count--;
1185 if (source->ref_count == 0)
1187 old_cb_data = source->callback_data;
1188 old_cb_funcs = source->callback_funcs;
1190 source->callback_data = NULL;
1191 source->callback_funcs = NULL;
1193 if (context && !SOURCE_DESTROYED (source))
1195 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1196 source->ref_count++;
1199 g_source_list_remove (source, context);
1201 if (source->source_funcs->destroy)
1202 source->source_funcs->destroy (source);
1204 g_slist_free (source->poll_fds);
1205 source->poll_fds = NULL;
1209 if (!have_lock && context)
1210 UNLOCK_CONTEXT (context);
1215 UNLOCK_CONTEXT (context);
1217 old_cb_funcs->unref (old_cb_data);
1220 LOCK_CONTEXT (context);
1226 * @source: a #GSource
1228 * Decreases the reference count of a source by one. If the
1229 * resulting reference count is zero the source and associated
1230 * memory will be destroyed.
1233 g_source_unref (GSource *source)
1235 g_return_if_fail (source != NULL);
1237 g_source_unref_internal (source, source->context, FALSE);
1241 * g_main_context_find_source_by_id:
1242 * @context: a #GMainContext (if %NULL, the default context will be used)
1243 * @id: the source ID, as returned by g_source_get_id()
1245 * Finds a #GSource given a pair of context and ID
1247 * Return value: the #GSource if found, otherwise, %NULL
1250 g_main_context_find_source_by_id (GMainContext *context,
1255 g_return_val_if_fail (id > 0, FALSE);
1257 if (context == NULL)
1258 context = g_main_context_default ();
1260 LOCK_CONTEXT (context);
1262 source = context->source_list;
1265 if (!SOURCE_DESTROYED (source) &&
1268 source = source->next;
1271 UNLOCK_CONTEXT (context);
1277 * g_main_context_find_source_by_funcs_user_data:
1278 * @context: a #GMainContext (if %NULL, the default context will be used).
1279 * @funcs: the @source_funcs passed to g_source_new().
1280 * @user_data: the user data from the callback.
1282 * Finds a source with the given source functions and user data. If
1283 * multiple sources exist with the same source function and user data,
1284 * the first one found will be returned.
1286 * Return value: the source, if one was found, otherwise %NULL
1289 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1290 GSourceFuncs *funcs,
1295 g_return_val_if_fail (funcs != NULL, FALSE);
1297 if (context == NULL)
1298 context = g_main_context_default ();
1300 LOCK_CONTEXT (context);
1302 source = context->source_list;
1305 if (!SOURCE_DESTROYED (source) &&
1306 source->source_funcs == funcs &&
1307 source->callback_data == user_data)
1309 source = source->next;
1312 UNLOCK_CONTEXT (context);
1318 * g_main_context_find_source_by_user_data:
1319 * @context: a #GMainContext
1320 * @user_data: the user_data for the callback.
1322 * Finds a source with the given user data for the callback. If
1323 * multiple sources exist with the same user data, the first
1324 * one found will be returned.
1326 * Return value: the source, if one was found, otherwise %NULL
1329 g_main_context_find_source_by_user_data (GMainContext *context,
1334 if (context == NULL)
1335 context = g_main_context_default ();
1337 LOCK_CONTEXT (context);
1339 source = context->source_list;
1342 if (!SOURCE_DESTROYED (source) &&
1343 source->callback_data == user_data)
1345 source = source->next;
1348 UNLOCK_CONTEXT (context);
1355 * @tag: the id of the source to remove.
1357 * Removes the source with the given id from the default main
1358 * context. The id of a #GSource is given by g_source_get_id(),
1359 * or will be returned by the functions g_source_attach(),
1360 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1361 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1363 * See also g_source_destroy().
1365 * Return value: %TRUE if the source was found and removed.
1368 g_source_remove (guint tag)
1372 g_return_val_if_fail (tag > 0, FALSE);
1374 source = g_main_context_find_source_by_id (NULL, tag);
1376 g_source_destroy (source);
1378 return source != NULL;
1382 * g_source_remove_by_user_data:
1383 * @user_data: the user_data for the callback.
1385 * Removes a source from the default main loop context given the user
1386 * data for the callback. If multiple sources exist with the same user
1387 * data, only one will be destroyed.
1389 * Return value: %TRUE if a source was found and removed.
1392 g_source_remove_by_user_data (gpointer user_data)
1396 source = g_main_context_find_source_by_user_data (NULL, user_data);
1399 g_source_destroy (source);
1407 * g_source_remove_by_funcs_user_data:
1408 * @funcs: The @source_funcs passed to g_source_new()
1409 * @user_data: the user data for the callback
1411 * Removes a source from the default main loop context given the
1412 * source functions and user data. If multiple sources exist with the
1413 * same source functions and user data, only one will be destroyed.
1415 * Return value: %TRUE if a source was found and removed.
1418 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1423 g_return_val_if_fail (funcs != NULL, FALSE);
1425 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1428 g_source_destroy (source);
1436 * g_get_current_time:
1437 * @result: #GTimeVal structure in which to store current time.
1439 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1442 g_get_current_time (GTimeVal *result)
1447 g_return_if_fail (result != NULL);
1449 /*this is required on alpha, there the timeval structs are int's
1450 not longs and a cast only would fail horribly*/
1451 gettimeofday (&r, NULL);
1452 result->tv_sec = r.tv_sec;
1453 result->tv_usec = r.tv_usec;
1455 /* Avoid calling time() except for the first time.
1456 * GetTickCount() should be pretty fast and low-level?
1457 * I could also use ftime() but it seems unnecessarily overheady.
1459 static DWORD start_tick = 0;
1460 static time_t start_time;
1463 g_return_if_fail (result != NULL);
1465 if (start_tick == 0)
1467 start_tick = GetTickCount ();
1471 tick = GetTickCount ();
1473 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1474 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1478 /* Running the main loop */
1480 /* HOLDS: context's lock */
1482 g_main_dispatch (GMainContext *context)
1486 for (i = 0; i < context->pending_dispatches->len; i++)
1488 GSource *source = context->pending_dispatches->pdata[i];
1490 context->pending_dispatches->pdata[i] = NULL;
1493 source->flags &= ~G_SOURCE_READY;
1495 if (!SOURCE_DESTROYED (source))
1497 gboolean was_in_call;
1498 gpointer user_data = NULL;
1499 GSourceFunc callback = NULL;
1500 GSourceCallbackFuncs *cb_funcs;
1502 gboolean need_destroy;
1504 gboolean (*dispatch) (GSource *,
1508 dispatch = source->source_funcs->dispatch;
1509 cb_funcs = source->callback_funcs;
1510 cb_data = source->callback_data;
1513 cb_funcs->ref (cb_data);
1515 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1516 source->flags |= G_HOOK_FLAG_IN_CALL;
1518 UNLOCK_CONTEXT (context);
1521 cb_funcs->get (cb_data, &callback, &user_data);
1523 need_destroy = ! dispatch (source,
1526 LOCK_CONTEXT (context);
1529 cb_funcs->unref (cb_data);
1532 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1534 /* Note: this depends on the fact that we can't switch
1535 * sources from one main context to another
1537 if (need_destroy && !SOURCE_DESTROYED (source))
1539 g_assert (source->context == context);
1540 g_source_destroy_internal (source, context, TRUE);
1544 SOURCE_UNREF (source, context);
1547 g_ptr_array_set_size (context->pending_dispatches, 0);
1550 /* Holds context's lock */
1551 static inline GSource *
1552 next_valid_source (GMainContext *context,
1555 GSource *new_source = source ? source->next : context->source_list;
1559 if (!SOURCE_DESTROYED (new_source))
1561 new_source->ref_count++;
1565 new_source = new_source->next;
1569 SOURCE_UNREF (source, context);
1576 * g_main_context_prepare:
1577 * @context: a #GMainContext
1578 * @priority: location to store priority of highest priority
1579 * source already ready.
1581 * Prepares to poll sources within a main loop. The resulting information
1582 * for polling is determined by calling g_main_context_query ().
1584 * Return value: %TRUE if some source is ready to be dispatched
1588 g_main_context_prepare (GMainContext *context,
1592 gint current_priority = G_MAXINT;
1595 if (context == NULL)
1596 context = g_main_context_default ();
1598 LOCK_CONTEXT (context);
1600 context->time_is_current = FALSE;
1602 if (context->in_check_or_prepare)
1604 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1605 "prepare() member.");
1609 #ifdef G_THREADS_ENABLED
1610 if (context->poll_waiting)
1612 g_warning("g_main_context_prepare(): main loop already active in another thread");
1613 UNLOCK_CONTEXT (context);
1617 context->poll_waiting = TRUE;
1618 #endif /* G_THREADS_ENABLED */
1621 /* If recursing, finish up current dispatch, before starting over */
1622 if (context->pending_dispatches)
1625 g_main_dispatch (context, ¤t_time);
1627 UNLOCK_CONTEXT (context);
1632 /* If recursing, clear list of pending dispatches */
1633 g_ptr_array_set_size (context->pending_dispatches, 0);
1635 /* Prepare all sources */
1637 context->timeout = -1;
1639 source = next_valid_source (context, NULL);
1642 gint source_timeout = -1;
1644 if ((n_ready > 0) && (source->priority > current_priority))
1646 SOURCE_UNREF (source, context);
1649 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1652 if (!(source->flags & G_SOURCE_READY))
1655 gboolean (*prepare) (GSource *source,
1658 prepare = source->source_funcs->prepare;
1659 context->in_check_or_prepare++;
1660 UNLOCK_CONTEXT (context);
1662 result = (*prepare) (source, &source_timeout);
1664 LOCK_CONTEXT (context);
1665 context->in_check_or_prepare--;
1668 source->flags |= G_SOURCE_READY;
1671 if (source->flags & G_SOURCE_READY)
1674 current_priority = source->priority;
1675 context->timeout = 0;
1678 if (source_timeout >= 0)
1680 if (context->timeout < 0)
1681 context->timeout = source_timeout;
1683 context->timeout = MIN (context->timeout, source_timeout);
1687 source = next_valid_source (context, source);
1690 UNLOCK_CONTEXT (context);
1693 *priority = current_priority;
1695 return (n_ready > 0);
1699 * g_main_context_query:
1700 * @context: a #GMainContext
1701 * @max_priority: maximum priority source to check
1702 * @timeout: location to store timeout to be used in polling
1703 * @fds: location to store #GPollFD records that need to be polled.
1704 * @n_fds: length of @fds.
1706 * Determines information necessary to poll this main loop.
1711 g_main_context_query (GMainContext *context,
1720 LOCK_CONTEXT (context);
1722 pollrec = context->poll_records;
1724 while (pollrec && max_priority >= pollrec->priority)
1726 if (pollrec->fd->events)
1730 fds[n_poll].fd = pollrec->fd->fd;
1731 /* In direct contradiction to the Unix98 spec, IRIX runs into
1732 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1733 * flags in the events field of the pollfd while it should
1734 * just ignoring them. So we mask them out here.
1736 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1737 fds[n_poll].revents = 0;
1742 pollrec = pollrec->next;
1745 #ifdef G_THREADS_ENABLED
1746 context->poll_changed = FALSE;
1751 *timeout = context->timeout;
1753 context->time_is_current = FALSE;
1756 UNLOCK_CONTEXT (context);
1762 * g_main_context_check:
1763 * @context: a #GMainContext
1764 * @max_priority: the maximum numerical priority of sources to check
1765 * @fds: array of #GPollFD's that was passed to the last call to
1766 * g_main_context_query()
1767 * @n_fds: return value of g_main_context_query()
1769 * Pass the results of polling back to the main loop.
1771 * Return value: %TRUE if some sources are ready to be dispatched.
1774 g_main_context_check (GMainContext *context,
1784 LOCK_CONTEXT (context);
1786 if (context->in_check_or_prepare)
1788 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1789 "prepare() member.");
1793 #ifdef G_THREADS_ENABLED
1794 if (!context->poll_waiting)
1798 read (context->wake_up_pipe[0], &c, 1);
1802 context->poll_waiting = FALSE;
1804 /* If the set of poll file descriptors changed, bail out
1805 * and let the main loop rerun
1807 if (context->poll_changed)
1809 #endif /* G_THREADS_ENABLED */
1811 pollrec = context->poll_records;
1815 if (pollrec->fd->events)
1817 pollrec->fd->revents = fds[i].revents;
1820 pollrec = pollrec->next;
1823 source = next_valid_source (context, NULL);
1826 if ((n_ready > 0) && (source->priority > max_priority))
1828 SOURCE_UNREF (source, context);
1831 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1834 if (!(source->flags & G_SOURCE_READY))
1837 gboolean (*check) (GSource *source);
1839 check = source->source_funcs->check;
1841 context->in_check_or_prepare++;
1842 UNLOCK_CONTEXT (context);
1844 result = (*check) (source);
1846 LOCK_CONTEXT (context);
1847 context->in_check_or_prepare--;
1850 source->flags |= G_SOURCE_READY;
1853 if (source->flags & G_SOURCE_READY)
1855 source->ref_count++;
1856 g_ptr_array_add (context->pending_dispatches, source);
1862 source = next_valid_source (context, source);
1865 UNLOCK_CONTEXT (context);
1871 * g_main_context_dispatch:
1872 * @context: a #GMainContext
1874 * Dispatch all pending sources()
1877 g_main_context_dispatch (GMainContext *context)
1879 LOCK_CONTEXT (context);
1881 if (context->pending_dispatches->len > 0)
1883 g_main_dispatch (context);
1886 UNLOCK_CONTEXT (context);
1890 g_main_context_iterate (GMainContext *context,
1896 gboolean some_ready;
1897 gint nfds, new_nfds;
1900 some_ready = g_main_context_prepare (context, &max_priority);
1904 LOCK_CONTEXT (context);
1906 if (context->cached_poll_array)
1908 nfds = context->cached_poll_array_size;
1909 fds = context->cached_poll_array;
1910 context->cached_poll_array = NULL;
1914 nfds = context->cached_poll_array_size = context->n_poll_records;
1915 fds = g_new (GPollFD, nfds);
1918 UNLOCK_CONTEXT (context);
1920 new_nfds = g_main_context_query (context, max_priority,
1921 &timeout, fds, nfds);
1923 while (new_nfds > nfds);
1928 g_main_context_poll (context, timeout, max_priority,
1931 g_main_context_check (context,
1935 LOCK_CONTEXT (context);
1937 g_assert (!context->cached_poll_array);
1939 context->cached_poll_array = fds;
1940 context->cached_poll_array_size = nfds;
1942 UNLOCK_CONTEXT (context);
1945 g_main_context_dispatch (context);
1951 * g_main_context_pending:
1952 * @context: a #GMainContext (if %NULL, the default context will be used)
1954 * Check if any sources have pending events for the given context.
1956 * Return value: %TRUE if events are pending.
1959 g_main_context_pending (GMainContext *context)
1962 context = g_main_context_default();
1964 return g_main_context_iterate (context, FALSE, FALSE);
1968 * g_main_context_iteration:
1969 * @context: a #GMainContext (if %NULL, the default context will be used)
1970 * @may_block: whether the call may block.
1972 * Run a single iteration for the given main loop. This involves
1973 * checking to see if any event sources are ready to be processed,
1974 * then if no events sources are ready and @may_block is %TRUE, waiting
1975 * for a source to become ready, then dispatching the highest priority
1976 * events sources that are ready. Note that even when @may_block is %TRUE,
1977 * it is still possible for g_main_context_iteration() to return
1978 * %FALSE, since the the wait may be interrupted for other
1979 * reasons than an event source becoming ready.
1981 * Return value: %TRUE if events were dispatched.
1984 g_main_context_iteration (GMainContext *context, gboolean may_block)
1987 context = g_main_context_default();
1989 return g_main_context_iterate (context, may_block, TRUE);
1994 * @context: a #GMainContext (if %NULL, the default context will be used).
1995 * @is_running: set to TRUE to indicate that the loop is running. This
1996 * is not very important since calling g_main_run() will set this to
1999 * Create a new #GMainLoop structure
2004 g_main_loop_new (GMainContext *context,
2005 gboolean is_running)
2010 context = g_main_context_default();
2012 loop = g_new0 (GMainLoop, 1);
2013 loop->context = context;
2014 loop->is_running = is_running != FALSE;
2016 #ifdef G_THREADS_ENABLED
2017 if (g_thread_supported ())
2018 loop->mutex = g_mutex_new ();
2021 loop->sem_cond = NULL;
2022 #endif /* G_THREADS_ENABLED */
2029 * @loop: a #GMainLoop
2031 * Run a main loop until g_main_quit() is called on the loop.
2032 * If this is called for the thread of the loop's #GMainContext,
2033 * it will process events from the loop, otherwise it will
2037 g_main_loop_run (GMainLoop *loop)
2039 g_return_if_fail (loop != NULL);
2041 #ifdef G_THREADS_ENABLED
2042 if (loop->context->thread != g_thread_self ())
2046 if (!g_thread_supported ())
2048 g_warning ("g_main_loop_run() was called from second thread but"
2049 "g_thread_init() was never called.");
2053 if (!loop->sem_cond)
2054 loop->sem_cond = g_cond_new ();
2056 if (!loop->is_running)
2057 loop->is_running = TRUE;
2059 while (loop->is_running)
2060 g_cond_wait (loop->sem_cond, loop->mutex);
2066 #endif /* G_THREADS_ENABLED */
2068 LOCK_CONTEXT (loop->context);
2069 if (loop->context->in_check_or_prepare)
2071 g_warning ("g_main_run(): called recursively from within a source's check() or "
2072 "prepare() member, iteration not possible.");
2075 UNLOCK_CONTEXT (loop->context);
2079 loop->is_running = TRUE;
2080 while (loop->is_running)
2083 g_main_context_iterate (loop->context, TRUE, TRUE);
2092 * @loop: a #GMainLoop
2094 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2095 * for the loop will return.
2098 g_main_loop_quit (GMainLoop *loop)
2100 g_return_if_fail (loop != NULL);
2103 loop->is_running = FALSE;
2105 #ifdef G_THREADS_ENABLED
2107 g_cond_broadcast (loop->sem_cond);
2112 LOCK_CONTEXT (loop->context);
2114 g_main_context_wakeup (loop->context);
2115 UNLOCK_CONTEXT (loop->context);
2119 * g_main_loop_destroy:
2120 * @loop: a #GMainLoop
2122 * Destroy a #GMainLoop object and free all associated memory.
2123 * The loop must not currently be running via g_main_run().
2126 g_main_loop_destroy (GMainLoop *loop)
2128 g_return_if_fail (loop != NULL);
2129 g_return_if_fail (!loop->is_running);
2131 #ifdef G_THREADS_ENABLED
2132 g_mutex_free (loop->mutex);
2134 g_cond_free (loop->sem_cond);
2135 #endif /* G_THREADS_ENABLED */
2141 * g_main_loop_is_running:
2142 * @loop: a #GMainLoop.
2144 * Check to see if the main loop is currently being run via g_main_run()
2146 * Return value: %TRUE if the mainloop is currently being run.
2149 g_main_loop_is_running (GMainLoop *loop)
2153 g_return_val_if_fail (loop != NULL, FALSE);
2156 result = loop->is_running;
2162 /* HOLDS: context's lock */
2164 g_main_context_poll (GMainContext *context,
2170 #ifdef G_MAIN_POLL_DEBUG
2176 GPollFunc poll_func;
2178 if (n_fds || timeout != 0)
2180 #ifdef G_MAIN_POLL_DEBUG
2181 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2182 poll_timer = g_timer_new ();
2185 LOCK_CONTEXT (context);
2187 poll_func = context->poll_func;
2189 UNLOCK_CONTEXT (context);
2190 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2191 g_warning ("poll(2) failed due to: %s.",
2192 g_strerror (errno));
2194 #ifdef G_MAIN_POLL_DEBUG
2195 LOCK_CONTEXT (context);
2197 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2200 g_timer_elapsed (poll_timer, NULL));
2201 g_timer_destroy (poll_timer);
2202 pollrec = context->poll_records;
2206 if (pollrec->fd->events)
2210 g_print (" [%d:", fds[i].fd);
2211 if (fds[i].revents & G_IO_IN)
2213 if (fds[i].revents & G_IO_OUT)
2215 if (fds[i].revents & G_IO_PRI)
2217 if (fds[i].revents & G_IO_ERR)
2219 if (fds[i].revents & G_IO_HUP)
2221 if (fds[i].revents & G_IO_NVAL)
2227 pollrec = pollrec->next;
2231 UNLOCK_CONTEXT (context);
2233 } /* if (n_fds || timeout != 0) */
2237 * g_main_context_add_poll:
2238 * @context: a #GMainContext (or %NULL for the default context)
2239 * @fd: a #GPollFD structure holding information about a file
2240 * descriptor to watch.
2241 * @priority: the priority for this file descriptor which should be
2242 * the same as the priority used for g_source_attach() to ensure that the
2243 * file descriptor is polled whenever the results may be needed.
2245 * Add a file descriptor to the set of file descriptors polled * for
2246 * this context. This will very seldom be used directly. Instead
2247 * a typical event source will use g_source_add_poll() instead.
2250 g_main_context_add_poll (GMainContext *context,
2255 context = g_main_context_default ();
2257 LOCK_CONTEXT (context);
2258 g_main_context_add_poll_unlocked (context, priority, fd);
2259 UNLOCK_CONTEXT (context);
2262 /* HOLDS: main_loop_lock */
2264 g_main_context_add_poll_unlocked (GMainContext *context,
2268 GPollRec *lastrec, *pollrec, *newrec;
2270 if (!context->poll_chunk)
2271 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2273 if (context->poll_free_list)
2275 newrec = context->poll_free_list;
2276 context->poll_free_list = newrec->next;
2279 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2281 /* This file descriptor may be checked before we ever poll */
2284 newrec->priority = priority;
2287 pollrec = context->poll_records;
2288 while (pollrec && priority >= pollrec->priority)
2291 pollrec = pollrec->next;
2295 lastrec->next = newrec;
2297 context->poll_records = newrec;
2299 newrec->next = pollrec;
2301 context->n_poll_records++;
2302 if (context->cached_poll_array &&
2303 context->cached_poll_array_size < context->n_poll_records)
2305 g_free (context->cached_poll_array);
2306 context->cached_poll_array = NULL;
2309 #ifdef G_THREADS_ENABLED
2310 context->poll_changed = TRUE;
2312 /* Now wake up the main loop if it is waiting in the poll() */
2313 g_main_context_wakeup (context);
2318 * g_main_context_remove_poll:
2319 * @context:a #GMainContext
2320 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2322 * Remove file descriptor from the set of file descriptors to be
2323 * polled for a particular context.
2326 g_main_context_remove_poll (GMainContext *context,
2330 context = g_main_context_default ();
2332 LOCK_CONTEXT (context);
2334 g_main_context_remove_poll_unlocked (context, fd);
2336 UNLOCK_CONTEXT (context);
2340 g_main_context_remove_poll_unlocked (GMainContext *context,
2343 GPollRec *pollrec, *lastrec;
2346 pollrec = context->poll_records;
2350 if (pollrec->fd == fd)
2352 if (lastrec != NULL)
2353 lastrec->next = pollrec->next;
2355 context->poll_records = pollrec->next;
2357 #ifdef ENABLE_GC_FRIENDLY
2359 #endif /* ENABLE_GC_FRIENDLY */
2361 pollrec->next = context->poll_free_list;
2362 context->poll_free_list = pollrec;
2364 context->n_poll_records--;
2368 pollrec = pollrec->next;
2371 #ifdef G_THREADS_ENABLED
2372 context->poll_changed = TRUE;
2374 /* Now wake up the main loop if it is waiting in the poll() */
2375 g_main_context_wakeup (context);
2380 * g_source_get_current_time:
2381 * @source: a #GSource
2382 * @timeval: #GTimeVal structure in which to store current time.
2384 * Gets the "current time" to be used when checking
2385 * this source. The advantage of calling this function over
2386 * calling g_get_current_time() directly is that when
2387 * checking multiple sources, GLib can cache a single value
2388 * instead of having to repeatedly get the system time.
2391 g_source_get_current_time (GSource *source,
2394 GMainContext *context;
2396 g_return_if_fail (source->context != NULL);
2398 context = source->context;
2400 LOCK_CONTEXT (context);
2402 if (!context->time_is_current)
2404 g_get_current_time (&context->current_time);
2405 context->time_is_current = TRUE;
2408 *timeval = context->current_time;
2410 UNLOCK_CONTEXT (context);
2414 * g_main_context_set_poll_func:
2415 * @context: a #GMainContext
2416 * @func: the function to call to poll all file descriptors
2418 * Sets the function to use to handle polling of file descriptors. It
2419 * will be used instead of the poll() system call (or GLib's
2420 * replacement function, which is used where poll() isn't available).
2422 * This function could possibly be used to integrate the GLib event
2423 * loop with an external event loop.
2426 g_main_context_set_poll_func (GMainContext *context,
2430 context = g_main_context_default ();
2432 LOCK_CONTEXT (context);
2435 context->poll_func = func;
2439 context->poll_func = (GPollFunc) poll;
2441 context->poll_func = (GPollFunc) g_poll;
2445 UNLOCK_CONTEXT (context);
2449 * g_main_context_get_poll_func:
2450 * @context: a #GMainContext
2452 * Gets the poll function set by g_main_context_set_poll_func()
2454 * Return value: the poll function
2457 g_main_context_get_poll_func (GMainContext *context)
2462 context = g_main_context_default ();
2464 LOCK_CONTEXT (context);
2465 result = context->poll_func;
2466 UNLOCK_CONTEXT (context);
2471 /* HOLDS: context's lock */
2472 /* Wake the main loop up from a poll() */
2474 g_main_context_wakeup (GMainContext *context)
2476 #ifdef G_THREADS_ENABLED
2477 if (g_thread_supported() && context->poll_waiting)
2479 context->poll_waiting = FALSE;
2481 write (context->wake_up_pipe[1], "A", 1);
2483 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2492 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2493 GTimeVal *current_time)
2495 guint seconds = timeout_source->interval / 1000;
2496 guint msecs = timeout_source->interval - seconds * 1000;
2498 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2499 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2500 if (timeout_source->expiration.tv_usec >= 1000000)
2502 timeout_source->expiration.tv_usec -= 1000000;
2503 timeout_source->expiration.tv_sec++;
2508 g_timeout_prepare (GSource *source,
2512 GTimeVal current_time;
2514 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2516 g_source_get_current_time (source, ¤t_time);
2518 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2519 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2523 else if (msec > timeout_source->interval)
2525 /* The system time has been set backwards, so we
2526 * reset the expiration time to now + timeout_source->interval;
2527 * this at least avoids hanging for long periods of time.
2529 g_timeout_set_expiration (timeout_source, ¤t_time);
2530 msec = timeout_source->interval;
2539 g_timeout_check (GSource *source)
2541 GTimeVal current_time;
2542 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2544 g_source_get_current_time (source, ¤t_time);
2546 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2547 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2548 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2552 g_timeout_dispatch (GSource *source,
2553 GSourceFunc callback,
2556 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2560 g_warning ("Timeout source dispatched without callback\n"
2561 "You must call g_source_set_callback().");
2565 if (callback (user_data))
2567 GTimeVal current_time;
2569 g_source_get_current_time (source, ¤t_time);
2570 g_timeout_set_expiration (timeout_source, ¤t_time);
2579 * g_timeout_source_new:
2580 * @interval: the timeout interval in milliseconds.
2582 * Create a new timeout source.
2584 * The source will not initially be associated with any #GMainContext
2585 * and must be added to one with g_source_attach() before it will be
2588 * Return value: the newly create timeout source
2591 g_timeout_source_new (guint interval)
2593 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2594 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2595 GTimeVal current_time;
2597 timeout_source->interval = interval;
2599 g_get_current_time (¤t_time);
2600 g_timeout_set_expiration (timeout_source, ¤t_time);
2606 * g_timeout_add_full:
2607 * @priority: the priority of the idle source. Typically this will be in the
2608 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2609 * @interval: the time between calls to the function, in milliseconds
2610 * (1/1000ths of a second.)
2611 * @function: function to call
2612 * @data: data to pass to @function
2613 * @notify: function to call when the idle is removed, or %NULL
2615 * Sets a function to be called at regular intervals, with the given
2616 * priority. The function is called repeatedly until it returns
2617 * FALSE, at which point the timeout is automatically destroyed and
2618 * the function will not be called again. The @notify function is
2619 * called when the timeout is destroyed. The first call to the
2620 * function will be at the end of the first @interval.
2622 * Note that timeout functions may be delayed, due to the processing of other
2623 * event sources. Thus they should not be relied on for precise timing.
2624 * After each call to the timeout function, the time of the next
2625 * timeout is recalculated based on the current time and the given interval
2626 * (it does not try to 'catch up' time lost in delays).
2628 * Return value: the id of event source.
2631 g_timeout_add_full (gint priority,
2633 GSourceFunc function,
2635 GDestroyNotify notify)
2640 g_return_val_if_fail (function != NULL, 0);
2642 source = g_timeout_source_new (interval);
2644 if (priority != G_PRIORITY_DEFAULT)
2645 g_source_set_priority (source, priority);
2647 g_source_set_callback (source, function, data, notify);
2648 id = g_source_attach (source, NULL);
2649 g_source_unref (source);
2656 * @interval: the time between calls to the function, in milliseconds
2657 * (1/1000ths of a second.)
2658 * @function: function to call
2659 * @data: data to pass to @function
2661 * Sets a function to be called at regular intervals, with the default
2662 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2663 * until it returns FALSE, at which point the timeout is automatically
2664 * destroyed and the function will not be called again. The @notify
2665 * function is called when the timeout is destroyed. The first call
2666 * to the function will be at the end of the first @interval.
2668 * Note that timeout functions may be delayed, due to the processing of other
2669 * event sources. Thus they should not be relied on for precise timing.
2670 * After each call to the timeout function, the time of the next
2671 * timeout is recalculated based on the current time and the given interval
2672 * (it does not try to 'catch up' time lost in delays).
2674 * Return value: the id of event source.
2677 g_timeout_add (guint32 interval,
2678 GSourceFunc function,
2681 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2682 interval, function, data, NULL);
2685 /* Idle functions */
2688 g_idle_prepare (GSource *source,
2697 g_idle_check (GSource *source)
2703 g_idle_dispatch (GSource *source,
2704 GSourceFunc callback,
2709 g_warning ("Idle source dispatched without callback\n"
2710 "You must call g_source_set_callback().");
2714 return callback (user_data);
2718 * g_idle_source_new:
2720 * Create a new idle source.
2722 * The source will not initially be associated with any #GMainContext
2723 * and must be added to one with g_source_attach() before it will be
2726 * Return value: the newly created idle source
2729 g_idle_source_new (void)
2731 return g_source_new (&idle_funcs, sizeof (GSource));
2736 * @priority: the priority of the idle source. Typically this will be in the
2737 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2738 * @function: function to call
2739 * @data: data to pass to @function
2740 * @notify: function to call when the idle is removed, or %NULL
2742 * Adds a function to be called whenever there are no higher priority
2743 * events pending. If the function returns FALSE it is automatically
2744 * removed from the list of event sources and will not be called again.
2746 * Return value: the id of the event source.
2749 g_idle_add_full (gint priority,
2750 GSourceFunc function,
2752 GDestroyNotify notify)
2757 g_return_val_if_fail (function != NULL, 0);
2759 source = g_idle_source_new ();
2761 if (priority != G_PRIORITY_DEFAULT)
2762 g_source_set_priority (source, priority);
2764 g_source_set_callback (source, function, data, notify);
2765 id = g_source_attach (source, NULL);
2766 g_source_unref (source);
2773 * @function: function to call
2774 * @data: data to pass to @function.
2776 * Adds a function to be called whenever there are no higher priority
2777 * events pending to the default main loop. The function is given the
2778 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2779 * returns FALSE it is automatically removed from the list of event
2780 * sources and will not be called again.
2782 * Return value: the id of the event source.
2785 g_idle_add (GSourceFunc function,
2788 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2792 * g_idle_remove_by_data:
2793 * @data: the data for the idle source's callback.
2795 * Removes the idle function with the given data.
2797 * Return value: %TRUE if an idle source was found and removed.
2800 g_idle_remove_by_data (gpointer data)
2802 return g_source_remove_by_funcs_user_data (&idle_funcs, data);