网站搜索

javascript - 无法通过 GSettings 更改 dconf 条目


我目前正在使用 Gjs 构建一个简单的应用程序,该应用程序应该更改我的 GNOME Shell 的背景图片。关于如何使用 gsettings 工具实现这一点的解决方案可以在这里找到。

由于我想围绕它构建一个桌面应用程序,我想使用 Gio 的 GSettings 类来更改 org.gnome.desktop.background.picture-uri 键。但使用 set_X() 方法并没有更改该键的值。

这是我用于更改 gsettings 值的代码:

var gio = imports.gi.Gio;

// Get the GSettings-object for the background-schema:
var background = new gio.Settings({schema: "org.gnome.desktop.background"});

// Read the current Background-Image:
print( "Current Background-Image: "+background.get_string("picture-uri") );

if (background.is_writable("picture-uri")){
    // Set a new Background-Image (should show up immediately):
    if (background.set_string("picture-uri", "file:///path/to/some/pic.jpg")){
        print("Success!");
    }
    else throw "Couldn't set the key!";
} else throw "The key is not writable";

读取该值确实如预期般工作,is_writable() 方法返回 true,set_string() 方法也返回 true。

我已经检查过我不在“delay-apply”模式,并且该键的 GVariantType 是字符串,所以 set_string() 方法应该可以工作。

使用常规的 gsettings 命令行工具(如链接帖子中所解释的)完全可以正常工作。

我无法弄清楚问题出在哪里,有没有什么地方可以查看日志之类的?

答案#1

在这里没有得到任何回应后,我在 gjs 邮件列表上问了同样的问题。

事实证明,当我的脚本退出时,对 dconf 的写入还没有写入磁盘,所以它们实际上从未真正应用过。

解决方法是在 set_string() 函数之后立即调用 g_settings_sync() 函数(JsDoc),以确保所有写入操作已完成。

if (background.set_string("picture-uri", "file:///path/to/some/pic.jpg")){
    gio.Settings.sync()
    print("Success!");
}

感谢 Johan Dahlin 及他的回答。