summaryrefslogtreecommitdiff
path: root/packages/SystemUI/src/com/android/systemui/statusbar/events/PrivacyDotViewController.kt
blob: 29cfb07a14f915a965890eef855c8e248674442a (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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
 * Copyright (C) 2021 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.statusbar.events

import android.animation.Animator
import android.annotation.UiThread
import android.graphics.Point
import android.graphics.Rect
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout

import com.android.internal.annotations.GuardedBy
import com.android.systemui.animation.Interpolators
import com.android.systemui.R
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.plugins.statusbar.StatusBarStateController
import com.android.systemui.statusbar.StatusBarState.SHADE
import com.android.systemui.statusbar.StatusBarState.SHADE_LOCKED
import com.android.systemui.statusbar.phone.StatusBarContentInsetsChangedListener
import com.android.systemui.statusbar.phone.StatusBarContentInsetsProvider
import com.android.systemui.statusbar.policy.ConfigurationController
import com.android.systemui.util.concurrency.DelayableExecutor
import com.android.systemui.util.leak.RotationUtils
import com.android.systemui.util.leak.RotationUtils.ROTATION_LANDSCAPE
import com.android.systemui.util.leak.RotationUtils.ROTATION_NONE
import com.android.systemui.util.leak.RotationUtils.ROTATION_SEASCAPE
import com.android.systemui.util.leak.RotationUtils.ROTATION_UPSIDE_DOWN
import com.android.systemui.util.leak.RotationUtils.Rotation

import java.lang.IllegalStateException
import java.util.concurrent.Executor
import javax.inject.Inject

/**
 * Understands how to keep the persistent privacy dot in the corner of the screen in
 * ScreenDecorations, which does not rotate with the device.
 *
 * The basic principle here is that each dot will sit in a box that is equal to the margins of the
 * status bar (specifically the status_bar_contents view in PhoneStatusBarView). Each dot container
 * will have its gravity set towards the corner (i.e., top-right corner gets top|right gravity), and
 * the contained ImageView will be set to center_vertical and away from the corner horizontally. The
 * Views will match the status bar top padding and status bar height so that the dot can appear to
 * reside directly after the status bar system contents (basically after the battery).
 *
 * NOTE: any operation that modifies views directly must run on the provided executor, because
 * these views are owned by ScreenDecorations and it runs in its own thread
 */

@SysUISingleton
class PrivacyDotViewController @Inject constructor(
    @Main private val mainExecutor: Executor,
    private val stateController: StatusBarStateController,
    private val configurationController: ConfigurationController,
    private val contentInsetsProvider: StatusBarContentInsetsProvider,
    private val animationScheduler: SystemStatusAnimationScheduler
) {
    private var sbHeightPortrait = 0
    private var sbHeightLandscape = 0

    private lateinit var tl: View
    private lateinit var tr: View
    private lateinit var bl: View
    private lateinit var br: View

    // Only can be modified on @UiThread
    private var currentViewState: ViewState = ViewState()

    @GuardedBy("lock")
    private var nextViewState: ViewState = currentViewState.copy()
        set(value) {
            field = value
            scheduleUpdate()
        }
    private val lock = Object()
    private var cancelRunnable: Runnable? = null

    // Privacy dots are created in ScreenDecoration's UiThread, which is not the main thread
    private var uiExecutor: DelayableExecutor? = null

    private val views: Sequence<View>
        get() = if (!this::tl.isInitialized) sequenceOf() else sequenceOf(tl, tr, br, bl)

    init {
        contentInsetsProvider.addCallback(object : StatusBarContentInsetsChangedListener {
            override fun onStatusBarContentInsetsChanged() {
                dlog("onStatusBarContentInsetsChanged: ")
                setNewLayoutRects()
            }
        })
        configurationController.addCallback(object : ConfigurationController.ConfigurationListener {
            override fun onLayoutDirectionChanged(isRtl: Boolean) {
                synchronized(this) {
                    val corner = selectDesignatedCorner(nextViewState.rotation, isRtl)
                    nextViewState = nextViewState.copy(
                            layoutRtl = isRtl,
                            designatedCorner = corner
                    )
                }
            }
        })

        stateController.addCallback(object : StatusBarStateController.StateListener {
            override fun onExpandedChanged(isExpanded: Boolean) {
                updateStatusBarState()
            }

            override fun onStateChanged(newState: Int) {
                updateStatusBarState()
            }
        })
    }

    fun setUiExecutor(e: DelayableExecutor) {
        uiExecutor = e
    }

    fun setQsExpanded(expanded: Boolean) {
        dlog("setQsExpanded $expanded")
        synchronized(lock) {
            nextViewState = nextViewState.copy(qsExpanded = expanded)
        }
    }

    @UiThread
    fun setNewRotation(rot: Int) {
        dlog("updateRotation: $rot")

        val isRtl: Boolean
        synchronized(lock) {
            if (rot == nextViewState.rotation) {
                return
            }

            isRtl = nextViewState.layoutRtl
        }

        // If we rotated, hide all dotes until the next state resolves
        setCornerVisibilities(View.INVISIBLE)

        val newCorner = selectDesignatedCorner(rot, isRtl)
        val index = newCorner.cornerIndex()

        val h = when (rot) {
            0, 2 -> sbHeightPortrait
            1, 3 -> sbHeightLandscape
            else -> 0
        }
        synchronized(lock) {
            nextViewState = nextViewState.copy(
                    rotation = rot,
                    height = h,
                    designatedCorner = newCorner,
                    cornerIndex = index)
        }
    }

    @UiThread
    private fun hideDotView(dot: View, animate: Boolean) {
        dot.clearAnimation()
        if (animate) {
            dot.animate()
                    .setDuration(DURATION)
                    .setInterpolator(Interpolators.ALPHA_OUT)
                    .alpha(0f)
                    .withEndAction { dot.visibility = View.INVISIBLE }
                    .start()
        } else {
            dot.visibility = View.INVISIBLE
        }
    }

    @UiThread
    private fun showDotView(dot: View, animate: Boolean) {
        dot.clearAnimation()
        if (animate) {
            dot.visibility = View.VISIBLE
            dot.alpha = 0f
            dot.animate()
                    .alpha(1f)
                    .setDuration(DURATION)
                    .setInterpolator(Interpolators.ALPHA_IN)
                    .start()
        } else {
            dot.visibility = View.VISIBLE
            dot.alpha = 1f
        }
    }

    @UiThread
    private fun updateHeights(rot: Int) {
        val height = when (rot) {
            0, 2 -> sbHeightPortrait
            1, 3 -> sbHeightLandscape
            else -> 0
        }

        views.forEach { it.layoutParams.height = height }
    }

    // Update the gravity and margins of the privacy views
    @UiThread
    private fun updateRotations(rotation: Int) {
        // To keep a view in the corner, its gravity is always the description of its current corner
        // Therefore, just figure out which view is in which corner. This turns out to be something
        // like (myCorner - rot) mod 4, where topLeft = 0, topRight = 1, etc. and portrait = 0, and
        // rotating the device counter-clockwise increments rotation by 1

        views.forEach { corner ->
            val rotatedCorner = rotatedCorner(cornerForView(corner), rotation)
            (corner.layoutParams as FrameLayout.LayoutParams).apply {
                gravity = rotatedCorner.toGravity()
            }

            // Set the dot's view gravity to hug the status bar
            (corner.findViewById<View>(R.id.privacy_dot)
                    .layoutParams as FrameLayout.LayoutParams)
                        .gravity = rotatedCorner.innerGravity()
        }
    }

    @UiThread
    private fun updateCornerSizes(l: Int, r: Int, rotation: Int) {
        views.forEach { corner ->
            val rotatedCorner = rotatedCorner(cornerForView(corner), rotation)
            val w = widthForCorner(rotatedCorner, l, r)
            (corner.layoutParams as FrameLayout.LayoutParams).width = w
        }
    }

    @UiThread
    private fun setCornerSizes(state: ViewState) {
        // StatusBarContentInsetsProvider can tell us the location of the privacy indicator dot
        // in every rotation. The only thing we need to check is rtl
        val rtl = state.layoutRtl
        val size = Point()
        tl.context.display.getRealSize(size)
        val currentRotation = RotationUtils.getExactRotation(tl.context)

        val displayWidth: Int
        val displayHeight: Int
        if (currentRotation == ROTATION_LANDSCAPE || currentRotation == ROTATION_SEASCAPE) {
            displayWidth = size.y
            displayHeight = size.x
        } else {
            displayWidth = size.x
            displayHeight = size.y
        }

        var rot = activeRotationForCorner(tl, rtl)
        var contentInsets = state.contentRectForRotation(rot)
        (tl.layoutParams as FrameLayout.LayoutParams).apply {
            height = contentInsets.height()
            if (rtl) {
                width = contentInsets.left
            } else {
                width = displayHeight - contentInsets.right
            }
        }

        rot = activeRotationForCorner(tr, rtl)
        contentInsets = state.contentRectForRotation(rot)
        (tr.layoutParams as FrameLayout.LayoutParams).apply {
            height = contentInsets.height()
            if (rtl) {
                width = contentInsets.left
            } else {
                width = displayWidth - contentInsets.right
            }
        }

        rot = activeRotationForCorner(br, rtl)
        contentInsets = state.contentRectForRotation(rot)
        (br.layoutParams as FrameLayout.LayoutParams).apply {
            height = contentInsets.height()
            if (rtl) {
                width = contentInsets.left
            } else {
                width = displayHeight - contentInsets.right
            }
        }

        rot = activeRotationForCorner(bl, rtl)
        contentInsets = state.contentRectForRotation(rot)
        (bl.layoutParams as FrameLayout.LayoutParams).apply {
            height = contentInsets.height()
            if (rtl) {
                width = contentInsets.left
            } else {
                width = displayWidth - contentInsets.right
            }
        }
    }

    // Designated view will be the one at statusbar's view.END
    @UiThread
    private fun selectDesignatedCorner(r: Int, isRtl: Boolean): View? {
        if (!this::tl.isInitialized) {
            return null
        }

        return when (r) {
            0 -> if (isRtl) tl else tr
            1 -> if (isRtl) tr else br
            2 -> if (isRtl) br else bl
            3 -> if (isRtl) bl else tl
            else -> throw IllegalStateException("unknown rotation")
        }
    }

    // Track the current designated corner and maybe animate to a new rotation
    @UiThread
    private fun updateDesignatedCorner(newCorner: View?, shouldShowDot: Boolean) {
        if (shouldShowDot) {
            newCorner?.apply {
                clearAnimation()
                visibility = View.VISIBLE
                alpha = 0f
                animate()
                    .alpha(1.0f)
                    .setDuration(300)
                    .start()
            }
        }
    }

    @UiThread
    private fun setCornerVisibilities(vis: Int) {
        views.forEach { corner ->
            corner.visibility = vis
        }
    }

    private fun cornerForView(v: View): Int {
        return when (v) {
            tl -> TOP_LEFT
            tr -> TOP_RIGHT
            bl -> BOTTOM_LEFT
            br -> BOTTOM_RIGHT
            else -> throw IllegalArgumentException("not a corner view")
        }
    }

    private fun rotatedCorner(corner: Int, rotation: Int): Int {
        var modded = corner - rotation
        if (modded < 0) {
            modded += 4
        }

        return modded
    }

    @Rotation
    private fun activeRotationForCorner(corner: View, rtl: Boolean): Int {
        // Each corner will only be visible in a single rotation, based on rtl
        return when (corner) {
            tr -> if (rtl) ROTATION_LANDSCAPE else ROTATION_NONE
            tl -> if (rtl) ROTATION_NONE else ROTATION_SEASCAPE
            br -> if (rtl) ROTATION_UPSIDE_DOWN else ROTATION_LANDSCAPE
            else /* bl */ -> if (rtl) ROTATION_SEASCAPE else ROTATION_UPSIDE_DOWN
        }
    }

    private fun widthForCorner(corner: Int, left: Int, right: Int): Int {
        return when (corner) {
            TOP_LEFT, BOTTOM_LEFT -> left
            TOP_RIGHT, BOTTOM_RIGHT -> right
            else -> throw IllegalArgumentException("Unknown corner")
        }
    }

    fun initialize(topLeft: View, topRight: View, bottomLeft: View, bottomRight: View) {
        if (this::tl.isInitialized && this::tr.isInitialized &&
                this::bl.isInitialized && this::br.isInitialized) {
            if (tl == topLeft && tr == topRight && bl == bottomLeft && br == bottomRight) {
                return
            }
        }

        tl = topLeft
        tr = topRight
        bl = bottomLeft
        br = bottomRight

        val rtl = configurationController.isLayoutRtl
        val dc = selectDesignatedCorner(0, rtl)

        val index = dc.cornerIndex()

        mainExecutor.execute {
            animationScheduler.addCallback(systemStatusAnimationCallback)
        }

        val left = contentInsetsProvider.getStatusBarContentInsetsForRotation(ROTATION_SEASCAPE)
        val top = contentInsetsProvider.getStatusBarContentInsetsForRotation(ROTATION_NONE)
        val right = contentInsetsProvider.getStatusBarContentInsetsForRotation(ROTATION_LANDSCAPE)
        val bottom = contentInsetsProvider
                .getStatusBarContentInsetsForRotation(ROTATION_UPSIDE_DOWN)

        synchronized(lock) {
            nextViewState = nextViewState.copy(
                    viewInitialized = true,
                    designatedCorner = dc,
                    cornerIndex = index,
                    seascapeRect = left,
                    portraitRect = top,
                    landscapeRect = right,
                    upsideDownRect = bottom,
                    layoutRtl = rtl
            )
        }
    }

    /**
     * Set the status bar height in portrait and landscape, in pixels. If they are the same you can
     * pass the same value twice
     */
    fun setStatusBarHeights(portrait: Int, landscape: Int) {
        sbHeightPortrait = portrait
        sbHeightLandscape = landscape
    }

    private fun updateStatusBarState() {
        synchronized(lock) {
            nextViewState = nextViewState.copy(shadeExpanded = isShadeInQs())
        }
    }

    /**
     * If we are unlocked with an expanded shade, QS is showing. On keyguard, the shade is always
     * expanded so we use other signals from the panel view controller to know if QS is expanded
     */
    @GuardedBy("lock")
    private fun isShadeInQs(): Boolean {
        return (stateController.isExpanded && stateController.state == SHADE) ||
                (stateController.state == SHADE_LOCKED)
    }

    private fun scheduleUpdate() {
        dlog("scheduleUpdate: ")

        cancelRunnable?.run()
        cancelRunnable = uiExecutor?.executeDelayed({
            processNextViewState()
        }, 100)
    }

    @UiThread
    private fun processNextViewState() {
        dlog("processNextViewState: ")

        val newState: ViewState
        synchronized(lock) {
            newState = nextViewState.copy()
        }

        resolveState(newState)
    }

    @UiThread
    private fun resolveState(state: ViewState) {
        dlog("resolveState $state")
        if (!state.viewInitialized) {
            dlog("resolveState: view is not initialized. skipping.")
            return
        }

        if (state == currentViewState) {
            dlog("resolveState: skipping")
            return
        }

        if (state.rotation != currentViewState.rotation) {
            // A rotation has started, hide the views to avoid flicker
            updateRotations(state.rotation)
        }

        if (state.needsLayout(currentViewState)) {
            setCornerSizes(state)
            views.forEach { it.requestLayout() }
        }

        if (state.designatedCorner != currentViewState.designatedCorner) {
            updateDesignatedCorner(state.designatedCorner, state.shouldShowDot())
        }

        val shouldShow = state.shouldShowDot()
        if (shouldShow != currentViewState.shouldShowDot()) {
            if (shouldShow && state.designatedCorner != null) {
                showDotView(state.designatedCorner, true)
            } else if (!shouldShow && state.designatedCorner != null) {
                hideDotView(state.designatedCorner, true)
            }
        }

        currentViewState = state
    }

    private val systemStatusAnimationCallback: SystemStatusAnimationCallback =
            object : SystemStatusAnimationCallback {
        override fun onSystemStatusAnimationTransitionToPersistentDot(): Animator? {
            synchronized(lock) {
                nextViewState = nextViewState.copy(systemPrivacyEventIsActive = true)
            }

            return null
        }

        override fun onHidePersistentDot(): Animator? {
            synchronized(lock) {
                nextViewState = nextViewState.copy(systemPrivacyEventIsActive = false)
            }

            return null
        }
    }

    private fun View?.cornerIndex(): Int {
        if (this != null) {
            return cornerForView(this)
        }
        return -1
    }

    // Returns [left, top, right, bottom] aka [seascape, none, landscape, upside-down]
    private fun getLayoutRects(): List<Rect> {
        val left = contentInsetsProvider.getStatusBarContentInsetsForRotation(ROTATION_SEASCAPE)
        val top = contentInsetsProvider.getStatusBarContentInsetsForRotation(ROTATION_NONE)
        val right = contentInsetsProvider.getStatusBarContentInsetsForRotation(ROTATION_LANDSCAPE)
        val bottom = contentInsetsProvider
                .getStatusBarContentInsetsForRotation(ROTATION_UPSIDE_DOWN)

        return listOf(left, top, right, bottom)
    }

    private fun setNewLayoutRects() {
        val rects = getLayoutRects()

        synchronized(lock) {
            nextViewState = nextViewState.copy(
                    seascapeRect = rects[0],
                    portraitRect = rects[1],
                    landscapeRect = rects[2],
                    upsideDownRect = rects[3]
            )
        }
    }
}

private fun dlog(s: String) {
    if (DEBUG) {
        Log.d(TAG, s)
    }
}

private fun vlog(s: String) {
    if (DEBUG_VERBOSE) {
        Log.d(TAG, s)
    }
}

const val TOP_LEFT = 0
const val TOP_RIGHT = 1
const val BOTTOM_RIGHT = 2
const val BOTTOM_LEFT = 3
private const val DURATION = 160L
private const val TAG = "PrivacyDotViewController"
private const val DEBUG = false
private const val DEBUG_VERBOSE = false

private fun Int.toGravity(): Int {
    return when (this) {
        TOP_LEFT -> Gravity.TOP or Gravity.LEFT
        TOP_RIGHT -> Gravity.TOP or Gravity.RIGHT
        BOTTOM_LEFT -> Gravity.BOTTOM or Gravity.LEFT
        BOTTOM_RIGHT -> Gravity.BOTTOM or Gravity.RIGHT
        else -> throw IllegalArgumentException("Not a corner")
    }
}

private fun Int.innerGravity(): Int {
    return when (this) {
        TOP_LEFT -> Gravity.CENTER_VERTICAL or Gravity.RIGHT
        TOP_RIGHT -> Gravity.CENTER_VERTICAL or Gravity.LEFT
        BOTTOM_LEFT -> Gravity.CENTER_VERTICAL or Gravity.RIGHT
        BOTTOM_RIGHT -> Gravity.CENTER_VERTICAL or Gravity.LEFT
        else -> throw IllegalArgumentException("Not a corner")
    }
}

private data class ViewState(
    val viewInitialized: Boolean = false,

    val systemPrivacyEventIsActive: Boolean = false,
    val shadeExpanded: Boolean = false,
    val qsExpanded: Boolean = false,

    val portraitRect: Rect? = null,
    val landscapeRect: Rect? = null,
    val upsideDownRect: Rect? = null,
    val seascapeRect: Rect? = null,
    val layoutRtl: Boolean = false,

    val rotation: Int = 0,
    val height: Int = 0,
    val cornerIndex: Int = -1,
    val designatedCorner: View? = null
) {
    fun shouldShowDot(): Boolean {
        return systemPrivacyEventIsActive && !shadeExpanded && !qsExpanded
    }

    fun needsLayout(other: ViewState): Boolean {
        return rotation != other.rotation ||
                layoutRtl != other.layoutRtl ||
                portraitRect != other.portraitRect ||
                landscapeRect != other.landscapeRect ||
                upsideDownRect != other.upsideDownRect ||
                seascapeRect != other.seascapeRect
    }

    fun contentRectForRotation(@Rotation rot: Int): Rect {
        return when (rot) {
            ROTATION_NONE -> portraitRect!!
            ROTATION_LANDSCAPE -> landscapeRect!!
            ROTATION_UPSIDE_DOWN -> upsideDownRect!!
            ROTATION_SEASCAPE -> seascapeRect!!
            else -> throw IllegalArgumentException("not a rotation ($rot)")
        }
    }
}