Debian Codegraph @

libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 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 package com.android.wm.shell.bubbles;
17
18 import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
19 import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
20 import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_DATA;
21 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
22 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
23
24 import android.annotation.NonNull;
25 import android.app.PendingIntent;
26 import android.content.Context;
27 import android.content.LocusId;
28 import android.content.pm.ShortcutInfo;
29 import android.text.TextUtils;
30 import android.util.ArrayMap;
31 import android.util.ArraySet;
32 import android.util.Log;
33 import android.util.Pair;
34 import android.view.View;
35
36 import androidx.annotation.Nullable;
37
38 import com.android.internal.annotations.VisibleForTesting;
39 import com.android.internal.util.FrameworkStatsLog;
40 import com.android.wm.shell.R;
41 import com.android.wm.shell.bubbles.Bubbles.DismissReason;
42
43 import java.io.PrintWriter;
44 import java.util.ArrayList;
45 import java.util.Collections;
46 import java.util.Comparator;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.List;
50 import java.util.Objects;
51 import java.util.Set;
52 import java.util.concurrent.Executor;
53 import java.util.function.Consumer;
54 import java.util.function.Predicate;
55
56 /**
57 * Keeps track of active bubbles.
58 */
59 public class BubbleData {
60
61 private BubbleLogger mLogger;
62
63 private int mCurrentUserId;
64
65 private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleData" : TAG_BUBBLES;
66
67 private static final Comparator<Bubble> BUBBLES_BY_SORT_KEY_DESCENDING =
68 Comparator.comparing(BubbleData::sortKey).reversed();
69
70 /** Contains information about changes that have been made to the state of bubbles. */
71 static final class Update {
72 boolean expandedChanged;
73 boolean selectionChanged;
74 boolean orderChanged;
75 boolean suppressedSummaryChanged;
76 boolean expanded;
77 @Nullable BubbleViewProvider selectedBubble;
78 @Nullable Bubble addedBubble;
79 @Nullable Bubble updatedBubble;
80 @Nullable Bubble addedOverflowBubble;
81 @Nullable Bubble removedOverflowBubble;
82 @Nullable Bubble suppressedBubble;
83 @Nullable Bubble unsuppressedBubble;
84 @Nullable String suppressedSummaryGroup;
85 // Pair with Bubble and @DismissReason Integer
86 final List<Pair<Bubble, Integer>> removedBubbles = new ArrayList<>();
87
88 // A read-only view of the bubbles list, changes there will be reflected here.
89 final List<Bubble> bubbles;
90 final List<Bubble> overflowBubbles;
91
92 private Update(List<Bubble> row, List<Bubble> overflow) {
93 bubbles = Collections.unmodifiableList(row);
94 overflowBubbles = Collections.unmodifiableList(overflow);
95 }
96
97 boolean anythingChanged() {
98 return expandedChanged
99 || selectionChanged
100 || addedBubble != null
101 || updatedBubble != null
102 || !removedBubbles.isEmpty()
103 || addedOverflowBubble != null
104 || removedOverflowBubble != null
105 || orderChanged
106 || suppressedBubble != null
107 || unsuppressedBubble != null
108 || suppressedSummaryChanged
109 || suppressedSummaryGroup != null;
110 }
111
112 void bubbleRemoved(Bubble bubbleToRemove, @DismissReason int reason) {
113 removedBubbles.add(new Pair<>(bubbleToRemove, reason));
114 }
115 }
116
117 /**
118 * This interface reports changes to the state and appearance of bubbles which should be applied
119 * as necessary to the UI.
120 */
121 interface Listener {
122 /** Reports changes have have occurred as a result of the most recent operation. */
123 void applyUpdate(Update update);
124 }
125
126 interface TimeSource {
127 long currentTimeMillis();
128 }
129
130 private final Context mContext;
131 private final BubblePositioner mPositioner;
132 private final Executor mMainExecutor;
133 /** Bubbles that are actively in the stack. */
134 private final List<Bubble> mBubbles;
135 /** Bubbles that aged out to overflow. */
136 private final List<Bubble> mOverflowBubbles;
137 /** Bubbles that are being loaded but haven't been added to the stack just yet. */
138 private final HashMap<String, Bubble> mPendingBubbles;
139 /** Bubbles that are suppressed due to locusId. */
140 private final ArrayMap<LocusId, Bubble> mSuppressedBubbles = new ArrayMap<>();
141 /** Visible locusIds. */
142 private final ArraySet<LocusId> mVisibleLocusIds = new ArraySet<>();
143
144 private BubbleViewProvider mSelectedBubble;
145 private final BubbleOverflow mOverflow;
146 private boolean mShowingOverflow;
147 private boolean mExpanded;
148 private int mMaxBubbles;
149 private int mMaxOverflowBubbles;
150
151 private boolean mNeedsTrimming;
152
153 // State tracked during an operation -- keeps track of what listener events to dispatch.
154 private Update mStateChange;
155
156 private TimeSource mTimeSource = System::currentTimeMillis;
157
158 @Nullable
159 private Listener mListener;
160
161 private Bubbles.BubbleMetadataFlagListener mBubbleMetadataFlagListener;
162 private Bubbles.PendingIntentCanceledListener mCancelledListener;
163
164 /**
165 * We track groups with summaries that aren't visibly displayed but still kept around because
166 * the bubble(s) associated with the summary still exist.
167 *
168 * The summary must be kept around so that developers can cancel it (and hence the bubbles
169 * associated with it). This list is used to check if the summary should be hidden from the
170 * shade.
171 *
172 * Key: group key of the notification
173 * Value: key of the notification
174 */
175 private HashMap<String, String> mSuppressedGroupKeys = new HashMap<>();
176
177 public BubbleData(Context context, BubbleLogger bubbleLogger, BubblePositioner positioner,
178 Executor mainExecutor) {
179 mContext = context;
180 mLogger = bubbleLogger;
181 mPositioner = positioner;
182 mMainExecutor = mainExecutor;
183 mOverflow = new BubbleOverflow(context, positioner);
184 mBubbles = new ArrayList<>();
185 mOverflowBubbles = new ArrayList<>();
186 mPendingBubbles = new HashMap<>();
187 mStateChange = new Update(mBubbles, mOverflowBubbles);
188 mMaxBubbles = mPositioner.getMaxBubbles();
189 mMaxOverflowBubbles = mContext.getResources().getInteger(R.integer.bubbles_max_overflow);
190 }
191
192 public void setSuppressionChangedListener(Bubbles.BubbleMetadataFlagListener listener) {
193 mBubbleMetadataFlagListener = listener;
194 }
195
196 public void setPendingIntentCancelledListener(
197 Bubbles.PendingIntentCanceledListener listener) {
198 mCancelledListener = listener;
199 }
200
201 public void onMaxBubblesChanged() {
202 mMaxBubbles = mPositioner.getMaxBubbles();
203 if (!mExpanded) {
204 trim();
205 dispatchPendingChanges();
206 } else {
207 mNeedsTrimming = true;
208 }
209 }
210
211 public boolean hasBubbles() {
212 return !mBubbles.isEmpty();
213 }
214
215 public boolean hasOverflowBubbles() {
216 return !mOverflowBubbles.isEmpty();
217 }
218
219 public boolean isExpanded() {
220 return mExpanded;
221 }
222
223 public boolean hasAnyBubbleWithKey(String key) {
224 return hasBubbleInStackWithKey(key) || hasOverflowBubbleWithKey(key)
225 || hasSuppressedBubbleWithKey(key);
226 }
227
228 public boolean hasBubbleInStackWithKey(String key) {
229 return getBubbleInStackWithKey(key) != null;
230 }
231
232 public boolean hasOverflowBubbleWithKey(String key) {
233 return getOverflowBubbleWithKey(key) != null;
234 }
235
236 /**
237 * Check if there are any bubbles suppressed with the given notification <code>key</code>
238 */
239 public boolean hasSuppressedBubbleWithKey(String key) {
240 return mSuppressedBubbles.values().stream().anyMatch(b -> b.getKey().equals(key));
241 }
242
243 /**
244 * Check if there are any bubbles suppressed with the given <code>LocusId</code>
245 */
246 public boolean isSuppressedWithLocusId(LocusId locusId) {
247 return mSuppressedBubbles.get(locusId) != null;
248 }
249
250 @Nullable
251 public BubbleViewProvider getSelectedBubble() {
252 return mSelectedBubble;
253 }
254
255 public BubbleOverflow getOverflow() {
256 return mOverflow;
257 }
258
259 /** Return a read-only current active bubble lists. */
260 public List<Bubble> getActiveBubbles() {
261 return Collections.unmodifiableList(mBubbles);
262 }
263
264 public void setExpanded(boolean expanded) {
265 if (DEBUG_BUBBLE_DATA) {
266 Log.d(TAG, "setExpanded: " + expanded);
267 }
268 setExpandedInternal(expanded);
269 dispatchPendingChanges();
270 }
271
272 public void setSelectedBubble(BubbleViewProvider bubble) {
273 if (DEBUG_BUBBLE_DATA) {
274 Log.d(TAG, "setSelectedBubble: " + bubble);
275 }
276 setSelectedBubbleInternal(bubble);
277 dispatchPendingChanges();
278 }
279
280 void setShowingOverflow(boolean showingOverflow) {
281 mShowingOverflow = showingOverflow;
282 }
283
284 boolean isShowingOverflow() {
285 return mShowingOverflow && (isExpanded() || mPositioner.showingInTaskbar());
286 }
287
288 /**
289 * Constructs a new bubble or returns an existing one. Does not add new bubbles to
290 * bubble data, must go through {@link #notificationEntryUpdated(Bubble, boolean, boolean)}
291 * for that.
292 *
293 * @param entry The notification entry to use, only null if it's a bubble being promoted from
294 * the overflow that was persisted over reboot.
295 * @param persistedBubble The bubble to use, only non-null if it's a bubble being promoted from
296 * the overflow that was persisted over reboot.
297 */
298 public Bubble getOrCreateBubble(BubbleEntry entry, Bubble persistedBubble) {
299 String key = persistedBubble != null ? persistedBubble.getKey() : entry.getKey();
300 Bubble bubbleToReturn = getBubbleInStackWithKey(key);
301
302 if (bubbleToReturn == null) {
303 bubbleToReturn = getOverflowBubbleWithKey(key);
304 if (bubbleToReturn != null) {
305 // Promoting from overflow
306 mOverflowBubbles.remove(bubbleToReturn);
307 } else if (mPendingBubbles.containsKey(key)) {
308 // Update while it was pending
309 bubbleToReturn = mPendingBubbles.get(key);
310 } else if (entry != null) {
311 // New bubble
312 bubbleToReturn = new Bubble(entry, mBubbleMetadataFlagListener, mCancelledListener,
313 mMainExecutor);
314 } else {
315 // Persisted bubble being promoted
316 bubbleToReturn = persistedBubble;
317 }
318 }
319
320 if (entry != null) {
321 bubbleToReturn.setEntry(entry);
322 }
323 mPendingBubbles.put(key, bubbleToReturn);
324 return bubbleToReturn;
325 }
326
327 /**
328 * When this method is called it is expected that all info in the bubble has completed loading.
329 * @see Bubble#inflate(BubbleViewInfoTask.Callback, Context, BubbleController, BubbleStackView,
330 * BubbleIconFactory, boolean)
331 */
332 void notificationEntryUpdated(Bubble bubble, boolean suppressFlyout, boolean showInShade) {
333 if (DEBUG_BUBBLE_DATA) {
334 Log.d(TAG, "notificationEntryUpdated: " + bubble);
335 }
336 mPendingBubbles.remove(bubble.getKey()); // No longer pending once we're here
337 Bubble prevBubble = getBubbleInStackWithKey(bubble.getKey());
338 suppressFlyout |= !bubble.isTextChanged();
339
340 if (prevBubble == null) {
341 // Create a new bubble
342 bubble.setSuppressFlyout(suppressFlyout);
343 bubble.markUpdatedAt(mTimeSource.currentTimeMillis());
344 doAdd(bubble);
345 trim();
346 } else {
347 // Updates an existing bubble
348 bubble.setSuppressFlyout(suppressFlyout);
349 // If there is no flyout, we probably shouldn't show the bubble at the top
350 doUpdate(bubble, !suppressFlyout /* reorder */);
351 }
352
353 if (bubble.shouldAutoExpand()) {
354 bubble.setShouldAutoExpand(false);
355 setSelectedBubbleInternal(bubble);
356 if (!mExpanded) {
357 setExpandedInternal(true);
358 }
359 }
360
361 boolean isBubbleExpandedAndSelected = mExpanded && mSelectedBubble == bubble;
362 boolean suppress = isBubbleExpandedAndSelected || !showInShade || !bubble.showInShade();
363 bubble.setSuppressNotification(suppress);
364 bubble.setShowDot(!isBubbleExpandedAndSelected /* show */);
365
366 LocusId locusId = bubble.getLocusId();
367 if (locusId != null) {
368 boolean isSuppressed = mSuppressedBubbles.containsKey(locusId);
369 if (isSuppressed && (!bubble.isSuppressed() || !bubble.isSuppressable())) {
370 mSuppressedBubbles.remove(locusId);
371 doUnsuppress(bubble);
372 } else if (!isSuppressed && (bubble.isSuppressed()
373 || bubble.isSuppressable() && mVisibleLocusIds.contains(locusId))) {
374 mSuppressedBubbles.put(locusId, bubble);
375 doSuppress(bubble);
376 }
377 }
378 dispatchPendingChanges();
379 }
380
381 /**
382 * Dismisses the bubble with the matching key, if it exists.
383 */
384 public void dismissBubbleWithKey(String key, @DismissReason int reason) {
385 if (DEBUG_BUBBLE_DATA) {
386 Log.d(TAG, "notificationEntryRemoved: key=" + key + " reason=" + reason);
387 }
388 doRemove(key, reason);
389 dispatchPendingChanges();
390 }
391
392 /**
393 * Adds a group key indicating that the summary for this group should be suppressed.
394 *
395 * @param groupKey the group key of the group whose summary should be suppressed.
396 * @param notifKey the notification entry key of that summary.
397 */
398 void addSummaryToSuppress(String groupKey, String notifKey) {
399 mSuppressedGroupKeys.put(groupKey, notifKey);
400 mStateChange.suppressedSummaryChanged = true;
401 mStateChange.suppressedSummaryGroup = groupKey;
402 dispatchPendingChanges();
403 }
404
405 /**
406 * Retrieves the notif entry key of the summary associated with the provided group key.
407 *
408 * @param groupKey the group to look up
409 * @return the key for the notification that is the summary of this group.
410 */
411 String getSummaryKey(String groupKey) {
412 return mSuppressedGroupKeys.get(groupKey);
413 }
414
415 /**
416 * Removes a group key indicating that summary for this group should no longer be suppressed.
417 */
418 void removeSuppressedSummary(String groupKey) {
419 mSuppressedGroupKeys.remove(groupKey);
420 mStateChange.suppressedSummaryChanged = true;
421 mStateChange.suppressedSummaryGroup = groupKey;
422 dispatchPendingChanges();
423 }
424
425 /**
426 * Whether the summary for the provided group key is suppressed.
427 */
428 @VisibleForTesting
429 public boolean isSummarySuppressed(String groupKey) {
430 return mSuppressedGroupKeys.containsKey(groupKey);
431 }
432
433 /**
434 * Removes bubbles from the given package whose shortcut are not in the provided list of valid
435 * shortcuts.
436 */
437 public void removeBubblesWithInvalidShortcuts(
438 String packageName, List<ShortcutInfo> validShortcuts, int reason) {
439
440 final Set<String> validShortcutIds = new HashSet<String>();
441 for (ShortcutInfo info : validShortcuts) {
442 validShortcutIds.add(info.getId());
443 }
444
445 final Predicate<Bubble> invalidBubblesFromPackage = bubble -> {
446 final boolean bubbleIsFromPackage = packageName.equals(bubble.getPackageName());
447 final boolean isShortcutBubble = bubble.hasMetadataShortcutId();
448 if (!bubbleIsFromPackage || !isShortcutBubble) {
449 return false;
450 }
451 final boolean hasShortcutIdAndValidShortcut =
452 bubble.hasMetadataShortcutId()
453 && bubble.getShortcutInfo() != null
454 && bubble.getShortcutInfo().isEnabled()
455 && validShortcutIds.contains(bubble.getShortcutInfo().getId());
456 return bubbleIsFromPackage && !hasShortcutIdAndValidShortcut;
457 };
458
459 final Consumer<Bubble> removeBubble = bubble ->
460 dismissBubbleWithKey(bubble.getKey(), reason);
461
462 performActionOnBubblesMatching(getBubbles(), invalidBubblesFromPackage, removeBubble);
463 performActionOnBubblesMatching(
464 getOverflowBubbles(), invalidBubblesFromPackage, removeBubble);
465 }
466
467 /** Removes all bubbles from the given package. */
468 public void removeBubblesWithPackageName(String packageName, int reason) {
469 final Predicate<Bubble> bubbleMatchesPackage = bubble ->
470 bubble.getPackageName().equals(packageName);
471
472 final Consumer<Bubble> removeBubble = bubble ->
473 dismissBubbleWithKey(bubble.getKey(), reason);
474
475 performActionOnBubblesMatching(getBubbles(), bubbleMatchesPackage, removeBubble);
476 performActionOnBubblesMatching(getOverflowBubbles(), bubbleMatchesPackage, removeBubble);
477 }
478
479 /** Removes all bubbles for the given user. */
480 public void removeBubblesForUser(int userId) {
481 List<Bubble> removedBubbles = filterAllBubbles(bubble ->
482 userId == bubble.getUser().getIdentifier());
483 for (Bubble b : removedBubbles) {
484 doRemove(b.getKey(), Bubbles.DISMISS_USER_REMOVED);
485 }
486 if (!removedBubbles.isEmpty()) {
487 dispatchPendingChanges();
488 }
489 }
490
491 private void doAdd(Bubble bubble) {
492 if (DEBUG_BUBBLE_DATA) {
493 Log.d(TAG, "doAdd: " + bubble);
494 }
495 mBubbles.add(0, bubble);
496 mStateChange.addedBubble = bubble;
497 // Adding the first bubble doesn't change the order
498 mStateChange.orderChanged = mBubbles.size() > 1;
499 if (!isExpanded()) {
500 setSelectedBubbleInternal(mBubbles.get(0));
501 }
502 }
503
504 private void trim() {
505 if (mBubbles.size() > mMaxBubbles) {
506 int numtoRemove = mBubbles.size() - mMaxBubbles;
507 ArrayList<Bubble> toRemove = new ArrayList<>();
508 mBubbles.stream()
509 // sort oldest first (ascending lastActivity)
510 .sorted(Comparator.comparingLong(Bubble::getLastActivity))
511 // skip the selected bubble
512 .filter((b) -> !b.equals(mSelectedBubble))
513 .forEachOrdered((b) -> {
514 if (toRemove.size() < numtoRemove) {
515 toRemove.add(b);
516 }
517 });
518 toRemove.forEach((b) -> doRemove(b.getKey(), Bubbles.DISMISS_AGED));
519 }
520 }
521
522 private void doUpdate(Bubble bubble, boolean reorder) {
523 if (DEBUG_BUBBLE_DATA) {
524 Log.d(TAG, "doUpdate: " + bubble);
525 }
526 mStateChange.updatedBubble = bubble;
527 if (!isExpanded() && reorder) {
528 int prevPos = mBubbles.indexOf(bubble);
529 mBubbles.remove(bubble);
530 mBubbles.add(0, bubble);
531 mStateChange.orderChanged = prevPos != 0;
532 setSelectedBubbleInternal(mBubbles.get(0));
533 }
534 }
535
536 /** Runs the given action on Bubbles that match the given predicate. */
537 private void performActionOnBubblesMatching(
538 List<Bubble> bubbles, Predicate<Bubble> predicate, Consumer<Bubble> action) {
539 final List<Bubble> matchingBubbles = new ArrayList<>();
540 for (Bubble bubble : bubbles) {
541 if (predicate.test(bubble)) {
542 matchingBubbles.add(bubble);
543 }
544 }
545
546 for (Bubble matchingBubble : matchingBubbles) {
547 action.accept(matchingBubble);
548 }
549 }
550
551 private void doRemove(String key, @DismissReason int reason) {
552 if (DEBUG_BUBBLE_DATA) {
553 Log.d(TAG, "doRemove: " + key);
554 }
555 // If it was pending remove it
556 if (mPendingBubbles.containsKey(key)) {
557 mPendingBubbles.remove(key);
558 }
559
560 boolean shouldRemoveHiddenBubble = reason == Bubbles.DISMISS_NOTIF_CANCEL
561 || reason == Bubbles.DISMISS_GROUP_CANCELLED
562 || reason == Bubbles.DISMISS_NO_LONGER_BUBBLE
563 || reason == Bubbles.DISMISS_BLOCKED
564 || reason == Bubbles.DISMISS_SHORTCUT_REMOVED
565 || reason == Bubbles.DISMISS_PACKAGE_REMOVED
566 || reason == Bubbles.DISMISS_USER_CHANGED
567 || reason == Bubbles.DISMISS_USER_REMOVED;
568
569 int indexToRemove = indexForKey(key);
570 if (indexToRemove == -1) {
571 if (hasOverflowBubbleWithKey(key)
572 && shouldRemoveHiddenBubble) {
573
574 Bubble b = getOverflowBubbleWithKey(key);
575 if (DEBUG_BUBBLE_DATA) {
576 Log.d(TAG, "Cancel overflow bubble: " + b);
577 }
578 if (b != null) {
579 b.stopInflation();
580 }
581 mLogger.logOverflowRemove(b, reason);
582 mOverflowBubbles.remove(b);
583 mStateChange.bubbleRemoved(b, reason);
584 mStateChange.removedOverflowBubble = b;
585 }
586 if (hasSuppressedBubbleWithKey(key) && shouldRemoveHiddenBubble) {
587 Bubble b = getSuppressedBubbleWithKey(key);
588 if (DEBUG_BUBBLE_DATA) {
589 Log.d(TAG, "Cancel suppressed bubble: " + b);
590 }
591 if (b != null) {
592 mSuppressedBubbles.remove(b.getLocusId());
593 b.stopInflation();
594 mStateChange.bubbleRemoved(b, reason);
595 }
596 }
597 return;
598 }
599 Bubble bubbleToRemove = mBubbles.get(indexToRemove);
600 bubbleToRemove.stopInflation();
601 overflowBubble(reason, bubbleToRemove);
602
603 if (mBubbles.size() == 1) {
604 setExpandedInternal(false);
605 // Don't use setSelectedBubbleInternal because we don't want to trigger an
606 // applyUpdate
607 mSelectedBubble = null;
608 }
609 if (indexToRemove < mBubbles.size() - 1) {
610 // Removing anything but the last bubble means positions will change.
611 mStateChange.orderChanged = true;
612 }
613 mBubbles.remove(indexToRemove);
614 mStateChange.bubbleRemoved(bubbleToRemove, reason);
615 if (!isExpanded()) {
616 mStateChange.orderChanged |= repackAll();
617 }
618
619 // Note: If mBubbles.isEmpty(), then mSelectedBubble is now null.
620 if (Objects.equals(mSelectedBubble, bubbleToRemove)) {
621 setNewSelectedIndex(indexToRemove);
622 }
623 maybeSendDeleteIntent(reason, bubbleToRemove);
624 }
625
626 private void setNewSelectedIndex(int indexOfSelected) {
627 if (mBubbles.isEmpty()) {
628 Log.w(TAG, "Bubbles list empty when attempting to select index: " + indexOfSelected);
629 return;
630 }
631 // Move selection to the new bubble at the same position.
632 int newIndex = Math.min(indexOfSelected, mBubbles.size() - 1);
633 if (DEBUG_BUBBLE_DATA) {
634 Log.d(TAG, "setNewSelectedIndex: " + indexOfSelected);
635 }
636 BubbleViewProvider newSelected = mBubbles.get(newIndex);
637 setSelectedBubbleInternal(newSelected);
638 }
639
640 private void doSuppress(Bubble bubble) {
641 if (DEBUG_BUBBLE_DATA) {
642 Log.d(TAG, "doSuppressed: " + bubble);
643 }
644 mStateChange.suppressedBubble = bubble;
645 bubble.setSuppressBubble(true);
646
647 int indexToRemove = mBubbles.indexOf(bubble);
648 // Order changes if we are not suppressing the last bubble
649 mStateChange.orderChanged = !(mBubbles.size() - 1 == indexToRemove);
650 mBubbles.remove(indexToRemove);
651
652 // Update selection if we suppressed the selected bubble
653 if (Objects.equals(mSelectedBubble, bubble)) {
654 if (mBubbles.isEmpty()) {
655 // Don't use setSelectedBubbleInternal because we don't want to trigger an
656 // applyUpdate
657 mSelectedBubble = null;
658 } else {
659 // Mark new first bubble as selected
660 setNewSelectedIndex(0);
661 }
662 }
663 }
664
665 private void doUnsuppress(Bubble bubble) {
666 if (DEBUG_BUBBLE_DATA) {
667 Log.d(TAG, "doUnsuppressed: " + bubble);
668 }
669 bubble.setSuppressBubble(false);
670 mStateChange.unsuppressedBubble = bubble;
671 mBubbles.add(bubble);
672 if (mBubbles.size() > 1) {
673 // See where the bubble actually lands
674 repackAll();
675 mStateChange.orderChanged = true;
676 }
677 if (mBubbles.get(0) == bubble) {
678 // Unsuppressed bubble is sorted to first position. Mark it as the selected.
679 setNewSelectedIndex(0);
680 }
681 }
682
683 void overflowBubble(@DismissReason int reason, Bubble bubble) {
684 if (bubble.getPendingIntentCanceled()
685 || !(reason == Bubbles.DISMISS_AGED
686 || reason == Bubbles.DISMISS_USER_GESTURE
687 || reason == Bubbles.DISMISS_RELOAD_FROM_DISK)) {
688 return;
689 }
690 if (DEBUG_BUBBLE_DATA) {
691 Log.d(TAG, "Overflowing: " + bubble);
692 }
693 mLogger.logOverflowAdd(bubble, reason);
694 mOverflowBubbles.remove(bubble);
695 mOverflowBubbles.add(0, bubble);
696 mStateChange.addedOverflowBubble = bubble;
697 bubble.stopInflation();
698 if (mOverflowBubbles.size() == mMaxOverflowBubbles + 1) {
699 // Remove oldest bubble.
700 Bubble oldest = mOverflowBubbles.get(mOverflowBubbles.size() - 1);
701 if (DEBUG_BUBBLE_DATA) {
702 Log.d(TAG, "Overflow full. Remove: " + oldest);
703 }
704 mStateChange.bubbleRemoved(oldest, Bubbles.DISMISS_OVERFLOW_MAX_REACHED);
705 mLogger.log(bubble, BubbleLogger.Event.BUBBLE_OVERFLOW_REMOVE_MAX_REACHED);
706 mOverflowBubbles.remove(oldest);
707 mStateChange.removedOverflowBubble = oldest;
708 }
709 }
710
711 public void dismissAll(@DismissReason int reason) {
712 if (DEBUG_BUBBLE_DATA) {
713 Log.d(TAG, "dismissAll: reason=" + reason);
714 }
715 if (mBubbles.isEmpty() && mSuppressedBubbles.isEmpty()) {
716 return;
717 }
718 setExpandedInternal(false);
719 setSelectedBubbleInternal(null);
720 while (!mBubbles.isEmpty()) {
721 doRemove(mBubbles.get(0).getKey(), reason);
722 }
723 while (!mSuppressedBubbles.isEmpty()) {
724 Bubble bubble = mSuppressedBubbles.removeAt(0);
725 doRemove(bubble.getKey(), reason);
726 }
727 dispatchPendingChanges();
728 }
729
730 /**
731 * Called in response to the visibility of a locusId changing. A locusId is set on a task
732 * and if there's a matching bubble for that locusId then the bubble may be hidden or shown
733 * depending on the visibility of the locusId.
734 *
735 * @param taskId the taskId associated with the locusId visibility change.
736 * @param locusId the locusId whose visibility has changed.
737 * @param visible whether the task with the locusId is visible or not.
738 */
739 public void onLocusVisibilityChanged(int taskId, LocusId locusId, boolean visible) {
740 if (DEBUG_BUBBLE_DATA) {
741 Log.d(TAG, "onLocusVisibilityChanged: " + locusId + " visible=" + visible);
742 }
743
744 Bubble matchingBubble = getBubbleInStackWithLocusId(locusId);
745 // Don't add the locus if it's from a bubble'd activity, we only suppress for non-bubbled.
746 if (visible && (matchingBubble == null || matchingBubble.getTaskId() != taskId)) {
747 mVisibleLocusIds.add(locusId);
748 } else {
749 mVisibleLocusIds.remove(locusId);
750 }
751 if (matchingBubble == null) {
752 // Check if there is a suppressed bubble for this LocusId
753 matchingBubble = mSuppressedBubbles.get(locusId);
754 if (matchingBubble == null) {
755 return;
756 }
757 }
758 boolean isAlreadySuppressed = mSuppressedBubbles.get(locusId) != null;
759 if (visible && !isAlreadySuppressed && matchingBubble.isSuppressable()
760 && taskId != matchingBubble.getTaskId()) {
761 mSuppressedBubbles.put(locusId, matchingBubble);
762 doSuppress(matchingBubble);
763 dispatchPendingChanges();
764 } else if (!visible) {
765 Bubble unsuppressedBubble = mSuppressedBubbles.remove(locusId);
766 if (unsuppressedBubble != null) {
767 doUnsuppress(unsuppressedBubble);
768 }
769 dispatchPendingChanges();
770 }
771 }
772
773 /**
774 * Removes all bubbles from the overflow, called when the user changes.
775 */
776 public void clearOverflow() {
777 while (!mOverflowBubbles.isEmpty()) {
778 doRemove(mOverflowBubbles.get(0).getKey(), Bubbles.DISMISS_USER_CHANGED);
779 }
780 dispatchPendingChanges();
781 }
782
783 private void dispatchPendingChanges() {
784 if (mListener != null && mStateChange.anythingChanged()) {
785 mListener.applyUpdate(mStateChange);
786 }
787 mStateChange = new Update(mBubbles, mOverflowBubbles);
788 }
789
790 /**
791 * Requests a change to the selected bubble.
792 *
793 * @param bubble the new selected bubble
794 */
795 private void setSelectedBubbleInternal(@Nullable BubbleViewProvider bubble) {
796 if (DEBUG_BUBBLE_DATA) {
797 Log.d(TAG, "setSelectedBubbleInternal: " + bubble);
798 }
799 if (Objects.equals(bubble, mSelectedBubble)) {
800 return;
801 }
802 boolean isOverflow = bubble != null && BubbleOverflow.KEY.equals(bubble.getKey());
803 if (bubble != null
804 && !mBubbles.contains(bubble)
805 && !mOverflowBubbles.contains(bubble)
806 && !isOverflow) {
807 Log.e(TAG, "Cannot select bubble which doesn't exist!"
808 + " (" + bubble + ") bubbles=" + mBubbles);
809 return;
810 }
811 if (mExpanded && bubble != null && !isOverflow) {
812 ((Bubble) bubble).markAsAccessedAt(mTimeSource.currentTimeMillis());
813 }
814 mSelectedBubble = bubble;
815 mStateChange.selectedBubble = bubble;
816 mStateChange.selectionChanged = true;
817 }
818
819 void setCurrentUserId(int uid) {
820 mCurrentUserId = uid;
821 }
822
823 /**
824 * Logs the bubble UI event.
825 *
826 * @param provider The bubble view provider that is being interacted on. Null value indicates
827 * that the user interaction is not specific to one bubble.
828 * @param action The user interaction enum
829 * @param packageName SystemUI package
830 * @param bubbleCount Number of bubbles in the stack
831 * @param bubbleIndex Index of bubble in the stack
832 * @param normalX Normalized x position of the stack
833 * @param normalY Normalized y position of the stack
834 */
835 void logBubbleEvent(@Nullable BubbleViewProvider provider, int action, String packageName,
836 int bubbleCount, int bubbleIndex, float normalX, float normalY) {
837 if (provider == null) {
838 mLogger.logStackUiChanged(packageName, action, bubbleCount, normalX, normalY);
839 } else if (provider.getKey().equals(BubbleOverflow.KEY)) {
840 if (action == FrameworkStatsLog.BUBBLE_UICHANGED__ACTION__EXPANDED) {
841 mLogger.logShowOverflow(packageName, mCurrentUserId);
842 }
843 } else {
844 mLogger.logBubbleUiChanged((Bubble) provider, packageName, action, bubbleCount, normalX,
845 normalY, bubbleIndex);
846 }
847 }
848
849 /**
850 * Requests a change to the expanded state.
851 *
852 * @param shouldExpand the new requested state
853 */
854 private void setExpandedInternal(boolean shouldExpand) {
855 if (DEBUG_BUBBLE_DATA) {
856 Log.d(TAG, "setExpandedInternal: shouldExpand=" + shouldExpand);
857 }
858 if (mExpanded == shouldExpand) {
859 return;
860 }
861 if (shouldExpand) {
862 if (mBubbles.isEmpty() && !mShowingOverflow) {
863 Log.e(TAG, "Attempt to expand stack when empty!");
864 return;
865 }
866 if (mSelectedBubble == null) {
867 Log.e(TAG, "Attempt to expand stack without selected bubble!");
868 return;
869 }
870 if (mSelectedBubble.getKey().equals(mOverflow.getKey()) && !mBubbles.isEmpty()) {
871 // Show previously selected bubble instead of overflow menu when expanding.
872 setSelectedBubbleInternal(mBubbles.get(0));
873 }
874 if (mSelectedBubble instanceof Bubble) {
875 ((Bubble) mSelectedBubble).markAsAccessedAt(mTimeSource.currentTimeMillis());
876 }
877 mStateChange.orderChanged |= repackAll();
878 } else if (!mBubbles.isEmpty()) {
879 // Apply ordering and grouping rules from expanded -> collapsed, then save
880 // the result.
881 mStateChange.orderChanged |= repackAll();
882 if (mBubbles.indexOf(mSelectedBubble) > 0) {
883 // Move the selected bubble to the top while collapsed.
884 int index = mBubbles.indexOf(mSelectedBubble);
885 if (index != 0) {
886 mBubbles.remove((Bubble) mSelectedBubble);
887 mBubbles.add(0, (Bubble) mSelectedBubble);
888 mStateChange.orderChanged = true;
889 }
890 }
891 }
892 if (mNeedsTrimming) {
893 mNeedsTrimming = false;
894 trim();
895 }
896 mExpanded = shouldExpand;
897 mStateChange.expanded = shouldExpand;
898 mStateChange.expandedChanged = true;
899 }
900
901 private static long sortKey(Bubble bubble) {
902 return bubble.getLastActivity();
903 }
904
905 /**
906 * This applies a full sort and group pass to all existing bubbles.
907 * Bubbles are sorted by lastUpdated descending.
908 *
909 * @return true if the position of any bubbles changed as a result
910 */
911 private boolean repackAll() {
912 if (DEBUG_BUBBLE_DATA) {
913 Log.d(TAG, "repackAll()");
914 }
915 if (mBubbles.isEmpty()) {
916 return false;
917 }
918 List<Bubble> repacked = new ArrayList<>(mBubbles.size());
919 // Add bubbles, freshest to oldest
920 mBubbles.stream()
921 .sorted(BUBBLES_BY_SORT_KEY_DESCENDING)
922 .forEachOrdered(repacked::add);
923 if (repacked.equals(mBubbles)) {
924 return false;
925 }
926 mBubbles.clear();
927 mBubbles.addAll(repacked);
928 return true;
929 }
930
931 private void maybeSendDeleteIntent(@DismissReason int reason, @NonNull final Bubble bubble) {
932 if (reason != Bubbles.DISMISS_USER_GESTURE) return;
933 PendingIntent deleteIntent = bubble.getDeleteIntent();
934 if (deleteIntent == null) return;
935 try {
936 deleteIntent.send();
937 } catch (PendingIntent.CanceledException e) {
938 Log.w(TAG, "Failed to send delete intent for bubble with key: " + bubble.getKey());
939 }
940 }
941
942 private int indexForKey(String key) {
943 for (int i = 0; i < mBubbles.size(); i++) {
944 Bubble bubble = mBubbles.get(i);
945 if (bubble.getKey().equals(key)) {
946 return i;
947 }
948 }
949 return -1;
950 }
951
952 /**
953 * The set of bubbles in row.
954 */
955 @VisibleForTesting(visibility = PACKAGE)
956 public List<Bubble> getBubbles() {
957 return Collections.unmodifiableList(mBubbles);
958 }
959
960 /**
961 * The set of bubbles in overflow.
962 */
963 @VisibleForTesting(visibility = PRIVATE)
964 public List<Bubble> getOverflowBubbles() {
965 return Collections.unmodifiableList(mOverflowBubbles);
966 }
967
968 @VisibleForTesting(visibility = PRIVATE)
969 @Nullable
970 Bubble getAnyBubbleWithkey(String key) {
971 Bubble b = getBubbleInStackWithKey(key);
972 if (b == null) {
973 b = getOverflowBubbleWithKey(key);
974 }
975 if (b == null) {
976 b = getSuppressedBubbleWithKey(key);
977 }
978 return b;
979 }
980
981 /** @return any bubble (in the stack or the overflow) that matches the provided shortcutId. */
982 @Nullable
983 Bubble getAnyBubbleWithShortcutId(String shortcutId) {
984 if (TextUtils.isEmpty(shortcutId)) {
985 return null;
986 }
987 for (int i = 0; i < mBubbles.size(); i++) {
988 Bubble bubble = mBubbles.get(i);
989 String bubbleShortcutId = bubble.getShortcutInfo() != null
990 ? bubble.getShortcutInfo().getId()
991 : bubble.getMetadataShortcutId();
992 if (shortcutId.equals(bubbleShortcutId)) {
993 return bubble;
994 }
995 }
996
997 for (int i = 0; i < mOverflowBubbles.size(); i++) {
998 Bubble bubble = mOverflowBubbles.get(i);
999 String bubbleShortcutId = bubble.getShortcutInfo() != null
1000 ? bubble.getShortcutInfo().getId()
1001 : bubble.getMetadataShortcutId();
1002 if (shortcutId.equals(bubbleShortcutId)) {
1003 return bubble;
1004 }
1005 }
1006 return null;
1007 }
1008
1009 @VisibleForTesting(visibility = PRIVATE)
1010 @Nullable
1011 public Bubble getBubbleInStackWithKey(String key) {
1012 for (int i = 0; i < mBubbles.size(); i++) {
1013 Bubble bubble = mBubbles.get(i);
1014 if (bubble.getKey().equals(key)) {
1015 return bubble;
1016 }
1017 }
1018 return null;
1019 }
1020
1021 @Nullable
1022 private Bubble getBubbleInStackWithLocusId(LocusId locusId) {
1023 if (locusId == null) return null;
1024 for (int i = 0; i < mBubbles.size(); i++) {
1025 Bubble bubble = mBubbles.get(i);
1026 if (locusId.equals(bubble.getLocusId())) {
1027 return bubble;
1028 }
1029 }
1030 return null;
1031 }
1032
1033 @Nullable
1034 Bubble getBubbleWithView(View view) {
1035 for (int i = 0; i < mBubbles.size(); i++) {
1036 Bubble bubble = mBubbles.get(i);
1037 if (bubble.getIconView() != null && bubble.getIconView().equals(view)) {
1038 return bubble;
1039 }
1040 }
1041 return null;
1042 }
1043
1044 @VisibleForTesting(visibility = PRIVATE)
1045 public Bubble getOverflowBubbleWithKey(String key) {
1046 for (int i = 0; i < mOverflowBubbles.size(); i++) {
1047 Bubble bubble = mOverflowBubbles.get(i);
1048 if (bubble.getKey().equals(key)) {
1049 return bubble;
1050 }
1051 }
1052 return null;
1053 }
1054
1055 /**
1056 * Get a suppressed bubble with given notification <code>key</code>
1057 *
1058 * @param key notification key
1059 * @return bubble that matches or null
1060 */
1061 @Nullable
1062 @VisibleForTesting(visibility = PRIVATE)
1063 public Bubble getSuppressedBubbleWithKey(String key) {
1064 for (Bubble b : mSuppressedBubbles.values()) {
1065 if (b.getKey().equals(key)) {
1066 return b;
1067 }
1068 }
1069 return null;
1070 }
1071
1072 /**
1073 * Get a pending bubble with given notification <code>key</code>
1074 *
1075 * @param key notification key
1076 * @return bubble that matches or null
1077 */
1078 @VisibleForTesting(visibility = PRIVATE)
1079 public Bubble getPendingBubbleWithKey(String key) {
1080 for (Bubble b : mPendingBubbles.values()) {
1081 if (b.getKey().equals(key)) {
1082 return b;
1083 }
1084 }
1085 return null;
1086 }
1087
1088 /**
1089 * Returns a list of bubbles that match the provided predicate. This checks all types of
1090 * bubbles (i.e. pending, suppressed, active, and overflowed).
1091 */
1092 private List<Bubble> filterAllBubbles(Predicate<Bubble> predicate) {
1093 ArrayList<Bubble> matchingBubbles = new ArrayList<>();
1094 for (Bubble b : mPendingBubbles.values()) {
1095 if (predicate.test(b)) {
1096 matchingBubbles.add(b);
1097 }
1098 }
1099 for (Bubble b : mSuppressedBubbles.values()) {
1100 if (predicate.test(b)) {
1101 matchingBubbles.add(b);
1102 }
1103 }
1104 for (Bubble b : mBubbles) {
1105 if (predicate.test(b)) {
1106 matchingBubbles.add(b);
1107 }
1108 }
1109 for (Bubble b : mOverflowBubbles) {
1110 if (predicate.test(b)) {
1111 matchingBubbles.add(b);
1112 }
1113 }
1114 return matchingBubbles;
1115 }
1116
1117 @VisibleForTesting(visibility = PRIVATE)
1118 void setTimeSource(TimeSource timeSource) {
1119 mTimeSource = timeSource;
1120 }
1121
1122 public void setListener(Listener listener) {
1123 mListener = listener;
1124 }
1125
1126 /**
1127 * Set maximum number of bubbles allowed in overflow.
1128 * This method should only be used in tests, not in production.
1129 */
1130 @VisibleForTesting
1131 public void setMaxOverflowBubbles(int maxOverflowBubbles) {
1132 mMaxOverflowBubbles = maxOverflowBubbles;
1133 }
1134
1135 /**
1136 * Description of current bubble data state.
1137 */
1138 public void dump(PrintWriter pw) {
1139 pw.print("selected: ");
1140 pw.println(mSelectedBubble != null
1141 ? mSelectedBubble.getKey()
1142 : "null");
1143 pw.print("expanded: ");
1144 pw.println(mExpanded);
1145
1146 pw.print("stack bubble count: ");
1147 pw.println(mBubbles.size());
1148 for (Bubble bubble : mBubbles) {
1149 bubble.dump(pw);
1150 }
1151
1152 pw.print("overflow bubble count: ");
1153 pw.println(mOverflowBubbles.size());
1154 for (Bubble bubble : mOverflowBubbles) {
1155 bubble.dump(pw);
1156 }
1157
1158 pw.print("summaryKeys: ");
1159 pw.println(mSuppressedGroupKeys.size());
1160 for (String key : mSuppressedGroupKeys.keySet()) {
1161 pw.println(" suppressing: " + key);
1162 }
1163 }
1164 }