How does one add an item to GTK's "recently used" file list from Python? How does one add an item to GTK's "recently used" file list from Python? python python

How does one add an item to GTK's "recently used" file list from Python?


A Gtk.RecentManager needs to emit the changed signal for the update to be written in a private attribute of the C++ class. To use a RecentManager object in an application, you need to start the event loop by calling Gtk.main:

from gi.repository import Gtkrecent_mgr = Gtk.RecentManager.get_default()uri = r'file:/path/to/my/file'recent_mgr.add_item(uri)Gtk.main()

If you don't call Gtk.main(), the changed signal is not emitted and nothing happens.

To answer @andlabs query, the reason why RecentManager.add_item returns a boolean is because the g_file_query_info_async function is called. The callback function gtk_recent_manager_add_item_query_info then gathers the mimetype, application name and command into a GtkRecentData struct and finally calls gtk_recent_manager_add_full. The source is here.

If anything goes wrong, it is well after add_item has finished, so the method just returns True if the object it is called from is a RecentManager and if the uri is not NULL; and False otherwise.

The documentation is inaccurate in saying:

Returns TRUE if the new item was successfully added to the recently used resources list

as returning TRUE only means that an asynchronous function was called to deal with the addition of a new item.

As suggested by Laurence Gonsalves, the following runs pseudo-synchronously:

from gi.repository import Gtk, GObjectrecent_mgr = Gtk.RecentManager.get_default()uri = r'file:/path/to/my/file'recent_mgr.add_item(uri)GObject.idle_add(Gtk.main_quit)Gtk.main()


This is my solution (complet script) with timer for quit GTK.main() loop

#!/usr/bin/env python3import gigi.require_version("Gtk", "3.0")from gi.repository import Gtk, GLibimport sysimport osimport subprocessrecent_mgr = Gtk.RecentManager.get_default()if len(sys.argv) <= 1:    paths = (os.getcwd(),)else:    paths = sys.argv[1:]for path in paths:    if os.path.exists(path):        if path[0] != "/":            path = os.getcwd() + "/" + path        subprocess.call(["touch", "-a", path])        uri = r"file:" + path        recent_mgr.add_item(uri)GLib.timeout_add(22, Gtk.main_quit, None)Gtk.main()