Toc Gallery Index Tree Glib.Main

Description

This package contains low-level subprograms that are used to interact or configure the main loop. This loop is responsible for processing events, monitoring input sources like pipes, sockets,..., and calling callbacks at given time intervals. New event sources can be created.

To allow multiple independent sets of sources to be handled in different threads, each source is associated with a main context. A main context 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.

Creating new sources types ==========================

One of the unusual features of the GTK+ main loop 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.

New source types basically interact with 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().

Ada ===

Some of these features duplicate Ada builtin tasking support, but the latter might be more complex to use in the context of a graphical application, since most of the time the windowing system doesn't support multi-threaded applications.

Types

  • type Destroy_Notify is access procedure (Data : in out Data_Type);
    Notify is called just prior to the destruction of Data. It is also called if the idle or timeout is destroyed through a call to Remove (Id);
  • type G_Main_Context is new Glib.C_Proxy;
    This type represents a set of sources to handled in the main loop. Basically, this represents a main loop. There might be several main loops running at the same time, although gtk+ itself has only one, identified as the default main context.
  • type G_Priority is new Gint;
  • type G_Source is new Glib.C_Proxy;
    This type represents an event source that can be monitored by the main loop. There are various internal types of such sources, that can be configured by setting appropriate callbacks (this is not yet doable in GtkAda). See Idle_Source_New and Timeout_Source_New.
  • type G_Source_Func is access function (Data : Data_Type) return Boolean;
    If the function returns FALSE it is automatically removed from the list of event sources and will not be called again.
  • type G_Source_Func_User_Data is access function (User_Data : System.Address) return Gboolean;
  • type G_Source_Id is new Guint;
    The ID of a source within the context to which it is attached.
  • type G_Source_Type is private;
  • type Source_Check_Func is access function (Source : G_Source) return Gboolean;
  • type Source_Dispatch_Func is access function (Source : G_Source; Callback : G_Source_Func_User_Data; Data : System.Address) return Gboolean;
  • type Source_Finalize_Func is access procedure (Source : G_Source);
  • type Source_Prepare_Func is access function (Source : G_Source; Timeout : access Gint) return Gboolean;

Subprograms

    G_Main_Context

  • function Main_Context_New return G_Main_Context;
    Create a new context
  • procedure Main_Context_Ref (Context : G_Main_Context);
    procedure Main_Context_Unref (Context : G_Main_Context);
    Increase or decreate the reference counting for Context. When this reaches 0, the memory is freed.
  • function Main_Context_Default return G_Main_Context;
    Returns the default main context. This is the main context used for main loop functions when a main loop is not explicitly specified.
  • procedure Wakeup (Context : G_Main_Context);
    If context is currently waiting in a poll(), interrupt the poll(), and continue the iteration process.
  • function Acquire (Context : G_Main_Context) return Boolean;
    Tries to become the owner of the specified context. If some other thread is the owner of the context, returns FALSE immediately. Ownership is properly recursive: the owner can require ownership again and will release ownership when Release() is called as many times as Acquire(). You must be the owner of a context before you can call Prepare(), Query(), Check(), Dispatch().
  • procedure Release (Context : G_Main_Context);
    Releases ownership of a context previously acquired by this thread with Acquire(). If the context was acquired multiple times, the only release ownership when Release() is called as many times as it was acquired.
  • function Is_Owner (Context : G_Main_Context) return Boolean;
    Determines whether this thread holds the (recursive) ownership of this context. This is useful to know before waiting on another thread that may be blocking to get ownership of context.
  • procedure Dispatch (Context : G_Main_Context);
    Dispatches all pending sources.
  • Main loop

  • function Depth return Integer;
    The main loop recursion level in the current thread. It returns 0 when called from the toplevel.
  • G_Source

  • function Default_Dispatch (Source : G_Source; Cb : G_Source_Func_User_Data; Data : System.Address) return Gboolean;
  • function G_Source_Type_New (Prepare : Source_Prepare_Func; Check : Source_Check_Func; Dispatch : Source_Dispatch_Func := Default_Dispatch'Access; Finalize : Source_Finalize_Func := null) return G_Source_Type;
    Create a new type of sources. This function is specific to GtkAda. The returned value is never freed. Most of the time, you do not need to create a new source type, or even call Source_New. Most things can be implemented through the careful use of Idle and Timeout callbacks. However, creating a new source type allows for cleaner code, by sharing the common part of the handling.

    For idle sources, the prepare and check functions always return TRUE to indicate that the source is always ready to be processed. The prepare function also returns a timeout value of 0 to ensure that the poll() call doesn't block (since that would be time wasted which could have been spent running the idle function).

    For timeout sources, the prepare and check functions both return TRUE if the timeout interval has expired. The prepare function also returns a timeout value to ensure that the poll() call doesn't block too long and miss the next timeout.

    For file descriptor sources, the prepare function typically returns FALSE, since it must wait until poll() has been called before it knows whether any events need to be processed. It sets the returned timeout to -1 to indicate that it doesn't mind how long the poll() call blocks. In the check function, it tests the results of the poll() call to see if the required condition has been met, and returns TRUE if so.

  • function Source_New (Source_Type : G_Source_Type; User_Data : System.Address) return G_Source;
    Creates a new GSource structure.

    The source will not initially be associated with any GMainContext and must be added to one with Attach() before it will be executed.

  • function Get_User_Data (Source : G_Source) return System.Address;
    Return the user data passed to Source_New. This only applies to sources created through that function, and returns undefined results (or even segfaults) otherwise
  • procedure Source_Ref (Source : G_Source);
    procedure Source_Unref (Source : G_Source);
    Increase or decrease the reference counting for Source. When this reaches 0, the Source is destroyed
  • procedure Source_Destroy (Source : G_Source);
    Removes the source from its context, and mark it as destroyed (the memory is not reclaimed while the reference counting doesn't reach 0). Source cannot be added to another context.
  • function Attach (Source : G_Source; Context : G_Main_Context := null) return G_Source_Id;
    Add Source to Context. The Source will be executed within that context. If context is null, the source is added to the default context. Returns the Id of the source within Context.
  • function Remove (Id : G_Source_Id) return Boolean;
    procedure Remove (Id : G_Source_Id);
    Removes the source with the given id from the default main context. The id of. Return True if the source was found and removed
  • procedure Set_Priority (Source : G_Source; Priority : G_Priority);
    function Get_Priority (Source : G_Source) return G_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.
  • procedure Set_Can_Recurse (Source : G_Source; Can_Recurse : Boolean);
    function Get_Can_Recurse (Source : G_Source) return Boolean;
    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.
  • function Get_Id (Source : G_Source) return G_Source_Id;
    Returns the numeric ID for a particular source. The ID of a source is positive integer which is unique within a particular main loop context. The reverse mapping from ID to source is done by Find_Source_By_Id
  • function Find_Source_By_Id (Id : G_Source_Id; Context : G_Main_Context := null) return G_Source;
    Find a source given a context and its Id.
  • function Get_Context (Source : G_Source) return G_Main_Context;
    Gets the context with which the source is associated. Calling this function on a destroyed source is an error. The returned value is Null for sources that haven't been attached yet
  • Idle and timeout

  • function Idle_Source_New return G_Source;
    Return a newly allocated idle G_Source. Such a source is polled whenever the main loop is not processing events with a higher priority. This source must be attached to a main context before it will be executed.
  • function Timeout_Source_New (Interval : Guint) return G_Source;
    Return a newly allocated idle G_Source. Such a source is called at regular intervals. Internval is in milliseconds.
  • function Idle_Add (Func : G_Source_Func) return G_Source_Id;
    Adds a function to be called whenever there are no higher priority events pending in the default main loop. This function is given the priority Priority_Default_Idle. If the function returns False, it is automatically removed from the list of event sources and will not be called again. This function returns the Id of the event source. See Find_Source_By_Id. This is implemented by using Idle_Source_New internally.
  • function Timeout_Add (Interval : Guint; Func : G_Source_Func) return G_Source_Id;
    Create a new function to be called periodically until it returns False.

    Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

  • function Idle_Add (Func : G_Source_Func; Data : Data_Type; Priority : G_Priority := Priority_Default_Idle; Notify : Destroy_Notify := null) return G_Source_Id;
    Adds a function to be called whenever there are no higher priority events pending.
  • function Timeout_Add (Interval : Guint; Func : G_Source_Func; Data : Data_Type; Priority : G_Priority := Priority_Default; Notify : Destroy_Notify := null) return G_Source_Id;
    Adds a function to be called at regular intervals (in milliseconds).
  • procedure Set_Callback (Source : G_Source; Func : G_Source_Func; Data : Data_Type; Notify : Destroy_Notify := null);
    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.

  • procedure Free_Data (D : System.Address);
  • function General_Cb (D : System.Address) return Gint;

Testgtk source code

This code is part of testgtk, a demo application packaged with GtkAda. Testgtk demonstrates the various widgets of GtkAda
----------------------------------------------------------------------- -- GtkAda - Ada95 binding for the Gimp Toolkit -- -- -- -- Copyright 2006 AdaCore -- -- -- -- This library is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public -- -- License as published by the Free Software Foundation; either -- -- version 2 of the License, or (at your option) any later version. -- -- -- -- This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public -- -- License along with this library; if not, write to the -- -- Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- -- Boston, MA 02111-1307, USA. -- -- -- -- -- -- -- -- -- -- ----------------------------------------------------------------------- with Ada.Calendar; use Ada.Calendar; with Glib.Main; use Glib, Glib.Main; with Gtk.Box; use Gtk.Box; with Gtk.Enums; use Gtk.Enums; with Gtk.Frame; use Gtk.Frame; with Gtk.Label; use Gtk.Label; with Gtk.Scrolled_Window; use Gtk.Scrolled_Window; with Gtk.Text_Buffer; use Gtk.Text_Buffer; with Gtk.Text_Iter; use Gtk.Text_Iter; with Gtk.Text_View; use Gtk.Text_View; with Gtk.Widget; use Gtk.Widget; with Gtkada.Handlers; use Gtkada.Handlers; with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; with System; with GNAT.OS_Lib; use GNAT.OS_Lib; with GNAT.Directory_Operations; use GNAT.Directory_Operations; with Ada.Text_IO; use Ada.Text_IO; package body Create_Sources is Buffer : Gtk_Text_Buffer; Id : G_Source_Id := 0; File_Monitor : G_Source_Type := Null_Source_Type; -- A particular kind of G_Source that monitors changes to a file. type String_Access is access String; type Source_User_Data is record File_Name : String_Access; Last_Check : Time; File_Timestamp : OS_Time := Invalid_Time; end record; type Source_User_Data_Access is access Source_User_Data; -- The user data stored in our monitor. -- We use it to avoid checking the file system too often function Convert is new Ada.Unchecked_Conversion (System.Address, Source_User_Data_Access); procedure On_Destroy (Box : access Gtk_Widget_Record'Class); -- Called when this demo is closed. ------------- -- Monitor -- ------------- -- This defines a new source type that monitors file events. procedure Create_Monitor (File_Name : String); -- Create a new input source that monitors changes in a file. function Prepare (Source : G_Source; Timeout : access Gint) return Gboolean; function Check (Source : G_Source) return Gboolean; procedure Finalize (Source : G_Source); -- See the documentation in glib-main.ads for these primitive operations -- of G_Source pragma Convention (C, Prepare); pragma Convention (C, Check); pragma Convention (C, Finalize); -------------- -- G_Source -- -------------- -- This is the implementation of a specific source of the type Monitor, -- which refreshes the graphical buffer to show the new file contents package String_Sources is new Generic_Sources (String); function Refresh_File (Filename : String) return Boolean; -- Refresh the contents of the file that the source was monitoring ---------- -- Help -- ---------- function Help return String is begin return "The main even loop of gtk+ is highly configurable. It monitors" & " various event sources, including the windowing system, pipes," & " running processes, timeouts... and will call user-defined" & " callbacks whenever some event happens." & ASCII.LF & "It is possible for you to define your own source of events, as" & " demonstrated here." & ASCII.LF & "This demo monitors a file on the disk (""sources"" in the testgtk/" & " directory. Open a text editor, create that file if necessary," & " add some data to it, and save. You will see immediately the new" & " contents of the file." & ASCII.LF & "While it certainly isn't the most efficient way to do that (having" & " a timeout that checks periodically might be more appropriate)," & " this demo shows how you can create your own event source. On" & " linux systems, the kernel is able to notify users whenever some" & " part of the file system changes. You could connect to dbus, on" & " which the kernel sends this info, and use this as an event source" & " in your application."; end Help; ------------------ -- Refresh_File -- ------------------ function Refresh_File (Filename : String) return Boolean is Start, Last : Gtk_Text_Iter; File : File_Type; Contents : String (1 .. 1024); L : Natural; begin Get_Start_Iter (Buffer, Start); Get_End_Iter (Buffer, Last); Delete (Buffer, Start, Last); Open (File, In_File, Get_Current_Dir & Filename); Insert_At_Cursor (Buffer, "File name is: " & Filename & ASCII.LF); loop Get_Line (File, Contents, L); exit when L = 0; Get_End_Iter (Buffer, Last); Insert (Buffer, Last, Contents (Contents'First .. L)); end loop; Close (File); return True; exception when End_Error => Close (File); return True; when Name_Error => return True; end Refresh_File; ------------- -- Prepare -- ------------- function Prepare (Source : G_Source; Timeout : access Gint) return Gboolean is Data : constant Source_User_Data_Access := Convert (Get_User_Data (Source)); T : OS_Time; begin -- Note: we always set the timeout to something suitable. If we don't, -- its default value of -1 will be used, which means that gtk+ will wait -- until one even is available somewhere (most likely a graphical -- event), and as a result Prepare will only be called after an event -- has been processed, which isn't what we want Timeout.all := 500; -- The timeout above ensures that we are not called less than every -- 500 ms. However, to spare system resources, which should ensure that -- we do not check the file system too often if Clock - Data.Last_Check > 0.4 then Data.Last_Check := Clock; -- Check whether the file has been modified T := File_Time_Stamp (Data.File_Name.all); if T /= Data.File_Timestamp then Data.File_Timestamp := T; return 1; else return 0; end if; else return 0; end if; end Prepare; ----------- -- Check -- ----------- function Check (Source : G_Source) return Gboolean is pragma Unreferenced (Source); begin return 0; end Check; -------------- -- Finalize -- -------------- procedure Finalize (Source : G_Source) is procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Source_User_Data, Source_User_Data_Access); procedure Unchecked_Free is new Ada.Unchecked_Deallocation (String, String_Access); Data : Source_User_Data_Access := Convert (Get_User_Data (Source)); begin Unchecked_Free (Data.File_Name); Unchecked_Free (Data); end Finalize; -------------------- -- Create_Monitor -- -------------------- procedure Create_Monitor (File_Name : String) is Source : G_Source; Data : Source_User_Data_Access; begin if File_Monitor = Null_Source_Type then File_Monitor := G_Source_Type_New (Prepare => Prepare'Access, Check => Check'Access, Finalize => Finalize'Access); end if; Data := new Source_User_Data' (Last_Check => Clock, File_Name => new String'(File_Name), File_Timestamp => Invalid_Time); Source := Source_New (File_Monitor, Data.all'Address); String_Sources.Set_Callback (Source, Refresh_File'Access, File_Name); -- Start executing Source Id := Attach (Source, null); end Create_Monitor; ---------------- -- On_Destroy -- ---------------- procedure On_Destroy (Box : access Gtk_Widget_Record'Class) is pragma Unreferenced (Box); begin if Id /= 0 then Remove (Id); Id := 0; Buffer := null; end if; end On_Destroy; --------- -- Run -- --------- procedure Run (F : access Gtk.Frame.Gtk_Frame_Record'Class) is Label : Gtk_Label; View : Gtk_Text_View; Box : Gtk_Box; Scrolled : Gtk_Scrolled_Window; begin Gtk_New_Vbox (Box, Homogeneous => False); Set_Label (F, "New event source for main loop"); Add (F, Box); Gtk_New (Label, "Edit and save the file ""sources"" in the current directory"); Pack_Start (Box, Label, Expand => False); Gtk_New (Label, "and let this demo monitor its contents"); Pack_Start (Box, Label, Expand => False); Gtk_New (Scrolled); Set_Policy (Scrolled, Policy_Automatic, Policy_Automatic); Pack_Start (Box, Scrolled, Expand => True, Fill => True); Gtk_New (Buffer); Gtk_New (View, Buffer); Add (Scrolled, View); Create_Monitor ("sources"); Widget_Callback.Connect (Box, "destroy", On_Destroy'Access); Show_All (Box); end Run; end Create_Sources;

Alphabetical Index