Debian Codegraph @

libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.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.ActivityManager.START_SUCCESS;
20 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
21 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
22 import static android.view.Display.DEFAULT_DISPLAY;
23 import static android.view.WindowManager.TRANSIT_CLOSE;
24 import static android.view.WindowManager.TRANSIT_OPEN;
25 import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_OP_TYPE;
26 import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_TASK_FRAGMENT_INFO;
27 import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_THROWABLE;
28 import static android.window.TaskFragmentTransaction.TYPE_ACTIVITY_REPARENTED_TO_TASK;
29 import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_APPEARED;
30 import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_ERROR;
31 import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_INFO_CHANGED;
32 import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_PARENT_INFO_CHANGED;
33 import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_VANISHED;
34 import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_REPARENT_ACTIVITY_TO_TASK_FRAGMENT;
35 import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_START_ACTIVITY_IN_TASK_FRAGMENT;
36
37 import static androidx.window.extensions.embedding.SplitContainer.getFinishPrimaryWithSecondaryBehavior;
38 import static androidx.window.extensions.embedding.SplitContainer.getFinishSecondaryWithPrimaryBehavior;
39 import static androidx.window.extensions.embedding.SplitContainer.isStickyPlaceholderRule;
40 import static androidx.window.extensions.embedding.SplitContainer.shouldFinishAssociatedContainerWhenAdjacent;
41 import static androidx.window.extensions.embedding.SplitContainer.shouldFinishAssociatedContainerWhenStacked;
42 import static androidx.window.extensions.embedding.SplitPresenter.RESULT_EXPAND_FAILED_NO_TF_INFO;
43 import static androidx.window.extensions.embedding.SplitPresenter.getActivityIntentMinDimensionsPair;
44 import static androidx.window.extensions.embedding.SplitPresenter.shouldShowSplit;
45
46 import android.app.Activity;
47 import android.app.ActivityClient;
48 import android.app.ActivityOptions;
49 import android.app.ActivityThread;
50 import android.app.Application;
51 import android.app.Instrumentation;
52 import android.content.ComponentName;
53 import android.content.Context;
54 import android.content.Intent;
55 import android.content.res.Configuration;
56 import android.graphics.Rect;
57 import android.os.Bundle;
58 import android.os.Handler;
59 import android.os.IBinder;
60 import android.os.Looper;
61 import android.os.SystemProperties;
62 import android.util.ArraySet;
63 import android.util.Log;
64 import android.util.Pair;
65 import android.util.Size;
66 import android.util.SparseArray;
67 import android.view.WindowMetrics;
68 import android.window.TaskFragmentAnimationParams;
69 import android.window.TaskFragmentInfo;
70 import android.window.TaskFragmentParentInfo;
71 import android.window.TaskFragmentTransaction;
72 import android.window.WindowContainerTransaction;
73
74 import androidx.annotation.GuardedBy;
75 import androidx.annotation.NonNull;
76 import androidx.annotation.Nullable;
77 import androidx.window.common.CommonFoldingFeature;
78 import androidx.window.common.DeviceStateManagerFoldingFeatureProducer;
79 import androidx.window.common.EmptyLifecycleCallbacksAdapter;
80 import androidx.window.extensions.embedding.TransactionManager.TransactionRecord;
81 import androidx.window.extensions.layout.WindowLayoutComponentImpl;
82
83 import com.android.internal.annotations.VisibleForTesting;
84
85 import java.util.ArrayList;
86 import java.util.List;
87 import java.util.Objects;
88 import java.util.Set;
89 import java.util.concurrent.Executor;
90 import java.util.function.Consumer;
91
92 /**
93 * Main controller class that manages split states and presentation.
94 */
95 public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmentCallback,
96 ActivityEmbeddingComponent {
97 static final String TAG = "SplitController";
98 static final boolean ENABLE_SHELL_TRANSITIONS =
99 SystemProperties.getBoolean("persist.wm.debug.shell_transit", false);
100
101 @VisibleForTesting
102 @GuardedBy("mLock")
103 final SplitPresenter mPresenter;
104
105 @VisibleForTesting
106 @GuardedBy("mLock")
107 final TransactionManager mTransactionManager;
108
109 // Currently applied split configuration.
110 @GuardedBy("mLock")
111 private final List<EmbeddingRule> mSplitRules = new ArrayList<>();
112
113 /**
114 * A developer-defined {@link SplitAttributes} calculator to compute the current
115 * {@link SplitAttributes} with the current device and window states.
116 * It is registered via {@link #setSplitAttributesCalculator(SplitAttributesCalculator)}
117 * and unregistered via {@link #clearSplitAttributesCalculator()}.
118 * This is called when:
119 * <ul>
120 * <li>{@link SplitPresenter#updateSplitContainer(SplitContainer, TaskFragmentContainer,
121 * WindowContainerTransaction)}</li>
122 * <li>There's a started Activity which matches {@link SplitPairRule} </li>
123 * <li>Checking whether the place holder should be launched if there's a Activity matches
124 * {@link SplitPlaceholderRule} </li>
125 * </ul>
126 */
127 @GuardedBy("mLock")
128 @Nullable
129 private SplitAttributesCalculator mSplitAttributesCalculator;
130
131 /**
132 * Map from Task id to {@link TaskContainer} which contains all TaskFragment and split pair info
133 * below it.
134 * When the app is host of multiple Tasks, there can be multiple splits controlled by the same
135 * organizer.
136 */
137 @VisibleForTesting
138 @GuardedBy("mLock")
139 final SparseArray<TaskContainer> mTaskContainers = new SparseArray<>();
140
141 /** Callback to Jetpack to notify about changes to split states. */
142 @Nullable
143 private Consumer<List<SplitInfo>> mEmbeddingCallback;
144 private final List<SplitInfo> mLastReportedSplitStates = new ArrayList<>();
145 private final Handler mHandler;
146 final Object mLock = new Object();
147 private final ActivityStartMonitor mActivityStartMonitor;
148
149 public SplitController(@NonNull WindowLayoutComponentImpl windowLayoutComponent,
150 @NonNull DeviceStateManagerFoldingFeatureProducer foldingFeatureProducer) {
151 final MainThreadExecutor executor = new MainThreadExecutor();
152 mHandler = executor.mHandler;
153 mPresenter = new SplitPresenter(executor, windowLayoutComponent, this);
154 mTransactionManager = new TransactionManager(mPresenter);
155 final ActivityThread activityThread = ActivityThread.currentActivityThread();
156 final Application application = activityThread.getApplication();
157 // Register a callback to be notified about activities being created.
158 application.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
159 // Intercept activity starts to route activities to new containers if necessary.
160 Instrumentation instrumentation = activityThread.getInstrumentation();
161
162 mActivityStartMonitor = new ActivityStartMonitor();
163 instrumentation.addMonitor(mActivityStartMonitor);
164 foldingFeatureProducer.addDataChangedCallback(new FoldingFeatureListener());
165 }
166
167 private class FoldingFeatureListener implements Consumer<List<CommonFoldingFeature>> {
168 @Override
169 public void accept(List<CommonFoldingFeature> foldingFeatures) {
170 synchronized (mLock) {
171 final TransactionRecord transactionRecord = mTransactionManager
172 .startNewTransaction();
173 final WindowContainerTransaction wct = transactionRecord.getTransaction();
174 for (int i = 0; i < mTaskContainers.size(); i++) {
175 final TaskContainer taskContainer = mTaskContainers.valueAt(i);
176 if (!taskContainer.isVisible()) {
177 continue;
178 }
179 if (taskContainer.getDisplayId() != DEFAULT_DISPLAY) {
180 continue;
181 }
182 // TODO(b/238948678): Support reporting display features in all windowing modes.
183 if (taskContainer.isInMultiWindow()) {
184 continue;
185 }
186 if (taskContainer.isEmpty()) {
187 continue;
188 }
189 updateContainersInTask(wct, taskContainer);
190 }
191 // The WCT should be applied and merged to the device state change transition if
192 // there is one.
193 transactionRecord.apply(false /* shouldApplyIndependently */);
194 }
195 }
196 }
197
198 /** Updates the embedding rules applied to future activity launches. */
199 @Override
200 public void setEmbeddingRules(@NonNull Set<EmbeddingRule> rules) {
201 synchronized (mLock) {
202 mSplitRules.clear();
203 mSplitRules.addAll(rules);
204 }
205 }
206
207 @Override
208 public void setSplitAttributesCalculator(@NonNull SplitAttributesCalculator calculator) {
209 synchronized (mLock) {
210 mSplitAttributesCalculator = calculator;
211 }
212 }
213
214 @Override
215 public void clearSplitAttributesCalculator() {
216 synchronized (mLock) {
217 mSplitAttributesCalculator = null;
218 }
219 }
220
221 @GuardedBy("mLock")
222 @Nullable
223 SplitAttributesCalculator getSplitAttributesCalculator() {
224 return mSplitAttributesCalculator;
225 }
226
227 @NonNull
228 @GuardedBy("mLock")
229 @VisibleForTesting
230 List<EmbeddingRule> getSplitRules() {
231 return mSplitRules;
232 }
233
234 /**
235 * Registers the split organizer callback to notify about changes to active splits.
236 */
237 @Override
238 public void setSplitInfoCallback(@NonNull Consumer<List<SplitInfo>> callback) {
239 synchronized (mLock) {
240 mEmbeddingCallback = callback;
241 updateCallbackIfNecessary();
242 }
243 }
244
245 /**
246 * Clears the listener set in {@link SplitController#setSplitInfoCallback(Consumer)}.
247 */
248 @Override
249 public void clearSplitInfoCallback() {
250 synchronized (mLock) {
251 mEmbeddingCallback = null;
252 }
253 }
254
255 /**
256 * Called when the transaction is ready so that the organizer can update the TaskFragments based
257 * on the changes in transaction.
258 */
259 @Override
260 public void onTransactionReady(@NonNull TaskFragmentTransaction transaction) {
261 synchronized (mLock) {
262 final TransactionRecord transactionRecord = mTransactionManager.startNewTransaction(
263 transaction.getTransactionToken());
264 final WindowContainerTransaction wct = transactionRecord.getTransaction();
265 final List<TaskFragmentTransaction.Change> changes = transaction.getChanges();
266 for (TaskFragmentTransaction.Change change : changes) {
267 final int taskId = change.getTaskId();
268 final TaskFragmentInfo info = change.getTaskFragmentInfo();
269 switch (change.getType()) {
270 case TYPE_TASK_FRAGMENT_APPEARED:
271 mPresenter.updateTaskFragmentInfo(info);
272 onTaskFragmentAppeared(wct, info);
273 break;
274 case TYPE_TASK_FRAGMENT_INFO_CHANGED:
275 mPresenter.updateTaskFragmentInfo(info);
276 onTaskFragmentInfoChanged(wct, info);
277 break;
278 case TYPE_TASK_FRAGMENT_VANISHED:
279 mPresenter.removeTaskFragmentInfo(info);
280 onTaskFragmentVanished(wct, info);
281 break;
282 case TYPE_TASK_FRAGMENT_PARENT_INFO_CHANGED:
283 onTaskFragmentParentInfoChanged(wct, taskId,
284 change.getTaskFragmentParentInfo());
285 break;
286 case TYPE_TASK_FRAGMENT_ERROR:
287 final Bundle errorBundle = change.getErrorBundle();
288 final IBinder errorToken = change.getErrorCallbackToken();
289 final TaskFragmentInfo errorTaskFragmentInfo = errorBundle.getParcelable(
290 KEY_ERROR_CALLBACK_TASK_FRAGMENT_INFO, TaskFragmentInfo.class);
291 final int opType = errorBundle.getInt(KEY_ERROR_CALLBACK_OP_TYPE);
292 final Throwable exception = errorBundle.getSerializable(
293 KEY_ERROR_CALLBACK_THROWABLE, Throwable.class);
294 if (errorTaskFragmentInfo != null) {
295 mPresenter.updateTaskFragmentInfo(errorTaskFragmentInfo);
296 }
297 onTaskFragmentError(wct, errorToken, errorTaskFragmentInfo, opType,
298 exception);
299 break;
300 case TYPE_ACTIVITY_REPARENTED_TO_TASK:
301 onActivityReparentedToTask(
302 wct,
303 taskId,
304 change.getActivityIntent(),
305 change.getActivityToken());
306 break;
307 default:
308 throw new IllegalArgumentException(
309 "Unknown TaskFragmentEvent=" + change.getType());
310 }
311 }
312
313 // Notify the server, and the server should apply and merge the
314 // WindowContainerTransaction to the active sync to finish the TaskFragmentTransaction.
315 transactionRecord.apply(false /* shouldApplyIndependently */);
316 updateCallbackIfNecessary();
317 }
318 }
319
320 /**
321 * Called when a TaskFragment is created and organized by this organizer.
322 *
323 * @param wct The {@link WindowContainerTransaction} to make any changes with if needed.
324 * @param taskFragmentInfo Info of the TaskFragment that is created.
325 */
326 // Suppress GuardedBy warning because lint ask to mark this method as
327 // @GuardedBy(container.mController.mLock), which is mLock itself
328 @SuppressWarnings("GuardedBy")
329 @VisibleForTesting
330 @GuardedBy("mLock")
331 void onTaskFragmentAppeared(@NonNull WindowContainerTransaction wct,
332 @NonNull TaskFragmentInfo taskFragmentInfo) {
333 final TaskFragmentContainer container = getContainer(taskFragmentInfo.getFragmentToken());
334 if (container == null) {
335 return;
336 }
337
338 container.setInfo(wct, taskFragmentInfo);
339 if (container.isFinished()) {
340 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE);
341 mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */);
342 } else {
343 // Update with the latest Task configuration.
344 updateContainer(wct, container);
345 }
346 }
347
348 /**
349 * Called when the status of an organized TaskFragment is changed.
350 *
351 * @param wct The {@link WindowContainerTransaction} to make any changes with if needed.
352 * @param taskFragmentInfo Info of the TaskFragment that is changed.
353 */
354 // Suppress GuardedBy warning because lint ask to mark this method as
355 // @GuardedBy(container.mController.mLock), which is mLock itself
356 @SuppressWarnings("GuardedBy")
357 @VisibleForTesting
358 @GuardedBy("mLock")
359 void onTaskFragmentInfoChanged(@NonNull WindowContainerTransaction wct,
360 @NonNull TaskFragmentInfo taskFragmentInfo) {
361 final TaskFragmentContainer container = getContainer(taskFragmentInfo.getFragmentToken());
362 if (container == null) {
363 return;
364 }
365
366 final boolean wasInPip = isInPictureInPicture(container);
367 container.setInfo(wct, taskFragmentInfo);
368 final boolean isInPip = isInPictureInPicture(container);
369 // Check if there are no running activities - consider the container empty if there are
370 // no non-finishing activities left.
371 if (!taskFragmentInfo.hasRunningActivity()) {
372 if (taskFragmentInfo.isTaskFragmentClearedForPip()) {
373 // Do not finish the dependents if the last activity is reparented to PiP.
374 // Instead, the original split should be cleanup, and the dependent may be
375 // expanded to fullscreen.
376 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE);
377 cleanupForEnterPip(wct, container);
378 mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */);
379 } else if (taskFragmentInfo.isTaskClearedForReuse()) {
380 // Do not finish the dependents if this TaskFragment was cleared due to
381 // launching activity in the Task.
382 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE);
383 mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */);
384 } else if (taskFragmentInfo.isClearedForReorderActivityToFront()) {
385 // Do not finish the dependents if this TaskFragment was cleared to reorder
386 // the launching Activity to front of the Task.
387 mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */);
388 } else if (!container.isWaitingActivityAppear()) {
389 // Do not finish the container before the expected activity appear until
390 // timeout.
391 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE);
392 mPresenter.cleanupContainer(wct, container, true /* shouldFinishDependent */);
393 }
394 } else if (wasInPip && isInPip) {
395 // No update until exit PIP.
396 return;
397 } else if (isInPip) {
398 // Enter PIP.
399 // All overrides will be cleanup.
400 container.setLastRequestedBounds(null /* bounds */);
401 container.setLastRequestedWindowingMode(WINDOWING_MODE_UNDEFINED);
402 cleanupForEnterPip(wct, container);
403 } else if (wasInPip) {
404 // Exit PIP.
405 // Updates the presentation of the container. Expand or launch placeholder if
406 // needed.
407 updateContainer(wct, container);
408 }
409 }
410
411 /**
412 * Called when an organized TaskFragment is removed.
413 *
414 * @param wct The {@link WindowContainerTransaction} to make any changes with if needed.
415 * @param taskFragmentInfo Info of the TaskFragment that is removed.
416 */
417 @VisibleForTesting
418 @GuardedBy("mLock")
419 void onTaskFragmentVanished(@NonNull WindowContainerTransaction wct,
420 @NonNull TaskFragmentInfo taskFragmentInfo) {
421 final TaskFragmentContainer container = getContainer(taskFragmentInfo.getFragmentToken());
422 if (container != null) {
423 // Cleanup if the TaskFragment vanished is not requested by the organizer.
424 removeContainer(container);
425 // Make sure the containers in the Task are up-to-date.
426 updateContainersInTaskIfVisible(wct, container.getTaskId());
427 }
428 cleanupTaskFragment(taskFragmentInfo.getFragmentToken());
429 }
430
431 /**
432 * Called when the parent leaf Task of organized TaskFragments is changed.
433 * When the leaf Task is changed, the organizer may want to update the TaskFragments in one
434 * transaction.
435 *
436 * For case like screen size change, it will trigger {@link #onTaskFragmentParentInfoChanged}
437 * with new Task bounds, but may not trigger {@link #onTaskFragmentInfoChanged} because there
438 * can be an override bounds.
439 *
440 * @param wct The {@link WindowContainerTransaction} to make any changes with if needed.
441 * @param taskId Id of the parent Task that is changed.
442 * @param parentInfo {@link TaskFragmentParentInfo} of the parent Task.
443 */
444 @VisibleForTesting
445 @GuardedBy("mLock")
446 void onTaskFragmentParentInfoChanged(@NonNull WindowContainerTransaction wct,
447 int taskId, @NonNull TaskFragmentParentInfo parentInfo) {
448 final TaskContainer taskContainer = getTaskContainer(taskId);
449 if (taskContainer == null || taskContainer.isEmpty()) {
450 Log.e(TAG, "onTaskFragmentParentInfoChanged on empty Task id=" + taskId);
451 return;
452 }
453 taskContainer.updateTaskFragmentParentInfo(parentInfo);
454 if (!taskContainer.isVisible()) {
455 // Don't update containers if the task is not visible. We only update containers when
456 // parentInfo#isVisibleRequested is true.
457 return;
458 }
459 if (isInPictureInPicture(parentInfo.getConfiguration())) {
460 // No need to update presentation in PIP until the Task exit PIP.
461 return;
462 }
463 updateContainersInTask(wct, taskContainer);
464 }
465
466 @GuardedBy("mLock")
467 void updateContainersInTaskIfVisible(@NonNull WindowContainerTransaction wct, int taskId) {
468 final TaskContainer taskContainer = getTaskContainer(taskId);
469 if (taskContainer != null && taskContainer.isVisible()) {
470 updateContainersInTask(wct, taskContainer);
471 }
472 }
473
474 @GuardedBy("mLock")
475 private void updateContainersInTask(@NonNull WindowContainerTransaction wct,
476 @NonNull TaskContainer taskContainer) {
477 // Update all TaskFragments in the Task. Make a copy of the list since some may be
478 // removed on updating.
479 final List<TaskFragmentContainer> containers =
480 new ArrayList<>(taskContainer.mContainers);
481 for (int i = containers.size() - 1; i >= 0; i--) {
482 final TaskFragmentContainer container = containers.get(i);
483 // Wait until onTaskFragmentAppeared to update new container.
484 if (!container.isFinished() && !container.isWaitingActivityAppear()) {
485 updateContainer(wct, container);
486 }
487 }
488 }
489
490 /**
491 * Called when an Activity is reparented to the Task with organized TaskFragment. For example,
492 * when an Activity enters and then exits Picture-in-picture, it will be reparented back to its
493 * original Task. In this case, we need to notify the organizer so that it can check if the
494 * Activity matches any split rule.
495 *
496 * @param wct The {@link WindowContainerTransaction} to make any changes with if needed.
497 * @param taskId The Task that the activity is reparented to.
498 * @param activityIntent The intent that the activity is original launched with.
499 * @param activityToken If the activity belongs to the same process as the organizer, this
500 * will be the actual activity token; if the activity belongs to a
501 * different process, the server will generate a temporary token that
502 * the organizer can use to reparent the activity through
503 * {@link WindowContainerTransaction} if needed.
504 */
505 @VisibleForTesting
506 @GuardedBy("mLock")
507 void onActivityReparentedToTask(@NonNull WindowContainerTransaction wct,
508 int taskId, @NonNull Intent activityIntent,
509 @NonNull IBinder activityToken) {
510 // If the activity belongs to the current app process, we treat it as a new activity
511 // launch.
512 final Activity activity = getActivity(activityToken);
513 if (activity != null) {
514 // We don't allow split as primary for new launch because we currently only support
515 // launching to top. We allow split as primary for activity reparent because the
516 // activity may be split as primary before it is reparented out. In that case, we
517 // want to show it as primary again when it is reparented back.
518 if (!resolveActivityToContainer(wct, activity, true /* isOnReparent */)) {
519 // When there is no embedding rule matched, try to place it in the top container
520 // like a normal launch.
521 placeActivityInTopContainer(wct, activity);
522 }
523 return;
524 }
525
526 final TaskContainer taskContainer = getTaskContainer(taskId);
527 if (taskContainer == null || taskContainer.isInPictureInPicture()) {
528 // We don't embed activity when it is in PIP.
529 return;
530 }
531
532 // If the activity belongs to a different app process, we treat it as starting new
533 // intent, since both actions might result in a new activity that should appear in an
534 // organized TaskFragment.
535 TaskFragmentContainer targetContainer = resolveStartActivityIntent(wct, taskId,
536 activityIntent, null /* launchingActivity */);
537 if (targetContainer == null) {
538 // When there is no embedding rule matched, try to place it in the top container
539 // like a normal launch.
540 targetContainer = taskContainer.getTopTaskFragmentContainer();
541 }
542 if (targetContainer == null) {
543 return;
544 }
545 wct.reparentActivityToTaskFragment(targetContainer.getTaskFragmentToken(),
546 activityToken);
547 // Because the activity does not belong to the organizer process, we wait until
548 // onTaskFragmentAppeared to trigger updateCallbackIfNecessary().
549 }
550
551 /**
552 * Called when the {@link WindowContainerTransaction} created with
553 * {@link WindowContainerTransaction#setErrorCallbackToken(IBinder)} failed on the server side.
554 *
555 * @param wct The {@link WindowContainerTransaction} to make any changes with if needed.
556 * @param errorCallbackToken token set in
557 * {@link WindowContainerTransaction#setErrorCallbackToken(IBinder)}
558 * @param taskFragmentInfo The {@link TaskFragmentInfo}. This could be {@code null} if no
559 * TaskFragment created.
560 * @param opType The {@link WindowContainerTransaction.HierarchyOp} of the failed
561 * transaction operation.
562 * @param exception exception from the server side.
563 */
564 // Suppress GuardedBy warning because lint ask to mark this method as
565 // @GuardedBy(container.mController.mLock), which is mLock itself
566 @SuppressWarnings("GuardedBy")
567 @VisibleForTesting
568 @GuardedBy("mLock")
569 void onTaskFragmentError(@NonNull WindowContainerTransaction wct,
570 @Nullable IBinder errorCallbackToken, @Nullable TaskFragmentInfo taskFragmentInfo,
571 int opType, @NonNull Throwable exception) {
572 Log.e(TAG, "onTaskFragmentError=" + exception.getMessage());
573 switch (opType) {
574 case HIERARCHY_OP_TYPE_START_ACTIVITY_IN_TASK_FRAGMENT:
575 case HIERARCHY_OP_TYPE_REPARENT_ACTIVITY_TO_TASK_FRAGMENT: {
576 final TaskFragmentContainer container;
577 if (taskFragmentInfo != null) {
578 container = getContainer(taskFragmentInfo.getFragmentToken());
579 } else {
580 container = null;
581 }
582 if (container == null) {
583 break;
584 }
585
586 // Update the latest taskFragmentInfo and perform necessary clean-up
587 container.setInfo(wct, taskFragmentInfo);
588 container.clearPendingAppearedActivities();
589 if (container.isEmpty()) {
590 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE);
591 mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */);
592 }
593 break;
594 }
595 default:
596 Log.e(TAG, "onTaskFragmentError: taskFragmentInfo = " + taskFragmentInfo
597 + ", opType = " + opType);
598 }
599 }
600
601 /** Called on receiving {@link #onTaskFragmentVanished} for cleanup. */
602 @GuardedBy("mLock")
603 private void cleanupTaskFragment(@NonNull IBinder taskFragmentToken) {
604 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
605 final TaskContainer taskContainer = mTaskContainers.valueAt(i);
606 if (!taskContainer.mFinishedContainer.remove(taskFragmentToken)) {
607 continue;
608 }
609 if (taskContainer.isEmpty()) {
610 // Cleanup the TaskContainer if it becomes empty.
611 mTaskContainers.remove(taskContainer.getTaskId());
612 }
613 return;
614 }
615 }
616
617 /** Returns whether the given {@link TaskContainer} may show in split. */
618 // Suppress GuardedBy warning because lint asks to mark this method as
619 // @GuardedBy(mPresenter.mController.mLock), which is mLock itself
620 @SuppressWarnings("GuardedBy")
621 @GuardedBy("mLock")
622 private boolean mayShowSplit(@NonNull TaskContainer taskContainer) {
623 // No split inside PIP.
624 if (taskContainer.isInPictureInPicture()) {
625 return false;
626 }
627 // Always assume the TaskContainer if SplitAttributesCalculator is set
628 if (mSplitAttributesCalculator != null) {
629 return true;
630 }
631 // Check if the parent container bounds can support any split rule.
632 for (EmbeddingRule rule : mSplitRules) {
633 if (!(rule instanceof SplitRule)) {
634 continue;
635 }
636 final SplitRule splitRule = (SplitRule) rule;
637 final SplitAttributes splitAttributes = mPresenter.computeSplitAttributes(
638 taskContainer.getTaskProperties(), splitRule, null /* minDimensionsPair */);
639 if (shouldShowSplit(splitAttributes)) {
640 return true;
641 }
642 }
643 return false;
644 }
645
646 @VisibleForTesting
647 @GuardedBy("mLock")
648 void onActivityCreated(@NonNull WindowContainerTransaction wct,
649 @NonNull Activity launchedActivity) {
650 // TODO(b/229680885): we don't support launching into primary yet because we want to always
651 // launch the new activity on top.
652 resolveActivityToContainer(wct, launchedActivity, false /* isOnReparent */);
653 updateCallbackIfNecessary();
654 }
655
656 /**
657 * Checks if the new added activity should be routed to a particular container. It can create a
658 * new container for the activity and a new split container if necessary.
659 * @param activity the activity that is newly added to the Task.
660 * @param isOnReparent whether the activity is reparented to the Task instead of new launched.
661 * We only support to split as primary for reparented activity for now.
662 * @return {@code true} if the activity has been handled, such as placed in a TaskFragment, or
663 * in a state that the caller shouldn't handle.
664 */
665 @VisibleForTesting
666 @GuardedBy("mLock")
667 boolean resolveActivityToContainer(@NonNull WindowContainerTransaction wct,
668 @NonNull Activity activity, boolean isOnReparent) {
669 if (isInPictureInPicture(activity) || activity.isFinishing()) {
670 // We don't embed activity when it is in PIP, or finishing. Return true since we don't
671 // want any extra handling.
672 return true;
673 }
674
675 if (!isOnReparent && getContainerWithActivity(activity) == null
676 && getTaskFragmentTokenFromActivityClientRecord(activity) != null) {
677 // We can't find the new launched activity in any recorded container, but it is
678 // currently placed in an embedded TaskFragment. This can happen in two cases:
679 // 1. the activity is embedded in another app.
680 // 2. the organizer has already requested to remove the TaskFragment.
681 // In either case, return true since we don't want any extra handling.
682 Log.d(TAG, "Activity is in a TaskFragment that is not recorded by the organizer. r="
683 + activity);
684 return true;
685 }
686
687 /*
688 * We will check the following to see if there is any embedding rule matched:
689 * 1. Whether the new launched activity should always expand.
690 * 2. Whether the new launched activity should launch a placeholder.
691 * 3. Whether the new launched activity has already been in a split with a rule matched
692 * (likely done in #onStartActivity).
693 * 4. Whether the activity below (if any) should be split with the new launched activity.
694 * 5. Whether the activity split with the activity below (if any) should be split with the
695 * new launched activity.
696 */
697
698 // 1. Whether the new launched activity should always expand.
699 if (shouldExpand(activity, null /* intent */)) {
700 expandActivity(wct, activity);
701 return true;
702 }
703
704 // 2. Whether the new launched activity should launch a placeholder.
705 if (launchPlaceholderIfNecessary(wct, activity, !isOnReparent)) {
706 return true;
707 }
708
709 // 3. Whether the new launched activity has already been in a split with a rule matched.
710 if (isNewActivityInSplitWithRuleMatched(activity)) {
711 return true;
712 }
713
714 // 4. Whether the activity below (if any) should be split with the new launched activity.
715 final Activity activityBelow = findActivityBelow(activity);
716 if (activityBelow == null) {
717 // Can't find any activity below.
718 return false;
719 }
720 if (putActivitiesIntoSplitIfNecessary(wct, activityBelow, activity)) {
721 // Have split rule of [ activityBelow | launchedActivity ].
722 return true;
723 }
724 if (isOnReparent && putActivitiesIntoSplitIfNecessary(wct, activity, activityBelow)) {
725 // Have split rule of [ launchedActivity | activityBelow].
726 return true;
727 }
728
729 // 5. Whether the activity split with the activity below (if any) should be split with the
730 // new launched activity.
731 final TaskFragmentContainer activityBelowContainer = getContainerWithActivity(
732 activityBelow);
733 final SplitContainer topSplit = getActiveSplitForContainer(activityBelowContainer);
734 if (topSplit == null || !isTopMostSplit(topSplit)) {
735 // Skip if it is not the topmost split.
736 return false;
737 }
738 final TaskFragmentContainer otherTopContainer =
739 topSplit.getPrimaryContainer() == activityBelowContainer
740 ? topSplit.getSecondaryContainer()
741 : topSplit.getPrimaryContainer();
742 final Activity otherTopActivity = otherTopContainer.getTopNonFinishingActivity();
743 if (otherTopActivity == null || otherTopActivity == activity) {
744 // Can't find the top activity on the other split TaskFragment.
745 return false;
746 }
747 if (putActivitiesIntoSplitIfNecessary(wct, otherTopActivity, activity)) {
748 // Have split rule of [ otherTopActivity | launchedActivity ].
749 return true;
750 }
751 // Have split rule of [ launchedActivity | otherTopActivity].
752 return isOnReparent && putActivitiesIntoSplitIfNecessary(wct, activity, otherTopActivity);
753 }
754
755 /**
756 * Places the given activity to the top most TaskFragment in the task if there is any.
757 */
758 @GuardedBy("mLock")
759 @VisibleForTesting
760 void placeActivityInTopContainer(@NonNull WindowContainerTransaction wct,
761 @NonNull Activity activity) {
762 if (getContainerWithActivity(activity) != null) {
763 // The activity has already been put in a TaskFragment. This is likely to be done by
764 // the server when the activity is started.
765 return;
766 }
767 final int taskId = getTaskId(activity);
768 final TaskContainer taskContainer = getTaskContainer(taskId);
769 if (taskContainer == null) {
770 return;
771 }
772 final TaskFragmentContainer targetContainer = taskContainer.getTopTaskFragmentContainer();
773 if (targetContainer == null) {
774 return;
775 }
776 targetContainer.addPendingAppearedActivity(activity);
777 wct.reparentActivityToTaskFragment(targetContainer.getTaskFragmentToken(),
778 activity.getActivityToken());
779 }
780
781 /**
782 * Starts an activity to side of the launchingActivity with the provided split config.
783 */
784 // Suppress GuardedBy warning because lint ask to mark this method as
785 // @GuardedBy(container.mController.mLock), which is mLock itself
786 @SuppressWarnings("GuardedBy")
787 @GuardedBy("mLock")
788 private void startActivityToSide(@NonNull WindowContainerTransaction wct,
789 @NonNull Activity launchingActivity, @NonNull Intent intent,
790 @Nullable Bundle options, @NonNull SplitRule sideRule,
791 @NonNull SplitAttributes splitAttributes, @Nullable Consumer<Exception> failureCallback,
792 boolean isPlaceholder) {
793 try {
794 mPresenter.startActivityToSide(wct, launchingActivity, intent, options, sideRule,
795 splitAttributes, isPlaceholder);
796 } catch (Exception e) {
797 if (failureCallback != null) {
798 failureCallback.accept(e);
799 }
800 }
801 }
802
803 /**
804 * Expands the given activity by either expanding the TaskFragment it is currently in or putting
805 * it into a new expanded TaskFragment.
806 */
807 @GuardedBy("mLock")
808 private void expandActivity(@NonNull WindowContainerTransaction wct,
809 @NonNull Activity activity) {
810 final TaskFragmentContainer container = getContainerWithActivity(activity);
811 if (shouldContainerBeExpanded(container)) {
812 // Make sure that the existing container is expanded.
813 mPresenter.expandTaskFragment(wct, container.getTaskFragmentToken());
814 } else {
815 // Put activity into a new expanded container.
816 final TaskFragmentContainer newContainer = newContainer(activity, getTaskId(activity));
817 mPresenter.expandActivity(wct, newContainer.getTaskFragmentToken(), activity);
818 }
819 }
820
821 /** Whether the given new launched activity is in a split with a rule matched. */
822 // Suppress GuardedBy warning because lint asks to mark this method as
823 // @GuardedBy(mPresenter.mController.mLock), which is mLock itself
824 @SuppressWarnings("GuardedBy")
825 @GuardedBy("mLock")
826 private boolean isNewActivityInSplitWithRuleMatched(@NonNull Activity launchedActivity) {
827 final TaskFragmentContainer container = getContainerWithActivity(launchedActivity);
828 final SplitContainer splitContainer = getActiveSplitForContainer(container);
829 if (splitContainer == null) {
830 return false;
831 }
832
833 if (container == splitContainer.getPrimaryContainer()) {
834 // The new launched can be in the primary container when it is starting a new activity
835 // onCreate.
836 final TaskFragmentContainer secondaryContainer = splitContainer.getSecondaryContainer();
837 final Intent secondaryIntent = secondaryContainer.getPendingAppearedIntent();
838 if (secondaryIntent != null) {
839 // Check with the pending Intent before it is started on the server side.
840 // This can happen if the launched Activity start a new Intent to secondary during
841 // #onCreated().
842 return getSplitRule(launchedActivity, secondaryIntent) != null;
843 }
844 final Activity secondaryActivity = secondaryContainer.getTopNonFinishingActivity();
845 return secondaryActivity != null
846 && getSplitRule(launchedActivity, secondaryActivity) != null;
847 }
848
849 // Check if the new launched activity is a placeholder.
850 if (splitContainer.getSplitRule() instanceof SplitPlaceholderRule) {
851 final SplitPlaceholderRule placeholderRule =
852 (SplitPlaceholderRule) splitContainer.getSplitRule();
853 final ComponentName placeholderName = placeholderRule.getPlaceholderIntent()
854 .getComponent();
855 // TODO(b/232330767): Do we have a better way to check this?
856 return placeholderName == null
857 || placeholderName.equals(launchedActivity.getComponentName())
858 || placeholderRule.getPlaceholderIntent().equals(launchedActivity.getIntent());
859 }
860
861 // Check if the new launched activity should be split with the primary top activity.
862 final Activity primaryActivity = splitContainer.getPrimaryContainer()
863 .getTopNonFinishingActivity();
864 if (primaryActivity == null) {
865 return false;
866 }
867 /* TODO(b/231845476) we should always respect clearTop.
868 final SplitPairRule curSplitRule = (SplitPairRule) splitContainer.getSplitRule();
869 final SplitPairRule splitRule = getSplitRule(primaryActivity, launchedActivity);
870 return splitRule != null && haveSamePresentation(splitRule, curSplitRule)
871 // If the new launched split rule should clear top and it is not the bottom most,
872 // it means we should create a new split pair and clear the existing secondary.
873 && (!splitRule.shouldClearTop()
874 || container.getBottomMostActivity() == launchedActivity);
875 */
876 return getSplitRule(primaryActivity, launchedActivity) != null;
877 }
878
879 /** Finds the activity below the given activity. */
880 @VisibleForTesting
881 @Nullable
882 @GuardedBy("mLock")
883 Activity findActivityBelow(@NonNull Activity activity) {
884 Activity activityBelow = null;
885 final TaskFragmentContainer container = getContainerWithActivity(activity);
886 if (container != null) {
887 final List<Activity> containerActivities = container.collectNonFinishingActivities();
888 final int index = containerActivities.indexOf(activity);
889 if (index > 0) {
890 activityBelow = containerActivities.get(index - 1);
891 }
892 }
893 if (activityBelow == null) {
894 final IBinder belowToken = ActivityClient.getInstance().getActivityTokenBelow(
895 activity.getActivityToken());
896 if (belowToken != null) {
897 activityBelow = getActivity(belowToken);
898 }
899 }
900 return activityBelow;
901 }
902
903 /**
904 * Checks if there is a rule to split the two activities. If there is one, puts them into split
905 * and returns {@code true}. Otherwise, returns {@code false}.
906 */
907 // Suppress GuardedBy warning because lint ask to mark this method as
908 // @GuardedBy(mPresenter.mController.mLock), which is mLock itself
909 @SuppressWarnings("GuardedBy")
910 @GuardedBy("mLock")
911 private boolean putActivitiesIntoSplitIfNecessary(@NonNull WindowContainerTransaction wct,
912 @NonNull Activity primaryActivity, @NonNull Activity secondaryActivity) {
913 final SplitPairRule splitRule = getSplitRule(primaryActivity, secondaryActivity);
914 if (splitRule == null) {
915 return false;
916 }
917 final TaskFragmentContainer primaryContainer = getContainerWithActivity(
918 primaryActivity);
919 final SplitContainer splitContainer = getActiveSplitForContainer(primaryContainer);
920 final WindowMetrics taskWindowMetrics = mPresenter.getTaskWindowMetrics(primaryActivity);
921 if (splitContainer != null && primaryContainer == splitContainer.getPrimaryContainer()
922 && canReuseContainer(splitRule, splitContainer.getSplitRule(), taskWindowMetrics)) {
923 // Can launch in the existing secondary container if the rules share the same
924 // presentation.
925 final TaskFragmentContainer secondaryContainer = splitContainer.getSecondaryContainer();
926 if (secondaryContainer == getContainerWithActivity(secondaryActivity)) {
927 // The activity is already in the target TaskFragment.
928 return true;
929 }
930 secondaryContainer.addPendingAppearedActivity(secondaryActivity);
931 if (mPresenter.expandSplitContainerIfNeeded(wct, splitContainer, primaryActivity,
932 secondaryActivity, null /* secondaryIntent */)
933 != RESULT_EXPAND_FAILED_NO_TF_INFO) {
934 wct.reparentActivityToTaskFragment(
935 secondaryContainer.getTaskFragmentToken(),
936 secondaryActivity.getActivityToken());
937 return true;
938 }
939 }
940 // Create new split pair.
941 mPresenter.createNewSplitContainer(wct, primaryActivity, secondaryActivity, splitRule);
942 return true;
943 }
944
945 @GuardedBy("mLock")
946 private void onActivityConfigurationChanged(@NonNull WindowContainerTransaction wct,
947 @NonNull Activity activity) {
948 if (activity.isFinishing()) {
949 // Do nothing if the activity is currently finishing.
950 return;
951 }
952
953 if (isInPictureInPicture(activity)) {
954 // We don't embed activity when it is in PIP.
955 return;
956 }
957 final TaskFragmentContainer currentContainer = getContainerWithActivity(activity);
958
959 if (currentContainer != null) {
960 // Changes to activities in controllers are handled in
961 // onTaskFragmentParentInfoChanged
962 return;
963 }
964
965 // Check if activity requires a placeholder
966 launchPlaceholderIfNecessary(wct, activity, false /* isOnCreated */);
967 }
968
969 @VisibleForTesting
970 @GuardedBy("mLock")
971 void onActivityDestroyed(@NonNull Activity activity) {
972 if (!activity.isFinishing()) {
973 // onDestroyed is triggered without finishing. This happens when the activity is
974 // relaunched. In this case, we don't want to cleanup the record.
975 return;
976 }
977 // Remove any pending appeared activity, as the server won't send finished activity to the
978 // organizer.
979 final IBinder activityToken = activity.getActivityToken();
980 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
981 mTaskContainers.valueAt(i).onActivityDestroyed(activityToken);
982 }
983 // We didn't trigger the callback if there were any pending appeared activities, so check
984 // again after the pending is removed.
985 updateCallbackIfNecessary();
986 }
987
988 /**
989 * Called when we have been waiting too long for the TaskFragment to become non-empty after
990 * creation.
991 */
992 @GuardedBy("mLock")
993 void onTaskFragmentAppearEmptyTimeout(@NonNull TaskFragmentContainer container) {
994 final TransactionRecord transactionRecord = mTransactionManager.startNewTransaction();
995 onTaskFragmentAppearEmptyTimeout(transactionRecord.getTransaction(), container);
996 // Can be applied independently as a timeout callback.
997 transactionRecord.apply(true /* shouldApplyIndependently */);
998 }
999
1000 /**
1001 * Called when we have been waiting too long for the TaskFragment to become non-empty after
1002 * creation.
1003 */
1004 @GuardedBy("mLock")
1005 void onTaskFragmentAppearEmptyTimeout(@NonNull WindowContainerTransaction wct,
1006 @NonNull TaskFragmentContainer container) {
1007 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE);
1008 mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */);
1009 }
1010
1011 @Nullable
1012 @GuardedBy("mLock")
1013 private TaskFragmentContainer resolveStartActivityIntentFromNonActivityContext(
1014 @NonNull WindowContainerTransaction wct, @NonNull Intent intent) {
1015 final int taskCount = mTaskContainers.size();
1016 if (taskCount == 0) {
1017 // We don't have other Activity to check split with.
1018 return null;
1019 }
1020 if (taskCount > 1) {
1021 Log.w(TAG, "App is calling startActivity from a non-Activity context when it has"
1022 + " more than one Task. If the new launch Activity is in a different process,"
1023 + " and it is expected to be embedded, please start it from an Activity"
1024 + " instead.");
1025 return null;
1026 }
1027
1028 // Check whether the Intent should be embedded in the known Task.
1029 final TaskContainer taskContainer = mTaskContainers.valueAt(0);
1030 if (taskContainer.isInPictureInPicture()
1031 || taskContainer.getTopNonFinishingActivity() == null) {
1032 // We don't embed activity when it is in PIP, or if we can't find any other owner
1033 // activity in the Task.
1034 return null;
1035 }
1036
1037 return resolveStartActivityIntent(wct, taskContainer.getTaskId(), intent,
1038 null /* launchingActivity */);
1039 }
1040
1041 /**
1042 * When we are trying to handle a new activity Intent, returns the {@link TaskFragmentContainer}
1043 * that we should reparent the new activity to if there is any embedding rule matched.
1044 *
1045 * @param wct {@link WindowContainerTransaction} including all the window change
1046 * requests. The caller is responsible to call
1047 * {@link android.window.TaskFragmentOrganizer#applyTransaction}.
1048 * @param taskId The Task to start the activity in.
1049 * @param intent The {@link Intent} for starting the new launched activity.
1050 * @param launchingActivity The {@link Activity} that starts the new activity. We will
1051 * prioritize to split the new activity with it if it is not
1052 * {@code null}.
1053 * @return the {@link TaskFragmentContainer} to start the new activity in. {@code null} if there
1054 * is no embedding rule matched.
1055 */
1056 @VisibleForTesting
1057 @Nullable
1058 @GuardedBy("mLock")
1059 TaskFragmentContainer resolveStartActivityIntent(@NonNull WindowContainerTransaction wct,
1060 int taskId, @NonNull Intent intent, @Nullable Activity launchingActivity) {
1061 /*
1062 * We will check the following to see if there is any embedding rule matched:
1063 * 1. Whether the new activity intent should always expand.
1064 * 2. Whether the launching activity (if set) should be split with the new activity intent.
1065 * 3. Whether the top activity (if any) should be split with the new activity intent.
1066 * 4. Whether the top activity (if any) in other split should be split with the new
1067 * activity intent.
1068 */
1069
1070 // 1. Whether the new activity intent should always expand.
1071 if (shouldExpand(null /* activity */, intent)) {
1072 return createEmptyExpandedContainer(wct, intent, taskId, launchingActivity);
1073 }
1074
1075 // 2. Whether the launching activity (if set) should be split with the new activity intent.
1076 if (launchingActivity != null) {
1077 final TaskFragmentContainer container = getSecondaryContainerForSplitIfAny(wct,
1078 launchingActivity, intent, true /* respectClearTop */);
1079 if (container != null) {
1080 return container;
1081 }
1082 }
1083
1084 // 3. Whether the top activity (if any) should be split with the new activity intent.
1085 final TaskContainer taskContainer = getTaskContainer(taskId);
1086 if (taskContainer == null || taskContainer.getTopTaskFragmentContainer() == null) {
1087 // There is no other activity in the Task to check split with.
1088 return null;
1089 }
1090 final TaskFragmentContainer topContainer = taskContainer.getTopTaskFragmentContainer();
1091 final Activity topActivity = topContainer.getTopNonFinishingActivity();
1092 if (topActivity != null && topActivity != launchingActivity) {
1093 final TaskFragmentContainer container = getSecondaryContainerForSplitIfAny(wct,
1094 topActivity, intent, false /* respectClearTop */);
1095 if (container != null) {
1096 return container;
1097 }
1098 }
1099
1100 // 4. Whether the top activity (if any) in other split should be split with the new
1101 // activity intent.
1102 final SplitContainer topSplit = getActiveSplitForContainer(topContainer);
1103 if (topSplit == null) {
1104 return null;
1105 }
1106 final TaskFragmentContainer otherTopContainer =
1107 topSplit.getPrimaryContainer() == topContainer
1108 ? topSplit.getSecondaryContainer()
1109 : topSplit.getPrimaryContainer();
1110 final Activity otherTopActivity = otherTopContainer.getTopNonFinishingActivity();
1111 if (otherTopActivity != null && otherTopActivity != launchingActivity) {
1112 return getSecondaryContainerForSplitIfAny(wct, otherTopActivity, intent,
1113 false /* respectClearTop */);
1114 }
1115 return null;
1116 }
1117
1118 /**
1119 * Returns an empty expanded {@link TaskFragmentContainer} that we can launch an activity into.
1120 */
1121 @GuardedBy("mLock")
1122 @Nullable
1123 private TaskFragmentContainer createEmptyExpandedContainer(
1124 @NonNull WindowContainerTransaction wct, @NonNull Intent intent, int taskId,
1125 @Nullable Activity launchingActivity) {
1126 // We need an activity in the organizer process in the same Task to use as the owner
1127 // activity, as well as to get the Task window info.
1128 final Activity activityInTask;
1129 if (launchingActivity != null) {
1130 activityInTask = launchingActivity;
1131 } else {
1132 final TaskContainer taskContainer = getTaskContainer(taskId);
1133 activityInTask = taskContainer != null
1134 ? taskContainer.getTopNonFinishingActivity()
1135 : null;
1136 }
1137 if (activityInTask == null) {
1138 // Can't find any activity in the Task that we can use as the owner activity.
1139 return null;
1140 }
1141 final TaskFragmentContainer expandedContainer = newContainer(intent, activityInTask,
1142 taskId);
1143 mPresenter.createTaskFragment(wct, expandedContainer.getTaskFragmentToken(),
1144 activityInTask.getActivityToken(), new Rect(), WINDOWING_MODE_UNDEFINED);
1145 mPresenter.updateAnimationParams(wct, expandedContainer.getTaskFragmentToken(),
1146 TaskFragmentAnimationParams.DEFAULT);
1147 return expandedContainer;
1148 }
1149
1150 /**
1151 * Returns a container for the new activity intent to launch into as splitting with the primary
1152 * activity.
1153 */
1154 @GuardedBy("mLock")
1155 @Nullable
1156 private TaskFragmentContainer getSecondaryContainerForSplitIfAny(
1157 @NonNull WindowContainerTransaction wct, @NonNull Activity primaryActivity,
1158 @NonNull Intent intent, boolean respectClearTop) {
1159 final SplitPairRule splitRule = getSplitRule(primaryActivity, intent);
1160 if (splitRule == null) {
1161 return null;
1162 }
1163 final TaskFragmentContainer existingContainer = getContainerWithActivity(primaryActivity);
1164 final SplitContainer splitContainer = getActiveSplitForContainer(existingContainer);
1165 final WindowMetrics taskWindowMetrics = mPresenter.getTaskWindowMetrics(primaryActivity);
1166 if (splitContainer != null && existingContainer == splitContainer.getPrimaryContainer()
1167 && (canReuseContainer(splitRule, splitContainer.getSplitRule(), taskWindowMetrics)
1168 // TODO(b/231845476) we should always respect clearTop.
1169 || !respectClearTop)
1170 && mPresenter.expandSplitContainerIfNeeded(wct, splitContainer, primaryActivity,
1171 null /* secondaryActivity */, intent) != RESULT_EXPAND_FAILED_NO_TF_INFO) {
1172 // Can launch in the existing secondary container if the rules share the same
1173 // presentation.
1174 return splitContainer.getSecondaryContainer();
1175 }
1176 // Create a new TaskFragment to split with the primary activity for the new activity.
1177 return mPresenter.createNewSplitWithEmptySideContainer(wct, primaryActivity, intent,
1178 splitRule);
1179 }
1180
1181 /**
1182 * Returns a container that this activity is registered with. An activity can only belong to one
1183 * container, or no container at all.
1184 */
1185 @GuardedBy("mLock")
1186 @Nullable
1187 TaskFragmentContainer getContainerWithActivity(@NonNull Activity activity) {
1188 return getContainerWithActivity(activity.getActivityToken());
1189 }
1190
1191 @GuardedBy("mLock")
1192 @Nullable
1193 TaskFragmentContainer getContainerWithActivity(@NonNull IBinder activityToken) {
1194 // Check pending appeared activity first because there can be a delay for the server
1195 // update.
1196 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
1197 final List<TaskFragmentContainer> containers = mTaskContainers.valueAt(i).mContainers;
1198 for (int j = containers.size() - 1; j >= 0; j--) {
1199 final TaskFragmentContainer container = containers.get(j);
1200 if (container.hasPendingAppearedActivity(activityToken)) {
1201 return container;
1202 }
1203 }
1204 }
1205
1206 // Check appeared activity if there is no such pending appeared activity.
1207 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
1208 final List<TaskFragmentContainer> containers = mTaskContainers.valueAt(i).mContainers;
1209 for (int j = containers.size() - 1; j >= 0; j--) {
1210 final TaskFragmentContainer container = containers.get(j);
1211 if (container.hasAppearedActivity(activityToken)) {
1212 return container;
1213 }
1214 }
1215 }
1216 return null;
1217 }
1218
1219 @GuardedBy("mLock")
1220 TaskFragmentContainer newContainer(@NonNull Activity pendingAppearedActivity, int taskId) {
1221 return newContainer(pendingAppearedActivity, pendingAppearedActivity, taskId);
1222 }
1223
1224 @GuardedBy("mLock")
1225 TaskFragmentContainer newContainer(@NonNull Activity pendingAppearedActivity,
1226 @NonNull Activity activityInTask, int taskId) {
1227 return newContainer(pendingAppearedActivity, null /* pendingAppearedIntent */,
1228 activityInTask, taskId, null /* pairedPrimaryContainer */);
1229 }
1230
1231 @GuardedBy("mLock")
1232 TaskFragmentContainer newContainer(@NonNull Intent pendingAppearedIntent,
1233 @NonNull Activity activityInTask, int taskId) {
1234 return newContainer(null /* pendingAppearedActivity */, pendingAppearedIntent,
1235 activityInTask, taskId, null /* pairedPrimaryContainer */);
1236 }
1237
1238 /**
1239 * Creates and registers a new organized container with an optional activity that will be
1240 * re-parented to it in a WCT.
1241 *
1242 * @param pendingAppearedActivity the activity that will be reparented to the TaskFragment.
1243 * @param pendingAppearedIntent the Intent that will be started in the TaskFragment.
1244 * @param activityInTask activity in the same Task so that we can get the Task bounds
1245 * if needed.
1246 * @param taskId parent Task of the new TaskFragment.
1247 * @param pairedPrimaryContainer the paired primary {@link TaskFragmentContainer}. When it is
1248 * set, the new container will be added right above it.
1249 */
1250 @GuardedBy("mLock")
1251 TaskFragmentContainer newContainer(@Nullable Activity pendingAppearedActivity,
1252 @Nullable Intent pendingAppearedIntent, @NonNull Activity activityInTask, int taskId,
1253 @Nullable TaskFragmentContainer pairedPrimaryContainer) {
1254 if (activityInTask == null) {
1255 throw new IllegalArgumentException("activityInTask must not be null,");
1256 }
1257 if (!mTaskContainers.contains(taskId)) {
1258 mTaskContainers.put(taskId, new TaskContainer(taskId, activityInTask));
1259 }
1260 final TaskContainer taskContainer = mTaskContainers.get(taskId);
1261 final TaskFragmentContainer container = new TaskFragmentContainer(pendingAppearedActivity,
1262 pendingAppearedIntent, taskContainer, this, pairedPrimaryContainer);
1263 return container;
1264 }
1265
1266 /**
1267 * Creates and registers a new split with the provided containers and configuration. Finishes
1268 * existing secondary containers if found for the given primary container.
1269 */
1270 // Suppress GuardedBy warning because lint ask to mark this method as
1271 // @GuardedBy(mPresenter.mController.mLock), which is mLock itself
1272 @SuppressWarnings("GuardedBy")
1273 @GuardedBy("mLock")
1274 void registerSplit(@NonNull WindowContainerTransaction wct,
1275 @NonNull TaskFragmentContainer primaryContainer, @NonNull Activity primaryActivity,
1276 @NonNull TaskFragmentContainer secondaryContainer,
1277 @NonNull SplitRule splitRule, @NonNull SplitAttributes splitAttributes) {
1278 final SplitContainer splitContainer = new SplitContainer(primaryContainer, primaryActivity,
1279 secondaryContainer, splitRule, splitAttributes);
1280 // Remove container later to prevent pinning escaping toast showing in lock task mode.
1281 if (splitRule instanceof SplitPairRule && ((SplitPairRule) splitRule).shouldClearTop()) {
1282 removeExistingSecondaryContainers(wct, primaryContainer);
1283 }
1284 primaryContainer.getTaskContainer().mSplitContainers.add(splitContainer);
1285 }
1286
1287 /** Cleanups all the dependencies when the TaskFragment is entering PIP. */
1288 @GuardedBy("mLock")
1289 private void cleanupForEnterPip(@NonNull WindowContainerTransaction wct,
1290 @NonNull TaskFragmentContainer container) {
1291 final TaskContainer taskContainer = container.getTaskContainer();
1292 if (taskContainer == null) {
1293 return;
1294 }
1295 final List<SplitContainer> splitsToRemove = new ArrayList<>();
1296 final Set<TaskFragmentContainer> containersToUpdate = new ArraySet<>();
1297 for (SplitContainer splitContainer : taskContainer.mSplitContainers) {
1298 if (splitContainer.getPrimaryContainer() != container
1299 && splitContainer.getSecondaryContainer() != container) {
1300 continue;
1301 }
1302 splitsToRemove.add(splitContainer);
1303 final TaskFragmentContainer splitTf = splitContainer.getPrimaryContainer() == container
1304 ? splitContainer.getSecondaryContainer()
1305 : splitContainer.getPrimaryContainer();
1306 containersToUpdate.add(splitTf);
1307 // We don't want the PIP TaskFragment to be removed as a result of any of its dependents
1308 // being removed.
1309 splitTf.removeContainerToFinishOnExit(container);
1310 if (container.getTopNonFinishingActivity() != null) {
1311 splitTf.removeActivityToFinishOnExit(container.getTopNonFinishingActivity());
1312 }
1313 }
1314 container.resetDependencies();
1315 taskContainer.mSplitContainers.removeAll(splitsToRemove);
1316 // If there is any TaskFragment split with the PIP TaskFragment, update their presentations
1317 // since the split is dismissed.
1318 // We don't want to close any of them even if they are dependencies of the PIP TaskFragment.
1319 for (TaskFragmentContainer containerToUpdate : containersToUpdate) {
1320 updateContainer(wct, containerToUpdate);
1321 }
1322 }
1323
1324 /**
1325 * Removes the container from bookkeeping records.
1326 */
1327 void removeContainer(@NonNull TaskFragmentContainer container) {
1328 // Remove all split containers that included this one
1329 final TaskContainer taskContainer = container.getTaskContainer();
1330 taskContainer.mContainers.remove(container);
1331 // Marked as a pending removal which will be removed after it is actually removed on the
1332 // server side (#onTaskFragmentVanished).
1333 // In this way, we can keep track of the Task bounds until we no longer have any
1334 // TaskFragment there.
1335 taskContainer.mFinishedContainer.add(container.getTaskFragmentToken());
1336
1337 // Cleanup any split references.
1338 final List<SplitContainer> containersToRemove = new ArrayList<>();
1339 for (SplitContainer splitContainer : taskContainer.mSplitContainers) {
1340 if (container.equals(splitContainer.getSecondaryContainer())
1341 || container.equals(splitContainer.getPrimaryContainer())) {
1342 containersToRemove.add(splitContainer);
1343 }
1344 }
1345 taskContainer.mSplitContainers.removeAll(containersToRemove);
1346
1347 // Cleanup any dependent references.
1348 for (TaskFragmentContainer containerToUpdate : taskContainer.mContainers) {
1349 containerToUpdate.removeContainerToFinishOnExit(container);
1350 }
1351 }
1352
1353 /**
1354 * Removes a secondary container for the given primary container if an existing split is
1355 * already registered.
1356 */
1357 // Suppress GuardedBy warning because lint asks to mark this method as
1358 // @GuardedBy(existingSplitContainer.getSecondaryContainer().mController.mLock), which is mLock
1359 // itself
1360 @SuppressWarnings("GuardedBy")
1361 @GuardedBy("mLock")
1362 private void removeExistingSecondaryContainers(@NonNull WindowContainerTransaction wct,
1363 @NonNull TaskFragmentContainer primaryContainer) {
1364 // If the primary container was already in a split - remove the secondary container that
1365 // is now covered by the new one that replaced it.
1366 final SplitContainer existingSplitContainer = getActiveSplitForContainer(
1367 primaryContainer);
1368 if (existingSplitContainer == null
1369 || primaryContainer == existingSplitContainer.getSecondaryContainer()) {
1370 return;
1371 }
1372
1373 existingSplitContainer.getSecondaryContainer().finish(
1374 false /* shouldFinishDependent */, mPresenter, wct, this);
1375 }
1376
1377 /**
1378 * Returns the topmost not finished container in Task of given task id.
1379 */
1380 @GuardedBy("mLock")
1381 @Nullable
1382 TaskFragmentContainer getTopActiveContainer(int taskId) {
1383 final TaskContainer taskContainer = mTaskContainers.get(taskId);
1384 if (taskContainer == null) {
1385 return null;
1386 }
1387 for (int i = taskContainer.mContainers.size() - 1; i >= 0; i--) {
1388 final TaskFragmentContainer container = taskContainer.mContainers.get(i);
1389 if (!container.isFinished() && (container.getRunningActivityCount() > 0
1390 // We may be waiting for the top TaskFragment to become non-empty after
1391 // creation. In that case, we don't want to treat the TaskFragment below it as
1392 // top active, otherwise it may incorrectly launch placeholder on top of the
1393 // pending TaskFragment.
1394 || container.isWaitingActivityAppear())) {
1395 return container;
1396 }
1397 }
1398 return null;
1399 }
1400
1401 /**
1402 * Updates the presentation of the container. If the container is part of the split or should
1403 * have a placeholder, it will also update the other part of the split.
1404 */
1405 @GuardedBy("mLock")
1406 void updateContainer(@NonNull WindowContainerTransaction wct,
1407 @NonNull TaskFragmentContainer container) {
1408 if (!container.getTaskContainer().isVisible()) {
1409 // Wait until the Task is visible to avoid unnecessary update when the Task is still in
1410 // background.
1411 return;
1412 }
1413 if (launchPlaceholderIfNecessary(wct, container)) {
1414 // Placeholder was launched, the positions will be updated when the activity is added
1415 // to the secondary container.
1416 return;
1417 }
1418 if (shouldContainerBeExpanded(container)) {
1419 if (container.getInfo() != null) {
1420 mPresenter.expandTaskFragment(wct, container.getTaskFragmentToken());
1421 }
1422 // If the info is not available yet the task fragment will be expanded when it's ready
1423 return;
1424 }
1425 SplitContainer splitContainer = getActiveSplitForContainer(container);
1426 if (splitContainer == null) {
1427 return;
1428 }
1429 if (!isTopMostSplit(splitContainer)) {
1430 // Skip position update - it isn't the topmost split.
1431 return;
1432 }
1433 if (splitContainer.getPrimaryContainer().isFinished()
1434 || splitContainer.getSecondaryContainer().isFinished()) {
1435 // Skip position update - one or both containers are finished.
1436 return;
1437 }
1438 final TaskContainer taskContainer = splitContainer.getTaskContainer();
1439 final SplitRule splitRule = splitContainer.getSplitRule();
1440 final Pair<Size, Size> minDimensionsPair = splitContainer.getMinDimensionsPair();
1441 final SplitAttributes splitAttributes = mPresenter.computeSplitAttributes(
1442 taskContainer.getTaskProperties(), splitRule, minDimensionsPair);
1443 splitContainer.setSplitAttributes(splitAttributes);
1444 if (dismissPlaceholderIfNecessary(wct, splitContainer)) {
1445 // Placeholder was finished, the positions will be updated when its container is emptied
1446 return;
1447 }
1448 mPresenter.updateSplitContainer(splitContainer, container, wct);
1449 }
1450
1451 /** Whether the given split is the topmost split in the Task. */
1452 private boolean isTopMostSplit(@NonNull SplitContainer splitContainer) {
1453 final List<SplitContainer> splitContainers = splitContainer.getPrimaryContainer()
1454 .getTaskContainer().mSplitContainers;
1455 return splitContainer == splitContainers.get(splitContainers.size() - 1);
1456 }
1457
1458 /**
1459 * Returns the top active split container that has the provided container, if available.
1460 */
1461 @Nullable
1462 private SplitContainer getActiveSplitForContainer(@Nullable TaskFragmentContainer container) {
1463 if (container == null) {
1464 return null;
1465 }
1466 final List<SplitContainer> splitContainers = container.getTaskContainer().mSplitContainers;
1467 if (splitContainers.isEmpty()) {
1468 return null;
1469 }
1470 for (int i = splitContainers.size() - 1; i >= 0; i--) {
1471 final SplitContainer splitContainer = splitContainers.get(i);
1472 if (container.equals(splitContainer.getSecondaryContainer())
1473 || container.equals(splitContainer.getPrimaryContainer())) {
1474 return splitContainer;
1475 }
1476 }
1477 return null;
1478 }
1479
1480 /**
1481 * Returns the active split that has the provided containers as primary and secondary or as
1482 * secondary and primary, if available.
1483 */
1484 @VisibleForTesting
1485 @Nullable
1486 SplitContainer getActiveSplitForContainers(
1487 @NonNull TaskFragmentContainer firstContainer,
1488 @NonNull TaskFragmentContainer secondContainer) {
1489 final List<SplitContainer> splitContainers = firstContainer.getTaskContainer()
1490 .mSplitContainers;
1491 for (int i = splitContainers.size() - 1; i >= 0; i--) {
1492 final SplitContainer splitContainer = splitContainers.get(i);
1493 final TaskFragmentContainer primary = splitContainer.getPrimaryContainer();
1494 final TaskFragmentContainer secondary = splitContainer.getSecondaryContainer();
1495 if ((firstContainer == secondary && secondContainer == primary)
1496 || (firstContainer == primary && secondContainer == secondary)) {
1497 return splitContainer;
1498 }
1499 }
1500 return null;
1501 }
1502
1503 /**
1504 * Checks if the container requires a placeholder and launches it if necessary.
1505 */
1506 @GuardedBy("mLock")
1507 private boolean launchPlaceholderIfNecessary(@NonNull WindowContainerTransaction wct,
1508 @NonNull TaskFragmentContainer container) {
1509 final Activity topActivity = container.getTopNonFinishingActivity();
1510 if (topActivity == null) {
1511 return false;
1512 }
1513
1514 return launchPlaceholderIfNecessary(wct, topActivity, false /* isOnCreated */);
1515 }
1516
1517 // Suppress GuardedBy warning because lint ask to mark this method as
1518 // @GuardedBy(mPresenter.mController.mLock), which is mLock itself
1519 @SuppressWarnings("GuardedBy")
1520 @GuardedBy("mLock")
1521 boolean launchPlaceholderIfNecessary(@NonNull WindowContainerTransaction wct,
1522 @NonNull Activity activity, boolean isOnCreated) {
1523 if (activity.isFinishing()) {
1524 return false;
1525 }
1526
1527 final TaskFragmentContainer container = getContainerWithActivity(activity);
1528 if (container != null && !allowLaunchPlaceholder(container)) {
1529 // We don't allow activity in this TaskFragment to launch placeholder.
1530 return false;
1531 }
1532
1533 // Check if there is enough space for launch
1534 final SplitPlaceholderRule placeholderRule = getPlaceholderRule(activity);
1535
1536 if (placeholderRule == null) {
1537 return false;
1538 }
1539
1540 final TaskContainer.TaskProperties taskProperties = mPresenter.getTaskProperties(activity);
1541 final Pair<Size, Size> minDimensionsPair = getActivityIntentMinDimensionsPair(activity,
1542 placeholderRule.getPlaceholderIntent());
1543 final SplitAttributes splitAttributes = mPresenter.computeSplitAttributes(taskProperties,
1544 placeholderRule, minDimensionsPair);
1545 if (!SplitPresenter.shouldShowSplit(splitAttributes)) {
1546 return false;
1547 }
1548
1549 // TODO(b/190433398): Handle failed request
1550 final Bundle options = getPlaceholderOptions(activity, isOnCreated);
1551 startActivityToSide(wct, activity, placeholderRule.getPlaceholderIntent(), options,
1552 placeholderRule, splitAttributes, null /* failureCallback */,
1553 true /* isPlaceholder */);
1554 return true;
1555 }
1556
1557 /** Whether or not to allow activity in this container to launch placeholder. */
1558 @GuardedBy("mLock")
1559 private boolean allowLaunchPlaceholder(@NonNull TaskFragmentContainer container) {
1560 final TaskFragmentContainer topContainer = getTopActiveContainer(container.getTaskId());
1561 if (container != topContainer) {
1562 // The container is not the top most.
1563 if (!container.isVisible()) {
1564 // In case the container is visible (the one on top may be transparent), we may
1565 // still want to launch placeholder even if it is not the top most.
1566 return false;
1567 }
1568 if (topContainer.isWaitingActivityAppear()) {
1569 // When the top container appeared info is not sent by the server yet, the visible
1570 // check above may not be reliable.
1571 return false;
1572 }
1573 }
1574
1575 final SplitContainer splitContainer = getActiveSplitForContainer(container);
1576 if (splitContainer != null && container.equals(splitContainer.getPrimaryContainer())) {
1577 // Don't launch placeholder for primary split container.
1578 return false;
1579 }
1580 return true;
1581 }
1582
1583 /**
1584 * Gets the activity options for starting the placeholder activity. In case the placeholder is
1585 * launched when the Task is in the background, we don't want to bring the Task to the front.
1586 * @param primaryActivity the primary activity to launch the placeholder from.
1587 * @param isOnCreated whether this happens during the primary activity onCreated.
1588 */
1589 @VisibleForTesting
1590 @GuardedBy("mLock")
1591 @Nullable
1592 Bundle getPlaceholderOptions(@NonNull Activity primaryActivity, boolean isOnCreated) {
1593 // Setting avoid move to front will also skip the animation. We only want to do that when
1594 // the Task is currently in background.
1595 // Check if the primary is resumed or if this is called when the primary is onCreated
1596 // (not resumed yet).
1597 if (isOnCreated || primaryActivity.isResumed()) {
1598 // Only set trigger type if the launch happens in foreground.
1599 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_OPEN);
1600 return null;
1601 }
1602 final ActivityOptions options = ActivityOptions.makeBasic();
1603 options.setAvoidMoveToFront();
1604 return options.toBundle();
1605 }
1606
1607 // Suppress GuardedBy warning because lint ask to mark this method as
1608 // @GuardedBy(mPresenter.mController.mLock), which is mLock itself
1609 @SuppressWarnings("GuardedBy")
1610 @VisibleForTesting
1611 @GuardedBy("mLock")
1612 boolean dismissPlaceholderIfNecessary(@NonNull WindowContainerTransaction wct,
1613 @NonNull SplitContainer splitContainer) {
1614 if (!splitContainer.isPlaceholderContainer()) {
1615 return false;
1616 }
1617
1618 if (isStickyPlaceholderRule(splitContainer.getSplitRule())) {
1619 // The placeholder should remain after it was first shown.
1620 return false;
1621 }
1622 final SplitAttributes splitAttributes = splitContainer.getSplitAttributes();
1623 if (SplitPresenter.shouldShowSplit(splitAttributes)) {
1624 return false;
1625 }
1626
1627 mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE);
1628 mPresenter.cleanupContainer(wct, splitContainer.getSecondaryContainer(),
1629 false /* shouldFinishDependent */);
1630 return true;
1631 }
1632
1633 /**
1634 * Returns the rule to launch a placeholder for the activity with the provided component name
1635 * if it is configured in the split config.
1636 */
1637 @GuardedBy("mLock")
1638 private SplitPlaceholderRule getPlaceholderRule(@NonNull Activity activity) {
1639 for (EmbeddingRule rule : mSplitRules) {
1640 if (!(rule instanceof SplitPlaceholderRule)) {
1641 continue;
1642 }
1643 SplitPlaceholderRule placeholderRule = (SplitPlaceholderRule) rule;
1644 if (placeholderRule.matchesActivity(activity)) {
1645 return placeholderRule;
1646 }
1647 }
1648 return null;
1649 }
1650
1651 /**
1652 * Notifies listeners about changes to split states if necessary.
1653 */
1654 @VisibleForTesting
1655 @GuardedBy("mLock")
1656 void updateCallbackIfNecessary() {
1657 if (mEmbeddingCallback == null || !readyToReportToClient()) {
1658 return;
1659 }
1660 final List<SplitInfo> currentSplitStates = getActiveSplitStates();
1661 if (mLastReportedSplitStates.equals(currentSplitStates)) {
1662 return;
1663 }
1664 mLastReportedSplitStates.clear();
1665 mLastReportedSplitStates.addAll(currentSplitStates);
1666 mEmbeddingCallback.accept(currentSplitStates);
1667 }
1668
1669 /**
1670 * Returns a list of descriptors for currently active split states.
1671 */
1672 @GuardedBy("mLock")
1673 @NonNull
1674 private List<SplitInfo> getActiveSplitStates() {
1675 final List<SplitInfo> splitStates = new ArrayList<>();
1676 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
1677 mTaskContainers.valueAt(i).getSplitStates(splitStates);
1678 }
1679 return splitStates;
1680 }
1681
1682 /**
1683 * Whether we can now report the split states to the client.
1684 */
1685 @GuardedBy("mLock")
1686 private boolean readyToReportToClient() {
1687 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
1688 if (mTaskContainers.valueAt(i).isInIntermediateState()) {
1689 // If any Task is in an intermediate state, wait for the server update.
1690 return false;
1691 }
1692 }
1693 return true;
1694 }
1695
1696 /**
1697 * Returns {@code true} if the container is expanded to occupy full task size.
1698 * Returns {@code false} if the container is included in an active split.
1699 */
1700 boolean shouldContainerBeExpanded(@Nullable TaskFragmentContainer container) {
1701 if (container == null) {
1702 return false;
1703 }
1704 return getActiveSplitForContainer(container) == null;
1705 }
1706
1707 /**
1708 * Returns a split rule for the provided pair of primary activity and secondary activity intent
1709 * if available.
1710 */
1711 @GuardedBy("mLock")
1712 @Nullable
1713 private SplitPairRule getSplitRule(@NonNull Activity primaryActivity,
1714 @NonNull Intent secondaryActivityIntent) {
1715 for (EmbeddingRule rule : mSplitRules) {
1716 if (!(rule instanceof SplitPairRule)) {
1717 continue;
1718 }
1719 SplitPairRule pairRule = (SplitPairRule) rule;
1720 if (pairRule.matchesActivityIntentPair(primaryActivity, secondaryActivityIntent)) {
1721 return pairRule;
1722 }
1723 }
1724 return null;
1725 }
1726
1727 /**
1728 * Returns a split rule for the provided pair of primary and secondary activities if available.
1729 */
1730 @GuardedBy("mLock")
1731 @Nullable
1732 private SplitPairRule getSplitRule(@NonNull Activity primaryActivity,
1733 @NonNull Activity secondaryActivity) {
1734 for (EmbeddingRule rule : mSplitRules) {
1735 if (!(rule instanceof SplitPairRule)) {
1736 continue;
1737 }
1738 SplitPairRule pairRule = (SplitPairRule) rule;
1739 final Intent intent = secondaryActivity.getIntent();
1740 if (pairRule.matchesActivityPair(primaryActivity, secondaryActivity)
1741 && (intent == null
1742 || pairRule.matchesActivityIntentPair(primaryActivity, intent))) {
1743 return pairRule;
1744 }
1745 }
1746 return null;
1747 }
1748
1749 @Nullable
1750 @GuardedBy("mLock")
1751 TaskFragmentContainer getContainer(@NonNull IBinder fragmentToken) {
1752 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
1753 final List<TaskFragmentContainer> containers = mTaskContainers.valueAt(i).mContainers;
1754 for (TaskFragmentContainer container : containers) {
1755 if (container.getTaskFragmentToken().equals(fragmentToken)) {
1756 return container;
1757 }
1758 }
1759 }
1760 return null;
1761 }
1762
1763 @Nullable
1764 @GuardedBy("mLock")
1765 TaskContainer getTaskContainer(int taskId) {
1766 return mTaskContainers.get(taskId);
1767 }
1768
1769 Handler getHandler() {
1770 return mHandler;
1771 }
1772
1773 @GuardedBy("mLock")
1774 int getTaskId(@NonNull Activity activity) {
1775 // Prefer to get the taskId from TaskFragmentContainer because Activity.getTaskId() is an
1776 // IPC call.
1777 final TaskFragmentContainer container = getContainerWithActivity(activity);
1778 return container != null ? container.getTaskId() : activity.getTaskId();
1779 }
1780
1781 @Nullable
1782 Activity getActivity(@NonNull IBinder activityToken) {
1783 return ActivityThread.currentActivityThread().getActivity(activityToken);
1784 }
1785
1786 @VisibleForTesting
1787 ActivityStartMonitor getActivityStartMonitor() {
1788 return mActivityStartMonitor;
1789 }
1790
1791 /**
1792 * Gets the token of the TaskFragment that embedded this activity. It is available as soon as
1793 * the activity is created and attached, so it can be used during {@link #onActivityCreated}
1794 * before the server notifies the organizer to avoid racing condition.
1795 */
1796 @VisibleForTesting
1797 @Nullable
1798 IBinder getTaskFragmentTokenFromActivityClientRecord(@NonNull Activity activity) {
1799 final ActivityThread.ActivityClientRecord record = ActivityThread.currentActivityThread()
1800 .getActivityClient(activity.getActivityToken());
1801 return record != null ? record.mTaskFragmentToken : null;
1802 }
1803
1804 /**
1805 * Returns {@code true} if an Activity with the provided component name should always be
1806 * expanded to occupy full task bounds. Such activity must not be put in a split.
1807 */
1808 @GuardedBy("mLock")
1809 private boolean shouldExpand(@Nullable Activity activity, @Nullable Intent intent) {
1810 for (EmbeddingRule rule : mSplitRules) {
1811 if (!(rule instanceof ActivityRule)) {
1812 continue;
1813 }
1814 ActivityRule activityRule = (ActivityRule) rule;
1815 if (!activityRule.shouldAlwaysExpand()) {
1816 continue;
1817 }
1818 if (activity != null && activityRule.matchesActivity(activity)) {
1819 return true;
1820 } else if (intent != null && activityRule.matchesIntent(intent)) {
1821 return true;
1822 }
1823 }
1824 return false;
1825 }
1826
1827 /**
1828 * Checks whether the associated container should be destroyed together with a finishing
1829 * container. There is a case when primary containers for placeholders should be retained
1830 * despite the rule configuration to finish primary with secondary - if they are marked as
1831 * 'sticky' and the placeholder was finished when fully overlapping the primary container.
1832 * @return {@code true} if the associated container should be retained (and not be finished).
1833 */
1834 // Suppress GuardedBy warning because lint ask to mark this method as
1835 // @GuardedBy(mPresenter.mController.mLock), which is mLock itself
1836 @SuppressWarnings("GuardedBy")
1837 @GuardedBy("mLock")
1838 boolean shouldRetainAssociatedContainer(@NonNull TaskFragmentContainer finishingContainer,
1839 @NonNull TaskFragmentContainer associatedContainer) {
1840 SplitContainer splitContainer = getActiveSplitForContainers(associatedContainer,
1841 finishingContainer);
1842 if (splitContainer == null) {
1843 // Containers are not in the same split, no need to retain.
1844 return false;
1845 }
1846 // Find the finish behavior for the associated container
1847 int finishBehavior;
1848 SplitRule splitRule = splitContainer.getSplitRule();
1849 if (finishingContainer == splitContainer.getPrimaryContainer()) {
1850 finishBehavior = getFinishSecondaryWithPrimaryBehavior(splitRule);
1851 } else {
1852 finishBehavior = getFinishPrimaryWithSecondaryBehavior(splitRule);
1853 }
1854 // Decide whether the associated container should be retained based on the current
1855 // presentation mode.
1856 if (shouldShowSplit(splitContainer)) {
1857 return !shouldFinishAssociatedContainerWhenAdjacent(finishBehavior);
1858 } else {
1859 return !shouldFinishAssociatedContainerWhenStacked(finishBehavior);
1860 }
1861 }
1862
1863 /**
1864 * @see #shouldRetainAssociatedContainer(TaskFragmentContainer, TaskFragmentContainer)
1865 */
1866 @GuardedBy("mLock")
1867 boolean shouldRetainAssociatedActivity(@NonNull TaskFragmentContainer finishingContainer,
1868 @NonNull Activity associatedActivity) {
1869 final TaskFragmentContainer associatedContainer = getContainerWithActivity(
1870 associatedActivity);
1871 if (associatedContainer == null) {
1872 return false;
1873 }
1874
1875 return shouldRetainAssociatedContainer(finishingContainer, associatedContainer);
1876 }
1877
1878 private final class LifecycleCallbacks extends EmptyLifecycleCallbacksAdapter {
1879
1880 @Override
1881 public void onActivityPreCreated(@NonNull Activity activity,
1882 @Nullable Bundle savedInstanceState) {
1883 if (activity.isChild()) {
1884 // Skip Activity that is child of another Activity (ActivityGroup) because it's
1885 // window will just be a child of the parent Activity window.
1886 return;
1887 }
1888 synchronized (mLock) {
1889 final IBinder activityToken = activity.getActivityToken();
1890 final IBinder initialTaskFragmentToken =
1891 getTaskFragmentTokenFromActivityClientRecord(activity);
1892 // If the activity is not embedded, then it will not have an initial task fragment
1893 // token so no further action is needed.
1894 if (initialTaskFragmentToken == null) {
1895 return;
1896 }
1897 for (int i = mTaskContainers.size() - 1; i >= 0; i--) {
1898 final List<TaskFragmentContainer> containers = mTaskContainers.valueAt(i)
1899 .mContainers;
1900 for (int j = containers.size() - 1; j >= 0; j--) {
1901 final TaskFragmentContainer container = containers.get(j);
1902 if (!container.hasActivity(activityToken)
1903 && container.getTaskFragmentToken()
1904 .equals(initialTaskFragmentToken)) {
1905 // The onTaskFragmentInfoChanged callback containing this activity has
1906 // not reached the client yet, so add the activity to the pending
1907 // appeared activities.
1908 container.addPendingAppearedActivity(activity);
1909 return;
1910 }
1911 }
1912 }
1913 }
1914 }
1915
1916 @Override
1917 public void onActivityPostCreated(@NonNull Activity activity,
1918 @Nullable Bundle savedInstanceState) {
1919 if (activity.isChild()) {
1920 // Skip Activity that is child of another Activity (ActivityGroup) because it's
1921 // window will just be a child of the parent Activity window.
1922 return;
1923 }
1924 // Calling after Activity#onCreate is complete to allow the app launch something
1925 // first. In case of a configured placeholder activity we want to make sure
1926 // that we don't launch it if an activity itself already requested something to be
1927 // launched to side.
1928 synchronized (mLock) {
1929 final TransactionRecord transactionRecord = mTransactionManager
1930 .startNewTransaction();
1931 transactionRecord.setOriginType(TRANSIT_OPEN);
1932 SplitController.this.onActivityCreated(transactionRecord.getTransaction(),
1933 activity);
1934 // The WCT should be applied and merged to the activity launch transition.
1935 transactionRecord.apply(false /* shouldApplyIndependently */);
1936 }
1937 }
1938
1939 @Override
1940 public void onActivityConfigurationChanged(@NonNull Activity activity) {
1941 if (activity.isChild()) {
1942 // Skip Activity that is child of another Activity (ActivityGroup) because it's
1943 // window will just be a child of the parent Activity window.
1944 return;
1945 }
1946 synchronized (mLock) {
1947 final TransactionRecord transactionRecord = mTransactionManager
1948 .startNewTransaction();
1949 SplitController.this.onActivityConfigurationChanged(
1950 transactionRecord.getTransaction(), activity);
1951 // The WCT should be applied and merged to the Task change transition so that the
1952 // placeholder is launched in the same transition.
1953 transactionRecord.apply(false /* shouldApplyIndependently */);
1954 }
1955 }
1956
1957 @Override
1958 public void onActivityPostDestroyed(@NonNull Activity activity) {
1959 if (activity.isChild()) {
1960 // Skip Activity that is child of another Activity (ActivityGroup) because it's
1961 // window will just be a child of the parent Activity window.
1962 return;
1963 }
1964 synchronized (mLock) {
1965 SplitController.this.onActivityDestroyed(activity);
1966 }
1967 }
1968 }
1969
1970 /** Executor that posts on the main application thread. */
1971 private static class MainThreadExecutor implements Executor {
1972 private final Handler mHandler = new Handler(Looper.getMainLooper());
1973
1974 @Override
1975 public void execute(@NonNull Runnable r) {
1976 mHandler.post(r);
1977 }
1978 }
1979
1980 /**
1981 * A monitor that intercepts all activity start requests originating in the client process and
1982 * can amend them to target a specific task fragment to form a split.
1983 */
1984 @VisibleForTesting
1985 class ActivityStartMonitor extends Instrumentation.ActivityMonitor {
1986 @VisibleForTesting
1987 @GuardedBy("mLock")
1988 Intent mCurrentIntent;
1989
1990 @Override
1991 public Instrumentation.ActivityResult onStartActivity(@NonNull Context who,
1992 @NonNull Intent intent, @NonNull Bundle options) {
1993 // TODO(b/232042367): Consolidate the activity create handling so that we can handle
1994 // cross-process the same as normal.
1995
1996 final Activity launchingActivity;
1997 if (who instanceof Activity) {
1998 // We will check if the new activity should be split with the activity that launched
1999 // it.
2000 final Activity activity = (Activity) who;
2001 // For Activity that is child of another Activity (ActivityGroup), treat the parent
2002 // Activity as the launching one because it's window will just be a child of the
2003 // parent Activity window.
2004 launchingActivity = activity.isChild() ? activity.getParent() : activity;
2005 if (isInPictureInPicture(launchingActivity)) {
2006 // We don't embed activity when it is in PIP.
2007 return super.onStartActivity(who, intent, options);
2008 }
2009 } else {
2010 // When the context to start activity is not an Activity context, we will check if
2011 // the new activity should be embedded in the known Task belonging to the organizer
2012 // process. @see #resolveStartActivityIntentFromNonActivityContext
2013 // It is a current security limitation that we can't access the activity info of
2014 // other process even if it is in the same Task.
2015 launchingActivity = null;
2016 }
2017
2018 synchronized (mLock) {
2019 final TransactionRecord transactionRecord = mTransactionManager
2020 .startNewTransaction();
2021 transactionRecord.setOriginType(TRANSIT_OPEN);
2022 final WindowContainerTransaction wct = transactionRecord.getTransaction();
2023 final TaskFragmentContainer launchedInTaskFragment;
2024 if (launchingActivity != null) {
2025 final int taskId = getTaskId(launchingActivity);
2026 launchedInTaskFragment = resolveStartActivityIntent(wct, taskId, intent,
2027 launchingActivity);
2028 } else {
2029 launchedInTaskFragment = resolveStartActivityIntentFromNonActivityContext(wct,
2030 intent);
2031 }
2032 if (launchedInTaskFragment != null) {
2033 // Make sure the WCT is applied immediately instead of being queued so that the
2034 // TaskFragment will be ready before activity attachment.
2035 transactionRecord.apply(false /* shouldApplyIndependently */);
2036 // Amend the request to let the WM know that the activity should be placed in
2037 // the dedicated container.
2038 options.putBinder(ActivityOptions.KEY_LAUNCH_TASK_FRAGMENT_TOKEN,
2039 launchedInTaskFragment.getTaskFragmentToken());
2040 mCurrentIntent = intent;
2041 } else {
2042 transactionRecord.abort();
2043 }
2044 }
2045
2046 return super.onStartActivity(who, intent, options);
2047 }
2048
2049 @Override
2050 public void onStartActivityResult(int result, @NonNull Bundle bOptions) {
2051 super.onStartActivityResult(result, bOptions);
2052 synchronized (mLock) {
2053 if (mCurrentIntent != null && result != START_SUCCESS) {
2054 // Clear the pending appeared intent if the activity was not started
2055 // successfully.
2056 final IBinder token = bOptions.getBinder(
2057 ActivityOptions.KEY_LAUNCH_TASK_FRAGMENT_TOKEN);
2058 if (token != null) {
2059 final TaskFragmentContainer container = getContainer(token);
2060 if (container != null) {
2061 container.clearPendingAppearedIntentIfNeeded(mCurrentIntent);
2062 }
2063 }
2064 }
2065 mCurrentIntent = null;
2066 }
2067 }
2068 }
2069
2070 /**
2071 * Checks if an activity is embedded and its presentation is customized by a
2072 * {@link android.window.TaskFragmentOrganizer} to only occupy a portion of Task bounds.
2073 */
2074 @Override
2075 public boolean isActivityEmbedded(@NonNull Activity activity) {
2076 synchronized (mLock) {
2077 return mPresenter.isActivityEmbedded(activity.getActivityToken());
2078 }
2079 }
2080
2081 /**
2082 * If the two rules have the same presentation, we can reuse the same {@link SplitContainer} if
2083 * there is any.
2084 */
2085 private static boolean canReuseContainer(@NonNull SplitRule rule1, @NonNull SplitRule rule2,
2086 @NonNull WindowMetrics parentWindowMetrics) {
2087 if (!isContainerReusableRule(rule1) || !isContainerReusableRule(rule2)) {
2088 return false;
2089 }
2090 return haveSamePresentation((SplitPairRule) rule1, (SplitPairRule) rule2,
2091 parentWindowMetrics);
2092 }
2093
2094 /** Whether the two rules have the same presentation. */
2095 @VisibleForTesting
2096 static boolean haveSamePresentation(@NonNull SplitPairRule rule1,
2097 @NonNull SplitPairRule rule2, @NonNull WindowMetrics parentWindowMetrics) {
2098 if (rule1.getTag() != null || rule2.getTag() != null) {
2099 // Tag must be unique if it is set. We don't want to reuse the container if the rules
2100 // have different tags because they can have different SplitAttributes later through
2101 // SplitAttributesCalculator.
2102 return Objects.equals(rule1.getTag(), rule2.getTag());
2103 }
2104 // If both rules don't have tag, compare all SplitRules' properties that may affect their
2105 // SplitAttributes.
2106 // TODO(b/231655482): add util method to do the comparison in SplitPairRule.
2107 return rule1.getDefaultSplitAttributes().equals(rule2.getDefaultSplitAttributes())
2108 && rule1.checkParentMetrics(parentWindowMetrics)
2109 == rule2.checkParentMetrics(parentWindowMetrics)
2110 && rule1.getFinishPrimaryWithSecondary() == rule2.getFinishPrimaryWithSecondary()
2111 && rule1.getFinishSecondaryWithPrimary() == rule2.getFinishSecondaryWithPrimary();
2112 }
2113
2114 /**
2115 * Whether it is ok for other rule to reuse the {@link TaskFragmentContainer} of the given
2116 * rule.
2117 */
2118 private static boolean isContainerReusableRule(@NonNull SplitRule rule) {
2119 // We don't expect to reuse the placeholder rule.
2120 if (!(rule instanceof SplitPairRule)) {
2121 return false;
2122 }
2123 final SplitPairRule pairRule = (SplitPairRule) rule;
2124
2125 // Not reuse if it needs to destroy the existing.
2126 return !pairRule.shouldClearTop();
2127 }
2128
2129 private static boolean isInPictureInPicture(@NonNull Activity activity) {
2130 return isInPictureInPicture(activity.getResources().getConfiguration());
2131 }
2132
2133 private static boolean isInPictureInPicture(@NonNull TaskFragmentContainer tf) {
2134 return isInPictureInPicture(tf.getInfo().getConfiguration());
2135 }
2136
2137 private static boolean isInPictureInPicture(@Nullable Configuration configuration) {
2138 return configuration != null
2139 && configuration.windowConfiguration.getWindowingMode() == WINDOWING_MODE_PINNED;
2140 }
2141 }