/usr/lib/exaile/xl/event.py is in exaile 3.4.0.2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | # Copyright (C) 2008-2010 Adam Olsen
#
# 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 2, 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
# The developers of the Exaile media player hereby grant permission
# for non-GPL compatible GStreamer and Exaile plugins to be used and
# distributed together with GStreamer and Exaile. This permission is
# above and beyond the permissions granted by the GPL license by which
# Exaile is covered. If you modify this code, you may extend this
# exception to your version of the code, but you are not obligated to
# do so. If you do not wish to do so, delete this exception statement
# from your version.
"""
Provides a signals-like system for sending and listening for 'events'
Events are kind of like signals, except they may be listened for on a
global scale, rather than connected on a per-object basis like signals
are. This means that ANY object can emit ANY event, and these events may
be listened for by ANY object.
Events should be emitted AFTER the given event has taken place. Often the
most appropriate spot is immediately before a return statement.
"""
from __future__ import with_statement
from inspect import ismethod
import logging
from new import instancemethod
import re
import threading
import time
import traceback
import weakref
import glib
from xl import common
from xl.nls import gettext as _
# define this here so the interperter doesn't complain
EVENT_MANAGER = None
logger = logging.getLogger(__name__)
class Nothing(object):
pass
_NONE = Nothing() # used by event for a safe None replacement
def log_event(type, obj, data):
"""
Sends an event.
:param type: the *type* or *name* of the event.
:type type: string
:param obj: the object sending the event.
:type obj: object
:param data: some data about the event, None if not required
:type data: object
"""
global EVENT_MANAGER
e = Event(type, obj, data, time.time())
EVENT_MANAGER.emit(e)
def add_callback(function, type=None, obj=None, *args, **kwargs):
"""
Adds a callback to an event
You should ALWAYS specify one of the two options on what to listen
for. While not forbidden to listen to all events, doing so will
cause your callback to be called very frequently, and possibly may
cause slowness within the player itself.
:param function: the function to call when the event happens
:type function: callable
:param type: the *type* or *name* of the event to listen for, eg
`tracks_added`, `cover_changed`. Defaults to any event if
not specified.
:type type: string
:param obj: the object to listen to events from, e.g. `exaile.collection`
or `xl.covers.MANAGER`. Defaults to any object if not
specified.
:type obj: object
Any additional parameters will be passed to the callback.
:returns: a convenience function that you can call to remove the callback.
"""
global EVENT_MANAGER
return EVENT_MANAGER.add_callback(function, type, obj, args, kwargs)
def remove_callback(function, type=None, obj=None):
"""
Removes a callback
The parameters passed should match those that were passed when adding
the callback
"""
global EVENT_MANAGER
EVENT_MANAGER.remove_callback(function, type, obj)
class Event(object):
"""
Represents an Event
"""
def __init__(self, type, obj, data, time):
"""
type: the 'type' or 'name' for this Event [string]
obj: the object emitting the Event [object]
data: some piece of data relevant to the Event [object]
"""
self.type = type
self.object = obj
self.data = data
self.time = time
class Callback(object):
"""
Represents a callback
"""
def __init__(self, function, time, args, kwargs):
"""
@param function: the function to call
@param time: the time this callback was added
"""
self.valid = True
self.wfunction = _getWeakRef(function, self.vanished)
self.time = time
self.args = args
self.kwargs = kwargs
def vanished(self, ref):
self.valid = False
class _WeakMethod:
"""Represent a weak bound method, i.e. a method doesn't keep alive the
object that it is bound to. It uses WeakRef which, used on its own,
produces weak methods that are dead on creation, not very useful.
Typically, you will use the getRef() function instead of using
this class directly. """
def __init__(self, method, notifyDead = None):
"""
The method must be bound. notifyDead will be called when
object that method is bound to dies.
"""
assert ismethod(method)
if method.im_self is None:
raise ValueError, "We need a bound method!"
if notifyDead is None:
self.objRef = weakref.ref(method.im_self)
else:
self.objRef = weakref.ref(method.im_self, notifyDead)
self.fun = method.im_func
self.cls = method.im_class
def __call__(self):
if self.objRef() is None:
return None
else:
return instancemethod(self.fun, self.objRef(), self.cls)
def __eq__(self, method2):
if not isinstance(method2, _WeakMethod):
return False
return self.fun is method2.fun \
and self.objRef() is method2.objRef() \
and self.objRef() is not None
def __hash__(self):
return hash(self.fun)
def __repr__(self):
dead = ''
if self.objRef() is None:
dead = '; DEAD'
obj = '<%s at %s%s>' % (self.__class__, id(self), dead)
return obj
def refs(self, weakRef):
"""Return true if we are storing same object referred to by weakRef."""
return self.objRef == weakRef
def _getWeakRef(obj, notifyDead=None):
"""
Get a weak reference to obj. If obj is a bound method, a _WeakMethod
object, that behaves like a WeakRef, is returned, if it is
anything else a WeakRef is returned. If obj is an unbound method,
a ValueError will be raised.
"""
if ismethod(obj):
createRef = _WeakMethod
else:
createRef = weakref.ref
if notifyDead is None:
return createRef(obj)
else:
return createRef(obj, notifyDead)
class EventManager(object):
"""
Manages all Events
"""
def __init__(self, use_logger=False, logger_filter=None):
self.callbacks = {}
self.use_logger = use_logger
self.logger_filter = logger_filter
# RLock is needed so that event callbacks can themselves send
# synchronous events and add or remove callbacks
self.lock = threading.RLock()
def emit(self, event):
"""
Emits an Event, calling any registered callbacks.
event: the Event to emit [Event]
"""
with self.lock:
callbacks = set()
for tcall in [_NONE, event.type]:
for ocall in [_NONE, event.object]:
try:
callbacks.update(self.callbacks[tcall][ocall])
except KeyError:
pass
# now call them
for cb in callbacks:
try:
if not cb.valid:
try:
self.callbacks[event.type][event.object].remove(cb)
except (KeyError, ValueError):
pass
elif event.time >= cb.time:
if self.use_logger and (not self.logger_filter or \
re.search(self.logger_filter, event.type)):
logger.debug("Attempting to call "
"%(function)s in response "
"to %(event)s." % {
'function': cb.wfunction(),
'event': event.type})
cb.wfunction().__call__(event.type, event.object,
event.data, *cb.args, **cb.kwargs)
except Exception:
# something went wrong inside the function we're calling
common.log_exception(logger,
message="Event callback exception caught!")
if self.use_logger:
if not self.logger_filter or re.search(self.logger_filter,
event.type):
logger.debug("Sent '%(type)s' event from "
"'%(object)s' with data '%(data)s'." %
{'type' : event.type, 'object' : repr(event.object),
'data' : repr(event.data)})
def emit_async(self, event):
"""
Same as emit(), but does not block.
"""
glib.idle_add(self.emit, event)
def add_callback(self, function, type, obj, args, kwargs):
"""
Registers a callback.
You should always specify at least one of type or object.
@param function: The function to call [function]
@param type: The 'type' or 'name' of event to listen for. Defaults
to any. [string]
@param obj: The object to listen to events from. Defaults
to any. [string]
Returns a convenience function that you can call to
remove the callback.
"""
with self.lock:
# add the specified categories if needed.
if not self.callbacks.has_key(type):
self.callbacks[type] = weakref.WeakKeyDictionary()
if obj is None:
obj = _NONE
try:
callbacks = self.callbacks[type][obj]
except KeyError:
callbacks = self.callbacks[type][obj] = []
# add the actual callback
callbacks.append(Callback(function, time.time(), args, kwargs))
if self.use_logger:
if not self.logger_filter or re.search(self.logger_filter, type):
logger.debug("Added callback %s for [%s, %s]" %
(function, type, obj))
return lambda: self.remove_callback(function, type, obj)
def remove_callback(self, function, type=None, obj=None):
"""
Unsets a callback
The parameters must match those given when the callback was
registered. (minus any additional args)
"""
if obj is None:
obj = _NONE
remove = []
with self.lock:
try:
callbacks = self.callbacks[type][obj]
for cb in callbacks:
if cb.wfunction() == function:
remove.append(cb)
except KeyError:
return
except TypeError:
return
for cb in remove:
callbacks.remove(cb)
if self.use_logger:
if not self.logger_filter or re.search(self.logger_filter, type):
logger.debug("Removed callback %s for [%s, %s]" %
(function, type, obj))
EVENT_MANAGER = EventManager()
# vim: et sts=4 sw=4
|