Debian Codegraph @

libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.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
17 package com.android.wm.shell.bubbles;
18
19 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
20 import static android.service.notification.NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_DELETED;
21 import static android.service.notification.NotificationListenerService.NOTIFICATION_CHANNEL_OR_GROUP_UPDATED;
22 import static android.service.notification.NotificationListenerService.REASON_CANCEL;
23 import static android.view.View.INVISIBLE;
24 import static android.view.View.VISIBLE;
25 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
26
27 import static com.android.wm.shell.bubbles.Bubble.KEY_APP_BUBBLE;
28 import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_CONTROLLER;
29 import static com.android.wm.shell.bubbles.BubbleDebugConfig.DEBUG_BUBBLE_GESTURE;
30 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_BUBBLES;
31 import static com.android.wm.shell.bubbles.BubbleDebugConfig.TAG_WITH_CLASS_NAME;
32 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_BLOCKED;
33 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_GROUP_CANCELLED;
34 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_INVALID_INTENT;
35 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_NOTIF_CANCEL;
36 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_NO_BUBBLE_UP;
37 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_NO_LONGER_BUBBLE;
38 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_PACKAGE_REMOVED;
39 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_SHORTCUT_REMOVED;
40 import static com.android.wm.shell.bubbles.Bubbles.DISMISS_USER_CHANGED;
41
42 import android.annotation.NonNull;
43 import android.annotation.UserIdInt;
44 import android.app.ActivityManager;
45 import android.app.Notification;
46 import android.app.NotificationChannel;
47 import android.app.PendingIntent;
48 import android.content.BroadcastReceiver;
49 import android.content.Context;
50 import android.content.Intent;
51 import android.content.IntentFilter;
52 import android.content.pm.ActivityInfo;
53 import android.content.pm.LauncherApps;
54 import android.content.pm.PackageManager;
55 import android.content.pm.ShortcutInfo;
56 import android.content.pm.UserInfo;
57 import android.content.res.Configuration;
58 import android.graphics.PixelFormat;
59 import android.graphics.Rect;
60 import android.os.Binder;
61 import android.os.Handler;
62 import android.os.RemoteException;
63 import android.os.ServiceManager;
64 import android.os.UserHandle;
65 import android.os.UserManager;
66 import android.service.notification.NotificationListenerService;
67 import android.service.notification.NotificationListenerService.RankingMap;
68 import android.util.Log;
69 import android.util.Pair;
70 import android.util.SparseArray;
71 import android.view.View;
72 import android.view.ViewGroup;
73 import android.view.WindowInsets;
74 import android.view.WindowManager;
75
76 import androidx.annotation.MainThread;
77 import androidx.annotation.Nullable;
78
79 import com.android.internal.annotations.VisibleForTesting;
80 import com.android.internal.statusbar.IStatusBarService;
81 import com.android.wm.shell.ShellTaskOrganizer;
82 import com.android.wm.shell.TaskViewTransitions;
83 import com.android.wm.shell.WindowManagerShellWrapper;
84 import com.android.wm.shell.common.DisplayController;
85 import com.android.wm.shell.common.FloatingContentCoordinator;
86 import com.android.wm.shell.common.ShellExecutor;
87 import com.android.wm.shell.common.SyncTransactionQueue;
88 import com.android.wm.shell.common.TaskStackListenerCallback;
89 import com.android.wm.shell.common.TaskStackListenerImpl;
90 import com.android.wm.shell.common.annotations.ShellBackgroundThread;
91 import com.android.wm.shell.common.annotations.ShellMainThread;
92 import com.android.wm.shell.draganddrop.DragAndDropController;
93 import com.android.wm.shell.onehanded.OneHandedController;
94 import com.android.wm.shell.onehanded.OneHandedTransitionCallback;
95 import com.android.wm.shell.pip.PinnedStackListenerForwarder;
96 import com.android.wm.shell.sysui.ConfigurationChangeListener;
97 import com.android.wm.shell.sysui.ShellCommandHandler;
98 import com.android.wm.shell.sysui.ShellController;
99 import com.android.wm.shell.sysui.ShellInit;
100
101 import java.io.PrintWriter;
102 import java.util.ArrayList;
103 import java.util.HashMap;
104 import java.util.HashSet;
105 import java.util.List;
106 import java.util.Map;
107 import java.util.Objects;
108 import java.util.Optional;
109 import java.util.Set;
110 import java.util.concurrent.Executor;
111 import java.util.function.Consumer;
112 import java.util.function.IntConsumer;
113
114 /**
115 * Bubbles are a special type of content that can "float" on top of other apps or System UI.
116 * Bubbles can be expanded to show more content.
117 *
118 * The controller manages addition, removal, and visible state of bubbles on screen.
119 */
120 public class BubbleController implements ConfigurationChangeListener {
121
122 private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleController" : TAG_BUBBLES;
123
124 // Should match with PhoneWindowManager
125 private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
126 private static final String SYSTEM_DIALOG_REASON_GESTURE_NAV = "gestureNav";
127
128 private final Context mContext;
129 private final BubblesImpl mImpl = new BubblesImpl();
130 private Bubbles.BubbleExpandListener mExpandListener;
131 @Nullable private BubbleStackView.SurfaceSynchronizer mSurfaceSynchronizer;
132 private final FloatingContentCoordinator mFloatingContentCoordinator;
133 private final BubbleDataRepository mDataRepository;
134 private final WindowManagerShellWrapper mWindowManagerShellWrapper;
135 private final UserManager mUserManager;
136 private final LauncherApps mLauncherApps;
137 private final IStatusBarService mBarService;
138 private final WindowManager mWindowManager;
139 private final TaskStackListenerImpl mTaskStackListener;
140 private final ShellTaskOrganizer mTaskOrganizer;
141 private final DisplayController mDisplayController;
142 private final TaskViewTransitions mTaskViewTransitions;
143 private final SyncTransactionQueue mSyncQueue;
144 private final ShellController mShellController;
145 private final ShellCommandHandler mShellCommandHandler;
146
147 // Used to post to main UI thread
148 private final ShellExecutor mMainExecutor;
149 private final Handler mMainHandler;
150
151 private final ShellExecutor mBackgroundExecutor;
152
153 // Whether or not we should show bubbles pinned at the bottom of the screen.
154 private boolean mIsBubbleBarEnabled;
155
156 private BubbleLogger mLogger;
157 private BubbleData mBubbleData;
158 @Nullable private BubbleStackView mStackView;
159 private BubbleIconFactory mBubbleIconFactory;
160 private BubbleBadgeIconFactory mBubbleBadgeIconFactory;
161 private BubblePositioner mBubblePositioner;
162 private Bubbles.SysuiProxy mSysuiProxy;
163
164 // Tracks the id of the current (foreground) user.
165 private int mCurrentUserId;
166 // Current profiles of the user (e.g. user with a workprofile)
167 private SparseArray<UserInfo> mCurrentProfiles;
168 // Saves data about active bubbles when users are switched.
169 private final SparseArray<UserBubbleData> mSavedUserBubbleData;
170
171 // Used when ranking updates occur and we check if things should bubble / unbubble
172 private NotificationListenerService.Ranking mTmpRanking;
173
174 // Callback that updates BubbleOverflowActivity on data change.
175 @Nullable private BubbleData.Listener mOverflowListener = null;
176
177 // Typically only load once & after user switches
178 private boolean mOverflowDataLoadNeeded = true;
179
180 /**
181 * When the shade status changes to SHADE (from anything but SHADE, like LOCKED) we'll select
182 * this bubble and expand the stack.
183 */
184 @Nullable private BubbleEntry mNotifEntryToExpandOnShadeUnlock;
185
186 /** LayoutParams used to add the BubbleStackView to the window manager. */
187 private WindowManager.LayoutParams mWmLayoutParams;
188 /** Whether or not the BubbleStackView has been added to the WindowManager. */
189 private boolean mAddedToWindowManager = false;
190
191 /** Saved screen density, used to detect display size changes in {@link #onConfigChanged}. */
192 private int mDensityDpi = Configuration.DENSITY_DPI_UNDEFINED;
193
194 /** Saved screen bounds, used to detect screen size changes in {@link #onConfigChanged}. **/
195 private Rect mScreenBounds = new Rect();
196
197 /** Saved font scale, used to detect font size changes in {@link #onConfigChanged}. */
198 private float mFontScale = 0;
199
200 /** Saved direction, used to detect layout direction changes @link #onConfigChanged}. */
201 private int mLayoutDirection = View.LAYOUT_DIRECTION_UNDEFINED;
202
203 /** Saved insets, used to detect WindowInset changes. */
204 private WindowInsets mWindowInsets;
205
206 private boolean mInflateSynchronously;
207
208 /** True when user is in status bar unlock shade. */
209 private boolean mIsStatusBarShade = true;
210
211 /** One handed mode controller to register transition listener. */
212 private Optional<OneHandedController> mOneHandedOptional;
213 /** Drag and drop controller to register listener for onDragStarted. */
214 private DragAndDropController mDragAndDropController;
215
216 public BubbleController(Context context,
217 ShellInit shellInit,
218 ShellCommandHandler shellCommandHandler,
219 ShellController shellController,
220 BubbleData data,
221 @Nullable BubbleStackView.SurfaceSynchronizer synchronizer,
222 FloatingContentCoordinator floatingContentCoordinator,
223 BubbleDataRepository dataRepository,
224 @Nullable IStatusBarService statusBarService,
225 WindowManager windowManager,
226 WindowManagerShellWrapper windowManagerShellWrapper,
227 UserManager userManager,
228 LauncherApps launcherApps,
229 BubbleLogger bubbleLogger,
230 TaskStackListenerImpl taskStackListener,
231 ShellTaskOrganizer organizer,
232 BubblePositioner positioner,
233 DisplayController displayController,
234 Optional<OneHandedController> oneHandedOptional,
235 DragAndDropController dragAndDropController,
236 @ShellMainThread ShellExecutor mainExecutor,
237 @ShellMainThread Handler mainHandler,
238 @ShellBackgroundThread ShellExecutor bgExecutor,
239 TaskViewTransitions taskViewTransitions,
240 SyncTransactionQueue syncQueue) {
241 mContext = context;
242 mShellCommandHandler = shellCommandHandler;
243 mShellController = shellController;
244 mLauncherApps = launcherApps;
245 mBarService = statusBarService == null
246 ? IStatusBarService.Stub.asInterface(
247 ServiceManager.getService(Context.STATUS_BAR_SERVICE))
248 : statusBarService;
249 mWindowManager = windowManager;
250 mWindowManagerShellWrapper = windowManagerShellWrapper;
251 mUserManager = userManager;
252 mFloatingContentCoordinator = floatingContentCoordinator;
253 mDataRepository = dataRepository;
254 mLogger = bubbleLogger;
255 mMainExecutor = mainExecutor;
256 mMainHandler = mainHandler;
257 mBackgroundExecutor = bgExecutor;
258 mTaskStackListener = taskStackListener;
259 mTaskOrganizer = organizer;
260 mSurfaceSynchronizer = synchronizer;
261 mCurrentUserId = ActivityManager.getCurrentUser();
262 mBubblePositioner = positioner;
263 mBubbleData = data;
264 mSavedUserBubbleData = new SparseArray<>();
265 mBubbleIconFactory = new BubbleIconFactory(context);
266 mBubbleBadgeIconFactory = new BubbleBadgeIconFactory(context);
267 mDisplayController = displayController;
268 mTaskViewTransitions = taskViewTransitions;
269 mOneHandedOptional = oneHandedOptional;
270 mDragAndDropController = dragAndDropController;
271 mSyncQueue = syncQueue;
272 shellInit.addInitCallback(this::onInit, this);
273 }
274
275 private void registerOneHandedState(OneHandedController oneHanded) {
276 oneHanded.registerTransitionCallback(
277 new OneHandedTransitionCallback() {
278 @Override
279 public void onStartFinished(Rect bounds) {
280 if (mStackView != null) {
281 mStackView.onVerticalOffsetChanged(bounds.top);
282 }
283 }
284
285 @Override
286 public void onStopFinished(Rect bounds) {
287 if (mStackView != null) {
288 mStackView.onVerticalOffsetChanged(bounds.top);
289 }
290 }
291 });
292 }
293
294 protected void onInit() {
295 mBubbleData.setListener(mBubbleDataListener);
296 mBubbleData.setSuppressionChangedListener(this::onBubbleMetadataFlagChanged);
297 mDataRepository.setSuppressionChangedListener(this::onBubbleMetadataFlagChanged);
298
299 mBubbleData.setPendingIntentCancelledListener(bubble -> {
300 if (bubble.getBubbleIntent() == null) {
301 return;
302 }
303 if (bubble.isIntentActive() || mBubbleData.hasBubbleInStackWithKey(bubble.getKey())) {
304 bubble.setPendingIntentCanceled();
305 return;
306 }
307 mMainExecutor.execute(() -> removeBubble(bubble.getKey(), DISMISS_INVALID_INTENT));
308 });
309
310 try {
311 mWindowManagerShellWrapper.addPinnedStackListener(new BubblesImeListener());
312 } catch (RemoteException e) {
313 e.printStackTrace();
314 }
315
316 mBubbleData.setCurrentUserId(mCurrentUserId);
317
318 mTaskOrganizer.addLocusIdListener((taskId, locus, visible) ->
319 mBubbleData.onLocusVisibilityChanged(taskId, locus, visible));
320
321 mLauncherApps.registerCallback(new LauncherApps.Callback() {
322 @Override
323 public void onPackageAdded(String s, UserHandle userHandle) {}
324
325 @Override
326 public void onPackageChanged(String s, UserHandle userHandle) {}
327
328 @Override
329 public void onPackageRemoved(String s, UserHandle userHandle) {
330 // Remove bubbles with this package name, since it has been uninstalled and attempts
331 // to open a bubble from an uninstalled app can cause issues.
332 mBubbleData.removeBubblesWithPackageName(s, DISMISS_PACKAGE_REMOVED);
333 }
334
335 @Override
336 public void onPackagesAvailable(String[] strings, UserHandle userHandle, boolean b) {}
337
338 @Override
339 public void onPackagesUnavailable(String[] packages, UserHandle userHandle,
340 boolean b) {
341 for (String packageName : packages) {
342 // Remove bubbles from unavailable apps. This can occur when the app is on
343 // external storage that has been removed.
344 mBubbleData.removeBubblesWithPackageName(packageName, DISMISS_PACKAGE_REMOVED);
345 }
346 }
347
348 @Override
349 public void onShortcutsChanged(String packageName, List<ShortcutInfo> validShortcuts,
350 UserHandle user) {
351 super.onShortcutsChanged(packageName, validShortcuts, user);
352
353 // Remove bubbles whose shortcuts aren't in the latest list of valid shortcuts.
354 mBubbleData.removeBubblesWithInvalidShortcuts(
355 packageName, validShortcuts, DISMISS_SHORTCUT_REMOVED);
356 }
357 }, mMainHandler);
358
359 mTaskStackListener.addListener(new TaskStackListenerCallback() {
360 @Override
361 public void onTaskMovedToFront(int taskId) {
362 mMainExecutor.execute(() -> {
363 int expandedId = INVALID_TASK_ID;
364 if (mStackView != null && mStackView.getExpandedBubble() != null
365 && isStackExpanded()
366 && !mStackView.isExpansionAnimating()
367 && !mStackView.isSwitchAnimating()) {
368 expandedId = mStackView.getExpandedBubble().getTaskId();
369 }
370 if (expandedId != INVALID_TASK_ID && expandedId != taskId) {
371 mBubbleData.setExpanded(false);
372 }
373 });
374 }
375
376 @Override
377 public void onActivityRestartAttempt(ActivityManager.RunningTaskInfo task,
378 boolean homeTaskVisible, boolean clearedTask, boolean wasVisible) {
379 for (Bubble b : mBubbleData.getBubbles()) {
380 if (task.taskId == b.getTaskId()) {
381 mBubbleData.setSelectedBubble(b);
382 mBubbleData.setExpanded(true);
383 return;
384 }
385 }
386 for (Bubble b : mBubbleData.getOverflowBubbles()) {
387 if (task.taskId == b.getTaskId()) {
388 promoteBubbleFromOverflow(b);
389 mBubbleData.setExpanded(true);
390 return;
391 }
392 }
393 }
394 });
395
396 mDisplayController.addDisplayChangingController(
397 (displayId, fromRotation, toRotation, newDisplayAreaInfo, t) -> {
398 // This is triggered right before the rotation is applied
399 if (fromRotation != toRotation) {
400 if (mStackView != null) {
401 // Layout listener set on stackView will update the positioner
402 // once the rotation is applied
403 mStackView.onOrientationChanged();
404 }
405 }
406 });
407
408 mOneHandedOptional.ifPresent(this::registerOneHandedState);
409 mDragAndDropController.addListener(this::collapseStack);
410
411 // Clear out any persisted bubbles on disk that no longer have a valid user.
412 List<UserInfo> users = mUserManager.getAliveUsers();
413 mDataRepository.sanitizeBubbles(users);
414
415 // Init profiles
416 SparseArray<UserInfo> userProfiles = new SparseArray<>();
417 for (UserInfo user : mUserManager.getProfiles(mCurrentUserId)) {
418 userProfiles.put(user.id, user);
419 }
420 mCurrentProfiles = userProfiles;
421
422 mShellController.addConfigurationChangeListener(this);
423 mShellCommandHandler.addDumpCallback(this::dump, this);
424 }
425
426 @VisibleForTesting
427 public Bubbles asBubbles() {
428 return mImpl;
429 }
430
431 @VisibleForTesting
432 public BubblesImpl.CachedState getImplCachedState() {
433 return mImpl.mCachedState;
434 }
435
436 public ShellExecutor getMainExecutor() {
437 return mMainExecutor;
438 }
439
440 /**
441 * Hides the current input method, wherever it may be focused, via InputMethodManagerInternal.
442 */
443 void hideCurrentInputMethod() {
444 try {
445 mBarService.hideCurrentInputMethodForBubbles();
446 } catch (RemoteException e) {
447 e.printStackTrace();
448 }
449 }
450
451 private void openBubbleOverflow() {
452 ensureStackViewCreated();
453 mBubbleData.setShowingOverflow(true);
454 mBubbleData.setSelectedBubble(mBubbleData.getOverflow());
455 mBubbleData.setExpanded(true);
456 }
457
458 /**
459 * Called when the status bar has become visible or invisible (either permanently or
460 * temporarily).
461 */
462 private void onStatusBarVisibilityChanged(boolean visible) {
463 if (mStackView != null) {
464 // Hide the stack temporarily if the status bar has been made invisible, and the stack
465 // is collapsed. An expanded stack should remain visible until collapsed.
466 mStackView.setTemporarilyInvisible(!visible && !isStackExpanded());
467 }
468 }
469
470 private void onZenStateChanged() {
471 for (Bubble b : mBubbleData.getBubbles()) {
472 b.setShowDot(b.showInShade());
473 }
474 }
475
476 @VisibleForTesting
477 public void onStatusBarStateChanged(boolean isShade) {
478 boolean didChange = mIsStatusBarShade != isShade;
479 if (DEBUG_BUBBLE_CONTROLLER) {
480 Log.d(TAG, "onStatusBarStateChanged isShade=" + isShade + " didChange=" + didChange);
481 }
482 mIsStatusBarShade = isShade;
483 if (!mIsStatusBarShade && didChange) {
484 // Only collapse stack on change
485 collapseStack();
486 }
487
488 if (mNotifEntryToExpandOnShadeUnlock != null) {
489 expandStackAndSelectBubble(mNotifEntryToExpandOnShadeUnlock);
490 }
491
492 updateStack();
493 }
494
495 @VisibleForTesting
496 public void onBubbleMetadataFlagChanged(Bubble bubble) {
497 // Make sure NoMan knows suppression state so that anyone querying it can tell.
498 try {
499 mBarService.onBubbleMetadataFlagChanged(bubble.getKey(), bubble.getFlags());
500 } catch (RemoteException e) {
501 // Bad things have happened
502 }
503 mImpl.mCachedState.updateBubbleSuppressedState(bubble);
504 }
505
506 /** Called when the current user changes. */
507 @VisibleForTesting
508 public void onUserChanged(int newUserId) {
509 saveBubbles(mCurrentUserId);
510 mCurrentUserId = newUserId;
511
512 mBubbleData.dismissAll(DISMISS_USER_CHANGED);
513 mBubbleData.clearOverflow();
514 mOverflowDataLoadNeeded = true;
515
516 restoreBubbles(newUserId);
517 mBubbleData.setCurrentUserId(newUserId);
518 }
519
520 /** Called when the profiles for the current user change. **/
521 public void onCurrentProfilesChanged(SparseArray<UserInfo> currentProfiles) {
522 mCurrentProfiles = currentProfiles;
523 }
524
525 /** Called when a user is removed from the device, including work profiles. */
526 public void onUserRemoved(int removedUserId) {
527 UserInfo parent = mUserManager.getProfileParent(removedUserId);
528 int parentUserId = parent != null ? parent.getUserHandle().getIdentifier() : -1;
529 mBubbleData.removeBubblesForUser(removedUserId);
530 // Typically calls from BubbleData would remove bubbles from the DataRepository as well,
531 // however, this gets complicated when users are removed (mCurrentUserId won't necessarily
532 // be correct for this) so we update the repo directly.
533 mDataRepository.removeBubblesForUser(removedUserId, parentUserId);
534 }
535
536 // TODO(b/256873975): Should pass this into the constructor once flags are available to shell.
537 /** Sets whether the bubble bar is enabled (i.e. bubbles pinned to bottom on large screens). */
538 public void setBubbleBarEnabled(boolean enabled) {
539 mIsBubbleBarEnabled = enabled;
540 }
541
542 /** Whether this userId belongs to the current user. */
543 private boolean isCurrentProfile(int userId) {
544 return userId == UserHandle.USER_ALL
545 || (mCurrentProfiles != null && mCurrentProfiles.get(userId) != null);
546 }
547
548 /**
549 * Sets whether to perform inflation on the same thread as the caller. This method should only
550 * be used in tests, not in production.
551 */
552 @VisibleForTesting
553 public void setInflateSynchronously(boolean inflateSynchronously) {
554 mInflateSynchronously = inflateSynchronously;
555 }
556
557 /** Set a listener to be notified of when overflow view update. */
558 public void setOverflowListener(BubbleData.Listener listener) {
559 mOverflowListener = listener;
560 }
561
562 /**
563 * @return Bubbles for updating overflow.
564 */
565 List<Bubble> getOverflowBubbles() {
566 return mBubbleData.getOverflowBubbles();
567 }
568
569 /** The task listener for events in bubble tasks. */
570 public ShellTaskOrganizer getTaskOrganizer() {
571 return mTaskOrganizer;
572 }
573
574 SyncTransactionQueue getSyncTransactionQueue() {
575 return mSyncQueue;
576 }
577
578 TaskViewTransitions getTaskViewTransitions() {
579 return mTaskViewTransitions;
580 }
581
582 /** Contains information to help position things on the screen. */
583 @VisibleForTesting
584 public BubblePositioner getPositioner() {
585 return mBubblePositioner;
586 }
587
588 Bubbles.SysuiProxy getSysuiProxy() {
589 return mSysuiProxy;
590 }
591
592 /**
593 * BubbleStackView is lazily created by this method the first time a Bubble is added. This
594 * method initializes the stack view and adds it to window manager.
595 */
596 private void ensureStackViewCreated() {
597 if (mStackView == null) {
598 mStackView = new BubbleStackView(
599 mContext, this, mBubbleData, mSurfaceSynchronizer, mFloatingContentCoordinator,
600 mMainExecutor);
601 mStackView.onOrientationChanged();
602 if (mExpandListener != null) {
603 mStackView.setExpandListener(mExpandListener);
604 }
605 mStackView.setUnbubbleConversationCallback(mSysuiProxy::onUnbubbleConversation);
606 }
607
608 if (mIsBubbleBarEnabled && mBubblePositioner.isLargeScreen()) {
609 mBubblePositioner.setUsePinnedLocation(true);
610 } else {
611 mBubblePositioner.setUsePinnedLocation(false);
612 }
613
614 addToWindowManagerMaybe();
615 }
616
617 /** Adds the BubbleStackView to the WindowManager if it's not already there. */
618 private void addToWindowManagerMaybe() {
619 // If the stack is null, or already added, don't add it.
620 if (mStackView == null || mAddedToWindowManager) {
621 return;
622 }
623
624 mWmLayoutParams = new WindowManager.LayoutParams(
625 // Fill the screen so we can use translation animations to position the bubble
626 // stack. We'll use touchable regions to ignore touches that are not on the bubbles
627 // themselves.
628 ViewGroup.LayoutParams.MATCH_PARENT,
629 ViewGroup.LayoutParams.MATCH_PARENT,
630 WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
631 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
632 | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
633 | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
634 PixelFormat.TRANSLUCENT);
635
636 mWmLayoutParams.setTrustedOverlay();
637 mWmLayoutParams.setFitInsetsTypes(0);
638 mWmLayoutParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
639 mWmLayoutParams.token = new Binder();
640 mWmLayoutParams.setTitle("Bubbles!");
641 mWmLayoutParams.packageName = mContext.getPackageName();
642 mWmLayoutParams.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
643 mWmLayoutParams.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
644
645 try {
646 mAddedToWindowManager = true;
647 registerBroadcastReceiver();
648 mBubbleData.getOverflow().initialize(this);
649 mWindowManager.addView(mStackView, mWmLayoutParams);
650 mStackView.setOnApplyWindowInsetsListener((view, windowInsets) -> {
651 if (!windowInsets.equals(mWindowInsets)) {
652 mWindowInsets = windowInsets;
653 mBubblePositioner.update();
654 mStackView.onDisplaySizeChanged();
655 }
656 return windowInsets;
657 });
658 } catch (IllegalStateException e) {
659 // This means the stack has already been added. This shouldn't happen...
660 e.printStackTrace();
661 }
662 }
663
664 /**
665 * In some situations bubble's should be able to receive key events for back:
666 * - when the bubble overflow is showing
667 * - when the user education for the stack is showing.
668 *
669 * @param interceptBack whether back should be intercepted or not.
670 */
671 void updateWindowFlagsForBackpress(boolean interceptBack) {
672 if (mStackView != null && mAddedToWindowManager) {
673 mWmLayoutParams.flags = interceptBack
674 ? 0
675 : WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
676 | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
677 mWmLayoutParams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
678 mWindowManager.updateViewLayout(mStackView, mWmLayoutParams);
679 }
680 }
681
682 /** Removes the BubbleStackView from the WindowManager if it's there. */
683 private void removeFromWindowManagerMaybe() {
684 if (!mAddedToWindowManager) {
685 return;
686 }
687
688 try {
689 mAddedToWindowManager = false;
690 // Put on background for this binder call, was causing jank
691 mBackgroundExecutor.execute(() -> mContext.unregisterReceiver(mBroadcastReceiver));
692 if (mStackView != null) {
693 mWindowManager.removeView(mStackView);
694 mBubbleData.getOverflow().cleanUpExpandedState();
695 } else {
696 Log.w(TAG, "StackView added to WindowManager, but was null when removing!");
697 }
698 } catch (IllegalArgumentException e) {
699 // This means the stack has already been removed - it shouldn't happen, but ignore if it
700 // does, since we wanted it removed anyway.
701 e.printStackTrace();
702 }
703 }
704
705 private void registerBroadcastReceiver() {
706 IntentFilter filter = new IntentFilter();
707 filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
708 filter.addAction(Intent.ACTION_SCREEN_OFF);
709 mContext.registerReceiver(mBroadcastReceiver, filter);
710 }
711
712 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
713 @Override
714 public void onReceive(Context context, Intent intent) {
715 if (!isStackExpanded()) return; // Nothing to do
716
717 String action = intent.getAction();
718 String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
719 if ((Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
720 && SYSTEM_DIALOG_REASON_GESTURE_NAV.equals(reason))
721 || Intent.ACTION_SCREEN_OFF.equals(action)) {
722 mMainExecutor.execute(() -> collapseStack());
723 }
724 }
725 };
726
727 /**
728 * Called by the BubbleStackView and whenever all bubbles have animated out, and none have been
729 * added in the meantime.
730 */
731 @VisibleForTesting
732 public void onAllBubblesAnimatedOut() {
733 if (mStackView != null) {
734 mStackView.setVisibility(INVISIBLE);
735 removeFromWindowManagerMaybe();
736 }
737 }
738
739 /**
740 * Records the notification key for any active bubbles. These are used to restore active
741 * bubbles when the user returns to the foreground.
742 *
743 * @param userId the id of the user
744 */
745 private void saveBubbles(@UserIdInt int userId) {
746 // First clear any existing keys that might be stored.
747 mSavedUserBubbleData.remove(userId);
748 UserBubbleData userBubbleData = new UserBubbleData();
749 // Add in all active bubbles for the current user.
750 for (Bubble bubble : mBubbleData.getBubbles()) {
751 userBubbleData.add(bubble.getKey(), bubble.showInShade());
752 }
753 mSavedUserBubbleData.put(userId, userBubbleData);
754 }
755
756 /**
757 * Promotes existing notifications to Bubbles if they were previously bubbles.
758 *
759 * @param userId the id of the user
760 */
761 private void restoreBubbles(@UserIdInt int userId) {
762 UserBubbleData savedBubbleData = mSavedUserBubbleData.get(userId);
763 if (savedBubbleData == null) {
764 // There were no bubbles saved for this used.
765 return;
766 }
767 mSysuiProxy.getShouldRestoredEntries(savedBubbleData.getKeys(), (entries) -> {
768 mMainExecutor.execute(() -> {
769 for (BubbleEntry e : entries) {
770 if (canLaunchInTaskView(mContext, e)) {
771 boolean showInShade = savedBubbleData.isShownInShade(e.getKey());
772 updateBubble(e, true /* suppressFlyout */, showInShade);
773 }
774 }
775 });
776 });
777 // Finally, remove the entries for this user now that bubbles are restored.
778 mSavedUserBubbleData.remove(userId);
779 }
780
781 @Override
782 public void onThemeChanged() {
783 if (mStackView != null) {
784 mStackView.onThemeChanged();
785 }
786 mBubbleIconFactory = new BubbleIconFactory(mContext);
787 mBubbleBadgeIconFactory = new BubbleBadgeIconFactory(mContext);
788
789 // Reload each bubble
790 for (Bubble b : mBubbleData.getBubbles()) {
791 b.inflate(null /* callback */, mContext, this, mStackView, mBubbleIconFactory,
792 mBubbleBadgeIconFactory,
793 false /* skipInflation */);
794 }
795 for (Bubble b : mBubbleData.getOverflowBubbles()) {
796 b.inflate(null /* callback */, mContext, this, mStackView, mBubbleIconFactory,
797 mBubbleBadgeIconFactory,
798 false /* skipInflation */);
799 }
800 }
801
802 @Override
803 public void onConfigurationChanged(Configuration newConfig) {
804 if (mBubblePositioner != null) {
805 mBubblePositioner.update();
806 }
807 if (mStackView != null && newConfig != null) {
808 if (newConfig.densityDpi != mDensityDpi
809 || !newConfig.windowConfiguration.getBounds().equals(mScreenBounds)) {
810 mDensityDpi = newConfig.densityDpi;
811 mScreenBounds.set(newConfig.windowConfiguration.getBounds());
812 mBubbleData.onMaxBubblesChanged();
813 mBubbleIconFactory = new BubbleIconFactory(mContext);
814 mBubbleBadgeIconFactory = new BubbleBadgeIconFactory(mContext);
815 mStackView.onDisplaySizeChanged();
816 }
817 if (newConfig.fontScale != mFontScale) {
818 mFontScale = newConfig.fontScale;
819 mStackView.updateFontScale();
820 }
821 if (newConfig.getLayoutDirection() != mLayoutDirection) {
822 mLayoutDirection = newConfig.getLayoutDirection();
823 mStackView.onLayoutDirectionChanged(mLayoutDirection);
824 }
825 }
826 }
827
828 private void onNotificationPanelExpandedChanged(boolean expanded) {
829 if (DEBUG_BUBBLE_GESTURE) {
830 Log.d(TAG, "onNotificationPanelExpandedChanged: expanded=" + expanded);
831 }
832 if (mStackView != null && mStackView.isExpanded()) {
833 if (expanded) {
834 mStackView.stopMonitoringSwipeUpGesture();
835 } else {
836 mStackView.startMonitoringSwipeUpGesture();
837 }
838 }
839 }
840
841 private void setSysuiProxy(Bubbles.SysuiProxy proxy) {
842 mSysuiProxy = proxy;
843 }
844
845 @VisibleForTesting
846 public void setExpandListener(Bubbles.BubbleExpandListener listener) {
847 mExpandListener = ((isExpanding, key) -> {
848 if (listener != null) {
849 listener.onBubbleExpandChanged(isExpanding, key);
850 }
851 });
852 if (mStackView != null) {
853 mStackView.setExpandListener(mExpandListener);
854 }
855 }
856
857 /**
858 * Whether or not there are bubbles present, regardless of them being visible on the
859 * screen (e.g. if on AOD).
860 */
861 @VisibleForTesting
862 public boolean hasBubbles() {
863 if (mStackView == null) {
864 return false;
865 }
866 return mBubbleData.hasBubbles() || mBubbleData.isShowingOverflow();
867 }
868
869 @VisibleForTesting
870 public boolean isStackExpanded() {
871 return mBubbleData.isExpanded();
872 }
873
874 public void collapseStack() {
875 mBubbleData.setExpanded(false /* expanded */);
876 }
877
878 @VisibleForTesting
879 public boolean isBubbleNotificationSuppressedFromShade(String key, String groupKey) {
880 boolean isSuppressedBubble = (mBubbleData.hasAnyBubbleWithKey(key)
881 && !mBubbleData.getAnyBubbleWithkey(key).showInShade());
882
883 boolean isSuppressedSummary = mBubbleData.isSummarySuppressed(groupKey);
884 boolean isSummary = key.equals(mBubbleData.getSummaryKey(groupKey));
885 return (isSummary && isSuppressedSummary) || isSuppressedBubble;
886 }
887
888 /** Promote the provided bubble from the overflow view. */
889 public void promoteBubbleFromOverflow(Bubble bubble) {
890 mLogger.log(bubble, BubbleLogger.Event.BUBBLE_OVERFLOW_REMOVE_BACK_TO_STACK);
891 bubble.setInflateSynchronously(mInflateSynchronously);
892 bubble.setShouldAutoExpand(true);
893 bubble.markAsAccessedAt(System.currentTimeMillis());
894 setIsBubble(bubble, true /* isBubble */);
895 }
896
897 /**
898 * Expands and selects the provided bubble as long as it already exists in the stack or the
899 * overflow.
900 *
901 * This is currently only used when opening a bubble via clicking on a conversation widget.
902 */
903 public void expandStackAndSelectBubble(Bubble b) {
904 if (b == null) {
905 return;
906 }
907 if (mBubbleData.hasBubbleInStackWithKey(b.getKey())) {
908 // already in the stack
909 mBubbleData.setSelectedBubble(b);
910 mBubbleData.setExpanded(true);
911 } else if (mBubbleData.hasOverflowBubbleWithKey(b.getKey())) {
912 // promote it out of the overflow
913 promoteBubbleFromOverflow(b);
914 }
915 }
916
917 /**
918 * Expands and selects a bubble based on the provided {@link BubbleEntry}. If no bubble
919 * exists for this entry, and it is able to bubble, a new bubble will be created.
920 *
921 * This is the method to use when opening a bubble via a notification or in a state where
922 * the device might not be unlocked.
923 *
924 * @param entry the entry to use for the bubble.
925 */
926 public void expandStackAndSelectBubble(BubbleEntry entry) {
927 if (mIsStatusBarShade) {
928 mNotifEntryToExpandOnShadeUnlock = null;
929
930 String key = entry.getKey();
931 Bubble bubble = mBubbleData.getBubbleInStackWithKey(key);
932 if (bubble != null) {
933 mBubbleData.setSelectedBubble(bubble);
934 mBubbleData.setExpanded(true);
935 } else {
936 bubble = mBubbleData.getOverflowBubbleWithKey(key);
937 if (bubble != null) {
938 promoteBubbleFromOverflow(bubble);
939 } else if (entry.canBubble()) {
940 // It can bubble but it's not -- it got aged out of the overflow before it
941 // was dismissed or opened, make it a bubble again.
942 setIsBubble(entry, true /* isBubble */, true /* autoExpand */);
943 }
944 }
945 } else {
946 // Wait until we're unlocked to expand, so that the user can see the expand animation
947 // and also to work around bugs with expansion animation + shade unlock happening at the
948 // same time.
949 mNotifEntryToExpandOnShadeUnlock = entry;
950 }
951 }
952
953 /**
954 * Adds or updates a bubble associated with the provided notification entry.
955 *
956 * @param notif the notification associated with this bubble.
957 */
958 @VisibleForTesting
959 public void updateBubble(BubbleEntry notif) {
960 int bubbleUserId = notif.getStatusBarNotification().getUserId();
961 if (isCurrentProfile(bubbleUserId)) {
962 updateBubble(notif, false /* suppressFlyout */, true /* showInShade */);
963 } else {
964 // Skip update, but store it in user bubbles so it gets restored after user switch
965 mSavedUserBubbleData.get(bubbleUserId, new UserBubbleData()).add(notif.getKey(),
966 true /* shownInShade */);
967 if (DEBUG_BUBBLE_CONTROLLER) {
968 Log.d(TAG,
969 "Ignore update to bubble for not active user. Bubble userId=" + bubbleUserId
970 + " current userId=" + mCurrentUserId);
971 }
972 }
973 }
974
975 /**
976 * Adds and expands bubble for a specific intent. These bubbles are <b>not</b> backed by a n
977 * otification and remain until the user dismisses the bubble or bubble stack. Only one intent
978 * bubble is supported at a time.
979 *
980 * @param intent the intent to display in the bubble expanded view.
981 */
982 public void showAppBubble(Intent intent) {
983 if (intent == null || intent.getPackage() == null) return;
984
985 PackageManager packageManager = getPackageManagerForUser(mContext, mCurrentUserId);
986 if (!isResizableActivity(intent, packageManager, KEY_APP_BUBBLE)) return;
987
988 Bubble b = new Bubble(intent, UserHandle.of(mCurrentUserId), mMainExecutor);
989 b.setShouldAutoExpand(true);
990 inflateAndAdd(b, /* suppressFlyout= */ true, /* showInShade= */ false);
991 }
992
993 /**
994 * Fills the overflow bubbles by loading them from disk.
995 */
996 void loadOverflowBubblesFromDisk() {
997 if (!mOverflowDataLoadNeeded) {
998 return;
999 }
1000 mOverflowDataLoadNeeded = false;
1001 mDataRepository.loadBubbles(mCurrentUserId, (bubbles) -> {
1002 bubbles.forEach(bubble -> {
1003 if (mBubbleData.hasAnyBubbleWithKey(bubble.getKey())) {
1004 // if the bubble is already active, there's no need to push it to overflow
1005 return;
1006 }
1007 bubble.inflate(
1008 (b) -> mBubbleData.overflowBubble(Bubbles.DISMISS_RELOAD_FROM_DISK, bubble),
1009 mContext, this, mStackView, mBubbleIconFactory, mBubbleBadgeIconFactory,
1010 true /* skipInflation */);
1011 });
1012 return null;
1013 });
1014 }
1015
1016 /**
1017 * Adds or updates a bubble associated with the provided notification entry.
1018 *
1019 * @param notif the notification associated with this bubble.
1020 * @param suppressFlyout this bubble suppress flyout or not.
1021 * @param showInShade this bubble show in shade or not.
1022 */
1023 @VisibleForTesting
1024 public void updateBubble(BubbleEntry notif, boolean suppressFlyout, boolean showInShade) {
1025 // If this is an interruptive notif, mark that it's interrupted
1026 mSysuiProxy.setNotificationInterruption(notif.getKey());
1027 boolean isNonInterruptiveNotExpanding = !notif.getRanking().isTextChanged()
1028 && (notif.getBubbleMetadata() != null
1029 && !notif.getBubbleMetadata().getAutoExpandBubble());
1030 if (isNonInterruptiveNotExpanding
1031 && mBubbleData.hasOverflowBubbleWithKey(notif.getKey())) {
1032 // Update the bubble but don't promote it out of overflow
1033 Bubble b = mBubbleData.getOverflowBubbleWithKey(notif.getKey());
1034 if (notif.isBubble()) {
1035 notif.setFlagBubble(false);
1036 }
1037 updateNotNotifyingEntry(b, notif, showInShade);
1038 } else if (mBubbleData.hasAnyBubbleWithKey(notif.getKey())
1039 && isNonInterruptiveNotExpanding) {
1040 Bubble b = mBubbleData.getAnyBubbleWithkey(notif.getKey());
1041 if (b != null) {
1042 updateNotNotifyingEntry(b, notif, showInShade);
1043 }
1044 } else if (mBubbleData.isSuppressedWithLocusId(notif.getLocusId())) {
1045 // Update the bubble but don't promote it out of overflow
1046 Bubble b = mBubbleData.getSuppressedBubbleWithKey(notif.getKey());
1047 if (b != null) {
1048 updateNotNotifyingEntry(b, notif, showInShade);
1049 }
1050 } else {
1051 Bubble bubble = mBubbleData.getOrCreateBubble(notif, null /* persistedBubble */);
1052 if (notif.shouldSuppressNotificationList()) {
1053 // If we're suppressing notifs for DND, we don't want the bubbles to randomly
1054 // expand when DND turns off so flip the flag.
1055 if (bubble.shouldAutoExpand()) {
1056 bubble.setShouldAutoExpand(false);
1057 }
1058 mImpl.mCachedState.updateBubbleSuppressedState(bubble);
1059 } else {
1060 inflateAndAdd(bubble, suppressFlyout, showInShade);
1061 }
1062 }
1063 }
1064
1065 void updateNotNotifyingEntry(Bubble b, BubbleEntry entry, boolean showInShade) {
1066 boolean showInShadeBefore = b.showInShade();
1067 boolean isBubbleSelected = Objects.equals(b, mBubbleData.getSelectedBubble());
1068 boolean isBubbleExpandedAndSelected = isStackExpanded() && isBubbleSelected;
1069 b.setEntry(entry);
1070 boolean suppress = isBubbleExpandedAndSelected || !showInShade || !b.showInShade();
1071 b.setSuppressNotification(suppress);
1072 b.setShowDot(!isBubbleExpandedAndSelected);
1073 if (showInShadeBefore != b.showInShade()) {
1074 mImpl.mCachedState.updateBubbleSuppressedState(b);
1075 }
1076 }
1077
1078 @VisibleForTesting
1079 public void inflateAndAdd(Bubble bubble, boolean suppressFlyout, boolean showInShade) {
1080 // Lazy init stack view when a bubble is created
1081 ensureStackViewCreated();
1082 bubble.setInflateSynchronously(mInflateSynchronously);
1083 bubble.inflate(b -> mBubbleData.notificationEntryUpdated(b, suppressFlyout, showInShade),
1084 mContext, this, mStackView, mBubbleIconFactory, mBubbleBadgeIconFactory,
1085 false /* skipInflation */);
1086 }
1087
1088 /**
1089 * Removes the bubble with the given key.
1090 * <p>
1091 * Must be called from the main thread.
1092 */
1093 @VisibleForTesting
1094 @MainThread
1095 public void removeBubble(String key, int reason) {
1096 if (mBubbleData.hasAnyBubbleWithKey(key)) {
1097 mBubbleData.dismissBubbleWithKey(key, reason);
1098 }
1099 }
1100
1101 private void onEntryAdded(BubbleEntry entry) {
1102 if (canLaunchInTaskView(mContext, entry)) {
1103 updateBubble(entry);
1104 }
1105 }
1106
1107 @VisibleForTesting
1108 public void onEntryUpdated(BubbleEntry entry, boolean shouldBubbleUp, boolean fromSystem) {
1109 if (!fromSystem) {
1110 return;
1111 }
1112 // shouldBubbleUp checks canBubble & for bubble metadata
1113 boolean shouldBubble = shouldBubbleUp && canLaunchInTaskView(mContext, entry);
1114 if (!shouldBubble && mBubbleData.hasAnyBubbleWithKey(entry.getKey())) {
1115 // It was previously a bubble but no longer a bubble -- lets remove it
1116 removeBubble(entry.getKey(), DISMISS_NO_LONGER_BUBBLE);
1117 } else if (shouldBubble && entry.isBubble()) {
1118 updateBubble(entry);
1119 }
1120 }
1121
1122 private void onEntryRemoved(BubbleEntry entry) {
1123 if (isSummaryOfBubbles(entry)) {
1124 final String groupKey = entry.getStatusBarNotification().getGroupKey();
1125 mBubbleData.removeSuppressedSummary(groupKey);
1126
1127 // Remove any associated bubble children with the summary
1128 final List<Bubble> bubbleChildren = getBubblesInGroup(groupKey);
1129 for (int i = 0; i < bubbleChildren.size(); i++) {
1130 removeBubble(bubbleChildren.get(i).getKey(), DISMISS_GROUP_CANCELLED);
1131 }
1132 } else {
1133 removeBubble(entry.getKey(), DISMISS_NOTIF_CANCEL);
1134 }
1135 }
1136
1137 @VisibleForTesting
1138 public void onRankingUpdated(RankingMap rankingMap,
1139 HashMap<String, Pair<BubbleEntry, Boolean>> entryDataByKey) {
1140 if (mTmpRanking == null) {
1141 mTmpRanking = new NotificationListenerService.Ranking();
1142 }
1143 String[] orderedKeys = rankingMap.getOrderedKeys();
1144 for (int i = 0; i < orderedKeys.length; i++) {
1145 String key = orderedKeys[i];
1146 Pair<BubbleEntry, Boolean> entryData = entryDataByKey.get(key);
1147 BubbleEntry entry = entryData.first;
1148 boolean shouldBubbleUp = entryData.second;
1149 if (entry != null && !isCurrentProfile(
1150 entry.getStatusBarNotification().getUser().getIdentifier())) {
1151 return;
1152 }
1153 if (entry != null && (entry.shouldSuppressNotificationList()
1154 || entry.getRanking().isSuspended())) {
1155 shouldBubbleUp = false;
1156 }
1157 rankingMap.getRanking(key, mTmpRanking);
1158 boolean isActiveOrInOverflow = mBubbleData.hasAnyBubbleWithKey(key);
1159 boolean isActive = mBubbleData.hasBubbleInStackWithKey(key);
1160 if (isActiveOrInOverflow && !mTmpRanking.canBubble()) {
1161 // If this entry is no longer allowed to bubble, dismiss with the BLOCKED reason.
1162 // This means that the app or channel's ability to bubble has been revoked.
1163 mBubbleData.dismissBubbleWithKey(key, DISMISS_BLOCKED);
1164 } else if (isActiveOrInOverflow && !shouldBubbleUp) {
1165 // If this entry is allowed to bubble, but cannot currently bubble up or is
1166 // suspended, dismiss it. This happens when DND is enabled and configured to hide
1167 // bubbles, or focus mode is enabled and the app is designated as distracting.
1168 // Dismissing with the reason DISMISS_NO_BUBBLE_UP will retain the underlying
1169 // notification, so that the bubble will be re-created if shouldBubbleUp returns
1170 // true.
1171 mBubbleData.dismissBubbleWithKey(key, DISMISS_NO_BUBBLE_UP);
1172 } else if (entry != null && mTmpRanking.isBubble() && !isActiveOrInOverflow) {
1173 entry.setFlagBubble(true);
1174 onEntryUpdated(entry, shouldBubbleUp, /* fromSystem= */ true);
1175 }
1176 }
1177 }
1178
1179 @VisibleForTesting
1180 public void onNotificationChannelModified(String pkg, UserHandle user,
1181 NotificationChannel channel, int modificationType) {
1182 // Only query overflow bubbles here because active bubbles will have an active notification
1183 // and channel changes we care about would result in a ranking update.
1184 List<Bubble> overflowBubbles = new ArrayList<>(mBubbleData.getOverflowBubbles());
1185 for (int i = 0; i < overflowBubbles.size(); i++) {
1186 Bubble b = overflowBubbles.get(i);
1187 if (Objects.equals(b.getShortcutId(), channel.getConversationId())
1188 && b.getPackageName().equals(pkg)
1189 && b.getUser().getIdentifier() == user.getIdentifier()) {
1190 if (!channel.canBubble() || channel.isDeleted()) {
1191 mBubbleData.dismissBubbleWithKey(b.getKey(), DISMISS_NO_LONGER_BUBBLE);
1192 }
1193 }
1194 }
1195 }
1196
1197 /**
1198 * Retrieves any bubbles that are part of the notification group represented by the provided
1199 * group key.
1200 */
1201 private ArrayList<Bubble> getBubblesInGroup(@Nullable String groupKey) {
1202 ArrayList<Bubble> bubbleChildren = new ArrayList<>();
1203 if (groupKey == null) {
1204 return bubbleChildren;
1205 }
1206 for (Bubble bubble : mBubbleData.getActiveBubbles()) {
1207 if (bubble.getGroupKey() != null && groupKey.equals(bubble.getGroupKey())) {
1208 bubbleChildren.add(bubble);
1209 }
1210 }
1211 return bubbleChildren;
1212 }
1213
1214 private void setIsBubble(@NonNull final BubbleEntry entry, final boolean isBubble,
1215 final boolean autoExpand) {
1216 Objects.requireNonNull(entry);
1217 entry.setFlagBubble(isBubble);
1218 try {
1219 int flags = 0;
1220 if (autoExpand) {
1221 flags = Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION;
1222 flags |= Notification.BubbleMetadata.FLAG_AUTO_EXPAND_BUBBLE;
1223 }
1224 mBarService.onNotificationBubbleChanged(entry.getKey(), isBubble, flags);
1225 } catch (RemoteException e) {
1226 // Bad things have happened
1227 }
1228 }
1229
1230 private void setIsBubble(@NonNull final Bubble b, final boolean isBubble) {
1231 Objects.requireNonNull(b);
1232 b.setIsBubble(isBubble);
1233 mSysuiProxy.getPendingOrActiveEntry(b.getKey(), (entry) -> {
1234 mMainExecutor.execute(() -> {
1235 if (entry != null) {
1236 // Updating the entry to be a bubble will trigger our normal update flow
1237 setIsBubble(entry, isBubble, b.shouldAutoExpand());
1238 } else if (isBubble) {
1239 // If bubble doesn't exist, it's a persisted bubble so we need to add it to the
1240 // stack ourselves
1241 Bubble bubble = mBubbleData.getOrCreateBubble(null, b /* persistedBubble */);
1242 inflateAndAdd(bubble, bubble.shouldAutoExpand() /* suppressFlyout */,
1243 !bubble.shouldAutoExpand() /* showInShade */);
1244 }
1245 });
1246 });
1247 }
1248
1249 @SuppressWarnings("FieldCanBeLocal")
1250 private final BubbleData.Listener mBubbleDataListener = new BubbleData.Listener() {
1251
1252 @Override
1253 public void applyUpdate(BubbleData.Update update) {
1254 if (DEBUG_BUBBLE_CONTROLLER) {
1255 Log.d(TAG, "applyUpdate:" + " bubbleAdded=" + (update.addedBubble != null)
1256 + " bubbleRemoved="
1257 + (update.removedBubbles != null && update.removedBubbles.size() > 0)
1258 + " bubbleUpdated=" + (update.updatedBubble != null)
1259 + " orderChanged=" + update.orderChanged
1260 + " expandedChanged=" + update.expandedChanged
1261 + " selectionChanged=" + update.selectionChanged
1262 + " suppressed=" + (update.suppressedBubble != null)
1263 + " unsuppressed=" + (update.unsuppressedBubble != null));
1264 }
1265
1266 ensureStackViewCreated();
1267
1268 // Lazy load overflow bubbles from disk
1269 loadOverflowBubblesFromDisk();
1270
1271 mStackView.updateOverflowButtonDot();
1272
1273 // Update bubbles in overflow.
1274 if (mOverflowListener != null) {
1275 mOverflowListener.applyUpdate(update);
1276 }
1277
1278 // Do removals, if any.
1279 ArrayList<Pair<Bubble, Integer>> removedBubbles =
1280 new ArrayList<>(update.removedBubbles);
1281 ArrayList<Bubble> bubblesToBeRemovedFromRepository = new ArrayList<>();
1282 for (Pair<Bubble, Integer> removed : removedBubbles) {
1283 final Bubble bubble = removed.first;
1284 @Bubbles.DismissReason final int reason = removed.second;
1285
1286 if (mStackView != null) {
1287 mStackView.removeBubble(bubble);
1288 }
1289
1290 // Leave the notification in place if we're dismissing due to user switching, or
1291 // because DND is suppressing the bubble. In both of those cases, we need to be able
1292 // to restore the bubble from the notification later.
1293 if (reason == DISMISS_USER_CHANGED || reason == DISMISS_NO_BUBBLE_UP) {
1294 continue;
1295 }
1296 if (reason == DISMISS_NOTIF_CANCEL
1297 || reason == DISMISS_SHORTCUT_REMOVED) {
1298 bubblesToBeRemovedFromRepository.add(bubble);
1299 }
1300 if (!mBubbleData.hasBubbleInStackWithKey(bubble.getKey())) {
1301 if (!mBubbleData.hasOverflowBubbleWithKey(bubble.getKey())
1302 && (!bubble.showInShade()
1303 || reason == DISMISS_NOTIF_CANCEL
1304 || reason == DISMISS_GROUP_CANCELLED)) {
1305 // The bubble is now gone & the notification is hidden from the shade, so
1306 // time to actually remove it
1307 mSysuiProxy.notifyRemoveNotification(bubble.getKey(), REASON_CANCEL);
1308 } else {
1309 if (bubble.isBubble()) {
1310 setIsBubble(bubble, false /* isBubble */);
1311 }
1312 mSysuiProxy.updateNotificationBubbleButton(bubble.getKey());
1313 }
1314 }
1315 }
1316 mDataRepository.removeBubbles(mCurrentUserId, bubblesToBeRemovedFromRepository);
1317
1318 if (update.addedBubble != null && mStackView != null) {
1319 mDataRepository.addBubble(mCurrentUserId, update.addedBubble);
1320 mStackView.addBubble(update.addedBubble);
1321 }
1322
1323 if (update.updatedBubble != null && mStackView != null) {
1324 mStackView.updateBubble(update.updatedBubble);
1325 }
1326
1327 if (update.suppressedBubble != null && mStackView != null) {
1328 mStackView.setBubbleSuppressed(update.suppressedBubble, true);
1329 }
1330
1331 if (update.unsuppressedBubble != null && mStackView != null) {
1332 mStackView.setBubbleSuppressed(update.unsuppressedBubble, false);
1333 }
1334
1335 boolean collapseStack = update.expandedChanged && !update.expanded;
1336
1337 // At this point, the correct bubbles are inflated in the stack.
1338 // Make sure the order in bubble data is reflected in bubble row.
1339 if (update.orderChanged && mStackView != null) {
1340 mDataRepository.addBubbles(mCurrentUserId, update.bubbles);
1341 // if the stack is going to be collapsed, do not update pointer position
1342 // after reordering
1343 mStackView.updateBubbleOrder(update.bubbles, !collapseStack);
1344 }
1345
1346 if (collapseStack) {
1347 mStackView.setExpanded(false);
1348 mSysuiProxy.requestNotificationShadeTopUi(false, TAG);
1349 }
1350
1351 if (update.selectionChanged && mStackView != null) {
1352 mStackView.setSelectedBubble(update.selectedBubble);
1353 }
1354
1355 // Expanding? Apply this last.
1356 if (update.expandedChanged && update.expanded) {
1357 if (mStackView != null) {
1358 mStackView.setExpanded(true);
1359 mSysuiProxy.requestNotificationShadeTopUi(true, TAG);
1360 }
1361 }
1362
1363 mSysuiProxy.notifyInvalidateNotifications("BubbleData.Listener.applyUpdate");
1364 updateStack();
1365
1366 // Update the cached state for queries from SysUI
1367 mImpl.mCachedState.update(update);
1368 }
1369 };
1370
1371 private boolean handleDismissalInterception(BubbleEntry entry,
1372 @Nullable List<BubbleEntry> children, IntConsumer removeCallback) {
1373 if (isSummaryOfBubbles(entry)) {
1374 handleSummaryDismissalInterception(entry, children, removeCallback);
1375 } else {
1376 Bubble bubble = mBubbleData.getBubbleInStackWithKey(entry.getKey());
1377 if (bubble == null || !entry.isBubble()) {
1378 bubble = mBubbleData.getOverflowBubbleWithKey(entry.getKey());
1379 }
1380 if (bubble == null) {
1381 return false;
1382 }
1383 bubble.setSuppressNotification(true);
1384 bubble.setShowDot(false /* show */);
1385 }
1386 // Update the shade
1387 mSysuiProxy.notifyInvalidateNotifications("BubbleController.handleDismissalInterception");
1388 return true;
1389 }
1390
1391 private boolean isSummaryOfBubbles(BubbleEntry entry) {
1392 String groupKey = entry.getStatusBarNotification().getGroupKey();
1393 ArrayList<Bubble> bubbleChildren = getBubblesInGroup(groupKey);
1394 boolean isSuppressedSummary = mBubbleData.isSummarySuppressed(groupKey)
1395 && mBubbleData.getSummaryKey(groupKey).equals(entry.getKey());
1396 boolean isSummary = entry.getStatusBarNotification().getNotification().isGroupSummary();
1397 return (isSuppressedSummary || isSummary) && !bubbleChildren.isEmpty();
1398 }
1399
1400 private void handleSummaryDismissalInterception(
1401 BubbleEntry summary, @Nullable List<BubbleEntry> children, IntConsumer removeCallback) {
1402 if (children != null) {
1403 for (int i = 0; i < children.size(); i++) {
1404 BubbleEntry child = children.get(i);
1405 if (mBubbleData.hasAnyBubbleWithKey(child.getKey())) {
1406 // Suppress the bubbled child
1407 // As far as group manager is concerned, once a child is no longer shown
1408 // in the shade, it is essentially removed.
1409 Bubble bubbleChild = mBubbleData.getAnyBubbleWithkey(child.getKey());
1410 if (bubbleChild != null) {
1411 bubbleChild.setSuppressNotification(true);
1412 bubbleChild.setShowDot(false /* show */);
1413 }
1414 } else {
1415 // non-bubbled children can be removed
1416 removeCallback.accept(i);
1417 }
1418 }
1419 }
1420
1421 // And since all children are removed, remove the summary.
1422 removeCallback.accept(-1);
1423
1424 // TODO: (b/145659174) remove references to mSuppressedGroupKeys once fully migrated
1425 mBubbleData.addSummaryToSuppress(summary.getStatusBarNotification().getGroupKey(),
1426 summary.getKey());
1427 }
1428
1429 /**
1430 * Updates the visibility of the bubbles based on current state.
1431 * Does not un-bubble, just hides or un-hides.
1432 * Updates stack description for TalkBack focus.
1433 * Updates bubbles' icon views clickable states
1434 */
1435 public void updateStack() {
1436 if (mStackView == null) {
1437 return;
1438 }
1439
1440 if (!mIsStatusBarShade) {
1441 // Bubbles don't appear over the locked shade.
1442 mStackView.setVisibility(INVISIBLE);
1443 } else if (hasBubbles()) {
1444 // If we're unlocked, show the stack if we have bubbles. If we don't have bubbles, the
1445 // stack will be set to INVISIBLE in onAllBubblesAnimatedOut after the bubbles animate
1446 // out.
1447 mStackView.setVisibility(VISIBLE);
1448 }
1449
1450 mStackView.updateContentDescription();
1451
1452 mStackView.updateBubblesAcessibillityStates();
1453 }
1454
1455 @VisibleForTesting
1456 public BubbleStackView getStackView() {
1457 return mStackView;
1458 }
1459
1460 /**
1461 * Check if notification panel is in an expanded state.
1462 * Makes a call to System UI process and delivers the result via {@code callback} on the
1463 * WM Shell main thread.
1464 *
1465 * @param callback callback that has the result of notification panel expanded state
1466 */
1467 public void isNotificationPanelExpanded(Consumer<Boolean> callback) {
1468 mSysuiProxy.isNotificationPanelExpand(expanded ->
1469 mMainExecutor.execute(() -> callback.accept(expanded)));
1470 }
1471
1472 /**
1473 * Description of current bubble state.
1474 */
1475 private void dump(PrintWriter pw, String prefix) {
1476 pw.println("BubbleController state:");
1477 mBubbleData.dump(pw);
1478 pw.println();
1479 if (mStackView != null) {
1480 mStackView.dump(pw);
1481 }
1482 pw.println();
1483 mImpl.mCachedState.dump(pw);
1484 }
1485
1486 /**
1487 * Whether an intent is properly configured to display in a
1488 * {@link com.android.wm.shell.TaskView}.
1489 *
1490 * Keep checks in sync with BubbleExtractor#canLaunchInTaskView. Typically
1491 * that should filter out any invalid bubbles, but should protect SysUI side just in case.
1492 *
1493 * @param context the context to use.
1494 * @param entry the entry to bubble.
1495 */
1496 static boolean canLaunchInTaskView(Context context, BubbleEntry entry) {
1497 PendingIntent intent = entry.getBubbleMetadata() != null
1498 ? entry.getBubbleMetadata().getIntent()
1499 : null;
1500 if (entry.getBubbleMetadata() != null
1501 && entry.getBubbleMetadata().getShortcutId() != null) {
1502 return true;
1503 }
1504 if (intent == null) {
1505 Log.w(TAG, "Unable to create bubble -- no intent: " + entry.getKey());
1506 return false;
1507 }
1508 PackageManager packageManager = getPackageManagerForUser(
1509 context, entry.getStatusBarNotification().getUser().getIdentifier());
1510 return isResizableActivity(intent.getIntent(), packageManager, entry.getKey());
1511 }
1512
1513 static boolean isResizableActivity(Intent intent, PackageManager packageManager, String key) {
1514 if (intent == null) {
1515 Log.w(TAG, "Unable to send as bubble: " + key + " null intent");
1516 return false;
1517 }
1518 ActivityInfo info = intent.resolveActivityInfo(packageManager, 0);
1519 if (info == null) {
1520 Log.w(TAG, "Unable to send as bubble: " + key
1521 + " couldn't find activity info for intent: " + intent);
1522 return false;
1523 }
1524 if (!ActivityInfo.isResizeableMode(info.resizeMode)) {
1525 Log.w(TAG, "Unable to send as bubble: " + key
1526 + " activity is not resizable for intent: " + intent);
1527 return false;
1528 }
1529 return true;
1530 }
1531
1532 static PackageManager getPackageManagerForUser(Context context, int userId) {
1533 Context contextForUser = context;
1534 // UserHandle defines special userId as negative values, e.g. USER_ALL
1535 if (userId >= 0) {
1536 try {
1537 // Create a context for the correct user so if a package isn't installed
1538 // for user 0 we can still load information about the package.
1539 contextForUser =
1540 context.createPackageContextAsUser(context.getPackageName(),
1541 Context.CONTEXT_RESTRICTED,
1542 new UserHandle(userId));
1543 } catch (PackageManager.NameNotFoundException e) {
1544 // Shouldn't fail to find the package name for system ui.
1545 }
1546 }
1547 return contextForUser.getPackageManager();
1548 }
1549
1550 /** PinnedStackListener that dispatches IME visibility updates to the stack. */
1551 //TODO(b/170442945): Better way to do this / insets listener?
1552 private class BubblesImeListener extends PinnedStackListenerForwarder.PinnedTaskListener {
1553 @Override
1554 public void onImeVisibilityChanged(boolean imeVisible, int imeHeight) {
1555 mBubblePositioner.setImeVisible(imeVisible, imeHeight);
1556 if (mStackView != null) {
1557 mStackView.setImeVisible(imeVisible);
1558 }
1559 }
1560 }
1561
1562 private class BubblesImpl implements Bubbles {
1563 // Up-to-date cached state of bubbles data for SysUI to query from the calling thread
1564 @VisibleForTesting
1565 public class CachedState {
1566 private boolean mIsStackExpanded;
1567 private String mSelectedBubbleKey;
1568 private HashSet<String> mSuppressedBubbleKeys = new HashSet<>();
1569 private HashMap<String, String> mSuppressedGroupToNotifKeys = new HashMap<>();
1570 private HashMap<String, Bubble> mShortcutIdToBubble = new HashMap<>();
1571
1572 private ArrayList<Bubble> mTmpBubbles = new ArrayList<>();
1573
1574 /**
1575 * Updates the cached state based on the last full BubbleData change.
1576 */
1577 synchronized void update(BubbleData.Update update) {
1578 if (update.selectionChanged) {
1579 mSelectedBubbleKey = update.selectedBubble != null
1580 ? update.selectedBubble.getKey()
1581 : null;
1582 }
1583 if (update.expandedChanged) {
1584 mIsStackExpanded = update.expanded;
1585 }
1586 if (update.suppressedSummaryChanged) {
1587 String summaryKey =
1588 mBubbleData.getSummaryKey(update.suppressedSummaryGroup);
1589 if (summaryKey != null) {
1590 mSuppressedGroupToNotifKeys.put(update.suppressedSummaryGroup, summaryKey);
1591 } else {
1592 mSuppressedGroupToNotifKeys.remove(update.suppressedSummaryGroup);
1593 }
1594 }
1595
1596 mTmpBubbles.clear();
1597 mTmpBubbles.addAll(update.bubbles);
1598 mTmpBubbles.addAll(update.overflowBubbles);
1599
1600 mSuppressedBubbleKeys.clear();
1601 mShortcutIdToBubble.clear();
1602 for (Bubble b : mTmpBubbles) {
1603 mShortcutIdToBubble.put(b.getShortcutId(), b);
1604 updateBubbleSuppressedState(b);
1605 }
1606 }
1607
1608 /**
1609 * Updates a specific bubble suppressed state. This is used mainly because notification
1610 * suppression changes don't go through the same BubbleData update mechanism.
1611 */
1612 synchronized void updateBubbleSuppressedState(Bubble b) {
1613 if (!b.showInShade()) {
1614 mSuppressedBubbleKeys.add(b.getKey());
1615 } else {
1616 mSuppressedBubbleKeys.remove(b.getKey());
1617 }
1618 }
1619
1620 public synchronized boolean isStackExpanded() {
1621 return mIsStackExpanded;
1622 }
1623
1624 public synchronized boolean isBubbleExpanded(String key) {
1625 return mIsStackExpanded && key.equals(mSelectedBubbleKey);
1626 }
1627
1628 public synchronized boolean isBubbleNotificationSuppressedFromShade(String key,
1629 String groupKey) {
1630 return mSuppressedBubbleKeys.contains(key)
1631 || (mSuppressedGroupToNotifKeys.containsKey(groupKey)
1632 && key.equals(mSuppressedGroupToNotifKeys.get(groupKey)));
1633 }
1634
1635 @Nullable
1636 public synchronized Bubble getBubbleWithShortcutId(String id) {
1637 return mShortcutIdToBubble.get(id);
1638 }
1639
1640 synchronized void dump(PrintWriter pw) {
1641 pw.println("BubbleImpl.CachedState state:");
1642
1643 pw.println("mIsStackExpanded: " + mIsStackExpanded);
1644 pw.println("mSelectedBubbleKey: " + mSelectedBubbleKey);
1645
1646 pw.print("mSuppressedBubbleKeys: ");
1647 pw.println(mSuppressedBubbleKeys.size());
1648 for (String key : mSuppressedBubbleKeys) {
1649 pw.println(" suppressing: " + key);
1650 }
1651
1652 pw.print("mSuppressedGroupToNotifKeys: ");
1653 pw.println(mSuppressedGroupToNotifKeys.size());
1654 for (String key : mSuppressedGroupToNotifKeys.keySet()) {
1655 pw.println(" suppressing: " + key);
1656 }
1657 }
1658 }
1659
1660 private CachedState mCachedState = new CachedState();
1661
1662 @Override
1663 public boolean isBubbleNotificationSuppressedFromShade(String key, String groupKey) {
1664 return mCachedState.isBubbleNotificationSuppressedFromShade(key, groupKey);
1665 }
1666
1667 @Override
1668 public boolean isBubbleExpanded(String key) {
1669 return mCachedState.isBubbleExpanded(key);
1670 }
1671
1672 @Override
1673 @Nullable
1674 public Bubble getBubbleWithShortcutId(String shortcutId) {
1675 return mCachedState.getBubbleWithShortcutId(shortcutId);
1676 }
1677
1678 @Override
1679 public void collapseStack() {
1680 mMainExecutor.execute(() -> {
1681 BubbleController.this.collapseStack();
1682 });
1683 }
1684
1685 @Override
1686 public void expandStackAndSelectBubble(BubbleEntry entry) {
1687 mMainExecutor.execute(() -> {
1688 BubbleController.this.expandStackAndSelectBubble(entry);
1689 });
1690 }
1691
1692 @Override
1693 public void expandStackAndSelectBubble(Bubble bubble) {
1694 mMainExecutor.execute(() -> {
1695 BubbleController.this.expandStackAndSelectBubble(bubble);
1696 });
1697 }
1698
1699 @Override
1700 public void showAppBubble(Intent intent) {
1701 mMainExecutor.execute(() -> {
1702 BubbleController.this.showAppBubble(intent);
1703 });
1704 }
1705
1706 @Override
1707 public boolean handleDismissalInterception(BubbleEntry entry,
1708 @Nullable List<BubbleEntry> children, IntConsumer removeCallback,
1709 Executor callbackExecutor) {
1710 IntConsumer cb = removeCallback != null
1711 ? (index) -> callbackExecutor.execute(() -> removeCallback.accept(index))
1712 : null;
1713 return mMainExecutor.executeBlockingForResult(() -> {
1714 return BubbleController.this.handleDismissalInterception(entry, children, cb);
1715 }, Boolean.class);
1716 }
1717
1718 @Override
1719 public void setSysuiProxy(SysuiProxy proxy) {
1720 mMainExecutor.execute(() -> {
1721 BubbleController.this.setSysuiProxy(proxy);
1722 });
1723 }
1724
1725 @Override
1726 public void setExpandListener(BubbleExpandListener listener) {
1727 mMainExecutor.execute(() -> {
1728 BubbleController.this.setExpandListener(listener);
1729 });
1730 }
1731
1732 @Override
1733 public void onEntryAdded(BubbleEntry entry) {
1734 mMainExecutor.execute(() -> {
1735 BubbleController.this.onEntryAdded(entry);
1736 });
1737 }
1738
1739 @Override
1740 public void onEntryUpdated(BubbleEntry entry, boolean shouldBubbleUp, boolean fromSystem) {
1741 mMainExecutor.execute(() -> {
1742 BubbleController.this.onEntryUpdated(entry, shouldBubbleUp, fromSystem);
1743 });
1744 }
1745
1746 @Override
1747 public void onEntryRemoved(BubbleEntry entry) {
1748 mMainExecutor.execute(() -> {
1749 BubbleController.this.onEntryRemoved(entry);
1750 });
1751 }
1752
1753 @Override
1754 public void onRankingUpdated(RankingMap rankingMap,
1755 HashMap<String, Pair<BubbleEntry, Boolean>> entryDataByKey) {
1756 mMainExecutor.execute(() -> {
1757 BubbleController.this.onRankingUpdated(rankingMap, entryDataByKey);
1758 });
1759 }
1760
1761 @Override
1762 public void onNotificationChannelModified(String pkg,
1763 UserHandle user, NotificationChannel channel, int modificationType) {
1764 // Bubbles only cares about updates or deletions.
1765 if (modificationType == NOTIFICATION_CHANNEL_OR_GROUP_UPDATED
1766 || modificationType == NOTIFICATION_CHANNEL_OR_GROUP_DELETED) {
1767 mMainExecutor.execute(() -> {
1768 BubbleController.this.onNotificationChannelModified(pkg, user, channel,
1769 modificationType);
1770 });
1771 }
1772 }
1773
1774 @Override
1775 public void onStatusBarVisibilityChanged(boolean visible) {
1776 mMainExecutor.execute(() -> {
1777 BubbleController.this.onStatusBarVisibilityChanged(visible);
1778 });
1779 }
1780
1781 @Override
1782 public void onZenStateChanged() {
1783 mMainExecutor.execute(() -> {
1784 BubbleController.this.onZenStateChanged();
1785 });
1786 }
1787
1788 @Override
1789 public void onStatusBarStateChanged(boolean isShade) {
1790 mMainExecutor.execute(() -> {
1791 BubbleController.this.onStatusBarStateChanged(isShade);
1792 });
1793 }
1794
1795 @Override
1796 public void onUserChanged(int newUserId) {
1797 mMainExecutor.execute(() -> {
1798 BubbleController.this.onUserChanged(newUserId);
1799 });
1800 }
1801
1802 @Override
1803 public void onCurrentProfilesChanged(SparseArray<UserInfo> currentProfiles) {
1804 mMainExecutor.execute(() -> {
1805 BubbleController.this.onCurrentProfilesChanged(currentProfiles);
1806 });
1807 }
1808
1809 @Override
1810 public void onUserRemoved(int removedUserId) {
1811 mMainExecutor.execute(() -> {
1812 BubbleController.this.onUserRemoved(removedUserId);
1813 });
1814 }
1815
1816 @Override
1817 public void setBubbleBarEnabled(boolean enabled) {
1818 mMainExecutor.execute(() -> {
1819 BubbleController.this.setBubbleBarEnabled(enabled);
1820 });
1821 }
1822
1823 @Override
1824 public void onNotificationPanelExpandedChanged(boolean expanded) {
1825 mMainExecutor.execute(
1826 () -> BubbleController.this.onNotificationPanelExpandedChanged(expanded));
1827 }
1828 }
1829
1830 /**
1831 * Bubble data that is stored per user.
1832 * Used to store and restore active bubbles during user switching.
1833 */
1834 private static class UserBubbleData {
1835 private final Map<String, Boolean> mKeyToShownInShadeMap = new HashMap<>();
1836
1837 /**
1838 * Add bubble key and whether it should be shown in notification shade
1839 */
1840 void add(String key, boolean shownInShade) {
1841 mKeyToShownInShadeMap.put(key, shownInShade);
1842 }
1843
1844 /**
1845 * Get all bubble keys stored for this user
1846 */
1847 Set<String> getKeys() {
1848 return mKeyToShownInShadeMap.keySet();
1849 }
1850
1851 /**
1852 * Check if this bubble with the given key should be shown in the notification shade
1853 */
1854 boolean isShownInShade(String key) {
1855 return mKeyToShownInShadeMap.get(key);
1856 }
1857 }
1858 }