How does one add an item to GTK's "recently used" file list from Python?
<p>I'm trying to add to the "recently used" files list from Python 3 on Ubuntu.</p>

<p>I am able to successfully <em>read</em> the recently used file list like this:</p>

<pre><code>from gi.repository import Gtk
recent_mgr = Gtk.RecentManager.get_default()
for item in recent_mgr.get_items():
    print(item.get_uri())
</code></pre>

<p>This prints out the same list of files I see when I look at "Recent" in Nautilus, or look at the "Recently Used" place in the file dialog of apps like GIMP.</p>

<p>However, when I tried adding an item like this (where <code>/home/laurence/foo/bar.txt</code> is an existing text file)...</p>

<pre><code>recent_mgr.add_item('file:///home/laurence/foo/bar.txt')
</code></pre>

<p>...the file does not show up in the Recent section of Nautilus or in file dialogs. It doesn't even show up in the results returned by <code>get_items()</code>.</p>

<p>How can I add a file to GTK's recently used file list from Python?</p>

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

<pre><code>from gi.repository import Gtk

recent_mgr = Gtk.RecentManager.get_default()
uri = r'file:/path/to/my/file'
recent_mgr.add_item(uri)
Gtk.main()
</code></pre>

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

<p>To answer @andlabs query, the reason why <code>RecentManager.add_item</code> returns a boolean is because the <code>g_file_query_info_async</code> function is called. The callback function <code>gtk_recent_manager_add_item_query_info</code> then gathers the mimetype, application name and command into a <code>GtkRecentData</code> struct and finally calls <code>gtk_recent_manager_add_full</code>. The source is <a href="https://github.com/GNOME/gtk/blob/master/gtk/gtkrecentmanager.c">here</a>.</p>

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

<p>The documentation is inaccurate in saying:</p>

<blockquote>
  <p>Returns</p>
  
  <p>TRUE if the new item was successfully added to the recently used resources list</p>
</blockquote>

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

python gtk pygtk gtk3