1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
36 /* uncomment the next line to get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
40 #include <sys/types.h>
42 #ifdef HAVE_SYS_TIME_H
44 #endif /* HAVE_SYS_TIME_H */
45 #ifdef GLIB_HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
48 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
49 #endif /* GLIB_HAVE_SYS_POLL_H */
52 #endif /* HAVE_UNISTD_H */
58 #endif /* G_OS_WIN32 */
61 #include <net/socket.h>
62 #endif /* G_OS_BEOS */
66 typedef struct _GTimeoutSource GTimeoutSource;
67 typedef struct _GPollRec GPollRec;
68 typedef struct _GSourceCallback GSourceCallback;
72 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
73 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
78 #ifdef G_THREADS_ENABLED
79 /* The following lock is used for both the list of sources
80 * and the list of poll records
86 GPtrArray *pending_dispatches;
87 gint timeout; /* Timeout for current iteration */
91 gint in_check_or_prepare;
93 GPollRec *poll_records;
94 GPollRec *poll_free_list;
95 GMemChunk *poll_chunk;
97 GPollFD *cached_poll_array;
98 gint cached_poll_array_size;
100 #ifdef G_THREADS_ENABLED
102 /* this pipe is used to wake up the main loop when a source is added.
104 gint wake_up_pipe[2];
105 #else /* G_OS_WIN32 */
106 HANDLE wake_up_semaphore;
107 #endif /* G_OS_WIN32 */
110 gboolean poll_waiting;
112 /* Flag indicating whether the set of fd's changed during a poll */
113 gboolean poll_changed;
114 #endif /* G_THREADS_ENABLED */
118 GTimeVal current_time;
119 gboolean time_is_current;
122 struct _GSourceCallback
127 GDestroyNotify notify;
132 GMainContext *context;
136 #ifdef G_THREADS_ENABLED
139 #endif /* G_THREADS_ENABLED */
142 struct _GTimeoutSource
156 #ifdef G_THREADS_ENABLED
157 #define LOCK_CONTEXT(context) g_mutex_lock(context->mutex)
158 #define UNLOCK_CONTEXT(context) g_mutex_unlock(context->mutex)
159 #define LOCK_LOOP(loop) g_mutex_lock(loop->mutex)
160 #define UNLOCK_LOOP(loop) g_mutex_unlock(loop->mutex)
162 #define LOCK_CONTEXT(context) (void)0
163 #define UNLOCK_CONTEXT(context) (void)0
164 #define LOCK_LOOP(context) (void)0
165 #define UNLOCK_LOOP(context) (void)0
168 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
170 #define SOURCE_UNREF(source, context) \
172 if ((source)->ref_count > 1) \
173 (source)->ref_count--; \
175 g_source_unref_internal ((source), (context), TRUE); \
179 /* Forward declarations */
181 static void g_source_unref_internal (GSource *source,
182 GMainContext *context,
184 static void g_source_destroy_internal (GSource *source,
185 GMainContext *context,
187 static void g_main_context_poll (GMainContext *context,
192 static void g_main_context_add_poll_unlocked (GMainContext *context,
195 static void g_main_context_remove_poll_unlocked (GMainContext *context,
197 static void g_main_context_wakeup (GMainContext *context);
199 static gboolean g_timeout_prepare (GSource *source,
201 static gboolean g_timeout_check (GSource *source);
202 static gboolean g_timeout_dispatch (GSource *source,
203 GSourceFunc callback,
205 static gboolean g_idle_prepare (GSource *source,
207 static gboolean g_idle_check (GSource *source);
208 static gboolean g_idle_dispatch (GSource *source,
209 GSourceFunc callback,
212 G_LOCK_DEFINE_STATIC (main_loop);
213 static GMainContext *default_main_context;
215 static GSourceFuncs timeout_funcs =
223 static GSourceFuncs idle_funcs =
232 /* SunOS has poll, but doesn't provide a prototype. */
233 # if defined (sun) && !defined (__SVR4)
234 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
236 #else /* !HAVE_POLL */
241 g_poll (GPollFD *fds,
245 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
246 gboolean poll_msgs = FALSE;
253 for (f = fds; f < &fds[nfds]; ++f)
256 if (f->events & G_IO_IN)
258 if (f->fd == G_WIN32_MSG_HANDLE)
262 #ifdef G_MAIN_POLL_DEBUG
263 g_print ("g_poll: waiting for %#x\n", f->fd);
265 handles[nhandles++] = (HANDLE) f->fd;
275 /* Waiting for messages, and maybe events
276 * -> First PeekMessage
278 #ifdef G_MAIN_POLL_DEBUG
279 g_print ("PeekMessage\n");
281 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
282 ready = WAIT_OBJECT_0 + nhandles;
287 /* Waiting just for messages */
288 if (timeout == INFINITE)
293 #ifdef G_MAIN_POLL_DEBUG
294 g_print ("WaitMessage\n");
297 g_warning (G_STRLOC ": WaitMessage() failed");
298 ready = WAIT_OBJECT_0 + nhandles;
300 else if (timeout == 0)
302 /* Waiting just for messages, zero timeout.
303 * If we got here, there was no message
305 ready = WAIT_TIMEOUT;
309 /* Waiting just for messages, some timeout
310 * -> Set a timer, wait for message,
311 * kill timer, use PeekMessage
313 timer = SetTimer (NULL, 0, timeout, NULL);
315 g_warning (G_STRLOC ": SetTimer() failed");
318 #ifdef G_MAIN_POLL_DEBUG
319 g_print ("WaitMessage\n");
322 KillTimer (NULL, timer);
323 #ifdef G_MAIN_POLL_DEBUG
324 g_print ("PeekMessage\n");
326 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
327 && msg.message != WM_TIMER)
328 ready = WAIT_OBJECT_0;
330 ready = WAIT_TIMEOUT;
336 /* Wait for either message or event
337 * -> Use MsgWaitForMultipleObjects
339 #ifdef G_MAIN_POLL_DEBUG
340 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
342 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
343 timeout, QS_ALLINPUT);
345 if (ready == WAIT_FAILED)
346 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
350 else if (nhandles == 0)
352 /* Wait for nothing (huh?) */
357 /* Wait for just events
358 * -> Use WaitForMultipleObjects
360 #ifdef G_MAIN_POLL_DEBUG
361 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
363 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
364 if (ready == WAIT_FAILED)
365 g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
368 #ifdef G_MAIN_POLL_DEBUG
369 g_print ("wait returns %d%s\n",
371 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
372 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
373 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
375 for (f = fds; f < &fds[nfds]; ++f)
378 if (ready == WAIT_FAILED)
380 else if (ready == WAIT_TIMEOUT)
382 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
384 for (f = fds; f < &fds[nfds]; ++f)
387 if (f->events & G_IO_IN)
388 if (f->fd == G_WIN32_MSG_HANDLE)
389 f->revents |= G_IO_IN;
392 #if TEST_WITHOUT_THIS
393 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
394 for (f = fds; f < &fds[nfds]; ++f)
396 if ((f->events & G_IO_IN)
397 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
399 f->revents |= G_IO_IN;
400 #ifdef G_MAIN_POLL_DEBUG
401 g_print ("g_poll: got event %#x\n", f->fd);
404 ResetEvent ((HANDLE) f->fd);
413 #else /* !G_OS_WIN32 */
415 /* The following implementation of poll() comes from the GNU C Library.
416 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
419 #include <string.h> /* for bzero on BSD systems */
421 #ifdef HAVE_SYS_SELECT_H
422 #include <sys/select.h>
423 #endif /* HAVE_SYS_SELECT_H */
427 #endif /* G_OS_BEOS */
430 # define SELECT_MASK fd_set
431 #else /* !NO_FD_SET */
433 typedef long fd_mask;
436 # define SELECT_MASK void
438 # define SELECT_MASK int
439 # endif /* !_IBMR2 */
440 #endif /* !NO_FD_SET */
443 g_poll (GPollFD *fds,
448 SELECT_MASK rset, wset, xset;
457 for (f = fds; f < &fds[nfds]; ++f)
460 if (f->events & G_IO_IN)
461 FD_SET (f->fd, &rset);
462 if (f->events & G_IO_OUT)
463 FD_SET (f->fd, &wset);
464 if (f->events & G_IO_PRI)
465 FD_SET (f->fd, &xset);
466 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
470 tv.tv_sec = timeout / 1000;
471 tv.tv_usec = (timeout % 1000) * 1000;
473 ready = select (maxfd + 1, &rset, &wset, &xset,
474 timeout == -1 ? NULL : &tv);
476 for (f = fds; f < &fds[nfds]; ++f)
481 if (FD_ISSET (f->fd, &rset))
482 f->revents |= G_IO_IN;
483 if (FD_ISSET (f->fd, &wset))
484 f->revents |= G_IO_OUT;
485 if (FD_ISSET (f->fd, &xset))
486 f->revents |= G_IO_PRI;
493 #endif /* !G_OS_WIN32 */
495 #endif /* !HAVE_POLL */
497 /* Called to clean up when a thread terminates
500 g_main_context_destroy (GMainContext *context)
504 /* We need the lock here only because g_source_destroy expects
505 * to be able to unlock when destroying the source's data
507 LOCK_CONTEXT (context);
508 source = context->source_list;
511 GSource *next = source->next;
512 g_source_destroy_internal (source, context, TRUE);
515 UNLOCK_CONTEXT (context);
517 #ifdef G_THREADS_ENABLED
518 g_mutex_free (context->mutex);
521 g_ptr_array_free (context->pending_dispatches, TRUE);
522 g_free (context->cached_poll_array);
524 g_mem_chunk_destroy (context->poll_chunk);
526 #ifdef G_THREADS_ENABLED
527 if (g_thread_supported())
530 close (context->wake_up_pipe[0]);
531 close (context->wake_up_pipe[1]);
533 CloseHandle (context->wake_up_semaphore);
541 /* This is an imcomplete (only the members up till context) version of
542 * GRealThread from gthread.h. Keep them in sync */
543 typedef struct _GRealThread GRealThread;
549 gpointer private_data;
550 GMainContext *context;
554 * g_main_context_get:
555 * @thread: a #GThread
557 * Retrieves the main loop context for a particular thread. This
558 * will create the main context for the thread if none previously
559 * existed. The context will exist until the thread terminates.
561 * Return value: the main loop context for @thread.
564 g_main_context_get (GThread *thread)
566 GRealThread *real_thread = (GRealThread*)thread;
567 GMainContext *context;
569 g_return_val_if_fail (thread != NULL, NULL);
571 if (g_thread_supported ())
572 context = real_thread->context;
574 context = default_main_context;
578 context = g_new0 (GMainContext, 1);
580 #ifdef G_THREADS_ENABLED
581 if (g_thread_supported ())
582 context->mutex = g_mutex_new();
584 context->thread = thread;
587 context->next_id = 1;
589 context->source_list = NULL;
592 context->poll_func = (GPollFunc)poll;
594 context->poll_func = g_poll;
597 context->cached_poll_array = NULL;
598 context->cached_poll_array_size = 0;
600 context->pending_dispatches = g_ptr_array_new ();
602 context->time_is_current = FALSE;
604 #ifdef G_THREADS_ENABLED
605 if (g_thread_supported ())
608 if (pipe (context->wake_up_pipe) < 0)
609 g_error ("Cannot create pipe main loop wake-up: %s\n",
612 context->wake_up_rec.fd = context->wake_up_pipe[0];
613 context->wake_up_rec.events = G_IO_IN;
614 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
616 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
617 if (context->wake_up_semaphore == NULL)
618 g_error ("Cannot create wake-up semaphore: %s",
619 g_win32_error_message (GetLastError ()));
620 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
621 context->wake_up_rec.events = G_IO_IN;
622 #ifdef G_MAIN_POLL_DEBUG
623 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
625 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
630 if (g_thread_supported ())
631 real_thread->context = context;
633 default_main_context = context;
640 * g_main_context_default:
642 * Return the default main context. This is the main context used
643 * for main loop functions when a main loop is not explicitly
646 * Return value: the default main context.
649 g_main_context_default (void)
655 if (!default_main_context)
656 default_main_context = g_main_context_get (g_thread_self ());
658 G_UNLOCK (main_loop);
660 return default_main_context;
663 /* Hooks for adding to the main loop */
667 * @source_funcs: structure containing functions that implement
668 * the sources behavior.
669 * @struct_size: size of the #GSource structure to create
671 * Create a new GSource structure. The size is specified to
672 * allow creating structures derived from GSource that contain
673 * additional data. The size passed in must be at least
676 * The source will not initially be associated with any #GMainContext
677 * and must be added to one with g_source_add() before it will be
680 * Return value: the newly create #GSource
683 g_source_new (GSourceFuncs *source_funcs,
688 g_return_val_if_fail (source_funcs != NULL, NULL);
689 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
691 source = (GSource*) g_malloc0 (struct_size);
693 source->source_funcs = source_funcs;
694 source->ref_count = 1;
696 source->priority = G_PRIORITY_DEFAULT;
698 source->flags = G_HOOK_FLAG_ACTIVE;
700 /* NULL/0 initialization for all other fields */
705 /* Holds context's lock
708 g_source_list_add (GSource *source,
709 GMainContext *context)
711 GSource *tmp_source, *last_source;
714 tmp_source = context->source_list;
715 while (tmp_source && tmp_source->priority <= source->priority)
717 last_source = tmp_source;
718 tmp_source = tmp_source->next;
721 source->next = tmp_source;
723 tmp_source->prev = source;
725 source->prev = last_source;
727 last_source->next = source;
729 context->source_list = source;
732 /* Holds context's lock
735 g_source_list_remove (GSource *source,
736 GMainContext *context)
739 source->prev->next = source->next;
741 context->source_list = source->next;
744 source->next->prev = source->prev;
752 * @source: a #GSource
753 * @context: a #GMainContext (if %NULL, the default context will be used)
755 * Adds a #GSource to a @context so that it will be executed within
758 * Return value: the ID for the source within the #GMainContext
761 g_source_attach (GSource *source,
762 GMainContext *context)
767 g_return_val_if_fail (source->context == NULL, 0);
768 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
771 context = g_main_context_default ();
773 LOCK_CONTEXT (context);
775 source->context = context;
776 result = source->id = context->next_id++;
779 g_source_list_add (source, context);
781 tmp_list = source->poll_fds;
784 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
785 tmp_list = tmp_list->next;
788 #ifdef G_THREADS_ENABLED
789 /* Now wake up the main loop if it is waiting in the poll() */
790 g_main_context_wakeup (context);
793 UNLOCK_CONTEXT (context);
799 g_source_destroy_internal (GSource *source,
800 GMainContext *context,
804 LOCK_CONTEXT (context);
806 if (!SOURCE_DESTROYED (source))
809 gpointer old_cb_data;
810 GSourceCallbackFuncs *old_cb_funcs;
812 source->flags &= ~G_HOOK_FLAG_ACTIVE;
814 old_cb_data = source->callback_data;
815 old_cb_funcs = source->callback_funcs;
817 source->callback_data = NULL;
818 source->callback_funcs = NULL;
822 UNLOCK_CONTEXT (context);
823 old_cb_funcs->unref (old_cb_data);
824 LOCK_CONTEXT (context);
827 tmp_list = source->poll_fds;
830 g_main_context_remove_poll_unlocked (context, tmp_list->data);
831 tmp_list = tmp_list->next;
834 g_source_unref_internal (source, context, TRUE);
838 UNLOCK_CONTEXT (context);
843 * @source: a #GSource
845 * Remove a source from its #GMainContext, if any, and mark it as
846 * destroyed. The source cannot be subsequently added to another
850 g_source_destroy (GSource *source)
852 GMainContext *context;
854 g_return_if_fail (source != NULL);
856 context = source->context;
859 g_source_destroy_internal (source, context, FALSE);
861 source->flags &= ~G_HOOK_FLAG_ACTIVE;
866 * @source: a #GSource
868 * Return the numeric ID for a particular source. The ID of a source
869 * is unique within a particular main loop context. The reverse
870 * mapping from ID to source is done by g_main_context_find_source_by_id().
872 * Return value: the ID for the source
875 g_source_get_id (GSource *source)
879 g_return_val_if_fail (source != NULL, 0);
880 g_return_val_if_fail (source->context != NULL, 0);
882 LOCK_CONTEXT (source->context);
884 UNLOCK_CONTEXT (source->context);
890 * g_source_get_context:
891 * @source: a #GSource
893 * Get the #GMainContext with which the source is associated.
894 * Calling this function on a destroyed source is an error.
896 * Return value: the #GMainContext with which the source is associated,
897 * or %NULL if the context has not yet been added
901 g_source_get_context (GSource *source)
903 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
905 return source->context;
911 * @fd: a #GPollFD structure holding information about a file
912 * descriptor to watch.
914 * Add a file descriptor to the set of file descriptors polled for
915 * this source. This is usually combined with g_source_new() to add an
916 * event source. The event source's check function will typically test
917 * the revents field in the #GPollFD struct and return %TRUE if events need
921 g_source_add_poll (GSource *source,
924 GMainContext *context;
926 g_return_if_fail (source != NULL);
927 g_return_if_fail (fd != NULL);
928 g_return_if_fail (!SOURCE_DESTROYED (source));
930 context = source->context;
933 LOCK_CONTEXT (context);
935 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
939 g_main_context_add_poll_unlocked (context, source->priority, fd);
940 UNLOCK_CONTEXT (context);
945 * g_source_remove_poll:
947 * @fd: a #GPollFD structure previously passed to g_source_poll.
949 * Remove a file descriptor from the set of file descriptors polled for
953 g_source_remove_poll (GSource *source,
956 GMainContext *context;
958 g_return_if_fail (source != NULL);
959 g_return_if_fail (fd != NULL);
960 g_return_if_fail (!SOURCE_DESTROYED (source));
962 context = source->context;
965 LOCK_CONTEXT (context);
967 source->poll_fds = g_slist_remove (source->poll_fds, fd);
971 g_main_context_remove_poll_unlocked (context, fd);
972 UNLOCK_CONTEXT (context);
977 * g_source_set_callback_indirect:
978 * @source: the source
979 * @callback_data: pointer to callback data "object"
980 * @callback_funcs: functions for reference counting callback_data
981 * and getting the callback and data
983 * Set the callback function storing the data as a refcounted callback
984 * "object". This is used to implement g_source_set_callback_closure()
985 * and internally. Note that calling g_source_set_callback_indirect() assumes
986 * an initial reference count on @callback_data, and thus
987 * @callback_funcs->unref will eventually be called once more
988 * than @callback_funcs->ref.
991 g_source_set_callback_indirect (GSource *source,
992 gpointer callback_data,
993 GSourceCallbackFuncs *callback_funcs)
995 GMainContext *context;
996 gpointer old_cb_data;
997 GSourceCallbackFuncs *old_cb_funcs;
999 g_return_if_fail (source != NULL);
1000 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1002 context = source->context;
1005 LOCK_CONTEXT (context);
1007 old_cb_data = source->callback_data;
1008 old_cb_funcs = source->callback_funcs;
1010 source->callback_data = callback_data;
1011 source->callback_funcs = callback_funcs;
1014 UNLOCK_CONTEXT (context);
1017 old_cb_funcs->unref (old_cb_data);
1021 g_source_callback_ref (gpointer cb_data)
1023 GSourceCallback *callback = cb_data;
1025 callback->ref_count++;
1030 g_source_callback_unref (gpointer cb_data)
1032 GSourceCallback *callback = cb_data;
1034 callback->ref_count--;
1035 if (callback->ref_count == 0)
1037 if (callback->notify)
1038 callback->notify (callback->data);
1044 g_source_callback_get (gpointer cb_data,
1048 GSourceCallback *callback = cb_data;
1050 *func = callback->func;
1051 *data = callback->data;
1054 static GSourceCallbackFuncs g_source_callback_funcs = {
1055 g_source_callback_ref,
1056 g_source_callback_unref,
1057 g_source_callback_get,
1061 * g_source_set_callback:
1062 * @source: the source
1063 * @func: a callback function
1064 * @data: the data to pass to callback function
1065 * @notify: a function to call when @data is no longer in use, or %NULL.
1067 * Set the callback function for a source.
1070 g_source_set_callback (GSource *source,
1073 GDestroyNotify notify)
1075 GSourceCallback *new_callback;
1077 g_return_if_fail (source != NULL);
1079 new_callback = g_new (GSourceCallback, 1);
1081 new_callback->ref_count = 1;
1082 new_callback->func = func;
1083 new_callback->data = data;
1084 new_callback->notify = notify;
1086 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1090 * g_source_set_priority:
1091 * @source: a #GSource
1092 * @priority: the new priority.
1094 * Set the priority of a source. While the main loop is being
1095 * run, a source will
1098 g_source_set_priority (GSource *source,
1102 GMainContext *context;
1104 g_return_if_fail (source != NULL);
1106 context = source->context;
1109 LOCK_CONTEXT (context);
1111 source->priority = priority;
1115 source->next = NULL;
1116 source->prev = NULL;
1118 tmp_list = source->poll_fds;
1121 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1122 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1124 tmp_list = tmp_list->next;
1127 UNLOCK_CONTEXT (source->context);
1132 * g_source_get_priority:
1133 * @source: a #GSource
1135 * Gets the priority of a surce
1137 * Return value: the priority of the source
1140 g_source_get_priority (GSource *source)
1142 g_return_val_if_fail (source != NULL, 0);
1144 return source->priority;
1148 * g_source_set_can_recurse:
1149 * @source: a #GSource
1150 * @can_recurse: whether recursion is allowed for this source
1152 * Sets whether a source can be called recursively. If @can_recurse is
1153 * %TRUE, then while the source is being dispatched then this source
1154 * will be processed normally. Otherwise, all processing of this
1155 * source is blocked until the dispatch function returns.
1158 g_source_set_can_recurse (GSource *source,
1159 gboolean can_recurse)
1161 GMainContext *context;
1163 g_return_if_fail (source != NULL);
1165 context = source->context;
1168 LOCK_CONTEXT (context);
1171 source->flags |= G_SOURCE_CAN_RECURSE;
1173 source->flags &= ~G_SOURCE_CAN_RECURSE;
1176 UNLOCK_CONTEXT (context);
1180 * g_source_get_can_recurse:
1181 * @source: a #GSource
1183 * Checks whether a source is allowed to be called recursively.
1184 * see g_source_set_can_recurse.
1186 * Return value: whether recursion is allowed.
1189 g_source_get_can_recurse (GSource *source)
1191 g_return_val_if_fail (source != NULL, FALSE);
1193 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1198 * @source: a #GSource
1200 * Increases the reference count on a source by one.
1202 * Return value: @source
1205 g_source_ref (GSource *source)
1207 GMainContext *context;
1209 g_return_val_if_fail (source != NULL, NULL);
1211 context = source->context;
1214 LOCK_CONTEXT (context);
1216 source->ref_count++;
1219 UNLOCK_CONTEXT (context);
1224 /* g_source_unref() but possible to call within context lock
1227 g_source_unref_internal (GSource *source,
1228 GMainContext *context,
1231 gpointer old_cb_data = NULL;
1232 GSourceCallbackFuncs *old_cb_funcs = NULL;
1234 g_return_if_fail (source != NULL);
1236 if (!have_lock && context)
1237 LOCK_CONTEXT (context);
1239 source->ref_count--;
1240 if (source->ref_count == 0)
1242 old_cb_data = source->callback_data;
1243 old_cb_funcs = source->callback_funcs;
1245 source->callback_data = NULL;
1246 source->callback_funcs = NULL;
1248 if (context && !SOURCE_DESTROYED (source))
1250 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1251 source->ref_count++;
1254 g_source_list_remove (source, context);
1256 if (source->source_funcs->destroy)
1257 source->source_funcs->destroy (source);
1259 g_slist_free (source->poll_fds);
1260 source->poll_fds = NULL;
1264 if (!have_lock && context)
1265 UNLOCK_CONTEXT (context);
1270 UNLOCK_CONTEXT (context);
1272 old_cb_funcs->unref (old_cb_data);
1275 LOCK_CONTEXT (context);
1281 * @source: a #GSource
1283 * Decreases the reference count of a source by one. If the
1284 * resulting reference count is zero the source and associated
1285 * memory will be destroyed.
1288 g_source_unref (GSource *source)
1290 g_return_if_fail (source != NULL);
1292 g_source_unref_internal (source, source->context, FALSE);
1296 * g_main_context_find_source_by_id:
1297 * @context: a #GMainContext (if %NULL, the default context will be used)
1298 * @id: the source ID, as returned by g_source_get_id()
1300 * Finds a #GSource given a pair of context and ID
1302 * Return value: the #GSource if found, otherwise, %NULL
1305 g_main_context_find_source_by_id (GMainContext *context,
1310 g_return_val_if_fail (id > 0, FALSE);
1312 if (context == NULL)
1313 context = g_main_context_default ();
1315 LOCK_CONTEXT (context);
1317 source = context->source_list;
1320 if (!SOURCE_DESTROYED (source) &&
1323 source = source->next;
1326 UNLOCK_CONTEXT (context);
1332 * g_main_context_find_source_by_funcs_user_data:
1333 * @context: a #GMainContext (if %NULL, the default context will be used).
1334 * @funcs: the @source_funcs passed to g_source_new().
1335 * @user_data: the user data from the callback.
1337 * Finds a source with the given source functions and user data. If
1338 * multiple sources exist with the same source function and user data,
1339 * the first one found will be returned.
1341 * Return value: the source, if one was found, otherwise %NULL
1344 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1345 GSourceFuncs *funcs,
1350 g_return_val_if_fail (funcs != NULL, FALSE);
1352 if (context == NULL)
1353 context = g_main_context_default ();
1355 LOCK_CONTEXT (context);
1357 source = context->source_list;
1360 if (!SOURCE_DESTROYED (source) &&
1361 source->source_funcs == funcs &&
1362 source->callback_data == user_data)
1364 source = source->next;
1367 UNLOCK_CONTEXT (context);
1373 * g_main_context_find_source_by_user_data:
1374 * @context: a #GMainContext
1375 * @user_data: the user_data for the callback.
1377 * Finds a source with the given user data for the callback. If
1378 * multiple sources exist with the same user data, the first
1379 * one found will be returned.
1381 * Return value: the source, if one was found, otherwise %NULL
1384 g_main_context_find_source_by_user_data (GMainContext *context,
1389 if (context == NULL)
1390 context = g_main_context_default ();
1392 LOCK_CONTEXT (context);
1394 source = context->source_list;
1397 if (!SOURCE_DESTROYED (source) &&
1398 source->callback_data == user_data)
1400 source = source->next;
1403 UNLOCK_CONTEXT (context);
1410 * @tag: the id of the source to remove.
1412 * Removes the source with the given id from the default main
1413 * context. The id of a #GSource is given by g_source_get_id(),
1414 * or will be returned by the functions g_source_attach(),
1415 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1416 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1418 * See also g_source_destroy().
1420 * Return value: %TRUE if the source was found and removed.
1423 g_source_remove (guint tag)
1427 g_return_val_if_fail (tag > 0, FALSE);
1429 source = g_main_context_find_source_by_id (NULL, tag);
1431 g_source_destroy (source);
1433 return source != NULL;
1437 * g_source_remove_by_user_data:
1438 * @user_data: the user_data for the callback.
1440 * Removes a source from the default main loop context given the user
1441 * data for the callback. If multiple sources exist with the same user
1442 * data, only one will be destroyed.
1444 * Return value: %TRUE if a source was found and removed.
1447 g_source_remove_by_user_data (gpointer user_data)
1451 source = g_main_context_find_source_by_user_data (NULL, user_data);
1454 g_source_destroy (source);
1462 * g_source_remove_by_funcs_user_data:
1463 * @funcs: The @source_funcs passed to g_source_new()
1464 * @user_data: the user data for the callback
1466 * Removes a source from the default main loop context given the
1467 * source functions and user data. If multiple sources exist with the
1468 * same source functions and user data, only one will be destroyed.
1470 * Return value: %TRUE if a source was found and removed.
1473 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1478 g_return_val_if_fail (funcs != NULL, FALSE);
1480 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1483 g_source_destroy (source);
1491 * g_get_current_time:
1492 * @result: #GTimeVal structure in which to store current time.
1494 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1497 g_get_current_time (GTimeVal *result)
1502 g_return_if_fail (result != NULL);
1504 /*this is required on alpha, there the timeval structs are int's
1505 not longs and a cast only would fail horribly*/
1506 gettimeofday (&r, NULL);
1507 result->tv_sec = r.tv_sec;
1508 result->tv_usec = r.tv_usec;
1510 /* Avoid calling time() except for the first time.
1511 * GetTickCount() should be pretty fast and low-level?
1512 * I could also use ftime() but it seems unnecessarily overheady.
1514 static DWORD start_tick = 0;
1515 static time_t start_time;
1518 g_return_if_fail (result != NULL);
1520 if (start_tick == 0)
1522 start_tick = GetTickCount ();
1526 tick = GetTickCount ();
1528 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1529 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1533 /* Running the main loop */
1535 /* HOLDS: context's lock */
1537 g_main_dispatch (GMainContext *context)
1541 for (i = 0; i < context->pending_dispatches->len; i++)
1543 GSource *source = context->pending_dispatches->pdata[i];
1545 context->pending_dispatches->pdata[i] = NULL;
1548 source->flags &= ~G_SOURCE_READY;
1550 if (!SOURCE_DESTROYED (source))
1552 gboolean was_in_call;
1553 gpointer user_data = NULL;
1554 GSourceFunc callback = NULL;
1555 GSourceCallbackFuncs *cb_funcs;
1557 gboolean need_destroy;
1559 gboolean (*dispatch) (GSource *,
1563 dispatch = source->source_funcs->dispatch;
1564 cb_funcs = source->callback_funcs;
1565 cb_data = source->callback_data;
1568 cb_funcs->ref (cb_data);
1570 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1571 source->flags |= G_HOOK_FLAG_IN_CALL;
1573 UNLOCK_CONTEXT (context);
1576 cb_funcs->get (cb_data, &callback, &user_data);
1578 need_destroy = ! dispatch (source,
1581 LOCK_CONTEXT (context);
1584 cb_funcs->unref (cb_data);
1587 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1589 /* Note: this depends on the fact that we can't switch
1590 * sources from one main context to another
1592 if (need_destroy && !SOURCE_DESTROYED (source))
1594 g_assert (source->context == context);
1595 g_source_destroy_internal (source, context, TRUE);
1599 SOURCE_UNREF (source, context);
1602 g_ptr_array_set_size (context->pending_dispatches, 0);
1605 /* Holds context's lock */
1606 static inline GSource *
1607 next_valid_source (GMainContext *context,
1610 GSource *new_source = source ? source->next : context->source_list;
1614 if (!SOURCE_DESTROYED (new_source))
1616 new_source->ref_count++;
1620 new_source = new_source->next;
1624 SOURCE_UNREF (source, context);
1631 * g_main_context_prepare:
1632 * @context: a #GMainContext
1633 * @priority: location to store priority of highest priority
1634 * source already ready.
1636 * Prepares to poll sources within a main loop. The resulting information
1637 * for polling is determined by calling g_main_context_query ().
1639 * Return value: %TRUE if some source is ready to be dispatched
1643 g_main_context_prepare (GMainContext *context,
1647 gint current_priority = G_MAXINT;
1650 if (context == NULL)
1651 context = g_main_context_default ();
1653 LOCK_CONTEXT (context);
1655 context->time_is_current = FALSE;
1657 if (context->in_check_or_prepare)
1659 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1660 "prepare() member.");
1664 #ifdef G_THREADS_ENABLED
1665 if (context->poll_waiting)
1667 g_warning("g_main_context_prepare(): main loop already active in another thread");
1668 UNLOCK_CONTEXT (context);
1672 context->poll_waiting = TRUE;
1673 #endif /* G_THREADS_ENABLED */
1676 /* If recursing, finish up current dispatch, before starting over */
1677 if (context->pending_dispatches)
1680 g_main_dispatch (context, ¤t_time);
1682 UNLOCK_CONTEXT (context);
1687 /* If recursing, clear list of pending dispatches */
1688 g_ptr_array_set_size (context->pending_dispatches, 0);
1690 /* Prepare all sources */
1692 context->timeout = -1;
1694 source = next_valid_source (context, NULL);
1697 gint source_timeout = -1;
1699 if ((n_ready > 0) && (source->priority > current_priority))
1701 SOURCE_UNREF (source, context);
1704 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1707 if (!(source->flags & G_SOURCE_READY))
1710 gboolean (*prepare) (GSource *source,
1713 prepare = source->source_funcs->prepare;
1714 context->in_check_or_prepare++;
1715 UNLOCK_CONTEXT (context);
1717 result = (*prepare) (source, &source_timeout);
1719 LOCK_CONTEXT (context);
1720 context->in_check_or_prepare--;
1723 source->flags |= G_SOURCE_READY;
1726 if (source->flags & G_SOURCE_READY)
1729 current_priority = source->priority;
1730 context->timeout = 0;
1733 if (source_timeout >= 0)
1735 if (context->timeout < 0)
1736 context->timeout = source_timeout;
1738 context->timeout = MIN (context->timeout, source_timeout);
1742 source = next_valid_source (context, source);
1745 UNLOCK_CONTEXT (context);
1748 *priority = current_priority;
1750 return (n_ready > 0);
1754 * g_main_context_query:
1755 * @context: a #GMainContext
1756 * @max_priority: maximum priority source to check
1757 * @timeout: location to store timeout to be used in polling
1758 * @fds: location to store #GPollFD records that need to be polled.
1759 * @n_fds: length of @fds.
1761 * Determines information necessary to poll this main loop.
1766 g_main_context_query (GMainContext *context,
1775 LOCK_CONTEXT (context);
1777 pollrec = context->poll_records;
1779 while (pollrec && max_priority >= pollrec->priority)
1781 if (pollrec->fd->events)
1785 fds[n_poll].fd = pollrec->fd->fd;
1786 /* In direct contradiction to the Unix98 spec, IRIX runs into
1787 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1788 * flags in the events field of the pollfd while it should
1789 * just ignoring them. So we mask them out here.
1791 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1792 fds[n_poll].revents = 0;
1797 pollrec = pollrec->next;
1800 #ifdef G_THREADS_ENABLED
1801 context->poll_changed = FALSE;
1806 *timeout = context->timeout;
1808 context->time_is_current = FALSE;
1811 UNLOCK_CONTEXT (context);
1817 * g_main_context_check:
1818 * @context: a #GMainContext
1819 * @max_priority: the maximum numerical priority of sources to check
1820 * @fds: array of #GPollFD's that was passed to the last call to
1821 * g_main_context_query()
1822 * @n_fds: return value of g_main_context_query()
1824 * Pass the results of polling back to the main loop.
1826 * Return value: %TRUE if some sources are ready to be dispatched.
1829 g_main_context_check (GMainContext *context,
1839 LOCK_CONTEXT (context);
1841 if (context->in_check_or_prepare)
1843 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1844 "prepare() member.");
1848 #ifdef G_THREADS_ENABLED
1849 if (!context->poll_waiting)
1853 read (context->wake_up_pipe[0], &c, 1);
1857 context->poll_waiting = FALSE;
1859 /* If the set of poll file descriptors changed, bail out
1860 * and let the main loop rerun
1862 if (context->poll_changed)
1864 #endif /* G_THREADS_ENABLED */
1866 pollrec = context->poll_records;
1870 if (pollrec->fd->events)
1872 pollrec->fd->revents = fds[i].revents;
1875 pollrec = pollrec->next;
1878 source = next_valid_source (context, NULL);
1881 if ((n_ready > 0) && (source->priority > max_priority))
1883 SOURCE_UNREF (source, context);
1886 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1889 if (!(source->flags & G_SOURCE_READY))
1892 gboolean (*check) (GSource *source);
1894 check = source->source_funcs->check;
1896 context->in_check_or_prepare++;
1897 UNLOCK_CONTEXT (context);
1899 result = (*check) (source);
1901 LOCK_CONTEXT (context);
1902 context->in_check_or_prepare--;
1905 source->flags |= G_SOURCE_READY;
1908 if (source->flags & G_SOURCE_READY)
1910 source->ref_count++;
1911 g_ptr_array_add (context->pending_dispatches, source);
1917 source = next_valid_source (context, source);
1920 UNLOCK_CONTEXT (context);
1926 * g_main_context_dispatch:
1927 * @context: a #GMainContext
1929 * Dispatch all pending sources()
1932 g_main_context_dispatch (GMainContext *context)
1934 LOCK_CONTEXT (context);
1936 if (context->pending_dispatches->len > 0)
1938 g_main_dispatch (context);
1941 UNLOCK_CONTEXT (context);
1945 g_main_context_iterate (GMainContext *context,
1951 gboolean some_ready;
1952 gint nfds, new_nfds;
1955 some_ready = g_main_context_prepare (context, &max_priority);
1959 LOCK_CONTEXT (context);
1961 if (context->cached_poll_array)
1963 nfds = context->cached_poll_array_size;
1964 fds = context->cached_poll_array;
1965 context->cached_poll_array = NULL;
1969 nfds = context->cached_poll_array_size = context->n_poll_records;
1970 fds = g_new (GPollFD, nfds);
1973 UNLOCK_CONTEXT (context);
1975 new_nfds = g_main_context_query (context, max_priority,
1976 &timeout, fds, nfds);
1978 while (new_nfds > nfds);
1983 g_main_context_poll (context, timeout, max_priority,
1986 g_main_context_check (context,
1990 LOCK_CONTEXT (context);
1992 g_assert (!context->cached_poll_array);
1994 context->cached_poll_array = fds;
1995 context->cached_poll_array_size = nfds;
1997 UNLOCK_CONTEXT (context);
2000 g_main_context_dispatch (context);
2006 * g_main_context_pending:
2007 * @context: a #GMainContext (if %NULL, the default context will be used)
2009 * Check if any sources have pending events for the given context.
2011 * Return value: %TRUE if events are pending.
2014 g_main_context_pending (GMainContext *context)
2017 context = g_main_context_default();
2019 return g_main_context_iterate (context, FALSE, FALSE);
2023 * g_main_context_iteration:
2024 * @context: a #GMainContext (if %NULL, the default context will be used)
2025 * @may_block: whether the call may block.
2027 * Run a single iteration for the given main loop. This involves
2028 * checking to see if any event sources are ready to be processed,
2029 * then if no events sources are ready and @may_block is %TRUE, waiting
2030 * for a source to become ready, then dispatching the highest priority
2031 * events sources that are ready. Note that even when @may_block is %TRUE,
2032 * it is still possible for g_main_context_iteration() to return
2033 * %FALSE, since the the wait may be interrupted for other
2034 * reasons than an event source becoming ready.
2036 * Return value: %TRUE if events were dispatched.
2039 g_main_context_iteration (GMainContext *context, gboolean may_block)
2042 context = g_main_context_default();
2044 return g_main_context_iterate (context, may_block, TRUE);
2049 * @context: a #GMainContext (if %NULL, the default context will be used).
2050 * @is_running: set to TRUE to indicate that the loop is running. This
2051 * is not very important since calling g_main_run() will set this to
2054 * Create a new #GMainLoop structure
2059 g_main_loop_new (GMainContext *context,
2060 gboolean is_running)
2065 context = g_main_context_default();
2067 loop = g_new0 (GMainLoop, 1);
2068 loop->context = context;
2069 loop->is_running = is_running != FALSE;
2070 loop->ref_count = 1;
2072 #ifdef G_THREADS_ENABLED
2073 if (g_thread_supported ())
2074 loop->mutex = g_mutex_new ();
2077 loop->sem_cond = NULL;
2078 #endif /* G_THREADS_ENABLED */
2085 * @loop: a #GMainLoop
2087 * Increase the reference count on a #GMainLoop object by one.
2089 * Return value: @loop
2092 g_main_loop_ref (GMainLoop *loop)
2094 g_return_val_if_fail (loop != NULL, NULL);
2104 main_loop_destroy (GMainLoop *loop)
2106 #ifdef G_THREADS_ENABLED
2107 g_mutex_free (loop->mutex);
2109 g_cond_free (loop->sem_cond);
2110 #endif /* G_THREADS_ENABLED */
2116 * g_main_loop_unref:
2117 * @loop: a #GMainLoop
2119 * Decreases the reference count on a #GMainLoop object by one. If
2120 * the result is zero, free the loop and free all associated memory.
2123 g_main_loop_unref (GMainLoop *loop)
2125 g_return_if_fail (loop != NULL);
2126 g_return_if_fail (loop->ref_count > 0);
2131 if (loop->ref_count == 0)
2133 /* When the ref_count is 0, there can be nobody else using the
2134 * loop, so it is safe to unlock before destroying.
2137 main_loop_destroy (loop);
2145 * @loop: a #GMainLoop
2147 * Run a main loop until g_main_quit() is called on the loop.
2148 * If this is called for the thread of the loop's #GMainContext,
2149 * it will process events from the loop, otherwise it will
2153 g_main_loop_run (GMainLoop *loop)
2155 g_return_if_fail (loop != NULL);
2157 /* The assumption here is that a reference is held to the loop
2158 * until we recursively iterate
2160 #ifdef G_THREADS_ENABLED
2161 if (loop->context->thread != g_thread_self ())
2167 if (!g_thread_supported ())
2169 g_warning ("g_main_loop_run() was called from second thread but"
2170 "g_thread_init() was never called.");
2174 if (!loop->sem_cond)
2175 loop->sem_cond = g_cond_new ();
2177 if (!loop->is_running)
2178 loop->is_running = TRUE;
2180 while (loop->is_running)
2181 g_cond_wait (loop->sem_cond, loop->mutex);
2185 #endif /* G_THREADS_ENABLED */
2187 LOCK_CONTEXT (loop->context);
2188 if (loop->context->in_check_or_prepare)
2190 g_warning ("g_main_run(): called recursively from within a source's check() or "
2191 "prepare() member, iteration not possible.");
2194 UNLOCK_CONTEXT (loop->context);
2199 loop->is_running = TRUE;
2200 while (loop->is_running)
2203 g_main_context_iterate (loop->context, TRUE, TRUE);
2208 /* We inline this here rather than calling g_main_loop_unref() to
2209 * avoid an extra unlock/lock.
2212 if (loop->ref_count == 0)
2215 main_loop_destroy (loop);
2223 * @loop: a #GMainLoop
2225 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2226 * for the loop will return.
2229 g_main_loop_quit (GMainLoop *loop)
2231 g_return_if_fail (loop != NULL);
2234 loop->is_running = FALSE;
2236 #ifdef G_THREADS_ENABLED
2238 g_cond_broadcast (loop->sem_cond);
2243 LOCK_CONTEXT (loop->context);
2245 g_main_context_wakeup (loop->context);
2246 UNLOCK_CONTEXT (loop->context);
2250 * g_main_loop_is_running:
2251 * @loop: a #GMainLoop.
2253 * Check to see if the main loop is currently being run via g_main_run()
2255 * Return value: %TRUE if the mainloop is currently being run.
2258 g_main_loop_is_running (GMainLoop *loop)
2262 g_return_val_if_fail (loop != NULL, FALSE);
2265 result = loop->is_running;
2271 /* HOLDS: context's lock */
2273 g_main_context_poll (GMainContext *context,
2279 #ifdef G_MAIN_POLL_DEBUG
2285 GPollFunc poll_func;
2287 if (n_fds || timeout != 0)
2289 #ifdef G_MAIN_POLL_DEBUG
2290 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2291 poll_timer = g_timer_new ();
2294 LOCK_CONTEXT (context);
2296 poll_func = context->poll_func;
2298 UNLOCK_CONTEXT (context);
2299 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2300 g_warning ("poll(2) failed due to: %s.",
2301 g_strerror (errno));
2303 #ifdef G_MAIN_POLL_DEBUG
2304 LOCK_CONTEXT (context);
2306 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2309 g_timer_elapsed (poll_timer, NULL));
2310 g_timer_destroy (poll_timer);
2311 pollrec = context->poll_records;
2315 if (pollrec->fd->events)
2319 g_print (" [%d:", fds[i].fd);
2320 if (fds[i].revents & G_IO_IN)
2322 if (fds[i].revents & G_IO_OUT)
2324 if (fds[i].revents & G_IO_PRI)
2326 if (fds[i].revents & G_IO_ERR)
2328 if (fds[i].revents & G_IO_HUP)
2330 if (fds[i].revents & G_IO_NVAL)
2336 pollrec = pollrec->next;
2340 UNLOCK_CONTEXT (context);
2342 } /* if (n_fds || timeout != 0) */
2346 * g_main_context_add_poll:
2347 * @context: a #GMainContext (or %NULL for the default context)
2348 * @fd: a #GPollFD structure holding information about a file
2349 * descriptor to watch.
2350 * @priority: the priority for this file descriptor which should be
2351 * the same as the priority used for g_source_attach() to ensure that the
2352 * file descriptor is polled whenever the results may be needed.
2354 * Add a file descriptor to the set of file descriptors polled * for
2355 * this context. This will very seldom be used directly. Instead
2356 * a typical event source will use g_source_add_poll() instead.
2359 g_main_context_add_poll (GMainContext *context,
2364 context = g_main_context_default ();
2366 LOCK_CONTEXT (context);
2367 g_main_context_add_poll_unlocked (context, priority, fd);
2368 UNLOCK_CONTEXT (context);
2371 /* HOLDS: main_loop_lock */
2373 g_main_context_add_poll_unlocked (GMainContext *context,
2377 GPollRec *lastrec, *pollrec, *newrec;
2379 if (!context->poll_chunk)
2380 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2382 if (context->poll_free_list)
2384 newrec = context->poll_free_list;
2385 context->poll_free_list = newrec->next;
2388 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2390 /* This file descriptor may be checked before we ever poll */
2393 newrec->priority = priority;
2396 pollrec = context->poll_records;
2397 while (pollrec && priority >= pollrec->priority)
2400 pollrec = pollrec->next;
2404 lastrec->next = newrec;
2406 context->poll_records = newrec;
2408 newrec->next = pollrec;
2410 context->n_poll_records++;
2411 if (context->cached_poll_array &&
2412 context->cached_poll_array_size < context->n_poll_records)
2414 g_free (context->cached_poll_array);
2415 context->cached_poll_array = NULL;
2418 #ifdef G_THREADS_ENABLED
2419 context->poll_changed = TRUE;
2421 /* Now wake up the main loop if it is waiting in the poll() */
2422 g_main_context_wakeup (context);
2427 * g_main_context_remove_poll:
2428 * @context:a #GMainContext
2429 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2431 * Remove file descriptor from the set of file descriptors to be
2432 * polled for a particular context.
2435 g_main_context_remove_poll (GMainContext *context,
2439 context = g_main_context_default ();
2441 LOCK_CONTEXT (context);
2443 g_main_context_remove_poll_unlocked (context, fd);
2445 UNLOCK_CONTEXT (context);
2449 g_main_context_remove_poll_unlocked (GMainContext *context,
2452 GPollRec *pollrec, *lastrec;
2455 pollrec = context->poll_records;
2459 if (pollrec->fd == fd)
2461 if (lastrec != NULL)
2462 lastrec->next = pollrec->next;
2464 context->poll_records = pollrec->next;
2466 #ifdef ENABLE_GC_FRIENDLY
2468 #endif /* ENABLE_GC_FRIENDLY */
2470 pollrec->next = context->poll_free_list;
2471 context->poll_free_list = pollrec;
2473 context->n_poll_records--;
2477 pollrec = pollrec->next;
2480 #ifdef G_THREADS_ENABLED
2481 context->poll_changed = TRUE;
2483 /* Now wake up the main loop if it is waiting in the poll() */
2484 g_main_context_wakeup (context);
2489 * g_source_get_current_time:
2490 * @source: a #GSource
2491 * @timeval: #GTimeVal structure in which to store current time.
2493 * Gets the "current time" to be used when checking
2494 * this source. The advantage of calling this function over
2495 * calling g_get_current_time() directly is that when
2496 * checking multiple sources, GLib can cache a single value
2497 * instead of having to repeatedly get the system time.
2500 g_source_get_current_time (GSource *source,
2503 GMainContext *context;
2505 g_return_if_fail (source->context != NULL);
2507 context = source->context;
2509 LOCK_CONTEXT (context);
2511 if (!context->time_is_current)
2513 g_get_current_time (&context->current_time);
2514 context->time_is_current = TRUE;
2517 *timeval = context->current_time;
2519 UNLOCK_CONTEXT (context);
2523 * g_main_context_set_poll_func:
2524 * @context: a #GMainContext
2525 * @func: the function to call to poll all file descriptors
2527 * Sets the function to use to handle polling of file descriptors. It
2528 * will be used instead of the poll() system call (or GLib's
2529 * replacement function, which is used where poll() isn't available).
2531 * This function could possibly be used to integrate the GLib event
2532 * loop with an external event loop.
2535 g_main_context_set_poll_func (GMainContext *context,
2539 context = g_main_context_default ();
2541 LOCK_CONTEXT (context);
2544 context->poll_func = func;
2548 context->poll_func = (GPollFunc) poll;
2550 context->poll_func = (GPollFunc) g_poll;
2554 UNLOCK_CONTEXT (context);
2558 * g_main_context_get_poll_func:
2559 * @context: a #GMainContext
2561 * Gets the poll function set by g_main_context_set_poll_func()
2563 * Return value: the poll function
2566 g_main_context_get_poll_func (GMainContext *context)
2571 context = g_main_context_default ();
2573 LOCK_CONTEXT (context);
2574 result = context->poll_func;
2575 UNLOCK_CONTEXT (context);
2580 /* HOLDS: context's lock */
2581 /* Wake the main loop up from a poll() */
2583 g_main_context_wakeup (GMainContext *context)
2585 #ifdef G_THREADS_ENABLED
2586 if (g_thread_supported() && context->poll_waiting)
2588 context->poll_waiting = FALSE;
2590 write (context->wake_up_pipe[1], "A", 1);
2592 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2601 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2602 GTimeVal *current_time)
2604 guint seconds = timeout_source->interval / 1000;
2605 guint msecs = timeout_source->interval - seconds * 1000;
2607 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2608 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2609 if (timeout_source->expiration.tv_usec >= 1000000)
2611 timeout_source->expiration.tv_usec -= 1000000;
2612 timeout_source->expiration.tv_sec++;
2617 g_timeout_prepare (GSource *source,
2621 GTimeVal current_time;
2623 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2625 g_source_get_current_time (source, ¤t_time);
2627 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2628 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2632 else if (msec > timeout_source->interval)
2634 /* The system time has been set backwards, so we
2635 * reset the expiration time to now + timeout_source->interval;
2636 * this at least avoids hanging for long periods of time.
2638 g_timeout_set_expiration (timeout_source, ¤t_time);
2639 msec = timeout_source->interval;
2648 g_timeout_check (GSource *source)
2650 GTimeVal current_time;
2651 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2653 g_source_get_current_time (source, ¤t_time);
2655 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2656 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2657 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2661 g_timeout_dispatch (GSource *source,
2662 GSourceFunc callback,
2665 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2669 g_warning ("Timeout source dispatched without callback\n"
2670 "You must call g_source_set_callback().");
2674 if (callback (user_data))
2676 GTimeVal current_time;
2678 g_source_get_current_time (source, ¤t_time);
2679 g_timeout_set_expiration (timeout_source, ¤t_time);
2688 * g_timeout_source_new:
2689 * @interval: the timeout interval in milliseconds.
2691 * Create a new timeout source.
2693 * The source will not initially be associated with any #GMainContext
2694 * and must be added to one with g_source_attach() before it will be
2697 * Return value: the newly create timeout source
2700 g_timeout_source_new (guint interval)
2702 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2703 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2704 GTimeVal current_time;
2706 timeout_source->interval = interval;
2708 g_get_current_time (¤t_time);
2709 g_timeout_set_expiration (timeout_source, ¤t_time);
2715 * g_timeout_add_full:
2716 * @priority: the priority of the idle source. Typically this will be in the
2717 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2718 * @interval: the time between calls to the function, in milliseconds
2719 * (1/1000ths of a second.)
2720 * @function: function to call
2721 * @data: data to pass to @function
2722 * @notify: function to call when the idle is removed, or %NULL
2724 * Sets a function to be called at regular intervals, with the given
2725 * priority. The function is called repeatedly until it returns
2726 * FALSE, at which point the timeout is automatically destroyed and
2727 * the function will not be called again. The @notify function is
2728 * called when the timeout is destroyed. The first call to the
2729 * function will be at the end of the first @interval.
2731 * Note that timeout functions may be delayed, due to the processing of other
2732 * event sources. Thus they should not be relied on for precise timing.
2733 * After each call to the timeout function, the time of the next
2734 * timeout is recalculated based on the current time and the given interval
2735 * (it does not try to 'catch up' time lost in delays).
2737 * Return value: the id of event source.
2740 g_timeout_add_full (gint priority,
2742 GSourceFunc function,
2744 GDestroyNotify notify)
2749 g_return_val_if_fail (function != NULL, 0);
2751 source = g_timeout_source_new (interval);
2753 if (priority != G_PRIORITY_DEFAULT)
2754 g_source_set_priority (source, priority);
2756 g_source_set_callback (source, function, data, notify);
2757 id = g_source_attach (source, NULL);
2758 g_source_unref (source);
2765 * @interval: the time between calls to the function, in milliseconds
2766 * (1/1000ths of a second.)
2767 * @function: function to call
2768 * @data: data to pass to @function
2770 * Sets a function to be called at regular intervals, with the default
2771 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2772 * until it returns FALSE, at which point the timeout is automatically
2773 * destroyed and the function will not be called again. The @notify
2774 * function is called when the timeout is destroyed. The first call
2775 * to the function will be at the end of the first @interval.
2777 * Note that timeout functions may be delayed, due to the processing of other
2778 * event sources. Thus they should not be relied on for precise timing.
2779 * After each call to the timeout function, the time of the next
2780 * timeout is recalculated based on the current time and the given interval
2781 * (it does not try to 'catch up' time lost in delays).
2783 * Return value: the id of event source.
2786 g_timeout_add (guint32 interval,
2787 GSourceFunc function,
2790 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2791 interval, function, data, NULL);
2794 /* Idle functions */
2797 g_idle_prepare (GSource *source,
2806 g_idle_check (GSource *source)
2812 g_idle_dispatch (GSource *source,
2813 GSourceFunc callback,
2818 g_warning ("Idle source dispatched without callback\n"
2819 "You must call g_source_set_callback().");
2823 return callback (user_data);
2827 * g_idle_source_new:
2829 * Create a new idle source.
2831 * The source will not initially be associated with any #GMainContext
2832 * and must be added to one with g_source_attach() before it will be
2835 * Return value: the newly created idle source
2838 g_idle_source_new (void)
2840 return g_source_new (&idle_funcs, sizeof (GSource));
2845 * @priority: the priority of the idle source. Typically this will be in the
2846 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2847 * @function: function to call
2848 * @data: data to pass to @function
2849 * @notify: function to call when the idle is removed, or %NULL
2851 * Adds a function to be called whenever there are no higher priority
2852 * events pending. If the function returns FALSE it is automatically
2853 * removed from the list of event sources and will not be called again.
2855 * Return value: the id of the event source.
2858 g_idle_add_full (gint priority,
2859 GSourceFunc function,
2861 GDestroyNotify notify)
2866 g_return_val_if_fail (function != NULL, 0);
2868 source = g_idle_source_new ();
2870 if (priority != G_PRIORITY_DEFAULT)
2871 g_source_set_priority (source, priority);
2873 g_source_set_callback (source, function, data, notify);
2874 id = g_source_attach (source, NULL);
2875 g_source_unref (source);
2882 * @function: function to call
2883 * @data: data to pass to @function.
2885 * Adds a function to be called whenever there are no higher priority
2886 * events pending to the default main loop. The function is given the
2887 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2888 * returns FALSE it is automatically removed from the list of event
2889 * sources and will not be called again.
2891 * Return value: the id of the event source.
2894 g_idle_add (GSourceFunc function,
2897 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2901 * g_idle_remove_by_data:
2902 * @data: the data for the idle source's callback.
2904 * Removes the idle function with the given data.
2906 * Return value: %TRUE if an idle source was found and removed.
2909 g_idle_remove_by_data (gpointer data)
2911 return g_source_remove_by_funcs_user_data (&idle_funcs, data);