33 Commits
v2 ... v6

Author SHA1 Message Date
02d3e8b72a Remove timer resource during SignalMgt destructor 2022-01-06 09:52:11 +01:00
78254a550e Update support for version 41 in metadata 2022-01-06 09:14:55 +01:00
7a5f506c23 Remove use of deprecated "lang" package 2021-10-01 09:02:34 +02:00
1d3328f71e Update support for version 40 in metadata 2021-09-30 16:33:06 +02:00
45d0cc9d11 Use WeakMap to store objects as key and rename MonitorWidget signals field into signalManager to avoid confusions 2021-09-30 16:32:26 +02:00
4d6fe82790 Update version 2021-02-02 07:04:45 +01:00
9943a9075f Popup text must be labels not buttons 2021-01-31 20:18:11 +01:00
83609b58ab After linter pass 2021-01-29 09:15:40 +01:00
b85ff4a782 Update examples 2021-01-28 10:34:18 +01:00
30bfc796b9 Update README 2021-01-28 10:34:18 +01:00
35e34b52f2 Move signal management into external class. It allows to handle signals for popup nested elements. 2021-01-28 10:34:17 +01:00
1b4430c3ac Update README 2020-11-28 12:14:48 +01:00
ca5426bbde Some spaces changes 2020-11-25 10:53:06 +01:00
c8dc01fe62 Add signal management in _manageEventAction() 2020-11-25 10:53:06 +01:00
fbf138faee Enter/Leave problem fixed with c5b9f25587 2020-11-25 10:53:06 +01:00
b0977da704 Fix some errors 2020-11-25 10:53:06 +01:00
bdf3bac8c4 Update metadata 2020-11-25 10:53:06 +01:00
5d64f4e8db Update code for Gnome Shell coding rules 2020-11-25 10:53:06 +01:00
11acefa076 Fix quit script action 2020-11-25 10:53:06 +01:00
4438709a99 Add Python picture.py example 2020-11-25 10:53:06 +01:00
389e6a108a Update Python example with new API 2020-11-25 10:53:01 +01:00
d756ef2c1e Update README 2020-11-18 16:20:12 +01:00
4c52c9fa8e Add management for onDblClick, onRightClick and onRightDblClick events. Before they were put under Click event. 2020-11-18 16:17:58 +01:00
8a480254cd Add picture into an inner layout in order to avoid parent resize 2020-11-18 16:17:13 +01:00
c5b9f25587 Propagate events. If not, other items doesn't get it 2020-11-18 16:16:06 +01:00
b10b73135d Add onScroll[Up|Down] event 2020-11-12 14:16:17 +01:00
6b1fe1dd2d Add openPopup(), closePopup() and togglePopup() functions to DBUS interface 2020-11-12 10:42:11 +01:00
d3eb13994a Work on events 2020-11-06 16:22:05 +01:00
bd9e3722a2 Remove useless old code 2020-11-05 15:38:50 +01:00
cf879a2c46 Manage events 2020-11-05 15:36:14 +01:00
8c709d38d5 Fix positioning and blank spaces 2020-11-04 14:52:43 +01:00
5458908603 New architecture : create & update works, signals and remove doesn't 2020-11-03 16:59:27 +01:00
8032ce0245 WIP 2020-11-02 17:03:34 +01:00
8 changed files with 1287 additions and 314 deletions

103
README.md
View File

@@ -23,18 +23,14 @@ All functions read JSON formatted parameters
notify():
{
"group": "groupname",
// item can have text and/or icon, other are optional
// click action can be : "signal" or "delete"
// box property can be : "left", "center" or "right"
"items": [
{
"name":"",
"text":"",
"style":"",
"icon-style":"",
"icon":"",
"on-click":"",
"box":"",
"name" : "",
"box" : ["left"|"center"|"right"], // Optional : center by default
"text" : <text_object>, // Optional
"icon" : <icon_object>, // Optional
"popup" : <popup_object>, // Optional
<signals_description>, // Optional
}, ...
]
}
@@ -50,14 +46,90 @@ All functions read JSON formatted parameters
"groups": ["<groupName>", ...]
}
openPopup():
{
"item": "<itemName>@<groupName>"
}
When text/icon is clicked and on-click parameter is set to "signal",
extension emit one of the following signals :
closePopup():
{
"item": "<itemName>@<groupName>"
}
togglePopup():
{
"item": "<itemName>@<groupName>"
}
DBUS object
===========
<text_object> is defined as :
"text" : {
"name" : "" // Optional, used with popup nested element
<signals_description>, // Optional, used with popup nested element
"text" : "Text to be displayed",
"style" : "CSS style to be applied", // Optional
}
<icon_object> is defined as :
"icon" : {
"path" : "Icon path",
"style" : "CSS style to be applied", // Optional
}
<picture_object> is defined as :
"picture" : {
"name" : "" // Optional, used with popup nested element
<signals_description>, // Optional, used with popup nested element
"path" : "Icon path",
"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
}
<popup_object is defuned as :
"popup" : {
"items": [<text_objects> and/or <picture_objects>]
}
Signals description
===================
Signals can be :
"on-click" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-dblclick" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-rightclick" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-rightdblclick" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-enter" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-leave" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-scroll" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
Targets :
* signal : emit a signal to desktop application
* delete : Delete item
* open-popup : Open the popup if there is one
* close-popup : Close the popup if there is one
* toggle-popup : Toggle (open/close) the popup if there is one
Signal names emit when action "signal" is specified :
* onClick
* onRightClick
* onDblClick
* onRightClick
* onRightDblClick
* onEnter
* onLeave
* onScrollUp
* onScrollDown
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 :
@@ -70,10 +142,11 @@ Example
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","text":"Hello","style":"color:green"}]}'
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"]}'
Python example is available
Python examples is available
Development

View File

@@ -9,7 +9,16 @@
<method name="deleteGroups">
<arg type="s" direction="in" />
</method>
<!-- Click events -->
<method name="openPopup">
<arg type="s" direction="in" />
</method>
<method name="closePopup">
<arg type="s" direction="in" />
</method>
<method name="togglePopup">
<arg type="s" direction="in" />
</method>
<!-- Events -->
<signal name="onClick">
<arg type="s" direction="out" />
</signal>
@@ -22,6 +31,18 @@
<signal name="onRightDblClick">
<arg type="s" direction="out" />
</signal>
<signal name="onScrollUp">
<arg type="s" direction="out" />
</signal>
<signal name="onScrollDown">
<arg type="s" direction="out" />
</signal>
<signal name="onEnter">
<arg type="s" direction="out" />
</signal>
<signal name="onLeave">
<arg type="s" direction="out" />
</signal>
<!-- Activate/Deactivate signals -->
<signal name="onActivate">
</signal>

View File

@@ -20,10 +20,17 @@ import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, GLib, Gst
#
# DBUS interface
#
class GenericMonitor:
"""
Class that manage DBUS communication with GNOME generic monitor addon.
You have to subclass it
"""
def setupMonitor(self):
""" Setup DBUS stuff (equivalent to constructor) """
self._activated = True
self._encoder = json.JSONEncoder()
self._dbus_interface = 'com.soutade.GenericMonitor'
@@ -33,108 +40,485 @@ class GenericMonitor:
self.systray_proxy = self._dbus.get_object('org.gnome.Shell', '/com/soutade/GenericMonitor')
self._dbus.add_signal_receiver(self.onClick, 'onClick', self._dbus_interface)
self._dbus.add_signal_receiver(self.onDblClick, 'onDblClick', self._dbus_interface)
self._dbus.add_signal_receiver(self.onRightClick, 'onRightClick', self._dbus_interface)
self._dbus.add_signal_receiver(self.onDblRightClick, 'onDblRightClick', self._dbus_interface)
self.add_signal_receiver(self.onClick, 'onClick')
self.add_signal_receiver(self.onDblClick, 'onDblClick')
self.add_signal_receiver(self.onRightClick, 'onRightClick')
self.add_signal_receiver(self.onRightDblClick, 'onRightDblClick')
self.add_signal_receiver(self.onScrollUp, 'onScrollUp')
self.add_signal_receiver(self.onScrollDown, 'onScrollDown')
self.add_signal_receiver(self.onEnter, 'onEnter')
self.add_signal_receiver(self.onLeave, 'onLeave')
self._dbus.add_signal_receiver(self.onActivate, 'onActivate', self._dbus_interface)
self._dbus.add_signal_receiver(self.onDeactivate, 'onDeactivate', self._dbus_interface)
self.add_signal_receiver(self.onActivate, 'onActivate')
self.add_signal_receiver(self.onDeactivate, 'onDeactivate')
def runMainLoop(self):
""" Start infinite loop that allows to send and receive events and functions """
self._mainLoop = GLib.MainLoop()
self._mainLoop.run()
def stopMainLoop(self):
""" Stop infinite main loop """
self._mainLoop.quit()
# Generic Monitor functions
def notify(self, group):
""" Send notify() function
Parameters
----------
group : GenericMonitorGroup
group to notify
"""
if self._activated:
if type(group) == GenericMonitorGroup:
group = group.getValues()
self.systray_proxy.notify(self._encoder.encode(group), dbus_interface=self._dbus_interface)
def deleteItems(self, items):
""" Send deleteItems() function
Parameters
----------
items : list of str (<itemName>@<groupName>)
items to delete
"""
if self._activated:
items = {'items':items}
self.systray_proxy.deleteItems(self._encoder.encode(items), dbus_interface=self._dbus_interface)
def deleteGroups(self, groups):
""" Send deleteGroups() function
Parameters
----------
groups : list of str (<groupName>)
groups to delete
"""
if self._activated:
groups = {'groups':groups}
self.systray_proxy.deleteGroups(self._encoder.encode(groups), dbus_interface=self._dbus_interface)
def openPopup(self, item):
""" Send openPopup() function
Parameters
----------
item : str (<itemName>@<groupName>)
Open popup (if there is one) of item
"""
if self._activated:
item = {'item':item}
self.systray_proxy.openPopup(self._encoder.encode(item), dbus_interface=self._dbus_interface)
def closePopup(self, item):
""" Send closePopup() function
Parameters
----------
item : str (<itemName>@<groupName>)
Close popup (if there is one) of item
"""
if self._activated:
item = {'item':item}
self.systray_proxy.closePopup(self._encoder.encode(item), dbus_interface=self._dbus_interface)
def togglePopup(self, item):
""" Send togglePopup() function
Parameters
----------
item : str (<itemName>@<groupName>)
Toggle popup (if there is one) of item
"""
if self._activated:
item = {'item':item}
self.systray_proxy.togglePopup(self._encoder.encode(item), dbus_interface=self._dbus_interface)
# Generic Monitor signals
def onClick(self, sender):
""" onClick event
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onRightClick(self, sender):
""" onRightClick event
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onDblClick(self, sender):
""" onDblClick event
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onDblRightClick(self, sender):
def onRightDblClick(self, sender):
""" onRightDblClick event
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onEnter(self, sender):
""" onEnter event (mouse enter in item)
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onLeave(self, sender):
""" onLeave event (mouse leave item)
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onScrollUp(self, sender):
""" onScrollUp event
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onScrollDown(self, sender):
""" onScrollDown event
Parameters
----------
sender : str (<itemName>@<groupName>)
Sender which event has been raised
"""
pass
def onActivate(self):
""" onActivate event (addon activated)
"""
self._activated = True
def onDeactivate(self):
""" onDeactivate event (addon deactivated)
"""
self._activated = False
# DBUS method
def add_signal_receiver(self, callback, signalName, interface):
""" Add callback when DBUS signal is raised
Parameters
----------
callback : function
Callback raised on DBUS signal
signalName : str
Name of DBUS signal
interface : str
Name of DBUS interface
"""
def add_signal_receiver(self, callback, signalName, interface=None):
if not interface:
interface = self._dbus_interface
self._dbus.add_signal_receiver(callback, signalName, interface)
class GenericMonitorItem:
def __init__(self, name, text='', style='', icon='', iconStyle='', onClick='', box=''):
#
# Item stuff
#
class GenericMonitorGenericWidget:
""" Generic widget class, parent of all widgets
"""
def __init__(self, style='', name='', signals={}):
"""
Parameters
----------
name : str, optional
Widget name
signals : dictionary, optional
Dictionary of signals and their action
"""
self.valuesToMap = ['name', 'style']
self.mapValues = {}
self.mapName = ''
self.style = style
self.name = name
self.signals = signals
def setStyle(self, style):
self.style = style
def _toMap(self):
""" Return dictionary of class elements to send to addon
"""
self.mapValues = {}
for p in self.valuesToMap:
if 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}
class GenericMonitorTextWidget(GenericMonitorGenericWidget):
""" Text widget
"""
def __init__(self, text, style='', name='', signals={}):
"""
Parameters
----------
text : str
Text to display
style : str, optional
CSS style
name : str, optional
Widget name
signals : dictionary, optional
Dictionary of signals and their action
"""
super().__init__(style, name, signals)
self.valuesToMap += ['text']
self.mapName = 'text'
self.text = text
self.style= style
self.icon = icon
self.iconStyle = iconStyle
self.onClick = onClick
def setText(self, text):
self.text = text
class GenericMonitorIconWidget(GenericMonitorGenericWidget):
""" Icon widget
"""
def __init__(self, path, style=''):
"""
Parameters
----------
path : str
Icon path
style : str, optional
CSS style
"""
super().__init__(style=style)
self.valuesToMap += ['path']
self.mapName = 'icon'
self.path = path
self.style = style
def setPath(self, path):
self.path = path
class GenericMonitorPictureWidget(GenericMonitorGenericWidget):
""" Picture widget
"""
def __init__(self, path, style='', width=-1, height=-1, name='', signals={}):
"""
Parameters
----------
path : str
Picture path
style : str, optional
CSS style
width : int, optional
Width of displayed picture (-1 for default width)
height : int, optional
Width of displayed picture (-1 for default width)
name : str, optional
Widget name
signals : dictionary, optional
Dictionary of signals and their action
"""
super().__init__(style, name, signals)
self.valuesToMap += ['path', 'width', 'height']
self.mapName = 'picture'
self.path = path
self.width = width
self.height = height
def setPath(self, path):
self.path = path
def setWidth(self, width):
self.width = width
def setHeight(self, height):
self.height = height
class GenericMonitorPopup(GenericMonitorGenericWidget):
""" Popup of current item
"""
def __init__(self, items):
"""
Parameters
----------
items : list of GenericMonitorTextWidget and GenericMonitorPictureWidget
List of items (text or picture)
"""
self.valuesToMap = ('items',)
self.mapName = 'popup'
self.items = items
def _toMap(self):
self.mapValues = {}
self.mapValues['items'] = []
for item in self.items:
self.mapValues['items'] += [item._toMap()]
return {self.mapName:self.mapValues}
def clear(self):
""" Clear items list
"""
self.items = []
def setItems(self, items):
self.items = items
class GenericMonitorItem:
""" Addon item that will be displayed in status bar
"""
def __init__(self, name, items=[], signals={}, popup=None, box='center'):
"""
Parameters
----------
name : str
Item name
items : list of GenericMonitorTextWidget and GenericMonitorIconWidget, optional
List of items (text or icon)
signals : dictionary, optional
Dictionary of signals and their action
"on-click" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-dblclick" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-rightclick" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-rightdblclick" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-click" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-enter" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-leave" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
"on-scroll" : ["signal"|"delete"|"open-popup"|"close-popup"|"toggle-popup"]
popup : GenericMonitorPopup, optional
Popup to be displayed
box : str, optional
Box were to put items : left, center (default), or right
"""
self.name = name
self.items = items
self.signals = signals
self.popup = popup
self.box = box
self.group = ''
self._checkValues()
def _checkValues(self):
if self.onClick and not self.onClick in ('signal', 'delete'):
raise ValueError('Invalid onClick value')
if not self.name:
raise ValueError('Need a name')
if len(self.items) > 2:
raise ValueError('Maximum 2 items can be displayed')
for (name, value) in self.signals.items():
if not name in ('on-click', 'on-dblclick', 'on-rightclick', 'on-rightdblclick',
'on-enter', 'on-leave', 'on-scroll'):
raise ValueError('Invalid signal name ' + name)
if not value in ('signal', 'delete', 'open-popup', 'close-popup', 'toggle-popup'):
raise ValueError('Invalid signal value ' + value)
for item in self.items:
if not isinstance(item, GenericMonitorGenericWidget):
raise ValueError('Invalid item ' + item)
if self.popup and not isinstance(self.popup, GenericMonitorPopup):
raise ValueError('Invalid popup object')
if self.box and not self.box in ('left', 'center', 'right'):
raise ValueError('Invalid box value')
def toMap(self):
myMap = {"name":self.name}
for p in ('text', 'style', 'icon', 'box'):
def setGroup(self, group):
""" Set current group (automatically done when added in a group)
Parameters
----------
group : str
Group name
"""
self.group = group
def getName(self):
return self.name
def getFullName(self):
""" return full name used by addon
"""
return '%s@%s' % (self.name, self.group)
def _toMap(self):
myMap = {}
for p in ('name', 'box'):
if self.__dict__[p]:
myMap[p] = self.__dict__[p]
if self.iconStyle:
myMap['icon-style'] = self.iconStyle
if self.onClick:
myMap['on-click'] = self.onClick
for item in self.items:
item._toMap()
myMap[item.mapName] = item.mapValues
if self.popup:
self.popup._toMap()
myMap['popup'] = self.popup.mapValues
for (name, value) in self.signals.items():
myMap[name] = value
return [myMap]
class GenericMonitorGroup:
""" Group of items
"""
def __init__(self, name, items=[]):
"""
Parameters
----------
name : str
Group name
items : list of GenericMonitorItem, optional
List of items
"""
self.name = name
self.items = []
if type(items) != list:
self.items = [items]
self.addItem(items)
else:
self.items = items
self.addItems(items)
def addItem(self, item):
""" Add item into the groupw
Parameters
----------
item : GenericMonitorItem
Item to add
"""
item.setGroup(self.name)
self.items.append(item)
def addItems(self, items):
""" Add items into the group
Parameters
----------
items : list of GenericMonitorItem
Items to add
"""
for item in items:
self.addItem(item)
def clear(self):
""" Clear items list
"""
for item in items:
item.setGroup('')
self.items = []
def getValues(self):
""" Returns group and its items in addon format
"""
res = {'group': self.name, 'items':[]}
for item in self.items:
res['items'] += item.toMap()
res['items'] += item._toMap()
return res
def __str__(self):

View File

@@ -27,7 +27,7 @@ import getpass
from threading import Thread
from signal import signal, SIGINT
import sys
from genericmonitor import GenericMonitor, GenericMonitorGroup, GenericMonitorItem
from genericmonitor import *
PURPLE_CONV_UPDATE_UNSEEN = 4
PURPLE_MESSAGE_SEND = 0
@@ -66,27 +66,28 @@ class EventThread(Thread,GenericMonitor):
self.stopMainLoop()
def _getMail(self):
mailItem = GenericMonitorItem('mail')
mailGroup = GenericMonitorGroup('Mail', [mailItem])
address = "https://mail.google.com/mail/feed/atom"
auth = HTTPBasicAuth(self.MAIL_ADDRESS, self._mail_password)
req = requests.get(address, auth=auth)
text = ''
style = ''
if req.status_code == requests.codes.ok:
dom = xml.dom.minidom.parseString(req.text)
try:
nb_messages = int(dom.getElementsByTagName('fullcount')[0].firstChild.nodeValue)
if nb_messages == 1:
mailItem.text = '1 msg'
text = '1 msg'
elif nb_messages > 1:
mailItem.text = '%d msgs' % (nb_messages)
mailItem.style = 'color:white'
text = '%d msgs' % (nb_messages)
style = 'color:white'
except Exception as e:
mailItem.text = str(e)
text = str(e)
else:
mailItem.text = 'Mail error %d' % (req.status_code)
text = 'Mail error %d' % (req.status_code)
self.notify(mailGroup)
self.mailWidget.setText(text)
self.mailWidget.setStyle(style)
self.notify(self.mailGroup)
def getEvents(self):
self._getMail()
@@ -104,6 +105,14 @@ class EventThread(Thread,GenericMonitor):
self._mail_password = getpass.getpass('Enter password for address %s: ' % (self.MAIL_ADDRESS))
self.mailWidget = GenericMonitorTextWidget('')
mailItem = GenericMonitorItem('mail', [self.mailWidget])
self.mailGroup = GenericMonitorGroup('Mail', [mailItem])
icon = GenericMonitorIconWidget('/usr/share/icons/hicolor/22x22/apps/pidgin.png', 'icon-size:22px')
pidginItem = GenericMonitorItem('pidgin', [icon])
self.pidginGroup = GenericMonitorGroup('Pidgin', pidginItem)
while not self._stopLoop:
self.getEvents()
# Be more reactive on signal capture
@@ -129,9 +138,7 @@ class EventThread(Thread,GenericMonitor):
pidginConversation.nbMessages = 1
def displayIcon(self):
pidginItem = GenericMonitorItem('pidgin', icon='/usr/share/icons/hicolor/22x22/apps/pidgin.png', iconStyle='icon-size:22px')
pidginGroup = GenericMonitorGroup('Pidgin', pidginItem)
self.notify(pidginGroup)
self.notify(self.pidginGroup)
def pidginConversationUpdated(self, conversation, _type):
if _type != PURPLE_CONV_UPDATE_UNSEEN:
@@ -171,7 +178,7 @@ class EventThread(Thread,GenericMonitor):
def signalHandler(signal_received, frame):
eventThread.stop()
eventThread.join()
groups = {'groups':['Mail', 'Pidgin']}
groups = ['Mail', 'Pidgin']
eventThread.deleteGroups(groups)
sys.exit(0)

106
examples/picture.py Executable file
View File

@@ -0,0 +1,106 @@
#!/usr/bin/env python3
#
# 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 <https://www.gnu.org/licenses/>.
#
'''
Display random picture from unsplash.com in a popup
* Click : open/close popup
* Popup item click : display who clicked
* ScrollUp/ScrollDown/Double click : display next picture
* Right click : exit
'''
import urllib.request
import sys
import signal
from genericmonitor import *
class PicturePopup(GenericMonitor):
def __init__(self):
self.scrolling = False
self.item = None
self.imgs_idx = 0
self.setupMonitor()
def run(self):
self.display_next_img()
self.runMainLoop()
def display_next_img(self):
filedata = urllib.request.urlopen('https://source.unsplash.com/random')
# Get redirected URL without parameters
url = filedata.url.split('?')[0]
filedata = urllib.request.urlopen(url + '?fit=max&width=500&height=500')
datatowrite = filedata.read()
with open('/tmp/cat2.jpg', 'wb') as f:
f.write(datatowrite)
widget = GenericMonitorTextWidget('#%d' % self.imgs_idx, 'color:purple')
url_widget = GenericMonitorTextWidget(url, 'color:white;font-weight:bold', signals={'on-click':'signal'}) # No name here
picture_widget = GenericMonitorPictureWidget('/tmp/cat2.jpg', name='NestedWidget', signals={'on-click':'signal'})
popup = GenericMonitorPopup([url_widget, picture_widget])
signals = {
'on-click':'toggle-popup',
# Could also use this behavior
# 'on-enter':'open-popup',
# 'on-leave':'close-popup',
'on-dblclick':'signal',
'on-rightclick':'signal',
'on-scroll':'signal',
}
self.item = GenericMonitorItem('picturepopup', [widget], signals, popup)
group = GenericMonitorGroup('PicturePopup', [self.item])
self.notify(group)
self.imgs_idx += 1
def _forMe(self, sender):
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):
if not self._forMe(sender): return
if self.scrolling: return
self.scrolling = True
self.display_next_img()
self.scrolling = False
def onScrollUp(self, sender):
self._onScroll(sender)
def onScrollDown(self, sender):
self._onScroll(sender)
def onDblClick(self, sender):
self.onScrollUp(sender)
def onRightClick(self, sender):
if not self._forMe(sender): return
if self.item:
self.deleteItems([self.item.getFullName()])
self.stopMainLoop()
def signal_handler(sig, frame):
picture.deleteGroups(['PicturePopup'])
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
picture = PicturePopup()
picture.run()

View File

@@ -29,7 +29,7 @@ import time
from threading import Thread
from signal import signal, SIGINT
import sys
from genericmonitor import GenericMonitor, GenericMonitorGroup, GenericMonitorItem
from genericmonitor import *
class TimerThread(Thread,GenericMonitor):
@@ -38,20 +38,24 @@ class TimerThread(Thread,GenericMonitor):
self.stopMainLoop()
def _displayTimerValue(self):
item = GenericMonitorItem('timer', onClick='signal', box='right')
group = GenericMonitorGroup('Timer', item)
curValue = self.timers[self.curTimer]
item.text = '%02d:%02d' % (int(curValue/60)%60, curValue%60)
text = '%02d:%02d' % (int(curValue/60)%60, curValue%60)
if curValue >= (60*60):
item.text = '%02d:%s' % (int(curValue/(60*60)), item.text)
text = '%02d:%s' % (int(curValue/(60*60)), text)
if self.curTimer == 0:
if self.timerPaused and curValue:
style = 'color:black;background-color:white'
else:
style = 'color:white'
if curValue > (60*60):
if curValue >= (60*60):
style += ';background-color:red'
else:
style = 'color:#215D9C'
item.style = style
self.notify(group)
self.textWidget.setText(text)
self.textWidget.setStyle(style)
self.notify(self.monitorGroup)
def run(self):
self.setupMonitor()
@@ -59,6 +63,12 @@ class TimerThread(Thread,GenericMonitor):
self.curTimer = 0
self.timerPaused = False
self._stopLoop = False
self.textWidget = GenericMonitorTextWidget('')
signals = {'on-click':'signal','on-dblclick':'signal','on-rightclick':'signal'}
self.monitorItem = GenericMonitorItem('timer', [self.textWidget], signals, box='right')
self.monitorGroup = GenericMonitorGroup('Timer', self.monitorItem)
while not self._stopLoop:
time.sleep(1)
if not self.timerPaused:
@@ -66,7 +76,7 @@ class TimerThread(Thread,GenericMonitor):
self._displayTimerValue()
def _forMe(self, sender):
return sender == 'timer@Timer'
return sender == self.monitorItem.getFullName()
def onClick(self, sender):
if not self._forMe(sender): return
@@ -103,7 +113,7 @@ class TimerThread(Thread,GenericMonitor):
def signalHandler(signal_received, frame):
timerThread.stop()
timerThread.join()
groups = {'groups':['Timer']}
groups = ['Timer']
timerThread.deleteGroups(groups)
sys.exit(0)

View File

@@ -18,139 +18,530 @@
/* Based on https://stackoverflow.com/questions/33001192/how-to-send-a-string-to-a-gnome-shell-extension */
/*
Some useful documentation :
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
https://gitlab.gnome.org/GNOME/gnome-shell/-/blob/master/js/ui/panel.js
*/
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;
const Clutter = imports.gi.Clutter;
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;
class MonitorWidget {
constructor(name, group, text, style, icon, iconStyle, onClick, box, lastWidget) {
function hashGet(hash, key, defaultValue) {
if (hash.hasOwnProperty(key))
return hash[key];
return defaultValue;
}
function log(message) {
global.log('[GenericMontior]', message);
}
class SignalMgt {
constructor(item, name, group, dbus, menu) {
this.name = name;
this.group = group;
this._createIcon(icon, iconStyle);
this._createText(text, style);
this.onClick = onClick;
this.fullname = this.name + '@' + this.group;
this.dbus = dbus;
this.menu = menu;
this.signals = new WeakMap();
this.widgets = new Array();
this.timeouts = new Array();
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;
this.nbClicks = 0;
this.button = -1;
this.onClick = hashGet(item, 'on-click', '');
this.onDblClick = hashGet(item, 'on-dblclick', '');
this.onRightClick = hashGet(item, 'on-rightclick', '');
this.onRightDblClick = hashGet(item, 'on-rightdblclick', '');
this.onEnter = hashGet(item, 'on-enter', '');
this.onLeave = hashGet(item, 'on-leave', '');
this.onScroll = hashGet(item, 'on-scroll', '');
}
// 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;
destructor() {
for(let widgetIdx in this.widgets)
this.disconnectWidgetSignals(this.widgets[widgetIdx]);
for(let timeoutIdx in this.timeouts)
GLib.Source.remove(this.timeouts[timeoutIdx]);
}
this._addToBox(lastWidget);
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);
}
_createText(text, style) {
this.style = style;
if (text === '') {
this.widget = null;
connectWidgetSignals(widget) {
this.widgets.push(widget);
let array = new Array();
this.signals.set(widget, array);
let id;
id = widget.connect('enter-event', this._onEnter.bind(this));
array.push(id);
id = widget.connect('leave-event', this._onLeave.bind(this));
array.push(id);
id = widget.connect('scroll-event', this._onScroll.bind(this));
array.push(id);
widget.set_reactive(true);
id = widget.connect('button-release-event', this._clicked.bind(this));
array.push(id);
}
disconnectWidgetSignals(widget) {
let array = this.signals.get(widget);
for(let idx in array)
widget.disconnect(array[idx]);
this.signals.set(widget, null);
}
_manageEventAction(action, signalName) {
if (action === 'open-popup')
this.menu.open(true);
else if (action === 'close-popup')
this.menu.close();
else if (action === 'toggle-popup')
this.menu.toggle();
else if (action == 'delete')
this.dbus.deleteItem(this, this.group);
else if (action === 'signal')
this.dbus.emitSignal(signalName, this.fullname);
return Clutter.EVENT_PROPAGATE;
}
_manageLeaveEvent() {
this._manageEventAction(this.onLeave);
}
_doClickCallback() {
let right = '';
let nbClicks = '';
if (this.button == 3)
right = 'Right';
if (this.nbClicks > 1)
nbClicks = 'Dbl';
const signalName = 'on' + right + nbClicks + 'Click';
let action = 'signal';
switch(signalName) {
case 'onClick': action = this.onClick; break;
case 'onDblClick': action = this.onDblClick; break;
case 'onRightClick': action = this.onRightClick; break;
case 'onRightDblClick': action = this.onRightDblClick; break;
}
this._manageEventAction(action, signalName);
this.nbClicks = 0;
this.button = -1;
return false;
}
_clicked(actor, event) {
if (event.get_button() == this.button) {
this.nbClicks++;
} else {
this.widget = new St.Button({ label: text });
this.widget.set_style(this.style);
}
this.button = event.get_button();
this.nbClicks = 1;
let sourceId = Mainloop.timeout_add(this.dbus.ClutterSettings['double-click-time'],
this._doClickCallback.bind(this));
this.timeouts.push(sourceId);
}
_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);
}
return Clutter.EVENT_PROPAGATE;
}
_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;
_onEnter(/*actor, event*/) {
return this._manageEventAction(this.onEnter, 'onEnter');
}
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;
_onLeave(/*actor, event*/) {
return this._manageEventAction(this.onLeave, 'onLeave');
}
if (this.widget) {
if (lastWidget)
this.box.insert_child_above(this.widget, lastWidget);
_onScroll(actor, event) {
let signalName = '';
const direction = event.get_scroll_direction ();
if (direction == Clutter.ScrollDirection.UP)
signalName = 'onScrollUp';
else if (direction == Clutter.ScrollDirection.DOWN)
signalName = 'onScrollDown';
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.signalManager = new SignalMgt(item, this.name, group, dbus, this.menu);
this.popup_signals = null;
this.popup_widgets = null;
if (item.hasOwnProperty('icon'))
{
if (typeof(item['icon']) === 'string')
this.icon = this._createIconOld(item);
else
this.box.insert_child_at_index(this.icon, 0);
this.icon = this._createIcon(item['icon']);
if (this.icon !== null) {
this.signalManager.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.signalManager.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);
}
removeFromBox() {
if (this.widget)
this.box.remove_child(this.widget);
if (this.icon)
this.box.remove_child(this.icon);
}
update(item) {
const prevWidget = this.widget;
const prevIcon = this.icon;
update(text, style, icon, iconStyle) {
let prevWidget = this.widget;
let prevIcon = this.icon;
if (item.hasOwnProperty('text'))
{
let text = '';
let style = '';
if (typeof(item['text']) === 'string') {
text = hashGet(item, 'text', '');
style = hashGet(item, 'style', '');
} else {
const textValues = item['text'];
text = hashGet(textValues, 'text', '');
style = hashGet(textValues, 'style', '');
}
if (text !== '') {
if (!this.widget) {
this._createText(text, style);
this.box.insert_child_above(this.widget, this.icon);
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.style = style;
this.widget.set_style(this.style);
this.widget.set_style(style);
}
}
if (item.hasOwnProperty('icon'))
{
let icon = '';
let style = '';
if (typeof(item['icon']) === 'string') {
icon = hashGet(item, 'icon', '');
style = hashGet(item, 'iconStyle', '');
} else {
const iconValues = item['icon'];
icon = hashGet(iconValues, 'path', '');
style = hashGet(iconValues, 'style', '');
}
if (icon !== '') {
this._createIcon(icon, iconStyle);
if (prevIcon)
this.box.insert_child_above(this.icon, prevIcon);
if (typeof(item['icon']) === 'string')
this.icon = this._createIconOld(item);
else
this.box.insert_child_before(this.icon, prevWidget);
this.icon = this._createIcon(item['icon']);
}
if (iconStyle !== '' && this.icon) {
this.iconStyle = style;
this.icon.set_style(this.iconStyle);
if (prevIcon) {
this.signalManager.disconnectWidgetSignals(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);
}
}
if (prevIcon && icon !== '')
this.box.remove_child(prevIcon);
if (item.hasOwnProperty('popup'))
{
const menuOpen = this.menu.isOpen;
if (this.menuItem) {
if (menuOpen)
this.menu.close();
for(let widgetIdx in this.popup_widgets)
this.signalManager.disconnectWidgetSignals(this.popup_widgets[widgetIdx]);
this.menu.removeAll();
//delete this.menuItem;
}
}
const popup = this._createPopup(item['popup']);
if (popup !== null && menuOpen)
this.menu.open(true);
}
this.signalManager.updateSignals(item);
}
openPopup() {
this.menu.open(true);
}
closePopup() {
this.menu.close();
}
togglePopup() {
this.menu.toggle();
}
destroy() {
this.menu.close();
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 = [];
this.popup_signals = new WeakMap();
this.popup_widgets = new Array();
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._createLabel(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);
this.popup_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, isLabel) {
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 {
let widget = null;
if (isLabel)
widget = new St.Label({ text: item['text'] });
else
widget = new St.Button({ label: item['text'] });
widget.set_style(style);
return widget;
}
}
_createText(item) {
return this.__createText(item, false);
}
_createLabel(item) {
return this.__createText(item, true);
}
_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
// loads a xml file into an in-memory string
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());
@@ -162,7 +553,7 @@ function loadInterfaceXml(filename) {
// will spit out a TypeError soon).
if (contents instanceof Uint8Array)
contents = imports.byteArray.toString(contents);
let res = `<node>${contents}</node>`;
const res = `<node>${contents}</node>`;
return res;
} else {
throw new Error(`Generic monitor: Could not load file: ${filename}`);
@@ -173,39 +564,41 @@ class GenericMonitorDBUS {
constructor() {
this.monitor_groups = {};
this.actor_clicked = {};
this.clutterSettings = clutter.Settings.get_default();
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');
emitSignal(name, value) {
this._dbusImpl.emit_signal(name, GLib.Variant.new('(s)',[value]));
}
if (!parameters.hasOwnProperty('items'))
throw new Error('No items defined');
_checkParameters(parameters) {
if (!parameters.hasOwnProperty('group')) {
log('No group defined');
return false;
}
if (!parameters.hasOwnProperty('items')) {
log('No items defined');
return false;
}
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');
const item = parameters['items'][itemIndex];
if (!item.hasOwnProperty('name')) {
log('No name defined for item');
return false;
}
}
return true;
}
_getItemFromGroup(group, name) {
for (let groupItemIndex in group) {
let groupItem = group[groupItemIndex];
const groupItem = group[groupItemIndex];
if (groupItem.name === name)
return groupItem;
}
@@ -213,33 +606,16 @@ class GenericMonitorDBUS {
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];
}
}
_getItemFromFullName(fullname) {
const splitName = fullname.split('@');
if (splitName.length !== 2) {
log(`Invalid name ${fullname}`);
return null;
}
if (!this.monitor_groups.hasOwnProperty(splitName[1]))
return null;
return this._getItemFromGroup(this.monitor_groups[splitName[1]], splitName[0]);
}
_removeFromArray(array, value) {
for(let i=0; i<array.length; i++) {
@@ -253,38 +629,12 @@ class GenericMonitorDBUS {
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)
notify(str) {
const parameters = JSON.parse(str);
if (!this._checkParameters(parameters))
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'];
const groupName = parameters['group'];
let group;
if (!this.monitor_groups.hasOwnProperty(groupName)) {
group = [];
@@ -294,59 +644,38 @@ class GenericMonitorDBUS {
}
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'];
const item = parameters['items'][itemIndex];
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);
let position = group.length - 1;
// Find real position
if (position != -1) {
const lastWidget = group[position].container;
const childrens = lastWidget.get_parent().get_children();
for(;position < childrens.length; position++)
{
if (childrens[position] == lastWidget) {
position++;
break;
}
}
if (position >= childrens.length)
position = -1;
}
monitorWidget = new MonitorWidget(item, groupName, this, position);
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);
monitorWidget.update(item);
}
}
}
deleteItem(item, groupName) {
let group = this.monitor_groups[groupName];
item.removeFromBox();
group = this._removeFromArray(group, item);
item.destroy();
if (group.length === 0)
delete this.monitor_groups[groupName];
else
@@ -354,18 +683,22 @@ class GenericMonitorDBUS {
}
deleteItems(str) {
let parameters = JSON.parse(str);
const parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('items'))
throw new Error('No items defined');
if (!parameters.hasOwnProperty('items')) {
log('No items defined');
return false;
}
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];
const splitName = itemName.split('@');
if (splitName.length !== 2) {
log(`Invalid name ${itemName}`);
return false;
}
itemName = splitName[0];
let groupName = splitName[1];
if (!this.monitor_groups.hasOwnProperty(groupName))
continue;
let group = this.monitor_groups[groupName];
@@ -377,33 +710,70 @@ class GenericMonitorDBUS {
}
deleteGroups(str) {
let parameters = JSON.parse(str);
const parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('groups'))
throw new Error('No groups defined');
if (!parameters.hasOwnProperty('groups')) {
log('No groups defined');
return false;
}
let groupsToDelete = [];
for (let groupIndex in parameters['groups']) {
let groupName = parameters['groups'][groupIndex];
const groupName = parameters['groups'][groupIndex];
if (!this.monitor_groups.hasOwnProperty(groupName))
continue;
let group = this.monitor_groups[groupName];
const group = this.monitor_groups[groupName];
for (let itemIndex in group)
group[itemIndex].removeFromBox();
group[itemIndex].destroy();
groupsToDelete.push(groupName);
}
for (let groupDeleteIndex in groupsToDelete) {
let groupName = groupsToDelete[groupDeleteIndex];
const groupName = groupsToDelete[groupDeleteIndex];
delete this.monitor_groups[groupName];
}
}
_popupFunction(str) {
const parameters = JSON.parse(str);
if (!parameters.hasOwnProperty('item')) {
log('No item defined');
return false;
}
const monitorWidget = this._getItemFromFullName(parameters['item']);
if (monitorWidget !== null)
return monitorWidget;
else
log(`Item ${str} not found`);
return null;
}
openPopup(str) {
const monitorWidget = this._popupFunction(str)
if (monitorWidget !== null)
monitorWidget.openPopup();
}
closePopup(str) {
const monitorWidget = this._popupFunction(str)
if (monitorWidget !== null)
monitorWidget.closePopup();
}
togglePopup(str) {
const monitorWidget = this._popupFunction(str)
if (monitorWidget !== null)
monitorWidget.togglePopup();
}
destructor() {
this._dbusImpl.emit_signal('onDeactivate', null);
for (let groupIndex in this.monitor_groups) {
let group = this.monitor_groups[groupIndex];
const group = this.monitor_groups[groupIndex];
for (let itemIndex in group)
group[itemIndex].removeFromBox();
group[itemIndex].destroy();
}
this.monitor_groups = {};
this._dbusImpl.unexport();
@@ -421,7 +791,7 @@ class Extension {
}
}
let extension = new Extension();
const extension = new Extension();
function init() {
}

View File

@@ -2,10 +2,12 @@
"uuid": "generic-monitor@gnome-shell-extensions",
"name": "Generic Monitor",
"description": "Display text & icon on systray using DBUS",
"version": "2",
"version": "6",
"shell-version": [
"3.36",
"3.34"
"41",
"40",
"3.38",
"3.36"
],
"url": "http://indefero.soutade.fr/p/genericmonitor"
}