Update of /cvsroot/freevo/kaa/base/src/notifier
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3249/notifier
Modified Files:
__init__.py callback.py signals.py
Removed Files:
wrapper.py
Log Message:
Refactored (ok, rewrote :)) Callback/Timer/OneShotTimer/SocketDispatcher
and weakref variants thereof, added shutdown and idle handlers as signals
and provided kaa.signals dict to connect to them. Removed deprecated code
for the above. Deprecated Function class and folded that functionality
into Callback class via set_ignore_caller_args() method. Also added
set_user_args_first() method.
Index: signals.py
===================================================================
RCS file: /cvsroot/freevo/kaa/base/src/notifier/signals.py,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -d -r1.3 -r1.4
*** signals.py 12 Jul 2005 14:06:57 -0000 1.3
--- signals.py 13 Jul 2005 17:31:37 -0000 1.4
***************
*** 37,41 ****
import weakref, types
! class WeakRefMethod:
def __init__(self, method, destroy_callback = None):
# FIXME: need to handle weakref finalize callback
--- 37,41 ----
import weakref, types
! class WeakRefMethod(object):
def __init__(self, method, destroy_callback = None):
# FIXME: need to handle weakref finalize callback
***************
*** 58,69 ****
! class Signal:
! def __init__(self):
self.callbacks = []
self._items = {}
!
! def __del__(self):
! pass
! # print "Signal deleting", self.callbacks
def __getitem__(self, name):
--- 58,71 ----
! class Signal(object):
!
! # Parameters for changed callback
! SIGNAL_CONNECTED = 1
! SIGNAL_DISCONNECTED = 2
!
! def __init__(self, changed_cb = None):
self.callbacks = []
self._items = {}
! self._changed_cb = changed_cb
def __getitem__(self, name):
***************
*** 81,84 ****
--- 83,88 ----
pos = len(self.callbacks)
self.callbacks.insert(pos, (self._ref(callback),
self._ref(data), once) )
+ if self._changed_cb:
+ self._changed_cb(self, Signal.SIGNAL_CONNECTED, pos)
return self
***************
*** 91,98 ****
for (cb_callback, cb_data, cb_once) in self.callbacks:
if self._unref(cb_callback) == callback and self._unref(cb_data)
== data:
! self.callbacks.remove( (cb_callback, cb_data, cb_once) )
found = True
! if not found:
! print "*** DISCONNECT FAILED", callback, data, once
def disconnect_all(self):
--- 95,105 ----
for (cb_callback, cb_data, cb_once) in self.callbacks:
if self._unref(cb_callback) == callback and self._unref(cb_data)
== data:
! pos = self.callbacks.index((cb_callback, cb_data, cb_once))
! self.callbacks.pop(pos)
! if self._changed_cb:
! self._changed_cb(self, Signal.SIGNAL_DISCONNECTED, pos)
found = True
!
! return found
def disconnect_all(self):
***************
*** 146,151 ****
# Make weakref for methods
return WeakRefMethod(data, self._weakref_destroyed)
- elif type(data) == types.InstanceType:
- return weakref.ref(data)
elif type(data) in (types.ListType, types.TupleType):
refed_data = []
--- 153,156 ----
***************
*** 155,158 ****
--- 160,168 ----
refed_data = tuple(refed_data)
return refed_data
+ elif not callable(data):
+ try:
+ return weakref.ref(data)
+ except TypeError:
+ pass
return data
Index: __init__.py
===================================================================
RCS file: /cvsroot/freevo/kaa/base/src/notifier/__init__.py,v
retrieving revision 1.5
retrieving revision 1.6
diff -C2 -d -r1.5 -r1.6
*** __init__.py 12 Jul 2005 15:34:14 -0000 1.5
--- __init__.py 13 Jul 2005 17:31:37 -0000 1.6
***************
*** 35,41 ****
# kaa.notifier imports
- import wrapper
- from wrapper import Timer, OneShotTimer, Socket, Dispatcher, Shutdown
- from wrapper import IO_READ, IO_WRITE, IO_EXCEPT
from posixsignals import *
from posixsignals import register as signal
--- 35,38 ----
***************
*** 44,48 ****
from popen import killall as kill_processes
from thread import Thread, call_from_main
! from callback import Callback, Function, CallbackObject
# get logging object
--- 41,46 ----
from popen import killall as kill_processes
from thread import Thread, call_from_main
! from callback import Callback, WeakCallback, Timer, WeakTimer, OneShotTimer, \
! SocketDispatcher, WeakSocketDispatcher
# get logging object
***************
*** 53,56 ****
--- 51,68 ----
+ def _idle_signal_changed(signal, flag, pos):
+ if flag == Signal.SIGNAL_CONNECTED and signal.count() == 1:
+ notifier.addDispatcher(signal.emit)
+ elif flag == Signal.SIGNAL_DISCONNETED and signal.count() == 0:
+ notifier.removeDispatcher(signal.emit)
+
+
+ signals = {
+ "shutdown": Signal(),
+ "idle": Signal(changed_cb = _idle_signal_changed)
+ }
+
+
+
def select_notifier(type):
"""
***************
*** 71,74 ****
--- 83,87 ----
+
def shutdown():
"""
***************
*** 78,86 ****
# notifier loop still running, send system exit
log.info('Stop notifier loop')
! sys.exit(0)
kill_processes()
! while wrapper.shutdown_callbacks:
! # call all shutdown functions
! wrapper.shutdown_callbacks.pop()()
--- 91,98 ----
# notifier loop still running, send system exit
log.info('Stop notifier loop')
! raise SystemExit
!
kill_processes()
! signals["shutdown"].emit()
***************
*** 134,154 ****
- # **** functions while freevo is ported to kaa.notifier ****
- # WARNING: the following functions will be deleted in the future
-
- def addShutdown(function):
- Shutdown(function).register()
-
- def addTimer(interval, function, *args, **kwargs):
- t = Timer(function, *args, **kwargs)
- t.start(interval)
- return t.id
-
- def timer(interval, function, *args, **kwargs):
- t = Timer(function, *args, **kwargs)
- t.remove = t.stop
- t.start(interval)
- return t
-
try:
import notifier
--- 146,149 ----
***************
*** 156,162 ****
import nf_generic as notifier
! addSocket = notifier.addSocket
! addDispatcher = notifier.addDispatcher
! removeTimer = notifier.removeTimer
! removeSocket = notifier.removeSocket
! removeDispatcher = notifier.removeDispatcher
--- 151,153 ----
import nf_generic as notifier
!
--- wrapper.py DELETED ---
Index: callback.py
===================================================================
RCS file: /cvsroot/freevo/kaa/base/src/notifier/callback.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** callback.py 7 Jul 2005 13:40:44 -0000 1.1
--- callback.py 13 Jul 2005 17:31:37 -0000 1.2
***************
*** 30,41 ****
#
-----------------------------------------------------------------------------
! __all__ = [ 'Callback', 'Function', 'CallbackObject' ]
try:
# try to import pyNotifier
import notifier
except ImportError:
# use a copy of nf_generic
import nf_generic as notifier
class Callback(object):
--- 30,73 ----
#
-----------------------------------------------------------------------------
! __all__ = [ 'Callback', 'WeakCallback', 'Timer', 'WeakTimer', 'OneShotTimer',
! 'SocketDispatcher', 'WeakSocketDispatcher' ]
!
! import weakref
try:
# try to import pyNotifier
import notifier
+ # init pyNotifier with the generic notifier
+ notifier.init(notifier.GENERIC)
+ use_pynotifier = True
+
except ImportError:
# use a copy of nf_generic
import nf_generic as notifier
+ use_pynotifier = False
+
+ IO_READ = notifier.IO_READ
+ IO_WRITE = notifier.IO_WRITE
+ IO_EXCEPT = notifier.IO_EXCEPT
+
+ def select_notifier(type):
+ """
+ Select a new notifier.
+ """
+ if not use_pynotifier:
+ raise AttributeError('pyNotifier not installed')
+ if type == notifier.GENERIC:
+ raise AttributeError('generic notifier already running')
+ notifier.init(type)
+
+ global IO_READ
+ global IO_WRITE
+ global IO_EXCEPT
+
+ IO_READ = notifier.IO_READ
+ IO_WRITE = notifier.IO_WRITE
+ IO_EXCEPT = notifier.IO_EXCEPT
+
+
class Callback(object):
***************
*** 45,67 ****
and after that the args and kwargs defined in the init function.
"""
! def __init__(self, function, *args, **kwargs):
! self.function = function
! self.args = args
! self.kwargs = kwargs
! def __call__(self, *args):
! """
! Call the callback function.
! """
! return self.function(*(list(args) + list(self.args)), **self.kwargs)
! class Function(Callback):
! """
! Wrapper for functions calls with arguments inside the notifier. The
! function passed to this objects get the only args and kwargs defined in
! the init function, parameter passed to the object on call are dropped.
! """
def __call__(self, *args, **kwargs):
--- 77,100 ----
and after that the args and kwargs defined in the init function.
"""
! def __init__(self, callback, *args, **kwargs):
! assert(callable(callback))
! self._callback = callback
! self._args = args
! self._kwargs = kwargs
! self._ignore_caller_args = False
! self._user_args_first = False
! def set_ignore_caller_args(self, flag = True):
! self._ignore_caller_args = flag
! def set_user_args_first(self, flag = True):
! self._user_args_first = flag
!
!
! def _get_callback(self):
! return self._callback
!
def __call__(self, *args, **kwargs):
***************
*** 69,95 ****
Call the callback function.
"""
! return self.function(*self.args, **self.kwargs)
- class CallbackObject(Callback):
- """
- Object to wrap notifier function calls with a remove function to remove
- the timer / socket later. Do not create an object like this outside the
- kaa.notifier source.
- """
! def register(self, type, *args):
! """
! Register the callback. Do not use this function directly.
! """
! self.type = type
! self.id = getattr(notifier, 'add' + type)(*(list(args) + [self]))
- def remove(self):
- """
- Remove the callback from the notifier.
- """
- if not hasattr(self, 'id'):
- raise AttributeError('Callback not registered')
- getattr(notifier, 'remove' + self.type)(self.id)
--- 102,249 ----
Call the callback function.
"""
! cb = self._get_callback()
! if not cb:
! # Is it wise to fail so gracefully here?
! return
+ if self._ignore_caller_args:
+ cb_args, cb_kwargs = self._args, self._kwargs
+ else:
+ if self._user_args_first:
+ cb_args, cb_kwargs = self._args + args, kwargs
+ cb_kwargs.update(self._kwargs)
+ else:
+ cb_args, cb_kwargs = args + self._args, self._kwargs
+ cb_kwargs.update(kwargs)
+
+ return cb(*cb_args, **cb_kwargs)
!
! class NotifierCallback(Callback):
!
! def __init__(self, callback, *args, **kwargs):
! super(NotifierCallback, self).__init__(callback, *args, **kwargs)
! self._id = None
!
!
! def active(self):
! return self._id != None
!
!
! def unregister(self):
! # Unregister callback with notifier. Must be implemented by
subclasses.
! self._id = None
!
!
! def __call__(self, *args, **kwargs):
! if not self._get_callback():
! if self.active():
! self.unregister()
! return False
!
! ret = super(NotifierCallback, self).__call__(*args, **kwargs)
! # If Notifier callbacks return False, they get unregistered.
! if ret == False:
! self.unregister()
! return False
! return True
!
!
!
! class Timer(NotifierCallback):
!
! def start(self, interval):
! if self.active():
! self.unregister()
! self._id = notifier.addTimer(interval, self)
!
!
! def stop(self):
! self.unregister()
!
!
! def unregister(self):
! if self.active():
! notifier.removeTimer(self._id)
! self._id = None
!
!
!
! class OneShotTimer(Timer):
!
! def __call__(self, *args, **kwargs):
! self.unregister()
! super(OneShotTimer, self).__call__(*args, **kwargs)
! return False
!
!
!
! class SocketDispatcher(NotifierCallback):
!
! def __init__(self, callback, *args, **kwargs):
! super(SocketDispatcher, self).__init__(callback, *args, **kwargs)
! self.set_ignore_caller_args()
!
!
! def register(self, fd, condition = None):
! if self.active():
! return
!
! if condition == None:
! self._id = notifier.addSocket(fd, self)
! else:
! self._id = notifier.addSocket(fd, self, condition)
!
!
! def unregister(self):
! if self.active():
! notifier.removeSocket(self._id)
! self._id = None
!
!
!
! class WeakCallback(Callback):
!
! def __init__(self, callback, *args, **kwargs):
! super(WeakCallback, self).__init__(callback, *args, **kwargs)
! if hasattr(callback, "im_self"):
! # For methods
! self._instance = weakref.ref(callback.im_self,
self._weakref_destroyed)
! self._callback = callback.im_func.func_name
! else:
! # For functions
! self._instance = None
! self._callback = weakref.ref(callback, self._weakref_destroyed)
!
! # TODO: make weak refs of args/kwargs too.
!
!
! def _get_callback(self):
! if self._instance:
! if self._instance():
! return getattr(self._instance(), self._callback)
! else:
! return self._callback()
!
!
! def _weakref_destroyed(self, object):
! pass
!
!
!
! class WeakNotifierCallback(WeakCallback, NotifierCallback):
!
! def _weakref_destroyed(self, object):
! self.unregister()
!
!
! class WeakTimer(WeakNotifierCallback, Timer):
! pass
!
!
! class WeakSocketDispatcher(WeakNotifierCallback, SocketDispatcher):
! pass
!
-------------------------------------------------------
This SF.Net email is sponsored by the 'Do More With Dual!' webinar happening
July 14 at 8am PDT/11am EDT. We invite you to explore the latest in dual
core and dual graphics technology at this free one hour event hosted by HP,
AMD, and NVIDIA. To register visit http://www.hp.com/go/dualwebinar
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog