GnomeShellGenericMonitor/extension.js

436 lines
14 KiB
JavaScript

/* extension.js
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
/* Based on https://stackoverflow.com/questions/33001192/how-to-send-a-string-to-a-gnome-shell-extension */
const St = imports.gi.St;
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const GLib = imports.gi.GLib
const Main = imports.ui.main;
const Mainloop = imports.mainloop;
const clutter = imports.gi.Clutter;
class MonitorWidget {
constructor(name, group, text, style, icon, iconStyle, onClick, box, lastWidget) {
this.name = name;
this.group = group;
this._createIcon(icon, iconStyle);
this._createText(text, style);
this.onClick = onClick;
switch(box) {
case 'left':
this.box = Main.panel._leftBox;
break;
case 'right':
this.box = Main.panel._rigthBox;
break;
default:
case 'center':
this.box = Main.panel._centerBox;
break;
}
// Don't know why, _rightBox seems undefined on shell 3.36 !!
if (this.box === undefined) {
log(`${box} box is undefined, falling back to center one`);
this.box = Main.panel._centerBox;
}
this._addToBox(lastWidget);
}
_createText(text, style) {
this.style = style;
if (text === '') {
this.widget = null;
} else {
this.widget = new St.Button({ label: text });
this.widget.set_style(this.style);
}
}
_createIcon(icon, style) {
this.iconStyle = style;
if (icon === '') {
this.icon = null;
} else {
let gicon = Gio.icon_new_for_string(icon);
this.icon = new St.Icon({ gicon });
this.icon.set_style(this.iconStyle);
}
}
_addToBox(lastWidget) {
// lastWidget => NULL, insert at the end
if (this.box !== Main.panel._rigthBox || lastWidget) {
if (this.icon) {
this.box.insert_child_above(this.icon, lastWidget);
lastWidget = this.icon;
}
if (this.widget)
this.box.insert_child_above(this.widget, lastWidget);
} else {
if (this.icon) {
this.box.insert_child_at_index(this.icon, 0);
lastWidget = this.icon;
}
if (this.widget) {
if (lastWidget)
this.box.insert_child_above(this.widget, lastWidget);
else
this.box.insert_child_at_index(this.icon, 0);
}
}
}
removeFromBox() {
if (this.widget)
this.box.remove_child(this.widget);
if (this.icon)
this.box.remove_child(this.icon);
}
update(text, style, icon, iconStyle) {
let prevWidget = this.widget;
let prevIcon = this.icon;
if (text !== '') {
if (!this.widget) {
this._createText(text, style);
this.box.insert_child_above(this.widget, this.icon);
} else {
this.widget.label = text;
}
}
if (style !== '' && this.widget) {
this.style = style;
this.widget.set_style(this.style);
}
if (icon !== '') {
this._createIcon(icon, iconStyle);
if (prevIcon)
this.box.insert_child_above(this.icon, prevIcon);
else
this.box.insert_child_before(this.icon, prevWidget);
}
if (iconStyle !== '' && this.icon) {
this.iconStyle = style;
this.icon.set_style(this.iconStyle);
}
if (prevIcon && icon !== '')
this.box.remove_child(prevIcon);
}
}
// From https://github.com/ubuntu/gnome-shell-extension-appindicator/blob/master/interfaces.js
// loads a xml file into an in-memory string
function loadInterfaceXml(filename) {
let extension = imports.misc.extensionUtils.getCurrentExtension();
let interfacesDir = extension.dir.get_child('.');
let file = interfacesDir.get_child(filename);
let [result, contents] = imports.gi.GLib.file_get_contents(file.get_path());
if (result) {
// HACK: The "" + trick is important as hell because file_get_contents returns
// an object (WTF?) but Gio.makeProxyWrapper requires `typeof() == "string"`
// Otherwise, it will try to check `instanceof XML` and fail miserably because there
// is no `XML` on very recent SpiderMonkey releases (or, if SpiderMonkey is old enough,
// will spit out a TypeError soon).
if (contents instanceof Uint8Array)
contents = imports.byteArray.toString(contents);
let res = `<node>${contents}</node>`;
return res;
} else {
throw new Error(`Generic monitor: Could not load file: ${filename}`);
}
}
class GenericMonitorDBUS {
constructor() {
this.monitor_groups = {};
this.actor_clicked = {};
this.clutterSettings = clutter.Settings.get_default();
this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(loadInterfaceXml('dbus.xml'), this);
this._dbusImpl.export(Gio.DBus.session, '/com/soutade/GenericMonitor');
this._dbusImpl.emit_signal('onActivate', null);
}
_checkParmeters(parameters) {
if (!parameters.hasOwnProperty('group'))
throw new Error('No group defined');
if (!parameters.hasOwnProperty('items'))
throw new Error('No items defined');
for (let itemIndex in parameters['items']) {
let item = parameters['items'][itemIndex];
if (!item.hasOwnProperty('name'))
throw new Error('No name defined for item');
if (!item.hasOwnProperty('text') && !item.hasOwnProperty('icon'))
throw new Error('No text not icon defined for item');
if (item.hasOwnProperty('on-click')) {
if (item['on-click'] !== 'signal' && item['on-click'] !== 'delete')
throw new Error('Invalid on-click value');
}
if (item.hasOwnProperty('box')) {
if (item['box'] !== 'left' && item['box'] !== 'center' && item['box'] !== 'right')
throw new Error('Invalid box value');
}
}
}
_getItemFromGroup(group, name) {
for (let groupItemIndex in group) {
let groupItem = group[groupItemIndex];
if (groupItem.name === name)
return groupItem;
}
return null;
}
_doClickCallback() {
for(let itemIndex in this.actor_clicked) {
let item = this.actor_clicked[itemIndex];
let right = '';
let nbClicks = '';
if (item['button'] == 3)
right = 'Right';
if (item['nbClicks'] > 1)
nbClicks = 'Dbl';
let signalName = 'on' + right + nbClicks + 'Click';
this._dbusImpl.emit_signal(signalName, GLib.Variant.new('(s)',[item['name']]));
}
this.actor_clicked = {}
}
_actorToMonitorWidget(actor) {
for (let groupName in this.monitor_groups) {
let group = this.monitor_groups[groupName];
for (let itemIndex in group) {
let item = group[itemIndex];
if (item.widget === actor ||
item.icon === actor)
return [groupName, item];
}
}
return null;
}
_removeFromArray(array, value) {
for(let i=0; i<array.length; i++) {
if (array[i] === value) {
array.splice(i, 1);
if (array === null)
array = [];
break;
}
}
return array;
}
// https://stackoverflow.com/questions/50100546/how-do-i-detect-clicks-on-the-gnome-appmenu
_clicked(actor, event) {
let result = this._actorToMonitorWidget(actor);
if (result === null)
return;
let groupName = result[0];
let monitorWidget = result[1];
if (monitorWidget.onClick == 'signal') {
let actorName = monitorWidget.name + '@' + groupName;
if (!this.actor_clicked.hasOwnProperty(actorName)) {
let clickItem = {};
clickItem['name'] = actorName;
clickItem['nbClicks'] = 1;
clickItem['button'] = event.get_button();
this.actor_clicked[actorName] = clickItem;
Mainloop.timeout_add(this.clutterSettings['double-click-time'],
Lang.bind(this, this._doClickCallback));
} else {
this.actor_clicked[actorName]['nbClicks'] = 2;
}
} else if (monitorWidget.onClick == 'delete') {
this.deleteItem(monitorWidget, groupName);
}
}
notify(str) {
let parameters = JSON.parse(str);
this._checkParmeters(parameters);
let groupName = parameters['group'];
let group;
if (!this.monitor_groups.hasOwnProperty(groupName)) {
group = [];
this.monitor_groups[groupName] = group;
} else {
group = this.monitor_groups[groupName];
}
for (let itemIndex in parameters['items']) {
let item = parameters['items'][itemIndex];
let style = '';
if (item.hasOwnProperty('style'))
style = item['style'];
let text = '';
if (item.hasOwnProperty('text'))
text = item['text'];
let icon = '';
if (item.hasOwnProperty('icon'))
icon = item['icon'];
let iconStyle = '';
if (item.hasOwnProperty('icon-style'))
iconStyle = item['icon-style'];
let onClick = '';
if (item.hasOwnProperty('on-click'))
onClick = item['on-click'];
let box = 'center';
if (item.hasOwnProperty('box'))
box = item['box'];
let monitorWidget = this._getItemFromGroup(group, item['name']);
let lastWidget = null;
// New widget
if (monitorWidget === null) {
if (group.length)
lastWidget = group[group.length - 1].widget;
monitorWidget = new MonitorWidget(item['name'], groupName, text, style, icon, iconStyle, onClick, box, lastWidget);
group.push(monitorWidget);
// Connect signals
if (onClick !== '') {
if (monitorWidget.widget)
monitorWidget.widget.set_reactive(true);
monitorWidget.widget.connect(
'button-release-event', Lang.bind(this, this._clicked)
);
if (monitorWidget.icon) {
monitorWidget.icon.set_reactive(true);
monitorWidget.icon.connect(
'button-release-event', Lang.bind(this, this._clicked)
);
}
}
} else {
monitorWidget.update(text, style, icon, iconStyle);
}
}
}
deleteItem(item, groupName) {
let group = this.monitor_groups[groupName];
item.removeFromBox();
group = this._removeFromArray(group, item);
if (group.length === 0)
delete this.monitor_groups[groupName];
else
this.monitor_groups = group;
}
deleteItems(str) {
let parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('items'))
throw new Error('No items defined');
for (let itemIndex in parameters['items']) {
let itemName = parameters['items'][itemIndex];
let fullName = itemName.split('@');
if (fullName.length !== 2)
throw new Error(`Invalid name ${itemName}`);
itemName = fullName[0];
let groupName = fullName[1];
if (!this.monitor_groups.hasOwnProperty(groupName))
continue;
let group = this.monitor_groups[groupName];
let item = this._getItemFromGroup(group, itemName);
if (item !== null) {
this.deleteItem(item, groupName);
}
}
}
deleteGroups(str) {
let parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('groups'))
throw new Error('No groups defined');
let groupsToDelete = [];
for (let groupIndex in parameters['groups']) {
let groupName = parameters['groups'][groupIndex];
if (!this.monitor_groups.hasOwnProperty(groupName))
continue;
let group = this.monitor_groups[groupName];
for (let itemIndex in group)
group[itemIndex].removeFromBox();
groupsToDelete.push(groupName);
}
for (let groupDeleteIndex in groupsToDelete) {
let groupName = groupsToDelete[groupDeleteIndex];
delete this.monitor_groups[groupName];
}
}
destructor() {
this._dbusImpl.emit_signal('onDeactivate', null);
for (let groupIndex in this.monitor_groups) {
let group = this.monitor_groups[groupIndex];
for (let itemIndex in group)
group[itemIndex].removeFromBox();
}
this.monitor_groups = {};
this._dbusImpl.unexport();
}
}
class Extension {
enable() {
this.textDBusService = new GenericMonitorDBUS();
}
disable() {
this.textDBusService.destructor();
delete this.textDBusService;
}
}
let extension = new Extension();
function init() {
}
function enable() {
extension.enable();
}
function disable() {
extension.disable();
}