1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.systemui.controls.controller
18 
19 import android.service.controls.IControlsActionCallback
20 import android.service.controls.IControlsProvider
21 import android.service.controls.IControlsSubscriber
22 import android.service.controls.IControlsSubscription
23 import android.service.controls.actions.ControlAction
24 import android.service.controls.actions.ControlActionWrapper
25 import android.util.Log
26 
27 /**
28  * Wrapper for the service calls.
29  *
30  * Calling all [IControlsProvider] methods through here will wrap them in a try/catch block.
31  */
32 class ServiceWrapper(val service: IControlsProvider) {
33     companion object {
34         private const val TAG = "ServiceWrapper"
35     }
36 
37     private inline fun callThroughService(block: () -> Unit): Boolean {
38         try {
39             block()
40             return true
41         } catch (ex: Exception) {
42             Log.e(TAG, "Caught exception from ControlsProviderService", ex)
43             return false
44         }
45     }
46 
47     fun load(subscriber: IControlsSubscriber): Boolean {
48         return callThroughService {
49             service.load(subscriber)
50         }
51     }
52 
53     fun loadSuggested(subscriber: IControlsSubscriber): Boolean {
54         return callThroughService {
55             service.loadSuggested(subscriber)
56         }
57     }
58 
59     fun subscribe(controlIds: List<String>, subscriber: IControlsSubscriber): Boolean {
60         return callThroughService {
61             service.subscribe(controlIds, subscriber)
62         }
63     }
64 
65     fun request(subscription: IControlsSubscription, num: Long): Boolean {
66         return callThroughService {
67             subscription.request(num)
68         }
69     }
70 
71     fun cancel(subscription: IControlsSubscription): Boolean {
72         return callThroughService {
73             subscription.cancel()
74         }
75     }
76 
77     fun action(
78         controlId: String,
79         action: ControlAction,
80         cb: IControlsActionCallback
81     ): Boolean {
82         return callThroughService {
83             service.action(controlId, ControlActionWrapper(action), cb)
84         }
85     }
86 }
87