Search code examples
cgtkgnome

Why does my app crash when adding a valid keyboard accelerator to an action in GTK?


When I add a keyboard accelerator such as "<Ctrl>n" to an action in GTK using gtk_application_set_accels_for_action, the app crashes immediately:

// "app" & "handler" are defined here

const char *action_id = "action";
const char *full_id = "app.action";
// Remove "Ctrl" ({ "<>n" })
// or add an invalid shortcut ({ "<Ctrl>n", "<>f" })
// and the app doesn't crash.
const char *keyboard_shortcuts[] = { "<Ctrl>n" };

GSimpleAction *action = g_simple_action_new (action_id, NULL);
g_action_map_add_action (G_ACTION_MAP (app), G_ACTION (action));
g_signal_connect (action, "activate", G_CALLBACK (handler), NULL);
// Remove the following line and the app doesn't crash.
gtk_application_set_accels_for_action (GTK_APPLICATION (app), full_id, keyboard_shortcuts);

Whenever I change the keyboard shortcut to something invalid (such as "<>n") or add an invalid keyboard shortcut to the array ({ "<Ctrl>n", "<>f" }), the app runs as expected, but no keyboard shortcuts work.

Here is the code of a minimal app showcasing the problem.


Solution

  • gtk_application_set_accels_for_action() requires the accelerators to be given as a null-terminated array of pointers to strings. You are failing to do that. There is every reason to think that the result will be GTK overrunning the bounds of your array, thus producing undefined behavior. You appear to want this:

    const char *keyboard_shortcuts[] = { "<Ctrl>n", NULL };