GtkTextView: How to intercept context menu before it's shown (for both right-click and keyboard)?

I have a GtkSourceView subclass with grammar linting. When the user opens the context menu, I need to inspect the cursor/pointer position, find any lint spans covering that position, and inject fix suggestions as menu items via set_extra_menu. What is the correct GTK4 pattern for dynamically populating a GtkTextView context menu immediately before it is shown, for both mouse and keyboard triggers? Is there a virtual method, signal, or action interception pattern that covers both cases? From what I can tell reading the docs, there apparently used to be a populate-popup signal in GTK3 that seems to have served this purpose, but it was removed in GTK4. My current workaround is a GestureClick handler that updates set_extra_menu on right-click, but this misses keyboard activation entirely. Is there a supported GTK4 mechanism for this?

1 Like

Some places to look for possible answers:

  • The GTK 3 → 4 porting guide.
  • The source code of libspelling (it should, I suppose, add menu items to the context menu of a GtkTextView).
1 Like

Hi,

In general, avoid using set_extra_menu, prefer get_extra_menu and insert a section that you can later fully control/modify:

# Python
my_menu_model = Gio.Menu()
textview.get_extra_menu().append_section(_("Grammar"), my_menu_model)

Then you can add/remove items in my_menu_model anytime, typically when the cursor context changes.
(it’s what libspelling does: monitor the cursor, detect the word below, if changed look for the spellchecker asynchronously and refresh the proposals model)

I’m not aware of a replacement. Seems the trick is to keep the menu model up-to-date so when the context menu pops-up it will have the data ready.