• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3#   Copyright 2018 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16from acts.event.event_subscription import EventSubscription
17
18
19class SubscriptionHandle(object):
20    """The object created by a method decorated with an event decorator."""
21
22    def __init__(self, event_type, func, event_filter=None, order=0):
23        self._event_type = event_type
24        self._func = func
25        self._event_filter = event_filter
26        self._order = order
27        self._subscription = None
28        self._owner = None
29
30    @property
31    def subscription(self):
32        if self._subscription:
33            return self._subscription
34        self._subscription = EventSubscription(self._event_type, self._func,
35                                               event_filter=self._event_filter,
36                                               order=self._order)
37        return self._subscription
38
39    def __get__(self, instance, owner):
40        # If our owner has been initialized, or do not have an instance owner,
41        # return self.
42        if self._owner is not None or instance is None:
43            return self
44
45        # Otherwise, we create a new SubscriptionHandle that will only be used
46        # for the instance that owns this SubscriptionHandle.
47        ret = SubscriptionHandle(self._event_type, self._func,
48                                 self._event_filter, self._order)
49        ret._owner = instance
50        ret._func = ret._wrap_call(ret._func)
51        for attr, value in owner.__dict__.items():
52            if value is self:
53                setattr(instance, attr, ret)
54                break
55        return ret
56
57    def _wrap_call(self, func):
58        def _wrapped_call(*args, **kwargs):
59            if self._owner is None:
60                return func(*args, **kwargs)
61            else:
62                return func(self._owner, *args, **kwargs)
63        return _wrapped_call
64
65    def __call__(self, *args, **kwargs):
66        return self._func(*args, **kwargs)
67
68
69class InstanceSubscriptionHandle(SubscriptionHandle):
70    """A SubscriptionHandle for instance methods."""
71
72
73class StaticSubscriptionHandle(SubscriptionHandle):
74    """A SubscriptionHandle for static methods."""
75