summaryrefslogtreecommitdiff
path: root/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManager.kt
blob: d2ded71487dcddabbfa9378780d0e26c4b3af6ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.systemui.controls.controller

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.os.UserHandle
import android.service.controls.ControlsProviderService
import android.service.controls.ControlsProviderService.CALLBACK_BUNDLE
import android.service.controls.ControlsProviderService.CALLBACK_TOKEN
import android.service.controls.IControlsActionCallback
import android.service.controls.IControlsProvider
import android.service.controls.IControlsSubscriber
import android.service.controls.IControlsSubscription
import android.service.controls.actions.ControlAction
import android.util.ArraySet
import android.util.Log
import com.android.internal.annotations.GuardedBy
import com.android.systemui.util.concurrency.DelayableExecutor
import java.util.concurrent.TimeUnit

/**
 * Manager for the lifecycle of the connection to a given [ControlsProviderService].
 *
 * This class handles binding and unbinding and requests to the service. The class will queue
 * requests until the service is connected and dispatch them then.
 *
 * @property context A SystemUI context for binding to the services
 * @property executor A delayable executor for posting timeouts
 * @property actionCallbackService a callback interface to hand the remote service for sending
 *                                 action responses
 * @property subscriberService an "subscriber" interface for requesting and accepting updates for
 *                             controls from the service.
 * @property user the user for whose this service should be bound.
 * @property componentName the name of the component for the service.
 */
class ControlsProviderLifecycleManager(
    private val context: Context,
    private val executor: DelayableExecutor,
    private val actionCallbackService: IControlsActionCallback.Stub,
    val user: UserHandle,
    val componentName: ComponentName
) : IBinder.DeathRecipient {

    val token: IBinder = Binder()
    private var requiresBound = false
    @GuardedBy("queuedServiceMethods")
    private val queuedServiceMethods: MutableSet<ServiceMethod> = ArraySet()
    private var wrapper: ServiceWrapper? = null
    private var bindTryCount = 0
    private val TAG = javaClass.simpleName
    private var onLoadCanceller: Runnable? = null

    companion object {
        private const val BIND_RETRY_DELAY = 1000L // ms
        private const val LOAD_TIMEOUT_SECONDS = 20L // seconds
        private const val MAX_BIND_RETRIES = 5
        private const val DEBUG = true
        private val BIND_FLAGS = Context.BIND_AUTO_CREATE or Context.BIND_FOREGROUND_SERVICE or
            Context.BIND_NOT_PERCEPTIBLE
    }

    private val intent = Intent().apply {
        component = componentName
        putExtra(CALLBACK_BUNDLE, Bundle().apply {
            putBinder(CALLBACK_TOKEN, token)
        })
    }

    private fun bindService(bind: Boolean) {
        executor.execute {
            requiresBound = bind
            if (bind) {
                if (bindTryCount != MAX_BIND_RETRIES) {
                    if (DEBUG) {
                        Log.d(TAG, "Binding service $intent")
                    }
                    bindTryCount++
                    try {
                        context.bindServiceAsUser(intent, serviceConnection, BIND_FLAGS, user)
                    } catch (e: SecurityException) {
                        Log.e(TAG, "Failed to bind to service", e)
                    }
                }
            } else {
                if (DEBUG) {
                    Log.d(TAG, "Unbinding service $intent")
                }
                bindTryCount = 0
                wrapper?.run {
                    context.unbindService(serviceConnection)
                }
                wrapper = null
            }
        }
    }

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            if (DEBUG) Log.d(TAG, "onServiceConnected $name")
            bindTryCount = 0
            wrapper = ServiceWrapper(IControlsProvider.Stub.asInterface(service))
            try {
                service.linkToDeath(this@ControlsProviderLifecycleManager, 0)
            } catch (_: RemoteException) {}
            handlePendingServiceMethods()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            if (DEBUG) Log.d(TAG, "onServiceDisconnected $name")
            wrapper = null
            bindService(false)
        }

        override fun onNullBinding(name: ComponentName?) {
            if (DEBUG) Log.d(TAG, "onNullBinding $name")
            wrapper = null
            context.unbindService(this)
        }
    }

    private fun handlePendingServiceMethods() {
        val queue = synchronized(queuedServiceMethods) {
            ArraySet(queuedServiceMethods).also {
                queuedServiceMethods.clear()
            }
        }
        queue.forEach {
            it.run()
        }
    }

    override fun binderDied() {
        if (wrapper == null) return
        wrapper = null
        if (requiresBound) {
            if (DEBUG) {
                Log.d(TAG, "binderDied")
            }
            // Try rebinding some time later
        }
    }

    private fun queueServiceMethod(sm: ServiceMethod) {
        synchronized(queuedServiceMethods) {
            queuedServiceMethods.add(sm)
        }
    }

    private fun invokeOrQueue(sm: ServiceMethod) {
        wrapper?.run {
            sm.run()
        } ?: run {
            queueServiceMethod(sm)
            bindService(true)
        }
    }

    /**
     * Request a call to [IControlsProvider.load].
     *
     * If the service is not bound, the call will be queued and the service will be bound first.
     * The service will be unbound after the controls are returned or the call times out.
     *
     * @param subscriber the subscriber that manages coordination for loading controls
     */
    fun maybeBindAndLoad(subscriber: IControlsSubscriber.Stub) {
        onLoadCanceller = executor.executeDelayed({
            // Didn't receive a response in time, log and send back error
            Log.d(TAG, "Timeout waiting onLoad for $componentName")
            subscriber.onError(token, "Timeout waiting onLoad")
            unbindService()
        }, LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS)

        invokeOrQueue(Load(subscriber))
    }

    /**
     * Request a call to [IControlsProvider.loadSuggested].
     *
     * If the service is not bound, the call will be queued and the service will be bound first.
     * The service will be unbound if the call times out.
     *
     * @param subscriber the subscriber that manages coordination for loading controls
     */
    fun maybeBindAndLoadSuggested(subscriber: IControlsSubscriber.Stub) {
        onLoadCanceller = executor.executeDelayed({
            // Didn't receive a response in time, log and send back error
            Log.d(TAG, "Timeout waiting onLoadSuggested for $componentName")
            subscriber.onError(token, "Timeout waiting onLoadSuggested")
            unbindService()
        }, LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS)

        invokeOrQueue(Suggest(subscriber))
    }

    fun cancelLoadTimeout() {
        onLoadCanceller?.run()
        onLoadCanceller = null
    }

    /**
     * Request a subscription to the [Publisher] returned by [ControlsProviderService.publisherFor]
     *
     * If the service is not bound, the call will be queued and the service will be bound first.
     *
     * @param controlIds a list of the ids of controls to send status back.
     */
    fun maybeBindAndSubscribe(controlIds: List<String>, subscriber: IControlsSubscriber) =
        invokeOrQueue(Subscribe(controlIds, subscriber))

    /**
     * Request a call to [ControlsProviderService.performControlAction].
     *
     * If the service is not bound, the call will be queued and the service will be bound first.
     *
     * @param controlId the id of the [Control] the action is performed on
     * @param action the action performed
     */
    fun maybeBindAndSendAction(controlId: String, action: ControlAction) =
        invokeOrQueue(Action(controlId, action))

    /**
     * Starts the subscription to the [ControlsProviderService] and requests status of controls.
     *
     * @param subscription the subscription to use to request controls
     * @see maybeBindAndLoad
     */
    fun startSubscription(subscription: IControlsSubscription, requestLimit: Long) {
        if (DEBUG) {
            Log.d(TAG, "startSubscription: $subscription")
        }

        wrapper?.request(subscription, requestLimit)
    }

    /**
     * Cancels the subscription to the [ControlsProviderService].
     *
     * @param subscription the subscription to cancel
     * @see maybeBindAndLoad
     */
    fun cancelSubscription(subscription: IControlsSubscription) {
        if (DEBUG) {
            Log.d(TAG, "cancelSubscription: $subscription")
        }

        wrapper?.cancel(subscription)
    }

    /**
     * Request bind to the service.
     */
    fun bindService() {
        bindService(true)
    }

    /**
     * Request unbind from the service.
     */
    fun unbindService() {
        onLoadCanceller?.run()
        onLoadCanceller = null

        bindService(false)
    }

    override fun toString(): String {
        return StringBuilder("ControlsProviderLifecycleManager(").apply {
            append("component=$componentName")
            append(", user=$user")
            append(")")
        }.toString()
    }

    /**
     * Service methods that can be queued or invoked, and are retryable for failure scenarios
     */
    abstract inner class ServiceMethod {
        fun run() {
            if (!callWrapper()) {
                queueServiceMethod(this)
                binderDied()
            }
        }

        internal abstract fun callWrapper(): Boolean
    }

    inner class Load(val subscriber: IControlsSubscriber.Stub) : ServiceMethod() {
        override fun callWrapper(): Boolean {
            if (DEBUG) {
                Log.d(TAG, "load $componentName")
            }
            return wrapper?.load(subscriber) ?: false
        }
    }

    inner class Suggest(val subscriber: IControlsSubscriber.Stub) : ServiceMethod() {
        override fun callWrapper(): Boolean {
            if (DEBUG) {
                Log.d(TAG, "suggest $componentName")
            }
            return wrapper?.loadSuggested(subscriber) ?: false
        }
    }
    inner class Subscribe(
        val list: List<String>,
        val subscriber: IControlsSubscriber
    ) : ServiceMethod() {
        override fun callWrapper(): Boolean {
            if (DEBUG) {
                Log.d(TAG, "subscribe $componentName - $list")
            }

            return wrapper?.subscribe(list, subscriber) ?: false
        }
    }

    inner class Action(val id: String, val action: ControlAction) : ServiceMethod() {
        override fun callWrapper(): Boolean {
            if (DEBUG) {
                Log.d(TAG, "onAction $componentName - $id")
            }
            return wrapper?.action(id, action, actionCallbackService) ?: false
        }
    }
}