dbus/bus.py: correct name of logger
[dbus-python-phuang.git] / dbus / proxies.py
blob5934b56c0ce31e6fb9a541b6fcdc17860b38d331
1 # Copyright (C) 2003, 2004, 2005, 2006, 2007 Red Hat Inc. <http://www.redhat.com/>
2 # Copyright (C) 2003 David Zeuthen
3 # Copyright (C) 2004 Rob Taylor
4 # Copyright (C) 2005, 2006, 2007 Collabora Ltd. <http://www.collabora.co.uk/>
6 # Licensed under the Academic Free License version 2.1
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 import sys
23 import logging
25 try:
26 from threading import RLock
27 except ImportError:
28 from dummy_threading import RLock
30 import _dbus_bindings
31 from dbus._expat_introspect_parser import process_introspection_data
32 from dbus.exceptions import MissingReplyHandlerException, MissingErrorHandlerException, IntrospectionParserException, DBusException
34 __docformat__ = 'restructuredtext'
37 _logger = logging.getLogger('dbus.proxies')
39 from _dbus_bindings import LOCAL_PATH, \
40 BUS_DAEMON_NAME, BUS_DAEMON_PATH, BUS_DAEMON_IFACE,\
41 INTROSPECTABLE_IFACE
44 class _DeferredMethod:
45 """A proxy method which will only get called once we have its
46 introspection reply.
47 """
48 def __init__(self, proxy_method, append, block):
49 self._proxy_method = proxy_method
50 # the test suite relies on the existence of this property
51 self._method_name = proxy_method._method_name
52 self._append = append
53 self._block = block
55 def __call__(self, *args, **keywords):
56 if keywords.has_key('reply_handler'):
57 # defer the async call til introspection finishes
58 self._append(self._proxy_method, args, keywords)
59 return None
60 else:
61 # we're being synchronous, so block
62 self._block()
63 return self._proxy_method(*args, **keywords)
65 def call_async(self, *args, **keywords):
66 self._append(self._proxy_method, args, keywords)
69 class _ProxyMethod:
70 """A proxy method.
72 Typically a member of a ProxyObject. Calls to the
73 method produce messages that travel over the Bus and are routed
74 to a specific named Service.
75 """
76 def __init__(self, proxy, connection, named_service, object_path, method_name, iface):
77 if object_path == LOCAL_PATH:
78 raise DBusException('Methods may not be called on the reserved '
79 'path %s' % LOCAL_PATH)
81 # trust that the proxy, and the properties it had, are OK
82 self._proxy = proxy
83 self._connection = connection
84 self._named_service = named_service
85 self._object_path = object_path
86 # fail early if the method name is bad
87 _dbus_bindings.validate_member_name(method_name)
88 # the test suite relies on the existence of this property
89 self._method_name = method_name
90 # fail early if the interface name is bad
91 if iface is not None:
92 _dbus_bindings.validate_interface_name(iface)
93 self._dbus_interface = iface
95 def __call__(self, *args, **keywords):
96 reply_handler = keywords.pop('reply_handler', None)
97 error_handler = keywords.pop('error_handler', None)
98 ignore_reply = keywords.pop('ignore_reply', False)
100 if reply_handler is not None or error_handler is not None:
101 if reply_handler is None:
102 raise MissingErrorHandlerException()
103 elif error_handler is None:
104 raise MissingReplyHandlerException()
105 elif ignore_reply:
106 raise TypeError('ignore_reply and reply_handler cannot be '
107 'used together')
109 dbus_interface = keywords.pop('dbus_interface', self._dbus_interface)
111 if dbus_interface is None:
112 key = self._method_name
113 else:
114 key = dbus_interface + '.' + self._method_name
115 introspect_sig = self._proxy._introspect_method_map.get(key, None)
117 if ignore_reply or reply_handler is not None:
118 self._connection.call_async(self._named_service,
119 self._object_path,
120 dbus_interface,
121 self._method_name,
122 introspect_sig,
123 args,
124 reply_handler,
125 error_handler,
126 **keywords)
127 else:
128 return self._connection.call_blocking(self._named_service,
129 self._object_path,
130 dbus_interface,
131 self._method_name,
132 introspect_sig,
133 args,
134 **keywords)
136 def call_async(self, *args, **keywords):
137 reply_handler = keywords.pop('reply_handler', None)
138 error_handler = keywords.pop('error_handler', None)
140 dbus_interface = keywords.pop('dbus_interface', self._dbus_interface)
142 if dbus_interface:
143 key = dbus_interface + '.' + self._method_name
144 else:
145 key = self._method_name
146 introspect_sig = self._proxy._introspect_method_map.get(key, None)
148 self._connection.call_async(self._named_service,
149 self._object_path,
150 dbus_interface,
151 self._method_name,
152 introspect_sig,
153 args,
154 reply_handler,
155 error_handler,
156 **keywords)
159 class ProxyObject(object):
160 """A proxy to the remote Object.
162 A ProxyObject is provided by the Bus. ProxyObjects
163 have member functions, and can be called like normal Python objects.
165 ProxyMethodClass = _ProxyMethod
166 DeferredMethodClass = _DeferredMethod
168 INTROSPECT_STATE_DONT_INTROSPECT = 0
169 INTROSPECT_STATE_INTROSPECT_IN_PROGRESS = 1
170 INTROSPECT_STATE_INTROSPECT_DONE = 2
172 def __init__(self, bus, named_service, object_path, introspect=True,
173 follow_name_owner_changes=False):
174 """Initialize the proxy object.
176 :Parameters:
177 `bus` : `dbus.Bus`
178 The bus on which to find this object
179 `named_service` : str
180 A bus name for the endpoint owning the object (need not
181 actually be a service name)
182 `object_path` : str
183 The object path at which the endpoint exports the object
184 `introspect` : bool
185 If true (default), attempt to introspect the remote
186 object to find out supported methods and their signatures
187 `follow_name_owner_changes` : bool
188 If true (default is false) and the `named_service` is a
189 well-known name, follow ownership changes for that name
191 if follow_name_owner_changes:
192 # we don't get the signals unless the Bus has a main loop
193 # XXX: using Bus internals
194 bus._require_main_loop()
196 self._bus = bus
198 if named_service is not None:
199 _dbus_bindings.validate_bus_name(named_service)
200 self._named_service = self._requested_bus_name = named_service
202 _dbus_bindings.validate_object_path(object_path)
203 self.__dbus_object_path__ = object_path
205 if not follow_name_owner_changes:
206 self._named_service = bus.activate_name_owner(named_service)
208 #PendingCall object for Introspect call
209 self._pending_introspect = None
210 #queue of async calls waiting on the Introspect to return
211 self._pending_introspect_queue = []
212 #dictionary mapping method names to their input signatures
213 self._introspect_method_map = {}
215 # must be a recursive lock because block() is called while locked,
216 # and calls the callback which re-takes the lock
217 self._introspect_lock = RLock()
219 if not introspect or self.__dbus_object_path__ == LOCAL_PATH:
220 self._introspect_state = self.INTROSPECT_STATE_DONT_INTROSPECT
221 else:
222 self._introspect_state = self.INTROSPECT_STATE_INTROSPECT_IN_PROGRESS
224 self._pending_introspect = self._Introspect()
226 bus_name = property(lambda self: self._named_service, None, None,
227 """The bus name to which this proxy is bound. (Read-only,
228 may change.)
230 If the proxy was instantiated using a unique name, this property
231 is that unique name.
233 If the proxy was instantiated with a well-known name and with
234 `follow_name_owner_changes` set false (the default), this
235 property is the unique name of the connection that owned that
236 well-known name when the proxy was instantiated, which might
237 not actually own the requested well-known name any more.
239 If the proxy was instantiated with a well-known name and with
240 `follow_name_owner_changes` set true, this property is that
241 well-known name.
242 """)
244 requested_bus_name = property(lambda self: self._requested_bus_name,
245 None, None,
246 """The bus name which was requested when this proxy was
247 instantiated.
248 """)
250 object_path = property(lambda self: self.__dbus_object_path__,
251 None, None,
252 """The object-path of this proxy.""")
254 # XXX: We don't currently support this because it's the signal receiver
255 # that's responsible for tracking name owner changes, but it
256 # seems a natural thing to add in future.
257 #unique_bus_name = property(lambda self: something, None, None,
258 # """The unique name of the connection to which this proxy is
259 # currently bound. (Read-only, may change.)
260 # """)
262 def connect_to_signal(self, signal_name, handler_function, dbus_interface=None, **keywords):
263 """Arrange for the given function to be called when the given signal
264 is received.
266 :Parameters:
267 `signal_name` : str
268 The name of the signal
269 `handler_function` : callable
270 A function to be called when the signal is emitted by
271 the remote object. Its positional arguments will be the
272 arguments of the signal; optionally, it may be given
273 keyword arguments as described below.
274 `dbus_interface` : str
275 Optional interface with which to qualify the signal name.
276 If None (the default) the handler will be called whenever a
277 signal of the given member name is received, whatever
278 its interface.
279 :Keywords:
280 `utf8_strings` : bool
281 If True, the handler function will receive any string
282 arguments as dbus.UTF8String objects (a subclass of str
283 guaranteed to be UTF-8). If False (default) it will receive
284 any string arguments as dbus.String objects (a subclass of
285 unicode).
286 `byte_arrays` : bool
287 If True, the handler function will receive any byte-array
288 arguments as dbus.ByteArray objects (a subclass of str).
289 If False (default) it will receive any byte-array
290 arguments as a dbus.Array of dbus.Byte (subclasses of:
291 a list of ints).
292 `sender_keyword` : str
293 If not None (the default), the handler function will receive
294 the unique name of the sending endpoint as a keyword
295 argument with this name
296 `destination_keyword` : str
297 If not None (the default), the handler function will receive
298 the bus name of the destination (or None if the signal is a
299 broadcast, as is usual) as a keyword argument with this name.
300 `interface_keyword` : str
301 If not None (the default), the handler function will receive
302 the signal interface as a keyword argument with this name.
303 `member_keyword` : str
304 If not None (the default), the handler function will receive
305 the signal name as a keyword argument with this name.
306 `path_keyword` : str
307 If not None (the default), the handler function will receive
308 the object-path of the sending object as a keyword argument
309 with this name
310 `message_keyword` : str
311 If not None (the default), the handler function will receive
312 the `dbus.lowlevel.SignalMessage` as a keyword argument with
313 this name.
314 `arg...` : unicode or UTF-8 str
315 If there are additional keyword parameters of the form
316 ``arg``\ *n*, match only signals where the *n*\ th argument
317 is the value given for that keyword parameter. As of this time
318 only string arguments can be matched (in particular,
319 object paths and signatures can't).
321 return \
322 self._bus.add_signal_receiver(handler_function,
323 signal_name=signal_name,
324 dbus_interface=dbus_interface,
325 named_service=self._named_service,
326 path=self.__dbus_object_path__,
327 **keywords)
329 def _Introspect(self):
330 return self._bus.call_async(self._named_service,
331 self.__dbus_object_path__,
332 INTROSPECTABLE_IFACE, 'Introspect', '', (),
333 self._introspect_reply_handler,
334 self._introspect_error_handler,
335 utf8_strings=True,
336 require_main_loop=False)
338 def _introspect_execute_queue(self):
339 # FIXME: potential to flood the bus
340 # We should make sure mainloops all have idle handlers
341 # and do one message per idle
342 for (proxy_method, args, keywords) in self._pending_introspect_queue:
343 proxy_method(*args, **keywords)
345 def _introspect_reply_handler(self, data):
346 self._introspect_lock.acquire()
347 try:
348 try:
349 self._introspect_method_map = process_introspection_data(data)
350 except IntrospectionParserException, e:
351 self._introspect_error_handler(e)
352 return
354 self._introspect_state = self.INTROSPECT_STATE_INTROSPECT_DONE
355 self._pending_introspect = None
356 self._introspect_execute_queue()
357 finally:
358 self._introspect_lock.release()
360 def _introspect_error_handler(self, error):
361 self._introspect_lock.acquire()
362 try:
363 self._introspect_state = self.INTROSPECT_STATE_DONT_INTROSPECT
364 self._pending_introspect = None
365 self._introspect_execute_queue()
366 sys.stderr.write("Introspect error: " + str(error) + "\n")
367 finally:
368 self._introspect_lock.release()
370 def _introspect_block(self):
371 self._introspect_lock.acquire()
372 try:
373 if self._pending_introspect is not None:
374 self._pending_introspect.block()
375 # else someone still has a _DeferredMethod from before we
376 # finished introspection: no need to do anything special any more
377 finally:
378 self._introspect_lock.release()
380 def _introspect_add_to_queue(self, callback, args, kwargs):
381 self._introspect_lock.acquire()
382 try:
383 if self._introspect_state == self.INTROSPECT_STATE_INTROSPECT_IN_PROGRESS:
384 self._pending_introspect_queue.append((callback, args, kwargs))
385 else:
386 # someone still has a _DeferredMethod from before we
387 # finished introspection
388 callback(*args, **kwargs)
389 finally:
390 self._introspect_lock.release()
392 def __getattr__(self, member):
393 if member.startswith('__') and member.endswith('__'):
394 raise AttributeError(member)
395 else:
396 return self.get_dbus_method(member)
398 def get_dbus_method(self, member, dbus_interface=None):
399 """Return a proxy method representing the given D-Bus method. The
400 returned proxy method can be called in the usual way. For instance, ::
402 proxy.get_dbus_method("Foo", dbus_interface='com.example.Bar')(123)
404 is equivalent to::
406 proxy.Foo(123, dbus_interface='com.example.Bar')
408 or even::
410 getattr(proxy, "Foo")(123, dbus_interface='com.example.Bar')
412 However, using `get_dbus_method` is the only way to call D-Bus
413 methods with certain awkward names - if the author of a service
414 implements a method called ``connect_to_signal`` or even
415 ``__getattr__``, you'll need to use `get_dbus_method` to call them.
417 For services which follow the D-Bus convention of CamelCaseMethodNames
418 this won't be a problem.
421 ret = self.ProxyMethodClass(self, self._bus,
422 self._named_service,
423 self.__dbus_object_path__, member,
424 dbus_interface)
426 # this can be done without taking the lock - the worst that can
427 # happen is that we accidentally return a _DeferredMethod just after
428 # finishing introspection, in which case _introspect_add_to_queue and
429 # _introspect_block will do the right thing anyway
430 if self._introspect_state == self.INTROSPECT_STATE_INTROSPECT_IN_PROGRESS:
431 ret = self.DeferredMethodClass(ret, self._introspect_add_to_queue,
432 self._introspect_block)
434 return ret
436 def __repr__(self):
437 return '<ProxyObject wrapping %s %s %s at %#x>'%(
438 self._bus, self._named_service, self.__dbus_object_path__, id(self))
439 __str__ = __repr__
442 class Interface(object):
443 """An interface into a remote object.
445 An Interface can be used to wrap ProxyObjects
446 so that calls can be routed to their correct
447 D-Bus interface.
450 def __init__(self, object, dbus_interface):
451 """Construct a proxy for the given interface on the given object.
453 :Parameters:
454 `object` : `dbus.proxies.ProxyObject` or `dbus.Interface`
455 The remote object or another of its interfaces
456 `dbus_interface` : str
457 An interface the `object` implements
459 if isinstance(object, Interface):
460 self._obj = object.proxy_object
461 else:
462 self._obj = object
463 self._dbus_interface = dbus_interface
465 object_path = property (lambda self: self._obj.object_path, None, None,
466 "The D-Bus object path of the underlying object")
467 __dbus_object_path__ = object_path
468 bus_name = property (lambda self: self._obj.bus_name, None, None,
469 "The bus name to which the underlying proxy object "
470 "is bound")
471 requested_bus_name = property (lambda self: self._obj.requested_bus_name,
472 None, None,
473 "The bus name which was requested when the "
474 "underlying object was created")
475 proxy_object = property (lambda self: self._obj, None, None,
476 """The underlying proxy object""")
477 dbus_interface = property (lambda self: self._dbus_interface, None, None,
478 """The D-Bus interface represented""")
480 def connect_to_signal(self, signal_name, handler_function,
481 dbus_interface=None, **keywords):
482 """Arrange for a function to be called when the given signal is
483 emitted.
485 The parameters and keyword arguments are the same as for
486 `dbus.proxies.ProxyObject.connect_to_signal`, except that if
487 `dbus_interface` is None (the default), the D-Bus interface that
488 was passed to the `Interface` constructor is used.
490 if not dbus_interface:
491 dbus_interface = self._dbus_interface
493 return self._obj.connect_to_signal(signal_name, handler_function,
494 dbus_interface, **keywords)
496 def __getattr__(self, member):
497 if member.startswith('__') and member.endswith('__'):
498 raise AttributeError(member)
499 else:
500 return self._obj.get_dbus_method(member, self._dbus_interface)
502 def get_dbus_method(self, member, dbus_interface=None):
503 """Return a proxy method representing the given D-Bus method.
505 This is the same as `dbus.proxies.ProxyObject.get_dbus_method`
506 except that if `dbus_interface` is None (the default),
507 the D-Bus interface that was passed to the `Interface` constructor
508 is used.
510 if dbus_interface is None:
511 dbus_interface = self._dbus_interface
512 return self._obj.get_dbus_method(member, dbus_interface)
514 def __repr__(self):
515 return '<Interface %r implementing %r at %#x>'%(
516 self._obj, self._dbus_interface, id(self))
517 __str__ = __repr__