使用Vala的默认应用程序打开文件?

时间:2019-02-26 13:16:22

标签: vala xdgutils freedesktop.org

在Vala的默认应用程序中打开文件的最佳方法是什么? 有点像xdg-open的工作方式。

3 个答案:

答案 0 :(得分:4)

我在另一个应用程序中找到了一些现有代码,但后来我也发现了这一点 GLib.AppInfo.launch_default_for_uri方法。

一个简单的例子:

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);
    }
}

答案 1 :(得分:1)

如果您使用的是GTK,那么您还可以获得Gtk.gtk_show_uri_on_window(),它在幕后使用了GLib。

答案 2 :(得分:0)

据我所知,相关的freedesktop.org标准只有一种实现方式。

这是xdg-utils中的参考实现:

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

这些工具是用Shell脚本编写的,例如,这是xdg-open的源代码:

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

因此,到目前为止,最简单的方法是仅通过Process.spawn_async和朋友调用xdg-open脚本。

如果您坚持使用库函数,则必须自己实现符合标准的库。

更新

有许多实现各种freedesktop.org标准的各种语言的库,例如,以下是GitHub上的列表:

https://github.com/topics/xdg

例如,这是与用D编写的xdg-open类似的工具:

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

到目前为止,我找不到的是可以轻松地从Vala应用程序中使用的Vala / GLib或纯C库。

更新2:

实际上,GLib(或更确切地说,在Gio中)确实有一些目的:

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

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

因此,您应该可以使用GLib.AppInfo.launch_default_for_uri_async方法。

相关问题