从Vala打开默认应用程序中文件的最佳方法是什么?有点像xdg-open
的工作方式。
我在另一个应用程序中找到了一些现有代码,但后来我也发现了这个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);
}
}
如果你正在使用GTK,那么你也得到了Gtk.gtk_show_uri_on_window()
,它使用引擎盖下的GLib。
据我所知,只有一个相关的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的列表:
例如,这里是一个与Dd编写的xdg-open类似的工具:
https://github.com/FreeSlave/mimeapps/blob/master/source/mimeapps.d
到目前为止我没有找到的是Vala / GLib或普通C库,可以很容易地从Vala应用程序中使用。
更新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
方法。