summaryrefslogtreecommitdiffstats
path: root/python
diff options
context:
space:
mode:
Diffstat (limited to 'python')
-rw-r--r--python/.cvsignore10
-rw-r--r--python/Makefile.am56
-rw-r--r--python/__init__.py5
-rw-r--r--python/_dbus.py308
-rw-r--r--python/_util.py13
-rw-r--r--python/dbus.pth1
-rw-r--r--python/dbus_bindings.pxd.in8
-rw-r--r--python/dbus_bindings.pyx1849
-rw-r--r--python/dbus_glib_bindings.pyx17
-rw-r--r--python/dbus_h_wrapper.h3
-rw-r--r--python/decorators.py83
-rw-r--r--python/examples/.cvsignore2
-rw-r--r--python/examples/Makefile.am13
-rw-r--r--python/examples/example-client.py22
-rw-r--r--python/examples/example-service.py30
-rw-r--r--python/examples/example-signal-emitter.py29
-rw-r--r--python/examples/example-signal-recipient.py54
-rw-r--r--python/examples/gconf-proxy-client.py13
-rw-r--r--python/examples/gconf-proxy-service.py43
-rw-r--r--python/examples/gconf-proxy-service2.py39
-rw-r--r--python/examples/list-system-services.py22
-rw-r--r--python/exceptions.py29
-rw-r--r--python/extract.py234
-rw-r--r--python/glib.py17
-rw-r--r--python/introspect_parser.py51
-rw-r--r--python/matchrules.py232
-rw-r--r--python/proxies.py222
-rw-r--r--python/service.py370
-rw-r--r--python/types.py19
29 files changed, 0 insertions, 3794 deletions
diff --git a/python/.cvsignore b/python/.cvsignore
deleted file mode 100644
index cce7eeaf..00000000
--- a/python/.cvsignore
+++ /dev/null
@@ -1,10 +0,0 @@
-.deps
-Makefile.in
-Makefile
-dbus_bindings.pxd
-*.lo
-*.la
-dbus_bindings.c
-dbus_glib_bindings.c
-*.pyc
-.libs
diff --git a/python/Makefile.am b/python/Makefile.am
deleted file mode 100644
index ea261cb1..00000000
--- a/python/Makefile.am
+++ /dev/null
@@ -1,56 +0,0 @@
-SUBDIRS=examples
-
-INCLUDES=-I$(srcdir)/$(top_builddir) -I$(srcdir)/$(top_builddir)/dbus $(DBUS_CLIENT_CFLAGS) $(PYTHON_INCLUDES) -DDBUS_COMPILATION=1
-
-dbusmoduledir = $(pyexecdir)
-dbusmodule_PYTHON = dbus.pth
-
-dbusdir = $(pyexecdir)/dbus
-dbus_PYTHON = \
- __init__.py \
- _dbus.py \
- decorators.py \
- exceptions.py \
- service.py \
- proxies.py \
- _util.py \
- types.py \
- matchrules.py \
- glib.py \
- introspect_parser.py
-
-dbusbindingsdir = $(pyexecdir)/dbus
-dbusbindings_LTLIBRARIES = dbus_bindings.la dbus_glib_bindings.la
-
-dbus_bindings_la_LDFLAGS = -module -avoid-version -fPIC -export-symbols-regex initdbus_bindings
-dbus_bindings_la_LIBADD = $(top_builddir)/dbus/libdbus-1.la
-nodist_dbus_bindings_la_SOURCES = dbus_bindings.c
-
-dbus_glib_bindings_la_LDFLAGS = -module -avoid-version -fPIC -export-symbols-regex initdbus_glib_bindings
-dbus_glib_bindings_la_LIBADD = $(top_builddir)/dbus/libdbus-1.la $(top_builddir)/glib/libdbus-glib-1.la
-dbus_glib_bindings_la_CFLAGS = $(DBUS_GLIB_CFLAGS) $(DBUS_GLIB_TOOL_CFLAGS)
-nodist_dbus_glib_bindings_la_SOURCES = dbus_glib_bindings.c
-
-
-EXTRA_DIST = \
- dbus_h_wrapper.h \
- dbus_bindings.pyx \
- dbus_glib_bindings.pyx \
- dbus_bindings.pxd.in \
- extract.py
-
-CLEANFILES = \
- dbus_bindings.pxd \
- dbus_bindings.c \
- dbus_glib_bindings.c
-
-
-dbus_bindings.pxd: $(srcdir)/dbus_bindings.pxd.in $(srcdir)/extract.py
- -$(PYTHON) $(srcdir)/extract.py $(srcdir)/dbus_bindings.pxd.in -I$(srcdir)/$(top_builddir) -I$(srcdir) > $@.tmp && mv $@.tmp $@
-
-dbus_bindings.c: $(srcdir)/dbus_bindings.pyx dbus_bindings.pxd
- pyrexc $(srcdir)/dbus_bindings.pyx -I. -o ./dbus_bindings.c
-
-dbus_glib_bindings.c: $(srcdir)/dbus_glib_bindings.pyx dbus_bindings.pxd
- pyrexc $(srcdir)/dbus_glib_bindings.pyx -I. -o ./dbus_glib_bindings.c
-
diff --git a/python/__init__.py b/python/__init__.py
deleted file mode 100644
index 7d937831..00000000
--- a/python/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from _dbus import *
-from types import *
-
-version = (0, 51, 0)
-_dbus_main_loop_setup_function = None
diff --git a/python/_dbus.py b/python/_dbus.py
deleted file mode 100644
index 7e17d9f6..00000000
--- a/python/_dbus.py
+++ /dev/null
@@ -1,308 +0,0 @@
-
-"""Module for high-level communication over the FreeDesktop.org Bus (DBus)
-
-DBus allows you to share and access remote objects between processes
-running on the desktop, and also to access system services (such as
-the print spool).
-
-To use DBus, first get a Bus object, which provides a connection to one
-of a few standard dbus-daemon instances that might be running. From the
-Bus you can get a RemoteService. A service is provided by an application or
-process connected to the Bus, and represents a set of objects. Once you
-have a RemoteService you can get a RemoteObject that implements a specific interface
-(an interface is just a standard group of member functions). Then you can call
-those member functions directly.
-
-You can think of a complete method call as looking something like:
-
-Bus:SESSION -> Service:org.gnome.Evolution -> Object:/org/gnome/Evolution/Inbox -> Interface: org.gnome.Evolution.MailFolder -> Method: Forward('message1', 'seth@gnome.org')
-
-This communicates over the SESSION Bus to the org.gnome.Evolution process to call the
-Forward method of the /org/gnome/Evolution/Inbox object (which provides the
-org.gnome.Evolution.MailFolder interface) with two string arguments.
-
-For example, the dbus-daemon itself provides a service and some objects:
-
-# Get a connection to the desktop-wide SESSION bus
-bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
-
-# Get the service provided by the dbus-daemon named org.freedesktop.DBus
-dbus_service = bus.get_service('org.freedesktop.DBus')
-
-# Get a reference to the desktop bus' standard object, denoted
-# by the path /org/freedesktop/DBus. The object /org/freedesktop/DBus
-# implements the 'org.freedesktop.DBus' interface
-dbus_object = dbus_service.get_object('/org/freedesktop/DBus',
- 'org.freedesktop.DBus')
-
-# One of the member functions in the org.freedesktop.DBus interface
-# is ListServices(), which provides a list of all the other services
-# registered on this bus. Call it, and print the list.
-print(dbus_object.ListServices())
-"""
-
-import dbus
-import dbus_bindings
-import weakref
-
-from proxies import *
-from exceptions import *
-from matchrules import *
-
-class Bus(object):
- """A connection to a DBus daemon.
-
- One of three possible standard buses, the SESSION, SYSTEM,
- or STARTER bus
- """
- TYPE_SESSION = dbus_bindings.BUS_SESSION
- TYPE_SYSTEM = dbus_bindings.BUS_SYSTEM
- TYPE_STARTER = dbus_bindings.BUS_STARTER
-
- """bus_type=[Bus.TYPE_SESSION | Bus.TYPE_SYSTEM | Bus.TYPE_STARTER]
- """
-
- ProxyObjectClass = ProxyObject
-
- START_REPLY_SUCCESS = dbus_bindings.DBUS_START_REPLY_SUCCESS
- START_REPLY_ALREADY_RUNNING = dbus_bindings.DBUS_START_REPLY_ALREADY_RUNNING
-
- _shared_instances = weakref.WeakValueDictionary()
-
- def __new__(cls, bus_type=TYPE_SESSION, use_default_mainloop=True, private=False):
- if (not private and bus_type in cls._shared_instances):
- return cls._shared_instances[bus_type]
-
- # this is a bit odd, but we create instances of the subtypes
- # so we can return the shared instances if someone tries to
- # construct one of them (otherwise we'd eg try and return an
- # instance of Bus from __new__ in SessionBus). why are there
- # three ways to construct this class? we just don't know.
- if bus_type == cls.TYPE_SESSION:
- subclass = SessionBus
- elif bus_type == cls.TYPE_SYSTEM:
- subclass = SystemBus
- elif bus_type == cls.TYPE_STARTER:
- subclass = StarterBus
- else:
- raise ValueError('invalid bus_type %s' % bus_type)
-
- bus = object.__new__(subclass)
-
- bus._bus_type = bus_type
- bus._bus_names = weakref.WeakValueDictionary()
- bus._match_rule_tree = SignalMatchTree()
-
- # FIXME: if you get a starter and a system/session bus connection
- # in the same process, it's the same underlying connection that
- # is returned by bus_get, but we initialise it twice
- bus._connection = dbus_bindings.bus_get(bus_type, private)
- bus._connection.add_filter(bus._signal_func)
-
- if use_default_mainloop:
- func = getattr(dbus, "_dbus_mainloop_setup_function", None)
- if func:
- func(bus)
-
- if not private:
- cls._shared_instances[bus_type] = bus
-
- return bus
-
- def __init__(self, *args, **keywords):
- # do nothing here because this can get called multiple times on the
- # same object if __new__ returns a shared instance
- pass
-
- def close(self):
- self._connection.close()
-
- def get_connection(self):
- return self._connection
-
- def get_session(private=False):
- """Static method that returns the session bus"""
- return SessionBus(private=private)
-
- get_session = staticmethod(get_session)
-
- def get_system(private=False):
- """Static method that returns the system bus"""
- return SystemBus(private=private)
-
- get_system = staticmethod(get_system)
-
-
- def get_starter(private=False):
- """Static method that returns the starter bus"""
- return StarterBus(private=private)
-
- get_starter = staticmethod(get_starter)
-
-
- def get_object(self, named_service, object_path):
- """Get a proxy object to call over the bus"""
- return self.ProxyObjectClass(self, named_service, object_path)
-
- def _create_args_dict(self, keywords):
- args_dict = None
- for (key, value) in keywords.iteritems():
- if key.startswith('arg'):
- try:
- snum = key[3:]
- num = int(snum)
-
- if not args_dict:
- args_dict = {}
-
- args_dict[num] = value
- except ValueError:
- raise TypeError("Invalid arg index %s"%snum)
- elif key in ("sender_keyword", "path_keyword"):
- pass
- else:
- raise TypeError("Unknown keyword %s"%(key))
-
- return args_dict
-
- def add_signal_receiver(self, handler_function,
- signal_name=None,
- dbus_interface=None,
- named_service=None,
- path=None,
- **keywords):
-
- args_dict = self._create_args_dict(keywords)
-
- if (named_service and named_service[0] != ':'):
- bus_object = self.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
- named_service = bus_object.GetNameOwner(named_service, dbus_interface='org.freedesktop.DBus')
-
- match_rule = SignalMatchRule(signal_name, dbus_interface, named_service, path)
-
- for kw in ("sender_keyword", "path_keyword"):
- if kw in keywords:
- setattr(match_rule, kw, keywords[kw])
- else:
- setattr(match_rule, kw, None)
-
- if args_dict:
- match_rule.add_args_match(args_dict)
-
- match_rule.add_handler(handler_function)
-
- self._match_rule_tree.add(match_rule)
-
- dbus_bindings.bus_add_match(self._connection, repr(match_rule))
-
- def remove_signal_receiver(self, handler_function,
- signal_name=None,
- dbus_interface=None,
- named_service=None,
- path=None,
- **keywords):
-
- args_dict = self._create_args_dict(keywords)
-
- if (named_service and named_service[0] != ':'):
- bus_object = self.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
- named_service = bus_object.GetNameOwner(named_service, dbus_interface='org.freedesktop.DBus')
-
- match_rule = SignalMatchRule(signal_name, dbus_interface, named_service, path)
-
- if (args_dict):
- match_rule.add_args_match(args_dict)
-
- if (handler_function):
- match_rule.add_handler(handler_function)
-
- self._match_rule_tree.remove(match_rule)
-
- #TODO we leak match rules in the lower level bindings. We need to ref count them
-
- def get_unix_user(self, named_service):
- """Get the unix user for the given named_service on this Bus"""
- return dbus_bindings.bus_get_unix_user(self._connection, named_service)
-
- def _signal_func(self, connection, message):
- if (message.get_type() != dbus_bindings.MESSAGE_TYPE_SIGNAL):
- return dbus_bindings.HANDLER_RESULT_NOT_YET_HANDLED
-
- dbus_interface = message.get_interface()
- named_service = message.get_sender()
- path = message.get_path()
- signal_name = message.get_member()
-
- match_rule = SignalMatchRule(signal_name, dbus_interface, named_service, path)
-
- self._match_rule_tree.exec_matches(match_rule, message)
-
- def start_service_by_name(self, named_service):
- return dbus_bindings.bus_start_service_by_name(self._connection, named_service)
-
- def __repr__(self):
- if self._bus_type == self.TYPE_SESSION:
- name = 'SESSION'
- elif self._bus_type == self.TYPE_SYSTEM:
- name = 'SYSTEM'
- elif self._bus_type == self.TYPE_STARTER:
- name = 'STARTER'
- else:
- assert False, 'Unable to represent unknown bus type.'
-
- return '<dbus.Bus on %s at %#x>' % (name, id(self))
- __str__ = __repr__
-
-class SystemBus(Bus):
- """The system-wide message bus
- """
- def __new__(cls, use_default_mainloop=True, private=False):
- return Bus.__new__(cls, Bus.TYPE_SYSTEM, use_default_mainloop, private)
-
-class SessionBus(Bus):
- """The session (current login) message bus
- """
- def __new__(cls, use_default_mainloop=True, private=False):
- return Bus.__new__(cls, Bus.TYPE_SESSION, use_default_mainloop, private)
-
-class StarterBus(Bus):
- """The bus that activated this process (if
- this process was launched by DBus activation)
- """
- def __new__(cls, use_default_mainloop=True, private=False):
- return Bus.__new__(cls, Bus.TYPE_STARTER, use_default_mainloop, private)
-
-class Interface:
- """An interface into a remote object
-
- An Interface can be used to wrap ProxyObjects
- so that calls can be routed to their correct
- dbus interface
- """
-
- def __init__(self, object, dbus_interface):
- self._obj = object
- self._dbus_interface = dbus_interface
-
- def connect_to_signal(self, signal_name, handler_function, dbus_interface = None, **keywords):
- if not dbus_interface:
- dbus_interface = self._dbus_interface
-
- self._obj.connect_to_signal(signal_name, handler_function, dbus_interface, **keywords)
-
- def __getattr__(self, member, **keywords):
- if (keywords.has_key('dbus_interface')):
- _dbus_interface = keywords['dbus_interface']
- else:
- _dbus_interface = self._dbus_interface
-
- if member == '__call__':
- return object.__call__
- else:
- ret = self._obj.__getattr__(member, dbus_interface=_dbus_interface)
- return ret
-
- def __repr__(self):
- return '<Interface %r implementing %r at %#x>'%(
- self._obj, self._dbus_interface, id(self))
- __str__ = __repr__
diff --git a/python/_util.py b/python/_util.py
deleted file mode 100644
index c254178e..00000000
--- a/python/_util.py
+++ /dev/null
@@ -1,13 +0,0 @@
-import re
-from exceptions import ValidationException
-
-def _validate_interface_or_name(value):
- elements = value.split('.')
- if len(elements) <= 1:
- raise ValidationException("%s must contain at least two elements seperated by a period ('.')"%(value))
-
- validate = re.compile('[A-Za-z][\w_]*')
- for element in elements:
- if not validate.match(element):
- raise ValidationException("Element %s of %s has invalid characters"%(element ,value))
-
diff --git a/python/dbus.pth b/python/dbus.pth
deleted file mode 100644
index e2182f1e..00000000
--- a/python/dbus.pth
+++ /dev/null
@@ -1 +0,0 @@
-dbus
diff --git a/python/dbus_bindings.pxd.in b/python/dbus_bindings.pxd.in
deleted file mode 100644
index f1707208..00000000
--- a/python/dbus_bindings.pxd.in
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "dbus_h_wrapper.h"
-
-cdef class Connection:
- cdef DBusConnection *conn
-
- cdef __cinit__(self, address, DBusConnection *_conn)
- cdef _set_conn(self, DBusConnection *conn)
- cdef DBusConnection *_get_conn(self)
diff --git a/python/dbus_bindings.pyx b/python/dbus_bindings.pyx
deleted file mode 100644
index c29dea2d..00000000
--- a/python/dbus_bindings.pyx
+++ /dev/null
@@ -1,1849 +0,0 @@
-# -*- Mode: Python -*-
-
-# jdahlin is the most coolest and awesomest person in the world
-# and wrote all the good parts of this code. all the bad parts
-# where python conditionals have a ( ) around them, thus violating
-# PEP-8 were written by the lame wannabe python programmer seth
-
-#FIXME: find memory leaks that I am sure exist
-
-cdef extern from "sys/types.h":
- ctypedef size_t
- ctypedef __int64_t
- ctypedef __uint64_t
-
-cdef extern from "stdlib.h":
- cdef void *malloc(size_t size)
- cdef void free(void *ptr)
- cdef void *calloc(size_t nmemb, size_t size)
-
-cdef extern from "Python.h":
- void Py_XINCREF (object)
- void Py_XDECREF (object)
- object PyString_FromStringAndSize(char *, int)
- ctypedef void *PyGILState_STATE
- void PyErr_Clear()
- PyGILState_STATE PyGILState_Ensure()
- void PyGILState_Release(PyGILState_STATE)
-
-ctypedef struct DBusError:
- char *name
- char *message
- unsigned int dummy1
- unsigned int dummy2
- unsigned int dummy3
- unsigned int dummy4
- unsigned int dummy5
- void *padding1
-
-ctypedef struct DBusMessageIter:
- void *dummy1
- void *dummy2
- dbus_uint32_t dummy3
- int dummy4
- int dummy5
- int dummy6
- int dummy7
- int dummy8
- int dummy9
- int dummy10
- int dummy11
- int pad1
- int pad2
- void *pad3
-
-ctypedef struct DBusObjectPathVTable:
- DBusObjectPathUnregisterFunction unregister_function
- DBusObjectPathMessageFunction message_function
- void (* dbus_internal_pad1) (void *)
- void (* dbus_internal_pad2) (void *)
- void (* dbus_internal_pad3) (void *)
- void (* dbus_internal_pad4) (void *)
-
-class DBusException(Exception):
- pass
-
-class ConnectionError(Exception):
- pass
-
-class ObjectPath(str):
- def __init__(self, value):
- str.__init__(self, value)
-
-class ByteArray(str):
- def __init__(self, value):
- str.__init__(self, value)
-
-class SignatureIter(object):
- def __init__(self, string):
- object.__init__(self)
- self.remaining = string
-
- def next(self):
- if self.remaining == '':
- raise StopIteration
-
- signature = self.remaining
- block_depth = 0
- block_type = None
- end = len(signature)
-
- for marker in range(0, end):
- cur_sig = ord(signature[marker])
-
- if cur_sig == TYPE_ARRAY:
- pass
- elif cur_sig == DICT_ENTRY_BEGIN or cur_sig == STRUCT_BEGIN:
- if block_type == None:
- block_type = cur_sig
-
- if block_type == cur_sig:
- block_depth = block_depth + 1
-
- elif cur_sig == DICT_ENTRY_END:
- if block_type == DICT_ENTRY_BEGIN:
- block_depth = block_depth - 1
-
- if block_depth == 0:
- end = marker
- break
-
- elif cur_sig == STRUCT_END:
- if block_type == STRUCT_BEGIN:
- block_depth = block_depth - 1
-
- if block_depth == 0:
- end = marker
- break
-
- else:
- if block_depth == 0:
- end = marker
- break
-
- end = end + 1
- self.remaining = signature[end:]
- return Signature(signature[0:end])
-
-class Signature(str):
- """An iterable method signature. Iterating gives the signature of each
- argument in turn."""
- def __init__(self, value):
- return str.__init__(self, value)
-
- def __iter__(self):
- return SignatureIter(self)
-
-class VariantSignature(object):
- """A fake method signature which when iterated, is an endless stream
- of variants (handy with zip()). It has no string representation."""
- def __iter__(self):
- return self
-
- def next(self):
- return 'v'
-
-class Byte(int):
- def __init__(self, value):
- int.__init__(self, value)
-
-class Boolean(int):
- def __init__(self, value):
- int.__init__(self, value)
-
-class Int16(int):
- def __init__(self, value):
- int.__init__(self, value)
-
-class UInt16(int):
- def __init__(self, value):
- if value < 0:
- raise TypeError('Unsigned integers must not have a negitive value')
- int.__init__(self, value)
-
-class Int32(int):
- def __init__(self, value):
- int.__init__(self, value)
-
-class UInt32(long):
- def __init__(self, value):
- if value < 0:
- raise TypeError('Unsigned integers must not have a negitive value')
- long.__init__(self, value)
-
-class Int64(long):
- def __init__(self, value):
- long.__init__(self, value)
-
-class UInt64(long):
- def __init__(self, value):
- if value < 0:
- raise TypeError('Unsigned integers must not have a negitive value')
- long.__init__(self, value)
-
-class Double(float):
- def __init__(self, value):
- float.__init__(self, value)
-
-class String(unicode):
- def __init__(self, value):
- unicode.__init__(self, value)
-
-class Array(list):
- def __init__(self, value, type=None, signature=None):
- if signature and type:
- raise TypeError('Can not mix type and signature arguments in a D-BUS Array')
-
- self.type = type
- self.signature = signature
- list.__init__(self, value)
-
-class Variant:
- def __init__(self, value, type=None, signature=None):
- self.value = value
- if signature and type:
- raise TypeError('Can not mix type and signature arguments in a D-BUS Variant')
-
- self.type = type
- self.signature = signature
-
- def __repr__(self):
- return repr(self.value)
-
- def __str__(self):
- return str(self.value)
-
-class Struct(tuple):
- def __init__(self, value):
- tuple.__init__(self, value)
-
-class Dictionary(dict):
- def __init__(self, value, key_type=None, value_type=None, signature=None):
- if key_type and not value_type:
- raise TypeError('When specifying a key_type you must also have a value_type in a D-BUS Dictionary')
- elif value_type and not key_type:
- raise TypeError('When specifying a value_type you must also have a key_type in a D-BUS Dictionary')
- elif key_type and signature:
- raise TypeError('Can not mix type arguments with signature arguments in a D-BUS Dictionary')
-
- self.key_type = key_type
- self.value_type = value_type
- self.signature = signature
- dict.__init__(self, value)
-
-#forward delcerations
-cdef class Message
-cdef class PendingCall
-cdef class Watch
-cdef class MessageIter
-
-cdef void _GIL_safe_cunregister_function_handler (DBusConnection *connection,
- void *user_data):
- cdef Connection conn
-
- tup = <object>user_data
- assert (type(tup) == tuple)
- function = tup[1]
- conn = Connection()
- conn.__cinit__(None, connection)
-
- args = (conn)
- function(*args)
- Py_XDECREF(tup)
-
-cdef void cunregister_function_handler (DBusConnection *connection,
- void *user_data):
- cdef PyGILState_STATE gil
- gil = PyGILState_Ensure()
- try:
- _GIL_safe_cunregister_function_handler (connection, user_data);
- finally:
- PyGILState_Release(gil)
-
-
-
-cdef DBusHandlerResult _GIL_safe_cmessage_function_handler (
- DBusConnection *connection,
- DBusMessage *msg,
- void *user_data):
- cdef Connection conn
- cdef Message message
-
- tup = <object>user_data
- assert (type(tup) == tuple)
- function = tup[0]
- message = EmptyMessage()
-
- #we don't own the message so we need to ref it
- dbus_message_ref(msg)
- message._set_msg(msg)
- conn = Connection()
- conn.__cinit__(None, connection)
- args = (conn,
- message)
-
- retval = function(*args)
-
- if (retval == None):
- retval = DBUS_HANDLER_RESULT_HANDLED
- return retval
-
-cdef DBusHandlerResult cmessage_function_handler (DBusConnection *connection,
- DBusMessage *msg,
- void *user_data):
- cdef PyGILState_STATE gil
- gil = PyGILState_Ensure()
- try:
- return _GIL_safe_cmessage_function_handler (connection, msg, user_data);
- finally:
- PyGILState_Release(gil)
-
-
-cdef class Connection:
- def __init__(self, address=None, Connection _conn=None):
- cdef DBusConnection *c_conn
- cdef char *c_address
- c_conn=NULL
- self.conn = NULL
- if (_conn != None):
- c_conn = _conn.conn
-
- if (address != None or _conn != None):
- self.__cinit__(c_address, c_conn)
-
- # hack to be able to pass in a c pointer to the constructor
- # while still alowing python programs to create a Connection object
- cdef __cinit__(self, address, DBusConnection *_conn):
- cdef DBusError error
- dbus_error_init(&error)
- if _conn != NULL:
- self.conn = _conn
- dbus_connection_ref(self.conn)
- else:
- self.conn = dbus_connection_open(address,
- &error)
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free (&error)
- raise DBusException, errormsg
-
- def __dealloc__(self):
- if self.conn != NULL:
- dbus_connection_unref(self.conn)
-
- cdef _set_conn(self, DBusConnection *conn):
- self.conn = conn
-
- cdef DBusConnection *_get_conn(self):
- return self.conn
-
- def get_unique_name(self):
- return bus_get_unique_name(self)
-
- def close(self):
- dbus_connection_close(self.conn)
-
- def get_is_connected(self):
- return dbus_connection_get_is_connected(self.conn)
-
- def get_is_authenticated(self):
- return dbus_connection_get_is_authenticated(self.conn)
-
- def flush(self):
- dbus_connection_flush(self.conn)
-
- def borrow_message(self):
- cdef Message m
- m = EmptyMessage()
- m._set_msg(dbus_connection_borrow_message(self.conn))
- return m
-
- def return_message(self, Message message):
- cdef DBusMessage *msg
- msg = message._get_msg()
- dbus_connection_return_message(self.conn, msg)
-
- def steal_borrowed_message(self, Message message):
- cdef DBusMessage *msg
- msg = message._get_msg()
- dbus_connection_steal_borrowed_message(self.conn,
- msg)
-
- def pop_message(self):
- cdef DBusMessage *msg
- cdef Message m
-
- msg = dbus_connection_pop_message(self.conn)
- if msg != NULL:
- m = EmptyMessage()
- m._set_msg(msg)
- else:
- m = None
- return m
-
- def get_dispatch_status(self):
- return dbus_connection_get_dispatch_status(self.conn)
-
- def dispatch(self):
- return dbus_connection_dispatch(self.conn)
-
- def send(self, Message message):
- #cdef dbus_uint32_t client_serial
- #if type(message) != Message:
- # raise TypeError
- cdef DBusMessage *msg
- msg = message._get_msg()
- retval = dbus_connection_send(self.conn,
- msg,
- NULL)
- return retval
-
- def send_with_reply_handlers(self, Message message, timeout_milliseconds, reply_handler, error_handler):
- retval = False
- try:
- (retval, pending_call) = self.send_with_reply(message, timeout_milliseconds)
- if pending_call:
- pending_call.set_notify(reply_handler, error_handler)
- except Exception, e:
- error_handler(e)
-
- return (retval, pending_call)
-
- def send_with_reply(self, Message message, timeout_milliseconds):
- cdef dbus_bool_t retval
- cdef DBusPendingCall *cpending_call
- cdef DBusMessage *msg
- cdef PendingCall pending_call
-
- cpending_call = NULL
-
- msg = message._get_msg()
-
- retval = dbus_connection_send_with_reply(self.conn,
- msg,
- &cpending_call,
- timeout_milliseconds)
-
- if (cpending_call != NULL):
- pending_call = PendingCall()
- pending_call.__cinit__(cpending_call)
- else:
- pending_call = None
-
- return (retval, pending_call)
-
- def send_with_reply_and_block(self, Message message,
- timeout_milliseconds=-1):
- cdef DBusMessage * retval
- cdef DBusError error
- cdef DBusMessage *msg
- cdef Message m
-
- dbus_error_init(&error)
-
- msg = message._get_msg()
-
- retval = dbus_connection_send_with_reply_and_block(
- self.conn,
- msg,
- timeout_milliseconds,
- &error)
-
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free (&error)
- raise DBusException, errormsg
-
- assert(retval != NULL)
-
- m = EmptyMessage()
- m._set_msg(retval)
-
- return m
-
- def set_watch_functions(self, add_function, remove_function, data):
- pass
-
- def set_timeout_functions(self, add_function, remove_function, data):
- pass
-
- def set_wakeup_main_function(self, wakeup_main_function, data):
- pass
-
- # FIXME: set_dispatch_status_function, get_unix_user, set_unix_user_function
-
- def add_filter(self, filter_function):
- user_data = (filter_function,)
- Py_XINCREF(user_data)
-
- return dbus_connection_add_filter(self.conn,
- cmessage_function_handler,
- <void*>user_data,
- NULL)
-
-
- #FIXME: remove_filter
- # this is pretty tricky, we want to only remove the filter
- # if we truly have no more calls to our message_function_handler...ugh
-
- def set_data(self, slot, data):
- pass
-
- def get_data(self, slot):
- pass
-
- def set_max_message_size(self, size):
- dbus_connection_set_max_message_size(self.conn, size)
-
- def get_max_message_size(self):
- return dbus_connection_get_max_message_size(self.conn)
-
- def set_max_received_size(self, size):
- dbus_connection_set_max_received_size(self.conn, size)
-
- def get_max_received_size(self):
- return dbus_connection_get_max_received_size(self.conn)
-
- def get_outgoing_size(self):
- return dbus_connection_get_outgoing_size(self.conn)
-
- # preallocate_send, free_preallocated_send, send_preallocated
-
- def register_object_path(self, path, unregister_cb, message_cb):
- cdef DBusObjectPathVTable cvtable
-
- cvtable.unregister_function = cunregister_function_handler
- cvtable.message_function = cmessage_function_handler
-
- user_data = (message_cb, unregister_cb)
- Py_XINCREF(user_data)
-
- return dbus_connection_register_object_path(self.conn, path, &cvtable,
- <void*>user_data)
-
- def register_fallback(self, path, unregister_cb, message_cb):
- cdef DBusObjectPathVTable cvtable
-
- cvtable.unregister_function = cunregister_function_handler
- cvtable.message_function = cmessage_function_handler
-
- user_data = (message_cb, unregister_cb)
- Py_XINCREF(user_data)
-
- return dbus_connection_register_fallback(self.conn, path, &cvtable,
- <void*>user_data)
-
- #FIXME: unregister_object_path , see problems with remove_filter
-
- def list_registered (self, parent_path):
- cdef char **cchild_entries
- cdef dbus_bool_t retval
-
- retval = dbus_connection_list_registered(self.conn, parent_path, &cchild_entries)
-
- if (not retval):
- #FIXME: raise out of memory exception?
- return None
-
- i = 0
- child_entries = []
-
- while (cchild_entries[i] != NULL):
- child_entries.append(cchild_entries[i])
- i = i + 1
-
- dbus_free_string_array(cchild_entries)
-
- return child_entries
-
-cdef void _GIL_safe_pending_call_notification (DBusPendingCall *pending_call,
- void *user_data):
- cdef DBusMessage *dbus_message
- cdef Message message
-
- (reply_handler, error_handler) = <object>user_data
-
- dbus_message = dbus_pending_call_steal_reply(pending_call)
- message = EmptyMessage()
- message._set_msg(dbus_message)
-
- type = message.get_type()
-
- if type == MESSAGE_TYPE_METHOD_RETURN:
- args = message.get_args_list()
- reply_handler(*args)
- elif type == MESSAGE_TYPE_ERROR:
- args = message.get_args_list()
- if len(args) > 0:
- error_handler(DBusException(args[0]))
- else:
- error_handler(DBusException(""))
- else:
- error_handler(DBusException('Unexpected Message Type: ' + message.type_to_name(type)))
-
- dbus_pending_call_unref(pending_call)
- Py_XDECREF(<object>user_data)
-
-cdef void _pending_call_notification(DBusPendingCall *pending_call,
- void *user_data):
- cdef PyGILState_STATE gil
- gil = PyGILState_Ensure()
- try:
- _GIL_safe_pending_call_notification (pending_call, user_data);
- finally:
- PyGILState_Release(gil)
-
-cdef void _pending_call_free_user_data(void *data):
- call_tuple = <object>data
- Py_XDECREF(call_tuple)
-
-cdef class PendingCall:
- cdef DBusPendingCall *pending_call
-
- def __init__(self, PendingCall _pending_call=None):
- self.pending_call = NULL
- if (_pending_call != None):
- self.__cinit__(_pending_call.pending_call)
-
- cdef void __cinit__(self, DBusPendingCall *_pending_call):
- self.pending_call = _pending_call
- dbus_pending_call_ref(self.pending_call)
-
- def __dealloc__(self):
- if self.pending_call != NULL:
- dbus_pending_call_unref(self.pending_call)
-
- cdef DBusPendingCall *_get_pending_call(self):
- return self.pending_call
-
- def cancel(self):
- dbus_pending_call_cancel(self.pending_call)
-
- def get_completed(self):
- return dbus_pending_call_get_completed(self.pending_call)
-
- def get_reply(self):
- cdef Message message
- message = EmptyMessage()
- message._set_msg(dbus_pending_call_steal_reply(self.pending_call))
- return message
-
- def block(self):
- dbus_pending_call_block(self.pending_call)
-
- def set_notify(self, reply_handler, error_handler):
- user_data = (reply_handler, error_handler)
- Py_XINCREF(user_data)
- dbus_pending_call_ref(self.pending_call)
- dbus_pending_call_set_notify(self.pending_call, _pending_call_notification,
- <void *>user_data, _pending_call_free_user_data)
-
-
-cdef class Watch:
- cdef DBusWatch* watch
-
- def __init__(self):
- pass
-
- cdef __cinit__(self, DBusWatch *cwatch):
- self.watch = cwatch
-
- def get_fd(self):
- return dbus_watch_get_fd(self.watch)
-
- # FIXME: not picked up correctly by extract.py
- #def get_flags(self):
- # return dbus_watch_get_flags(self.watch)
-
- def handle(self, flags):
- return dbus_watch_handle(self.watch, flags)
-
- def get_enabled(self):
- return dbus_watch_get_enabled(self.watch)
-
-cdef class MessageIter:
- cdef DBusMessageIter *iter
- cdef DBusMessageIter real_iter
- cdef dbus_uint32_t level
-
- def __init__(self, level=0):
- self.iter = &self.real_iter
- self.level = level
- if(self.level > 32):
- raise TypeError, 'Type recurion is too deep'
-
- cdef __cinit__(self, DBusMessageIter *iter):
- self.real_iter = iter[0]
-
- cdef DBusMessageIter *_get_iter(self):
- return self.iter
-
- def has_next(self):
- return dbus_message_iter_has_next(self.iter)
-
- def next(self):
- return dbus_message_iter_next(self.iter)
-
- def get(self, arg_type=None):
- if(arg_type == None):
- arg_type = self.get_arg_type()
-
- if arg_type == TYPE_INVALID:
- raise TypeError, 'Invalid arg type in MessageIter'
- elif arg_type == TYPE_STRING:
- retval = self.get_string()
- elif arg_type == TYPE_INT16:
- retval = self.get_int16()
- elif arg_type == TYPE_UINT16:
- retval = self.get_uint16()
- elif arg_type == TYPE_INT32:
- retval = self.get_int32()
- elif arg_type == TYPE_UINT32:
- retval = self.get_uint32()
- elif arg_type == TYPE_INT64:
- retval = self.get_int64()
- elif arg_type == TYPE_UINT64:
- retval = self.get_uint64()
- elif arg_type == TYPE_DOUBLE:
- retval = self.get_double()
- elif arg_type == TYPE_BYTE:
- retval = self.get_byte()
- elif arg_type == TYPE_BOOLEAN:
- retval = self.get_boolean()
- elif arg_type == TYPE_SIGNATURE:
- retval = self.get_signature()
- elif arg_type == TYPE_ARRAY:
- array_type = self.get_element_type()
- if array_type == TYPE_DICT_ENTRY:
- retval = self.get_dict()
- else:
- retval = self.get_array(array_type)
- elif arg_type == TYPE_OBJECT_PATH:
- retval = self.get_object_path()
- elif arg_type == TYPE_STRUCT:
- retval = self.get_struct()
- elif arg_type == TYPE_VARIANT:
- retval = self.get_variant()
- elif arg_type == TYPE_DICT_ENTRY:
- raise TypeError, 'Dictionary Entries can only appear as part of an array container'
- else:
- raise TypeError, 'Unknown arg type %d in MessageIter' % (arg_type)
-
- return retval
-
- def get_arg_type(self):
- return dbus_message_iter_get_arg_type(self.iter)
-
- def get_element_type(self):
- return dbus_message_iter_get_element_type(self.iter)
-
- def get_byte(self):
- cdef unsigned char c_val
- dbus_message_iter_get_basic(self.iter, <unsigned char *>&c_val)
- return c_val
-
- def get_boolean(self):
- cdef dbus_bool_t c_val
- dbus_message_iter_get_basic(self.iter, <dbus_bool_t *>&c_val)
-
- if c_val:
- return True
- else:
- return False
-
- def get_signature(self):
- signature_string = self.get_string()
- return Signature(signature_string)
-
- def get_int16(self):
- cdef dbus_int16_t c_val
- dbus_message_iter_get_basic(self.iter, <dbus_int16_t *>&c_val)
-
- return c_val
-
- def get_uint16(self):
- cdef dbus_uint16_t c_val
- dbus_message_iter_get_basic(self.iter, <dbus_uint16_t *>&c_val)
- return c_val
-
- def get_int32(self):
- cdef dbus_int32_t c_val
- dbus_message_iter_get_basic(self.iter, <dbus_int32_t *>&c_val)
- return c_val
-
- def get_uint32(self):
- cdef dbus_uint32_t c_val
- dbus_message_iter_get_basic(self.iter, <dbus_uint32_t *>&c_val)
- return c_val
-
- def get_int64(self):
- cdef dbus_int64_t c_val
- dbus_message_iter_get_basic(self.iter, <dbus_int64_t *>&c_val)
- return c_val
-
- def get_uint64(self):
- cdef dbus_uint64_t c_val
- dbus_message_iter_get_basic(self.iter, <dbus_uint64_t *>&c_val)
- return c_val
-
- def get_double(self):
- cdef double c_val
- dbus_message_iter_get_basic(self.iter, <double *>&c_val)
- return c_val
-
- def get_string(self):
- cdef char *c_str
- dbus_message_iter_get_basic(self.iter, <char **>&c_str)
- ret = c_str.decode('utf8')
-
- return ret
-
- def get_object_path(self):
- object_path_string = self.get_string()
- return ObjectPath(object_path_string)
-
- def get_dict(self):
- cdef DBusMessageIter c_dict_iter
- cdef MessageIter dict_iter
- level = self.level + 1
-
- dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_dict_iter)
- dict_iter = MessageIter(level)
- dict_iter.__cinit__(&c_dict_iter)
-
- python_dict = {}
- cur_arg_type = dict_iter.get_arg_type()
- while cur_arg_type == TYPE_DICT_ENTRY:
- if cur_arg_type != TYPE_DICT_ENTRY:
- raise TypeError, "Dictionary elements must be of type TYPE_DICT_ENTRY '%s != %s'" % (TYPE_DICT_ENTRY, cur_arg_type)
-
- dict_entry = dict_iter.get_struct()
- if len(dict_entry) != 2:
- raise TypeError, "Dictionary entries must be structs of two elements. This entry had %i elements.'" % (len(dict_entry))
-
- python_dict[dict_entry[0]] = dict_entry[1]
-
- dict_iter.next()
- cur_arg_type = dict_iter.get_arg_type()
-
- return python_dict
-
- def get_array(self, type):
- cdef DBusMessageIter c_array_iter
- cdef MessageIter array_iter
- level = self.level + 1
-
- dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_array_iter)
- array_iter = MessageIter(level)
- array_iter.__cinit__(&c_array_iter)
-
- python_list = []
- cur_arg_type = array_iter.get_arg_type()
- while cur_arg_type != TYPE_INVALID:
- if cur_arg_type != type:
- raise TypeError, "Array elements must be of the same type '%s != %s'" % (type, cur_arg_type)
-
- value = array_iter.get(type)
- python_list.append(value)
-
- array_iter.next()
- cur_arg_type = array_iter.get_arg_type()
-
- return python_list
-
- def get_variant(self):
- cdef DBusMessageIter c_var_iter
- cdef MessageIter var_iter
- level = self.level + 1
-
- dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_var_iter)
- var_iter = MessageIter(level)
- var_iter.__cinit__(&c_var_iter)
-
- return var_iter.get()
-
- def get_struct(self):
- cdef DBusMessageIter c_struct_iter
- cdef MessageIter struct_iter
- level = self.level + 1
-
- dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_struct_iter)
- struct_iter = MessageIter(level)
- struct_iter.__cinit__(&c_struct_iter)
-
- python_list = []
- while struct_iter.get_arg_type() != TYPE_INVALID:
- value = struct_iter.get()
- python_list.append(value)
-
- struct_iter.next()
-
- return tuple(python_list)
-
- def python_value_to_dbus_sig(self, value, level = 0):
-
- if(level > 32):
- raise TypeError, 'Type recurion is too deep'
-
- level = level + 1
-
- ptype = type(value)
- ret = ""
- if ptype == bool:
- ret = TYPE_BOOLEAN
- ret = str(chr(ret))
- elif ptype == int:
- ret = TYPE_INT32
- ret = str(chr(ret))
- elif ptype == long:
- ret = TYPE_INT64
- ret = str(chr(ret))
- elif (ptype == str or ptype == unicode):
- ret = TYPE_STRING
- ret = str(chr(ret))
- elif ptype == float:
- ret = TYPE_DOUBLE
- ret = str(chr(ret))
- elif ptype == dict:
- dict_list = value.items()
- key, value = dict_list[0]
-
- ret = str(chr(TYPE_ARRAY)) + str(chr(DICT_ENTRY_BEGIN))
- ret = ret + self.python_value_to_dbus_sig(key, level)
- ret = ret + self.python_value_to_dbus_sig(value, level)
- ret = ret + str(chr(DICT_ENTRY_END))
-
- elif ptype == tuple:
- ret = str(chr(STRUCT_BEGIN))
- for item in value:
- ret = ret + self.python_value_to_dbus_sig(item, level)
- ret = ret + str(chr(STRUCT_END))
- elif ptype == list:
- ret = str(chr(TYPE_ARRAY))
- ret = ret + self.python_value_to_dbus_sig(value[0], level)
- elif isinstance(value, ObjectPath) or value == ObjectPath:
-
- ret = TYPE_OBJECT_PATH
- ret = str(chr(ret))
- elif isinstance(value, ByteArray) or value == ByteArray:
- ret = str(chr(TYPE_ARRAY)) + str(chr(TYPE_BYTE))
- elif isinstance(value, Signature) or value == Signature:
- ret = TYPE_SIGNATURE
- ret = str(chr(ret))
- elif isinstance(value, Byte) or value == Byte:
- ret = TYPE_BYTE
- ret = str(chr(ret))
- elif isinstance(value, Boolean) or value == Boolean:
- ret = TYPE_BOOLEAN
- ret = str(chr(ret))
- elif isinstance(value, Int16) or value == Int16:
- ret = TYPE_INT16
- ret = str(chr(ret))
- elif isinstance(value, UInt16) or value == UInt16:
- ret = TYPE_UINT16
- ret = str(chr(ret))
- elif isinstance(value, Int32) or value == Int32:
- ret = TYPE_INT32
- ret = str(chr(ret))
- elif isinstance(value, UInt32) or value == UInt32:
- ret = TYPE_UINT32
- ret = str(chr(ret))
- elif isinstance(value, Int64) or value == Int64:
- ret = TYPE_INT64
- ret = str(chr(ret))
- elif isinstance(value, UInt64) or value == UInt64:
- ret = TYPE_UINT64
- ret = str(chr(ret))
- elif isinstance(value, Double) or value == Double:
- ret = TYPE_DOUBLE
- ret = str(chr(ret))
- elif isinstance(value, String) or value == String:
- ret = TYPE_STRING
- ret = str(chr(ret))
- elif isinstance(value, Array):
- ret = str(chr(TYPE_ARRAY))
- if value.type == None:
- if value.signature:
- ret = ret + value.signature
- else:
- ret = ret + self.python_value_to_dbus_sig(value[0], level)
- else:
- ret = ret + self.python_value_to_dbus_sig(value.type, level)
-
- elif isinstance(value, Struct) or value == Struct:
- ret = str(chr(STRUCT_BEGIN))
- for item in value:
- ret = ret + self.python_value_to_dbus_sig(item, level)
- ret = ret + str(chr(STRUCT_END))
- elif isinstance(value, Dictionary):
- ret = str(chr(TYPE_ARRAY)) + str(chr(DICT_ENTRY_BEGIN))
-
- if value.key_type and value.value_type:
- ret = ret + self.python_value_to_dbus_sig(value.key_type, level)
- ret = ret + self.python_value_to_dbus_sig(value.value_type, level)
- elif value.signature:
- ret = ret + value.signature
- else:
- dict_list = value.items()
-
- key, val = dict_list[0]
- ret = ret + self.python_value_to_dbus_sig(key, level)
- ret = ret + self.python_value_to_dbus_sig(val, level)
-
- ret = ret + str(chr(DICT_ENTRY_END))
- elif isinstance(value, Variant) or value == Variant:
- ret = ret + str(chr(TYPE_VARIANT))
- else:
- raise TypeError, "Argument of unknown type '%s'" % (ptype)
-
- return ret
-
- def append_strict(self, value, sig):
-
- if sig == TYPE_INVALID or sig == None:
- raise TypeError, 'Invalid arg type sent to append_strict'
-
- sig_type = ord(sig[0])
-
- if sig_type == TYPE_STRING:
- retval = self.append_string(value)
- elif sig_type == TYPE_INT16:
- retval = self.append_int16(value)
- elif sig_type == TYPE_UINT16:
- retval = self.append_uint16(value)
- elif sig_type == TYPE_INT32:
- retval = self.append_int32(value)
- elif sig_type == TYPE_UINT32:
- retval = self.append_uint32(value)
- elif sig_type == TYPE_INT64:
- retval = self.append_int64(value)
- elif sig_type == TYPE_UINT64:
- retval = self.append_uint64(value)
- elif sig_type == TYPE_DOUBLE:
- retval = self.append_double(value)
- elif sig_type == TYPE_BYTE:
- retval = self.append_byte(value)
- elif sig_type == TYPE_BOOLEAN:
- retval = self.append_boolean(value)
- elif sig_type == TYPE_SIGNATURE:
- retval = self.append_signature(value)
- elif sig_type == TYPE_ARRAY:
- if len(sig) < 2:
- raise TypeError, "Invalid array signature in append_strict. Arrays must be followed by a type."
-
- array_type = ord(sig[1])
- if array_type == DICT_ENTRY_BEGIN:
- if ord(sig[-1]) != DICT_ENTRY_END:
- raise TypeError, "Invalid dict entry in append_strict. No termination in signature %s."%(sig)
-
- tmp_sig = sig[2:-1]
- retval = self.append_dict(Dictionary(value, signature=tmp_sig))
- else:
- tmp_sig = sig[1:]
- retval = self.append_array(Array(value, signature=tmp_sig))
- elif sig_type == TYPE_OBJECT_PATH:
- retval = self.append_object_path(value)
- elif sig_type == STRUCT_BEGIN:
- if ord(sig[-1]) != STRUCT_END:
- raise TypeError, "Invalid struct entry in append_strict. No termination in signature %s." % (sig)
-
- tmp_sig = sig[1:-1]
- retval = self.append_struct(value, signature = tmp_sig)
- elif sig_type == TYPE_VARIANT:
- if isinstance(value, Variant):
- retval = self.append_variant(value)
- else:
- retval = self.append_variant(Variant(value))
- elif sig_type == DICT_ENTRY_BEGIN:
- raise TypeError, "Signiture is invalid in append_strict. A dict entry must be part of an array."
- else:
- raise TypeError, "Argument of unknown type '%s' in append_strict" % (sig)
-
- return retval
-
- def append(self, value):
- value_type = type(value)
- if value_type == bool:
- retval = self.append_boolean(value)
- elif value_type == int:
- retval = self.append_int32(value)
- elif value_type == long:
- retval = self.append_int64(value)
- elif (value_type == str or value_type == unicode):
- retval = self.append_string(value)
- elif value_type == float:
- retval = self.append_double(value)
- elif value_type == dict:
- retval = self.append_dict(value)
- elif value_type == tuple:
- retval = self.append_struct(value)
- elif value_type == list:
- retval = self.append_array(value)
- #elif value_type == None.__class__:
- # retval = self.append_nil()
- elif isinstance(value, ObjectPath):
- retval = self.append_object_path(value)
- elif isinstance(value, ByteArray):
- retval = self.append_array(value)
- elif isinstance(value, Signature):
- retval = self.append_signature(value)
- elif isinstance(value, Byte):
- retval = self.append_byte(value)
- elif isinstance(value, Boolean):
- retval = self.append_boolean(value)
- elif isinstance(value, Int16):
- retval = self.append_int16(value)
- elif isinstance(value, UInt16):
- retval = self.append_uint16(value)
- elif isinstance(value, Int32):
- retval = self.append_int32(value)
- elif isinstance(value, UInt32):
- retval = self.append_uint32(value)
- elif isinstance(value, Int64):
- retval = self.append_int64(value)
- elif isinstance(value, UInt64):
- retval = self.append_uint64(value)
- elif isinstance(value, Double):
- retval = self.append_double(value)
- elif isinstance(value, String):
- retval = self.append_string(value)
- elif isinstance(value, Array):
- retval = self.append_array(value)
- elif isinstance(value, Struct):
- retval = self.append_struct(value)
- elif isinstance(value, Dictionary):
- retval = self.append_dict(value)
- elif isinstance(value, Variant):
- retval = self.append_variant(value)
- else:
- raise TypeError, "Argument of unknown type '%s'" % (value_type)
-
- return retval
-
- def append_boolean(self, value):
- cdef dbus_bool_t c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_BOOLEAN, <dbus_bool_t *>&c_value)
-
- def append_byte(self, value):
- cdef char b
- if type(value) == str and len(value) == 1:
- b = ord(value)
- elif type(value) == Byte:
- b = value
- else:
- raise TypeError
-
- return dbus_message_iter_append_basic(self.iter, TYPE_BYTE, <char *>&b)
-
- def append_int16(self, value):
- cdef dbus_int16_t c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_INT16, <dbus_int16_t *>&c_value)
-
- def append_uint16(self, value):
- cdef dbus_uint16_t c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_UINT16, <dbus_uint16_t *>&c_value)
-
- def append_int32(self, value):
- cdef dbus_int32_t c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_INT32, <dbus_int32_t *>&c_value)
-
- def append_uint32(self, value):
- cdef dbus_uint32_t c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_UINT32, <dbus_uint32_t *>&c_value)
-
- def append_int64(self, value):
- cdef dbus_int64_t c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_INT64, <dbus_int64_t *>&c_value)
-
- def append_uint64(self, value):
- cdef dbus_uint64_t c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_UINT64, <dbus_uint64_t *>&c_value)
-
- def append_double(self, value):
- cdef double c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_DOUBLE, <double *>&c_value)
-
- def append_string(self, value):
- cdef char *c_value
- tmp = value.encode('utf8')
- c_value = tmp
- return dbus_message_iter_append_basic(self.iter, TYPE_STRING, <char **>&c_value)
-
- def append_object_path(self, value):
- cdef char *c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_OBJECT_PATH, <char **>&c_value)
-
- def append_signature(self, value):
- cdef char *c_value
- c_value = value
- return dbus_message_iter_append_basic(self.iter, TYPE_SIGNATURE, <char **>&c_value)
-
-
- def append_dict(self, python_dict):
- cdef DBusMessageIter c_dict_iter, c_dict_entry_iter
- cdef MessageIter dict_iter, dict_entry_iter
-
- level = self.level + 1
-
- key = None
- value = None
-
- sig = str(chr(DICT_ENTRY_BEGIN))
-
- if isinstance(python_dict, Dictionary):
- key = python_dict.key_type
- value = python_dict.value_type
- signature = python_dict.signature
-
- dict_list = python_dict.items()
-
- if signature:
- sig = sig + signature
- else:
- if not (key and value):
- key, value = dict_list[0]
-
- sig = sig + self.python_value_to_dbus_sig(key)
- sig = sig + self.python_value_to_dbus_sig(value)
-
- sig = sig + str(chr(DICT_ENTRY_END))
-
- dbus_message_iter_open_container(self.iter, TYPE_ARRAY, sig, <DBusMessageIter *>&c_dict_iter)
- dict_iter = MessageIter(level)
- dict_iter.__cinit__(&c_dict_iter)
-
- for key, value in dict_list:
- dbus_message_iter_open_container(dict_iter.iter, TYPE_DICT_ENTRY, sig, <DBusMessageIter *>&c_dict_entry_iter)
- dict_entry_iter = MessageIter(level)
- dict_entry_iter.__cinit__(&c_dict_entry_iter)
-
- if signature:
- signature_iter = iter(Signature(signature))
- tmp_sig = signature_iter.next()
- if not dict_entry_iter.append_strict(key, tmp_sig):
- dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
- dbus_message_iter_close_container(self.iter, dict_iter.iter)
- return False
-
- tmp_sig = signature_iter.next()
- if not dict_entry_iter.append_strict(value, tmp_sig):
- dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
- dbus_message_iter_close_container(self.iter, dict_iter.iter)
- return False
-
- else:
- if not dict_entry_iter.append(key):
- dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
- dbus_message_iter_close_container(self.iter, dict_iter.iter)
- return False
-
- if not dict_entry_iter.append(value):
- dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
- dbus_message_iter_close_container(self.iter, dict_iter.iter)
- return False
-
- dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
-
- dbus_message_iter_close_container(self.iter, dict_iter.iter)
-
- return True
-
- def append_struct(self, python_struct, signature = None):
- cdef DBusMessageIter c_struct_iter
- cdef MessageIter struct_iter
-
- level = self.level + 1
- dbus_message_iter_open_container(self.iter, TYPE_STRUCT, NULL, <DBusMessageIter *>&c_struct_iter)
- struct_iter = MessageIter(level)
- struct_iter.__cinit__(&c_struct_iter)
-
- signature_iter = iter(Signature(signature))
- for item in python_struct:
- if signature:
- sig = signature_iter.next()
-
- if sig == '':
- dbus_message_iter_close_container(self.iter, struct_iter.iter)
- return False
-
- if not struct_iter.append_strict(item, sig):
- dbus_message_iter_close_container(self.iter, struct_iter.iter)
- return False
- else:
- if not struct_iter.append(item):
- dbus_message_iter_close_container(self.iter, struct_iter.iter)
- return False
-
- dbus_message_iter_close_container(self.iter, struct_iter.iter)
-
- return True
-
- def append_array(self, python_list):
- cdef DBusMessageIter c_array_iter
- cdef MessageIter array_iter
-
- level = self.level + 1
-
- sig = None
- if isinstance(python_list, Array):
- if python_list.type:
- sig = self.python_value_to_dbus_sig(python_list.type)
- elif python_list.signature:
- sig = python_list.signature
- else:
- sig = self.python_value_to_dbus_sig(python_list[0])
- else:
- sig = self.python_value_to_dbus_sig(python_list[0])
-
- dbus_message_iter_open_container(self.iter, TYPE_ARRAY, sig, <DBusMessageIter *>&c_array_iter)
- array_iter = MessageIter(level)
- array_iter.__cinit__(&c_array_iter)
-
- length = len(python_list)
- for item in python_list:
- if not array_iter.append_strict(item, sig):
- dbus_message_iter_close_container(self.iter, array_iter.iter)
- return False
-
- dbus_message_iter_close_container(self.iter, array_iter.iter)
-
- return True
-
- def append_variant(self, value):
- cdef DBusMessageIter c_variant_iter
- cdef MessageIter variant_iter
-
- level = self.level + 1
-
- if value.signature:
- sig = value.signature
- elif value.type:
- sig = self.python_value_to_dbus_sig(value.type)
- else:
- sig = self.python_value_to_dbus_sig(value.value)
-
- dbus_message_iter_open_container(self.iter, TYPE_VARIANT, sig, <DBusMessageIter *>&c_variant_iter)
-
- variant_iter = MessageIter(level)
- variant_iter.__cinit__(&c_variant_iter)
-
- if not variant_iter.append(value.value):
- dbus_message_iter_close_container(self.iter, variant_iter.iter)
- return False
-
- dbus_message_iter_close_container(self.iter, variant_iter.iter)
- return True
-
- def __str__(self):
- cdef DBusMessageIter c_array_iter
- cdef MessageIter array_iter
-
- value_at_iter = True
- retval = ""
- while (value_at_iter):
- type = self.get_arg_type()
- if type == TYPE_INVALID:
- break
- elif type == TYPE_STRING:
- str = iter.get_string()
- arg = 'string:%s\n' % (str)
- elif type == TYPE_OBJECT_PATH:
- path = iter.get_object_path()
- arg = 'object_path:%s\n' % (path)
- elif type == TYPE_INT16:
- num = iter.get_int16()
- arg = 'int16:%d\n' % (num)
- elif type == TYPE_UINT16:
- num = iter.get_uint16()
- arg = 'uint16:%u\n' % (num)
- elif type == TYPE_INT32:
- num = iter.get_int32()
- arg = 'int32:%d\n' % (num)
- elif type == TYPE_UINT32:
- num = iter.get_uint32()
- arg = 'uint32:%u\n' % (num)
- elif type == TYPE_INT64:
- num = iter.get_int64()
- arg = 'int64:%d\n' % (num)
- elif type == TYPE_UINT64:
- num = iter.get_uint64()
- arg = 'uint64:%u\n' % (num)
- elif type == TYPE_DOUBLE:
- num = iter.get_double()
- arg = 'double:%f\n' % (num)
- elif type == TYPE_BYTE:
- num = iter.get_byte()
- arg = 'byte:%x(%s)\n' % (num, str(chr(num)))
- elif type == TYPE_BOOLEAN:
- bool = iter.get_boolean()
- if (bool):
- str = "true"
- else:
- str = "false"
- arg = 'boolean:%s\n' % (str)
- elif type == TYPE_ARRAY:
- dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_array_iter)
- array_iter = MessageIter(self.level + 1)
- array_iter.__cinit__(&c_array_iter)
- if array_iter.has_next():
- arg = 'array [' + str(array_iter) + ']'
- else:
- arg = 'array []'
- else:
- arg = '(unknown arg type %d)\n' % type
-
- retval = retval + arg
- value_at_iter = self.next()
-
- return retval
-
-
-(MESSAGE_TYPE_INVALID, MESSAGE_TYPE_METHOD_CALL, MESSAGE_TYPE_METHOD_RETURN, MESSAGE_TYPE_ERROR, MESSAGE_TYPE_SIGNAL) = range(5)
-(TYPE_INVALID, TYPE_BYTE, TYPE_BOOLEAN, TYPE_INT16, TYPE_UINT16, TYPE_INT32, TYPE_UINT32, TYPE_INT64, TYPE_UINT64, TYPE_DOUBLE, TYPE_STRING, TYPE_OBJECT_PATH, TYPE_SIGNATURE, TYPE_ARRAY, TYPE_STRUCT, STRUCT_BEGIN, STRUCT_END, TYPE_VARIANT, TYPE_DICT_ENTRY, DICT_ENTRY_BEGIN, DICT_ENTRY_END) = (0, ord('y'), ord('b'), ord('n'), ord('q'), ord('i'), ord('u'), ord('x'), ord('t'), ord('d'), ord('s'), ord('o'), ord('g'), ord('a'), ord('r'), ord('('), ord(')'), ord('v'), ord('e'), ord('{'), ord('}'))
-(HANDLER_RESULT_HANDLED, HANDLER_RESULT_NOT_YET_HANDLED, HANDLER_RESULT_NEED_MEMORY) = range(3)
-
-cdef class Message:
- cdef DBusMessage *msg
-
- def __init__(self, message_type=MESSAGE_TYPE_INVALID,
- service=None, path=None, dbus_interface=None, method=None,
- Message method_call=None,
- name=None,
- Message reply_to=None, error_name=None, error_message=None,
- _create=1):
-
- self.msg = NULL
-
- cdef char *cservice
- cdef char *ciface
- cdef DBusMessage *cmsg
-
- ciface = NULL
- if (dbus_interface != None):
- ciface = dbus_interface
-
- cservice = NULL
- if (service != None):
- cservice = service
-
- if _create:
- if message_type == MESSAGE_TYPE_METHOD_CALL:
- self.msg = dbus_message_new_method_call(cservice, path, ciface, method)
- elif message_type == MESSAGE_TYPE_METHOD_RETURN:
- cmsg = method_call._get_msg()
- self.msg = dbus_message_new_method_return(cmsg)
- elif message_type == MESSAGE_TYPE_SIGNAL:
- self.msg = dbus_message_new_signal(path, ciface, name)
- elif message_type == MESSAGE_TYPE_ERROR:
- cmsg = reply_to._get_msg()
- self.msg = dbus_message_new_error(cmsg, error_name, error_message)
-
-
- def __dealloc__(self):
- if self.msg != NULL:
- dbus_message_unref(self.msg)
-
- def type_to_name(self, type):
- if type == MESSAGE_TYPE_SIGNAL:
- return "signal"
- elif type == MESSAGE_TYPE_METHOD_CALL:
- return "method call"
- elif type == MESSAGE_TYPE_METHOD_RETURN:
- return "method return"
- elif type == MESSAGE_TYPE_ERROR:
- return "error"
- else:
- return "(unknown message type)"
-
- def __str__(self):
- message_type = self.get_type()
- sender = self.get_sender()
-
- if sender == None:
- sender = "(no sender)"
-
- if (message_type == MESSAGE_TYPE_METHOD_CALL) or (message_type == MESSAGE_TYPE_SIGNAL):
- retval = '%s interface=%s; member=%s; sender=%s' % (self.type_to_name(message_type),
- self.get_interface(),
- self.get_member(),
- sender)
- elif message_type == MESSAGE_TYPE_METHOD_RETURN:
- retval = '%s sender=%s' % (self.type_to_name(message_type),
- sender)
- elif message_type == MESSAGE_TYPE_ERROR:
- retval = '%s name=%s; sender=%s' % (self.type_to_name(message_type),
- self.get_error_name(),
- sender)
- else:
- retval = "Message of unknown type %d" % (message_type)
-
-
- # FIXME: should really use self.convert_to_tuple() here
-
- iter = self.get_iter()
-
- retval = retval + "\n" + str(iter)
-
- return retval
-
- cdef _set_msg(self, DBusMessage *msg):
- self.msg = msg
-
- cdef DBusMessage *_get_msg(self):
- return self.msg
-
- def get_iter(self, append=False):
- cdef DBusMessageIter iter
- cdef MessageIter message_iter
- cdef DBusMessage *msg
-
- msg = self._get_msg()
-
- if append:
- dbus_message_iter_init_append(msg, &iter)
- else:
- dbus_message_iter_init(msg, &iter)
-
- message_iter = MessageIter(0)
- message_iter.__cinit__(&iter)
-
- return message_iter
-
- def get_args_list(self):
- retval = [ ]
-
- iter = self.get_iter()
- try:
- retval.append(iter.get())
- except TypeError, e:
- return [ ]
-
- value_at_iter = iter.next()
- while (value_at_iter):
- retval.append(iter.get())
- value_at_iter = iter.next()
-
- return retval
-
- # FIXME: implement dbus_message_copy?
-
- def get_type(self):
- return dbus_message_get_type(self.msg)
-
- def set_path(self, object_path):
- return dbus_message_set_path(self.msg, object_path)
-
- def get_path(self):
- return dbus_message_get_path(self.msg)
-
- def set_interface(self, interface):
- return dbus_message_set_interface(self.msg, interface)
-
- def get_interface(self):
- return dbus_message_get_interface(self.msg)
-
- def set_member(self, member):
- return dbus_message_set_member(self.msg, member)
-
- def get_member(self):
- return dbus_message_get_member(self.msg)
-
- def set_error_name(self, name):
- return dbus_message_set_error_name(self.msg, name)
-
- def get_error_name(self):
- return dbus_message_get_error_name(self.msg)
-
- def set_destination(self, destination):
- return dbus_message_set_destination(self.msg, destination)
-
- def get_destination(self):
- return dbus_message_get_destination(self.msg)
-
- def set_sender(self, sender):
- return dbus_message_set_sender(self.msg, sender)
-
- def get_sender(self):
- cdef char *sender
- sender = dbus_message_get_sender(self.msg)
- if (sender == NULL):
- return None
- else:
- return sender
-
- def set_no_reply(self, no_reply):
- dbus_message_set_no_reply(self.msg, no_reply)
-
- def get_no_reply(self):
- return dbus_message_get_no_reply(self.msg)
-
- def is_method_call(self, interface, method):
- return dbus_message_is_method_call(self.msg, interface, method)
-
- def is_signal(self, interface, signal_name):
- return dbus_message_is_signal(self.msg, interface, signal_name)
-
- def is_error(self, error_name):
- return dbus_message_is_error(self.msg, error_name)
-
- def has_destination(self, service):
- return dbus_message_has_destination(self.msg, service)
-
- def has_sender(self, service):
- return dbus_message_has_sender(self.msg, service)
-
- def get_serial(self):
- return dbus_message_get_serial(self.msg)
-
- def set_reply_serial(self, reply_serial):
- return dbus_message_set_reply_serial(self.msg, reply_serial)
-
- def get_reply_serial(self):
- return dbus_message_get_reply_serial(self.msg)
-
- #FIXME: dbus_message_get_path_decomposed
-
- # FIXME: all the different dbus_message_*args* methods
-
-class Signal(Message):
- def __init__(self, spath, sinterface, sname):
- Message.__init__(self, MESSAGE_TYPE_SIGNAL, path=spath, dbus_interface=sinterface, name=sname)
-
-class EmptyMessage(Message):
- def __init__(self):
- Message.__init__(self, _create=False)
-
-class MethodCall(Message):
- def __init__(self, mpath, minterface, mmethod):
- Message.__init__(self, MESSAGE_TYPE_METHOD_CALL, path=mpath, dbus_interface=minterface, method=mmethod)
-
-class MethodReturn(Message):
- def __init__(self, method_call):
- Message.__init__(self, MESSAGE_TYPE_METHOD_RETURN, method_call=method_call)
-
-class Error(Message):
- def __init__(self, reply_to, error_name, error_message):
- Message.__init__(self, MESSAGE_TYPE_ERROR, reply_to=reply_to, error_name=error_name, error_message=error_message)
-
-cdef class Server:
- cdef DBusServer *server
- def __init__(self, address):
- cdef DBusError error
- dbus_error_init(&error)
- self.server = dbus_server_listen(address,
- &error)
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free (&error)
- raise DBusException, errormsg
-
- def disconnect(self):
- dbus_server_disconnect(self.server)
-
- def get_is_connected(self):
- return dbus_server_get_is_connected(self.server)
-
-# def set_new_connection_function(self, function, data):
-# dbus_server_set_new_connection_function(self.conn, function,
-# data, NULL)
-
-# def set_watch_functions(self, add_function, remove_function, data):
-# dbus_server_set_watch_functions(self.server,
-# add_function, remove_function,
-# data, NULL)
-
-# def set_timeout_functions(self, add_function, remove_function, data):
-# dbus_server_set_timeout_functions(self.server,
-# add_function, remove_function,
-# data, NULL)
-
-# def handle_watch(self, watch, condition):
-# dbus_server_handle_watch(self.conn, watch, condition)
-
-BUS_SESSION = DBUS_BUS_SESSION
-BUS_SYSTEM = DBUS_BUS_SYSTEM
-BUS_STARTER = DBUS_BUS_STARTER
-
-def bus_get (bus_type, private=False):
- cdef DBusError error
- cdef Connection conn
- cdef DBusConnection *connection
-
- dbus_error_init(&error)
- if private:
- connection = dbus_bus_get_private(bus_type,
- &error)
- else:
- connection = dbus_bus_get(bus_type,
- &error)
-
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
- conn = Connection()
- conn.__cinit__(None, connection)
- return conn
-
-def bus_get_unique_name(Connection connection):
- cdef DBusConnection *conn
- conn = connection._get_conn()
- return dbus_bus_get_unique_name(conn)
-
-def bus_get_unix_user(Connection connection, service_name):
- cdef DBusError error
- dbus_error_init(&error)
- cdef int retval
- cdef DBusConnection *conn
-
- conn = connection._get_conn()
- retval = dbus_bus_get_unix_user(conn, service_name, &error)
-
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
- return retval
-
-# these are defines, not enums, so they aren't auto generated
-DBUS_START_REPLY_SUCCESS = 0
-DBUS_START_REPLY_ALREADY_RUNNING = 1
-
-def bus_start_service_by_name(Connection connection, service_name, flags=0):
- cdef DBusError error
- dbus_error_init(&error)
- cdef dbus_bool_t retval
- cdef dbus_uint32_t results
- cdef DBusConnection *conn
-
- conn = connection._get_conn()
-
- retval = dbus_bus_start_service_by_name(conn, service_name, flags, &results, &error)
-
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
- return (retval, results)
-
-def bus_register(Connection connection):
- cdef DBusError error
- dbus_error_init(&error)
- cdef dbus_bool_t retval
- cdef DBusConnection *conn
-
- conn = connection._get_conn()
- retval = dbus_bus_register(conn,
- &error)
- if dbus_error_is_set(&error):
- msg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
- return retval
-
-NAME_FLAG_ALLOW_REPLACEMENT = 0x1
-NAME_FLAG_REPLACE_EXISTING = 0x2
-NAME_FLAG_DO_NOT_QUEUE = 0x4
-
-REQUEST_NAME_REPLY_PRIMARY_OWNER = 1
-REQUEST_NAME_REPLY_IN_QUEUE = 2
-REQUEST_NAME_REPLY_EXISTS = 3
-REQUEST_NAME_REPLY_ALREADY_OWNER = 4
-
-def bus_request_name(Connection connection, service_name, flags=0):
- cdef DBusError error
- dbus_error_init(&error)
- cdef int retval
- cdef DBusConnection *conn
-
- conn = connection._get_conn()
- retval = dbus_bus_request_name(conn,
- service_name,
- flags,
- &error)
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
- return retval
-
-RELEASE_NAME_REPLY_RELEASED = 1
-RELEASE_NAME_REPLY_NON_EXISTENT = 2
-RELEASE_NAME_REPLY_NOT_OWNER = 3
-
-def bus_release_name(Connection connection, service_name):
- cdef DBusError error
- dbus_error_init(&error)
- cdef int retval
- cdef DBusConnection *conn
-
- conn = connection._get_conn()
- retval = dbus_bus_release_name(conn,
- service_name,
- &error)
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
- return retval
-
-def bus_name_has_owner(Connection connection, service_name):
- cdef DBusError error
- dbus_error_init(&error)
- cdef dbus_bool_t retval
- cdef DBusConnection *conn
-
- conn = connection._get_conn()
- retval = dbus_bus_name_has_owner(conn,
- service_name,
- &error)
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
- return retval
-
-def bus_add_match(Connection connection, rule):
- cdef DBusError error
- cdef DBusConnection *conn
-
- dbus_error_init(&error)
-
- conn = connection._get_conn()
- dbus_bus_add_match (conn, rule, &error)
-
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
-def bus_remove_match(Connection connection, rule):
- cdef DBusError error
- cdef DBusConnection *conn
-
- dbus_error_init(&error)
-
- conn = connection._get_conn()
- dbus_bus_remove_match (conn, rule, &error)
-
- if dbus_error_is_set(&error):
- errormsg = error.message
- dbus_error_free(&error)
- raise DBusException, errormsg
-
diff --git a/python/dbus_glib_bindings.pyx b/python/dbus_glib_bindings.pyx
deleted file mode 100644
index 3e2e33bd..00000000
--- a/python/dbus_glib_bindings.pyx
+++ /dev/null
@@ -1,17 +0,0 @@
-cimport dbus_bindings
-import dbus_bindings
-
-cdef extern from "dbus-glib.h":
- ctypedef struct GMainContext
- cdef void dbus_g_thread_init ()
-
-cdef extern from "dbus-glib-lowlevel.h":
- cdef void dbus_connection_setup_with_g_main (dbus_bindings.DBusConnection *connection,
- GMainContext *context)
-def setup_with_g_main(conn):
- cdef dbus_bindings.Connection connection
- connection = conn
- dbus_connection_setup_with_g_main(connection._get_conn(), NULL)
-
-def gthreads_init ():
- dbus_g_thread_init ()
diff --git a/python/dbus_h_wrapper.h b/python/dbus_h_wrapper.h
deleted file mode 100644
index 2e218c8c..00000000
--- a/python/dbus_h_wrapper.h
+++ /dev/null
@@ -1,3 +0,0 @@
-#define DBUS_API_SUBJECT_TO_CHANGE 1
-#include <dbus/dbus.h>
-
diff --git a/python/decorators.py b/python/decorators.py
deleted file mode 100644
index c9bc17fa..00000000
--- a/python/decorators.py
+++ /dev/null
@@ -1,83 +0,0 @@
-import _util
-import inspect
-import dbus_bindings
-
-def method(dbus_interface, in_signature=None, out_signature=None, async_callbacks=None, sender_keyword=None):
- _util._validate_interface_or_name(dbus_interface)
-
- def decorator(func):
- args = inspect.getargspec(func)[0]
- args.pop(0)
-
- if async_callbacks:
- if type(async_callbacks) != tuple:
- raise TypeError('async_callbacks must be a tuple of (keyword for return callback, keyword for error callback)')
- if len(async_callbacks) != 2:
- raise ValueError('async_callbacks must be a tuple of (keyword for return callback, keyword for error callback)')
- args.remove(async_callbacks[0])
- args.remove(async_callbacks[1])
-
- if sender_keyword:
- args.remove(sender_keyword)
-
- if in_signature:
- in_sig = tuple(dbus_bindings.Signature(in_signature))
-
- if len(in_sig) > len(args):
- raise ValueError, 'input signature is longer than the number of arguments taken'
- elif len(in_sig) < len(args):
- raise ValueError, 'input signature is shorter than the number of arguments taken'
-
- func._dbus_is_method = True
- func._dbus_async_callbacks = async_callbacks
- func._dbus_interface = dbus_interface
- func._dbus_in_signature = in_signature
- func._dbus_out_signature = out_signature
- func._dbus_sender_keyword = sender_keyword
- func._dbus_args = args
- return func
-
- return decorator
-
-def signal(dbus_interface, signature=None):
- _util._validate_interface_or_name(dbus_interface)
- def decorator(func):
- def emit_signal(self, *args, **keywords):
- func(self, *args, **keywords)
- message = dbus_bindings.Signal(self._object_path, dbus_interface, func.__name__)
- iter = message.get_iter(True)
-
- if emit_signal._dbus_signature:
- signature = tuple(dbus_bindings.Signature(emit_signal._dbus_signature))
- for (arg, sig) in zip(args, signature):
- iter.append_strict(arg, sig)
- else:
- for arg in args:
- iter.append(arg)
-
- self._connection.send(message)
-
- args = inspect.getargspec(func)[0]
- args.pop(0)
-
- if signature:
- sig = tuple(dbus_bindings.Signature(signature))
-
- if len(sig) > len(args):
- raise ValueError, 'signal signature is longer than the number of arguments provided'
- elif len(sig) < len(args):
- raise ValueError, 'signal signature is shorter than the number of arguments provided'
-
- emit_signal.__name__ = func.__name__
- emit_signal.__doc__ = func.__doc__
- emit_signal._dbus_is_signal = True
- emit_signal._dbus_interface = dbus_interface
- emit_signal._dbus_signature = signature
- emit_signal._dbus_args = args
- return emit_signal
-
- return decorator
-
-def explicitly_pass_message(func):
- func._dbus_pass_message = True
- return func
diff --git a/python/examples/.cvsignore b/python/examples/.cvsignore
deleted file mode 100644
index 282522db..00000000
--- a/python/examples/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Makefile
-Makefile.in
diff --git a/python/examples/Makefile.am b/python/examples/Makefile.am
deleted file mode 100644
index f7a1b22e..00000000
--- a/python/examples/Makefile.am
+++ /dev/null
@@ -1,13 +0,0 @@
-NULL=
-
-EXTRA_DIST = \
- example-service.py \
- example-client.py \
- example-signal-emitter.py \
- example-signal-recipient.py \
- gconf-proxy-client.py \
- gconf-proxy-service.py \
- gconf-proxy-service2.py \
- list-system-services.py \
- $(NULL)
-
diff --git a/python/examples/example-client.py b/python/examples/example-client.py
deleted file mode 100644
index 3d170bd4..00000000
--- a/python/examples/example-client.py
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/usr/bin/env python
-
-import dbus
-
-bus = dbus.SessionBus()
-remote_object = bus.get_object("org.designfu.SampleService", "/SomeObject")
-iface = dbus.Interface(remote_object, "org.designfu.SampleInterface")
-
-hello_reply_list = remote_object.HelloWorld("Hello from example-client.py!", dbus_interface = "org.designfu.SampleInterface")
-
-hello_reply_tuple = iface.GetTuple()
-
-hello_reply_dict = iface.GetDict()
-
-print (hello_reply_list)
-
-print str(hello_reply_tuple)
-
-print str(hello_reply_dict)
-
-print remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
-
diff --git a/python/examples/example-service.py b/python/examples/example-service.py
deleted file mode 100644
index cb25d203..00000000
--- a/python/examples/example-service.py
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/env python
-
-import dbus
-import dbus.service
-import dbus.glib
-import gobject
-
-class SomeObject(dbus.service.Object):
- def __init__(self, bus_name, object_path="/SomeObject"):
- dbus.service.Object.__init__(self, bus_name, object_path)
-
- @dbus.service.method("org.designfu.SampleInterface")
- def HelloWorld(self, hello_message):
- print (str(hello_message))
- return ["Hello", " from example-service.py"]
-
- @dbus.service.method("org.designfu.SampleInterface")
- def GetTuple(self):
- return ("Hello Tuple", " from example-service.py")
-
- @dbus.service.method("org.designfu.SampleInterface")
- def GetDict(self):
- return {"first": "Hello Dict", "second": " from example-service.py"}
-
-session_bus = dbus.SessionBus()
-name = dbus.service.BusName("org.designfu.SampleService", bus=session_bus)
-object = SomeObject(name)
-
-mainloop = gobject.MainLoop()
-mainloop.run()
diff --git a/python/examples/example-signal-emitter.py b/python/examples/example-signal-emitter.py
deleted file mode 100644
index 02eff893..00000000
--- a/python/examples/example-signal-emitter.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env python
-
-import dbus
-import dbus.service
-import dbus.glib
-import gobject
-
-class TestObject(dbus.service.Object):
- def __init__(self, bus_name, object_path='/org/designfu/TestService/object'):
- dbus.service.Object.__init__(self, bus_name, object_path)
-
- @dbus.service.signal('org.designfu.TestService')
- def HelloSignal(self, message):
- # The signal is emitted when this method exits
- # You can have code here if you wish
- pass
-
- @dbus.service.method('org.designfu.TestService')
- def emitHelloSignal(self):
- #you emit signals by calling the signal's skeleton method
- self.HelloSignal('Hello')
- return 'Signal emitted'
-
-session_bus = dbus.SessionBus()
-name = dbus.service.BusName('org.designfu.TestService', bus=session_bus)
-object = TestObject(name)
-
-loop = gobject.MainLoop()
-loop.run()
diff --git a/python/examples/example-signal-recipient.py b/python/examples/example-signal-recipient.py
deleted file mode 100644
index a06d4943..00000000
--- a/python/examples/example-signal-recipient.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python
-
-import dbus
-import dbus.decorators
-import dbus.glib
-import gobject
-
-def handle_reply(msg):
- print msg
-
-def handle_error(e):
- print str(e)
-
-def emit_signal():
- #call the emitHelloSignal method
- object.emitHelloSignal(dbus_interface="org.designfu.TestService")
- #reply_handler = handle_reply, error_handler = handle_error)
- return True
-
-bus = dbus.SessionBus()
-object = bus.get_object("org.designfu.TestService","/org/designfu/TestService/object")
-
-def hello_signal_handler(hello_string):
- print ("Received signal and it says: " + hello_string)
-
-@dbus.decorators.explicitly_pass_message
-def catchall_signal_handler(*args, **keywords):
- #The dbus.handler directive passes in the special __dbus_message__ variable
- dbus_message = keywords["dbus_message"]
- print "Caught signal " + dbus_message.get_member()
- for arg in args:
- print " " + str(arg)
-
-def catchall_hello_signals_handler(hello_string):
- print ("Received a hello signal and it says ") + hello_string
-
-@dbus.decorators.explicitly_pass_message
-def catchall_testservice_interface_handler(hello_string, dbus_message):
- print "org.designfu.TestService interface says " + hello_string + " when it sent signal " + dbus_message.get_member()
-
-object.connect_to_signal("HelloSignal", hello_signal_handler, dbus_interface="org.designfu.TestService", arg0="Hello")
-
-#lets make a catchall
-bus.add_signal_receiver(catchall_signal_handler)
-bus.add_signal_receiver(catchall_hello_signals_handler, dbus_interface = "org.designfu.TestService", signal_name = "HelloSignal")
-bus.add_signal_receiver(catchall_testservice_interface_handler, dbus_interface = "org.designfu.TestService")
-
-
-gobject.timeout_add(2000, emit_signal)
-
-# Tell the remote object to emit the signal
-
-loop = gobject.MainLoop()
-loop.run()
diff --git a/python/examples/gconf-proxy-client.py b/python/examples/gconf-proxy-client.py
deleted file mode 100644
index f763e3fa..00000000
--- a/python/examples/gconf-proxy-client.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python
-
-import dbus
-
-gconf_key = "/desktop/gnome/file_views/icon_theme"
-
-bus = dbus.SessionBus()
-gconf_service = bus.get_service("org.gnome.GConf")
-gconf_key_object = gconf_service.get_object("/org/gnome/GConf" + gconf_key, "org.gnome.GConf")
-
-value = gconf_key_object.getString()
-
-print ("Value of GConf key %s is %s" % (gconf_key, value))
diff --git a/python/examples/gconf-proxy-service.py b/python/examples/gconf-proxy-service.py
deleted file mode 100644
index a899cf21..00000000
--- a/python/examples/gconf-proxy-service.py
+++ /dev/null
@@ -1,43 +0,0 @@
-#!/usr/bin/env python
-#FIXME: Doesn't work with the new bindings
-import dbus
-
-import gobject
-import gconf
-
-class GConfService(dbus.Service):
-
- def __init__(self):
- dbus.Service.__init__(self, "org.gnome.GConf", dbus.SessionBus())
-
- gconf_object_tree = self.GConfObjectTree(self)
-
- class GConfObjectTree(dbus.ObjectTree):
- def __init__(self, service):
- dbus.ObjectTree.__init__(self, "/org/gnome/GConf", service, dbus_methods=[ self.getString, self.setString, self.getInt, self.setInt ])
-
- self.client = gconf.client_get_default()
-
- def getString(self, message, object_path):
- print ("getString called on GConf key %s" % (object_path))
- return self.client.get_string(object_path)
-
- def setString(self, message, object_path, new_value):
- print ("setString called on GConf key %s" % (object_path))
- self.client.set_string(object_path, new_value)
-
- def getInt(self, message, object_path):
- print ("getInt called on GConf key %s" % (object_path))
- return self.client.get_int(object_path)
-
- def setInt(self, message, object_path, new_value):
- print ("setInt called on GConf key %s" % (object_path))
- self.client.set_int(object_path, new_value)
-
-gconf_service = GConfService()
-
-print ("GConf Proxy service started.")
-print ("Run 'gconf-proxy-client.py' to fetch a GConf key through the proxy...")
-
-mainloop = gobject.MainLoop()
-mainloop.run()
diff --git a/python/examples/gconf-proxy-service2.py b/python/examples/gconf-proxy-service2.py
deleted file mode 100644
index 5731ab28..00000000
--- a/python/examples/gconf-proxy-service2.py
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env python
-#FIXME: doesn't work with the new bindings
-import dbus
-
-import gobject
-import gconf
-
-class GConfService(dbus.Service):
-
- def __init__(self):
- dbus.Service.__init__(self, "org.gnome.GConf", dbus.SessionBus())
-
- gconf_object_tree = self.GConfObjectTree(self)
-
- class GConfObjectTree(dbus.ObjectTree):
- def __init__(self, service):
- dbus.ObjectTree.__init__(self, "/org/gnome/GConf", service)
-
- self.client = gconf.client_get_default()
-
- def object_method_called(self, message, object_path, method_name, argument_list):
- print ("Method %s called on GConf key %s" % (method_name, object_path))
-
- if "getString" == method_name:
- return self.client.get_string(object_path)
- elif "setString" == method_name:
- self.client.set_int(object_path, argument_list[0])
- elif "getInt" == method_name:
- return self.client.get_int(object_path)
- elif "setInt" == method_name:
- self.client.set_int(object_path, argument_list[0])
-
-gconf_service = GConfService()
-
-print ("GConf Proxy service started.")
-print ("Run 'gconf-proxy-client.py' to fetch a GConf key through the proxy...")
-
-mainloop = gobject.MainLoop()
-mainloop.run()
diff --git a/python/examples/list-system-services.py b/python/examples/list-system-services.py
deleted file mode 100644
index 4cad8717..00000000
--- a/python/examples/list-system-services.py
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/usr/bin/env python
-
-"""Lists services on the system bus
-"""
-
-import dbus
-
-# Get a connection to the SYSTEM bus
-bus = dbus.SystemBus()
-
-# Get a reference to the desktop bus' standard object, denoted
-# by the path /org/freedesktop/DBus.
-dbus_object = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
-
-# The object /org/freedesktop/DBus
-# implements the 'org.freedesktop.DBus' interface
-dbus_iface = dbus.Interface(dbus_object, 'org.freedesktop.DBus')
-
-# One of the member functions in the org.freedesktop.DBus interface
-# is ListServices(), which provides a list of all the other services
-# registered on this bus. Call it, and print the list.
-print dbus_object.ListNames()
diff --git a/python/exceptions.py b/python/exceptions.py
deleted file mode 100644
index 2b01b96e..00000000
--- a/python/exceptions.py
+++ /dev/null
@@ -1,29 +0,0 @@
-import dbus_bindings
-
-DBusException = dbus_bindings.DBusException
-ConnectionError = dbus_bindings.ConnectionError
-
-class MissingErrorHandlerException(DBusException):
- def __init__(self):
- DBusException.__init__(self, "error_handler not defined: if you define a reply_handler you must also define an error_handler")
-
-class MissingReplyHandlerException(DBusException):
- def __init__(self):
- DBusException.__init__(self, "reply_handler not defined: if you define an error_handler you must also define a reply_handler")
-
-class ValidationException(DBusException):
- def __init__(self, msg=''):
- DBusException.__init__(self, "Error validating string: %s"%msg)
-
-class IntrospectionParserException(DBusException):
- def __init__(self, msg=''):
- DBusException.__init__(self, "Error parsing introspect data: %s"%msg)
-
-class UnknownMethodException(DBusException):
- def __init__(self, method):
- DBusException.__init__(self, "Unknown method: %s"%method)
-
-class NameExistsException(DBusException):
- def __init__(self, name):
- DBusException.__init__(self, "Bus name already exists: %s"%name)
-
diff --git a/python/extract.py b/python/extract.py
deleted file mode 100644
index 3cdb9755..00000000
--- a/python/extract.py
+++ /dev/null
@@ -1,234 +0,0 @@
-import commands
-import re
-import string
-import sys
-
-def clean_func(buf):
- buf = strip_comments(buf)
- pat = re.compile(r"""\\\n""", re.MULTILINE)
- buf = pat.sub('',buf)
- pat = re.compile(r"""^[#].*?$""", re.MULTILINE)
- buf = pat.sub('',buf)
- pat = re.compile(r"""^(typedef|struct|enum)(\s|.|\n)*?;\s*""", re.MULTILINE)
- buf = pat.sub('',buf)
- pat = re.compile(r"""\s+""", re.MULTILINE)
- buf = pat.sub(' ',buf)
- pat = re.compile(r""";\s*""", re.MULTILINE)
- buf = pat.sub('\n',buf)
- buf = buf.lstrip()
- #pat=re.compile(r'\s+([*|&]+)\s*(\w+)')
- pat = re.compile(r' \s+ ([*|&]+) \s* (\w+)',re.VERBOSE)
- buf = pat.sub(r'\1 \2', buf)
- pat = re.compile(r'\s+ (\w+) \[ \s* \]',re.VERBOSE)
- buf = pat.sub(r'[] \1', buf)
-# buf = string.replace(buf, 'G_CONST_RETURN ', 'const-')
- buf = string.replace(buf, 'const ', '')
- return buf
-
-def strip_comments(buf):
- parts = []
- lastpos = 0
- while 1:
- pos = string.find(buf, '/*', lastpos)
- if pos >= 0:
- parts.append(buf[lastpos:pos])
- pos = string.find(buf, '*/', pos)
- if pos >= 0:
- lastpos = pos + 2
- else:
- break
- else:
- parts.append(buf[lastpos:])
- break
- return string.join(parts, '')
-
-def find_enums(buf):
- enums = []
- buf = strip_comments(buf)
- buf = re.sub('\n', ' ', buf)
-
- enum_pat = re.compile(r'enum\s*{([^}]*)}\s*([A-Z][A-Za-z]*)(\s|;)')
- splitter = re.compile(r'\s*,\s', re.MULTILINE)
- pos = 0
- while pos < len(buf):
- m = enum_pat.search(buf, pos)
- if not m: break
-
- name = m.group(2)
- vals = m.group(1)
- isflags = string.find(vals, '<<') >= 0
- entries = []
- for val in splitter.split(vals):
- if not string.strip(val): continue
- entries.append(string.split(val)[0])
- enums.append((name, isflags, entries))
-
- pos = m.end()
- return enums
-
-#typedef unsigned int dbus_bool_t;
-#typedef struct {
-#
-# }
-#typedef struct FooStruct FooStruct;
-# typedef void (* DBusAddWatchFunction) (DBusWatch *watch,
-# void *data);
-
-def find_typedefs(buf):
- typedefs = []
- buf = re.sub('\n', ' ', strip_comments(buf))
- typedef_pat = re.compile(
- r"""typedef\s*(?P<type>\w*)
- \s*
- ([(]\s*\*\s*(?P<callback>[\w* ]*)[)]|{([^}]*)}|)
- \s*
- (?P<args1>[(](?P<args2>[\s\w*,_]*)[)]|[\w ]*)""",
- re.MULTILINE | re.VERBOSE)
- pat = re.compile(r"""\s+""", re.MULTILINE)
- pos = 0
- while pos < len(buf):
- m = typedef_pat.search(buf, pos)
- if not m:
- break
- if m.group('type') == 'enum':
- pos = m.end()
- continue
- if m.group('args2') != None:
- args = pat.sub(' ', m.group('args2'))
-
- current = '%s (* %s) (%s)' % (m.group('type'),
- m.group('callback'),
- args)
- else:
- current = '%s %s' % (m.group('type'), m.group('args1'))
- typedefs.append(current)
- pos = m.end()
- return typedefs
-
-proto_pat = re.compile(r"""
-(?P<ret>(-|\w|\&|\*|\s)+\s*) # return type
-\s+ # skip whitespace
-(?P<func>\w+)\s*[(] # match the function name until the opening (
-(?P<args>.*?)[)] # group the function arguments
-""", re.IGNORECASE|re.VERBOSE)
-arg_split_pat = re.compile("\s*,\s*")
-
-
-def find_functions(buf):
- functions = []
- buf = clean_func(buf)
- buf = string.split(buf,'\n')
- for p in buf:
- if len(p) == 0:
- continue
- m = proto_pat.match(p)
- if m == None:
- continue
-
- func = m.group('func')
- ret = m.group('ret')
- args = m.group('args')
- args = arg_split_pat.split(args)
-# for i in range(len(args)):
-# spaces = string.count(args[i], ' ')
-# if spaces > 1:
-# args[i] = string.replace(args[i], ' ', '-', spaces - 1)
-
- functions.append((func, ret, args))
- return functions
-
-class Writer:
- def __init__(self, filename, enums, typedefs, functions):
- if not (enums or typedefs or functions):
- return
- print 'cdef extern from "%s":' % filename
-
- self.output_enums(enums)
- self.output_typedefs(typedefs)
- self.output_functions(functions)
-
- print ' pass'
- print
-
- def output_enums(self, enums):
- for enum in enums:
- print ' ctypedef enum %s:' % enum[0]
- if enum[1] == 0:
- for item in enum[2]:
- print ' %s' % item
- else:
- i = 0
- for item in enum[2]:
- print ' %s' % item
-# print ' %s = 1 << %d' % (item, i)
- i += 1
- print
- def output_typedefs(self, typedefs):
- for typedef in typedefs:
- if typedef.find('va_list') != -1:
- continue
-
- parts = typedef.split()
- if parts[0] == 'struct':
- if parts[-2] == parts[-1]:
- parts = parts[:-1]
- print ' ctypedef %s' % ' '.join(parts)
- else:
- print ' ctypedef %s' % typedef
-
- def output_functions(self, functions):
- for func, ret, args in functions:
- if func[0] == '_':
- continue
-
- str = ', '.join(args)
- if str.find('...') != -1:
- continue
- if str.find('va_list') != -1:
- continue
- if str.strip() == 'void':
- continue
- print ' %-20s %s (%s)' % (ret, func, str)
-
-def do_buffer(name, buffer):
- functions = find_functions(buffer)
- typedefs = find_typedefs(buffer)
- enums = find_enums(buffer)
-
- Writer(name, enums, typedefs, functions)
-
-def do_header(filename, name=None):
- if name == None:
- name = filename
-
- buffer = ""
- for line in open(filename).readlines():
- if line[0] == '#':
- continue
- buffer += line
-
- print '# -- %s -- ' % filename
- do_buffer(name, buffer)
-
-filename = sys.argv[1]
-
-if filename.endswith('.h'):
- do_header(filename)
- raise SystemExit
-
-cppflags = ""
-
-for flag in sys.argv[2:]:
- cppflags = cppflags + " " + flag
-
-fd = open(filename)
-
-for line in fd.readlines():
- if line.startswith('#include'):
- filename = line.split(' ')[1][1:-2]
- command = "echo '%s'|cpp %s" % (line, cppflags)
- sys.stderr.write('running %s' % (command))
- output = commands.getoutput(command)
- do_buffer(filename, output)
- else:
- print line[:-1]
diff --git a/python/glib.py b/python/glib.py
deleted file mode 100644
index e1c3d9ca..00000000
--- a/python/glib.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import dbus
-import dbus_glib_bindings
-
-def _setup_with_g_main(conn):
- dbus_glib_bindings.setup_with_g_main(conn._connection)
-
-_dbus_gthreads_initialized = False
-def threads_init():
- global _dbus_gthreads_initialized
- if not _dbus_gthreads_initialized:
- dbus_glib_bindings.gthreads_init()
- _dbus_gthreads_initialized = True
-
-def init_threads():
- threads_init()
-
-setattr(dbus, "_dbus_mainloop_setup_function", _setup_with_g_main)
diff --git a/python/introspect_parser.py b/python/introspect_parser.py
deleted file mode 100644
index 47c9806e..00000000
--- a/python/introspect_parser.py
+++ /dev/null
@@ -1,51 +0,0 @@
-import libxml2
-import cStringIO
-import exceptions
-
-def process_introspection_data(data):
- method_map = {}
-
- XMLREADER_START_ELEMENT_NODE_TYPE = 1
- XMLREADER_END_ELEMENT_NODE_TYPE = 15
-
- stream = cStringIO.StringIO(data.encode('utf-8'))
- input_source = libxml2.inputBuffer(stream)
- reader = input_source.newTextReader("urn:introspect")
-
- ret = reader.Read()
- current_iface = None
- current_method = None
- current_sigstr = ''
-
- while ret == 1:
- name = reader.LocalName()
- if reader.NodeType() == XMLREADER_START_ELEMENT_NODE_TYPE:
- if (not current_iface and not current_method and name == 'interface'):
- current_iface = reader.GetAttribute('name')
- elif (current_iface and not current_method and name == 'method'):
- current_method = reader.GetAttribute('name')
- if reader.IsEmptyElement():
- method_map[current_iface + '.' + current_method] = ''
- current_method = None
- current_sigstr = ''
-
- elif (current_iface and current_method and name == 'arg'):
- direction = reader.GetAttribute('direction')
-
- if not direction or direction == 'in':
- current_sigstr = current_sigstr + reader.GetAttribute('type')
-
- elif reader.NodeType() == XMLREADER_END_ELEMENT_NODE_TYPE:
- if (current_iface and not current_method and name == 'interface'):
- current_iface = None
- if (current_iface and current_method and name == 'method'):
- method_map[current_iface + '.' + current_method] = current_sigstr
- current_method = None
- current_sigstr = ''
-
- ret = reader.Read()
-
- if ret != 0:
- raise exceptions.IntrospectionParserException(data)
-
- return method_map
diff --git a/python/matchrules.py b/python/matchrules.py
deleted file mode 100644
index 023a5b76..00000000
--- a/python/matchrules.py
+++ /dev/null
@@ -1,232 +0,0 @@
-from exceptions import DBusException
-
-class SignalMatchNode:
- def __init__(self):
- self.wildcard = None
- self.finite = {}
- self.rules = []
-
- def add(self, key, leaf=None):
- node = None
-
- if key:
- if self.finite.has_key(key):
- node = self.finite[key]
- else:
- node = SignalMatchNode()
- self.finite[key] = node
- else:
- if self.wildcard:
- node = self.wildcard
- else:
- node = SignalMatchNode()
- self.wildcard = node
-
- node.rules.append(leaf)
- return node
-
- def get_matches(self, key):
- result = []
- if self.wildcard:
- result.append(self.wildcard)
-
- if self.finite.has_key(key):
- result.append(self.finite[key])
-
- return result
-
- def get_match(self, key):
- if key:
- if self.finite.has_key(key):
- return self.finite[key]
- else:
- return None
-
- return self.wildcard
-
- def has_children(self):
- if self.wildcard or len(self.finite.iterkeys()) > 0:
- return True
- return False
-
- def remove_child(self, child, key=None):
- if self.wildcard == child:
- self.wildcard = None
- elif self.finite.has_key(key):
- del self.finite[key]
-
-class SignalMatchTree:
- """This class creates an ordered tree of SignalMatchRules
- to speed searchs. Left branches are wildcard elements
- and all other branches are concreet elements.
- """
- def __init__(self):
- self._tree = SignalMatchNode()
-
- def add(self, rule):
- interface = self._tree.add(rule.sender)
- signal = interface.add(rule.dbus_interface)
- path = signal.add(rule.signal_name)
- path.add(rule.path, leaf=rule)
-
- def exec_matches(self, match_rule, message):
- args = message.get_args_list()
-
- sender_matches = self._tree.get_matches(match_rule.sender)
- for sender_node in sender_matches:
- interface_matches = sender_node.get_matches(match_rule.dbus_interface)
- for interface_node in interface_matches:
- signal_matches = interface_node.get_matches(match_rule.signal_name)
- for signal_node in signal_matches:
- path_matches = signal_node.get_matches(match_rule.path)
- for path_node in path_matches:
- if(path_node.rules):
- for rule in path_node.rules:
- if (rule.match_args_from_list(args)):
- rule.execute(message, args)
-
- def remove(self, rule):
- try:
- sender = self._tree.get_match(rule.sender)
- interface = sender.get_match(rule.dbus_interface)
- signal = interface.get_match(rule.signal_name)
- path = signal.get_match(rule.path)
-
- rule_matches = []
- for _rule in path.rules:
- if _rule.is_match(rule):
- rule_matches.append(_rule)
-
- for _rule in rule_matches:
- path.rules.remove(_rule)
-
- #clean up tree
- if len(path.rules) == 0:
- signal.remove_child(path, key = rule.path)
- if not signal.has_children():
- interface.remove_child(signal, key = rule.signal_name)
- if not interface.has_children():
- sender.remove_child(interface, key = rule.dbus_interface)
- if not sender.has_children():
- self._tree.remove_child(sender, key = rule.sender)
-
- except:
- raise DBusException ("Trying to remove unkown rule: %s"%str(rule))
-
-class SignalMatchRule:
- """This class represents a dbus rule used to filter signals.
- When a rule matches a filter, the signal is propagated to the handler_funtions
- """
- def __init__(self, signal_name, dbus_interface, sender, path):
- self.handler_functions = []
-
- self.signal_name = signal_name
- self.dbus_interface = dbus_interface
- self.sender = sender
- self.path = path
- self.args = None
-
- def add_args_match(self, args):
- self.args = args
-
- def execute(self, message, args=None):
- keywords = {}
-
- if self.sender_keyword is not None:
- keywords[self.sender_keyword] = message.get_sender()
- if self.path_keyword is not None:
- keywords[self.path_keyword] = message.get_path()
-
- # optimization just in case we already extracted the args
- if not args:
- args = message.get_args_list()
-
- for handler in self.handler_functions:
- if getattr(handler, "_dbus_pass_message", False):
- keywords["dbus_message"] = message
-
- if len(keywords) == 0:
- handler(*args)
- else:
- handler(*args, **keywords)
-
- def add_handler(self, handler):
- self.handler_functions.append(handler)
-
- #matches only those arguments listed by self
- def match_args_from_list(self, args_list):
- if not self.args:
- return True
-
- last_index = len(args_list) - 1
- for (index, value) in self.args.iteritems():
- if index > last_index:
- return False
-
- if not (args_list[index] == value):
- return False
-
- return True
-
- #does exact matching
- def match_args_from_rule(self, rule):
- if self.args == rule.args:
- return True
-
- if self.args == None or rule.args == None:
- return False
-
- my_args_list = self.args.items()
- match_args_list = rule.args.iterms()
-
- if len(my_args_list) != len(match_args_list):
- return False
-
- for (key, value) in my_args_list:
- if rule.args.get(key) != value:
- return False
-
- return True
-
- def is_match(self, rule):
- if (self.signal_name == rule.signal_name and
- self.dbus_interface == rule.dbus_interface and
- self.sender == rule.sender and
- self.path == rule.path and
- self.match_args_from_rule(rule)):
- if rule.handler_functions == []:
- return True
-
- _funcs_copy_a = self.handler_functions[0:]
- _funcs_copy_b = rule.handler_functions[0:]
- _funcs_copy_a.sort()
- _funcs_copy_b.sort()
-
- return _funcs_copy_a == _funcs_copy_b
-
- return False
-
- def __repr__(self):
- """Returns a custom representation of this DBusMatchRule that can
- be used with dbus_bindings
- """
- repr = "type='signal'"
- if (self.dbus_interface):
- repr = repr + ",interface='%s'" % (self.dbus_interface)
-
- if (self.sender):
- repr = repr + ",sender='%s'" % (self.sender)
-
- if (self.path):
- repr = repr + ",path='%s'" % (self.path)
-
- if (self.signal_name):
- repr = repr + ",member='%s'" % (self.signal_name)
-
- if (self.args):
- my_args_list = self.args.items()
- my_args_list.sort()
- for (index, value) in my_args_list:
- repr = repr + ",arg%i='%s'" % (index, value)
-
- return repr
diff --git a/python/proxies.py b/python/proxies.py
deleted file mode 100644
index 80e9ac27..00000000
--- a/python/proxies.py
+++ /dev/null
@@ -1,222 +0,0 @@
-import dbus_bindings
-import introspect_parser
-import sys
-from exceptions import MissingReplyHandlerException, MissingErrorHandlerException, IntrospectionParserException
-
-class DeferedMethod:
- """A DeferedMethod
-
- This is returned instead of ProxyMethod when we are defering DBus calls
- while waiting for introspection data to be returned
- """
- def __init__(self, proxy_method):
- self._proxy_method = proxy_method
- self._method_name = proxy_method._method_name
-
- def __call__(self, *args, **keywords):
- reply_handler = None
- if keywords.has_key('reply_handler'):
- reply_handler = keywords['reply_handler']
-
- #block for now even on async
- # FIXME: put ret in async queue in future if we have a reply handler
-
- self._proxy_method._proxy._pending_introspect.block()
- ret = self._proxy_method (*args, **keywords)
-
- return ret
-
-class ProxyMethod:
- """A proxy Method.
-
- Typically a member of a ProxyObject. Calls to the
- method produce messages that travel over the Bus and are routed
- to a specific named Service.
- """
- def __init__(self, proxy, connection, named_service, object_path, method_name, iface):
- self._proxy = proxy
- self._connection = connection
- self._named_service = named_service
- self._object_path = object_path
- self._method_name = method_name
- self._dbus_interface = iface
-
- def __call__(self, *args, **keywords):
- timeout = -1
- if keywords.has_key('timeout'):
- timeout = keywords['timeout']
-
- reply_handler = None
- if keywords.has_key('reply_handler'):
- reply_handler = keywords['reply_handler']
-
- error_handler = None
- if keywords.has_key('error_handler'):
- error_handler = keywords['error_handler']
-
- ignore_reply = False
- if keywords.has_key('ignore_reply'):
- ignore_reply = keywords['ignore_reply']
-
-
- if not(reply_handler and error_handler):
- if reply_handler:
- raise MissingErrorHandlerException()
- elif error_handler:
- raise MissingReplyHandlerException()
-
- dbus_interface = self._dbus_interface
- if keywords.has_key('dbus_interface'):
- dbus_interface = keywords['dbus_interface']
-
- tmp_iface = ''
- if dbus_interface:
- tmp_iface = dbus_interface + '.'
-
- key = tmp_iface + self._method_name
-
- introspect_sig = None
- if self._proxy._introspect_method_map.has_key (key):
- introspect_sig = self._proxy._introspect_method_map[key]
-
- message = dbus_bindings.MethodCall(self._object_path, dbus_interface, self._method_name)
- message.set_destination(self._named_service)
-
- # Add the arguments to the function
- iter = message.get_iter(True)
-
- if introspect_sig:
- for (arg, sig) in zip(args, dbus_bindings.Signature(introspect_sig)):
- iter.append_strict(arg, sig)
- else:
- for arg in args:
- iter.append(arg)
-
- if ignore_reply:
- result = self._connection.send(message)
- args_tuple = (result,)
- elif reply_handler:
- result = self._connection.send_with_reply_handlers(message, timeout, reply_handler, error_handler)
- args_tuple = result
- else:
- reply_message = self._connection.send_with_reply_and_block(message, timeout)
- args_tuple = reply_message.get_args_list()
-
- if len(args_tuple) == 0:
- return
- elif len(args_tuple) == 1:
- return args_tuple[0]
- else:
- return args_tuple
-
-
-class ProxyObject:
- """A proxy to the remote Object.
-
- A ProxyObject is provided by the Bus. ProxyObjects
- have member functions, and can be called like normal Python objects.
- """
- ProxyMethodClass = ProxyMethod
- DeferedMethodClass = DeferedMethod
-
- INTROSPECT_STATE_DONT_INTROSPECT = 0
- INTROSPECT_STATE_INTROSPECT_IN_PROGRESS = 1
- INTROSPECT_STATE_INTROSPECT_DONE = 2
-
- def __init__(self, bus, named_service, object_path, introspect=True):
- self._bus = bus
- self._named_service = named_service
- self._object_path = object_path
-
- #PendingCall object for Introspect call
- self._pending_introspect = None
- #queue of async calls waiting on the Introspect to return
- self._pending_introspect_queue = []
- #dictionary mapping method names to their input signatures
- self._introspect_method_map = {}
-
- if not introspect:
- self._introspect_state = self.INTROSPECT_STATE_DONT_INTROSPECT
- else:
- self._introspect_state = self.INTROSPECT_STATE_INTROSPECT_IN_PROGRESS
-
- (result, self._pending_introspect) = self._Introspect()
-
-
- def connect_to_signal(self, signal_name, handler_function, dbus_interface=None, **keywords):
- self._bus.add_signal_receiver(handler_function,
- signal_name=signal_name,
- dbus_interface=dbus_interface,
- named_service=self._named_service,
- path=self._object_path,
- **keywords)
-
- def _Introspect(self):
- message = dbus_bindings.MethodCall(self._object_path, 'org.freedesktop.DBus.Introspectable', 'Introspect')
- message.set_destination(self._named_service)
-
- result = self._bus.get_connection().send_with_reply_handlers(message, -1,
- self._introspect_reply_handler,
- self._introspect_error_handler)
- return result
-
- def _introspect_execute_queue(self):
- for call in self._pending_introspect_queue:
- (member, iface, args, keywords) = call
-
- introspect_sig = None
-
- tmp_iface = ''
- if iface:
- tmp_iface = iface + '.'
-
- key = tmp_iface + '.' + member
- if self._introspect_method_map.has_key (key):
- introspect_sig = self._introspect_method_map[key]
-
-
- call_object = self.ProxyMethodClass(self._bus.get_connection(),
- self._named_service,
- self._object_path,
- iface,
- member,
- introspect_sig)
-
- call_object(args, keywords)
-
- def _introspect_reply_handler(self, data):
- try:
- self._introspect_method_map = introspect_parser.process_introspection_data(data)
- except IntrospectionParserException, e:
- self._introspect_error_handler(e)
- return
-
- self._introspect_state = self.INTROSPECT_STATE_INTROSPECT_DONE
- #self._introspect_execute_queue()
-
- def _introspect_error_handler(self, error):
- self._introspect_state = self.INTROSPECT_STATE_DONT_INTROSPECT
- self._introspect_execute_queue()
- sys.stderr.write("Introspect error: " + str(error) + "\n")
-
- def __getattr__(self, member, dbus_interface=None):
- if member == '__call__':
- return object.__call__
- elif member.startswith('__') and member.endswith('__'):
- raise AttributeError(member)
- else:
- ret = self.ProxyMethodClass(self, self._bus.get_connection(),
- self._named_service,
- self._object_path, member,
- dbus_interface)
-
- if self._introspect_state == self.INTROSPECT_STATE_INTROSPECT_IN_PROGRESS:
- ret = self.DeferedMethodClass(ret)
-
- return ret
-
- def __repr__(self):
- return '<ProxyObject wrapping %s %s %s at %#x>'%(
- self._bus, self._named_service, self._object_path , id(self))
- __str__ = __repr__
-
diff --git a/python/service.py b/python/service.py
deleted file mode 100644
index 9148a357..00000000
--- a/python/service.py
+++ /dev/null
@@ -1,370 +0,0 @@
-import dbus_bindings
-import _dbus
-import operator
-import traceback
-
-from exceptions import NameExistsException
-from exceptions import UnknownMethodException
-from decorators import method
-from decorators import signal
-
-class BusName(object):
- """A base class for exporting your own Named Services across the Bus
- """
- def __new__(cls, name, bus=None):
- # get default bus
- if bus == None:
- bus = _dbus.Bus()
-
- # see if this name is already defined, return it if so
- if name in bus._bus_names:
- return bus._bus_names[name]
-
- # otherwise register the name
- retval = dbus_bindings.bus_request_name(bus.get_connection(), name)
-
- # TODO: more intelligent tracking of bus name states?
- if retval == dbus_bindings.REQUEST_NAME_REPLY_PRIMARY_OWNER:
- pass
- elif retval == dbus_bindings.REQUEST_NAME_REPLY_IN_QUEUE:
- # queueing can happen by default, maybe we should
- # track this better or let the user know if they're
- # queued or not?
- pass
- elif retval == dbus_bindings.REQUEST_NAME_REPLY_EXISTS:
- raise NameExistsException(name)
- elif retval == dbus_bindings.REQUEST_NAME_REPLY_ALREADY_OWNER:
- # if this is a shared bus which is being used by someone
- # else in this process, this can happen legitimately
- pass
- else:
- raise RuntimeError('requesting bus name %s returned unexpected value %s' % (name, retval))
-
- # and create the object
- bus_name = object.__new__(cls)
- bus_name._bus = bus
- bus_name._name = name
-
- # cache instance
- bus._bus_names[name] = bus_name
-
- return bus_name
-
- # do nothing because this is called whether or not the bus name
- # object was retrieved from the cache or created new
- def __init__(self, *args, **keywords):
- pass
-
- # we can delete the low-level name here because these objects
- # are guaranteed to exist only once for each bus name
- def __del__(self):
- dbus_bindings.bus_release_name(self._bus.get_connection(), self._name)
- pass
-
- def get_bus(self):
- """Get the Bus this Service is on"""
- return self._bus
-
- def get_name(self):
- """Get the name of this service"""
- return self._name
-
- def __repr__(self):
- return '<dbus.service.BusName %s on %r at %#x>' % (self._name, self._bus, id(self))
- __str__ = __repr__
-
-
-def _method_lookup(self, method_name, dbus_interface):
- """Walks the Python MRO of the given class to find the method to invoke.
-
- Returns two methods, the one to call, and the one it inherits from which
- defines its D-Bus interface name, signature, and attributes.
- """
- parent_method = None
- candidate_class = None
- successful = False
-
- # split up the cases when we do and don't have an interface because the
- # latter is much simpler
- if dbus_interface:
- # search through the class hierarchy in python MRO order
- for cls in self.__class__.__mro__:
- # if we haven't got a candidate class yet, and we find a class with a
- # suitably named member, save this as a candidate class
- if (not candidate_class and method_name in cls.__dict__):
- if ("_dbus_is_method" in cls.__dict__[method_name].__dict__
- and "_dbus_interface" in cls.__dict__[method_name].__dict__):
- # however if it is annotated for a different interface
- # than we are looking for, it cannot be a candidate
- if cls.__dict__[method_name]._dbus_interface == dbus_interface:
- candidate_class = cls
- parent_method = cls.__dict__[method_name]
- successful = True
- break
- else:
- pass
- else:
- candidate_class = cls
-
- # if we have a candidate class, carry on checking this and all
- # superclasses for a method annoated as a dbus method
- # on the correct interface
- if (candidate_class and method_name in cls.__dict__
- and "_dbus_is_method" in cls.__dict__[method_name].__dict__
- and "_dbus_interface" in cls.__dict__[method_name].__dict__
- and cls.__dict__[method_name]._dbus_interface == dbus_interface):
- # the candidate class has a dbus method on the correct interface,
- # or overrides a method that is, success!
- parent_method = cls.__dict__[method_name]
- successful = True
- break
-
- else:
- # simpler version of above
- for cls in self.__class__.__mro__:
- if (not candidate_class and method_name in cls.__dict__):
- candidate_class = cls
-
- if (candidate_class and method_name in cls.__dict__
- and "_dbus_is_method" in cls.__dict__[method_name].__dict__):
- parent_method = cls.__dict__[method_name]
- successful = True
- break
-
- if successful:
- return (candidate_class.__dict__[method_name], parent_method)
- else:
- if dbus_interface:
- raise UnknownMethodException('%s is not a valid method of interface %s' % (method_name, dbus_interface))
- else:
- raise UnknownMethodException('%s is not a valid method' % method_name)
-
-
-def _method_reply_return(connection, message, method_name, signature, *retval):
- reply = dbus_bindings.MethodReturn(message)
- iter = reply.get_iter(append=True)
-
- # do strict adding if an output signature was provided
- if signature:
- if len(signature) > len(retval):
- raise TypeError('output signature %s is longer than the number of values returned by %s' %
- (signature, method_name))
- elif len(retval) > len(signature):
- raise TypeError('output signature %s is shorter than the number of values returned by %s' %
- (signature, method_name))
- else:
- for (value, sig) in zip(retval, signature):
- iter.append_strict(value, sig)
-
- # no signature, try and guess the return type by inspection
- else:
- for value in retval:
- iter.append(value)
-
- connection.send(reply)
-
-
-def _method_reply_error(connection, message, exception):
- if '_dbus_error_name' in exception.__dict__:
- name = exception._dbus_error_name
- elif exception.__module__ == '__main__':
- name = 'org.freedesktop.DBus.Python.%s' % exception.__class__.__name__
- else:
- name = 'org.freedesktop.DBus.Python.%s.%s' % (exception.__module__, exception.__class__.__name__)
-
- contents = traceback.format_exc()
- reply = dbus_bindings.Error(message, name, contents)
-
- connection.send(reply)
-
-
-class InterfaceType(type):
- def __init__(cls, name, bases, dct):
- # these attributes are shared between all instances of the Interface
- # object, so this has to be a dictionary that maps class names to
- # the per-class introspection/interface data
- class_table = getattr(cls, '_dbus_class_table', {})
- cls._dbus_class_table = class_table
- interface_table = class_table[cls.__module__ + '.' + name] = {}
-
- # merge all the name -> method tables for all the interfaces
- # implemented by our base classes into our own
- for b in bases:
- base_name = b.__module__ + '.' + b.__name__
- if getattr(b, '_dbus_class_table', False):
- for (interface, method_table) in class_table[base_name].iteritems():
- our_method_table = interface_table.setdefault(interface, {})
- our_method_table.update(method_table)
-
- # add in all the name -> method entries for our own methods/signals
- for func in dct.values():
- if getattr(func, '_dbus_interface', False):
- method_table = interface_table.setdefault(func._dbus_interface, {})
- method_table[func.__name__] = func
-
- super(InterfaceType, cls).__init__(name, bases, dct)
-
- # methods are different to signals, so we have two functions... :)
- def _reflect_on_method(cls, func):
- args = func._dbus_args
-
- if func._dbus_in_signature:
- # convert signature into a tuple so length refers to number of
- # types, not number of characters. the length is checked by
- # the decorator to make sure it matches the length of args.
- in_sig = tuple(dbus_bindings.Signature(func._dbus_in_signature))
- else:
- # magic iterator which returns as many v's as we need
- in_sig = dbus_bindings.VariantSignature()
-
- if func._dbus_out_signature:
- out_sig = dbus_bindings.Signature(func._dbus_out_signature)
- else:
- # its tempting to default to dbus_bindings.Signature('v'), but
- # for methods that return nothing, providing incorrect
- # introspection data is worse than providing none at all
- out_sig = []
-
- reflection_data = ' <method name="%s">\n' % (func.__name__)
- for pair in zip(in_sig, args):
- reflection_data += ' <arg direction="in" type="%s" name="%s" />\n' % pair
- for type in out_sig:
- reflection_data += ' <arg direction="out" type="%s" />\n' % type
- reflection_data += ' </method>\n'
-
- return reflection_data
-
- def _reflect_on_signal(cls, func):
- args = func._dbus_args
-
- if func._dbus_signature:
- # convert signature into a tuple so length refers to number of
- # types, not number of characters
- sig = tuple(dbus_bindings.Signature(func._dbus_signature))
- else:
- # magic iterator which returns as many v's as we need
- sig = dbus_bindings.VariantSignature()
-
- reflection_data = ' <signal name="%s">\n' % (func.__name__)
- for pair in zip(sig, args):
- reflection_data = reflection_data + ' <arg type="%s" name="%s" />\n' % pair
- reflection_data = reflection_data + ' </signal>\n'
-
- return reflection_data
-
-class Interface(object):
- __metaclass__ = InterfaceType
-
-class Object(Interface):
- """A base class for exporting your own Objects across the Bus.
-
- Just inherit from Object and provide a list of methods to share
- across the Bus
- """
- def __init__(self, bus_name, object_path):
- self._object_path = object_path
- self._name = bus_name
- self._bus = bus_name.get_bus()
-
- self._connection = self._bus.get_connection()
-
- self._connection.register_object_path(object_path, self._unregister_cb, self._message_cb)
-
- def _unregister_cb(self, connection):
- print ("Unregister")
-
- def _message_cb(self, connection, message):
- try:
- # lookup candidate method and parent method
- method_name = message.get_member()
- interface_name = message.get_interface()
- (candidate_method, parent_method) = _method_lookup(self, method_name, interface_name)
-
- # set up method call parameters
- args = message.get_args_list()
- keywords = {}
-
- # iterate signature into list of complete types
- if parent_method._dbus_out_signature:
- signature = tuple(dbus_bindings.Signature(parent_method._dbus_out_signature))
- else:
- signature = None
-
- # set up async callback functions
- if parent_method._dbus_async_callbacks:
- (return_callback, error_callback) = parent_method._dbus_async_callbacks
- keywords[return_callback] = lambda *retval: _method_reply_return(connection, message, method_name, signature, *retval)
- keywords[error_callback] = lambda exception: _method_reply_error(connection, message, exception)
-
- # include the sender if desired
- if parent_method._dbus_sender_keyword:
- keywords[parent_method._dbus_sender_keyword] = message.get_sender()
-
- # call method
- retval = candidate_method(self, *args, **keywords)
-
- # we're done - the method has got callback functions to reply with
- if parent_method._dbus_async_callbacks:
- return
-
- # otherwise we send the return values in a reply. if we have a
- # signature, use it to turn the return value into a tuple as
- # appropriate
- if parent_method._dbus_out_signature:
- # if we have zero or one return values we want make a tuple
- # for the _method_reply_return function, otherwise we need
- # to check we're passing it a sequence
- if len(signature) == 0:
- if retval == None:
- retval = ()
- else:
- raise TypeError('%s has an empty output signature but did not return None' %
- method_name)
- elif len(signature) == 1:
- retval = (retval,)
- else:
- if operator.isSequenceType(retval):
- # multi-value signature, multi-value return... proceed unchanged
- pass
- else:
- raise TypeError('%s has multiple output values in signature %s but did not return a sequence' %
- (method_name, signature))
-
- # no signature, so just turn the return into a tuple and send it as normal
- else:
- signature = None
- if retval == None:
- retval = ()
- else:
- retval = (retval,)
-
- _method_reply_return(connection, message, method_name, signature, *retval)
- except Exception, exception:
- # send error reply
- _method_reply_error(connection, message, exception)
-
- @method('org.freedesktop.DBus.Introspectable', in_signature='', out_signature='s')
- def Introspect(self):
- reflection_data = '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">\n'
- reflection_data += '<node name="%s">\n' % (self._object_path)
-
- interfaces = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__]
- for (name, funcs) in interfaces.iteritems():
- reflection_data += ' <interface name="%s">\n' % (name)
-
- for func in funcs.values():
- if getattr(func, '_dbus_is_method', False):
- reflection_data += self.__class__._reflect_on_method(func)
- elif getattr(func, '_dbus_is_signal', False):
- reflection_data += self.__class__._reflect_on_signal(func)
-
- reflection_data += ' </interface>\n'
-
- reflection_data += '</node>\n'
-
- return reflection_data
-
- def __repr__(self):
- return '<dbus.service.Object %s on %r at %#x>' % (self._object_path, self._name, id(self))
- __str__ = __repr__
-
diff --git a/python/types.py b/python/types.py
deleted file mode 100644
index f3d348c6..00000000
--- a/python/types.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import dbus_bindings
-
-ObjectPath = dbus_bindings.ObjectPath
-ByteArray = dbus_bindings.ByteArray
-Signature = dbus_bindings.Signature
-Byte = dbus_bindings.Byte
-Boolean = dbus_bindings.Boolean
-Int16 = dbus_bindings.Int16
-UInt16 = dbus_bindings.UInt16
-Int32 = dbus_bindings.Int32
-UInt32 = dbus_bindings.UInt32
-Int64 = dbus_bindings.Int64
-UInt64 = dbus_bindings.UInt64
-Double = dbus_bindings.Double
-String = dbus_bindings.String
-Array = dbus_bindings.Array
-Struct = dbus_bindings.Struct
-Dictionary = dbus_bindings.Dictionary
-Variant = dbus_bindings.Variant