Open file with default application from Vala?
Asked Answered
C

3

5

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

Curst answered 26/2, 2019 at 13:16 Comment(0)
C
7

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);
    }
}
Curst answered 26/2, 2019 at 23:27 Comment(0)
P
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.

Pitchy answered 27/2, 2019 at 7:40 Comment(2)
Could you clarify the difference? I'm curious why it includes "on_window". Could you include this link to the docs? valadoc.org/gtk+-3.0/Gtk.show_uri_on_window.htmlCurst
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.Pitchy
S
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.

Sorption answered 26/2, 2019 at 15:4 Comment(1)
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.Curst

© 2022 - 2024 — McMap. All rights reserved.