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)
76 #ifdef G_THREADS_ENABLED
77 typedef struct _GMainWaiter GMainWaiter;
88 #ifdef G_THREADS_ENABLED
89 /* The following lock is used for both the list of sources
90 * and the list of poll records
101 GPtrArray *pending_dispatches;
102 gint timeout; /* Timeout for current iteration */
105 GSource *source_list;
106 gint in_check_or_prepare;
108 GPollRec *poll_records;
109 GPollRec *poll_free_list;
110 GMemChunk *poll_chunk;
111 guint n_poll_records;
112 GPollFD *cached_poll_array;
113 guint cached_poll_array_size;
115 #ifdef G_THREADS_ENABLED
117 /* this pipe is used to wake up the main loop when a source is added.
119 gint wake_up_pipe[2];
120 #else /* G_OS_WIN32 */
121 HANDLE wake_up_semaphore;
122 #endif /* G_OS_WIN32 */
125 gboolean poll_waiting;
127 /* Flag indicating whether the set of fd's changed during a poll */
128 gboolean poll_changed;
129 #endif /* G_THREADS_ENABLED */
133 GTimeVal current_time;
134 gboolean time_is_current;
137 struct _GSourceCallback
142 GDestroyNotify notify;
147 GMainContext *context;
152 struct _GTimeoutSource
166 #ifdef G_THREADS_ENABLED
167 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
168 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
169 #define G_THREAD_SELF g_thread_self ()
171 #define LOCK_CONTEXT(context) (void)0
172 #define UNLOCK_CONTEXT(context) (void)0
173 #define G_THREAD_SELF NULL
176 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
178 #define SOURCE_UNREF(source, context) \
180 if ((source)->ref_count > 1) \
181 (source)->ref_count--; \
183 g_source_unref_internal ((source), (context), TRUE); \
187 /* Forward declarations */
189 static void g_source_unref_internal (GSource *source,
190 GMainContext *context,
192 static void g_source_destroy_internal (GSource *source,
193 GMainContext *context,
195 static void g_main_context_poll (GMainContext *context,
200 static void g_main_context_add_poll_unlocked (GMainContext *context,
203 static void g_main_context_remove_poll_unlocked (GMainContext *context,
205 static void g_main_context_wakeup_unlocked (GMainContext *context);
207 static gboolean g_timeout_prepare (GSource *source,
209 static gboolean g_timeout_check (GSource *source);
210 static gboolean g_timeout_dispatch (GSource *source,
211 GSourceFunc callback,
213 static gboolean g_idle_prepare (GSource *source,
215 static gboolean g_idle_check (GSource *source);
216 static gboolean g_idle_dispatch (GSource *source,
217 GSourceFunc callback,
220 G_LOCK_DEFINE_STATIC (main_loop);
221 static GMainContext *default_main_context;
223 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
224 __declspec(dllexport)
226 GSourceFuncs g_timeout_funcs =
234 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
235 __declspec(dllexport)
237 GSourceFuncs g_idle_funcs =
246 /* SunOS has poll, but doesn't provide a prototype. */
247 # if defined (sun) && !defined (__SVR4)
248 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
250 #else /* !HAVE_POLL */
255 g_poll (GPollFD *fds,
259 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
260 gboolean poll_msgs = FALSE;
267 for (f = fds; f < &fds[nfds]; ++f)
270 if (f->events & G_IO_IN)
272 if (f->fd == G_WIN32_MSG_HANDLE)
276 #ifdef G_MAIN_POLL_DEBUG
277 g_print ("g_poll: waiting for %#x\n", f->fd);
279 handles[nhandles++] = (HANDLE) f->fd;
289 /* Waiting for messages, and maybe events
290 * -> First PeekMessage
292 #ifdef G_MAIN_POLL_DEBUG
293 g_print ("PeekMessage\n");
295 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
296 ready = WAIT_OBJECT_0 + nhandles;
301 /* Waiting just for messages */
302 if (timeout == INFINITE)
307 #ifdef G_MAIN_POLL_DEBUG
308 g_print ("WaitMessage\n");
311 g_warning (G_STRLOC ": WaitMessage() failed");
312 ready = WAIT_OBJECT_0 + nhandles;
314 else if (timeout == 0)
316 /* Waiting just for messages, zero timeout.
317 * If we got here, there was no message
319 ready = WAIT_TIMEOUT;
323 /* Waiting just for messages, some timeout
324 * -> Set a timer, wait for message,
325 * kill timer, use PeekMessage
327 timer = SetTimer (NULL, 0, timeout, NULL);
329 g_warning (G_STRLOC ": SetTimer() failed");
332 #ifdef G_MAIN_POLL_DEBUG
333 g_print ("WaitMessage\n");
336 KillTimer (NULL, timer);
337 #ifdef G_MAIN_POLL_DEBUG
338 g_print ("PeekMessage\n");
340 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
341 && msg.message != WM_TIMER)
342 ready = WAIT_OBJECT_0;
344 ready = WAIT_TIMEOUT;
350 /* Wait for either message or event
351 * -> Use MsgWaitForMultipleObjects
353 #ifdef G_MAIN_POLL_DEBUG
354 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
356 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
357 timeout, QS_ALLINPUT);
359 if (ready == WAIT_FAILED)
360 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
364 else if (nhandles == 0)
366 /* Wait for nothing (huh?) */
371 /* Wait for just events
372 * -> Use WaitForMultipleObjects
374 #ifdef G_MAIN_POLL_DEBUG
375 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
377 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
378 if (ready == WAIT_FAILED)
379 g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
382 #ifdef G_MAIN_POLL_DEBUG
383 g_print ("wait returns %d%s\n",
385 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
386 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
387 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
389 for (f = fds; f < &fds[nfds]; ++f)
392 if (ready == WAIT_FAILED)
394 else if (ready == WAIT_TIMEOUT)
396 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
398 for (f = fds; f < &fds[nfds]; ++f)
401 if (f->events & G_IO_IN)
402 if (f->fd == G_WIN32_MSG_HANDLE)
403 f->revents |= G_IO_IN;
406 #if 1 /* TEST_WITHOUT_THIS */
407 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
408 for (f = fds; f < &fds[nfds]; ++f)
410 if ((f->events & G_IO_IN)
411 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
413 f->revents |= G_IO_IN;
414 #ifdef G_MAIN_POLL_DEBUG
415 g_print ("g_poll: got event %#x\n", f->fd);
418 ResetEvent ((HANDLE) f->fd);
427 #else /* !G_OS_WIN32 */
429 /* The following implementation of poll() comes from the GNU C Library.
430 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
433 #include <string.h> /* for bzero on BSD systems */
435 #ifdef HAVE_SYS_SELECT_H
436 #include <sys/select.h>
437 #endif /* HAVE_SYS_SELECT_H */
441 #endif /* G_OS_BEOS */
444 # define SELECT_MASK fd_set
445 #else /* !NO_FD_SET */
447 typedef long fd_mask;
450 # define SELECT_MASK void
452 # define SELECT_MASK int
453 # endif /* !_IBMR2 */
454 #endif /* !NO_FD_SET */
457 g_poll (GPollFD *fds,
462 SELECT_MASK rset, wset, xset;
471 for (f = fds; f < &fds[nfds]; ++f)
474 if (f->events & G_IO_IN)
475 FD_SET (f->fd, &rset);
476 if (f->events & G_IO_OUT)
477 FD_SET (f->fd, &wset);
478 if (f->events & G_IO_PRI)
479 FD_SET (f->fd, &xset);
480 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
484 tv.tv_sec = timeout / 1000;
485 tv.tv_usec = (timeout % 1000) * 1000;
487 ready = select (maxfd + 1, &rset, &wset, &xset,
488 timeout == -1 ? NULL : &tv);
490 for (f = fds; f < &fds[nfds]; ++f)
495 if (FD_ISSET (f->fd, &rset))
496 f->revents |= G_IO_IN;
497 if (FD_ISSET (f->fd, &wset))
498 f->revents |= G_IO_OUT;
499 if (FD_ISSET (f->fd, &xset))
500 f->revents |= G_IO_PRI;
507 #endif /* !G_OS_WIN32 */
509 #endif /* !HAVE_POLL */
512 * g_main_context_ref:
513 * @context: a #GMainContext
515 * Increases the reference count on a #GMainContext object by one.
518 g_main_context_ref (GMainContext *context)
520 g_return_if_fail (context != NULL);
521 g_return_if_fail (context->ref_count > 0);
523 LOCK_CONTEXT (context);
525 context->ref_count++;
527 UNLOCK_CONTEXT (context);
531 g_main_context_unref_and_unlock (GMainContext *context)
535 context->ref_count--;
537 if (context->ref_count != 0)
539 UNLOCK_CONTEXT (context);
543 source = context->source_list;
546 GSource *next = source->next;
547 g_source_destroy_internal (source, context, TRUE);
550 UNLOCK_CONTEXT (context);
552 #ifdef G_THREADS_ENABLED
553 g_static_mutex_free (&context->mutex);
556 g_ptr_array_free (context->pending_dispatches, TRUE);
557 g_free (context->cached_poll_array);
559 g_mem_chunk_destroy (context->poll_chunk);
561 #ifdef G_THREADS_ENABLED
562 if (g_thread_supported())
565 close (context->wake_up_pipe[0]);
566 close (context->wake_up_pipe[1]);
568 CloseHandle (context->wake_up_semaphore);
577 * g_main_context_unref:
578 * @context: a #GMainContext
580 * Decreases the reference count on a #GMainContext object by one. If
581 * the result is zero, free the context and free all associated memory.
584 g_main_context_unref (GMainContext *context)
586 g_return_if_fail (context != NULL);
587 g_return_if_fail (context->ref_count > 0);
589 LOCK_CONTEXT (context);
590 g_main_context_unref_and_unlock (context);
594 * g_main_context_new:
596 * Creates a new #GMainContext strcuture
598 * Return value: the new #GMainContext
601 g_main_context_new ()
603 GMainContext *context = g_new0 (GMainContext, 1);
605 #ifdef G_THREADS_ENABLED
606 g_static_mutex_init (&context->mutex);
608 context->owner = NULL;
609 context->waiters = NULL;
612 context->ref_count = 1;
614 context->next_id = 1;
616 context->source_list = NULL;
619 context->poll_func = (GPollFunc)poll;
621 context->poll_func = g_poll;
624 context->cached_poll_array = NULL;
625 context->cached_poll_array_size = 0;
627 context->pending_dispatches = g_ptr_array_new ();
629 context->time_is_current = FALSE;
631 #ifdef G_THREADS_ENABLED
632 if (g_thread_supported ())
635 if (pipe (context->wake_up_pipe) < 0)
636 g_error ("Cannot create pipe main loop wake-up: %s\n",
639 context->wake_up_rec.fd = context->wake_up_pipe[0];
640 context->wake_up_rec.events = G_IO_IN;
641 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
643 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
644 if (context->wake_up_semaphore == NULL)
645 g_error ("Cannot create wake-up semaphore: %s",
646 g_win32_error_message (GetLastError ()));
647 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
648 context->wake_up_rec.events = G_IO_IN;
649 #ifdef G_MAIN_POLL_DEBUG
650 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
652 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
661 * g_main_context_default:
663 * Returns the default main context. This is the main context used
664 * for main loop functions when a main loop is not explicitly
667 * Return value: the default main context.
670 g_main_context_default (void)
676 if (!default_main_context)
677 default_main_context = g_main_context_new ();
679 G_UNLOCK (main_loop);
681 return default_main_context;
684 /* Hooks for adding to the main loop */
688 * @source_funcs: structure containing functions that implement
689 * the sources behavior.
690 * @struct_size: size of the #GSource structure to create.
692 * Creates a new #GSource structure. The size is specified to
693 * allow creating structures derived from #GSource that contain
694 * additional data. The size passed in must be at least
695 * <literal>sizeof (GSource)</literal>.
697 * The source will not initially be associated with any #GMainContext
698 * and must be added to one with g_source_add() before it will be
701 * Return value: the newly-created #GSource.
704 g_source_new (GSourceFuncs *source_funcs,
709 g_return_val_if_fail (source_funcs != NULL, NULL);
710 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
712 source = (GSource*) g_malloc0 (struct_size);
714 source->source_funcs = source_funcs;
715 source->ref_count = 1;
717 source->priority = G_PRIORITY_DEFAULT;
719 source->flags = G_HOOK_FLAG_ACTIVE;
721 /* NULL/0 initialization for all other fields */
726 /* Holds context's lock
729 g_source_list_add (GSource *source,
730 GMainContext *context)
732 GSource *tmp_source, *last_source;
735 tmp_source = context->source_list;
736 while (tmp_source && tmp_source->priority <= source->priority)
738 last_source = tmp_source;
739 tmp_source = tmp_source->next;
742 source->next = tmp_source;
744 tmp_source->prev = source;
746 source->prev = last_source;
748 last_source->next = source;
750 context->source_list = source;
753 /* Holds context's lock
756 g_source_list_remove (GSource *source,
757 GMainContext *context)
760 source->prev->next = source->next;
762 context->source_list = source->next;
765 source->next->prev = source->prev;
773 * @source: a #GSource
774 * @context: a #GMainContext (if %NULL, the default context will be used)
776 * Adds a #GSource to a @context so that it will be executed within
779 * Return value: the ID for the source within the #GMainContext
782 g_source_attach (GSource *source,
783 GMainContext *context)
788 g_return_val_if_fail (source->context == NULL, 0);
789 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
792 context = g_main_context_default ();
794 LOCK_CONTEXT (context);
796 source->context = context;
797 result = source->source_id = context->next_id++;
800 g_source_list_add (source, context);
802 tmp_list = source->poll_fds;
805 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
806 tmp_list = tmp_list->next;
809 #ifdef G_THREADS_ENABLED
810 /* Now wake up the main loop if it is waiting in the poll() */
811 g_main_context_wakeup_unlocked (context);
814 UNLOCK_CONTEXT (context);
820 g_source_destroy_internal (GSource *source,
821 GMainContext *context,
825 LOCK_CONTEXT (context);
827 if (!SOURCE_DESTROYED (source))
830 gpointer old_cb_data;
831 GSourceCallbackFuncs *old_cb_funcs;
833 source->flags &= ~G_HOOK_FLAG_ACTIVE;
835 old_cb_data = source->callback_data;
836 old_cb_funcs = source->callback_funcs;
838 source->callback_data = NULL;
839 source->callback_funcs = NULL;
843 UNLOCK_CONTEXT (context);
844 old_cb_funcs->unref (old_cb_data);
845 LOCK_CONTEXT (context);
848 tmp_list = source->poll_fds;
851 g_main_context_remove_poll_unlocked (context, tmp_list->data);
852 tmp_list = tmp_list->next;
855 g_source_unref_internal (source, context, TRUE);
859 UNLOCK_CONTEXT (context);
864 * @source: a #GSource
866 * Removes a source from its #GMainContext, if any, and mark it as
867 * destroyed. The source cannot be subsequently added to another
871 g_source_destroy (GSource *source)
873 GMainContext *context;
875 g_return_if_fail (source != NULL);
877 context = source->context;
880 g_source_destroy_internal (source, context, FALSE);
882 source->flags &= ~G_HOOK_FLAG_ACTIVE;
887 * @source: a #GSource
889 * Returns the numeric ID for a particular source. The ID of a source
890 * is unique within a particular main loop context. The reverse
891 * mapping from ID to source is done by g_main_context_find_source_by_id().
893 * Return value: the ID for the source
896 g_source_get_id (GSource *source)
900 g_return_val_if_fail (source != NULL, 0);
901 g_return_val_if_fail (source->context != NULL, 0);
903 LOCK_CONTEXT (source->context);
904 result = source->source_id;
905 UNLOCK_CONTEXT (source->context);
911 * g_source_get_context:
912 * @source: a #GSource
914 * Gets the #GMainContext with which the source is associated.
915 * Calling this function on a destroyed source is an error.
917 * Return value: the #GMainContext with which the source is associated,
918 * or %NULL if the context has not yet been added
922 g_source_get_context (GSource *source)
924 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
926 return source->context;
932 * @fd: a #GPollFD structure holding information about a file
933 * descriptor to watch.
935 * Adds a file descriptor to the set of file descriptors polled for
936 * this source. This is usually combined with g_source_new() to add an
937 * event source. The event source's check function will typically test
938 * the @revents field in the #GPollFD struct and return %TRUE if events need
942 g_source_add_poll (GSource *source,
945 GMainContext *context;
947 g_return_if_fail (source != NULL);
948 g_return_if_fail (fd != NULL);
949 g_return_if_fail (!SOURCE_DESTROYED (source));
951 context = source->context;
954 LOCK_CONTEXT (context);
956 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
960 g_main_context_add_poll_unlocked (context, source->priority, fd);
961 UNLOCK_CONTEXT (context);
966 * g_source_remove_poll:
968 * @fd: a #GPollFD structure previously passed to g_source_poll().
970 * Removes a file descriptor from the set of file descriptors polled for
974 g_source_remove_poll (GSource *source,
977 GMainContext *context;
979 g_return_if_fail (source != NULL);
980 g_return_if_fail (fd != NULL);
981 g_return_if_fail (!SOURCE_DESTROYED (source));
983 context = source->context;
986 LOCK_CONTEXT (context);
988 source->poll_fds = g_slist_remove (source->poll_fds, fd);
992 g_main_context_remove_poll_unlocked (context, fd);
993 UNLOCK_CONTEXT (context);
998 * g_source_set_callback_indirect:
999 * @source: the source
1000 * @callback_data: pointer to callback data "object"
1001 * @callback_funcs: functions for reference counting @callback_data
1002 * and getting the callback and data
1004 * Sets the callback function storing the data as a refcounted callback
1005 * "object". This is used to implement g_source_set_callback_closure()
1006 * and internally. Note that calling g_source_set_callback_indirect() assumes
1007 * an initial reference count on @callback_data, and thus
1008 * @callback_funcs->unref will eventually be called once more
1009 * than @callback_funcs->ref.
1012 g_source_set_callback_indirect (GSource *source,
1013 gpointer callback_data,
1014 GSourceCallbackFuncs *callback_funcs)
1016 GMainContext *context;
1017 gpointer old_cb_data;
1018 GSourceCallbackFuncs *old_cb_funcs;
1020 g_return_if_fail (source != NULL);
1021 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1023 context = source->context;
1026 LOCK_CONTEXT (context);
1028 old_cb_data = source->callback_data;
1029 old_cb_funcs = source->callback_funcs;
1031 source->callback_data = callback_data;
1032 source->callback_funcs = callback_funcs;
1035 UNLOCK_CONTEXT (context);
1038 old_cb_funcs->unref (old_cb_data);
1042 g_source_callback_ref (gpointer cb_data)
1044 GSourceCallback *callback = cb_data;
1046 callback->ref_count++;
1051 g_source_callback_unref (gpointer cb_data)
1053 GSourceCallback *callback = cb_data;
1055 callback->ref_count--;
1056 if (callback->ref_count == 0)
1058 if (callback->notify)
1059 callback->notify (callback->data);
1065 g_source_callback_get (gpointer cb_data,
1070 GSourceCallback *callback = cb_data;
1072 *func = callback->func;
1073 *data = callback->data;
1076 static GSourceCallbackFuncs g_source_callback_funcs = {
1077 g_source_callback_ref,
1078 g_source_callback_unref,
1079 g_source_callback_get,
1083 * g_source_set_callback:
1084 * @source: the source
1085 * @func: a callback function
1086 * @data: the data to pass to callback function
1087 * @notify: a function to call when @data is no longer in use, or %NULL.
1089 * Sets the callback function for a source.
1092 g_source_set_callback (GSource *source,
1095 GDestroyNotify notify)
1097 GSourceCallback *new_callback;
1099 g_return_if_fail (source != NULL);
1101 new_callback = g_new (GSourceCallback, 1);
1103 new_callback->ref_count = 1;
1104 new_callback->func = func;
1105 new_callback->data = data;
1106 new_callback->notify = notify;
1108 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1112 * g_source_set_priority:
1113 * @source: a #GSource
1114 * @priority: the new priority.
1116 * Sets the priority of a source. While the main loop is being
1117 * run, a source will be dispatched if it is ready to be dispatched and no sources
1118 * at a higher (numerically smaller) priority are ready to be dispatched.
1121 g_source_set_priority (GSource *source,
1125 GMainContext *context;
1127 g_return_if_fail (source != NULL);
1129 context = source->context;
1132 LOCK_CONTEXT (context);
1134 source->priority = priority;
1138 source->next = NULL;
1139 source->prev = NULL;
1141 tmp_list = source->poll_fds;
1144 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1145 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1147 tmp_list = tmp_list->next;
1150 UNLOCK_CONTEXT (source->context);
1155 * g_source_get_priority:
1156 * @source: a #GSource
1158 * Gets the priority of a source.
1160 * Return value: the priority of the source
1163 g_source_get_priority (GSource *source)
1165 g_return_val_if_fail (source != NULL, 0);
1167 return source->priority;
1171 * g_source_set_can_recurse:
1172 * @source: a #GSource
1173 * @can_recurse: whether recursion is allowed for this source
1175 * Sets whether a source can be called recursively. If @can_recurse is
1176 * %TRUE, then while the source is being dispatched then this source
1177 * will be processed normally. Otherwise, all processing of this
1178 * source is blocked until the dispatch function returns.
1181 g_source_set_can_recurse (GSource *source,
1182 gboolean can_recurse)
1184 GMainContext *context;
1186 g_return_if_fail (source != NULL);
1188 context = source->context;
1191 LOCK_CONTEXT (context);
1194 source->flags |= G_SOURCE_CAN_RECURSE;
1196 source->flags &= ~G_SOURCE_CAN_RECURSE;
1199 UNLOCK_CONTEXT (context);
1203 * g_source_get_can_recurse:
1204 * @source: a #GSource
1206 * Checks whether a source is allowed to be called recursively.
1207 * see g_source_set_can_recurse().
1209 * Return value: whether recursion is allowed.
1212 g_source_get_can_recurse (GSource *source)
1214 g_return_val_if_fail (source != NULL, FALSE);
1216 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1221 * @source: a #GSource
1223 * Increases the reference count on a source by one.
1225 * Return value: @source
1228 g_source_ref (GSource *source)
1230 GMainContext *context;
1232 g_return_val_if_fail (source != NULL, NULL);
1234 context = source->context;
1237 LOCK_CONTEXT (context);
1239 source->ref_count++;
1242 UNLOCK_CONTEXT (context);
1247 /* g_source_unref() but possible to call within context lock
1250 g_source_unref_internal (GSource *source,
1251 GMainContext *context,
1254 gpointer old_cb_data = NULL;
1255 GSourceCallbackFuncs *old_cb_funcs = NULL;
1257 g_return_if_fail (source != NULL);
1259 if (!have_lock && context)
1260 LOCK_CONTEXT (context);
1262 source->ref_count--;
1263 if (source->ref_count == 0)
1265 old_cb_data = source->callback_data;
1266 old_cb_funcs = source->callback_funcs;
1268 source->callback_data = NULL;
1269 source->callback_funcs = NULL;
1271 if (context && !SOURCE_DESTROYED (source))
1273 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1274 source->ref_count++;
1277 g_source_list_remove (source, context);
1279 if (source->source_funcs->finalize)
1280 source->source_funcs->finalize (source);
1282 g_slist_free (source->poll_fds);
1283 source->poll_fds = NULL;
1287 if (!have_lock && context)
1288 UNLOCK_CONTEXT (context);
1293 UNLOCK_CONTEXT (context);
1295 old_cb_funcs->unref (old_cb_data);
1298 LOCK_CONTEXT (context);
1304 * @source: a #GSource
1306 * Decreases the reference count of a source by one. If the
1307 * resulting reference count is zero the source and associated
1308 * memory will be destroyed.
1311 g_source_unref (GSource *source)
1313 g_return_if_fail (source != NULL);
1315 g_source_unref_internal (source, source->context, FALSE);
1319 * g_main_context_find_source_by_id:
1320 * @context: a #GMainContext (if %NULL, the default context will be used)
1321 * @source_id: the source ID, as returned by g_source_get_id()
1323 * Finds a #GSource given a pair of context and ID
1325 * Return value: the #GSource if found, otherwise, %NULL
1328 g_main_context_find_source_by_id (GMainContext *context,
1333 g_return_val_if_fail (source_id > 0, FALSE);
1335 if (context == NULL)
1336 context = g_main_context_default ();
1338 LOCK_CONTEXT (context);
1340 source = context->source_list;
1343 if (!SOURCE_DESTROYED (source) &&
1344 source->source_id == source_id)
1346 source = source->next;
1349 UNLOCK_CONTEXT (context);
1355 * g_main_context_find_source_by_funcs_user_data:
1356 * @context: a #GMainContext (if %NULL, the default context will be used).
1357 * @funcs: the @source_funcs passed to g_source_new().
1358 * @user_data: the user data from the callback.
1360 * Finds a source with the given source functions and user data. If
1361 * multiple sources exist with the same source function and user data,
1362 * the first one found will be returned.
1364 * Return value: the source, if one was found, otherwise %NULL
1367 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1368 GSourceFuncs *funcs,
1373 g_return_val_if_fail (funcs != NULL, FALSE);
1375 if (context == NULL)
1376 context = g_main_context_default ();
1378 LOCK_CONTEXT (context);
1380 source = context->source_list;
1383 if (!SOURCE_DESTROYED (source) &&
1384 source->source_funcs == funcs &&
1385 source->callback_funcs)
1387 GSourceFunc callback;
1388 gpointer callback_data;
1390 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1392 if (callback_data == user_data)
1395 source = source->next;
1398 UNLOCK_CONTEXT (context);
1404 * g_main_context_find_source_by_user_data:
1405 * @context: a #GMainContext
1406 * @user_data: the user_data for the callback.
1408 * Finds a source with the given user data for the callback. If
1409 * multiple sources exist with the same user data, the first
1410 * one found will be returned.
1412 * Return value: the source, if one was found, otherwise %NULL
1415 g_main_context_find_source_by_user_data (GMainContext *context,
1420 if (context == NULL)
1421 context = g_main_context_default ();
1423 LOCK_CONTEXT (context);
1425 source = context->source_list;
1428 if (!SOURCE_DESTROYED (source) &&
1429 source->callback_funcs)
1431 GSourceFunc callback;
1432 gpointer callback_data = NULL;
1434 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1436 if (callback_data == user_data)
1439 source = source->next;
1442 UNLOCK_CONTEXT (context);
1449 * @tag: the id of the source to remove.
1451 * Removes the source with the given id from the default main
1452 * context. The id of a #GSource is given by g_source_get_id(),
1453 * or will be returned by the functions g_source_attach(),
1454 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1455 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1457 * See also g_source_destroy().
1459 * Return value: %TRUE if the source was found and removed.
1462 g_source_remove (guint tag)
1466 g_return_val_if_fail (tag > 0, FALSE);
1468 source = g_main_context_find_source_by_id (NULL, tag);
1470 g_source_destroy (source);
1472 return source != NULL;
1476 * g_source_remove_by_user_data:
1477 * @user_data: the user_data for the callback.
1479 * Removes a source from the default main loop context given the user
1480 * data for the callback. If multiple sources exist with the same user
1481 * data, only one will be destroyed.
1483 * Return value: %TRUE if a source was found and removed.
1486 g_source_remove_by_user_data (gpointer user_data)
1490 source = g_main_context_find_source_by_user_data (NULL, user_data);
1493 g_source_destroy (source);
1501 * g_source_remove_by_funcs_user_data:
1502 * @funcs: The @source_funcs passed to g_source_new()
1503 * @user_data: the user data for the callback
1505 * Removes a source from the default main loop context given the
1506 * source functions and user data. If multiple sources exist with the
1507 * same source functions and user data, only one will be destroyed.
1509 * Return value: %TRUE if a source was found and removed.
1512 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1517 g_return_val_if_fail (funcs != NULL, FALSE);
1519 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1522 g_source_destroy (source);
1530 * g_get_current_time:
1531 * @result: #GTimeVal structure in which to store current time.
1533 * Equivalent to the UNIX <function>gettimeofday()</function> function, but portable.
1536 g_get_current_time (GTimeVal *result)
1541 g_return_if_fail (result != NULL);
1543 /*this is required on alpha, there the timeval structs are int's
1544 not longs and a cast only would fail horribly*/
1545 gettimeofday (&r, NULL);
1546 result->tv_sec = r.tv_sec;
1547 result->tv_usec = r.tv_usec;
1549 /* Avoid calling time() except for the first time.
1550 * GetTickCount() should be pretty fast and low-level?
1551 * I could also use ftime() but it seems unnecessarily overheady.
1553 static DWORD start_tick = 0;
1554 static time_t start_time;
1557 g_return_if_fail (result != NULL);
1559 if (start_tick == 0)
1561 start_tick = GetTickCount ();
1565 tick = GetTickCount ();
1567 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1568 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1572 /* Running the main loop */
1574 /* HOLDS: context's lock */
1576 g_main_dispatch (GMainContext *context)
1580 for (i = 0; i < context->pending_dispatches->len; i++)
1582 GSource *source = context->pending_dispatches->pdata[i];
1584 context->pending_dispatches->pdata[i] = NULL;
1587 source->flags &= ~G_SOURCE_READY;
1589 if (!SOURCE_DESTROYED (source))
1591 gboolean was_in_call;
1592 gpointer user_data = NULL;
1593 GSourceFunc callback = NULL;
1594 GSourceCallbackFuncs *cb_funcs;
1596 gboolean need_destroy;
1598 gboolean (*dispatch) (GSource *,
1602 dispatch = source->source_funcs->dispatch;
1603 cb_funcs = source->callback_funcs;
1604 cb_data = source->callback_data;
1607 cb_funcs->ref (cb_data);
1609 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1610 source->flags |= G_HOOK_FLAG_IN_CALL;
1613 cb_funcs->get (cb_data, source, &callback, &user_data);
1615 UNLOCK_CONTEXT (context);
1617 need_destroy = ! dispatch (source,
1620 LOCK_CONTEXT (context);
1623 cb_funcs->unref (cb_data);
1626 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1628 /* Note: this depends on the fact that we can't switch
1629 * sources from one main context to another
1631 if (need_destroy && !SOURCE_DESTROYED (source))
1633 g_assert (source->context == context);
1634 g_source_destroy_internal (source, context, TRUE);
1638 SOURCE_UNREF (source, context);
1641 g_ptr_array_set_size (context->pending_dispatches, 0);
1644 /* Holds context's lock */
1645 static inline GSource *
1646 next_valid_source (GMainContext *context,
1649 GSource *new_source = source ? source->next : context->source_list;
1653 if (!SOURCE_DESTROYED (new_source))
1655 new_source->ref_count++;
1659 new_source = new_source->next;
1663 SOURCE_UNREF (source, context);
1669 * g_main_context_acquire:
1670 * @context: a #GMainContext
1672 * Tries to become the owner of the specified context.
1673 * If some other context is the owner of the context,
1674 * returns %FALSE immediately. Ownership is properly
1675 * recursive: the owner can require ownership again
1676 * and will release ownership when g_main_context_release()
1677 * is called as many times as g_main_context_acquire().
1679 * You must be the owner of a context before you
1680 * can call g_main_context_prepare(), g_main_context_query(),
1681 * g_main_context_check(), g_main_context_dispatch().
1683 * Return value: %TRUE if the operation succeeded, and
1684 * this thread is now the owner of @context.
1687 g_main_context_acquire (GMainContext *context)
1689 #ifdef G_THREADS_ENABLED
1690 gboolean result = FALSE;
1691 GThread *self = G_THREAD_SELF;
1693 if (context == NULL)
1694 context = g_main_context_default ();
1696 LOCK_CONTEXT (context);
1698 if (!context->owner)
1700 context->owner = self;
1701 g_assert (context->owner_count == 0);
1704 if (context->owner == self)
1706 context->owner_count++;
1710 UNLOCK_CONTEXT (context);
1713 #else /* !G_THREADS_ENABLED */
1715 #endif /* G_THREADS_ENABLED */
1719 * g_main_context_release:
1720 * @context: a #GMainContext
1722 * Releases ownership of a context previously acquired by this thread
1723 * with g_main_context_acquire(). If the context was acquired multiple
1724 * times, the only release ownership when g_main_context_release()
1725 * is called as many times as it was acquired.
1728 g_main_context_release (GMainContext *context)
1730 #ifdef G_THREADS_ENABLED
1731 if (context == NULL)
1732 context = g_main_context_default ();
1734 LOCK_CONTEXT (context);
1736 context->owner_count--;
1737 if (context->owner_count == 0)
1739 context->owner = NULL;
1741 if (context->waiters)
1743 GMainWaiter *waiter = context->waiters->data;
1744 gboolean loop_internal_waiter =
1745 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1746 context->waiters = g_slist_delete_link (context->waiters,
1748 if (!loop_internal_waiter)
1749 g_mutex_lock (waiter->mutex);
1751 g_cond_signal (waiter->cond);
1753 if (!loop_internal_waiter)
1754 g_mutex_unlock (waiter->mutex);
1758 UNLOCK_CONTEXT (context);
1759 #endif /* G_THREADS_ENABLED */
1763 * g_main_context_wait:
1764 * @context: a #GMainContext
1765 * @cond: a condition variable
1766 * @mutex: a mutex, currently held
1768 * Tries to become the owner of the specified context,
1769 * as with g_main_context_acquire(). But if another thread
1770 * is the owner, atomically drop @mutex and wait on @cond until
1771 * that owner releases ownership or until @cond is signaled, then
1772 * try again (once) to become the owner.
1774 * Return value: %TRUE if the operation succeeded, and
1775 * this thread is now the owner of @context.
1778 g_main_context_wait (GMainContext *context,
1782 #ifdef G_THREADS_ENABLED
1783 gboolean result = FALSE;
1784 GThread *self = G_THREAD_SELF;
1785 gboolean loop_internal_waiter;
1787 if (context == NULL)
1788 context = g_main_context_default ();
1790 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
1792 if (!loop_internal_waiter)
1793 LOCK_CONTEXT (context);
1795 if (context->owner && context->owner != self)
1800 waiter.mutex = mutex;
1802 context->waiters = g_slist_append (context->waiters, &waiter);
1804 if (!loop_internal_waiter)
1805 UNLOCK_CONTEXT (context);
1806 g_cond_wait (cond, mutex);
1807 if (!loop_internal_waiter)
1808 LOCK_CONTEXT (context);
1810 context->waiters = g_slist_remove (context->waiters, &waiter);
1813 if (!context->owner)
1815 context->owner = self;
1816 g_assert (context->owner_count == 0);
1819 if (context->owner == self)
1821 context->owner_count++;
1825 if (!loop_internal_waiter)
1826 UNLOCK_CONTEXT (context);
1829 #else /* !G_THREADS_ENABLED */
1831 #endif /* G_THREADS_ENABLED */
1835 * g_main_context_prepare:
1836 * @context: a #GMainContext
1837 * @priority: location to store priority of highest priority
1838 * source already ready.
1840 * Prepares to poll sources within a main loop. The resulting information
1841 * for polling is determined by calling g_main_context_query ().
1843 * Return value: %TRUE if some source is ready to be dispatched
1847 g_main_context_prepare (GMainContext *context,
1852 gint current_priority = G_MAXINT;
1855 if (context == NULL)
1856 context = g_main_context_default ();
1858 LOCK_CONTEXT (context);
1860 context->time_is_current = FALSE;
1862 if (context->in_check_or_prepare)
1864 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1865 "prepare() member.");
1866 UNLOCK_CONTEXT (context);
1870 #ifdef G_THREADS_ENABLED
1871 if (context->poll_waiting)
1873 g_warning("g_main_context_prepare(): main loop already active in another thread");
1874 UNLOCK_CONTEXT (context);
1878 context->poll_waiting = TRUE;
1879 #endif /* G_THREADS_ENABLED */
1882 /* If recursing, finish up current dispatch, before starting over */
1883 if (context->pending_dispatches)
1886 g_main_dispatch (context, ¤t_time);
1888 UNLOCK_CONTEXT (context);
1893 /* If recursing, clear list of pending dispatches */
1895 for (i = 0; i < context->pending_dispatches->len; i++)
1897 if (context->pending_dispatches->pdata[i])
1898 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
1900 g_ptr_array_set_size (context->pending_dispatches, 0);
1902 /* Prepare all sources */
1904 context->timeout = -1;
1906 source = next_valid_source (context, NULL);
1909 gint source_timeout = -1;
1911 if ((n_ready > 0) && (source->priority > current_priority))
1913 SOURCE_UNREF (source, context);
1916 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1919 if (!(source->flags & G_SOURCE_READY))
1922 gboolean (*prepare) (GSource *source,
1925 prepare = source->source_funcs->prepare;
1926 context->in_check_or_prepare++;
1927 UNLOCK_CONTEXT (context);
1929 result = (*prepare) (source, &source_timeout);
1931 LOCK_CONTEXT (context);
1932 context->in_check_or_prepare--;
1935 source->flags |= G_SOURCE_READY;
1938 if (source->flags & G_SOURCE_READY)
1941 current_priority = source->priority;
1942 context->timeout = 0;
1945 if (source_timeout >= 0)
1947 if (context->timeout < 0)
1948 context->timeout = source_timeout;
1950 context->timeout = MIN (context->timeout, source_timeout);
1954 source = next_valid_source (context, source);
1957 UNLOCK_CONTEXT (context);
1960 *priority = current_priority;
1962 return (n_ready > 0);
1966 * g_main_context_query:
1967 * @context: a #GMainContext
1968 * @max_priority: maximum priority source to check
1969 * @timeout: location to store timeout to be used in polling
1970 * @fds: location to store #GPollFD records that need to be polled.
1971 * @n_fds: length of @fds.
1973 * Determines information necessary to poll this main loop.
1975 * Return value: the number of records actually stored in @fds,
1976 * or, if more than @n_fds records need to be stored, the number
1977 * of records that need to be stored.
1980 g_main_context_query (GMainContext *context,
1989 LOCK_CONTEXT (context);
1991 pollrec = context->poll_records;
1993 while (pollrec && max_priority >= pollrec->priority)
1995 if (pollrec->fd->events)
1999 fds[n_poll].fd = pollrec->fd->fd;
2000 /* In direct contradiction to the Unix98 spec, IRIX runs into
2001 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2002 * flags in the events field of the pollfd while it should
2003 * just ignoring them. So we mask them out here.
2005 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2006 fds[n_poll].revents = 0;
2011 pollrec = pollrec->next;
2014 #ifdef G_THREADS_ENABLED
2015 context->poll_changed = FALSE;
2020 *timeout = context->timeout;
2022 context->time_is_current = FALSE;
2025 UNLOCK_CONTEXT (context);
2031 * g_main_context_check:
2032 * @context: a #GMainContext
2033 * @max_priority: the maximum numerical priority of sources to check
2034 * @fds: array of #GPollFD's that was passed to the last call to
2035 * g_main_context_query()
2036 * @n_fds: return value of g_main_context_query()
2038 * Passes the results of polling back to the main loop.
2040 * Return value: %TRUE if some sources are ready to be dispatched.
2043 g_main_context_check (GMainContext *context,
2053 LOCK_CONTEXT (context);
2055 if (context->in_check_or_prepare)
2057 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2058 "prepare() member.");
2059 UNLOCK_CONTEXT (context);
2063 #ifdef G_THREADS_ENABLED
2064 if (!context->poll_waiting)
2068 read (context->wake_up_pipe[0], &c, 1);
2072 context->poll_waiting = FALSE;
2074 /* If the set of poll file descriptors changed, bail out
2075 * and let the main loop rerun
2077 if (context->poll_changed)
2079 UNLOCK_CONTEXT (context);
2082 #endif /* G_THREADS_ENABLED */
2084 pollrec = context->poll_records;
2088 if (pollrec->fd->events)
2090 pollrec->fd->revents = fds[i].revents;
2093 pollrec = pollrec->next;
2096 source = next_valid_source (context, NULL);
2099 if ((n_ready > 0) && (source->priority > max_priority))
2101 SOURCE_UNREF (source, context);
2104 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2107 if (!(source->flags & G_SOURCE_READY))
2110 gboolean (*check) (GSource *source);
2112 check = source->source_funcs->check;
2114 context->in_check_or_prepare++;
2115 UNLOCK_CONTEXT (context);
2117 result = (*check) (source);
2119 LOCK_CONTEXT (context);
2120 context->in_check_or_prepare--;
2123 source->flags |= G_SOURCE_READY;
2126 if (source->flags & G_SOURCE_READY)
2128 source->ref_count++;
2129 g_ptr_array_add (context->pending_dispatches, source);
2133 /* never dispatch sources with less priority than the first
2134 * one we choose to dispatch
2136 max_priority = source->priority;
2140 source = next_valid_source (context, source);
2143 UNLOCK_CONTEXT (context);
2149 * g_main_context_dispatch:
2150 * @context: a #GMainContext
2152 * Dispatches all pending sources.
2155 g_main_context_dispatch (GMainContext *context)
2157 LOCK_CONTEXT (context);
2159 if (context->pending_dispatches->len > 0)
2161 g_main_dispatch (context);
2164 UNLOCK_CONTEXT (context);
2167 /* HOLDS context lock */
2169 g_main_context_iterate (GMainContext *context,
2176 gboolean some_ready;
2177 gint nfds, allocated_nfds;
2178 GPollFD *fds = NULL;
2180 UNLOCK_CONTEXT (context);
2182 #ifdef G_THREADS_ENABLED
2183 if (!g_main_context_acquire (context))
2185 gboolean got_ownership;
2187 g_return_val_if_fail (g_thread_supported (), FALSE);
2192 LOCK_CONTEXT (context);
2195 context->cond = g_cond_new ();
2197 got_ownership = g_main_context_wait (context,
2199 g_static_mutex_get_mutex (&context->mutex));
2203 UNLOCK_CONTEXT (context);
2208 LOCK_CONTEXT (context);
2209 #endif /* G_THREADS_ENABLED */
2211 if (!context->cached_poll_array)
2213 context->cached_poll_array_size = context->n_poll_records;
2214 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2217 allocated_nfds = context->cached_poll_array_size;
2218 fds = context->cached_poll_array;
2220 UNLOCK_CONTEXT (context);
2222 some_ready = g_main_context_prepare (context, &max_priority);
2224 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2225 allocated_nfds)) > allocated_nfds)
2227 LOCK_CONTEXT (context);
2229 context->cached_poll_array_size = allocated_nfds = nfds;
2230 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2231 UNLOCK_CONTEXT (context);
2237 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2239 g_main_context_check (context, max_priority, fds, nfds);
2242 g_main_context_dispatch (context);
2244 #ifdef G_THREADS_ENABLED
2245 g_main_context_release (context);
2246 #endif /* G_THREADS_ENABLED */
2248 LOCK_CONTEXT (context);
2254 * g_main_context_pending:
2255 * @context: a #GMainContext (if %NULL, the default context will be used)
2257 * Checks if any sources have pending events for the given context.
2259 * Return value: %TRUE if events are pending.
2262 g_main_context_pending (GMainContext *context)
2267 context = g_main_context_default();
2269 LOCK_CONTEXT (context);
2270 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2271 UNLOCK_CONTEXT (context);
2277 * g_main_context_iteration:
2278 * @context: a #GMainContext (if %NULL, the default context will be used)
2279 * @may_block: whether the call may block.
2281 * Runs a single iteration for the given main loop. This involves
2282 * checking to see if any event sources are ready to be processed,
2283 * then if no events sources are ready and @may_block is %TRUE, waiting
2284 * for a source to become ready, then dispatching the highest priority
2285 * events sources that are ready. Note that even when @may_block is %TRUE,
2286 * it is still possible for g_main_context_iteration() to return
2287 * %FALSE, since the the wait may be interrupted for other
2288 * reasons than an event source becoming ready.
2290 * Return value: %TRUE if events were dispatched.
2293 g_main_context_iteration (GMainContext *context, gboolean may_block)
2298 context = g_main_context_default();
2300 LOCK_CONTEXT (context);
2301 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2302 UNLOCK_CONTEXT (context);
2309 * @context: a #GMainContext (if %NULL, the default context will be used).
2310 * @is_running: set to %TRUE to indicate that the loop is running. This
2311 * is not very important since calling g_main_loop_run() will set this to
2314 * Creates a new #GMainLoop structure.
2316 * Return value: a new #GMainLoop.
2319 g_main_loop_new (GMainContext *context,
2320 gboolean is_running)
2325 context = g_main_context_default();
2327 g_main_context_ref (context);
2329 loop = g_new0 (GMainLoop, 1);
2330 loop->context = context;
2331 loop->is_running = is_running != FALSE;
2332 loop->ref_count = 1;
2339 * @loop: a #GMainLoop
2341 * Increases the reference count on a #GMainLoop object by one.
2343 * Return value: @loop
2346 g_main_loop_ref (GMainLoop *loop)
2348 g_return_val_if_fail (loop != NULL, NULL);
2349 g_return_val_if_fail (loop->ref_count > 0, NULL);
2351 LOCK_CONTEXT (loop->context);
2353 UNLOCK_CONTEXT (loop->context);
2359 g_main_loop_unref_and_unlock (GMainLoop *loop)
2362 if (loop->ref_count == 0)
2364 /* When the ref_count is 0, there can be nobody else using the
2365 * loop, so it is safe to unlock before destroying.
2367 g_main_context_unref_and_unlock (loop->context);
2371 UNLOCK_CONTEXT (loop->context);
2375 * g_main_loop_unref:
2376 * @loop: a #GMainLoop
2378 * Decreases the reference count on a #GMainLoop object by one. If
2379 * the result is zero, free the loop and free all associated memory.
2382 g_main_loop_unref (GMainLoop *loop)
2384 g_return_if_fail (loop != NULL);
2385 g_return_if_fail (loop->ref_count > 0);
2387 LOCK_CONTEXT (loop->context);
2389 g_main_loop_unref_and_unlock (loop);
2394 * @loop: a #GMainLoop
2396 * Runs a main loop until g_main_loop_quit() is called on the loop.
2397 * If this is called for the thread of the loop's #GMainContext,
2398 * it will process events from the loop, otherwise it will
2402 g_main_loop_run (GMainLoop *loop)
2404 GThread *self = G_THREAD_SELF;
2406 g_return_if_fail (loop != NULL);
2407 g_return_if_fail (loop->ref_count > 0);
2409 #ifdef G_THREADS_ENABLED
2410 if (!g_main_context_acquire (loop->context))
2412 gboolean got_ownership = FALSE;
2414 /* Another thread owns this context */
2415 if (!g_thread_supported ())
2417 g_warning ("g_main_loop_run() was called from second thread but "
2418 "g_thread_init() was never called.");
2422 LOCK_CONTEXT (loop->context);
2426 if (!loop->is_running)
2427 loop->is_running = TRUE;
2429 if (!loop->context->cond)
2430 loop->context->cond = g_cond_new ();
2432 while (loop->is_running || !got_ownership)
2433 got_ownership = g_main_context_wait (loop->context,
2434 loop->context->cond,
2435 g_static_mutex_get_mutex (&loop->context->mutex));
2437 if (!loop->is_running)
2439 UNLOCK_CONTEXT (loop->context);
2441 g_main_context_release (loop->context);
2442 g_main_loop_unref (loop);
2446 g_assert (got_ownership);
2449 LOCK_CONTEXT (loop->context);
2450 #endif /* G_THREADS_ENABLED */
2452 if (loop->context->in_check_or_prepare)
2454 g_warning ("g_main_loop_run(): called recursively from within a source's "
2455 "check() or prepare() member, iteration not possible.");
2460 loop->is_running = TRUE;
2461 while (loop->is_running)
2462 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2464 UNLOCK_CONTEXT (loop->context);
2466 #ifdef G_THREADS_ENABLED
2467 g_main_context_release (loop->context);
2468 #endif /* G_THREADS_ENABLED */
2470 g_main_loop_unref (loop);
2475 * @loop: a #GMainLoop
2477 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2478 * for the loop will return.
2481 g_main_loop_quit (GMainLoop *loop)
2483 g_return_if_fail (loop != NULL);
2484 g_return_if_fail (loop->ref_count > 0);
2486 LOCK_CONTEXT (loop->context);
2487 loop->is_running = FALSE;
2488 g_main_context_wakeup_unlocked (loop->context);
2490 #ifdef G_THREADS_ENABLED
2491 if (loop->context->cond)
2492 g_cond_broadcast (loop->context->cond);
2493 #endif /* G_THREADS_ENABLED */
2495 UNLOCK_CONTEXT (loop->context);
2499 * g_main_loop_is_running:
2500 * @loop: a #GMainLoop.
2502 * Checks to see if the main loop is currently being run via g_main_loop_run().
2504 * Return value: %TRUE if the mainloop is currently being run.
2507 g_main_loop_is_running (GMainLoop *loop)
2509 g_return_val_if_fail (loop != NULL, FALSE);
2510 g_return_val_if_fail (loop->ref_count > 0, FALSE);
2512 return loop->is_running;
2516 * g_main_loop_get_context:
2517 * @loop: a #GMainLoop.
2519 * Returns the #GMainContext of @loop.
2521 * Return value: the #GMainContext of @loop
2524 g_main_loop_get_context (GMainLoop *loop)
2526 g_return_val_if_fail (loop != NULL, NULL);
2527 g_return_val_if_fail (loop->ref_count > 0, NULL);
2529 return loop->context;
2532 /* HOLDS: context's lock */
2534 g_main_context_poll (GMainContext *context,
2540 #ifdef G_MAIN_POLL_DEBUG
2546 GPollFunc poll_func;
2548 if (n_fds || timeout != 0)
2550 #ifdef G_MAIN_POLL_DEBUG
2551 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2552 poll_timer = g_timer_new ();
2555 LOCK_CONTEXT (context);
2557 poll_func = context->poll_func;
2559 UNLOCK_CONTEXT (context);
2560 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2561 g_warning ("poll(2) failed due to: %s.",
2562 g_strerror (errno));
2564 #ifdef G_MAIN_POLL_DEBUG
2565 LOCK_CONTEXT (context);
2567 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2570 g_timer_elapsed (poll_timer, NULL));
2571 g_timer_destroy (poll_timer);
2572 pollrec = context->poll_records;
2576 if (pollrec->fd->events)
2580 g_print (" [%d:", fds[i].fd);
2581 if (fds[i].revents & G_IO_IN)
2583 if (fds[i].revents & G_IO_OUT)
2585 if (fds[i].revents & G_IO_PRI)
2587 if (fds[i].revents & G_IO_ERR)
2589 if (fds[i].revents & G_IO_HUP)
2591 if (fds[i].revents & G_IO_NVAL)
2597 pollrec = pollrec->next;
2601 UNLOCK_CONTEXT (context);
2603 } /* if (n_fds || timeout != 0) */
2607 * g_main_context_add_poll:
2608 * @context: a #GMainContext (or %NULL for the default context)
2609 * @fd: a #GPollFD structure holding information about a file
2610 * descriptor to watch.
2611 * @priority: the priority for this file descriptor which should be
2612 * the same as the priority used for g_source_attach() to ensure that the
2613 * file descriptor is polled whenever the results may be needed.
2615 * Adds a file descriptor to the set of file descriptors polled for
2616 * this context. This will very seldomly be used directly. Instead
2617 * a typical event source will use g_source_add_poll() instead.
2620 g_main_context_add_poll (GMainContext *context,
2625 context = g_main_context_default ();
2627 g_return_if_fail (context->ref_count > 0);
2628 g_return_if_fail (fd);
2630 LOCK_CONTEXT (context);
2631 g_main_context_add_poll_unlocked (context, priority, fd);
2632 UNLOCK_CONTEXT (context);
2635 /* HOLDS: main_loop_lock */
2637 g_main_context_add_poll_unlocked (GMainContext *context,
2641 GPollRec *lastrec, *pollrec, *newrec;
2643 if (!context->poll_chunk)
2644 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2646 if (context->poll_free_list)
2648 newrec = context->poll_free_list;
2649 context->poll_free_list = newrec->next;
2652 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2654 /* This file descriptor may be checked before we ever poll */
2657 newrec->priority = priority;
2660 pollrec = context->poll_records;
2661 while (pollrec && priority >= pollrec->priority)
2664 pollrec = pollrec->next;
2668 lastrec->next = newrec;
2670 context->poll_records = newrec;
2672 newrec->next = pollrec;
2674 context->n_poll_records++;
2676 #ifdef G_THREADS_ENABLED
2677 context->poll_changed = TRUE;
2679 /* Now wake up the main loop if it is waiting in the poll() */
2680 g_main_context_wakeup_unlocked (context);
2685 * g_main_context_remove_poll:
2686 * @context:a #GMainContext
2687 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2689 * Removes file descriptor from the set of file descriptors to be
2690 * polled for a particular context.
2693 g_main_context_remove_poll (GMainContext *context,
2697 context = g_main_context_default ();
2699 g_return_if_fail (context->ref_count > 0);
2700 g_return_if_fail (fd);
2702 LOCK_CONTEXT (context);
2703 g_main_context_remove_poll_unlocked (context, fd);
2704 UNLOCK_CONTEXT (context);
2708 g_main_context_remove_poll_unlocked (GMainContext *context,
2711 GPollRec *pollrec, *lastrec;
2714 pollrec = context->poll_records;
2718 if (pollrec->fd == fd)
2720 if (lastrec != NULL)
2721 lastrec->next = pollrec->next;
2723 context->poll_records = pollrec->next;
2725 #ifdef ENABLE_GC_FRIENDLY
2727 #endif /* ENABLE_GC_FRIENDLY */
2729 pollrec->next = context->poll_free_list;
2730 context->poll_free_list = pollrec;
2732 context->n_poll_records--;
2736 pollrec = pollrec->next;
2739 #ifdef G_THREADS_ENABLED
2740 context->poll_changed = TRUE;
2742 /* Now wake up the main loop if it is waiting in the poll() */
2743 g_main_context_wakeup_unlocked (context);
2748 * g_source_get_current_time:
2749 * @source: a #GSource
2750 * @timeval: #GTimeVal structure in which to store current time.
2752 * Gets the "current time" to be used when checking
2753 * this source. The advantage of calling this function over
2754 * calling g_get_current_time() directly is that when
2755 * checking multiple sources, GLib can cache a single value
2756 * instead of having to repeatedly get the system time.
2759 g_source_get_current_time (GSource *source,
2762 GMainContext *context;
2764 g_return_if_fail (source->context != NULL);
2766 context = source->context;
2768 LOCK_CONTEXT (context);
2770 if (!context->time_is_current)
2772 g_get_current_time (&context->current_time);
2773 context->time_is_current = TRUE;
2776 *timeval = context->current_time;
2778 UNLOCK_CONTEXT (context);
2782 * g_main_context_set_poll_func:
2783 * @context: a #GMainContext
2784 * @func: the function to call to poll all file descriptors
2786 * Sets the function to use to handle polling of file descriptors. It
2787 * will be used instead of the <function>poll()</function> system call
2788 * (or GLib's replacement function, which is used where
2789 * <function>poll()</function> isn't available).
2791 * This function could possibly be used to integrate the GLib event
2792 * loop with an external event loop.
2795 g_main_context_set_poll_func (GMainContext *context,
2799 context = g_main_context_default ();
2801 g_return_if_fail (context->ref_count > 0);
2803 LOCK_CONTEXT (context);
2806 context->poll_func = func;
2810 context->poll_func = (GPollFunc) poll;
2812 context->poll_func = (GPollFunc) g_poll;
2816 UNLOCK_CONTEXT (context);
2820 * g_main_context_get_poll_func:
2821 * @context: a #GMainContext
2823 * Gets the poll function set by g_main_context_set_poll_func().
2825 * Return value: the poll function
2828 g_main_context_get_poll_func (GMainContext *context)
2833 context = g_main_context_default ();
2835 g_return_val_if_fail (context->ref_count > 0, NULL);
2837 LOCK_CONTEXT (context);
2838 result = context->poll_func;
2839 UNLOCK_CONTEXT (context);
2844 /* HOLDS: context's lock */
2845 /* Wake the main loop up from a poll() */
2847 g_main_context_wakeup_unlocked (GMainContext *context)
2849 #ifdef G_THREADS_ENABLED
2850 if (g_thread_supported() && context->poll_waiting)
2852 context->poll_waiting = FALSE;
2854 write (context->wake_up_pipe[1], "A", 1);
2856 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2863 * g_main_context_wakeup:
2864 * @context: a #GMainContext
2866 * If @context is currently waiting in a <function>poll()</function>, interrupt
2867 * the <function>poll()</function>, and continue the iteration process.
2870 g_main_context_wakeup (GMainContext *context)
2873 context = g_main_context_default ();
2875 g_return_if_fail (context->ref_count > 0);
2877 LOCK_CONTEXT (context);
2878 g_main_context_wakeup_unlocked (context);
2879 UNLOCK_CONTEXT (context);
2885 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2886 GTimeVal *current_time)
2888 guint seconds = timeout_source->interval / 1000;
2889 guint msecs = timeout_source->interval - seconds * 1000;
2891 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2892 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2893 if (timeout_source->expiration.tv_usec >= 1000000)
2895 timeout_source->expiration.tv_usec -= 1000000;
2896 timeout_source->expiration.tv_sec++;
2901 g_timeout_prepare (GSource *source,
2906 GTimeVal current_time;
2908 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2910 g_source_get_current_time (source, ¤t_time);
2912 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
2913 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
2915 /* We do the following in a rather convoluted fashion to deal with
2916 * the fact that we don't have an integral type big enough to hold
2917 * the difference of two timevals in millseconds.
2919 if (sec < 0 || (sec == 0 && msec < 0))
2923 glong interval_sec = timeout_source->interval / 1000;
2924 glong interval_msec = timeout_source->interval % 1000;
2932 if (sec > interval_sec ||
2933 (sec == interval_sec && msec > interval_msec))
2935 /* The system time has been set backwards, so we
2936 * reset the expiration time to now + timeout_source->interval;
2937 * this at least avoids hanging for long periods of time.
2939 g_timeout_set_expiration (timeout_source, ¤t_time);
2940 msec = timeout_source->interval;
2948 *timeout = (gint)msec;
2954 g_timeout_check (GSource *source)
2956 GTimeVal current_time;
2957 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2959 g_source_get_current_time (source, ¤t_time);
2961 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2962 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2963 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2967 g_timeout_dispatch (GSource *source,
2968 GSourceFunc callback,
2971 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2975 g_warning ("Timeout source dispatched without callback\n"
2976 "You must call g_source_set_callback().");
2980 if (callback (user_data))
2982 GTimeVal current_time;
2984 g_source_get_current_time (source, ¤t_time);
2985 g_timeout_set_expiration (timeout_source, ¤t_time);
2994 * g_timeout_source_new:
2995 * @interval: the timeout interval in milliseconds.
2997 * Creates a new timeout source.
2999 * The source will not initially be associated with any #GMainContext
3000 * and must be added to one with g_source_attach() before it will be
3003 * Return value: the newly-created timeout source
3006 g_timeout_source_new (guint interval)
3008 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3009 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3010 GTimeVal current_time;
3012 timeout_source->interval = interval;
3014 g_get_current_time (¤t_time);
3015 g_timeout_set_expiration (timeout_source, ¤t_time);
3021 * g_timeout_add_full:
3022 * @priority: the priority of the idle source. Typically this will be in the
3023 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3024 * @interval: the time between calls to the function, in milliseconds
3025 * (1/1000ths of a second)
3026 * @function: function to call
3027 * @data: data to pass to @function
3028 * @notify: function to call when the idle is removed, or %NULL
3030 * Sets a function to be called at regular intervals, with the given
3031 * priority. The function is called repeatedly until it returns
3032 * %FALSE, at which point the timeout is automatically destroyed and
3033 * the function will not be called again. The @notify function is
3034 * called when the timeout is destroyed. The first call to the
3035 * function will be at the end of the first @interval.
3037 * Note that timeout functions may be delayed, due to the processing of other
3038 * event sources. Thus they should not be relied on for precise timing.
3039 * After each call to the timeout function, the time of the next
3040 * timeout is recalculated based on the current time and the given interval
3041 * (it does not try to 'catch up' time lost in delays).
3043 * Return value: the id of event source.
3046 g_timeout_add_full (gint priority,
3048 GSourceFunc function,
3050 GDestroyNotify notify)
3055 g_return_val_if_fail (function != NULL, 0);
3057 source = g_timeout_source_new (interval);
3059 if (priority != G_PRIORITY_DEFAULT)
3060 g_source_set_priority (source, priority);
3062 g_source_set_callback (source, function, data, notify);
3063 id = g_source_attach (source, NULL);
3064 g_source_unref (source);
3071 * @interval: the time between calls to the function, in milliseconds
3072 * (1/1000ths of a second)
3073 * @function: function to call
3074 * @data: data to pass to @function
3076 * Sets a function to be called at regular intervals, with the default
3077 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3078 * until it returns %FALSE, at which point the timeout is automatically
3079 * destroyed and the function will not be called again. The @notify
3080 * function is called when the timeout is destroyed. The first call
3081 * to the function will be at the end of the first @interval.
3083 * Note that timeout functions may be delayed, due to the processing of other
3084 * event sources. Thus they should not be relied on for precise timing.
3085 * After each call to the timeout function, the time of the next
3086 * timeout is recalculated based on the current time and the given interval
3087 * (it does not try to 'catch up' time lost in delays).
3089 * Return value: the id of event source.
3092 g_timeout_add (guint32 interval,
3093 GSourceFunc function,
3096 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3097 interval, function, data, NULL);
3100 /* Idle functions */
3103 g_idle_prepare (GSource *source,
3112 g_idle_check (GSource *source)
3118 g_idle_dispatch (GSource *source,
3119 GSourceFunc callback,
3124 g_warning ("Idle source dispatched without callback\n"
3125 "You must call g_source_set_callback().");
3129 return callback (user_data);
3133 * g_idle_source_new:
3135 * Creates a new idle source.
3137 * The source will not initially be associated with any #GMainContext
3138 * and must be added to one with g_source_attach() before it will be
3141 * Return value: the newly-created idle source
3144 g_idle_source_new (void)
3146 return g_source_new (&g_idle_funcs, sizeof (GSource));
3151 * @priority: the priority of the idle source. Typically this will be in the
3152 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3153 * @function: function to call
3154 * @data: data to pass to @function
3155 * @notify: function to call when the idle is removed, or %NULL
3157 * Adds a function to be called whenever there are no higher priority
3158 * events pending. If the function returns %FALSE it is automatically
3159 * removed from the list of event sources and will not be called again.
3161 * Return value: the id of the event source.
3164 g_idle_add_full (gint priority,
3165 GSourceFunc function,
3167 GDestroyNotify notify)
3172 g_return_val_if_fail (function != NULL, 0);
3174 source = g_idle_source_new ();
3176 if (priority != G_PRIORITY_DEFAULT)
3177 g_source_set_priority (source, priority);
3179 g_source_set_callback (source, function, data, notify);
3180 id = g_source_attach (source, NULL);
3181 g_source_unref (source);
3188 * @function: function to call
3189 * @data: data to pass to @function.
3191 * Adds a function to be called whenever there are no higher priority
3192 * events pending to the default main loop. The function is given the
3193 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3194 * returns %FALSE it is automatically removed from the list of event
3195 * sources and will not be called again.
3197 * Return value: the id of the event source.
3200 g_idle_add (GSourceFunc function,
3203 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3207 * g_idle_remove_by_data:
3208 * @data: the data for the idle source's callback.
3210 * Removes the idle function with the given data.
3212 * Return value: %TRUE if an idle source was found and removed.
3215 g_idle_remove_by_data (gpointer data)
3217 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);