4

What's the best way to open a file in the default application from Vala? A bit like how xdg-open works.

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
Peter Uithoven
  • 705
  • 1
  • 6
  • 17

3 Answers3

6

I found some existing code in another application, but later on I also found this GLib.AppInfo.launch_default_for_uri method.

A simple example:

var file = File.new_for_path (file_path);
if (file.query_exists ()) {
    try {
        AppInfo.launch_default_for_uri (file.get_uri (), null);
    } catch (Error e) {
        warning ("Unable to launch %s", file_path);
    }
}
Peter Uithoven
  • 705
  • 1
  • 6
  • 17
1

If you're using GTK, then you've also got Gtk.gtk_show_uri_on_window(), which uses the GLib stuff under the hood.

Michael Gratton
  • 516
  • 2
  • 10
  • Could you clarify the difference? I'm curious why it includes "on_window". Could you include this link to the docs? https://valadoc.org/gtk+-3.0/Gtk.show_uri_on_window.html – Peter Uithoven Feb 27 '19 at 15:39
  • `Gtk.gtk_show_uri` and `Gtk.gtk_show_uri_on_window` both do thing the same thing, but the latter works better for apps packaged under Flatpak where the portal, a separate process, actually opens the URI. It lets the portal know what the desktop etc. is that it should open the app on. – Michael Gratton Feb 27 '19 at 22:29
0

As far as I know there is only one implementation of the relevant freedesktop.org standards.

That is the reference implementation in xdg-utils:

https://www.freedesktop.org/wiki/Software/xdg-utils/

The tools are written in shell script, for example here is the source code for xdg-open:

https://cgit.freedesktop.org/xdg/xdg-utils/tree/scripts/xdg-open.in

So by far the easiest way is to just call the xdg-open script via Process.spawn_async and friends.

If you insist on using a library function you would have to implement a standard conforming library yourself.

Update:

There are quite a few libraries in various languages that implement some of the freedesktop.org standards, for example here is a list on GitHub:

https://github.com/topics/xdg

For example here is a similar tool to xdg-open written in D:

https://github.com/FreeSlave/mimeapps/blob/master/source/mimeapps.d

What I didn't find so far is a Vala / GLib or plain C library that could easily be used from a Vala application.

Update 2:

Actually it turns out there is something for that purpose in GLib (or more precisely in Gio):

https://valadoc.org/gio-2.0/GLib.AppInfo.launch_default_for_uri_async.html

https://developer.gnome.org/gio/stable/GAppInfo.html

So you should be able to use the GLib.AppInfo.launch_default_for_uri_async method.

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
  • I wish StackOverflow had a better designed notification system, I only just read your answer. I've also stumbled on the the same function in the end. I've included an example. – Peter Uithoven Feb 26 '19 at 23:28