summaryrefslogtreecommitdiff
path: root/PermissionController/src/com/android/permissioncontroller/safetycenter/ui/SafetyStatusPreference.java
blob: 0b8706a384d553e2cecbc039159036f158ed9bb1 (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
/*
 * Copyright (C) 2022 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.permissioncontroller.safetycenter.ui;

import static android.os.Build.VERSION_CODES.TIRAMISU;

import android.content.Context;
import android.graphics.drawable.Animatable2;
import android.graphics.drawable.AnimatedVectorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.safetycenter.SafetyCenterStatus;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.preference.Preference;
import androidx.preference.PreferenceViewHolder;

import com.android.permissioncontroller.R;
import com.android.permissioncontroller.safetycenter.ui.model.SafetyCenterViewModel;
import com.android.permissioncontroller.safetycenter.ui.model.StatusUiData;
import com.android.permissioncontroller.safetycenter.ui.view.StatusCardView;

import kotlin.Pair;

import java.util.List;
import java.util.Objects;

/** Preference which displays a visual representation of {@link SafetyCenterStatus}. */
@RequiresApi(TIRAMISU)
public class SafetyStatusPreference extends Preference implements ComparablePreference {

    @Nullable private StatusUiData mStatus;
    @Nullable private SafetyCenterViewModel mViewModel;

    private final TextFadeAnimator mTitleTextAnimator = new TextFadeAnimator(R.id.status_title);

    private final TextFadeAnimator mSummaryTextAnimator = new TextFadeAnimator(R.id.status_summary);

    private final TextFadeAnimator mAllTextAnimator =
            new TextFadeAnimator(List.of(R.id.status_title, R.id.status_summary));

    private boolean mFirstBind = true;

    public SafetyStatusPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        setLayoutResource(R.layout.preference_safety_status);
    }

    private boolean mIsTextChangeAnimationRunning;
    private final SafetyStatusAnimationSequencer mSequencer = new SafetyStatusAnimationSequencer();

    @Override
    public void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);

        if (mStatus == null) {
            return;
        }

        Context context = getContext();
        StatusCardView statusCardView = (StatusCardView) holder.itemView;
        configureButtons(context, statusCardView);
        statusCardView
                .getTitleAndSummaryContainerView()
                .setContentDescription(mStatus.getContentDescription(context));

        updateStatusIcon(statusCardView);

        updateStatusText(statusCardView.getTitleView(), statusCardView.getSummaryView());

        mFirstBind = false;
    }

    private void configureButtons(Context context, StatusCardView statusCardView) {
        statusCardView
                .getRescanButton()
                .setOnClickListener(
                        unused -> {
                            SafetyCenterViewModel viewModel = requireViewModel();
                            viewModel.rescan();
                            viewModel.getInteractionLogger().record(Action.SCAN_INITIATED);
                        });
        statusCardView
                .getReviewSettingsButton()
                .setOnClickListener(
                        unused -> {
                            SafetyCenterViewModel viewModel = requireViewModel();
                            viewModel.navigateToSafetyCenter(
                                    context, NavigationSource.QUICK_SETTINGS_TILE);
                            viewModel.getInteractionLogger().record(Action.REVIEW_SETTINGS_CLICKED);
                        });

        updateButtonState(statusCardView);
    }

    private void updateButtonState(StatusCardView statusCardView) {
        if (mStatus == null) return; // Shouldn't happen in practice but we do it for null safety.
        statusCardView.showButtons(mStatus);
    }

    private void updateStatusText(TextView title, TextView summary) {
        if (mFirstBind) {
            title.setText(mStatus.getTitle());
            summary.setText(mStatus.getSummary(getContext()));
        }
        runTextAnimationIfNeeded(title, summary);
    }

    private void updateStatusIcon(StatusCardView statusCardView) {
        int severityLevel = mStatus.getSeverityLevel();
        boolean isRefreshing = mStatus.isRefreshInProgress();

        handleAnimationSequencerAction(
                mSequencer.onUpdateReceived(isRefreshing, severityLevel),
                statusCardView,
                /* scanningAnimation= */ null);
    }

    private void runTextAnimationIfNeeded(TextView titleView, TextView summaryView) {
        if (mIsTextChangeAnimationRunning) {
            return;
        }
        String titleText = mStatus.getTitle().toString();
        String summaryText = mStatus.getSummary(getContext()).toString();
        boolean titleEquals = titleView.getText().toString().equals(titleText);
        boolean summaryEquals = summaryView.getText().toString().equals(summaryText);
        Runnable onFinish =
                () -> {
                    mIsTextChangeAnimationRunning = false;
                    runTextAnimationIfNeeded(titleView, summaryView);
                };
        mIsTextChangeAnimationRunning = !titleEquals || !summaryEquals;
        if (!titleEquals && !summaryEquals) {
            Pair<TextView, String> titleChange = new Pair<>(titleView, titleText);
            Pair<TextView, String> summaryChange = new Pair<>(summaryView, summaryText);
            mAllTextAnimator.animateChangeText(List.of(titleChange, summaryChange), onFinish);
        } else if (!titleEquals) {
            mTitleTextAnimator.animateChangeText(titleView, titleText, onFinish);
        } else if (!summaryEquals) {
            mSummaryTextAnimator.animateChangeText(summaryView, summaryText, onFinish);
        }
    }

    private void startScanningAnimation(StatusCardView statusCardView) {
        mSequencer.onStartScanningAnimationStart();
        ImageView statusImage = statusCardView.getStatusImageView();
        statusImage.setImageResource(
                StatusAnimationResolver.getScanningStartAnimation(
                        mSequencer.getCurrentlyVisibleSeverityLevel()));
        AnimatedVectorDrawable animation = (AnimatedVectorDrawable) statusImage.getDrawable();
        animation.registerAnimationCallback(
                new Animatable2.AnimationCallback() {
                    @Override
                    public void onAnimationEnd(Drawable drawable) {
                        handleAnimationSequencerAction(
                                mSequencer.onStartScanningAnimationEnd(),
                                statusCardView,
                                /* scanningAnimation= */ null);
                    }
                });
        animation.start();
    }

    private void continueScanningAnimation(StatusCardView statusCardView) {
        ImageView statusImage = statusCardView.getStatusImageView();

        // clear previous scan animation in case we need to continue with different severity level
        Drawable statusDrawable = statusImage.getDrawable();
        if (statusDrawable instanceof AnimatedVectorDrawable) {
            ((AnimatedVectorDrawable) statusDrawable).clearAnimationCallbacks();
        }

        statusImage.setImageResource(
                StatusAnimationResolver.getScanningAnimation(
                        mSequencer.getCurrentlyVisibleSeverityLevel()));
        AnimatedVectorDrawable scanningAnim = (AnimatedVectorDrawable) statusImage.getDrawable();
        scanningAnim.registerAnimationCallback(
                new Animatable2.AnimationCallback() {
                    @Override
                    public void onAnimationEnd(Drawable drawable) {
                        handleAnimationSequencerAction(
                                mSequencer.onContinueScanningAnimationEnd(
                                        mStatus.isRefreshInProgress(), mStatus.getSeverityLevel()),
                                statusCardView,
                                scanningAnim);
                    }
                });
        scanningAnim.start();
    }

    private void endScanningAnimation(StatusCardView statusCardView) {
        ImageView statusImage = statusCardView.getStatusImageView();
        Drawable statusDrawable = statusImage.getDrawable();
        int finishingSeverityLevel = mStatus.getSeverityLevel();
        if (!(statusDrawable instanceof AnimatedVectorDrawable)) {
            finishScanAnimation(statusCardView, finishingSeverityLevel);
            return;
        }
        AnimatedVectorDrawable animatedStatusDrawable = (AnimatedVectorDrawable) statusDrawable;

        if (!animatedStatusDrawable.isRunning()) {
            finishScanAnimation(statusCardView, finishingSeverityLevel);
            return;
        }

        int scanningSeverityLevel = mSequencer.getCurrentlyVisibleSeverityLevel();
        animatedStatusDrawable.clearAnimationCallbacks();
        animatedStatusDrawable.registerAnimationCallback(
                new Animatable2.AnimationCallback() {
                    @Override
                    public void onAnimationEnd(Drawable drawable) {
                        statusImage.setImageResource(
                                StatusAnimationResolver.getScanningEndAnimation(
                                        scanningSeverityLevel, finishingSeverityLevel));
                        AnimatedVectorDrawable animatedDrawable =
                                (AnimatedVectorDrawable) statusImage.getDrawable();
                        animatedDrawable.registerAnimationCallback(
                                new Animatable2.AnimationCallback() {
                                    @Override
                                    public void onAnimationEnd(Drawable drawable) {
                                        super.onAnimationEnd(drawable);
                                        finishScanAnimation(statusCardView, finishingSeverityLevel);
                                    }
                                });
                        animatedDrawable.start();
                    }
                });
    }

    private void finishScanAnimation(StatusCardView statusCardView, int finishedSeverityLevel) {
        updateButtonState(statusCardView);
        handleAnimationSequencerAction(
                mSequencer.onFinishScanAnimationEnd(
                        mStatus.isRefreshInProgress(), finishedSeverityLevel),
                statusCardView,
                /* scanningAnimation= */ null);
    }

    private void startIconChangeAnimation(StatusCardView statusCardView) {
        int finalSeverityLevel = mStatus.getSeverityLevel();
        int changeAnimationResId =
                StatusAnimationResolver.getStatusChangeAnimation(
                        mSequencer.getCurrentlyVisibleSeverityLevel(), finalSeverityLevel);
        if (changeAnimationResId == 0) {
            handleAnimationSequencerAction(
                    mSequencer.onCouldNotStartIconChangeAnimation(
                            mStatus.isRefreshInProgress(), finalSeverityLevel),
                    statusCardView,
                    /* scanningAnimation= */ null);
            return;
        }
        mSequencer.onIconChangeAnimationStart();
        statusCardView.getStatusImageView().setImageResource(changeAnimationResId);
        AnimatedVectorDrawable animation =
                (AnimatedVectorDrawable) statusCardView.getStatusImageView().getDrawable();
        animation.clearAnimationCallbacks();
        animation.registerAnimationCallback(
                new Animatable2.AnimationCallback() {
                    @Override
                    public void onAnimationEnd(Drawable drawable) {
                        handleAnimationSequencerAction(
                                mSequencer.onIconChangeAnimationEnd(
                                        mStatus.isRefreshInProgress(), finalSeverityLevel),
                                statusCardView,
                                /* scanningAnimation= */ null);
                    }
                });
        animation.start();
    }

    private void handleAnimationSequencerAction(
            @Nullable SafetyStatusAnimationSequencer.Action action,
            StatusCardView statusCardView,
            @Nullable AnimatedVectorDrawable scanningAnimation) {
        if (action == null) {
            return;
        }
        switch (action) {
            case START_SCANNING_ANIMATION:
                startScanningAnimation(statusCardView);
                break;
            case CONTINUE_SCANNING_ANIMATION:
                if (scanningAnimation != null) {
                    scanningAnimation.start();
                } else {
                    continueScanningAnimation(statusCardView);
                }
                break;
            case RESET_SCANNING_ANIMATION:
                continueScanningAnimation(statusCardView);
                break;
            case FINISH_SCANNING_ANIMATION:
                endScanningAnimation(statusCardView);
                break;
            case START_ICON_CHANGE_ANIMATION:
                startIconChangeAnimation(statusCardView);
                break;
            case CHANGE_ICON_WITHOUT_ANIMATION:
                setSettledStatus(statusCardView);
                break;
        }
    }

    private void setSettledStatus(StatusCardView statusCardView) {
        Drawable statusDrawable = statusCardView.getStatusImageView().getDrawable();
        if (statusDrawable instanceof AnimatedVectorDrawable) {
            ((AnimatedVectorDrawable) statusDrawable).clearAnimationCallbacks();
        }
        statusCardView
                .getStatusImageView()
                .setImageResource(
                        StatusUiData.Companion.getStatusImageResId(
                                mSequencer.getCurrentlyVisibleSeverityLevel()));
    }

    void setData(StatusUiData statusUiData) {
        mStatus = statusUiData;
        safeNotifyChanged();
    }

    void setViewModel(SafetyCenterViewModel viewModel) {
        mViewModel = Objects.requireNonNull(viewModel);
    }

    private SafetyCenterViewModel requireViewModel() {
        return Objects.requireNonNull(mViewModel);
    }

    // Calling notifyChanged while recyclerview is scrolling or computing layout will result in an
    // IllegalStateException. Post to handler to wait for UI to settle.
    private void safeNotifyChanged() {
        new Handler(Looper.getMainLooper()).post(this::notifyChanged);
    }

    @Override
    public boolean isSameItem(Preference preference) {
        return preference instanceof SafetyStatusPreference
                && TextUtils.equals(getKey(), preference.getKey());
    }

    @Override
    public boolean hasSameContents(Preference preference) {
        if (!(preference instanceof SafetyStatusPreference)) {
            return false;
        }
        SafetyStatusPreference other = (SafetyStatusPreference) preference;
        return Objects.equals(mStatus, other.mStatus);
    }
}