[RFE] API for context menus on custom widgets in GTK4
Having a look through the code in the current master (473ed75e), it seems
GtkNotebook and others all implement a very similar pattern:
- Define a function that handles creating a
GMenuModelassociated with the widget and positioning it per invocation-specific coordinates
- Add a
menu.popupaction handled by calling said function with default coordinates, with action bindings to Shift+F10 and the menu key
- Add a
GtkGestureClickhandler that calls said function if
GDK_KEY_Menu in GTK returns matches in more than a dozen files, so this appears to be a fairly common thing.
GtkText etc expose convenient
GMenuModel-based API that hides these details, but this all has to be reproduced by the user if, for example, they want context menus on a
GtkListBoxRow. Besides being a pain in the neck, it doesn't seem reasonable to expect people to replicate it correctly: I, for one, didn't even know about Shift+F10, and I think about the menu key so infrequently that I've hardly noticed it missing from my keyboard!
Is it possible some API could be introduced to abstract some or all of these details? If it helps, I can think of some (possibly questionable) approaches:
- Add a new event controller subclass,
GtkContextMenuController(?), that has a
GMenuModelproperty and does all the stuff required to make that appear as a context menu on its widget when appropriate. I quite like this sort of solution, since it's applicable to arbitrary widgets and can be done entirely in the GTK Builder interface description, but it seems incongruent with the other event controllers in that it implements some behaviour in response to events instead of just providing an interface for other code to respond to events.
- Give the
menu.popupaction some sort of special status within the toolkit, such that context menus are handled automatically on widgets implementing some interface that exposes a
GMenuModel; maybe something like
GtkContextMenuable(hopefully with a better name ;) that requires
GtkActionableand has a menu model property. Or maybe just adding a
GMenuModelproperty directly to
- A less invasive approach might be to move the function(s) creating/placing the popover into
GtkWidgetand expose it (
gtk_widget_create_and_place_menu(GtkWidget*, GMenuModel*, GdkEvent*)?); that would disentangle the popover placement from the event source. Adding a pre-defined
GtkShortcutTriggerthat knew about context menu shortcuts would then abstract the details of popover placement and exact key combinations away from widgets that needed to manually implement context menu support.
I must admit, I haven't fully digested the changes to event handling in GTK4, so perhaps none of the above are appropriate; nonetheless, hopefully it might serve as a place from which to start.