Debian Codegraph @

libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 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 androidx.window.extensions.embedding;
18
19 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
20
21 import android.app.Activity;
22 import android.app.ActivityThread;
23 import android.app.WindowConfiguration.WindowingMode;
24 import android.content.Intent;
25 import android.graphics.Rect;
26 import android.os.Binder;
27 import android.os.IBinder;
28 import android.util.Size;
29 import android.window.TaskFragmentAnimationParams;
30 import android.window.TaskFragmentInfo;
31 import android.window.WindowContainerTransaction;
32
33 import androidx.annotation.GuardedBy;
34 import androidx.annotation.NonNull;
35 import androidx.annotation.Nullable;
36
37 import com.android.internal.annotations.VisibleForTesting;
38
39 import java.util.ArrayList;
40 import java.util.Iterator;
41 import java.util.List;
42
43 /**
44 * Client-side container for a stack of activities. Corresponds to an instance of TaskFragment
45 * on the server side.
46 */
47 // Suppress GuardedBy warning because all the TaskFragmentContainers are stored in
48 // SplitController.mTaskContainers which is guarded.
49 @SuppressWarnings("GuardedBy")
50 class TaskFragmentContainer {
51 private static final int APPEAR_EMPTY_TIMEOUT_MS = 3000;
52
53 @NonNull
54 private final SplitController mController;
55
56 /**
57 * Client-created token that uniquely identifies the task fragment container instance.
58 */
59 @NonNull
60 private final IBinder mToken;
61
62 /** Parent leaf Task. */
63 @NonNull
64 private final TaskContainer mTaskContainer;
65
66 /**
67 * Server-provided task fragment information.
68 */
69 @VisibleForTesting
70 TaskFragmentInfo mInfo;
71
72 /**
73 * Activity tokens that are being reparented or being started to this container, but haven't
74 * been added to {@link #mInfo} yet.
75 */
76 @VisibleForTesting
77 final ArrayList<IBinder> mPendingAppearedActivities = new ArrayList<>();
78
79 /**
80 * When this container is created for an {@link Intent} to start within, we store that Intent
81 * until the container becomes non-empty on the server side, so that we can use it to check
82 * rules associated with this container.
83 */
84 @Nullable
85 private Intent mPendingAppearedIntent;
86
87 /** Containers that are dependent on this one and should be completely destroyed on exit. */
88 private final List<TaskFragmentContainer> mContainersToFinishOnExit =
89 new ArrayList<>();
90
91 /**
92 * Individual associated activity tokens in different containers that should be finished on
93 * exit.
94 */
95 private final List<IBinder> mActivitiesToFinishOnExit = new ArrayList<>();
96
97 /** Indicates whether the container was cleaned up after the last activity was removed. */
98 private boolean mIsFinished;
99
100 /**
101 * Bounds that were requested last via {@link android.window.WindowContainerTransaction}.
102 */
103 private final Rect mLastRequestedBounds = new Rect();
104
105 /**
106 * Windowing mode that was requested last via {@link android.window.WindowContainerTransaction}.
107 */
108 @WindowingMode
109 private int mLastRequestedWindowingMode = WINDOWING_MODE_UNDEFINED;
110
111 /**
112 * TaskFragmentAnimationParams that was requested last via
113 * {@link android.window.WindowContainerTransaction}.
114 */
115 @NonNull
116 private TaskFragmentAnimationParams mLastAnimationParams = TaskFragmentAnimationParams.DEFAULT;
117
118 /**
119 * When the TaskFragment has appeared in server, but is empty, we should remove the TaskFragment
120 * if it is still empty after the timeout.
121 */
122 @VisibleForTesting
123 @Nullable
124 Runnable mAppearEmptyTimeout;
125
126 /**
127 * Creates a container with an existing activity that will be re-parented to it in a window
128 * container transaction.
129 * @param pairedPrimaryContainer when it is set, the new container will be add right above it
130 */
131 TaskFragmentContainer(@Nullable Activity pendingAppearedActivity,
132 @Nullable Intent pendingAppearedIntent, @NonNull TaskContainer taskContainer,
133 @NonNull SplitController controller,
134 @Nullable TaskFragmentContainer pairedPrimaryContainer) {
135 if ((pendingAppearedActivity == null && pendingAppearedIntent == null)
136 || (pendingAppearedActivity != null && pendingAppearedIntent != null)) {
137 throw new IllegalArgumentException(
138 "One and only one of pending activity and intent must be non-null");
139 }
140 mController = controller;
141 mToken = new Binder("TaskFragmentContainer");
142 mTaskContainer = taskContainer;
143 if (pairedPrimaryContainer != null) {
144 if (pairedPrimaryContainer.getTaskContainer() != taskContainer) {
145 throw new IllegalArgumentException(
146 "pairedPrimaryContainer must be in the same Task");
147 }
148 final int primaryIndex = taskContainer.mContainers.indexOf(pairedPrimaryContainer);
149 taskContainer.mContainers.add(primaryIndex + 1, this);
150 } else {
151 taskContainer.mContainers.add(this);
152 }
153 if (pendingAppearedActivity != null) {
154 addPendingAppearedActivity(pendingAppearedActivity);
155 }
156 mPendingAppearedIntent = pendingAppearedIntent;
157 }
158
159 /**
160 * Returns the client-created token that uniquely identifies this container.
161 */
162 @NonNull
163 IBinder getTaskFragmentToken() {
164 return mToken;
165 }
166
167 /** List of non-finishing activities that belong to this container and live in this process. */
168 @NonNull
169 List<Activity> collectNonFinishingActivities() {
170 final List<Activity> allActivities = new ArrayList<>();
171 if (mInfo != null) {
172 // Add activities reported from the server.
173 for (IBinder token : mInfo.getActivities()) {
174 final Activity activity = mController.getActivity(token);
175 if (activity != null && !activity.isFinishing()) {
176 allActivities.add(activity);
177 }
178 }
179 }
180
181 // Add the re-parenting activity, in case the server has not yet reported the task
182 // fragment info update with it placed in this container. We still want to apply rules
183 // in this intermediate state.
184 // Place those on top of the list since they will be on the top after reported from the
185 // server.
186 for (IBinder token : mPendingAppearedActivities) {
187 final Activity activity = mController.getActivity(token);
188 if (activity != null && !activity.isFinishing()) {
189 allActivities.add(activity);
190 }
191 }
192 return allActivities;
193 }
194
195 /** Whether this TaskFragment is visible. */
196 boolean isVisible() {
197 return mInfo != null && mInfo.isVisible();
198 }
199
200 /** Whether the TaskFragment is in an intermediate state waiting for the server update.*/
201 boolean isInIntermediateState() {
202 if (mInfo == null) {
203 // Haven't received onTaskFragmentAppeared event.
204 return true;
205 }
206 if (mInfo.isEmpty()) {
207 // Empty TaskFragment will be removed or will have activity launched into it soon.
208 return true;
209 }
210 if (!mPendingAppearedActivities.isEmpty()) {
211 // Reparented activity hasn't appeared.
212 return true;
213 }
214 // Check if there is any reported activity that is no longer alive.
215 for (IBinder token : mInfo.getActivities()) {
216 final Activity activity = mController.getActivity(token);
217 if (activity == null && !mTaskContainer.isVisible()) {
218 // Activity can be null if the activity is not attached to process yet. That can
219 // happen when the activity is started in background.
220 continue;
221 }
222 if (activity == null || activity.isFinishing()) {
223 // One of the reported activity is no longer alive, wait for the server update.
224 return true;
225 }
226 }
227 return false;
228 }
229
230 @NonNull
231 ActivityStack toActivityStack() {
232 return new ActivityStack(collectNonFinishingActivities(), isEmpty());
233 }
234
235 /** Adds the activity that will be reparented to this container. */
236 void addPendingAppearedActivity(@NonNull Activity pendingAppearedActivity) {
237 final IBinder activityToken = pendingAppearedActivity.getActivityToken();
238 if (hasActivity(activityToken)) {
239 return;
240 }
241 // Remove the pending activity from other TaskFragments in case the activity is reparented
242 // again before the server update.
243 mTaskContainer.cleanupPendingAppearedActivity(activityToken);
244 mPendingAppearedActivities.add(activityToken);
245 updateActivityClientRecordTaskFragmentToken(activityToken);
246 }
247
248 /**
249 * Updates the {@link ActivityThread.ActivityClientRecord#mTaskFragmentToken} for the
250 * activity. This makes sure the token is up-to-date if the activity is relaunched later.
251 */
252 private void updateActivityClientRecordTaskFragmentToken(@NonNull IBinder activityToken) {
253 final ActivityThread.ActivityClientRecord record = ActivityThread
254 .currentActivityThread().getActivityClient(activityToken);
255 if (record != null) {
256 record.mTaskFragmentToken = mToken;
257 }
258 }
259
260 void removePendingAppearedActivity(@NonNull IBinder activityToken) {
261 mPendingAppearedActivities.remove(activityToken);
262 }
263
264 @GuardedBy("mController.mLock")
265 void clearPendingAppearedActivities() {
266 final List<IBinder> cleanupActivities = new ArrayList<>(mPendingAppearedActivities);
267 // Clear mPendingAppearedActivities so that #getContainerWithActivity won't return the
268 // current TaskFragment.
269 mPendingAppearedActivities.clear();
270 mPendingAppearedIntent = null;
271
272 // For removed pending activities, we need to update the them to their previous containers.
273 for (IBinder activityToken : cleanupActivities) {
274 final TaskFragmentContainer curContainer = mController.getContainerWithActivity(
275 activityToken);
276 if (curContainer != null) {
277 curContainer.updateActivityClientRecordTaskFragmentToken(activityToken);
278 }
279 }
280 }
281
282 /** Called when the activity is destroyed. */
283 void onActivityDestroyed(@NonNull IBinder activityToken) {
284 removePendingAppearedActivity(activityToken);
285 if (mInfo != null) {
286 // Remove the activity now because there can be a delay before the server callback.
287 mInfo.getActivities().remove(activityToken);
288 }
289 mActivitiesToFinishOnExit.remove(activityToken);
290 }
291
292 @Nullable
293 Intent getPendingAppearedIntent() {
294 return mPendingAppearedIntent;
295 }
296
297 void setPendingAppearedIntent(@Nullable Intent intent) {
298 mPendingAppearedIntent = intent;
299 }
300
301 /**
302 * Clears the pending appeared Intent if it is the same as given Intent. Otherwise, the
303 * pending appeared Intent is cleared when TaskFragmentInfo is set and is not empty (has
304 * running activities).
305 */
306 void clearPendingAppearedIntentIfNeeded(@NonNull Intent intent) {
307 if (mPendingAppearedIntent == null || mPendingAppearedIntent != intent) {
308 return;
309 }
310 mPendingAppearedIntent = null;
311 }
312
313 boolean hasActivity(@NonNull IBinder activityToken) {
314 // Instead of using (hasAppearedActivity() || hasPendingAppearedActivity), we want to make
315 // sure the controller considers this container as the one containing the activity.
316 // This is needed when the activity is added as pending appeared activity to one
317 // TaskFragment while it is also an appeared activity in another.
318 return mController.getContainerWithActivity(activityToken) == this;
319 }
320
321 /** Whether this activity has appeared in the TaskFragment on the server side. */
322 boolean hasAppearedActivity(@NonNull IBinder activityToken) {
323 return mInfo != null && mInfo.getActivities().contains(activityToken);
324 }
325
326 /**
327 * Whether we are waiting for this activity to appear in the TaskFragment on the server side.
328 */
329 boolean hasPendingAppearedActivity(@NonNull IBinder activityToken) {
330 return mPendingAppearedActivities.contains(activityToken);
331 }
332
333 int getRunningActivityCount() {
334 int count = mPendingAppearedActivities.size();
335 if (mInfo != null) {
336 count += mInfo.getRunningActivityCount();
337 }
338 return count;
339 }
340
341 /** Whether we are waiting for the TaskFragment to appear and become non-empty. */
342 boolean isWaitingActivityAppear() {
343 return !mIsFinished && (mInfo == null || mAppearEmptyTimeout != null);
344 }
345
346 @Nullable
347 TaskFragmentInfo getInfo() {
348 return mInfo;
349 }
350
351 @GuardedBy("mController.mLock")
352 void setInfo(@NonNull WindowContainerTransaction wct, @NonNull TaskFragmentInfo info) {
353 if (!mIsFinished && mInfo == null && info.isEmpty()) {
354 // onTaskFragmentAppeared with empty info. We will remove the TaskFragment if no
355 // pending appeared intent/activities. Otherwise, wait and removing the TaskFragment if
356 // it is still empty after timeout.
357 if (mPendingAppearedIntent != null || !mPendingAppearedActivities.isEmpty()) {
358 mAppearEmptyTimeout = () -> {
359 synchronized (mController.mLock) {
360 mAppearEmptyTimeout = null;
361 // Call without the pass-in wct when timeout. We need to applyWct directly
362 // in this case.
363 mController.onTaskFragmentAppearEmptyTimeout(this);
364 }
365 };
366 mController.getHandler().postDelayed(mAppearEmptyTimeout, APPEAR_EMPTY_TIMEOUT_MS);
367 } else {
368 mAppearEmptyTimeout = null;
369 mController.onTaskFragmentAppearEmptyTimeout(wct, this);
370 }
371 } else if (mAppearEmptyTimeout != null && !info.isEmpty()) {
372 mController.getHandler().removeCallbacks(mAppearEmptyTimeout);
373 mAppearEmptyTimeout = null;
374 }
375
376 mInfo = info;
377 if (mInfo == null || mInfo.isEmpty()) {
378 return;
379 }
380 // Only track the pending Intent when the container is empty.
381 mPendingAppearedIntent = null;
382 if (mPendingAppearedActivities.isEmpty()) {
383 return;
384 }
385 // Cleanup activities that were being re-parented
386 List<IBinder> infoActivities = mInfo.getActivities();
387 for (int i = mPendingAppearedActivities.size() - 1; i >= 0; --i) {
388 final IBinder activityToken = mPendingAppearedActivities.get(i);
389 if (infoActivities.contains(activityToken)) {
390 mPendingAppearedActivities.remove(i);
391 }
392 }
393 }
394
395 @Nullable
396 Activity getTopNonFinishingActivity() {
397 final List<Activity> activities = collectNonFinishingActivities();
398 return activities.isEmpty() ? null : activities.get(activities.size() - 1);
399 }
400
401 @Nullable
402 Activity getBottomMostActivity() {
403 final List<Activity> activities = collectNonFinishingActivities();
404 return activities.isEmpty() ? null : activities.get(0);
405 }
406
407 boolean isEmpty() {
408 return mPendingAppearedActivities.isEmpty() && (mInfo == null || mInfo.isEmpty());
409 }
410
411 /**
412 * Adds a container that should be finished when this container is finished.
413 */
414 void addContainerToFinishOnExit(@NonNull TaskFragmentContainer containerToFinish) {
415 if (mIsFinished) {
416 return;
417 }
418 mContainersToFinishOnExit.add(containerToFinish);
419 }
420
421 /**
422 * Removes a container that should be finished when this container is finished.
423 */
424 void removeContainerToFinishOnExit(@NonNull TaskFragmentContainer containerToRemove) {
425 if (mIsFinished) {
426 return;
427 }
428 mContainersToFinishOnExit.remove(containerToRemove);
429 }
430
431 /**
432 * Adds an activity that should be finished when this container is finished.
433 */
434 void addActivityToFinishOnExit(@NonNull Activity activityToFinish) {
435 if (mIsFinished) {
436 return;
437 }
438 mActivitiesToFinishOnExit.add(activityToFinish.getActivityToken());
439 }
440
441 /**
442 * Removes an activity that should be finished when this container is finished.
443 */
444 void removeActivityToFinishOnExit(@NonNull Activity activityToRemove) {
445 if (mIsFinished) {
446 return;
447 }
448 mActivitiesToFinishOnExit.remove(activityToRemove.getActivityToken());
449 }
450
451 /** Removes all dependencies that should be finished when this container is finished. */
452 void resetDependencies() {
453 if (mIsFinished) {
454 return;
455 }
456 mContainersToFinishOnExit.clear();
457 mActivitiesToFinishOnExit.clear();
458 }
459
460 /**
461 * Removes all activities that belong to this process and finishes other containers/activities
462 * configured to finish together.
463 */
464 @GuardedBy("mController.mLock")
465 void finish(boolean shouldFinishDependent, @NonNull SplitPresenter presenter,
466 @NonNull WindowContainerTransaction wct, @NonNull SplitController controller) {
467 if (!mIsFinished) {
468 mIsFinished = true;
469 if (mAppearEmptyTimeout != null) {
470 mController.getHandler().removeCallbacks(mAppearEmptyTimeout);
471 mAppearEmptyTimeout = null;
472 }
473 finishActivities(shouldFinishDependent, presenter, wct, controller);
474 }
475
476 if (mInfo == null) {
477 // Defer removal the container and wait until TaskFragment appeared.
478 return;
479 }
480
481 // Cleanup the visuals
482 presenter.deleteTaskFragment(wct, getTaskFragmentToken());
483 // Cleanup the records
484 controller.removeContainer(this);
485 // Clean up task fragment information
486 mInfo = null;
487 }
488
489 @GuardedBy("mController.mLock")
490 private void finishActivities(boolean shouldFinishDependent, @NonNull SplitPresenter presenter,
491 @NonNull WindowContainerTransaction wct, @NonNull SplitController controller) {
492 // Finish own activities
493 for (Activity activity : collectNonFinishingActivities()) {
494 if (!activity.isFinishing()
495 // In case we have requested to reparent the activity to another container (as
496 // pendingAppeared), we don't want to finish it with this container.
497 && mController.getContainerWithActivity(activity) == this) {
498 wct.finishActivity(activity.getActivityToken());
499 }
500 }
501
502 if (!shouldFinishDependent) {
503 return;
504 }
505
506 // Finish dependent containers
507 for (TaskFragmentContainer container : mContainersToFinishOnExit) {
508 if (container.mIsFinished
509 || controller.shouldRetainAssociatedContainer(this, container)) {
510 continue;
511 }
512 container.finish(true /* shouldFinishDependent */, presenter,
513 wct, controller);
514 }
515 mContainersToFinishOnExit.clear();
516
517 // Finish associated activities
518 for (IBinder activityToken : mActivitiesToFinishOnExit) {
519 final Activity activity = mController.getActivity(activityToken);
520 if (activity == null || activity.isFinishing()
521 || controller.shouldRetainAssociatedActivity(this, activity)) {
522 continue;
523 }
524 wct.finishActivity(activity.getActivityToken());
525 }
526 mActivitiesToFinishOnExit.clear();
527 }
528
529 boolean isFinished() {
530 return mIsFinished;
531 }
532
533 /**
534 * Checks if last requested bounds are equal to the provided value.
535 */
536 boolean areLastRequestedBoundsEqual(@Nullable Rect bounds) {
537 return (bounds == null && mLastRequestedBounds.isEmpty())
538 || mLastRequestedBounds.equals(bounds);
539 }
540
541 /**
542 * Updates the last requested bounds.
543 */
544 void setLastRequestedBounds(@Nullable Rect bounds) {
545 if (bounds == null) {
546 mLastRequestedBounds.setEmpty();
547 } else {
548 mLastRequestedBounds.set(bounds);
549 }
550 }
551
552 @NonNull
553 Rect getLastRequestedBounds() {
554 return mLastRequestedBounds;
555 }
556
557 /**
558 * Checks if last requested windowing mode is equal to the provided value.
559 */
560 boolean isLastRequestedWindowingModeEqual(@WindowingMode int windowingMode) {
561 return mLastRequestedWindowingMode == windowingMode;
562 }
563
564 /**
565 * Updates the last requested windowing mode.
566 */
567 void setLastRequestedWindowingMode(@WindowingMode int windowingModes) {
568 mLastRequestedWindowingMode = windowingModes;
569 }
570
571 /**
572 * Checks if last requested {@link TaskFragmentAnimationParams} are equal to the provided value.
573 */
574 boolean areLastRequestedAnimationParamsEqual(
575 @NonNull TaskFragmentAnimationParams animationParams) {
576 return mLastAnimationParams.equals(animationParams);
577 }
578
579 /**
580 * Updates the last requested {@link TaskFragmentAnimationParams}.
581 */
582 void setLastRequestAnimationParams(@NonNull TaskFragmentAnimationParams animationParams) {
583 mLastAnimationParams = animationParams;
584 }
585
586 /** Gets the parent leaf Task id. */
587 int getTaskId() {
588 return mTaskContainer.getTaskId();
589 }
590
591 /** Gets the parent Task. */
592 @NonNull
593 TaskContainer getTaskContainer() {
594 return mTaskContainer;
595 }
596
597 @Nullable
598 Size getMinDimensions() {
599 if (mInfo == null) {
600 return null;
601 }
602 int maxMinWidth = mInfo.getMinimumWidth();
603 int maxMinHeight = mInfo.getMinimumHeight();
604 for (IBinder activityToken : mPendingAppearedActivities) {
605 final Activity activity = mController.getActivity(activityToken);
606 final Size minDimensions = SplitPresenter.getMinDimensions(activity);
607 if (minDimensions == null) {
608 continue;
609 }
610 maxMinWidth = Math.max(maxMinWidth, minDimensions.getWidth());
611 maxMinHeight = Math.max(maxMinHeight, minDimensions.getHeight());
612 }
613 if (mPendingAppearedIntent != null) {
614 final Size minDimensions = SplitPresenter.getMinDimensions(mPendingAppearedIntent);
615 if (minDimensions != null) {
616 maxMinWidth = Math.max(maxMinWidth, minDimensions.getWidth());
617 maxMinHeight = Math.max(maxMinHeight, minDimensions.getHeight());
618 }
619 }
620 return new Size(maxMinWidth, maxMinHeight);
621 }
622
623 /** Whether the current TaskFragment is above the {@code other} TaskFragment. */
624 boolean isAbove(@NonNull TaskFragmentContainer other) {
625 if (mTaskContainer != other.mTaskContainer) {
626 throw new IllegalArgumentException(
627 "Trying to compare two TaskFragments in different Task.");
628 }
629 if (this == other) {
630 throw new IllegalArgumentException("Trying to compare a TaskFragment with itself.");
631 }
632 return mTaskContainer.indexOf(this) > mTaskContainer.indexOf(other);
633 }
634
635 @Override
636 public String toString() {
637 return toString(true /* includeContainersToFinishOnExit */);
638 }
639
640 /**
641 * @return string for this TaskFragmentContainer and includes containers to finish on exit
642 * based on {@code includeContainersToFinishOnExit}. If containers to finish on exit are always
643 * included in the string, then calling {@link #toString()} on a container that mutually
644 * finishes with another container would cause a stack overflow.
645 */
646 private String toString(boolean includeContainersToFinishOnExit) {
647 return "TaskFragmentContainer{"
648 + " parentTaskId=" + getTaskId()
649 + " token=" + mToken
650 + " topNonFinishingActivity=" + getTopNonFinishingActivity()
651 + " runningActivityCount=" + getRunningActivityCount()
652 + " isFinished=" + mIsFinished
653 + " lastRequestedBounds=" + mLastRequestedBounds
654 + " pendingAppearedActivities=" + mPendingAppearedActivities
655 + (includeContainersToFinishOnExit ? " containersToFinishOnExit="
656 + containersToFinishOnExitToString() : "")
657 + " activitiesToFinishOnExit=" + mActivitiesToFinishOnExit
658 + " info=" + mInfo
659 + "}";
660 }
661
662 private String containersToFinishOnExitToString() {
663 StringBuilder sb = new StringBuilder("[");
664 Iterator<TaskFragmentContainer> containerIterator = mContainersToFinishOnExit.iterator();
665 while (containerIterator.hasNext()) {
666 sb.append(containerIterator.next().toString(
667 false /* includeContainersToFinishOnExit */));
668 if (containerIterator.hasNext()) {
669 sb.append(", ");
670 }
671 }
672 return sb.append("]").toString();
673 }
674 }