### GTK UI Definition File Example
Source: https://developer.gnome.org/documentation/tutorials/widget-templates
An example of an XML file defining a GTK widget's UI structure, including child widgets like an entry and a button. This file is typically bundled with the application using GResource.
```xml
```
--------------------------------
### C: Initiate Asynchronous Connection and Read
Source: https://developer.gnome.org/documentation/tutorials/asynchronous-programming
Initiates an asynchronous connection to a server and then starts an asynchronous read operation in C using gio library. It uses G_PRIORITY_DEFAULT for the read operation and a cancellable object for managing the connection process. Errors during connection setup are handled.
```c
/* any time. The buffer could instead be allocated dynamically if this is a
* problem. */
input_stream = g_io_stream_get_input_stream (G_IO_STREAM (connection));
g_input_stream_read_async (input_stream,
priv->message_buffer,
sizeof (priv->message_buffer),
G_PRIORITY_DEFAULT, priv->connect_cancellable,
connect_to_server_cb3, self);
done:
if (error != NULL)
{
/* Stop the operation. */
if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
{
g_warning ("Failed to connect to server: %s", error->message);
}
g_clear_object (&priv->connect_cancellable);
g_clear_object (&priv->connection);
g_error_free (error);
}
g_clear_object (&connection);
```
--------------------------------
### Basic GLib Object Initialization in Python
Source: https://developer.gnome.org/documentation/tutorials/asynchronous-programming
Demonstrates the basic import and usage of GObject from the gi.repository in Python. This snippet is typically the starting point for any application using GLib's object system in Python, enabling object-oriented programming patterns.
```python
import logging
from gi.repository import GObject
```
--------------------------------
### GLib/GTK Floating References Example (C)
Source: https://developer.gnome.org/documentation/guidelines/programming/memory-management
Demonstrates the usage of floating references in GTK to simplify widget creation and addition to containers. Without floating references, explicit unreferencing is required, leading to more verbose code. The example highlights the conciseness achieved by directly adding newly created widgets to a container, relying on g_object_ref_sink() to manage the reference count.
```c
// Without floating references
GtkWidget *new_widget;
new_widget = gtk_some_widget_new ();
gtk_container_add (some_container, new_widget);
g_object_unref (new_widget);
// With floating references
gtk_container_add (some_container, gtk_some_widget_new ());
```
--------------------------------
### Create and Configure GtkMenuButton
Source: https://developer.gnome.org/documentation/tutorials/beginners/components/menu_button
Demonstrates creating a GtkMenuButton, setting its icon, and associating a menu model. The 'menu' variable is assumed to be defined elsewhere. These examples cover C, Vala, JavaScript, and XML implementations.
```c
GtkWidget *button = gtk_menu_button_new ();
gtk_menu_button_set_icon_name (GTK_MENU_BUTTON (button), "open-menu-symbolic");
// "menu" is defined elsewhere
gtk_menu_button_set_menu_model (GTK_MENU_BUTTON (button), menu);
```
```vala
// "menu" is defined elsewhere
button = Gtk.MenuButton(icon_name="open-menu-symbolic", menu_model=menu)
```
```javascript
// "menu" is defined elsewhere
var button = new Gtk.MenuButton () {
icon_name = "open-menu-symbolic",
menu_model = menu
};
```
```javascript
// "menu" is defined elsewhere
const button = new Gtk.MenuButton({
icon_name: "open-menu-symbolic",
menu_model: menu,
});
```
```xml
```
--------------------------------
### Create Basic GtkLabel Widget
Source: https://developer.gnome.org/documentation/tutorials/beginners/components/label
Provides examples of creating a basic GtkLabel widget and adding it to a GtkBox container. This serves as a foundation for more complex label configurations.
```C
// Add a switch to enable a feature
GtkWidget *box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
GtkWidget *sw = gtk_switch_new ();
GtkWidget *label = gtk_label_new ("Enable feature");gtk_box_append (GTK_BOX (box), label);gtk_box_append (GTK_BOX (box), sw);
```
```Vala
# Add a switch to enable a feature
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
switch = Gtk.Switch()
label = Gtk.Label(text="Enable feature")
box.append(label)
box.append(switch)
```
```JavaScript
var box = new Gtk.Box (Gtk.Orientation.HORIZONTAL, 12);
var switch = new Gtk.Switch ();
var label = new Gtk.Label ("Enable feature");
box.append (label);
box.append (switch);
```
```JavaScript (ES6)
// Add a switch to enable a feature
const box = new Gtk.Box({
orientation: Gtk.Orientation.HORIZONTAL,
spacing: 12,
});
const sw = new Gtk.Switch();
const label = new Gtk.Label({
label: "Enable feature",
});
box.append(label);
box.append(sw);
```
--------------------------------
### Bind Window State Properties using Vala (GSettings)
Source: https://developer.gnome.org/documentation/tutorials/beginners/getting_started/saving_state
This Vala code example shows the initialization of an Adw.ApplicationWindow and the binding of GSettings keys to window properties. It ensures that 'window-width', 'window-height', and 'window-maximized' are persisted across application sessions.
```vala
namespace TextViewer {
public class Window : Adw.ApplicationWindow {
// ...
public Window (Gtk.Application app) {
Object (application: app);
}
construct {
var open_action = new SimpleAction ("open", null);
open_action.activate.connect (this.open_file_dialog);
this.add_action (open_action);
var save_action = new SimpleAction ("save-as", null);
save_action.activate.connect (this.save_file_dialog);
self.add_action (save_action);
Gtk.TextBuffer buffer = this.text_view.buffer;
buffer.notify["cursor-position"].connect (this.update_cursor_position);
this.settings.bind ("window-width", this, "default-width", SettingsBindFlags.DEFAULT);
this.settings.bind ("window-height", this, "default-height", SettingsBindFlags.DEFAULT);
this.settings.bind ("window-maximized", this, "maximized", SettingsBindFlags.DEFAULT);
}
}
}
```
--------------------------------
### Initiate Asynchronous File Read (CPython, Vala, JavaScript)
Source: https://developer.gnome.org/documentation/tutorials/beginners/getting_started/opening_files
Starts the asynchronous operation to read the contents of a file. This function is non-blocking and uses a callback mechanism to handle completion. Dependencies include Gio library for file operations.
```c
static void
open_file (TextViewerWindow *self,
GFile *file)
{
g_file_load_contents_async (file,
NULL,
(GAsyncReadyCallback) open_file_complete,
self);
}
```
```python
def open_file(self, file):
file.load_contents_async(None, self.open_file_complete)
```
```vala
private void open_file (File file) {
file.load_contents_async.begin (null, (object, result) => {});
}
```
--------------------------------
### Asynchronous Server Connection with Gio and GLib
Source: https://developer.gnome.org/documentation/tutorials/asynchronous-programming
Initiates an asynchronous connection to a server using Gio.Task for managing the operation. It handles setup, address parsing, socket connection, and message reading, with robust error handling and support for cancellation. Dependencies include gi.repository.GLib and gi.repository.Gio.
```Python
from gi.repository import GLib
from gi.repository import Gio
from dataclasses import dataclass
@dataclass
class ConnectToServerData:
connection: Gio.SocketConnection = None
message_buffer: list = None
class MyObject(GObject.Object):
connect_task = None
def connect_to_server_async(self, cancellable, callback, user_data):
if self.connect_task is not None:
error = GLib.Error("Already connecting to the server.",
Gio.io_error_quark(),
Gio.IOErrorEnum.PENDING)
Gio.Task.report_error(self, callback, user_data, None, error)
return
cancellable = cancellable or Gio.Cancellable()
original_callback = callback
def callback(source_object, result, not_user_data):
original_callback(source_object, result, user_data)
task = Gio.Task.new(self, cancellable, callback, user_data)
task.set_check_cancellable(False)
task.task_data = ConnectToServerData()
self.connect_task = task
address_file = build_address_file()
address_file.load_contents_async(cancellable,
connect_to_server_cb1,
task)
def connect_to_server_cb1(self, address_file, result, task):
try:
address, etags = address_file.load_contents_finish(result)
try:
inet_address = Gio.InetAddress.new_from_string(address)
except TypeError:
raise GLib.Error("Invalid address ‘%s’." % address,
Gio.io_error_quark(),
Gio.IOErrorEnum.INVALID_ARGUMENT)
except GLib.Error as err:
self.connect_task = None
task.return_error(err)
return
port = 123
inet_socket_address = Gio.InetSocketAddress.new(inet_address, port)
socket_client = Gio.SocketClient()
socket_client.connect_async(inet_socket_address,
task.get_cancellable(),
connect_to_server_cb2,
task)
def connect_to_server_cb2(self, socket_client, result, task):
data = task.task_data
try:
connection = socket_client.connect_finish(result)
except GLib.Error as err:
self.connect_task = None
task.return_error(err)
return
data.connection = connection
input_stream = connection.get_input_stream()
data.message_buffer = input_stream.read_async(GLib.PRIORITY_DEFAULT,
task.get_cancellable(),
connect_to_server_cb3,
task)
def connect_to_server_cb3(self, input_stream, result, task):
data = task.task_data
try:
length = input_stream.read_finish(result)
assert 0 <= length <= len(data.message_buffer)
self.handle_received_message(data.message_buffer, length)
task.return_boolean(True)
except GLib.Error as err:
self.connect_task = None
task.return_error(err)
def connect_to_server_finish(self, result):
if not Gio.Task.is_valid(result, self):
return False
```
--------------------------------
### Create GNOME Application Window (C)
Source: https://developer.gnome.org/documentation/tutorials/beginners/components/window
This C code demonstrates how to create a minimal GNOME application with a window and a title using the Adwaita library. It initializes the application, defines an activate function to create and present the window, and runs the application. Dependencies include adwaita and gtk.
```c
#include
G_DECLARE_FINAL_TYPE (MyApplication, my_application, MY, APPLICATION, AdwApplication)
struct _MyApplication {
AdwApplication parent_instance;
};
G_DEFINE_TYPE (MyApplication, my_application, ADW_TYPE_APPLICATION)
static void
my_application_activate (GApplication *application)
{
// create a Gtk Window belonging to the application itself
GtkWidget *window =
gtk_application_window_new (GTK_APPLICATION (application));
gtk_window_set_title (GTK_WINDOW (window), "Welcome to GNOME");
gtk_window_present (GTK_WINDOW (window));
}
static void
my_application_class_init (MyApplicationClass *klass)
{
G_APPLICATION_CLASS (klass)->activate = my_application_activate;
}
static void
my_application_init (MyApplication *self)
{
}
int
main (int argc,
char *argv[])
{
GApplication *app =
g_object_new (my_application_get_type (),
"application-id", "com.example.Application",
NULL);
return g_application_run (app, argc, argv);
}
```
--------------------------------
### Initialize GSettings in C for TextViewerWindow
Source: https://developer.gnome.org/documentation/tutorials/beginners/getting_started/saving_state
Demonstrates how to initialize a GSettings instance for the 'com.example.TextViewer' schema within the TextViewerWindow initialization function in C. This involves creating the GSettings object and assigning it to the 'settings' member of the TextViewerWindow structure.
```c
static void
text_viewer_window_init (TextViewerWindow *self)
{
gtk_widget_init_template (GTK_WIDGET (self));
g_autoptr (GSimpleAction) open_action = g_simple_action_new ("open", NULL);
g_signal_connect (open_action, "activate", G_CALLBACK (text_viewer_window__open_file_dialog), self);
g_action_map_add_action (G_ACTION_MAP (self), G_ACTION (open_action));
g_autoptr (GSimpleAction) save_action = g_simple_action_new ("save-as", NULL);
g_signal_connect (save_action, "activate", G_CALLBACK (text_viewer_window__save_file_dialog), self);
g_action_map_add_action (G_ACTION_MAP (self), G_ACTION (save_action));
GtkTextBuffer *buffer = gtk_text_view_get_buffer (self->main_text_view);
g_signal_connect (buffer,
"notify::cursor-position",
G_CALLBACK (text_viewer_window__update_cursor_position),
self);
self->settings = g_settings_new ("com.example.TextViewer");
}
```
--------------------------------
### Start and Stop Spinner - CPython
Source: https://developer.gnome.org/documentation/tutorials/beginners/components/spinner
Demonstrates how to create, start, and stop a GtkSpinner widget in CPython. The spinner is automatically stopped after 5 seconds using a timeout function. It relies on the GTK library.
```c
static gboolean
stop_spinner (gpointer data)
{
GtkSpinner *spinner = data;
gtk_spinner_stop (spinner);
return G_SOURCE_REMOVE;
}
GtkWidget *spinner = gtk_spinner_new ();
gtk_spinner_start (GTK_SPINNER (spinner));
// Stop spinner after 5 seconds
g_timeout_add_seconds (5, stop_spinner, spinner);
```
```python
spinner = Gtk.Spinner()
spinner.start()
def stop_spinner(spinner):
spinner.stop()
return GLib.SOURCE_REMOVE
GLib.timeout_add_seconds(5, stop_spinner, spinner)
```
```javascript
var spinner = new Gtk.Spinner ();
spinner.start ();
// Stop spinner after 5 seconds
Timeout.add_seconds (5, () => {
spinner.stop ();
return Source.REMOVE;
});
```
```javascript
const spinner = new Gtk.Spinner();
spinner.start();
// Stop spinner after 5 seconds
GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 5, () => {
spinner.stop();
return GLib.SOURCE_REMOVE;
});
```
--------------------------------
### Add Actions to GtkApplicationWindow (CPython, Vala, JavaScript)
Source: https://developer.gnome.org/documentation/tutorials/actions
Demonstrates how to add a 'save' action to a GtkApplicationWindow and connect it to a button. This involves creating a SimpleAction, connecting its 'activate' signal, and adding it to the window's action map. The button is then configured to trigger this action. This pattern is common for user-initiated commands.
```c
static void
on_save_activate (GAction *action,
GVariant *param)
{
g_print ("You are welcome");
}
static void
on_app_activate (GApplication *app)
{
GtkWidget *window = gtk_application_window_new (GTK_APPLICATION (app));
gtk_window_present (GTK_WINDOW (window));
GAction *action = g_simple_action_new ("save", NULL);
g_signal_connect (action, "activate", G_CALLBACK (on_save_activate), NULL);
g_action_map_add_action (G_ACTION_MAP (window), action);
GtkWidget *button = gtk_button_new_with_label ("Save");
gtk_window_set_child (GTK_WINDOW (window), button);
gtk_actionable_set_action_name (GTK_ACTIONABLE (button), "win.save");
}
// ...
int
main (int argc,
char *argv[])
{
GtkApplication *app =
gtk_application_new ("com.example.App", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (on_app_activate), NULL);
return g_application_run (G_APPLICATION (app), argc, argv);
}
```
```python
from gi.repository import Gio, Gtk
def on_save_activate(action, _):
print "You are welcome"
def on_app_activate(app):
window = Gtk.ApplicationWindow(application=app)
window.present()
action = Gio.SimpleAction(name="save")
action.connect("activate", on_save_activate)
window.add_action(action)
button = Gtk.Button(label="Save")
window.set_child(button)
button.set_action_name("win.save")
app = Gtk.Application()
app.connect("activate", on_app_activate)
app.run([])
```
```vala
public class Example.App : Gtk.Application {
public App () {
Object (application_id: "com.example.App",
flags: ApplicationFlags.FLAGS_NONE);
}
public override void activate () {
var window = new Gtk.ApplicationWindow (this);
window.present ();
var action = new SimpleAction ("save", null);
action.activate.connect (() => {
stdout.printf ("You are welcome\n");
});
window.add_action (action);
var button = new Gtk.Button ("Save");
window.child = button;
button.action_name = "win.save";
}
public static int main (string[] args) {
var app = new Example.App ();
return app.run (args);
}
}
```
```javascript
import Gtk from "gi://Gtk?version=4.0";
import Adw from "gi://Adw?version=1";
import Gio from "gi://Gio";
function on_save_activate(action, param) {
log("You are welcome");
}
function on_app_activate(app) {
const window = new Gtk.ApplicationWindow({ application });
window.present();
const action = new Gio.SimpleAction({ name: "save" });
action.connect("activate", on_save_activate);
window.add_action(action);
const button = new Gtk.Button({ label: "Save" });
window.set_child(button);
button.set_action_name("win.save");
}
const application = new Gtk.Application();
application.connect("activate", on_app_activate);
application.run([]);
```
--------------------------------
### Add Open Action and Shortcut in Vala
Source: https://developer.gnome.org/documentation/tutorials/beginners/getting_started/opening_files
This Vala snippet illustrates adding the 'open' action to TextViewer.Window. It includes creating a SimpleAction within a construct block and connecting its activation to a handler. The 'Ctrl+O' accelerator is then configured for the 'win.open' action in the application's initialization.
```vala
namespace TextViewer {
[GtkTemplate (ui = "/org/example/app/window.ui")]
public class Window : Gtk.ApplicationWindow {
[GtkChild]
private unowned Gtk.TextView main_text_view;
[GtkChild]
private unowned Gtk.Button open_button;
public Window (Gtk.Application app) {
Object (application: app);
}
construct {
var open_action = new SimpleAction ("open", null);
open_action.activate.connect (this.open_file_dialog);
this.add_action (open_action);
}
}
}
public Application () {
Object (application_id: "com.example.TextViewer",
flags: ApplicationFlags.FLAGS_NONE);
}
construct {
// ...
this.set_accels_for_action ("win.open", { "o" });
}
```
--------------------------------
### C Compiler Deprecation Warning Example
Source: https://developer.gnome.org/documentation/tutorials/deprecations
Shows an example of a C compiler warning generated when a deprecated function is used during compilation. This warning helps developers identify and address the use of outdated APIs.
```c
$ make testheaderbar
CC testheaderbar.o
testheaderbar.c: In function ‘main’:
testheaderbar.c:192:3: warning: ‘gtk_window_reshow_with_initial_size’ is deprecated (declared at ../gtk/gtkwindow.h:419) [-Wdeprecated-declarations]
gtk_window_reshow_with_initial_size (GTK_WINDOW (window));
^
CCLD testheaderbar
```
--------------------------------
### Install Icons Using Meson Build System
Source: https://developer.gnome.org/documentation/tutorials/themed-icons
Demonstrates how to install application icons to the correct directories within the system's icon theme structure using the Meson build system. This ensures that icons are discoverable by the GtkIconTheme.
```meson
# Define PKG_DATADIR as a global symbol
pkg_datadir = get_option('prefix') / get_option('datadir') / meson.project_name()
add_project_arguments('-DPKG_DATADIR=@0@'.format(datadir), language: 'c')
# List the icons to install
action_icons_dir = pkg_datadir / 'icons/hicolor/16x16/actions'
action_icons = [
'action-name-1.png',
'action-name-2.png',
]
# Install the icons
install_data(action_icons, install_dir: action_icons_dir)
```
--------------------------------
### Initialize GSettings in Python for TextViewerWindow
Source: https://developer.gnome.org/documentation/tutorials/beginners/getting_started/saving_state
Illustrates how to initialize a GSettings instance for the 'com.example.TextViewer' schema in the `__init__` method of the TextViewerWindow class using Python. This makes the settings accessible for the lifetime of the window object.
```python
def __init__(self, **kwargs):
super().__init__(**kwargs)
open_action = Gio.SimpleAction(name="open")
open_action.connect("activate", self.open_file_dialog)
self.add_action(open_action)
save_action = Gio.SimpleAction(name="save-as")
save_action.connect("activate", self.save_file_dialog)
self.add_action(save_action)
buffer = self.main_text_view.get_buffer()
buffer.connect("notify::cursor-position", self.update_cursor_position)
self.settings = Gio.Settings(schema_id="com.example.TextViewer")
```
--------------------------------
### Original UI Definition (XML)
Source: https://developer.gnome.org/documentation/tutorials/widget-templates
This snippet shows an example of a complex UI definition with nested widgets, illustrating the need for templates to improve maintainability.
```xml