Source

The main event loop manages all the available sources of events for GLib and GTK+ applications. These events can come from any number of different types of sources such as file descriptors (plain files, pipes or sockets) and timeouts. New types of event sources can also be added using g_source_attach().

To allow multiple independent sets of sources to be handled in different threads, each source is associated with a GMainContext. A GMainContext can only be running in a single thread, but sources can be added to it and removed from it from other threads.

Each event source is assigned a priority. The default priority, G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities. Values greater than 0 denote lower priorities. Events from high priority sources are always processed before events from lower priority sources.

Idle functions can also be added, and assigned a priority. These will be run whenever no events with a higher priority are ready to be processed.

The GMainLoop data type represents a main event loop. A GMainLoop is created with g_main_loop_new(). After adding the initial event sources, g_main_loop_run() is called. This continuously checks for new events from each of the event sources and dispatches them. Finally, the processing of an event from one of the sources leads to a call to g_main_loop_quit() to exit the main loop, and g_main_loop_run() returns.

It is possible to create new instances of GMainLoop recursively. This is often used in GTK+ applications when showing modal dialog boxes. Note that event sources are associated with a particular GMainContext, and will be checked and dispatched for all main loops associated with that GMainContext.

GTK+ contains wrappers of some of these functions, e.g. gtk_main(), gtk_main_quit() and gtk_events_pending().

Creating new source types

One of the unusual features of the GMainLoop functionality is that new types of event source can be created and used in addition to the builtin type of event source. A new event source type is used for handling GDK events. A new source type is created by deriving from the GSource structure. The derived type of source is represented by a structure that has the GSource structure as a first element, and other elements specific to the new source type. To create an instance of the new source type, call g_source_new() passing in the size of the derived structure and a table of functions. These GSourceFuncs determine the behavior of the new source type.

New source types basically interact with the main context in two ways. Their prepare function in GSourceFuncs can set a timeout to determine the maximum amount of time that the main loop will sleep before checking the source again. In addition, or as well, the source can add file descriptors to the set that the main context checks using g_source_add_poll().

<hr>

Customizing the main loop iteration

Single iterations of a GMainContext can be run with g_main_context_iteration(). In some cases, more detailed control of exactly how the details of the main loop work is desired, for instance, when integrating the GMainLoop with an external main loop. In such cases, you can call the component functions of g_main_context_iteration() directly. These functions are g_main_context_prepare(), g_main_context_query(), g_main_context_check() and g_main_context_dispatch().

The operation of these functions can best be seen in terms of a state diagram, as shown in Figure 1, “States of a Main Context”.

Figure 1. States of a Main Context

On Unix, the GLib mainloop is incompatible with fork(). Any program using the mainloop must either exec() or exit() from the child without returning to the mainloop.

Constructors

this
this(GSource* gSource)

Sets our main struct and passes it to the parent class

this
this(GSourceFuncs* sourceFuncs, uint structSize)

Creates a new GSource structure. The size is specified to allow creating structures derived from GSource that contain additional data. The size passed in must be at least sizeof (GSource). The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed.

Members

Functions

addChildSource
void addChildSource(Source childSource)

Adds child_source to source as a "polled" source; when source is added to a GMainContext, child_source will be automatically added with the same priority, when child_source is triggered, it will cause source to dispatch (in addition to calling its own callback), and when source is destroyed, it will destroy child_source as well. (source will also still be dispatched if its own prepare/check functions indicate that it is ready.) If you don't need child_source to do anything on its own when it triggers, you can call g_source_set_dummy_callback() on it to set a callback that does nothing (except return TRUE if appropriate). source will hold a reference on child_source while child_source is attached to it. Since 2.28

addPoll
void addPoll(GPollFD fd)

Adds a file descriptor to the set of file descriptors polled for this source. This is usually combined with g_source_new() to add an event source. The event source's check function will typically test the revents field in the GPollFD struct and return TRUE if events need to be processed. Using this API forces the linear scanning of event sources on each main loop iteration. Newly-written event sources should try to use g_source_add_unix_fd() instead of this API.

addUnixFd
void* addUnixFd(int fd, GIOCondition events)

Monitors fd for the IO events in events. The tag returned by this function can be used to remove or modify the monitoring of the fd using g_source_remove_unix_fd() or g_source_modify_unix_fd(). It is not necessary to remove the fd before destroying the source; it will be cleaned up automatically. As the name suggests, this function is not available on Windows. Since 2.36

attach
uint attach(MainContext context)

Adds a GSource to a context so that it will be executed within that context. Remove it by calling g_source_destroy().

destroy
void destroy()

Removes a source from its GMainContext, if any, and mark it as destroyed. The source cannot be subsequently added to another context.

doref
Source doref()

Increases the reference count on a source by one.

getCanRecurse
int getCanRecurse()

Checks whether a source is allowed to be called recursively. see g_source_set_can_recurse().

getContext
MainContext getContext()

Gets the GMainContext with which the source is associated. You can call this on a source that has been destroyed, provided that the GMainContext it was attached to still exists (in which case it will return that GMainContext). In particular, you can always call this function on the source returned from g_main_current_source(). But calling this function on a source whose GMainContext has been destroyed is an error.

getCurrentTime
void getCurrentTime(GTimeVal timeval)

Warning g_source_get_current_time has been deprecated since version 2.28 and should not be used in newly-written code. use g_source_get_time() instead This function ignores source and is otherwise the same as g_get_current_time().

getId
uint getId()

Returns the numeric ID for a particular source. The ID of a source is a positive integer which is unique within a particular main loop context. The reverse mapping from ID to source is done by g_main_context_find_source_by_id().

getName
string getName()

Gets a name for the source, used in debugging and profiling. The name may be NULL if it has never been set with g_source_set_name(). Since 2.26

getPriority
int getPriority()

Gets the priority of a source.

getReadyTime
long getReadyTime()

Gets the "ready time" of source, as set by g_source_set_ready_time(). Any time before the current monotonic time (including 0) is an indication that the source will fire immediately.

getSourceStruct
GSource* getSourceStruct()
Undocumented in source. Be warned that the author may not have intended to support it.
getStruct
void* getStruct()

the main Gtk struct as a void*

getTime
long getTime()

Gets the time to be used when checking this source. The advantage of calling this function over calling g_get_monotonic_time() directly is that when checking multiple sources, GLib can cache a single value instead of having to repeatedly get the system monotonic time. The time here is the system monotonic time, if available, or some other reasonable alternative otherwise. See g_get_monotonic_time(). Since 2.28

isDestroyed
int isDestroyed()

Returns whether source has been destroyed. This is important when you operate upon your objects from within idle handlers, but may have freed the object before the dispatch of your idle handler. This will fail in a multi-threaded application if the widget is destroyed before the idle handler fires due to the use after free in the callback. A solution, to this particular problem, is to check to if the source has already been destroy within the callback. Since 2.12

modifyUnixFd
void modifyUnixFd(void* tag, GIOCondition newEvents)

Updates the event mask to watch for the fd identified by tag. tag is the tag returned from g_source_add_unix_fd(). If you want to remove a fd, don't set its event mask to zero. Instead, call g_source_remove_unix_fd(). As the name suggests, this function is not available on Windows. Since 2.36

queryUnixFd
GIOCondition queryUnixFd(void* tag)

Queries the events reported for the fd corresponding to tag on source during the last poll. The return value of this function is only defined when the function is called from the check or dispatch functions for source. As the name suggests, this function is not available on Windows. Since 2.36

removeChildSource
void removeChildSource(Source childSource)

Detaches child_source from source and destroys it. Since 2.28

removePoll
void removePoll(GPollFD fd)

Removes a file descriptor from the set of file descriptors polled for this source.

removeUnixFd
void removeUnixFd(void* tag)

Reverses the effect of a previous call to g_source_add_unix_fd(). You only need to call this if you want to remove an fd from being watched while keeping the same source around. In the normal case you will just want to destroy the source. As the name suggests, this function is not available on Windows. Since 2.36

setCallback
void setCallback(GSourceFunc func, void* data, GDestroyNotify notify)

Sets the callback function for a source. The callback for a source is called from the source's dispatch function. The exact type of func depends on the type of source; ie. you should not count on func being called with data as its first parameter. Typically, you won't use this function. Instead use functions specific to the type of source you are using.

setCallbackIndirect
void setCallbackIndirect(void* callbackData, GSourceCallbackFuncs* callbackFuncs)

Sets the callback function storing the data as a refcounted callback "object". This is used internally. Note that calling g_source_set_callback_indirect() assumes an initial reference count on callback_data, and thus callback_funcs-&gt;unref will eventually be called once more than callback_funcs-&gt;ref.

setCanRecurse
void setCanRecurse(int canRecurse)

Sets whether a source can be called recursively. If can_recurse is TRUE, then while the source is being dispatched then this source will be processed normally. Otherwise, all processing of this source is blocked until the dispatch function returns.

setFuncs
void setFuncs(GSourceFuncs* funcs)

Sets the source functions (can be used to override default implementations) of an unattached source. Since 2.12

setName
void setName(string name)

Sets a name for the source, used in debugging and profiling. The name defaults to NULL. The source name should describe in a human-readable way what the source does. For example, "X11 event queue" or "GTK+ repaint idle handler" or whatever it is. It is permitted to call this function multiple times, but is not recommended due to the potential performance impact. For example, one could change the name in the "check" function of a GSourceFuncs to include details like the event type in the source name. Since 2.26

setPriority
void setPriority(int priority)

Sets the priority of a source. While the main loop is being run, a source will be dispatched if it is ready to be dispatched and no sources at a higher (numerically smaller) priority are ready to be dispatched.

setReadyTime
void setReadyTime(long readyTime)

Sets a GSource to be dispatched when the given monotonic time is reached (or passed). If the monotonic time is in the past (as it always will be if ready_time is 0) then the source will be dispatched immediately. If ready_time is -1 then the source is never woken up on the basis of the passage of time. Dispatching the source does not reset the ready time. You should do so yourself, from the source dispatch function. Note that if you have a pair of sources where the ready time of one suggests that it will be delivered first but the priority for the other suggests that it would be delivered first, and the ready time for both sources is reached during the same main context iteration then the order of dispatch is undefined. Since 2.36

unref
void unref()

Decreases the reference count of a source by one. If the resulting reference count is zero the source and associated memory will be destroyed.

Static functions

remove
int remove(uint tag)

Removes the source with the given id from the default main context. The id of a GSource is given by g_source_get_id(), or will be returned by the functions g_source_attach(), g_idle_add(), g_idle_add_full(), g_timeout_add(), g_timeout_add_full(), g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full(). See also g_source_destroy(). You must use g_source_destroy() for sources added to a non-default main context.

removeByFuncsUserData
int removeByFuncsUserData(GSourceFuncs* funcs, void* userData)

Removes a source from the default main loop context given the source functions and user data. If multiple sources exist with the same source functions and user data, only one will be destroyed.

removeByUserData
int removeByUserData(void* userData)

Removes a source from the default main loop context given the user data for the callback. If multiple sources exist with the same user data, only one will be destroyed.

setNameById
void setNameById(uint tag, string name)

Sets the name of a source using its ID. This is a convenience utility to set source names from the return value of g_idle_add(), g_timeout_add(), etc. Since 2.26

Variables

gSource
GSource* gSource;

the main Gtk struct

Meta