GnomeShellGenericMonitor/extension.js

388 lines
13 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) {
this.name = name;
this.group = group;
this._createIcon(icon, iconStyle);
this._createText(text, style);
this.onClick = onClick;
}
_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);
}
}
update(text, style, icon, iconStyle) {
if (!this.widget) {
this._createText(text, style);
} else {
if (text !== '')
this.widget.label = text;
this.style = style;
this.widget.set_style(this.style);
}
if (icon !== '')
this._createIcon(icon, iconStyle);
if (icon === '' && iconStyle !== '' && this.icon) {
this.iconStyle = style;
this.icon.set_style(this.iconStyle);
}
}
}
// 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.box = Main.panel._centerBox;
this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(loadInterfaceXml('dbus.xml'), this);
this._dbusImpl.export(Gio.DBus.session, '/com/soutade/GenericMonitor');
}
_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');
}
}
}
_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 monitorWidget = this._getItemFromGroup(group, item['name']);
let lastWidget = null;
// New widget
if (monitorWidget === null) {
monitorWidget = new MonitorWidget(item['name'], groupName, text, style, icon, iconStyle, onClick);
if (group.length)
lastWidget = group[group.length - 1].widget;
group.push(monitorWidget);
// lastWidget => NULL, insert at the end
if (monitorWidget.icon) {
this.box.insert_child_above(monitorWidget.icon, lastWidget);
lastWidget = monitorWidget.icon;
}
if (monitorWidget.widget)
this.box.insert_child_above(monitorWidget.widget, lastWidget);
// 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 {
let prevWidget = monitorWidget.widget;
let prevIcon = monitorWidget.icon;
monitorWidget.update(text, style, icon, iconStyle);
if (monitorWidget.icon) {
if (prevIcon)
this.box.remove_child(prevIcon);
this.box.insert_child_above(monitorWidget.icon, lastWidget);
lastWidget = monitorWidget.icon;
}
if (!prevWidget && monitorWidget.widget)
this.box.insert_child_above(monitorWidget.widget, lastWidget);
}
}
}
_removeItemFromBox(item) {
if (item.widget)
this.box.remove_child(item.widget);
if (item.icon)
this.box.remove_child(item.icon);
}
deleteItem(item, groupName) {
let group = this.monitor_groups[groupName];
this._removeItemFromBox(item);
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)
this._removeItemFromBox(group[itemIndex]);
groupsToDelete.push(groupName);
}
for (let groupDeleteIndex in groupsToDelete) {
let groupName = groupsToDelete[groupDeleteIndex];
delete this.monitor_groups[groupName];
}
}
destructor() {
for (let groupIndex in this.monitor_groups) {
let group = this.monitor_groups[groupIndex];
for (let itemIndex in group)
this._removeItemFromBox(group[itemIndex]);
}
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();
}