Compare commits

..

5 Commits
v3 .. v4

Author SHA1 Message Date
soutade 83609b58ab After linter pass 2021-01-29 09:15:40 +01:00
soutade b85ff4a782 Update examples 2021-01-28 10:34:18 +01:00
soutade 30bfc796b9 Update README 2021-01-28 10:34:18 +01:00
soutade 35e34b52f2 Move signal management into external class. It allows to handle signals for popup nested elements. 2021-01-28 10:34:17 +01:00
soutade 1b4430c3ac Update README 2020-11-28 12:14:48 +01:00
6 changed files with 336 additions and 269 deletions
+7 -1
View File
@@ -67,6 +67,8 @@ DBUS object
<text_object> is defined as : <text_object> is defined as :
"text" : { "text" : {
"name" : "" // Optional, used with popup nested element
<signals_description>, // Optional, used with popup nested element
"text" : "Text to be displayed", "text" : "Text to be displayed",
"style" : "CSS style to be applied", // Optional "style" : "CSS style to be applied", // Optional
} }
@@ -79,6 +81,8 @@ DBUS object
<picture_object> is defined as : <picture_object> is defined as :
"picture" : { "picture" : {
"name" : "" // Optional, used with popup nested element
<signals_description>, // Optional, used with popup nested element
"path" : "Icon path", "path" : "Icon path",
"width" : XXX, // Optional : Force width in pixels, can be -1 for defaut value "width" : XXX, // Optional : Force width in pixels, can be -1 for defaut value
"height" : XXX, // Optional : Force height in pixels, can be -1 for defaut value "height" : XXX, // Optional : Force height in pixels, can be -1 for defaut value
@@ -124,6 +128,8 @@ Signal names emit when action "signal" is specified :
* onScrollDown * onScrollDown
Each signal is sent with one parameter : "<itemName>@<groupName>" Each signal is sent with one parameter : "<itemName>@<groupName>"
For popup nested elements, parameter is "<nestedName>@<itemName>@<groupName>"
where nestedName can be empty if not defined by user
Other signals are available when extension is activated/deactivated : Other signals are available when extension is activated/deactivated :
@@ -136,7 +142,7 @@ Example
You can test it with command line : You can test it with command line :
gdbus call --session --dest org.gnome.Shell --object-path /com/soutade/GenericMonitor --method com.soutade.GenericMonitor.notify '{"group":"new","items":[{"name":"first","on-click":"toggle-popup","text":"Hello","style":"color:green","popup":{"items":[{"picture":{"path":"/tmp/cat2.jpg"}}]}}]}' gdbus call --session --dest org.gnome.Shell --object-path /com/soutade/GenericMonitor --method com.soutade.GenericMonitor.notify '{"group":"new","items":[{"name":"first","on-click":"toggle-popup","text":{"text":"Hello","style":"color:green"},"popup":{"items":[{"picture":{"path":"/tmp/cat2.jpg"}}]}}]}'
gdbus call --session --dest org.gnome.Shell --object-path /com/soutade/GenericMonitor --method com.soutade.GenericMonitor.deleteGroups '{"groups":["new"]}' gdbus call --session --dest org.gnome.Shell --object-path /com/soutade/GenericMonitor --method com.soutade.GenericMonitor.deleteGroups '{"groups":["new"]}'
+39 -16
View File
@@ -235,11 +235,25 @@ class GenericMonitor:
class GenericMonitorGenericWidget: class GenericMonitorGenericWidget:
""" Generic widget class, parent of all widgets """ Generic widget class, parent of all widgets
""" """
def __init__(self): def __init__(self, style='', name='', signals={}):
self.valuesToMap = [] """
Parameters
----------
name : str, optional
Widget name
signals : dictionary, optional
Dictionary of signals and their action
"""
self.valuesToMap = ['name', 'style']
self.mapValues = {} self.mapValues = {}
self.mapName = '' self.mapName = ''
self.style = style
self.name = name
self.signals = signals
def setStyle(self, style):
self.style = style
def _toMap(self): def _toMap(self):
""" Return dictionary of class elements to send to addon """ Return dictionary of class elements to send to addon
""" """
@@ -247,12 +261,14 @@ class GenericMonitorGenericWidget:
for p in self.valuesToMap: for p in self.valuesToMap:
if self.__dict__[p]: if self.__dict__[p]:
self.mapValues[p] = self.__dict__[p] self.mapValues[p] = self.__dict__[p]
for (name, value) in self.signals.items():
self.mapValues[name] = value
return {self.mapName:self.mapValues} return {self.mapName:self.mapValues}
class GenericMonitorTextWidget(GenericMonitorGenericWidget): class GenericMonitorTextWidget(GenericMonitorGenericWidget):
""" Text widget """ Text widget
""" """
def __init__(self, text, style=''): def __init__(self, text, style='', name='', signals={}):
""" """
Parameters Parameters
---------- ----------
@@ -260,19 +276,20 @@ class GenericMonitorTextWidget(GenericMonitorGenericWidget):
Text to display Text to display
style : str, optional style : str, optional
CSS style CSS style
name : str, optional
Widget name
signals : dictionary, optional
Dictionary of signals and their action
""" """
self.valuesToMap = ('text', 'style') super().__init__(style, name, signals)
self.valuesToMap += ['text']
self.mapName = 'text' self.mapName = 'text'
self.text = text self.text = text
self.style = style
def setText(self, text): def setText(self, text):
self.text = text self.text = text
def setStyle(self, style):
self.style = style
class GenericMonitorIconWidget(GenericMonitorGenericWidget): class GenericMonitorIconWidget(GenericMonitorGenericWidget):
""" Icon widget """ Icon widget
""" """
@@ -285,7 +302,8 @@ class GenericMonitorIconWidget(GenericMonitorGenericWidget):
style : str, optional style : str, optional
CSS style CSS style
""" """
self.valuesToMap = ('path', 'style') super().__init__(style=style)
self.valuesToMap += ['path']
self.mapName = 'icon' self.mapName = 'icon'
self.path = path self.path = path
@@ -293,15 +311,12 @@ class GenericMonitorIconWidget(GenericMonitorGenericWidget):
def setPath(self, path): def setPath(self, path):
self.path = path self.path = path
def setStyle(self, style):
self.style = style
class GenericMonitorPictureWidget(GenericMonitorIconWidget): class GenericMonitorPictureWidget(GenericMonitorGenericWidget):
""" Picture widget """ Picture widget
""" """
def __init__(self, path, style='', width=-1, height=-1): def __init__(self, path, style='', width=-1, height=-1, name='', signals={}):
""" """
Parameters Parameters
---------- ----------
@@ -313,15 +328,23 @@ class GenericMonitorPictureWidget(GenericMonitorIconWidget):
Width of displayed picture (-1 for default width) Width of displayed picture (-1 for default width)
height : int, optional height : int, optional
Width of displayed picture (-1 for default width) Width of displayed picture (-1 for default width)
name : str, optional
Widget name
signals : dictionary, optional
Dictionary of signals and their action
""" """
super().__init__(path, style) super().__init__(style, name, signals)
self.valuesToMap = ('path', 'style', 'width', 'height') self.valuesToMap += ['path', 'width', 'height']
self.mapName = 'picture' self.mapName = 'picture'
self.path = path
self.width = width self.width = width
self.height = height self.height = height
def setPath(self, path):
self.path = path
def setWidth(self, width): def setWidth(self, width):
self.width = width self.width = width
+8 -3
View File
@@ -19,6 +19,7 @@
Display random picture from unsplash.com in a popup Display random picture from unsplash.com in a popup
* Click : open/close popup * Click : open/close popup
* Popup item click : display who clicked
* ScrollUp/ScrollDown/Double click : display next picture * ScrollUp/ScrollDown/Double click : display next picture
* Right click : exit * Right click : exit
''' '''
@@ -50,8 +51,8 @@ class PicturePopup(GenericMonitor):
with open('/tmp/cat2.jpg', 'wb') as f: with open('/tmp/cat2.jpg', 'wb') as f:
f.write(datatowrite) f.write(datatowrite)
widget = GenericMonitorTextWidget('#%d' % self.imgs_idx, 'color:purple') widget = GenericMonitorTextWidget('#%d' % self.imgs_idx, 'color:purple')
url_widget = GenericMonitorTextWidget(url, 'color:white;font-weight:bold') url_widget = GenericMonitorTextWidget(url, 'color:white;font-weight:bold', signals={'on-click':'signal'}) # No name here
picture_widget = GenericMonitorPictureWidget('/tmp/cat2.jpg') picture_widget = GenericMonitorPictureWidget('/tmp/cat2.jpg', name='NestedWidget', signals={'on-click':'signal'})
popup = GenericMonitorPopup([url_widget, picture_widget]) popup = GenericMonitorPopup([url_widget, picture_widget])
signals = { signals = {
'on-click':'toggle-popup', 'on-click':'toggle-popup',
@@ -68,7 +69,11 @@ class PicturePopup(GenericMonitor):
self.imgs_idx += 1 self.imgs_idx += 1
def _forMe(self, sender): def _forMe(self, sender):
return sender == self.item.getFullName() return str(sender).endswith(self.item.getFullName())
def onClick(self, sender):
if not self._forMe(sender): return
print('Click from {}'.format(sender))
def _onScroll(self, sender): def _onScroll(self, sender):
if not self._forMe(sender): return if not self._forMe(sender): return
+1 -1
View File
@@ -65,7 +65,7 @@ class TimerThread(Thread,GenericMonitor):
self._stopLoop = False self._stopLoop = False
self.textWidget = GenericMonitorTextWidget('') self.textWidget = GenericMonitorTextWidget('')
signals = {'on-click':'signal'} signals = {'on-click':'signal','on-dblclick':'signal','on-rightclick':'signal'}
self.monitorItem = GenericMonitorItem('timer', [self.textWidget], signals, box='right') self.monitorItem = GenericMonitorItem('timer', [self.textWidget], signals, box='right')
self.monitorGroup = GenericMonitorGroup('Timer', self.monitorItem) self.monitorGroup = GenericMonitorGroup('Timer', self.monitorItem)
+280 -247
View File
@@ -55,69 +55,18 @@ function log(message) {
} }
var MyPopupMenuItem = GObject.registerClass({ class SignalMgt {
GTypeName: "MyPopupMenuItem"
},
class MyPopupMenuItem extends PopupMenu.PopupBaseMenuItem {
_init(widgets, params) {
super._init(params);
this.box = new St.BoxLayout({ style_class: 'popup-combobox-item' }); constructor(item, name, group, dbus, menu) {
this.box.set_vertical(true); this.name = name;
for (let widgetIndex in widgets)
this.box.add(widgets[widgetIndex]);
this.add_child(this.box);
}
});
var MonitorWidget = GObject.registerClass({
GTypeName: "MonitorWidget"
},
class MonitorWidget extends PanelMenu.Button {
_init(item, group, dbus, position) {
super._init(0.0);
this.name = item['name'];
this.group = group; this.group = group;
this.fullname = this.name + '@' + this.group; this.fullname = this.name + '@' + this.group;
this.dbus = dbus; this.dbus = dbus;
this.menu = menu;
this.signals = {} this.signals = {}
if (item.hasOwnProperty('icon')) this.nbClicks = 0;
{ this.button = -1;
if (typeof(item['icon']) === "string")
this.icon = this._createIconOld(item);
else
this.icon = this._createIcon(item['icon']);
if (this.icon !== null) {
this._connectWidgetSignals(this.icon);
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']);
if (this.widget !== null) {
this._connectWidgetSignals(this.widget);
this.add_child(this.widget);
}
}
else
this.widget = null;
if (item.hasOwnProperty('popup'))
this._createPopup(item['popup']);
this.onClick = hashGet(item, 'on-click', ''); this.onClick = hashGet(item, 'on-click', '');
this.onDblClick = hashGet(item, 'on-dblclick', ''); this.onDblClick = hashGet(item, 'on-dblclick', '');
@@ -126,30 +75,24 @@ class MonitorWidget extends PanelMenu.Button {
this.onEnter = hashGet(item, 'on-enter', ''); this.onEnter = hashGet(item, 'on-enter', '');
this.onLeave = hashGet(item, 'on-leave', ''); this.onLeave = hashGet(item, 'on-leave', '');
this.onScroll = hashGet(item, 'on-scroll', ''); this.onScroll = hashGet(item, 'on-scroll', '');
let box = hashGet(item, 'box', 'center');
if (box === 'right' && position == -1)
position = 0;
this.connect('style-changed', this._onStyleChanged.bind(this));
// Disable click event at PanelMenu.button level
this.setSensitive(false);
this.nbClicks = 0;
this.button = -1;
Main.panel.addToStatusArea(this.fullname, this, position, box);
} }
_onStyleChanged() { destructor() {
// Force these values to avoid big spaces between each widgets for(let widgetIdx in this.signals)
this._minHPadding = 1; this.disconnectWidgetSignals(this.signals[widgetIdx]);
this._natHPadding = 1; }
updateSignals(item) {
this.onClick = hashGet(item, 'on-click', this.onClick);
this.onDblClick = hashGet(item, 'on-dblclick', this.onDblClick);
this.onRightClick = hashGet(item, 'on-rightclick', this.onRightClick);
this.onRightDblClick = hashGet(item, 'on-rightdblclick', this.onRightDblClick);
this.onEnter = hashGet(item, 'on-enter', this.onEnter);
this.onLeave = hashGet(item, 'on-leave', this.onLeave);
this.onScroll = hashGet(item, 'on-scroll', this.onScroll);
} }
_connectWidgetSignals(widget) { connectWidgetSignals(widget) {
this.signals[widget] = []; this.signals[widget] = [];
let id; let id;
id = widget.connect('enter-event', this._onEnter.bind(this)); id = widget.connect('enter-event', this._onEnter.bind(this));
@@ -163,132 +106,11 @@ class MonitorWidget extends PanelMenu.Button {
this.signals[widget].push(id); this.signals[widget].push(id);
} }
_disconnectWidgetSignals(widget) { disconnectWidgetSignals(widget) {
for(let idx in this.signals[widget]) for(let idx in this.signals[widget])
widget.disconnect(this.signals[widget][idx]); widget.disconnect(this.signals[widget][idx]);
this.signals[widget] = null; this.signals[widget] = null;
} }
_createPopup(item) {
if (!item.hasOwnProperty('items')) {
return null;
}
let widgets = [];
for (let itemIndex in item['items']) {
let widget = null;
let widgetDict = item['items'][itemIndex];
if (widgetDict.hasOwnProperty('text'))
widget = this._createText(widgetDict['text']);
else if (widgetDict.hasOwnProperty('picture'))
widget = this._createPicture(widgetDict['picture']);
if (widget !== null)
widgets.push(widget);
}
if (widgets.length > 0) {
this.menuItem = new MyPopupMenuItem(widgets, {});
this.menu.addMenuItem(this.menuItem);
this.menu.setSensitive(false);
return this.menuItem;
}
return null;
}
_createTextOld(item) {
var itemValues = {};
itemValues = { 'text':item['text'] };
if (item.hasOwnProperty('style'))
itemValues['style'] = item['style'];
return this._createText(itemValues);
}
_createText(item) {
if (!item.hasOwnProperty('text')) {
log("Text must have a 'text' value");
return null;
}
let style = hashGet(item, 'style', '');
this.textProperties = item;
if (item['text'] === '') {
return null;
} else {
let widget = new St.Button({ label: item['text'] });
widget.set_style(style);
return widget;
}
}
_createIconOld(item) {
var itemValues = {};
itemValues = { 'path':item['icon'] };
if (item.hasOwnProperty('iconStyle'))
itemValues['style'] = item['iconStyle'];
return this._createIcon(itemValues);
}
_createIcon(item) {
if (!item.hasOwnProperty('path')) {
log("Icon must have a 'path' value");
return null;
}
let style = hashGet(item, 'style', '');
this.iconProperties = item;
if (item['path'] === '') {
return null;
} else {
let gicon = Gio.icon_new_for_string(item['path']);
gicon = new St.Icon({ gicon });
gicon.set_style(style);
return gicon;
}
}
_createPicture(item) {
if (!item.hasOwnProperty('path')) {
log("Picture must have a 'path' value");
return null;
}
let width = hashGet(item, 'width', -1);
let height = hashGet(item, 'height', -1);
if (typeof(width) === "string")
width = parseInt(width, 10);
if (typeof(height) === "string")
height = parseInt(height, 10);
let img = new Clutter.Image();
let initialPixbuf = Pixbuf.Pixbuf.new_from_file(item['path']);
img.set_data(initialPixbuf.get_pixels(),
initialPixbuf.get_has_alpha() ? Cogl.PixelFormat.RGBA_8888
: Cogl.PixelFormat.RGB_888,
initialPixbuf.get_width(),
initialPixbuf.get_height(),
initialPixbuf.get_rowstride());
let picture = new Clutter.Actor();
picture.set_content(img);
picture.set_size((width != -1)?width:initialPixbuf.get_width(),
(height != -1)?height:initialPixbuf.get_height());
// Pack it in a box to avoid picture resize
let box = new St.BoxLayout({});
box.add_child(picture);
return box;
}
_manageEventAction(action, signalName) { _manageEventAction(action, signalName) {
if (action === 'open-popup') if (action === 'open-popup')
@@ -312,13 +134,13 @@ class MonitorWidget extends PanelMenu.Button {
_doClickCallback() { _doClickCallback() {
let right = ''; let right = '';
let nbClicks = ''; let nbClicks = '';
if (this.button == 3) if (this.button == 3)
right = 'Right'; right = 'Right';
if (this.nbClicks > 1) if (this.nbClicks > 1)
nbClicks = 'Dbl'; nbClicks = 'Dbl';
let signalName = 'on' + right + nbClicks + 'Click'; const signalName = 'on' + right + nbClicks + 'Click';
let action = 'signal'; let action = 'signal';
switch(signalName) { switch(signalName) {
@@ -359,36 +181,110 @@ class MonitorWidget extends PanelMenu.Button {
} }
_onScroll(actor, event) { _onScroll(actor, event) {
let signalName = ''; let signalName = '';
let direction = event.get_scroll_direction (); const direction = event.get_scroll_direction ();
if (direction == Clutter.ScrollDirection.UP) if (direction == Clutter.ScrollDirection.UP)
signalName = 'onScrollUp'; signalName = 'onScrollUp';
else if (direction == Clutter.ScrollDirection.DOWN) else if (direction == Clutter.ScrollDirection.DOWN)
signalName = 'onScrollDown'; signalName = 'onScrollDown';
return this._manageEventAction(this.onScroll, signalName); return this._manageEventAction(this.onScroll, signalName);
}
}
var MyPopupMenuItem = GObject.registerClass({
GTypeName: 'MyPopupMenuItem'
},
class MyPopupMenuItem extends PopupMenu.PopupBaseMenuItem {
_init(widgets, params) {
super._init(params);
this.box = new St.BoxLayout({ style_class: 'popup-combobox-item' });
this.box.set_vertical(true);
for (let widgetIndex in widgets)
this.box.add(widgets[widgetIndex]);
this.add_child(this.box);
}
});
var MonitorWidget = GObject.registerClass({
GTypeName: 'MonitorWidget'
},
class MonitorWidget extends PanelMenu.Button {
_init(item, group, dbus, position) {
super._init(0.0);
this.name = item['name'];
this.group = group;
this.fullname = this.name + '@' + this.group;
this.dbus = dbus;
this.signals = new SignalMgt(item, this.name, group, dbus, this.menu);
this.popup_signals = {};
if (item.hasOwnProperty('icon'))
{
if (typeof(item['icon']) === 'string')
this.icon = this._createIconOld(item);
else
this.icon = this._createIcon(item['icon']);
if (this.icon !== null) {
this.signals.connectWidgetSignals(this.icon);
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']);
if (this.widget !== null) {
this.signals.connectWidgetSignals(this.widget);
this.add_child(this.widget);
}
} else
this.widget = null;
if (item.hasOwnProperty('popup'))
this._createPopup(item['popup']);
const box = hashGet(item, 'box', 'center');
if (box === 'right' && position == -1)
position = 0;
this.connect('style-changed', this._onStyleChanged.bind(this));
Main.panel.addToStatusArea(this.fullname, this, position, box);
} }
update(item) { update(item) {
let prevWidget = this.widget; const prevWidget = this.widget;
let prevIcon = this.icon; const prevIcon = this.icon;
if (item.hasOwnProperty('text')) if (item.hasOwnProperty('text'))
{ {
let text = ''; let text = '';
let style = ''; let style = '';
if (typeof(item['text']) === "string") { if (typeof(item['text']) === 'string') {
text = hashGet(item, 'text', ''); text = hashGet(item, 'text', '');
style = hashGet(item, 'style', ''); style = hashGet(item, 'style', '');
} else { } else {
let textValues = item['text']; const textValues = item['text'];
text = hashGet(textValues, 'text', ''); text = hashGet(textValues, 'text', '');
style = hashGet(textValues, 'style', ''); style = hashGet(textValues, 'style', '');
} }
if (text !== '') { if (text !== '') {
if (!this.widget) { if (!this.widget) {
if (typeof(item['text']) === "string") if (typeof(item['text']) === 'string')
this.widget = this._createTextOld(item); this.widget = this._createTextOld(item);
else else
this.widget = this._createText(item['text']); this.widget = this._createText(item['text']);
@@ -407,24 +303,24 @@ class MonitorWidget extends PanelMenu.Button {
{ {
let icon = ''; let icon = '';
let style = ''; let style = '';
if (typeof(item['icon']) === "string") { if (typeof(item['icon']) === 'string') {
icon = hashGet(item, 'icon', ''); icon = hashGet(item, 'icon', '');
style = hashGet(item, 'iconStyle', ''); style = hashGet(item, 'iconStyle', '');
} else { } else {
let iconValues = item['icon']; const iconValues = item['icon'];
icon = hashGet(iconValues, 'path', ''); icon = hashGet(iconValues, 'path', '');
style = hashGet(iconValues, 'style', ''); style = hashGet(iconValues, 'style', '');
} }
if (icon !== '') { if (icon !== '') {
if (typeof(item['icon']) === "string") if (typeof(item['icon']) === 'string')
this.icon = this._createIconOld(item); this.icon = this._createIconOld(item);
else else
this.icon = this._createIcon(item['icon']); this.icon = this._createIcon(item['icon']);
} }
if (prevIcon) { if (prevIcon) {
this._disconnectWidgetSignals(prevIcon); this.signals.disconnectWidgetSignals(prevIcon);
this.insert_child_above(this.icon, prevIcon); this.insert_child_above(this.icon, prevIcon);
this.remove_child(prevIcon); this.remove_child(prevIcon);
//delete prevIcon; //delete prevIcon;
@@ -438,26 +334,22 @@ class MonitorWidget extends PanelMenu.Button {
if (item.hasOwnProperty('popup')) if (item.hasOwnProperty('popup'))
{ {
let menuOpen = this.menu.isOpen; const menuOpen = this.menu.isOpen;
if (this.menuItem) { if (this.menuItem) {
if (menuOpen) if (menuOpen)
this.menu.close(); this.menu.close();
for(let widgetIdx in this.popup_signals)
this.signals.disconnectWidgetSignals(this.popup_signals[widgetIdx]);
this.menu.removeAll(); this.menu.removeAll();
//delete this.menuItem; //delete this.menuItem;
} }
let popup = this._createPopup(item['popup']); const popup = this._createPopup(item['popup']);
if (popup !== null && menuOpen) if (popup !== null && menuOpen)
this.menu.open(true); this.menu.open(true);
} }
this.onClick = hashGet(item, 'on-click', this.onClick); this.signals.updateSignals(item);
this.onDblClick = hashGet(item, 'on-dblclick', this.onDblClick);
this.onRightClick = hashGet(item, 'on-rightclick', this.onRightClick);
this.onRightDblClick = hashGet(item, 'on-rightdblclick', this.onRightDblClick);
this.onEnter = hashGet(item, 'on-enter', this.onEnter);
this.onLeave = hashGet(item, 'on-leave', this.onLeave);
this.onScroll = hashGet(item, 'on-scroll', this.onScroll);
} }
openPopup() { openPopup() {
@@ -476,16 +368,157 @@ class MonitorWidget extends PanelMenu.Button {
this.menu.close(); this.menu.close();
super.destroy(); super.destroy();
} }
_onStyleChanged() {
// Force these values to avoid big spaces between each widgets
this._minHPadding = 1;
this._natHPadding = 1;
}
_createPopup(item) {
if (!item.hasOwnProperty('items')) {
return null;
}
let widgets = [];
for (let itemIndex in item['items']) {
let widget = null;
let widgetDict = item['items'][itemIndex];
let nestedItem = null;
if (widgetDict.hasOwnProperty('text')) {
nestedItem = widgetDict['text'];
widget = this._createText(nestedItem);
} else if (widgetDict.hasOwnProperty('picture')) {
nestedItem = widgetDict['picture'];
widget = this._createPicture(nestedItem);
} else {
log('No known widget defined in popup');
}
if (nestedItem === null) {
continue;
}
widgets.push(widget);
const name = hashGet(nestedItem, 'name', '');
this.popup_signals[widget] = new SignalMgt(nestedItem, name,
this.fullname, this.dbus,
this.menu);
this.popup_signals[widget].connectWidgetSignals(widget);
}
if (widgets.length > 0) {
this.menuItem = new MyPopupMenuItem(widgets, {});
this.menu.addMenuItem(this.menuItem);
this.menu.setSensitive(false);
return this.menuItem;
}
return null;
}
_createTextOld(item) {
var itemValues = {};
itemValues = { 'text':item['text'] };
if (item.hasOwnProperty('style'))
itemValues['style'] = item['style'];
return this._createText(itemValues);
}
_createText(item) {
if (!item.hasOwnProperty('text')) {
log('Text must have a \'text\' value');
return null;
}
const style = hashGet(item, 'style', '');
this.textProperties = item;
if (item['text'] === '') {
return null;
} else {
const widget = new St.Button({ label: item['text'] });
widget.set_style(style);
return widget;
}
}
_createIconOld(item) {
var itemValues = {};
itemValues = { 'path':item['icon'] };
if (item.hasOwnProperty('iconStyle'))
itemValues['style'] = item['iconStyle'];
return this._createIcon(itemValues);
}
_createIcon(item) {
if (!item.hasOwnProperty('path')) {
log('Icon must have a \'path\' value');
return null;
}
const style = hashGet(item, 'style', '');
this.iconProperties = item;
if (item['path'] === '') {
return null;
} else {
let gicon = Gio.icon_new_for_string(item['path']);
gicon = new St.Icon({ gicon });
gicon.set_style(style);
return gicon;
}
}
_createPicture(item) {
if (!item.hasOwnProperty('path')) {
log('Picture must have a \'path\' value');
return null;
}
let width = hashGet(item, 'width', -1);
let height = hashGet(item, 'height', -1);
if (typeof(width) === 'string')
width = parseInt(width, 10);
if (typeof(height) === 'string')
height = parseInt(height, 10);
const img = new Clutter.Image();
const initialPixbuf = Pixbuf.Pixbuf.new_from_file(item['path']);
img.set_data(initialPixbuf.get_pixels(),
initialPixbuf.get_has_alpha() ? Cogl.PixelFormat.RGBA_8888
: Cogl.PixelFormat.RGB_888,
initialPixbuf.get_width(),
initialPixbuf.get_height(),
initialPixbuf.get_rowstride());
const picture = new Clutter.Actor();
picture.set_content(img);
picture.set_size((width != -1)?width:initialPixbuf.get_width(),
(height != -1)?height:initialPixbuf.get_height());
// Pack it in a box to avoid picture resize
const box = new St.BoxLayout({});
box.add_child(picture);
return box;
}
}); });
// From https://github.com/ubuntu/gnome-shell-extension-appindicator/blob/master/interfaces.js // From https://github.com/ubuntu/gnome-shell-extension-appindicator/blob/master/interfaces.js
// loads a xml file into an in-memory string // loads a xml file into an in-memory string
function loadInterfaceXml(filename) { function loadInterfaceXml(filename) {
let extension = imports.misc.extensionUtils.getCurrentExtension(); const extension = imports.misc.extensionUtils.getCurrentExtension();
let interfacesDir = extension.dir.get_child('.'); const interfacesDir = extension.dir.get_child('.');
let file = interfacesDir.get_child(filename); const file = interfacesDir.get_child(filename);
let [result, contents] = imports.gi.GLib.file_get_contents(file.get_path()); let [result, contents] = imports.gi.GLib.file_get_contents(file.get_path());
@@ -497,7 +530,7 @@ function loadInterfaceXml(filename) {
// will spit out a TypeError soon). // will spit out a TypeError soon).
if (contents instanceof Uint8Array) if (contents instanceof Uint8Array)
contents = imports.byteArray.toString(contents); contents = imports.byteArray.toString(contents);
let res = `<node>${contents}</node>`; const res = `<node>${contents}</node>`;
return res; return res;
} else { } else {
throw new Error(`Generic monitor: Could not load file: ${filename}`); throw new Error(`Generic monitor: Could not load file: ${filename}`);
@@ -530,7 +563,7 @@ class GenericMonitorDBUS {
} }
for (let itemIndex in parameters['items']) { for (let itemIndex in parameters['items']) {
let item = parameters['items'][itemIndex]; const item = parameters['items'][itemIndex];
if (!item.hasOwnProperty('name')) { if (!item.hasOwnProperty('name')) {
log('No name defined for item'); log('No name defined for item');
return false; return false;
@@ -542,7 +575,7 @@ class GenericMonitorDBUS {
_getItemFromGroup(group, name) { _getItemFromGroup(group, name) {
for (let groupItemIndex in group) { for (let groupItemIndex in group) {
let groupItem = group[groupItemIndex]; const groupItem = group[groupItemIndex];
if (groupItem.name === name) if (groupItem.name === name)
return groupItem; return groupItem;
} }
@@ -551,7 +584,7 @@ class GenericMonitorDBUS {
} }
_getItemFromFullName(fullname) { _getItemFromFullName(fullname) {
let splitName = fullname.split('@'); const splitName = fullname.split('@');
if (splitName.length !== 2) { if (splitName.length !== 2) {
log(`Invalid name ${fullname}`); log(`Invalid name ${fullname}`);
return null; return null;
@@ -574,11 +607,11 @@ class GenericMonitorDBUS {
} }
notify(str) { notify(str) {
let parameters = JSON.parse(str); const parameters = JSON.parse(str);
if (!this._checkParameters(parameters)) if (!this._checkParameters(parameters))
return; return;
let groupName = parameters['group']; const groupName = parameters['group'];
let group; let group;
if (!this.monitor_groups.hasOwnProperty(groupName)) { if (!this.monitor_groups.hasOwnProperty(groupName)) {
group = []; group = [];
@@ -588,7 +621,7 @@ class GenericMonitorDBUS {
} }
for (let itemIndex in parameters['items']) { for (let itemIndex in parameters['items']) {
let item = parameters['items'][itemIndex]; const item = parameters['items'][itemIndex];
let monitorWidget = this._getItemFromGroup(group, item['name']); let monitorWidget = this._getItemFromGroup(group, item['name']);
// New widget // New widget
@@ -596,8 +629,8 @@ class GenericMonitorDBUS {
let position = group.length - 1; let position = group.length - 1;
// Find real position // Find real position
if (position != -1) { if (position != -1) {
let lastWidget = group[position].container; const lastWidget = group[position].container;
let childrens = lastWidget.get_parent().get_children(); const childrens = lastWidget.get_parent().get_children();
for(;position < childrens.length; position++) for(;position < childrens.length; position++)
{ {
if (childrens[position] == lastWidget) { if (childrens[position] == lastWidget) {
@@ -627,7 +660,7 @@ class GenericMonitorDBUS {
} }
deleteItems(str) { deleteItems(str) {
let parameters = JSON.parse(str); const parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('items')) { if (!parameters.hasOwnProperty('items')) {
log('No items defined'); log('No items defined');
@@ -636,7 +669,7 @@ class GenericMonitorDBUS {
for (let itemIndex in parameters['items']) { for (let itemIndex in parameters['items']) {
let itemName = parameters['items'][itemIndex]; let itemName = parameters['items'][itemIndex];
let splitName = itemName.split('@'); const splitName = itemName.split('@');
if (splitName.length !== 2) { if (splitName.length !== 2) {
log(`Invalid name ${itemName}`); log(`Invalid name ${itemName}`);
return false; return false;
@@ -654,7 +687,7 @@ class GenericMonitorDBUS {
} }
deleteGroups(str) { deleteGroups(str) {
let parameters = JSON.parse(str); const parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('groups')) { if (!parameters.hasOwnProperty('groups')) {
log('No groups defined'); log('No groups defined');
@@ -663,29 +696,29 @@ class GenericMonitorDBUS {
let groupsToDelete = []; let groupsToDelete = [];
for (let groupIndex in parameters['groups']) { for (let groupIndex in parameters['groups']) {
let groupName = parameters['groups'][groupIndex]; const groupName = parameters['groups'][groupIndex];
if (!this.monitor_groups.hasOwnProperty(groupName)) if (!this.monitor_groups.hasOwnProperty(groupName))
continue; continue;
let group = this.monitor_groups[groupName]; const group = this.monitor_groups[groupName];
for (let itemIndex in group) for (let itemIndex in group)
group[itemIndex].destroy(); group[itemIndex].destroy();
groupsToDelete.push(groupName); groupsToDelete.push(groupName);
} }
for (let groupDeleteIndex in groupsToDelete) { for (let groupDeleteIndex in groupsToDelete) {
let groupName = groupsToDelete[groupDeleteIndex]; const groupName = groupsToDelete[groupDeleteIndex];
delete this.monitor_groups[groupName]; delete this.monitor_groups[groupName];
} }
} }
_popupFunction(str) { _popupFunction(str) {
let parameters = JSON.parse(str); const parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('item')) { if (!parameters.hasOwnProperty('item')) {
log('No item defined'); log('No item defined');
return false; return false;
} }
let monitorWidget = this._getItemFromFullName(parameters['item']); const monitorWidget = this._getItemFromFullName(parameters['item']);
if (monitorWidget !== null) if (monitorWidget !== null)
return monitorWidget; return monitorWidget;
else else
@@ -695,19 +728,19 @@ class GenericMonitorDBUS {
} }
openPopup(str) { openPopup(str) {
let monitorWidget = this._popupFunction(str) const monitorWidget = this._popupFunction(str)
if (monitorWidget !== null) if (monitorWidget !== null)
monitorWidget.openPopup(); monitorWidget.openPopup();
} }
closePopup(str) { closePopup(str) {
let monitorWidget = this._popupFunction(str) const monitorWidget = this._popupFunction(str)
if (monitorWidget !== null) if (monitorWidget !== null)
monitorWidget.closePopup(); monitorWidget.closePopup();
} }
togglePopup(str) { togglePopup(str) {
let monitorWidget = this._popupFunction(str) const monitorWidget = this._popupFunction(str)
if (monitorWidget !== null) if (monitorWidget !== null)
monitorWidget.togglePopup(); monitorWidget.togglePopup();
} }
@@ -715,7 +748,7 @@ class GenericMonitorDBUS {
destructor() { destructor() {
this._dbusImpl.emit_signal('onDeactivate', null); this._dbusImpl.emit_signal('onDeactivate', null);
for (let groupIndex in this.monitor_groups) { for (let groupIndex in this.monitor_groups) {
let group = this.monitor_groups[groupIndex]; const group = this.monitor_groups[groupIndex];
for (let itemIndex in group) for (let itemIndex in group)
group[itemIndex].destroy(); group[itemIndex].destroy();
} }
@@ -735,7 +768,7 @@ class Extension {
} }
} }
let extension = new Extension(); const extension = new Extension();
function init() { function init() {
} }
+1 -1
View File
@@ -2,7 +2,7 @@
"uuid": "generic-monitor@gnome-shell-extensions", "uuid": "generic-monitor@gnome-shell-extensions",
"name": "Generic Monitor", "name": "Generic Monitor",
"description": "Display text & icon on systray using DBUS", "description": "Display text & icon on systray using DBUS",
"version": "3", "version": "4",
"shell-version": [ "shell-version": [
"3.38", "3.38",
"3.36", "3.36",