summaryrefslogtreecommitdiff
path: root/quickstep/src/com/android/quickstep/SystemUiProxy.java
blob: 94ed5b9cb01804e51438fdb06699f93e476fca46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.quickstep;

import static android.app.ActivityManager.RECENT_IGNORE_UNAVAILABLE;

import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import static com.android.launcher3.util.SplitConfigurationOptions.StagePosition;
import static com.android.quickstep.util.ActiveGestureErrorDetector.GestureEvent.RECENT_TASKS_MISSING;
import static com.android.quickstep.util.LogUtils.splitFailureMessage;

import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.PendingIntent;
import android.app.PictureInPictureParams;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ShortcutInfo;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.IBinder.DeathRecipient;
import android.os.Message;
import android.os.RemoteException;
import android.os.UserHandle;
import android.util.Log;
import android.view.IRecentsAnimationController;
import android.view.IRecentsAnimationRunner;
import android.view.IRemoteAnimationRunner;
import android.view.MotionEvent;
import android.view.RemoteAnimationAdapter;
import android.view.RemoteAnimationTarget;
import android.view.SurfaceControl;
import android.window.IOnBackInvokedCallback;
import android.window.RemoteTransition;
import android.window.TaskSnapshot;
import android.window.TransitionFilter;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;

import com.android.internal.logging.InstanceId;
import com.android.internal.util.ScreenshotRequest;
import com.android.internal.view.AppearanceRegion;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.util.Preconditions;
import com.android.quickstep.util.ActiveGestureLog;
import com.android.quickstep.util.AssistUtils;
import com.android.systemui.shared.recents.ISystemUiProxy;
import com.android.systemui.shared.recents.model.ThumbnailData;
import com.android.systemui.shared.system.RecentsAnimationControllerCompat;
import com.android.systemui.shared.system.RecentsAnimationListener;
import com.android.systemui.shared.system.smartspace.ILauncherUnlockAnimationController;
import com.android.systemui.shared.system.smartspace.ISysuiUnlockAnimationController;
import com.android.systemui.shared.system.smartspace.SmartspaceState;
import com.android.systemui.unfold.progress.IUnfoldAnimation;
import com.android.systemui.unfold.progress.IUnfoldTransitionListener;
import com.android.wm.shell.back.IBackAnimation;
import com.android.wm.shell.bubbles.IBubbles;
import com.android.wm.shell.bubbles.IBubblesListener;
import com.android.wm.shell.common.split.SplitScreenConstants.PersistentSnapPosition;
import com.android.wm.shell.desktopmode.IDesktopMode;
import com.android.wm.shell.desktopmode.IDesktopTaskListener;
import com.android.wm.shell.draganddrop.IDragAndDrop;
import com.android.wm.shell.onehanded.IOneHanded;
import com.android.wm.shell.pip.IPip;
import com.android.wm.shell.pip.IPipAnimationListener;
import com.android.wm.shell.recents.IRecentTasks;
import com.android.wm.shell.recents.IRecentTasksListener;
import com.android.wm.shell.splitscreen.ISplitScreen;
import com.android.wm.shell.splitscreen.ISplitScreenListener;
import com.android.wm.shell.splitscreen.ISplitSelectListener;
import com.android.wm.shell.startingsurface.IStartingWindow;
import com.android.wm.shell.startingsurface.IStartingWindowListener;
import com.android.wm.shell.transition.IHomeTransitionListener;
import com.android.wm.shell.transition.IShellTransitions;
import com.android.wm.shell.util.GroupedRecentTaskInfo;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Holds the reference to SystemUI.
 */
public class SystemUiProxy implements ISystemUiProxy {
    private static final String TAG = SystemUiProxy.class.getSimpleName();

    public static final MainThreadInitializedObject<SystemUiProxy> INSTANCE =
            new MainThreadInitializedObject<>(SystemUiProxy::new);

    private static final int MSG_SET_SHELF_HEIGHT = 1;
    private static final int MSG_SET_LAUNCHER_KEEP_CLEAR_AREA_HEIGHT = 2;

    private ISystemUiProxy mSystemUiProxy;
    private IPip mPip;
    private IBubbles mBubbles;
    private ISysuiUnlockAnimationController mSysuiUnlockAnimationController;
    private ISplitScreen mSplitScreen;
    private IOneHanded mOneHanded;
    private IShellTransitions mShellTransitions;
    private IStartingWindow mStartingWindow;
    private IRecentTasks mRecentTasks;
    private IBackAnimation mBackAnimation;
    private IDesktopMode mDesktopMode;
    private IUnfoldAnimation mUnfoldAnimation;
    private final DeathRecipient mSystemUiProxyDeathRecipient = () -> {
        MAIN_EXECUTOR.execute(() -> clearProxy());
    };

    // Save the listeners passed into the proxy since OverviewProxyService may not have been bound
    // yet, and we'll need to set/register these listeners with SysUI when they do.  Note that it is
    // up to the caller to clear the listeners to prevent leaks as these can be held indefinitely
    // in case SysUI needs to rebind.
    private IPipAnimationListener mPipAnimationListener;
    private IBubblesListener mBubblesListener;
    private ISplitScreenListener mSplitScreenListener;
    private ISplitSelectListener mSplitSelectListener;
    private IStartingWindowListener mStartingWindowListener;
    private ILauncherUnlockAnimationController mLauncherUnlockAnimationController;
    private String mLauncherActivityClass;
    private IRecentTasksListener mRecentTasksListener;
    private IUnfoldTransitionListener mUnfoldAnimationListener;
    private IDesktopTaskListener mDesktopTaskListener;
    private final LinkedHashMap<RemoteTransition, TransitionFilter> mRemoteTransitions =
            new LinkedHashMap<>();

    private final List<Runnable> mStateChangeCallbacks = new ArrayList<>();

    private IBinder mOriginalTransactionToken = null;
    private IOnBackInvokedCallback mBackToLauncherCallback;
    private IRemoteAnimationRunner mBackToLauncherRunner;
    private IDragAndDrop mDragAndDrop;
    private IHomeTransitionListener mHomeTransitionListener;

    // Used to dedupe calls to SystemUI
    private int mLastShelfHeight;
    private boolean mLastShelfVisible;

    // Used to dedupe calls to SystemUI
    private int mLastLauncherKeepClearAreaHeight;
    private boolean mLastLauncherKeepClearAreaHeightVisible;

    private final Context mContext;
    private final Handler mAsyncHandler;

    // TODO(141886704): Find a way to remove this
    private int mLastSystemUiStateFlags;

    /**
     * This is a singleton pending intent that is used to start recents via Shell (which is a
     * different process). It is bare-bones, so it's expected that the component and options will
     * be provided via fill-in intent.
     */
    private final PendingIntent mRecentsPendingIntent;

    public SystemUiProxy(Context context) {
        mContext = context;
        mAsyncHandler = new Handler(UI_HELPER_EXECUTOR.getLooper(), this::handleMessageAsync);
        final Intent baseIntent = new Intent().setPackage(mContext.getPackageName());
        final ActivityOptions options = ActivityOptions.makeBasic()
                .setPendingIntentCreatorBackgroundActivityStartMode(
                        ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
        mRecentsPendingIntent = PendingIntent.getActivity(mContext, 0, baseIntent,
                PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT
                        | Intent.FILL_IN_COMPONENT, options.toBundle());
    }

    @Override
    public void onBackPressed() {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.onBackPressed();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onBackPressed", e);
            }
        }
    }

    @Override
    public void onImeSwitcherPressed() {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.onImeSwitcherPressed();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onImeSwitcherPressed", e);
            }
        }
    }

    @Override
    public void setHomeRotationEnabled(boolean enabled) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.setHomeRotationEnabled(enabled);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onBackPressed", e);
            }
        }
    }

    @Override
    public IBinder asBinder() {
        // Do nothing
        return null;
    }

    /**
     * Sets proxy state, including death linkage, various listeners, and other configuration objects
     */
    @MainThread
    public void setProxy(ISystemUiProxy proxy, IPip pip, IBubbles bubbles, ISplitScreen splitScreen,
            IOneHanded oneHanded, IShellTransitions shellTransitions,
            IStartingWindow startingWindow, IRecentTasks recentTasks,
            ISysuiUnlockAnimationController sysuiUnlockAnimationController,
            IBackAnimation backAnimation, IDesktopMode desktopMode,
            IUnfoldAnimation unfoldAnimation, IDragAndDrop dragAndDrop) {
        Preconditions.assertUIThread();
        unlinkToDeath();
        mSystemUiProxy = proxy;
        mPip = pip;
        mBubbles = bubbles;
        mSplitScreen = splitScreen;
        mOneHanded = oneHanded;
        mShellTransitions = shellTransitions;
        mStartingWindow = startingWindow;
        mSysuiUnlockAnimationController = sysuiUnlockAnimationController;
        mRecentTasks = recentTasks;
        mBackAnimation = backAnimation;
        mDesktopMode = desktopMode;
        mUnfoldAnimation = unfoldAnimation;
        mDragAndDrop = dragAndDrop;
        linkToDeath();
        // re-attach the listeners once missing due to setProxy has not been initialized yet.
        setPipAnimationListener(mPipAnimationListener);
        setBubblesListener(mBubblesListener);
        registerSplitScreenListener(mSplitScreenListener);
        registerSplitSelectListener(mSplitSelectListener);
        setHomeTransitionListener(mHomeTransitionListener);
        setStartingWindowListener(mStartingWindowListener);
        setLauncherUnlockAnimationController(
                mLauncherActivityClass, mLauncherUnlockAnimationController);
        new LinkedHashMap<>(mRemoteTransitions).forEach(this::registerRemoteTransition);
        setupTransactionQueue();
        registerRecentTasksListener(mRecentTasksListener);
        setBackToLauncherCallback(mBackToLauncherCallback, mBackToLauncherRunner);
        setUnfoldAnimationListener(mUnfoldAnimationListener);
        setDesktopTaskListener(mDesktopTaskListener);
        setAssistantOverridesRequested(
                AssistUtils.newInstance(mContext).getSysUiAssistOverrideInvocationTypes());
        mStateChangeCallbacks.forEach(Runnable::run);
    }

    /**
     * Clear the proxy to release held resources and turn the majority of its operations into no-ops
     */
    @MainThread
    public void clearProxy() {
        setProxy(null, null, null, null, null, null, null, null, null, null, null, null, null);
    }

    /**
     * Adds a callback to be notified whenever the active state changes
     */
    public void addOnStateChangeListener(Runnable callback) {
        mStateChangeCallbacks.add(callback);
    }

    /**
     * Removes a previously added state change callback
     */
    public void removeOnStateChangeListener(Runnable callback) {
        mStateChangeCallbacks.remove(callback);
    }

    // TODO(141886704): Find a way to remove this
    public void setLastSystemUiStateFlags(int stateFlags) {
        mLastSystemUiStateFlags = stateFlags;
    }

    // TODO(141886704): Find a way to remove this
    public int getLastSystemUiStateFlags() {
        return mLastSystemUiStateFlags;
    }

    public boolean isActive() {
        return mSystemUiProxy != null;
    }

    private void linkToDeath() {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.asBinder().linkToDeath(mSystemUiProxyDeathRecipient, 0 /* flags */);
            } catch (RemoteException e) {
                Log.e(TAG, "Failed to link sysui proxy death recipient");
            }
        }
    }

    private void unlinkToDeath() {
        if (mSystemUiProxy != null) {
            mSystemUiProxy.asBinder().unlinkToDeath(mSystemUiProxyDeathRecipient, 0 /* flags */);
        }
    }

    @Override
    public void startScreenPinning(int taskId) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.startScreenPinning(taskId);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call startScreenPinning", e);
            }
        }
    }

    @Override
    public void onOverviewShown(boolean fromHome) {
        onOverviewShown(fromHome, TAG);
    }

    public void onOverviewShown(boolean fromHome, String tag) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.onOverviewShown(fromHome);
            } catch (RemoteException e) {
                Log.w(tag, "Failed call onOverviewShown from: " + (fromHome ? "home" : "app"), e);
            }
        }
    }

    @MainThread
    @Override
    public void onStatusBarTouchEvent(MotionEvent event) {
        Preconditions.assertUIThread();
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.onStatusBarTouchEvent(event);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onStatusBarTouchEvent with arg: " + event, e);
            }
        }
    }

    @Override
    public void onStatusBarTrackpadEvent(MotionEvent event) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.onStatusBarTrackpadEvent(event);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onStatusBarTrackpadEvent with arg: " + event, e);
            }
        }
    }

    @Override
    public void onAssistantProgress(float progress) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.onAssistantProgress(progress);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onAssistantProgress with progress: " + progress, e);
            }
        }
    }

    @Override
    public void onAssistantGestureCompletion(float velocity) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.onAssistantGestureCompletion(velocity);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onAssistantGestureCompletion", e);
            }
        }
    }

    @Override
    public void startAssistant(Bundle args) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.startAssistant(args);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call startAssistant", e);
            }
        }
    }

    @Override
    public void setAssistantOverridesRequested(int[] invocationTypes) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.setAssistantOverridesRequested(invocationTypes);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setAssistantOverridesRequested", e);
            }
        }
    }

    @Override
    public void animateNavBarLongPress(boolean isTouchDown, boolean shrink, long durationMs) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.animateNavBarLongPress(isTouchDown, shrink, durationMs);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call animateNavBarLongPress", e);
            }
        }
    }

    @Override
    public void notifyAccessibilityButtonClicked(int displayId) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.notifyAccessibilityButtonClicked(displayId);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call notifyAccessibilityButtonClicked", e);
            }
        }
    }

    @Override
    public void notifyAccessibilityButtonLongClicked() {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.notifyAccessibilityButtonLongClicked();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call notifyAccessibilityButtonLongClicked", e);
            }
        }
    }

    @Override
    public void stopScreenPinning() {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.stopScreenPinning();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call stopScreenPinning", e);
            }
        }
    }

    @Override
    public void notifyPrioritizedRotation(int rotation) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.notifyPrioritizedRotation(rotation);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call notifyPrioritizedRotation with arg: " + rotation, e);
            }
        }
    }

    @Override
    public void notifyTaskbarStatus(boolean visible, boolean stashed) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.notifyTaskbarStatus(visible, stashed);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call notifyTaskbarStatus with arg: " +
                        visible + ", " + stashed, e);
            }
        }
    }

    /**
     * NOTE: If called to suspend, caller MUST call this method to also un-suspend
     * @param suspend should be true to stop auto-hide, false to resume normal behavior
     */
    @Override
    public void notifyTaskbarAutohideSuspend(boolean suspend) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.notifyTaskbarAutohideSuspend(suspend);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call notifyTaskbarAutohideSuspend with arg: " +
                        suspend, e);
            }
        }
    }

    @Override
    public void takeScreenshot(ScreenshotRequest request) {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.takeScreenshot(request);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call takeScreenshot");
            }
        }
    }

    @Override
    public void expandNotificationPanel() {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.expandNotificationPanel();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call expandNotificationPanel", e);
            }
        }
    }

    @Override
    public void toggleNotificationPanel() {
        if (mSystemUiProxy != null) {
            try {
                mSystemUiProxy.toggleNotificationPanel();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call toggleNotificationPanel", e);
            }
        }
    }

    //
    // Pip
    //

    /**
     * Sets the shelf height.
     */
    public void setShelfHeight(boolean visible, int shelfHeight) {
        Message.obtain(mAsyncHandler, MSG_SET_SHELF_HEIGHT,
                visible ? 1 : 0 , shelfHeight).sendToTarget();
    }

    @WorkerThread
    private void setShelfHeightAsync(int visibleInt, int shelfHeight) {
        boolean visible = visibleInt != 0;
        boolean changed = visible != mLastShelfVisible || shelfHeight != mLastShelfHeight;
        IPip pip = mPip;
        if (pip != null && changed) {
            mLastShelfVisible = visible;
            mLastShelfHeight = shelfHeight;
            try {
                pip.setShelfHeight(visible, shelfHeight);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setShelfHeight visible: " + visible
                        + " height: " + shelfHeight, e);
            }
        }
    }

    /**
     * Sets the height of the keep clear area that is going to be reported by
     * the Launcher for the Hotseat.
     */
    public void setLauncherKeepClearAreaHeight(boolean visible, int height) {
        Message.obtain(mAsyncHandler, MSG_SET_LAUNCHER_KEEP_CLEAR_AREA_HEIGHT,
                visible ? 1 : 0 , height).sendToTarget();
    }

    @WorkerThread
    private void setLauncherKeepClearAreaHeight(int visibleInt, int height) {
        boolean visible = visibleInt != 0;
        boolean changed = visible != mLastLauncherKeepClearAreaHeightVisible
                || height != mLastLauncherKeepClearAreaHeight;
        IPip pip = mPip;
        if (pip != null && changed) {
            mLastLauncherKeepClearAreaHeightVisible = visible;
            mLastLauncherKeepClearAreaHeight = height;
            try {
                pip.setLauncherKeepClearAreaHeight(visible, height);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setLauncherKeepClearAreaHeight visible: " + visible
                        + " height: " + height, e);
            }
        }
    }

    /**
     * Sets listener to get pip animation callbacks.
     */
    public void setPipAnimationListener(IPipAnimationListener listener) {
        if (mPip != null) {
            try {
                mPip.setPipAnimationListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setPinnedStackAnimationListener", e);
            }
        }
        mPipAnimationListener = listener;
    }

    /**
     * @return Destination bounds of auto-pip animation, {@code null} if the animation is not ready.
     */
    @Nullable
    public Rect startSwipePipToHome(ComponentName componentName, ActivityInfo activityInfo,
            PictureInPictureParams pictureInPictureParams, int launcherRotation,
            Rect hotseatKeepClearArea) {
        if (mPip != null) {
            try {
                return mPip.startSwipePipToHome(componentName, activityInfo,
                        pictureInPictureParams, launcherRotation, hotseatKeepClearArea);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call startSwipePipToHome", e);
            }
        }
        return null;
    }

    /**
     * Notifies WM Shell that launcher has finished the preparation of the animation for swipe to
     * home. WM Shell can choose to fade out the overlay when entering PIP is finished, and WM Shell
     * should be responsible for cleaning up the overlay.
     */
    public void stopSwipePipToHome(int taskId, ComponentName componentName, Rect destinationBounds,
            SurfaceControl overlay) {
        if (mPip != null) {
            try {
                mPip.stopSwipePipToHome(taskId, componentName, destinationBounds, overlay);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call stopSwipePipToHome");
            }
        }
    }

    /**
     * Notifies WM Shell that launcher has aborted all the animation for swipe to home. WM Shell
     * can use this callback to clean up its internal states.
     */
    public void abortSwipePipToHome(int taskId, ComponentName componentName) {
        if (mPip != null) {
            try {
                mPip.abortSwipePipToHome(taskId, componentName);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call abortSwipePipToHome");
            }
        }
    }

    /**
     * Sets the next pip animation type to be the alpha animation.
     */
    public void setPipAnimationTypeToAlpha() {
        if (mPip != null) {
            try {
                mPip.setPipAnimationTypeToAlpha();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setPipAnimationTypeToAlpha", e);
            }
        }
    }

    /**
     * Sets the app icon size in pixel used by Launcher all apps.
     */
    public void setLauncherAppIconSize(int iconSizePx) {
        if (mPip != null) {
            try {
                mPip.setLauncherAppIconSize(iconSizePx);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setLauncherAppIconSize", e);
            }
        }
    }

    //
    // Bubbles
    //

    /**
     * Sets the listener to be notified of bubble state changes.
     */
    public void setBubblesListener(IBubblesListener listener) {
        if (mBubbles != null) {
            try {
                if (mBubblesListener != null) {
                    // Clear out any previous listener
                    mBubbles.unregisterBubbleListener(mBubblesListener);
                }
                if (listener != null) {
                    mBubbles.registerBubbleListener(listener);
                }
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call registerBubblesListener");
            }
        }
        mBubblesListener = listener;
    }

    /**
     * Tells SysUI to show the bubble with the provided key.
     * @param key the key of the bubble to show.
     * @param bubbleBarOffsetX the offset of the bubble bar from the edge of the screen on the X
     *                         axis.
     * @param bubbleBarOffsetY the offset of the bubble bar from the edge of the screen on the Y
     *                         axis.
     */
    public void showBubble(String key, int bubbleBarOffsetX, int bubbleBarOffsetY) {
        if (mBubbles != null) {
            try {
                mBubbles.showBubble(key, bubbleBarOffsetX, bubbleBarOffsetY);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call showBubble");
            }
        }
    }

    /**
     * Tells SysUI to remove the bubble with the provided key.
     * @param key the key of the bubble to show.
     */
    public void removeBubble(String key) {
        if (mBubbles == null) return;
        try {
            mBubbles.removeBubble(key);
        } catch (RemoteException e) {
            Log.w(TAG, "Failed call removeBubble");
        }
    }

    /**
     * Tells SysUI to remove all bubbles.
     */
    public void removeAllBubbles() {
        if (mBubbles == null) return;
        try {
            mBubbles.removeAllBubbles();
        } catch (RemoteException e) {
            Log.w(TAG, "Failed call removeAllBubbles");
        }
    }

    /**
     * Tells SysUI to collapse the bubbles.
     */
    public void collapseBubbles() {
        if (mBubbles != null) {
            try {
                mBubbles.collapseBubbles();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call collapseBubbles");
            }
        }
    }

    /**
     * Tells SysUI when the bubble is being dragged.
     * Should be called only when the bubble bar is expanded.
     * @param bubbleKey the key of the bubble to collapse/expand
     * @param isBeingDragged whether the bubble is being dragged
     */
    public void onBubbleDrag(@Nullable String bubbleKey, boolean isBeingDragged) {
        if (mBubbles == null) return;
        try {
            mBubbles.onBubbleDrag(bubbleKey, isBeingDragged);
        } catch (RemoteException e) {
            Log.w(TAG, "Failed call onBubbleDrag");
        }
    }

    /**
     * Tells SysUI to show user education relative to the reference point provided.
     * @param position the bubble bar top center position in Screen coordinates.
     */
    public void showUserEducation(Point position) {
        try {
            mBubbles.showUserEducation(position.x, position.y);
        } catch (RemoteException e) {
            Log.w(TAG, "Failed call showUserEducation");
        }
    }

    //
    // Splitscreen
    //

    public void registerSplitScreenListener(ISplitScreenListener listener) {
        if (mSplitScreen != null) {
            try {
                mSplitScreen.registerSplitScreenListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call registerSplitScreenListener");
            }
        }
        mSplitScreenListener = listener;
    }

    public void unregisterSplitScreenListener(ISplitScreenListener listener) {
        if (mSplitScreen != null) {
            try {
                mSplitScreen.unregisterSplitScreenListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call unregisterSplitScreenListener");
            }
        }
        mSplitScreenListener = null;
    }

    public void registerSplitSelectListener(ISplitSelectListener listener) {
        if (mSplitScreen != null) {
            try {
                mSplitScreen.registerSplitSelectListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call registerSplitSelectListener");
            }
        }
        mSplitSelectListener = listener;
    }

    public void unregisterSplitSelectListener(ISplitSelectListener listener) {
        if (mSplitScreen != null) {
            try {
                mSplitScreen.unregisterSplitSelectListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call unregisterSplitSelectListener");
            }
        }
        mSplitSelectListener = null;
    }

    /** Start multiple tasks in split-screen simultaneously. */
    public void startTasks(int taskId1, Bundle options1, int taskId2, Bundle options2,
            @StagePosition int splitPosition, @PersistentSnapPosition int snapPosition,
            RemoteTransition remoteTransition, InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startTasks(taskId1, options1, taskId2, options2, splitPosition,
                        snapPosition, remoteTransition, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage("startTasks", "RemoteException"), e);
            }
        }
    }

    public void startIntentAndTask(PendingIntent pendingIntent, int userId1, Bundle options1,
            int taskId, Bundle options2, @StagePosition int splitPosition,
            @PersistentSnapPosition int snapPosition, RemoteTransition remoteTransition,
            InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startIntentAndTask(pendingIntent, userId1, options1, taskId, options2,
                        splitPosition, snapPosition, remoteTransition, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage("startIntentAndTask", "RemoteException"), e);
            }
        }
    }

    public void startIntents(PendingIntent pendingIntent1, int userId1,
            @Nullable ShortcutInfo shortcutInfo1, Bundle options1, PendingIntent pendingIntent2,
            int userId2, @Nullable ShortcutInfo shortcutInfo2, Bundle options2,
            @StagePosition int splitPosition, @PersistentSnapPosition int snapPosition,
            RemoteTransition remoteTransition, InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startIntents(pendingIntent1, userId1, shortcutInfo1, options1,
                        pendingIntent2, userId2, shortcutInfo2, options2, splitPosition,
                        snapPosition, remoteTransition, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage("startIntents", "RemoteException"), e);
            }
        }
    }

    public void startShortcutAndTask(ShortcutInfo shortcutInfo, Bundle options1, int taskId,
            Bundle options2, @StagePosition int splitPosition,
            @PersistentSnapPosition int snapPosition, RemoteTransition remoteTransition,
            InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startShortcutAndTask(shortcutInfo, options1, taskId, options2,
                        splitPosition, snapPosition, remoteTransition, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage("startShortcutAndTask", "RemoteException"), e);
            }
        }
    }

    /**
     * Start multiple tasks in split-screen simultaneously.
     */
    public void startTasksWithLegacyTransition(int taskId1, Bundle options1, int taskId2,
            Bundle options2, @StagePosition int splitPosition,
            @PersistentSnapPosition int snapPosition, RemoteAnimationAdapter adapter,
            InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startTasksWithLegacyTransition(taskId1, options1, taskId2, options2,
                        splitPosition, snapPosition, adapter, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage(
                        "startTasksWithLegacyTransition", "RemoteException"), e);
            }
        }
    }

    public void startIntentAndTaskWithLegacyTransition(PendingIntent pendingIntent, int userId1,
            Bundle options1, int taskId, Bundle options2, @StagePosition int splitPosition,
            @PersistentSnapPosition int snapPosition, RemoteAnimationAdapter adapter,
            InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startIntentAndTaskWithLegacyTransition(pendingIntent, userId1,
                        options1, taskId, options2, splitPosition, snapPosition, adapter,
                        instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage(
                        "startIntentAndTaskWithLegacyTransition", "RemoteException"), e);
            }
        }
    }

    public void startShortcutAndTaskWithLegacyTransition(ShortcutInfo shortcutInfo, Bundle options1,
            int taskId, Bundle options2, @StagePosition int splitPosition,
            @PersistentSnapPosition int snapPosition, RemoteAnimationAdapter adapter,
            InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startShortcutAndTaskWithLegacyTransition(shortcutInfo, options1,
                        taskId, options2, splitPosition, snapPosition, adapter, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage(
                        "startShortcutAndTaskWithLegacyTransition", "RemoteException"), e);
            }
        }
    }

    /**
     * Starts a pair of intents or shortcuts in split-screen using legacy transition. Passing a
     * non-null shortcut info means to start the app as a shortcut.
     */
    public void startIntentsWithLegacyTransition(PendingIntent pendingIntent1, int userId1,
            @Nullable ShortcutInfo shortcutInfo1, @Nullable Bundle options1,
            PendingIntent pendingIntent2, int userId2, @Nullable ShortcutInfo shortcutInfo2,
            @Nullable Bundle options2, @StagePosition int sidePosition,
            @PersistentSnapPosition int snapPosition, RemoteAnimationAdapter adapter,
            InstanceId instanceId) {
        if (mSystemUiProxy != null) {
            try {
                mSplitScreen.startIntentsWithLegacyTransition(pendingIntent1, userId1,
                        shortcutInfo1, options1, pendingIntent2, userId2, shortcutInfo2, options2,
                        sidePosition, snapPosition, adapter, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage(
                        "startIntentsWithLegacyTransition", "RemoteException"), e);
            }
        }
    }

    public void startShortcut(String packageName, String shortcutId, int position,
            Bundle options, UserHandle user, InstanceId instanceId) {
        if (mSplitScreen != null) {
            try {
                mSplitScreen.startShortcut(packageName, shortcutId, position, options,
                        user, instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage("startShortcut", "RemoteException"), e);
            }
        }
    }

    public void startIntent(PendingIntent intent, int userId, Intent fillInIntent, int position,
            Bundle options, InstanceId instanceId) {
        if (mSplitScreen != null) {
            try {
                mSplitScreen.startIntent(intent, userId, fillInIntent, position, options,
                        instanceId);
            } catch (RemoteException e) {
                Log.w(TAG, splitFailureMessage("startIntent", "RemoteException"), e);
            }
        }
    }

    public void removeFromSideStage(int taskId) {
        if (mSplitScreen != null) {
            try {
                mSplitScreen.removeFromSideStage(taskId);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call removeFromSideStage");
            }
        }
    }

    /**
     * Call this when going to recents so that shell can set-up and provide appropriate leashes
     * for animation (eg. DividerBar).
     *
     * @return RemoteAnimationTargets of windows that need to animate but only exist in shell.
     */
    @Nullable
    public RemoteAnimationTarget[] onGoingToRecentsLegacy(RemoteAnimationTarget[] apps) {
        if (!TaskAnimationManager.ENABLE_SHELL_TRANSITIONS && mSplitScreen != null) {
            try {
                return mSplitScreen.onGoingToRecentsLegacy(apps);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onGoingToRecentsLegacy");
            }
        }
        return null;
    }

    @Nullable
    public RemoteAnimationTarget[] onStartingSplitLegacy(RemoteAnimationTarget[] apps) {
        if (mSplitScreen != null) {
            try {
                return mSplitScreen.onStartingSplitLegacy(apps);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onStartingSplitLegacy");
            }
        }
        return null;
    }

    //
    // One handed
    //

    public void startOneHandedMode() {
        if (mOneHanded != null) {
            try {
                mOneHanded.startOneHanded();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call startOneHandedMode", e);
            }
        }
    }

    public void stopOneHandedMode() {
        if (mOneHanded != null) {
            try {
                mOneHanded.stopOneHanded();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call stopOneHandedMode", e);
            }
        }
    }

    //
    // Remote transitions
    //

    public void registerRemoteTransition(
            RemoteTransition remoteTransition, TransitionFilter filter) {
        if (mShellTransitions != null) {
            try {
                mShellTransitions.registerRemote(filter, remoteTransition);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call registerRemoteTransition");
            }
        }
        if (!mRemoteTransitions.containsKey(remoteTransition)) {
            mRemoteTransitions.put(remoteTransition, filter);
        }
    }

    public void unregisterRemoteTransition(RemoteTransition remoteTransition) {
        if (mShellTransitions != null) {
            try {
                mShellTransitions.unregisterRemote(remoteTransition);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call registerRemoteTransition");
            }
        }
        mRemoteTransitions.remove(remoteTransition);
    }

    public void setHomeTransitionListener(IHomeTransitionListener listener) {
        if (!FeatureFlags.enableHomeTransitionListener()) {
            return;
        }

        mHomeTransitionListener = listener;

        if (mShellTransitions != null) {
            try {
                mShellTransitions.setHomeTransitionListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setHomeTransitionListener", e);
            }
        } else  {
            Log.w(TAG, "Unable to call setHomeTransitionListener because ShellTransitions is null");
        }
    }

    /**
     * Returns a surface which can be used to attach overlays to home task or null if
     * the task doesn't exist or sysui is not connected
     */
    @Nullable
    public SurfaceControl getHomeTaskOverlayContainer() {
        // Use a local reference as this method can be called on a worker thread, which can lead
        // to NullPointer exceptions if mShellTransitions is modified on the main thread.
        IShellTransitions shellTransitions = mShellTransitions;
        if (shellTransitions != null) {
            try {
                return mShellTransitions.getHomeTaskOverlayContainer();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call getOverlayContainerForTask", e);
            }
        }
        return null;
    }

    /**
     * Use SystemUI's transaction-queue instead of Launcher's independent one. This is necessary
     * if Launcher and SystemUI need to coordinate transactions (eg. for shell transitions).
     */
    public void shareTransactionQueue() {
        if (mOriginalTransactionToken == null) {
            mOriginalTransactionToken = SurfaceControl.Transaction.getDefaultApplyToken();
        }
        setupTransactionQueue();
    }

    /**
     * Switch back to using Launcher's independent transaction queue.
     */
    public void unshareTransactionQueue() {
        if (mOriginalTransactionToken == null) {
            return;
        }
        SurfaceControl.Transaction.setDefaultApplyToken(mOriginalTransactionToken);
        mOriginalTransactionToken = null;
    }

    private void setupTransactionQueue() {
        if (mOriginalTransactionToken == null) {
            return;
        }
        if (mShellTransitions == null) {
            SurfaceControl.Transaction.setDefaultApplyToken(mOriginalTransactionToken);
            return;
        }
        final IBinder shellApplyToken;
        try {
            shellApplyToken = mShellTransitions.getShellApplyToken();
        } catch (RemoteException e) {
            Log.e(TAG, "Error getting Shell's apply token", e);
            return;
        }
        if (shellApplyToken == null) {
            Log.e(TAG, "Didn't receive apply token from Shell");
            return;
        }
        SurfaceControl.Transaction.setDefaultApplyToken(shellApplyToken);
    }

    //
    // Starting window
    //

    /**
     * Sets listener to get callbacks when launching a task.
     */
    public void setStartingWindowListener(IStartingWindowListener listener) {
        if (mStartingWindow != null) {
            try {
                mStartingWindow.setStartingWindowListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setStartingWindowListener", e);
            }
        }
        mStartingWindowListener = listener;
    }

    //
    // SmartSpace transitions
    //

    /**
     * Sets the instance of {@link ILauncherUnlockAnimationController} that System UI should use to
     * control the launcher side of the unlock animation. This will also cause us to dispatch the
     * current state of the smartspace to System UI (this will subsequently happen if the state
     * changes).
     */
    public void setLauncherUnlockAnimationController(
            String activityClass, ILauncherUnlockAnimationController controller) {
        if (mSysuiUnlockAnimationController != null) {
            try {
                mSysuiUnlockAnimationController.setLauncherUnlockController(
                        activityClass, controller);
                if (controller != null) {
                    controller.dispatchSmartspaceStateToSysui();
                }
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setLauncherUnlockAnimationController", e);
            }
        }
        mLauncherActivityClass = activityClass;
        mLauncherUnlockAnimationController = controller;
    }

    /**
     * Tells System UI that the Launcher's smartspace state has been updated, so that it can prepare
     * the unlock animation accordingly.
     */
    public void notifySysuiSmartspaceStateUpdated(SmartspaceState state) {
        if (mSysuiUnlockAnimationController != null) {
            try {
                mSysuiUnlockAnimationController.onLauncherSmartspaceStateUpdated(state);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call notifySysuiSmartspaceStateUpdated", e);
                e.printStackTrace();
            }
        }
    }

    //
    // Recents
    //

    public void registerRecentTasksListener(IRecentTasksListener listener) {
        if (mRecentTasks != null) {
            try {
                mRecentTasks.registerRecentTasksListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call registerRecentTasksListener", e);
            }
        }
        mRecentTasksListener = listener;
    }

    public void unregisterRecentTasksListener(IRecentTasksListener listener) {
        if (mRecentTasks != null) {
            try {
                mRecentTasks.unregisterRecentTasksListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call unregisterRecentTasksListener");
            }
        }
        mRecentTasksListener = null;
    }

    //
    // Back navigation transitions
    //

    /** Sets the launcher {@link android.window.IOnBackInvokedCallback} to shell */
    public void setBackToLauncherCallback(IOnBackInvokedCallback callback,
            IRemoteAnimationRunner runner) {
        mBackToLauncherCallback = callback;
        mBackToLauncherRunner = runner;
        if (mBackAnimation == null || mBackToLauncherCallback == null) {
            return;
        }
        try {
            mBackAnimation.setBackToLauncherCallback(callback, runner);
        } catch (RemoteException | SecurityException e) {
            Log.e(TAG, "Failed call setBackToLauncherCallback", e);
        }
    }

    /** Clears the previously registered {@link IOnBackInvokedCallback}.
     *
     * @param callback The previously registered callback instance.
     */
    public void clearBackToLauncherCallback(IOnBackInvokedCallback callback) {
        if (mBackToLauncherCallback != callback) {
            return;
        }
        mBackToLauncherCallback = null;
        mBackToLauncherRunner = null;
        if (mBackAnimation == null) {
            return;
        }
        try {
            mBackAnimation.clearBackToLauncherCallback();
        } catch (RemoteException e) {
            Log.e(TAG, "Failed call clearBackToLauncherCallback", e);
        }
    }

    /**
     * Called when the status bar color needs to be customized when back navigation.
     */
    public void customizeStatusBarAppearance(AppearanceRegion appearance) {
        if (mBackAnimation == null) {
            return;
        }
        try {
            mBackAnimation.customizeStatusBarAppearance(appearance);
        } catch (RemoteException e) {
            Log.e(TAG, "Failed call useLauncherSysBarFlags", e);
        }
    }

    public ArrayList<GroupedRecentTaskInfo> getRecentTasks(int numTasks, int userId) {
        if (mRecentTasks == null) {
            Log.w(TAG, "getRecentTasks() failed due to null mRecentTasks");
            return new ArrayList<>();
        }
        try {
            final GroupedRecentTaskInfo[] rawTasks = mRecentTasks.getRecentTasks(numTasks,
                    RECENT_IGNORE_UNAVAILABLE, userId);
            if (rawTasks == null) {
                return new ArrayList<>();
            }
            return new ArrayList<>(Arrays.asList(rawTasks));
        } catch (RemoteException e) {
            Log.w(TAG, "Failed call getRecentTasks", e);
            return new ArrayList<>();
        }
    }

    /**
     * Gets the set of running tasks.
     */
    public ArrayList<ActivityManager.RunningTaskInfo> getRunningTasks(int numTasks) {
        if (mRecentTasks != null
                && mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC)) {
            try {
                return new ArrayList<>(Arrays.asList(mRecentTasks.getRunningTasks(numTasks)));
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call getRunningTasks", e);
            }
        }
        return new ArrayList<>();
    }

    private boolean handleMessageAsync(Message msg) {
        switch (msg.what) {
            case MSG_SET_SHELF_HEIGHT:
                setShelfHeightAsync(msg.arg1, msg.arg2);
                return true;
            case MSG_SET_LAUNCHER_KEEP_CLEAR_AREA_HEIGHT:
                setLauncherKeepClearAreaHeight(msg.arg1, msg.arg2);
                return true;
        }

        return false;
    }

    //
    // Desktop Mode
    //

    /** Call shell to show all apps active on the desktop */
    public void showDesktopApps(int displayId, @Nullable RemoteTransition transition) {
        if (mDesktopMode != null) {
            try {
                mDesktopMode.showDesktopApps(displayId, transition);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call showDesktopApps", e);
            }
        }
    }

    /** Call shell to stash desktop apps */
    public void stashDesktopApps(int displayId) {
        if (mDesktopMode != null) {
            try {
                mDesktopMode.stashDesktopApps(displayId);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call stashDesktopApps", e);
            }
        }
    }

    /** Call shell to hide desktop apps that may be stashed */
    public void hideStashedDesktopApps(int displayId) {
        if (mDesktopMode != null) {
            try {
                mDesktopMode.hideStashedDesktopApps(displayId);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call hideStashedDesktopApps", e);
            }
        }
    }

    /**
     * If task with the given id is on the desktop, bring it to front
     */
    public void showDesktopApp(int taskId) {
        if (mDesktopMode != null) {
            try {
                mDesktopMode.showDesktopApp(taskId);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call showDesktopApp", e);
            }
        }
    }

    /** Call shell to get number of visible freeform tasks */
    public int getVisibleDesktopTaskCount(int displayId) {
        if (mDesktopMode != null) {
            try {
                return mDesktopMode.getVisibleTaskCount(displayId);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call getVisibleDesktopTaskCount", e);
            }
        }
        return 0;
    }

    /** Set a listener on shell to get updates about desktop task state */
    public void setDesktopTaskListener(@Nullable IDesktopTaskListener listener) {
        mDesktopTaskListener = listener;
        if (mDesktopMode != null) {
            try {
                mDesktopMode.setTaskListener(listener);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call setDesktopTaskListener", e);
            }
        }
    }

    /** Perform cleanup transactions after animation to split select is complete */
    public void onDesktopSplitSelectAnimComplete(ActivityManager.RunningTaskInfo taskInfo) {
        if (mDesktopMode != null) {
            try {
                mDesktopMode.onDesktopSplitSelectAnimComplete(taskInfo);
            } catch (RemoteException e) {
                Log.w(TAG, "Failed call onDesktopSplitSelectAnimComplete", e);
            }
        }
    }

    //
    // Unfold transition
    //

    /** Sets the unfold animation lister to sysui. */
    public void setUnfoldAnimationListener(IUnfoldTransitionListener callback) {
        mUnfoldAnimationListener = callback;
        if (mUnfoldAnimation == null) {
            return;
        }
        try {
            Log.d(TAG, "Registering unfold animation receiver");
            mUnfoldAnimation.setListener(callback);
        } catch (RemoteException e) {
            Log.e(TAG, "Failed call setUnfoldAnimationListener", e);
        }
    }

    //
    // Recents
    //

    /**
     * Starts the recents activity. The caller should manage the thread on which this is called.
     */
    public boolean startRecentsActivity(Intent intent, ActivityOptions options,
            RecentsAnimationListener listener) {
        if (mRecentTasks == null) {
            ActiveGestureLog.INSTANCE.addLog("Null mRecentTasks", RECENT_TASKS_MISSING);
            return false;
        }
        final IRecentsAnimationRunner runner = new IRecentsAnimationRunner.Stub() {
            @Override
            public void onAnimationStart(IRecentsAnimationController controller,
                    RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers,
                    Rect homeContentInsets, Rect minimizedHomeBounds, Bundle extras) {
                // Aidl bundles need to explicitly set class loader
                // https://developer.android.com/guide/components/aidl#Bundles
                if (extras != null) {
                    extras.setClassLoader(getClass().getClassLoader());
                }
                listener.onAnimationStart(new RecentsAnimationControllerCompat(controller), apps,
                        wallpapers, homeContentInsets, minimizedHomeBounds, extras);
            }

            @Override
            public void onAnimationCanceled(int[] taskIds, TaskSnapshot[] taskSnapshots) {
                listener.onAnimationCanceled(
                        ThumbnailData.wrap(taskIds, taskSnapshots));
            }

            @Override
            public void onTasksAppeared(RemoteAnimationTarget[] apps) {
                listener.onTasksAppeared(apps);
            }
        };
        final Bundle optsBundle = options.toBundle();
        try {
            mRecentTasks.startRecentsTransition(mRecentsPendingIntent, intent, optsBundle,
                    mContext.getIApplicationThread(), runner);
            return true;
        } catch (RemoteException e) {
            Log.e(TAG, "Error starting recents via shell", e);
            return false;
        }
    }

    //
    // Drag and drop
    //

    /**
     * For testing purposes.  Returns `true` only if the shell drop target has shown and
     * drawn and is ready to handle drag events and the subsequent drop.
     */
    public boolean isDragAndDropReady() {
        if (mDragAndDrop == null) {
            return false;
        }
        try {
            return mDragAndDrop.isReadyToHandleDrag();
        } catch (RemoteException e) {
            Log.e(TAG, "Error querying drag state", e);
            return false;
        }
    }

    public void dump(PrintWriter pw) {
        pw.println(TAG + ":");

        pw.println("\tmSystemUiProxy=" + mSystemUiProxy);
        pw.println("\tmPip=" + mPip);
        pw.println("\tmPipAnimationListener=" + mPipAnimationListener);
        pw.println("\tmBubbles=" + mBubbles);
        pw.println("\tmBubblesListener=" + mBubblesListener);
        pw.println("\tmSplitScreen=" + mSplitScreen);
        pw.println("\tmSplitScreenListener=" + mSplitScreenListener);
        pw.println("\tmSplitSelectListener=" + mSplitSelectListener);
        pw.println("\tmOneHanded=" + mOneHanded);
        pw.println("\tmShellTransitions=" + mShellTransitions);
        pw.println("\tmHomeTransitionListener=" + mHomeTransitionListener);
        pw.println("\tmStartingWindow=" + mStartingWindow);
        pw.println("\tmStartingWindowListener=" + mStartingWindowListener);
        pw.println("\tmSysuiUnlockAnimationController=" + mSysuiUnlockAnimationController);
        pw.println("\tmLauncherActivityClass=" + mLauncherActivityClass);
        pw.println("\tmLauncherUnlockAnimationController=" + mLauncherUnlockAnimationController);
        pw.println("\tmRecentTasks=" + mRecentTasks);
        pw.println("\tmRecentTasksListener=" + mRecentTasksListener);
        pw.println("\tmBackAnimation=" + mBackAnimation);
        pw.println("\tmBackToLauncherCallback=" + mBackToLauncherCallback);
        pw.println("\tmBackToLauncherRunner=" + mBackToLauncherRunner);
        pw.println("\tmDesktopMode=" + mDesktopMode);
        pw.println("\tmDesktopTaskListener=" + mDesktopTaskListener);
        pw.println("\tmUnfoldAnimation=" + mUnfoldAnimation);
        pw.println("\tmUnfoldAnimationListener=" + mUnfoldAnimationListener);
        pw.println("\tmDragAndDrop=" + mDragAndDrop);
    }
}