1

这一定是对 gnome-shell 扩展如何工作的一些基本误解(就我而言)。我努力寻找一些文档,但是,唉,它似乎有点稀疏。

我想编写一个简单的扩展程序来将焦点模式从 FFM 切换到单击面板中的图标单击焦点,因为我通常使用 FFM,但是某些程序被它破坏了。所以我从基础开始,gnome-shell-extension-tool --create-extension并通过以下方式对其进行了修改:

const St = imports.gi.St;
const Main = imports.ui.main;
const Tweener = imports.ui.tweener;

let text, button, icon;

var toggle;

function _hideHello() {
    Main.uiGroup.remove_actor(text);
    text = null;
}

function _showHello(what) {
    if (!text) {
        text = new St.Label({ style_class: 'helloworld-label', text: what });
        Main.uiGroup.add_actor(text);
    }

    text.opacity = 255;
    let monitor = Main.layoutManager.primaryMonitor;
    text.set_position(Math.floor(monitor.width / 2 - text.width / 2),
                      Math.floor(monitor.height / 2 - text.height / 2));
    Tweener.addTween(text,
                     { opacity: 0,
                       time: 2,
                       transition: 'easeOutQuad',
                       onComplete: _hideHello });
}

function _switch() {
    if (toggle == 0) {
        toggle = 1;
        _showHello("Setting toggle to " + toggle);
    }
    if (toggle == 1) {
        toggle = 0;
        _showHello("Setting toggle to " + toggle);
    }
}

function init() {
    button = new St.Bin({ style_class: 'panel-button',
                          reactive: true,
                          can_focus: true,
                          x_fill: true,
                          y_fill: false,
                          track_hover: true });
    icon = new St.Icon({ icon_name: 'system-run-symbolic',
                             style_class: 'system-status-icon' });
    button.set_child(icon);
    toggle = 0;
    button.connect('button-press-event', _switch);
}

function enable() {
    Main.panel._rightBox.insert_child_at_index(button, 0);
}

function disable() {
    Main.panel._rightBox.remove_child(button);
}

有一个(可能是幼稚的)想法,即每次按下按钮时,我都可以toggle从 0 切换到 1,反之亦然。

相反,每次我单击按钮时,都会显示相同的“设置切换为 1”消息。

谁能解释发生了什么?谢谢。

4

1 回答 1

2

我觉得里面有问题_switchif在第二个语句之前应该有一个 else 。没有它,第二if条语句将始终运行并且toggle始终为 0。

当前代码:

if (toggle == 0) { 
    toggle = 1;
    _showHello("Setting toggle to " + toggle);
}
if (toggle == 1) { //at this stage, toggle will always be 1
    toggle = 0;
    _showHello("Setting toggle to " + toggle);
}

建议的代码:

if (toggle == 0) {
    toggle = 1;
    _showHello("Setting toggle to " + toggle);
} else if (toggle == 1) {
    toggle = 0;
    _showHello("Setting toggle to " + toggle);
}

作为替代方案,您也可以考虑使用这些来切换值而不是使用if statements

toggle=!toggle; //value becomes true/false instead of 1/0 if that matters

toggle= toggle ? 0 : 1; //ternary operator

示例小提琴

于 2014-05-15T04:28:10.763 回答