summaryrefslogtreecommitdiff
path: root/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/PreparationCoordinator.java
blob: 35fe0ee7cdb1f17b057e18024baa3c4f935b3a81 (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
/*
 * 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.statusbar.notification.collection.coordinator;

import static com.android.systemui.statusbar.notification.stack.NotificationChildrenContainer.NUMBER_OF_CHILDREN_WHEN_CHILDREN_EXPANDED;

import static java.util.Objects.requireNonNull;

import android.annotation.IntDef;
import android.os.RemoteException;
import android.service.notification.StatusBarNotification;
import android.util.ArrayMap;
import android.util.ArraySet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.statusbar.IStatusBarService;
import com.android.systemui.statusbar.notification.collection.GroupEntry;
import com.android.systemui.statusbar.notification.collection.ListEntry;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.ShadeListBuilder;
import com.android.systemui.statusbar.notification.collection.coordinator.dagger.CoordinatorScope;
import com.android.systemui.statusbar.notification.collection.inflation.BindEventManagerImpl;
import com.android.systemui.statusbar.notification.collection.inflation.NotifInflater;
import com.android.systemui.statusbar.notification.collection.inflation.NotifUiAdjustment;
import com.android.systemui.statusbar.notification.collection.inflation.NotifUiAdjustmentProvider;
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
import com.android.systemui.statusbar.notification.collection.render.NotifViewBarn;
import com.android.systemui.statusbar.notification.collection.render.NotifViewController;
import com.android.systemui.statusbar.notification.row.NotifInflationErrorManager;
import com.android.systemui.statusbar.notification.row.NotifInflationErrorManager.NotifInflationErrorListener;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * Kicks off core notification inflation and view rebinding when a notification is added or updated.
 * Aborts inflation when a notification is removed.
 *
 * If a notification was uninflated, this coordinator will filter the notification out from the
 * {@link ShadeListBuilder} until it is inflated.
 */
@CoordinatorScope
public class PreparationCoordinator implements Coordinator {
    private static final String TAG = "PreparationCoordinator";

    private final PreparationCoordinatorLogger mLogger;
    private final NotifInflater mNotifInflater;
    private final NotifInflationErrorManager mNotifErrorManager;
    private final NotifViewBarn mViewBarn;
    private final NotifUiAdjustmentProvider mAdjustmentProvider;
    private final ArrayMap<NotificationEntry, Integer> mInflationStates = new ArrayMap<>();

    /**
     * The map of notifications to the NotifUiAdjustment (i.e. parameters) that were calculated
     * when the inflation started.  If an update of any kind results in the adjustment changing,
     * then the row must be reinflated.  If the row is being inflated, then the inflation must be
     * aborted and restarted.
     */
    private final ArrayMap<NotificationEntry, NotifUiAdjustment> mInflationAdjustments =
            new ArrayMap<>();

    /**
     * The set of notifications that are currently inflating something. Note that this is
     * separate from inflation state as a view could either be uninflated or inflated and still be
     * inflating something.
     */
    private final ArraySet<NotificationEntry> mInflatingNotifs = new ArraySet<>();

    private final IStatusBarService mStatusBarService;

    /**
     * The number of children in a group we actually keep inflated since we don't actually show
     * all the children and don't need every child inflated at all times.
     */
    private final int mChildBindCutoff;

    /** How long we can delay a group while waiting for all children to inflate */
    private final long mMaxGroupInflationDelay;
    private final BindEventManagerImpl mBindEventManager;

    @Inject
    public PreparationCoordinator(
            PreparationCoordinatorLogger logger,
            NotifInflater notifInflater,
            NotifInflationErrorManager errorManager,
            NotifViewBarn viewBarn,
            NotifUiAdjustmentProvider adjustmentProvider,
            IStatusBarService service,
            BindEventManagerImpl bindEventManager) {
        this(
                logger,
                notifInflater,
                errorManager,
                viewBarn,
                adjustmentProvider,
                service,
                bindEventManager,
                CHILD_BIND_CUTOFF,
                MAX_GROUP_INFLATION_DELAY);
    }

    @VisibleForTesting
    PreparationCoordinator(
            PreparationCoordinatorLogger logger,
            NotifInflater notifInflater,
            NotifInflationErrorManager errorManager,
            NotifViewBarn viewBarn,
            NotifUiAdjustmentProvider adjustmentProvider,
            IStatusBarService service,
            BindEventManagerImpl bindEventManager,
            int childBindCutoff,
            long maxGroupInflationDelay) {
        mLogger = logger;
        mNotifInflater = notifInflater;
        mNotifErrorManager = errorManager;
        mViewBarn = viewBarn;
        mAdjustmentProvider = adjustmentProvider;
        mStatusBarService = service;
        mChildBindCutoff = childBindCutoff;
        mMaxGroupInflationDelay = maxGroupInflationDelay;
        mBindEventManager = bindEventManager;
    }

    @Override
    public void attach(NotifPipeline pipeline) {
        mNotifErrorManager.addInflationErrorListener(mInflationErrorListener);

        pipeline.addCollectionListener(mNotifCollectionListener);
        // Inflate after grouping/sorting since that affects what views to inflate.
        pipeline.addOnBeforeFinalizeFilterListener(this::inflateAllRequiredViews);
        pipeline.addFinalizeFilter(mNotifInflationErrorFilter);
        pipeline.addFinalizeFilter(mNotifInflatingFilter);
    }

    private final NotifCollectionListener mNotifCollectionListener = new NotifCollectionListener() {

        @Override
        public void onEntryInit(NotificationEntry entry) {
            mInflationStates.put(entry, STATE_UNINFLATED);
        }

        @Override
        public void onEntryUpdated(NotificationEntry entry) {
            abortInflation(entry, "entryUpdated");
            @InflationState int state = getInflationState(entry);
            if (state == STATE_INFLATED) {
                mInflationStates.put(entry, STATE_INFLATED_INVALID);
            } else if (state == STATE_ERROR) {
                // Updated so maybe it won't error out now.
                mInflationStates.put(entry, STATE_UNINFLATED);
            }
        }

        @Override
        public void onEntryRemoved(NotificationEntry entry, int reason) {
            abortInflation(entry, "entryRemoved reason=" + reason);
        }

        @Override
        public void onEntryCleanUp(NotificationEntry entry) {
            mInflationStates.remove(entry);
            mViewBarn.removeViewForEntry(entry);
            mInflationAdjustments.remove(entry);
        }
    };

    private final NotifFilter mNotifInflationErrorFilter = new NotifFilter(
            TAG + "InflationError") {
        /**
         * Filters out notifications that threw an error when attempting to inflate.
         */
        @Override
        public boolean shouldFilterOut(NotificationEntry entry, long now) {
            return getInflationState(entry) == STATE_ERROR;
        }
    };

    private final NotifFilter mNotifInflatingFilter = new NotifFilter(TAG + "Inflating") {
        private final Map<GroupEntry, Boolean> mIsDelayedGroupCache = new ArrayMap<>();

        /**
         * Filters out notifications that either (a) aren't inflated or (b) are part of a group
         * that isn't completely inflated yet
         */
        @Override
        public boolean shouldFilterOut(NotificationEntry entry, long now) {
            final GroupEntry parent = requireNonNull(entry.getParent());
            Boolean isMemberOfDelayedGroup = mIsDelayedGroupCache.get(parent);
            if (isMemberOfDelayedGroup == null) {
                isMemberOfDelayedGroup = shouldWaitForGroupToInflate(parent, now);
                mIsDelayedGroupCache.put(parent, isMemberOfDelayedGroup);
            }

            return !isInflated(entry) || isMemberOfDelayedGroup;
        }

        @Override
        public void onCleanup() {
            mIsDelayedGroupCache.clear();
        }
    };

    private final NotifInflationErrorListener mInflationErrorListener =
            new NotifInflationErrorListener() {
        @Override
        public void onNotifInflationError(NotificationEntry entry, Exception e) {
            mViewBarn.removeViewForEntry(entry);
            mInflationStates.put(entry, STATE_ERROR);
            try {
                final StatusBarNotification sbn = entry.getSbn();
                // report notification inflation errors back up
                // to notification delegates
                mStatusBarService.onNotificationError(
                        sbn.getPackageName(),
                        sbn.getTag(),
                        sbn.getId(),
                        sbn.getUid(),
                        sbn.getInitialPid(),
                        e.getMessage(),
                        sbn.getUser().getIdentifier());
            } catch (RemoteException ex) {
                // System server is dead, nothing to do about that
            }
            mNotifInflationErrorFilter.invalidateList();
        }

        @Override
        public void onNotifInflationErrorCleared(NotificationEntry entry) {
            mNotifInflationErrorFilter.invalidateList();
        }
    };

    private void inflateAllRequiredViews(List<ListEntry> entries) {
        for (int i = 0, size = entries.size(); i < size; i++) {
            ListEntry entry = entries.get(i);
            if (entry instanceof GroupEntry) {
                GroupEntry groupEntry = (GroupEntry) entry;
                inflateRequiredGroupViews(groupEntry);
            } else {
                NotificationEntry notifEntry = (NotificationEntry) entry;
                inflateRequiredNotifViews(notifEntry);
            }
        }
    }

    private void inflateRequiredGroupViews(GroupEntry groupEntry) {
        NotificationEntry summary = groupEntry.getSummary();
        List<NotificationEntry> children = groupEntry.getChildren();
        inflateRequiredNotifViews(summary);
        for (int j = 0; j < children.size(); j++) {
            NotificationEntry child = children.get(j);
            boolean childShouldBeBound = j < mChildBindCutoff;
            if (childShouldBeBound) {
                inflateRequiredNotifViews(child);
            } else {
                if (mInflatingNotifs.contains(child)) {
                    abortInflation(child, "Past last visible group child");
                }
                if (isInflated(child)) {
                    // TODO: May want to put an animation hint here so view manager knows to treat
                    //  this differently from a regular removal animation
                    freeNotifViews(child);
                }
            }
        }
    }

    private void inflateRequiredNotifViews(NotificationEntry entry) {
        NotifUiAdjustment newAdjustment = mAdjustmentProvider.calculateAdjustment(entry);
        if (mInflatingNotifs.contains(entry)) {
            // Already inflating this entry
            String errorIfNoOldAdjustment = "Inflating notification has no adjustments";
            if (needToReinflate(entry, newAdjustment, errorIfNoOldAdjustment)) {
                inflateEntry(entry, newAdjustment, "adjustment changed while inflating");
            }
            return;
        }
        @InflationState int state = mInflationStates.get(entry);
        switch (state) {
            case STATE_UNINFLATED:
                inflateEntry(entry, newAdjustment, "entryAdded");
                break;
            case STATE_INFLATED_INVALID:
                rebind(entry, newAdjustment, "entryUpdated");
                break;
            case STATE_INFLATED:
                String errorIfNoOldAdjustment = "Fully inflated notification has no adjustments";
                if (needToReinflate(entry, newAdjustment, errorIfNoOldAdjustment)) {
                    rebind(entry, newAdjustment, "adjustment changed after inflated");
                }
                break;
            case STATE_ERROR:
                if (needToReinflate(entry, newAdjustment, null)) {
                    inflateEntry(entry, newAdjustment, "adjustment changed after error");
                }
                break;
            default:
                // Nothing to do.
        }
    }

    private boolean needToReinflate(@NonNull NotificationEntry entry,
            @NonNull NotifUiAdjustment newAdjustment, @Nullable String oldAdjustmentMissingError) {
        NotifUiAdjustment oldAdjustment = mInflationAdjustments.get(entry);
        if (oldAdjustment == null) {
            if (oldAdjustmentMissingError == null) {
                return true;
            } else {
                throw new IllegalStateException(oldAdjustmentMissingError);
            }
        }
        return NotifUiAdjustment.needReinflate(oldAdjustment, newAdjustment);
    }

    private void inflateEntry(NotificationEntry entry,
            NotifUiAdjustment newAdjustment,
            String reason) {
        abortInflation(entry, reason);
        mInflationAdjustments.put(entry, newAdjustment);
        mInflatingNotifs.add(entry);
        NotifInflater.Params params = getInflaterParams(newAdjustment, reason);
        mNotifInflater.inflateViews(entry, params, this::onInflationFinished);
    }

    private void rebind(NotificationEntry entry,
            NotifUiAdjustment newAdjustment,
            String reason) {
        mInflationAdjustments.put(entry, newAdjustment);
        mInflatingNotifs.add(entry);
        NotifInflater.Params params = getInflaterParams(newAdjustment, reason);
        mNotifInflater.rebindViews(entry, params, this::onInflationFinished);
    }

    NotifInflater.Params getInflaterParams(NotifUiAdjustment adjustment, String reason) {
        return new NotifInflater.Params(adjustment.isMinimized(), reason);
    }

    private void abortInflation(NotificationEntry entry, String reason) {
        mLogger.logInflationAborted(entry.getKey(), reason);
        mNotifInflater.abortInflation(entry);
        mInflatingNotifs.remove(entry);
    }

    private void onInflationFinished(NotificationEntry entry, NotifViewController controller) {
        mLogger.logNotifInflated(entry.getKey());
        mInflatingNotifs.remove(entry);
        mViewBarn.registerViewForEntry(entry, controller);
        mInflationStates.put(entry, STATE_INFLATED);
        mBindEventManager.notifyViewBound(entry);
        mNotifInflatingFilter.invalidateList();
    }

    private void freeNotifViews(NotificationEntry entry) {
        mViewBarn.removeViewForEntry(entry);
        // TODO: clear the entry's row here, or even better, stop setting the row on the entry!
        mInflationStates.put(entry, STATE_UNINFLATED);
    }

    private boolean isInflated(NotificationEntry entry) {
        @InflationState int state = getInflationState(entry);
        return (state == STATE_INFLATED) || (state == STATE_INFLATED_INVALID);
    }

    private @InflationState int getInflationState(NotificationEntry entry) {
        Integer stateObj = mInflationStates.get(entry);
        requireNonNull(stateObj,
                "Asking state of a notification preparation coordinator doesn't know about");
        return stateObj;
    }

    private boolean shouldWaitForGroupToInflate(GroupEntry group, long now) {
        if (group == GroupEntry.ROOT_ENTRY || group.wasAttachedInPreviousPass()) {
            return false;
        }
        if (isBeyondGroupInitializationWindow(group, now)) {
            mLogger.logGroupInflationTookTooLong(group.getKey());
            return false;
        }
        if (mInflatingNotifs.contains(group.getSummary())) {
            mLogger.logDelayingGroupRelease(group.getKey(), group.getSummary().getKey());
            return true;
        }
        for (NotificationEntry child : group.getChildren()) {
            if (mInflatingNotifs.contains(child) && !child.wasAttachedInPreviousPass()) {
                mLogger.logDelayingGroupRelease(group.getKey(), child.getKey());
                return true;
            }
        }
        mLogger.logDoneWaitingForGroupInflation(group.getKey());
        return false;
    }

    private boolean isBeyondGroupInitializationWindow(GroupEntry entry, long now) {
        return now - entry.getCreationTime() > mMaxGroupInflationDelay;
    }

    @Retention(RetentionPolicy.SOURCE)
    @IntDef(prefix = {"STATE_"},
            value = {STATE_UNINFLATED, STATE_INFLATED_INVALID, STATE_INFLATED, STATE_ERROR})
    @interface InflationState {}

    /** The notification has no views attached. */
    private static final int STATE_UNINFLATED = 0;

    /** The notification is inflated. */
    private static final int STATE_INFLATED = 1;

    /**
     * The notification is inflated, but its content may be out-of-date since the notification has
     * been updated.
     */
    private static final int STATE_INFLATED_INVALID = 2;

    /** The notification errored out while inflating */
    private static final int STATE_ERROR = -1;

    /**
     * How big the buffer of extra views we keep around to be ready to show when we do need to
     * dynamically inflate a row.
     */
    private static final int EXTRA_VIEW_BUFFER_COUNT = 1;

    private static final long MAX_GROUP_INFLATION_DELAY = 500;

    private static final int CHILD_BIND_CUTOFF =
            NUMBER_OF_CHILDREN_WHEN_CHILDREN_EXPANDED + EXTRA_VIEW_BUFFER_COUNT;
}