GnomeShellGenericMonitor/extension.js

589 lines
18 KiB
JavaScript
Raw Normal View History

2020-03-30 10:45:26 +02:00
/* 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 */
2020-11-02 17:03:34 +01:00
// https://github.com/bananenfisch/RecentItems/blob/master/extension.js
// https://github.com/julio641742/gnome-shell-extension-reference/blob/master/tutorials/POPUPMENU-EXTENSION.md
// https://gjs-docs.gnome.org/st10~1.0_api/st.widget
// https://gitlab.gnome.org/GNOME/gnome-shell/-/blob/master/js/ui/panelMenu.js
// https://gitlab.gnome.org/GNOME/gnome-shell/-/blob/master/js/ui/popupMenu.js
2020-03-30 10:45:26 +02:00
const St = imports.gi.St;
const Gio = imports.gi.Gio;
2020-05-04 10:08:39 +02:00
const Lang = imports.lang;
const GLib = imports.gi.GLib
2020-03-30 10:45:26 +02:00
const Main = imports.ui.main;
2020-05-04 10:08:39 +02:00
const Mainloop = imports.mainloop;
const Clutter = imports.gi.Clutter;
2020-11-02 17:03:34 +01:00
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const GObject = imports.gi.GObject;
const Pixbuf = imports.gi.GdkPixbuf;
const Cogl = imports.gi.Cogl;
function hash_get(hash, key, default_value)
{
if (hash.hasOwnProperty(key))
return hash[key];
return default_value;
}
2020-11-02 17:03:34 +01:00
var MyPopupMenuItem = GObject.registerClass({
GTypeName: "MyPopupMenuItem"
},
class MyPopupMenuItem extends PopupMenu.PopupBaseMenuItem {
_init(widgets, params) {
super._init(params);
2020-11-02 17:03:34 +01:00
this.box = new St.BoxLayout({ style_class: 'popup-combobox-item' });
this.box.set_vertical(true);
2020-11-02 17:03:34 +01:00
for (let widgetIndex in widgets)
this.box.add(widgets[widgetIndex]);
this.add_child(this.box);
}
2020-11-02 17:03:34 +01:00
});
2020-11-02 17:03:34 +01:00
var MonitorWidget = GObject.registerClass({
GTypeName: "MonitorWidget"
},
class MonitorWidget extends PanelMenu.Button {
_init(item, group, lastWidget) {
super._init(0.0);
this.name = item['name'];
2020-04-01 09:36:51 +02:00
this.group = group;
2020-11-02 17:03:34 +01:00
if (item.hasOwnProperty('icon'))
{
if (typeof(item['icon']) === "string")
this.icon = this._createIconOld(item);
else
this.icon = this._createIcon(item['icon']);
2020-11-02 17:03:34 +01:00
this.add_child(this.icon);
}
else
this.icon = null;
if (item.hasOwnProperty('text'))
{
if (typeof(item['text']) === "string")
this.widget = this._createTextOld(item);
else
this.widget = this._createText(item['text']);
2020-11-02 17:03:34 +01:00
this.add_child(this.widget);
}
else
this.widget = null;
if (item.hasOwnProperty('popup'))
this._createPopup(item['popup']);
this.onClick = hash_get(item, 'on-click', '');
this.onEnter = hash_get(item, 'on-enter', '');
this.onLeave = hash_get(item, 'on-leave', '');
let box = hash_get(item, 'box', 'center');
2020-11-02 17:03:34 +01:00
this.connect('enter-event', this._onEnter.bind(this));
this.connect('leave-event', this._onLeave.bind(this));
Main.panel.addToStatusArea(group, this, (lastWidget>0)?lastWidget:-1, box);
}
2020-11-02 17:03:34 +01:00
_onEnter() {
this.menu.open(true);
}
_onLeave() {
this.menu.close();
2020-03-30 10:45:26 +02:00
}
_createPopup(item) {
if (!item.hasOwnProperty('items')) {
return null;
}
let widgets = [];
let widget;
for (let itemIndex in item['items']) {
switch(itemIndex)
{
case 'text':
widget = this._createText(item['items'][itemIndex]);
break;
case 'picture':
widget = this._createPicture(item['items'][itemIndex]);
break
}
if (widget !== null)
widgets.push(widget);
}
if (widgets.length > 0) {
this.menuItem = new MyPopupMenuItem(widgets, {});
this.menu.addMenuItem(this.menuItem);
return this.menuItem;
}
return null;
}
_createTextOld(item) {
var item_values = {};
item_values = {'text':item['text']};
if (item.hasOwnProperty('style'))
item_values['style'] = item['style'];
return this._createText(item_values);
}
_createText(item) {
if (!item.hasOwnProperty('text'))
throw new Error("Text must have a \'text\' value");
let style = hash_get(item, 'style', '');
this.textProperties = item;
if (item['text'] === '') {
2020-11-02 17:03:34 +01:00
return null;
2020-04-01 09:36:51 +02:00
} else {
let widget = new St.Button({ label: item['text'] });
widget.set_style(style);
2020-11-02 17:03:34 +01:00
return widget;
}
2020-03-30 10:45:26 +02:00
}
2020-04-01 09:36:51 +02:00
_createIconOld(item) {
var item_values = {};
item_values = {'path':item['icon']};
if (item.hasOwnProperty('iconStyle'))
item_values['style'] = item['iconStyle'];
return this._createIcon(item_values);
}
_createIcon(item) {
if (!item.hasOwnProperty('path'))
throw new Error("Icon must have a \'path\' value");
let style = hash_get(item, 'style', '');
this.iconProperties = item;
if (item['path'] === '') {
2020-11-02 17:03:34 +01:00
return null;
2020-04-01 09:36:51 +02:00
} else {
let gicon = Gio.icon_new_for_string(item['path']);
2020-11-02 17:03:34 +01:00
gicon = new St.Icon({ gicon });
gicon.set_style(style);
2020-11-02 17:03:34 +01:00
return gicon;
}
}
_createPicture(item) {
if (!item.hasOwnProperty('path'))
throw new Error("picture must have a \'path\' value");
let width = hash_get(item, 'width', -1);
let height = hash_get(item, 'height', -1);
if (typeof(width) === "string")
width = parseInt(width, 10);
if (typeof(heigth) === "string")
heigth = parseInt(heigth, 10);
let img = new Clutter.Image();
let initial_pixbuf = Pixbuf.Pixbuf.new_from_file(item['path']);
img.set_data(initial_pixbuf.get_pixels(),
initial_pixbuf.get_has_alpha() ? Cogl.PixelFormat.RGBA_8888
: Cogl.PixelFormat.RGB_888,
initial_pixbuf.get_width(),
initial_pixbuf.get_height(),
initial_pixbuf.get_rowstride());
let picture = new Clutter.Actor();
picture.set_content(img);
picture.set_size((width != -1)?width:initial_pixbuf.get_width(),
(height != -1)?height:initial_pixbuf.get_height());
return picture;
}
removeFromBox() {
if (this.widget)
this.box.remove_child(this.widget);
if (this.icon)
this.box.remove_child(this.icon);
}
update(item) {
let prevWidget = this.widget;
let prevIcon = this.icon;
if (item.hasOwnProperty('text'))
{
let text = '';
let style = '';
if (typeof(item['text']) === "string") {
text = hash_get(item, 'text', '');
style = hash_get(item, 'style', '');
} else {
let textValues = item['text'];
text = hash_get(textValues, 'text', '');
style = hash_get(textValues, 'style', '');
}
if (text !== '') {
if (!this.widget) {
if (typeof(item['text']) === "string")
this.widget = this._createTextOld(item);
else
this.widget = this._createText(item['text']);
this.insert_child_above(this.widget, this.icon);
} else {
this.widget.label = text;
}
}
if (style !== '' && this.widget) {
this.widget.set_style(style);
}
}
if (item.hasOwnProperty('icon'))
{
let icon = '';
let style = '';
if (typeof(item['icon']) === "string") {
icon = hash_get(item, 'icon', '');
style = hash_get(item, 'iconStyle', '');
} else {
let iconValues = item['icon'];
icon = hash_get(iconValues, 'path', '');
style = hash_get(textValues, 'style', '');
}
if (icon !== '') {
if (typeof(item['icon']) === "string")
this.icon = this._createIconOld(item);
else
this.icon = this._createIcon(item['icon']);
}
if (prevIcon) {
this.insert_child_above(this.icon, prevIcon);
this.remove_child(prevIcon);
//delete prevIcon;
} else
this.insert_child_before(this.icon, prevWidget);
if (style !== '' && this.icon) {
this.icon.set_style(style);
}
2020-04-01 09:36:51 +02:00
}
if (item.hasOwnProperty('popup'))
{
if (this.menuItem) {
this.menu.removeAll();
//delete this.menuItem;
}
2020-04-01 09:36:51 +02:00
this._createPopup(item['popup']);
}
this.onClick = hash_get(item, 'on-click', this.onClick);
this.onEnter = hash_get(item, 'on-enter', this.onEnter);
this.onLeave = hash_get(item, 'on-leave', this.onLeave);
2020-03-30 10:45:26 +02:00
}
2020-11-02 17:03:34 +01:00
});
2020-03-30 10:45:26 +02:00
// 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();
2020-04-01 09:36:51 +02:00
let interfacesDir = extension.dir.get_child('.');
2020-03-30 10:45:26 +02:00
2020-04-01 09:36:51 +02:00
let file = interfacesDir.get_child(filename);
2020-03-30 10:45:26 +02:00
2020-04-01 09:36:51 +02:00
let [result, contents] = imports.gi.GLib.file_get_contents(file.get_path());
2020-03-30 10:45:26 +02:00
if (result) {
2020-04-01 09:36:51 +02:00
// HACK: The "" + trick is important as hell because file_get_contents returns
2020-03-30 10:45:26 +02:00
// 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)
2020-04-01 09:36:51 +02:00
contents = imports.byteArray.toString(contents);
let res = `<node>${contents}</node>`;
return res;
2020-03-30 10:45:26 +02:00
} else {
2020-04-01 09:36:51 +02:00
throw new Error(`Generic monitor: Could not load file: ${filename}`);
2020-03-30 10:45:26 +02:00
}
}
2020-04-01 09:36:51 +02:00
class GenericMonitorDBUS {
constructor() {
this.monitor_groups = {};
2020-05-04 10:08:39 +02:00
this.actor_clicked = {};
this.ClutterSettings = Clutter.Settings.get_default();
2020-03-30 10:45:26 +02:00
this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(loadInterfaceXml('dbus.xml'), this);
this._dbusImpl.export(Gio.DBus.session, '/com/soutade/GenericMonitor');
this._dbusImpl.emit_signal('onActivate', null);
2020-04-01 09:36:51 +02:00
}
2020-03-30 10:45:26 +02:00
2020-04-01 09:36:51 +02:00
_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');
2020-11-02 17:03:34 +01:00
// 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');
// }
2020-04-01 09:36:51 +02:00
}
}
_getItemFromGroup(group, name) {
for (let groupItemIndex in group) {
let groupItem = group[groupItemIndex];
if (groupItem.name === name)
return groupItem;
}
return null;
2020-03-30 10:45:26 +02:00
}
2020-05-04 10:08:39 +02:00
_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'],
2020-05-04 10:08:39 +02:00
Lang.bind(this, this._doClickCallback));
} else {
this.actor_clicked[actorName]['nbClicks'] = 2;
}
} else if (monitorWidget.onClick == 'delete') {
this.deleteItem(monitorWidget, groupName);
}
}
2020-04-01 09:36:51 +02:00
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 monitorWidget = this._getItemFromGroup(group, item['name']);
// New widget
if (monitorWidget === null) {
let lastWidget = group.length - 1;
2020-11-02 17:03:34 +01:00
monitorWidget = new MonitorWidget(item, groupName, lastWidget);
2020-04-01 09:36:51 +02:00
group.push(monitorWidget);
2020-05-04 10:08:39 +02:00
// 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)
// );
// }
// }
2020-04-01 09:36:51 +02:00
} else {
monitorWidget.update(item);
2020-04-01 09:36:51 +02:00
}
}
}
2020-05-04 10:08:39 +02:00
deleteItem(item, groupName) {
let group = this.monitor_groups[groupName];
item.removeFromBox();
2020-05-04 10:08:39 +02:00
group = this._removeFromArray(group, item);
if (group.length === 0)
delete this.monitor_groups[groupName];
else
this.monitor_groups = group;
}
2020-04-01 09:36:51 +02:00
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) {
2020-05-04 10:08:39 +02:00
this.deleteItem(item, groupName);
2020-04-01 09:36:51 +02:00
}
}
}
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();
2020-04-01 09:36:51 +02:00
groupsToDelete.push(groupName);
}
for (let groupDeleteIndex in groupsToDelete) {
let groupName = groupsToDelete[groupDeleteIndex];
delete this.monitor_groups[groupName];
}
}
destructor() {
this._dbusImpl.emit_signal('onDeactivate', null);
2020-04-01 09:36:51 +02:00
for (let groupIndex in this.monitor_groups) {
let group = this.monitor_groups[groupIndex];
for (let itemIndex in group)
group[itemIndex].removeFromBox();
2020-04-01 09:36:51 +02:00
}
this.monitor_groups = {};
this._dbusImpl.unexport();
}
}
class Extension {
2020-03-30 10:45:26 +02:00
enable() {
2020-04-01 09:36:51 +02:00
this.textDBusService = new GenericMonitorDBUS();
2020-03-30 10:45:26 +02:00
}
disable() {
2020-04-01 09:36:51 +02:00
this.textDBusService.destructor();
delete this.textDBusService;
2020-03-30 10:45:26 +02:00
}
}
2020-04-01 09:36:51 +02:00
let extension = new Extension();
2020-03-30 10:45:26 +02:00
function init() {
}
function enable() {
extension.enable();
}
function disable() {
extension.disable();
}