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.subscription_handle import InstanceSubscriptionHandle 17from acts.event.subscription_handle import StaticSubscriptionHandle 18from acts.event import subscription_bundle 19 20 21def subscribe_static(event_type, event_filter=None, order=0): 22 """A decorator that subscribes a static or module-level function. 23 24 This function must be registered manually. 25 """ 26 class InnerSubscriptionHandle(StaticSubscriptionHandle): 27 def __init__(self, func): 28 super().__init__(event_type, func, 29 event_filter=event_filter, 30 order=order) 31 32 return InnerSubscriptionHandle 33 34 35def subscribe(event_type, event_filter=None, order=0): 36 """A decorator that subscribes an instance method.""" 37 class InnerSubscriptionHandle(InstanceSubscriptionHandle): 38 def __init__(self, func): 39 super().__init__(event_type, func, 40 event_filter=event_filter, 41 order=order) 42 43 return InnerSubscriptionHandle 44 45 46def register_static_subscriptions(decorated): 47 """Registers all static subscriptions in decorated's attributes. 48 49 Args: 50 decorated: The object being decorated 51 52 Returns: 53 The decorated. 54 """ 55 subscription_bundle.create_from_static(decorated).register() 56 57 return decorated 58 59 60def register_instance_subscriptions(obj): 61 """A decorator that subscribes all instance subscriptions after object init. 62 """ 63 old_init = obj.__init__ 64 65 def init_replacement(self, *args, **kwargs): 66 old_init(self, *args, **kwargs) 67 subscription_bundle.create_from_instance(self).register() 68 69 obj.__init__ = init_replacement 70 return obj 71