DEFINITION MODULE GtkUtils ; (* m2-GTK4 - small pure-Modula-2 helpers over the FOR "C" bindings. CStrToM2 copies a borrowed NUL-terminated C string (ADDRESS) into a Modula-2 CHAR array. The destination is always NUL-terminated and the copy is truncated to fit. StrAppend appends a NUL-terminated string onto the end of another, truncating to fit and keeping it NUL-terminated. IntToStr renders an INTEGER as a decimal string. Connect wraps GObject.g_signal_connect_data() with the defaults C's g_signal_connect() macro would use, returning the handler id so it can be disconnected later. SetAccel installs one keyboard accelerator for a detailed action name (e.g. SetAccel(app, "app.quit", "q")). C wants a NULL-terminated array of strings, which this builds on the stack and passes to gtk_application_set_accels_for_action(). Unref releases a GObject reference (NIL-checked). Free releases memory from g_malloc/g_strdup/... (NIL-checked). ErrorMessage copies a GError's message into a CHAR array. ClearError frees a GError and sets the variable to NIL. Connect is a real procedure (not a C binding): pass the handler as ADR(proc), e.g. Connect(button, "clicked", ADR(OnClicked), NIL); Ownership --------- Modula-2 has no destructors, so follow the C transfer rules: * GtkUtils.Unref (g_object_unref) for GObject handles; * GtkUtils.Free (g_free) for strings returned by getters (g_file_get_basename, g_settings_get_string, ...); * GtkUtils.ClearError for GError values; * GVariant values from g_variant_get_*/g_action_get_state need g_variant_unref, while g_variant_new_* are floating. *) FROM SYSTEM IMPORT ADDRESS; FROM GError IMPORT GError; EXPORT UNQUALIFIED CStrToM2, StrAppend, IntToStr, Connect, SetAccel, Unref, Free, ErrorMessage, ClearError; PROCEDURE CStrToM2 (src: ADDRESS; VAR dst: ARRAY OF CHAR); PROCEDURE StrAppend (VAR dst: ARRAY OF CHAR; src: ARRAY OF CHAR); PROCEDURE IntToStr (n: INTEGER; VAR dst: ARRAY OF CHAR); PROCEDURE Connect (instance: ADDRESS; signal: ARRAY OF CHAR; handler: ADDRESS; data: ADDRESS) : [ LONGCARD ]; PROCEDURE SetAccel (application: ADDRESS; action: ARRAY OF CHAR; accel: ARRAY OF CHAR); PROCEDURE Unref (obj: ADDRESS); PROCEDURE Free (ptr: ADDRESS); PROCEDURE ErrorMessage (err: GError; VAR dst: ARRAY OF CHAR); PROCEDURE ClearError (VAR err: GError); END GtkUtils.