Home > Mobile >  How to use a main loop in a Gnome Extension?
How to use a main loop in a Gnome Extension?

Time:07-21

I want to display the content of a file in the Gnome top bar and update the display when the content of the file changes.

For now I have just a skeleton extension that writes Hello world in the top bar.

I have tried to make a loop that should update the text:


File: extension.js

const {St, Clutter} = imports.gi;
const Main = imports.ui.main;

let panelButton;

function init () {
    // Create a Button with "Hello World" text
    panelButton = new St.Bin({
        style_class : "panel-button",
    });
    let panelButtonText = new St.Label({
        text : "Hello World",
        y_align: Clutter.ActorAlign.CENTER,
    });
    panelButton.set_child(panelButtonText);

    let i = "x"
    const Mainloop = imports.mainloop;
    let timeout = Mainloop.timeout_add_seconds(2.5, () => {
        i = i   "x"
        panelButtonText.set_text(i)
    });
}

function enable () {
    // Add the button to the panel
    Main.panel._rightBox.insert_child_at_index(panelButton, 0);
}

function disable () {
    // Remove the added button from panel
    Main.panel._rightBox.remove_child(panelButton);
}

I expect the Hello world text to change multiple times but it stops at xx:

enter image description here


I have tried to do the same with date and time but it does not work either:

const GLib = imports.gi.GLib;
let now = GLib.DateTime.new_now_local();
let nowString = now.format("%Y-%m-%d %H:%M:%S");
panelButtonText.set_text(nowString)

Date and time does not update!

CodePudding user response:

You'll need to return GLib.SOURCE_CONTINUE (true) for the event to keep looping, or GLib.SOURCE_REMOVE (false) for it to exit. Because you are not returning a value from your callback, it is being coerced from undefined to false and only run once.

More notes:

  • you will want to use GLib's functions now, not the MainLoop import, which is deprecated
  • you will want to store the returned GLib.Source ID (i.e. timeout), probably in the same scope as panelButton, so that you can remove it in disable().

There is a guide for using the mainloop on gjs.guide at https://gjs.guide/guides/gjs/asynchronous-programming.html#the-main-loop

  • Related