PhoneWindowManager.java revision 4911787249e7bed96d5a1fdcd689e9823b50c758
1e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project/*
2e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * Copyright (C) 2006 The Android Open Source Project
3e9629bad30a9f478b336ab46b8e6e02f7f87af46Evan Chu *
4e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * Licensed under the Apache License, Version 2.0 (the "License");
5e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * you may not use this file except in compliance with the License.
6e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * You may obtain a copy of the License at
7e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project *
8e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project *      http://www.apache.org/licenses/LICENSE-2.0
9e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project *
10e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * Unless required by applicable law or agreed to in writing, software
11e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * distributed under the License is distributed on an "AS IS" BASIS,
12e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * See the License for the specific language governing permissions and
14e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * limitations under the License.
15e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project */
16e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project
17e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectpackage com.android.server.policy;
18e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project
19e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
20e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
21e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
22e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.content.pm.PackageManager.FEATURE_TELEVISION;
23e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.content.pm.PackageManager.FEATURE_WATCH;
24e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.content.res.Configuration.UI_MODE_TYPE_CAR;
25e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.content.res.Configuration.UI_MODE_TYPE_MASK;
26e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.view.WindowManager.LayoutParams.*;
27e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.view.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_COVERED;
286fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport static android.view.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_COVER_ABSENT;
29e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.view.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_UNCOVERED;
30e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT;
31e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED;
32e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
33e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project
34e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.ActivityManager;
35e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.ActivityManagerInternal;
36e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.ActivityManagerInternal.SleepToken;
37e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.ActivityManagerNative;
38e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.AppOpsManager;
39e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.IUiModeManager;
40e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.ProgressDialog;
41e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.app.SearchManager;
426fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.app.StatusBarManager;
436fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.app.UiModeManager;
446fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.ActivityNotFoundException;
456fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.BroadcastReceiver;
466fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.ComponentName;
476fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.ContentResolver;
486fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.Context;
496fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.Intent;
506fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.IntentFilter;
516fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.ServiceConnection;
526fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.pm.ActivityInfo;
536fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.pm.PackageManager;
54e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.content.pm.ResolveInfo;
556fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.res.CompatibilityInfo;
566fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.content.res.Configuration;
57e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.content.res.Resources;
58e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.database.ContentObserver;
59e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.graphics.PixelFormat;
60e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.graphics.Rect;
61e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.hardware.hdmi.HdmiControlManager;
62e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.hardware.hdmi.HdmiPlaybackClient;
63e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.hardware.hdmi.HdmiPlaybackClient.OneTouchPlayCallback;
64e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.media.AudioAttributes;
65e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.media.AudioManager;
66e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.media.AudioSystem;
67e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.media.IAudioService;
68e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.media.Ringtone;
696fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.media.RingtoneManager;
706fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.media.session.MediaSessionLegacyHelper;
71e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.Binder;
726fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.os.Bundle;
73e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.Debug;
746fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.os.FactoryTest;
756fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.os.Handler;
766fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.os.IBinder;
776fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.os.IDeviceIdleController;
78e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.Looper;
79e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.Message;
80e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.Messenger;
81e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.PowerManager;
82e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.PowerManagerInternal;
83e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.Process;
84e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.RemoteException;
85e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.ServiceManager;
86e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.SystemClock;
87e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.SystemProperties;
88e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.UEventObserver;
89e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.os.UserHandle;
906fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.os.Vibrator;
916fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.provider.MediaStore;
926fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.provider.Settings;
936fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.service.dreams.DreamManagerInternal;
946fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.service.dreams.DreamService;
956fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.service.dreams.IDreamManager;
966fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.speech.RecognizerIntent;
976fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.telecom.TelecomManager;
98e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.util.DisplayMetrics;
996fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.util.EventLog;
1006fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.util.Log;
101e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.util.Slog;
102e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.util.SparseArray;
103e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.Display;
104e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.Gravity;
105e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.HapticFeedbackConstants;
106e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.IApplicationToken;
107e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.IWindowManager;
108e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.InputChannel;
109e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.InputDevice;
110e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.InputEvent;
111e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.InputEventReceiver;
112e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.KeyCharacterMap;
1136fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.KeyCharacterMap.FallbackAction;
1146fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.KeyEvent;
1156fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.MotionEvent;
1166fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.Surface;
1176fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.View;
1186fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.ViewConfiguration;
1196fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.WindowManager;
1206fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.WindowManagerGlobal;
1216fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.WindowManagerInternal;
1226fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.WindowManagerPolicy;
1236fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.accessibility.AccessibilityEvent;
1246fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.accessibility.AccessibilityManager;
125e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport android.view.animation.Animation;
1266fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.animation.AnimationSet;
1276fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport android.view.animation.AnimationUtils;
1286fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport com.android.internal.R;
1296fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport com.android.internal.logging.MetricsLogger;
1306fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport com.android.internal.policy.PhoneWindow;
131e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport com.android.internal.statusbar.IStatusBarService;
1326fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport com.android.internal.util.ScreenShapeHelper;
133e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport com.android.internal.widget.PointerLocationView;
1346fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoiimport com.android.server.GestureLauncherService;
135e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport com.android.server.LocalServices;
136e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport com.android.server.policy.keyguard.KeyguardServiceDelegate;
137e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport com.android.server.policy.keyguard.KeyguardServiceDelegate.DrawnListener;
138e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project
139e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport java.io.File;
140e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport java.io.FileReader;
141e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport java.io.IOException;
142e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport java.io.PrintWriter;
143e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport java.util.HashSet;
144e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectimport java.util.List;
145e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project
146e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project/**
1476fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi * WindowManagerPolicy implementation for the Android phone UI.  This
1486fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi * introduces a new method suffix, Lp, for an internal lock of the
149e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * PhoneWindowManager.  This is used to protect some internal state, and
1506fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi * can be acquired with either the Lw and Li lock held, so has the restrictions
151e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project * of both of those when held.
1526fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi */
153e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Projectpublic class PhoneWindowManager implements WindowManagerPolicy {
1546fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final String TAG = "WindowManager";
155e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final boolean DEBUG = false;
1566fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final boolean localLOGV = false;
1576fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final boolean DEBUG_INPUT = false;
1586fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final boolean DEBUG_KEYGUARD = false;
159e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final boolean DEBUG_LAYOUT = false;
160e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final boolean DEBUG_STARTING_WINDOW = false;
161e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final boolean DEBUG_WAKEUP = false;
162e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final boolean SHOW_STARTING_ANIMATIONS = true;
163e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
164e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project
165e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    // Whether to allow dock apps with METADATA_DOCK_HOME to temporarily take over the Home key.
166e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    // No longer recommended for desk docks;
167e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final boolean ENABLE_DESK_DOCK_HOME_CAPTURE = false;
168e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project
169e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final int SHORT_PRESS_POWER_NOTHING = 0;
170e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final int SHORT_PRESS_POWER_GO_TO_SLEEP = 1;
1716fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP = 2;
1726fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP_AND_GO_HOME = 3;
1736fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int SHORT_PRESS_POWER_GO_HOME = 4;
1746fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi
1756fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int LONG_PRESS_POWER_NOTHING = 0;
1766fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
1776fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int LONG_PRESS_POWER_SHUT_OFF = 2;
1786fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM = 3;
1796fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi
1806fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int MULTI_PRESS_POWER_NOTHING = 0;
1816fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int MULTI_PRESS_POWER_THEATER_MODE = 1;
1826fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int MULTI_PRESS_POWER_BRIGHTNESS_BOOST = 2;
1836fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi
1846fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    // These need to match the documentation/constant in
185e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    // core/res/res/values/config.xml
1866fca02d5010de7bd31d83b853c32138021da5f29Ruchi Kandoi    static final int LONG_PRESS_HOME_NOTHING = 0;
187e9df6ba5a8fcccf306a80b1670b423be8fe7746The Android Open Source Project    static final int LONG_PRESS_HOME_RECENT_SYSTEM_UI = 1;
188    static final int LONG_PRESS_HOME_ASSIST = 2;
189    static final int LONG_PRESS_HOME_PICTURE_IN_PICTURE = 3;
190    static final int LAST_LONG_PRESS_HOME_BEHAVIOR = LONG_PRESS_HOME_PICTURE_IN_PICTURE;
191
192    static final int DOUBLE_TAP_HOME_NOTHING = 0;
193    static final int DOUBLE_TAP_HOME_RECENT_SYSTEM_UI = 1;
194
195    static final int SHORT_PRESS_WINDOW_NOTHING = 0;
196    static final int SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE = 1;
197
198    static final int SHORT_PRESS_SLEEP_GO_TO_SLEEP = 0;
199    static final int SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME = 1;
200
201    static final int APPLICATION_MEDIA_SUBLAYER = -2;
202    static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
203    static final int APPLICATION_PANEL_SUBLAYER = 1;
204    static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
205    static final int APPLICATION_ABOVE_SUB_PANEL_SUBLAYER = 3;
206
207    static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
208    static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
209    static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
210    static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
211    static public final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
212
213    /**
214     * These are the system UI flags that, when changing, can cause the layout
215     * of the screen to change.
216     */
217    static final int SYSTEM_UI_CHANGING_LAYOUT =
218              View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
219            | View.SYSTEM_UI_FLAG_FULLSCREEN
220            | View.STATUS_BAR_TRANSLUCENT
221            | View.NAVIGATION_BAR_TRANSLUCENT
222            | View.STATUS_BAR_TRANSPARENT
223            | View.NAVIGATION_BAR_TRANSPARENT;
224
225    private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
226            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
227            .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
228            .build();
229
230    // The panic gesture may become active only after the keyguard is dismissed and the immersive
231    // app shows again. If that doesn't happen for 30s we drop the gesture.
232    private static final long PANIC_GESTURE_EXPIRATION = 30000;
233
234    /**
235     * Keyguard stuff
236     */
237    private WindowState mKeyguardScrim;
238    private boolean mKeyguardHidden;
239    private boolean mKeyguardDrawnOnce;
240
241    /* Table of Application Launch keys.  Maps from key codes to intent categories.
242     *
243     * These are special keys that are used to launch particular kinds of applications,
244     * such as a web browser.  HID defines nearly a hundred of them in the Consumer (0x0C)
245     * usage page.  We don't support quite that many yet...
246     */
247    static SparseArray<String> sApplicationLaunchKeyCategories;
248    static {
249        sApplicationLaunchKeyCategories = new SparseArray<String>();
250        sApplicationLaunchKeyCategories.append(
251                KeyEvent.KEYCODE_EXPLORER, Intent.CATEGORY_APP_BROWSER);
252        sApplicationLaunchKeyCategories.append(
253                KeyEvent.KEYCODE_ENVELOPE, Intent.CATEGORY_APP_EMAIL);
254        sApplicationLaunchKeyCategories.append(
255                KeyEvent.KEYCODE_CONTACTS, Intent.CATEGORY_APP_CONTACTS);
256        sApplicationLaunchKeyCategories.append(
257                KeyEvent.KEYCODE_CALENDAR, Intent.CATEGORY_APP_CALENDAR);
258        sApplicationLaunchKeyCategories.append(
259                KeyEvent.KEYCODE_MUSIC, Intent.CATEGORY_APP_MUSIC);
260        sApplicationLaunchKeyCategories.append(
261                KeyEvent.KEYCODE_CALCULATOR, Intent.CATEGORY_APP_CALCULATOR);
262    }
263
264    /** Amount of time (in milliseconds) to wait for windows drawn before powering on. */
265    static final int WAITING_FOR_DRAWN_TIMEOUT = 1000;
266
267    /**
268     * Lock protecting internal state.  Must not call out into window
269     * manager with lock held.  (This lock will be acquired in places
270     * where the window manager is calling in with its own lock held.)
271     */
272    private final Object mLock = new Object();
273
274    Context mContext;
275    IWindowManager mWindowManager;
276    WindowManagerFuncs mWindowManagerFuncs;
277    WindowManagerInternal mWindowManagerInternal;
278    PowerManager mPowerManager;
279    ActivityManagerInternal mActivityManagerInternal;
280    DreamManagerInternal mDreamManagerInternal;
281    PowerManagerInternal mPowerManagerInternal;
282    IStatusBarService mStatusBarService;
283    boolean mPreloadedRecentApps;
284    final Object mServiceAquireLock = new Object();
285    Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
286    SearchManager mSearchManager;
287    AccessibilityManager mAccessibilityManager;
288    BurnInProtectionHelper mBurnInProtectionHelper;
289    AppOpsManager mAppOpsManager;
290
291    // Vibrator pattern for haptic feedback of a long press.
292    long[] mLongPressVibePattern;
293
294    // Vibrator pattern for haptic feedback of virtual key press.
295    long[] mVirtualKeyVibePattern;
296
297    // Vibrator pattern for a short vibration.
298    long[] mKeyboardTapVibePattern;
299
300    // Vibrator pattern for a short vibration when tapping on an hour/minute tick of a Clock.
301    long[] mClockTickVibePattern;
302
303    // Vibrator pattern for a short vibration when tapping on a day/month/year date of a Calendar.
304    long[] mCalendarDateVibePattern;
305
306    // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
307    long[] mSafeModeDisabledVibePattern;
308
309    // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
310    long[] mSafeModeEnabledVibePattern;
311
312    // Vibrator pattern for haptic feedback of a context click.
313    long[] mContextClickVibePattern;
314
315    /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
316    boolean mEnableShiftMenuBugReports = false;
317
318    boolean mSafeMode;
319    WindowState mStatusBar = null;
320    int mStatusBarHeight;
321    WindowState mNavigationBar = null;
322    boolean mHasNavigationBar = false;
323    boolean mCanHideNavigationBar = false;
324    boolean mNavigationBarCanMove = false; // can the navigation bar ever move to the side?
325    boolean mNavigationBarOnBottom = true; // is the navigation bar on the bottom *right now*?
326    int[] mNavigationBarHeightForRotationDefault = new int[4];
327    int[] mNavigationBarWidthForRotationDefault = new int[4];
328    int[] mNavigationBarHeightForRotationInCarMode = new int[4];
329    int[] mNavigationBarWidthForRotationInCarMode = new int[4];
330
331    // Whether to allow dock apps with METADATA_DOCK_HOME to temporarily take over the Home key.
332    // This is for car dock and this is updated from resource.
333    private boolean mEnableCarDockHomeCapture = true;
334
335    boolean mBootMessageNeedsHiding;
336    KeyguardServiceDelegate mKeyguardDelegate;
337    final Runnable mWindowManagerDrawCallback = new Runnable() {
338        @Override
339        public void run() {
340            if (DEBUG_WAKEUP) Slog.i(TAG, "All windows ready for display!");
341            mHandler.sendEmptyMessage(MSG_WINDOW_MANAGER_DRAWN_COMPLETE);
342        }
343    };
344    final DrawnListener mKeyguardDrawnCallback = new DrawnListener() {
345        @Override
346        public void onDrawn() {
347            if (DEBUG_WAKEUP) Slog.d(TAG, "mKeyguardDelegate.ShowListener.onDrawn.");
348            mHandler.sendEmptyMessage(MSG_KEYGUARD_DRAWN_COMPLETE);
349        }
350    };
351
352    GlobalActions mGlobalActions;
353    Handler mHandler;
354    WindowState mLastInputMethodWindow = null;
355    WindowState mLastInputMethodTargetWindow = null;
356
357    // FIXME This state is shared between the input reader and handler thread.
358    // Technically it's broken and buggy but it has been like this for many years
359    // and we have not yet seen any problems.  Someday we'll rewrite this logic
360    // so that only one thread is involved in handling input policy.  Unfortunately
361    // it's on a critical path for power management so we can't just post the work to the
362    // handler thread.  We'll need to resolve this someday by teaching the input dispatcher
363    // to hold wakelocks during dispatch and eliminating the critical path.
364    volatile boolean mPowerKeyHandled;
365    volatile boolean mBeganFromNonInteractive;
366    volatile int mPowerKeyPressCounter;
367    volatile boolean mEndCallKeyHandled;
368
369    boolean mRecentsVisible;
370    int mRecentAppsHeldModifiers;
371    boolean mLanguageSwitchKeyPressed;
372
373    int mLidState = LID_ABSENT;
374    int mCameraLensCoverState = CAMERA_LENS_COVER_ABSENT;
375    boolean mHaveBuiltInKeyboard;
376
377    boolean mSystemReady;
378    boolean mSystemBooted;
379    private boolean mDeferBindKeyguard;
380    boolean mHdmiPlugged;
381    HdmiControl mHdmiControl;
382    IUiModeManager mUiModeManager;
383    int mUiMode;
384    int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED;
385    int mLidOpenRotation;
386    int mCarDockRotation;
387    int mDeskDockRotation;
388    int mUndockedHdmiRotation;
389    int mDemoHdmiRotation;
390    boolean mDemoHdmiRotationLock;
391    int mDemoRotation;
392    boolean mDemoRotationLock;
393
394    boolean mWakeGestureEnabledSetting;
395    MyWakeGestureListener mWakeGestureListener;
396
397    // Default display does not rotate, apps that require non-default orientation will have to
398    // have the orientation emulated.
399    private boolean mForceDefaultOrientation = false;
400
401    int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
402    int mUserRotation = Surface.ROTATION_0;
403    boolean mAccelerometerDefault;
404
405    boolean mSupportAutoRotation;
406    int mAllowAllRotations = -1;
407    boolean mCarDockEnablesAccelerometer;
408    boolean mDeskDockEnablesAccelerometer;
409    int mLidKeyboardAccessibility;
410    int mLidNavigationAccessibility;
411    boolean mLidControlsScreenLock;
412    boolean mLidControlsSleep;
413    int mShortPressOnPowerBehavior;
414    int mLongPressOnPowerBehavior;
415    int mDoublePressOnPowerBehavior;
416    int mTriplePressOnPowerBehavior;
417    int mShortPressOnSleepBehavior;
418    int mShortPressWindowBehavior;
419    boolean mAwake;
420    boolean mScreenOnEarly;
421    boolean mScreenOnFully;
422    ScreenOnListener mScreenOnListener;
423    boolean mKeyguardDrawComplete;
424    boolean mWindowManagerDrawComplete;
425    boolean mOrientationSensorEnabled = false;
426    int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
427    boolean mHasSoftInput = false;
428    boolean mTranslucentDecorEnabled = true;
429    boolean mUseTvRouting;
430
431    int mPointerLocationMode = 0; // guarded by mLock
432
433    // The last window we were told about in focusChanged.
434    WindowState mFocusedWindow;
435    IApplicationToken mFocusedApp;
436
437    PointerLocationView mPointerLocationView;
438
439    // The current size of the screen; really; extends into the overscan area of
440    // the screen and doesn't account for any system elements like the status bar.
441    int mOverscanScreenLeft, mOverscanScreenTop;
442    int mOverscanScreenWidth, mOverscanScreenHeight;
443    // The current visible size of the screen; really; (ir)regardless of whether the status
444    // bar can be hidden but not extending into the overscan area.
445    int mUnrestrictedScreenLeft, mUnrestrictedScreenTop;
446    int mUnrestrictedScreenWidth, mUnrestrictedScreenHeight;
447    // Like mOverscanScreen*, but allowed to move into the overscan region where appropriate.
448    int mRestrictedOverscanScreenLeft, mRestrictedOverscanScreenTop;
449    int mRestrictedOverscanScreenWidth, mRestrictedOverscanScreenHeight;
450    // The current size of the screen; these may be different than (0,0)-(dw,dh)
451    // if the status bar can't be hidden; in that case it effectively carves out
452    // that area of the display from all other windows.
453    int mRestrictedScreenLeft, mRestrictedScreenTop;
454    int mRestrictedScreenWidth, mRestrictedScreenHeight;
455    // During layout, the current screen borders accounting for any currently
456    // visible system UI elements.
457    int mSystemLeft, mSystemTop, mSystemRight, mSystemBottom;
458    // For applications requesting stable content insets, these are them.
459    int mStableLeft, mStableTop, mStableRight, mStableBottom;
460    // For applications requesting stable content insets but have also set the
461    // fullscreen window flag, these are the stable dimensions without the status bar.
462    int mStableFullscreenLeft, mStableFullscreenTop;
463    int mStableFullscreenRight, mStableFullscreenBottom;
464    // During layout, the current screen borders with all outer decoration
465    // (status bar, input method dock) accounted for.
466    int mCurLeft, mCurTop, mCurRight, mCurBottom;
467    // During layout, the frame in which content should be displayed
468    // to the user, accounting for all screen decoration except for any
469    // space they deem as available for other content.  This is usually
470    // the same as mCur*, but may be larger if the screen decor has supplied
471    // content insets.
472    int mContentLeft, mContentTop, mContentRight, mContentBottom;
473    // During layout, the frame in which voice content should be displayed
474    // to the user, accounting for all screen decoration except for any
475    // space they deem as available for other content.
476    int mVoiceContentLeft, mVoiceContentTop, mVoiceContentRight, mVoiceContentBottom;
477    // During layout, the current screen borders along which input method
478    // windows are placed.
479    int mDockLeft, mDockTop, mDockRight, mDockBottom;
480    // During layout, the layer at which the doc window is placed.
481    int mDockLayer;
482    // During layout, this is the layer of the status bar.
483    int mStatusBarLayer;
484    int mLastSystemUiFlags;
485    // Bits that we are in the process of clearing, so we want to prevent
486    // them from being set by applications until everything has been updated
487    // to have them clear.
488    int mResettingSystemUiFlags = 0;
489    // Bits that we are currently always keeping cleared.
490    int mForceClearedSystemUiFlags = 0;
491    // What we last reported to system UI about whether the compatibility
492    // menu needs to be displayed.
493    boolean mLastFocusNeedsMenu = false;
494    // If nonzero, a panic gesture was performed at that time in uptime millis and is still pending.
495    private long mPendingPanicGestureUptime;
496
497    InputConsumer mInputConsumer = null;
498
499    static final Rect mTmpParentFrame = new Rect();
500    static final Rect mTmpDisplayFrame = new Rect();
501    static final Rect mTmpOverscanFrame = new Rect();
502    static final Rect mTmpContentFrame = new Rect();
503    static final Rect mTmpVisibleFrame = new Rect();
504    static final Rect mTmpDecorFrame = new Rect();
505    static final Rect mTmpStableFrame = new Rect();
506    static final Rect mTmpNavigationFrame = new Rect();
507    static final Rect mTmpOutsetFrame = new Rect();
508
509    WindowState mTopFullscreenOpaqueWindowState;
510    WindowState mTopFullscreenOpaqueOrDimmingWindowState;
511    HashSet<IApplicationToken> mAppsToBeHidden = new HashSet<IApplicationToken>();
512    HashSet<IApplicationToken> mAppsThatDismissKeyguard = new HashSet<IApplicationToken>();
513    boolean mTopIsFullscreen;
514    boolean mForceStatusBar;
515    boolean mForceStatusBarFromKeyguard;
516    private boolean mForceStatusBarTransparent;
517    boolean mHideLockScreen;
518    boolean mForcingShowNavBar;
519    int mForcingShowNavBarLayer;
520
521    // States of keyguard dismiss.
522    private static final int DISMISS_KEYGUARD_NONE = 0; // Keyguard not being dismissed.
523    private static final int DISMISS_KEYGUARD_START = 1; // Keyguard needs to be dismissed.
524    private static final int DISMISS_KEYGUARD_CONTINUE = 2; // Keyguard has been dismissed.
525    int mDismissKeyguard = DISMISS_KEYGUARD_NONE;
526
527    /** The window that is currently dismissing the keyguard. Dismissing the keyguard must only
528     * be done once per window. */
529    private WindowState mWinDismissingKeyguard;
530
531    /** When window is currently dismissing the keyguard, dismissing the keyguard must handle
532     * the keygaurd secure state change instantly case, e.g. the use case of inserting a PIN
533     * lock SIM card. This variable is used to record the previous keyguard secure state for
534     * monitoring secure state change on window dismissing keyguard. */
535    private boolean mSecureDismissingKeyguard;
536
537    /** The window that is currently showing "over" the keyguard. If there is an app window
538     * belonging to another app on top of this the keyguard shows. If there is a fullscreen
539     * app window under this, still dismiss the keyguard but don't show the app underneath. Show
540     * the wallpaper. */
541    private WindowState mWinShowWhenLocked;
542
543    boolean mShowingLockscreen;
544    boolean mShowingDream;
545    boolean mDreamingLockscreen;
546    boolean mDreamingSleepTokenNeeded;
547    SleepToken mDreamingSleepToken;
548    SleepToken mScreenOffSleepToken;
549    boolean mKeyguardSecure;
550    boolean mKeyguardSecureIncludingHidden;
551    volatile boolean mKeyguardOccluded;
552    boolean mHomePressed;
553    boolean mHomeConsumed;
554    boolean mHomeDoubleTapPending;
555    Intent mHomeIntent;
556    Intent mCarDockIntent;
557    Intent mDeskDockIntent;
558    boolean mSearchKeyShortcutPending;
559    boolean mConsumeSearchKeyUp;
560    boolean mAssistKeyLongPressed;
561    boolean mPendingMetaAction;
562
563    // support for activating the lock screen while the screen is on
564    boolean mAllowLockscreenWhenOn;
565    int mLockScreenTimeout;
566    boolean mLockScreenTimerActive;
567
568    // Behavior of ENDCALL Button.  (See Settings.System.END_BUTTON_BEHAVIOR.)
569    int mEndcallBehavior;
570
571    // Behavior of POWER button while in-call and screen on.
572    // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
573    int mIncallPowerBehavior;
574
575    Display mDisplay;
576
577    private int mDisplayRotation;
578
579    int mLandscapeRotation = 0;  // default landscape rotation
580    int mSeascapeRotation = 0;   // "other" landscape rotation, 180 degrees from mLandscapeRotation
581    int mPortraitRotation = 0;   // default portrait rotation
582    int mUpsideDownRotation = 0; // "other" portrait rotation
583
584    int mOverscanLeft = 0;
585    int mOverscanTop = 0;
586    int mOverscanRight = 0;
587    int mOverscanBottom = 0;
588
589    // What we do when the user long presses on home
590    private int mLongPressOnHomeBehavior;
591
592    // What we do when the user double-taps on home
593    private int mDoubleTapOnHomeBehavior;
594
595    // Allowed theater mode wake actions
596    private boolean mAllowTheaterModeWakeFromKey;
597    private boolean mAllowTheaterModeWakeFromPowerKey;
598    private boolean mAllowTheaterModeWakeFromMotion;
599    private boolean mAllowTheaterModeWakeFromMotionWhenNotDreaming;
600    private boolean mAllowTheaterModeWakeFromCameraLens;
601    private boolean mAllowTheaterModeWakeFromLidSwitch;
602    private boolean mAllowTheaterModeWakeFromWakeGesture;
603
604    // Whether to support long press from power button in non-interactive mode
605    private boolean mSupportLongPressPowerWhenNonInteractive;
606
607    // Whether to go to sleep entering theater mode from power button
608    private boolean mGoToSleepOnButtonPressTheaterMode;
609
610    // Screenshot trigger states
611    // Time to volume and power must be pressed within this interval of each other.
612    private static final long SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS = 150;
613    // Increase the chord delay when taking a screenshot from the keyguard
614    private static final float KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER = 2.5f;
615    private boolean mScreenshotChordEnabled;
616    private boolean mScreenshotChordVolumeDownKeyTriggered;
617    private long mScreenshotChordVolumeDownKeyTime;
618    private boolean mScreenshotChordVolumeDownKeyConsumed;
619    private boolean mScreenshotChordVolumeUpKeyTriggered;
620    private boolean mScreenshotChordPowerKeyTriggered;
621    private long mScreenshotChordPowerKeyTime;
622
623    /* The number of steps between min and max brightness */
624    private static final int BRIGHTNESS_STEPS = 10;
625
626    SettingsObserver mSettingsObserver;
627    ShortcutManager mShortcutManager;
628    PowerManager.WakeLock mBroadcastWakeLock;
629    PowerManager.WakeLock mPowerKeyWakeLock;
630    boolean mHavePendingMediaKeyRepeatWithWakeLock;
631
632    private int mCurrentUserId;
633
634    // Maps global key codes to the components that will handle them.
635    private GlobalKeyManager mGlobalKeyManager;
636
637    // Fallback actions by key code.
638    private final SparseArray<KeyCharacterMap.FallbackAction> mFallbackActions =
639            new SparseArray<KeyCharacterMap.FallbackAction>();
640
641    private final LogDecelerateInterpolator mLogDecelerateInterpolator
642            = new LogDecelerateInterpolator(100, 0);
643
644    private boolean mForceWindowDrawsStatusBarBackground;
645
646    private static final int MSG_ENABLE_POINTER_LOCATION = 1;
647    private static final int MSG_DISABLE_POINTER_LOCATION = 2;
648    private static final int MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK = 3;
649    private static final int MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK = 4;
650    private static final int MSG_KEYGUARD_DRAWN_COMPLETE = 5;
651    private static final int MSG_KEYGUARD_DRAWN_TIMEOUT = 6;
652    private static final int MSG_WINDOW_MANAGER_DRAWN_COMPLETE = 7;
653    private static final int MSG_DISPATCH_SHOW_RECENTS = 9;
654    private static final int MSG_DISPATCH_SHOW_GLOBAL_ACTIONS = 10;
655    private static final int MSG_HIDE_BOOT_MESSAGE = 11;
656    private static final int MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK = 12;
657    private static final int MSG_POWER_DELAYED_PRESS = 13;
658    private static final int MSG_POWER_LONG_PRESS = 14;
659    private static final int MSG_UPDATE_DREAMING_SLEEP_TOKEN = 15;
660    private static final int MSG_REQUEST_TRANSIENT_BARS = 16;
661
662    private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0;
663    private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1;
664
665    private class PolicyHandler extends Handler {
666        @Override
667        public void handleMessage(Message msg) {
668            switch (msg.what) {
669                case MSG_ENABLE_POINTER_LOCATION:
670                    enablePointerLocation();
671                    break;
672                case MSG_DISABLE_POINTER_LOCATION:
673                    disablePointerLocation();
674                    break;
675                case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK:
676                    dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj);
677                    break;
678                case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK:
679                    dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj);
680                    break;
681                case MSG_DISPATCH_SHOW_RECENTS:
682                    showRecentApps(false);
683                    break;
684                case MSG_DISPATCH_SHOW_GLOBAL_ACTIONS:
685                    showGlobalActionsInternal();
686                    break;
687                case MSG_KEYGUARD_DRAWN_COMPLETE:
688                    if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mKeyguardDrawComplete");
689                    finishKeyguardDrawn();
690                    break;
691                case MSG_KEYGUARD_DRAWN_TIMEOUT:
692                    Slog.w(TAG, "Keyguard drawn timeout. Setting mKeyguardDrawComplete");
693                    finishKeyguardDrawn();
694                    break;
695                case MSG_WINDOW_MANAGER_DRAWN_COMPLETE:
696                    if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mWindowManagerDrawComplete");
697                    finishWindowsDrawn();
698                    break;
699                case MSG_HIDE_BOOT_MESSAGE:
700                    handleHideBootMessage();
701                    break;
702                case MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK:
703                    launchVoiceAssistWithWakeLock(msg.arg1 != 0);
704                    break;
705                case MSG_POWER_DELAYED_PRESS:
706                    powerPress((Long)msg.obj, msg.arg1 != 0, msg.arg2);
707                    finishPowerKeyPress();
708                    break;
709                case MSG_POWER_LONG_PRESS:
710                    powerLongPress();
711                    break;
712                case MSG_UPDATE_DREAMING_SLEEP_TOKEN:
713                    updateDreamingSleepToken(msg.arg1 != 0);
714                    break;
715                case MSG_REQUEST_TRANSIENT_BARS:
716                    WindowState targetBar = (msg.arg1 == MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS) ?
717                            mStatusBar : mNavigationBar;
718                    if (targetBar != null) {
719                        requestTransientBars(targetBar);
720                    }
721                    break;
722            }
723        }
724    }
725
726    private UEventObserver mHDMIObserver = new UEventObserver() {
727        @Override
728        public void onUEvent(UEventObserver.UEvent event) {
729            setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
730        }
731    };
732
733    class SettingsObserver extends ContentObserver {
734        SettingsObserver(Handler handler) {
735            super(handler);
736        }
737
738        void observe() {
739            // Observe all users' changes
740            ContentResolver resolver = mContext.getContentResolver();
741            resolver.registerContentObserver(Settings.System.getUriFor(
742                    Settings.System.END_BUTTON_BEHAVIOR), false, this,
743                    UserHandle.USER_ALL);
744            resolver.registerContentObserver(Settings.Secure.getUriFor(
745                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this,
746                    UserHandle.USER_ALL);
747            resolver.registerContentObserver(Settings.Secure.getUriFor(
748                    Settings.Secure.WAKE_GESTURE_ENABLED), false, this,
749                    UserHandle.USER_ALL);
750            resolver.registerContentObserver(Settings.System.getUriFor(
751                    Settings.System.ACCELEROMETER_ROTATION), false, this,
752                    UserHandle.USER_ALL);
753            resolver.registerContentObserver(Settings.System.getUriFor(
754                    Settings.System.USER_ROTATION), false, this,
755                    UserHandle.USER_ALL);
756            resolver.registerContentObserver(Settings.System.getUriFor(
757                    Settings.System.SCREEN_OFF_TIMEOUT), false, this,
758                    UserHandle.USER_ALL);
759            resolver.registerContentObserver(Settings.System.getUriFor(
760                    Settings.System.POINTER_LOCATION), false, this,
761                    UserHandle.USER_ALL);
762            resolver.registerContentObserver(Settings.Secure.getUriFor(
763                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this,
764                    UserHandle.USER_ALL);
765            resolver.registerContentObserver(Settings.Secure.getUriFor(
766                    Settings.Secure.IMMERSIVE_MODE_CONFIRMATIONS), false, this,
767                    UserHandle.USER_ALL);
768            resolver.registerContentObserver(Settings.Global.getUriFor(
769                    Settings.Global.POLICY_CONTROL), false, this,
770                    UserHandle.USER_ALL);
771            updateSettings();
772        }
773
774        @Override public void onChange(boolean selfChange) {
775            updateSettings();
776            updateRotation(false);
777        }
778    }
779
780    class MyWakeGestureListener extends WakeGestureListener {
781        MyWakeGestureListener(Context context, Handler handler) {
782            super(context, handler);
783        }
784
785        @Override
786        public void onWakeUp() {
787            synchronized (mLock) {
788                if (shouldEnableWakeGestureLp()) {
789                    performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
790                    wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromWakeGesture,
791                            "android.policy:GESTURE");
792                }
793            }
794        }
795    }
796
797    class MyOrientationListener extends WindowOrientationListener {
798        private final Runnable mUpdateRotationRunnable = new Runnable() {
799            @Override
800            public void run() {
801                // send interaction hint to improve redraw performance
802                mPowerManagerInternal.powerHint(PowerManagerInternal.POWER_HINT_INTERACTION, 0);
803                updateRotation(false);
804            }
805        };
806
807        MyOrientationListener(Context context, Handler handler) {
808            super(context, handler);
809        }
810
811        @Override
812        public void onProposedRotationChanged(int rotation) {
813            if (localLOGV) Slog.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
814            mHandler.post(mUpdateRotationRunnable);
815        }
816    }
817    MyOrientationListener mOrientationListener;
818
819    private final StatusBarController mStatusBarController = new StatusBarController();
820
821    private final BarController mNavigationBarController = new BarController("NavigationBar",
822            View.NAVIGATION_BAR_TRANSIENT,
823            View.NAVIGATION_BAR_UNHIDE,
824            View.NAVIGATION_BAR_TRANSLUCENT,
825            StatusBarManager.WINDOW_NAVIGATION_BAR,
826            WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
827            View.NAVIGATION_BAR_TRANSPARENT);
828
829    private ImmersiveModeConfirmation mImmersiveModeConfirmation;
830
831    private SystemGesturesPointerEventListener mSystemGestures;
832
833    IStatusBarService getStatusBarService() {
834        synchronized (mServiceAquireLock) {
835            if (mStatusBarService == null) {
836                mStatusBarService = IStatusBarService.Stub.asInterface(
837                        ServiceManager.getService("statusbar"));
838            }
839            return mStatusBarService;
840        }
841    }
842
843    /*
844     * We always let the sensor be switched on by default except when
845     * the user has explicitly disabled sensor based rotation or when the
846     * screen is switched off.
847     */
848    boolean needSensorRunningLp() {
849        if (mSupportAutoRotation) {
850            if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
851                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
852                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
853                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
854                // If the application has explicitly requested to follow the
855                // orientation, then we need to turn the sensor on.
856                return true;
857            }
858        }
859        if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
860                (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
861                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
862                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) {
863            // enable accelerometer if we are docked in a dock that enables accelerometer
864            // orientation management,
865            return true;
866        }
867        if (mUserRotationMode == USER_ROTATION_LOCKED) {
868            // If the setting for using the sensor by default is enabled, then
869            // we will always leave it on.  Note that the user could go to
870            // a window that forces an orientation that does not use the
871            // sensor and in theory we could turn it off... however, when next
872            // turning it on we won't have a good value for the current
873            // orientation for a little bit, which can cause orientation
874            // changes to lag, so we'd like to keep it always on.  (It will
875            // still be turned off when the screen is off.)
876            return false;
877        }
878        return mSupportAutoRotation;
879    }
880
881    /*
882     * Various use cases for invoking this function
883     * screen turning off, should always disable listeners if already enabled
884     * screen turned on and current app has sensor based orientation, enable listeners
885     * if not already enabled
886     * screen turned on and current app does not have sensor orientation, disable listeners if
887     * already enabled
888     * screen turning on and current app has sensor based orientation, enable listeners if needed
889     * screen turning on and current app has nosensor based orientation, do nothing
890     */
891    void updateOrientationListenerLp() {
892        if (!mOrientationListener.canDetectOrientation()) {
893            // If sensor is turned off or nonexistent for some reason
894            return;
895        }
896        // Could have been invoked due to screen turning on or off or
897        // change of the currently visible window's orientation.
898        if (localLOGV) Slog.v(TAG, "mScreenOnEarly=" + mScreenOnEarly
899                + ", mAwake=" + mAwake + ", mCurrentAppOrientation=" + mCurrentAppOrientation
900                + ", mOrientationSensorEnabled=" + mOrientationSensorEnabled
901                + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
902                + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
903        boolean disable = true;
904        // Note: We postpone the rotating of the screen until the keyguard as well as the
905        // window manager have reported a draw complete.
906        if (mScreenOnEarly && mAwake &&
907                mKeyguardDrawComplete && mWindowManagerDrawComplete) {
908            if (needSensorRunningLp()) {
909                disable = false;
910                //enable listener if not already enabled
911                if (!mOrientationSensorEnabled) {
912                    mOrientationListener.enable();
913                    if(localLOGV) Slog.v(TAG, "Enabling listeners");
914                    mOrientationSensorEnabled = true;
915                }
916            }
917        }
918        //check if sensors need to be disabled
919        if (disable && mOrientationSensorEnabled) {
920            mOrientationListener.disable();
921            if(localLOGV) Slog.v(TAG, "Disabling listeners");
922            mOrientationSensorEnabled = false;
923        }
924    }
925
926    private void interceptPowerKeyDown(KeyEvent event, boolean interactive) {
927        // Hold a wake lock until the power key is released.
928        if (!mPowerKeyWakeLock.isHeld()) {
929            mPowerKeyWakeLock.acquire();
930        }
931
932        // Cancel multi-press detection timeout.
933        if (mPowerKeyPressCounter != 0) {
934            mHandler.removeMessages(MSG_POWER_DELAYED_PRESS);
935        }
936
937        // Detect user pressing the power button in panic when an application has
938        // taken over the whole screen.
939        boolean panic = mImmersiveModeConfirmation.onPowerKeyDown(interactive,
940                SystemClock.elapsedRealtime(), isImmersiveMode(mLastSystemUiFlags));
941        if (panic) {
942            mHandler.post(mHiddenNavPanic);
943        }
944
945        // Latch power key state to detect screenshot chord.
946        if (interactive && !mScreenshotChordPowerKeyTriggered
947                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
948            mScreenshotChordPowerKeyTriggered = true;
949            mScreenshotChordPowerKeyTime = event.getDownTime();
950            interceptScreenshotChord();
951        }
952
953        // Stop ringing or end call if configured to do so when power is pressed.
954        TelecomManager telecomManager = getTelecommService();
955        boolean hungUp = false;
956        if (telecomManager != null) {
957            if (telecomManager.isRinging()) {
958                // Pressing Power while there's a ringing incoming
959                // call should silence the ringer.
960                telecomManager.silenceRinger();
961            } else if ((mIncallPowerBehavior
962                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
963                    && telecomManager.isInCall() && interactive) {
964                // Otherwise, if "Power button ends call" is enabled,
965                // the Power button will hang up any current active call.
966                hungUp = telecomManager.endCall();
967            }
968        }
969
970        GestureLauncherService gestureService = LocalServices.getService(
971                GestureLauncherService.class);
972        boolean gesturedServiceIntercepted = false;
973        if (gestureService != null) {
974            gesturedServiceIntercepted = gestureService.interceptPowerKeyDown(event, interactive);
975        }
976
977        // If the power key has still not yet been handled, then detect short
978        // press, long press, or multi press and decide what to do.
979        mPowerKeyHandled = hungUp || mScreenshotChordVolumeDownKeyTriggered
980                || mScreenshotChordVolumeUpKeyTriggered || gesturedServiceIntercepted;
981        if (!mPowerKeyHandled) {
982            if (interactive) {
983                // When interactive, we're already awake.
984                // Wait for a long press or for the button to be released to decide what to do.
985                if (hasLongPressOnPowerBehavior()) {
986                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
987                    msg.setAsynchronous(true);
988                    mHandler.sendMessageDelayed(msg,
989                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
990                }
991            } else {
992                wakeUpFromPowerKey(event.getDownTime());
993
994                if (mSupportLongPressPowerWhenNonInteractive && hasLongPressOnPowerBehavior()) {
995                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
996                    msg.setAsynchronous(true);
997                    mHandler.sendMessageDelayed(msg,
998                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
999                    mBeganFromNonInteractive = true;
1000                } else {
1001                    final int maxCount = getMaxMultiPressPowerCount();
1002
1003                    if (maxCount <= 1) {
1004                        mPowerKeyHandled = true;
1005                    } else {
1006                        mBeganFromNonInteractive = true;
1007                    }
1008                }
1009            }
1010        }
1011    }
1012
1013    private void interceptPowerKeyUp(KeyEvent event, boolean interactive, boolean canceled) {
1014        final boolean handled = canceled || mPowerKeyHandled;
1015        mScreenshotChordPowerKeyTriggered = false;
1016        cancelPendingScreenshotChordAction();
1017        cancelPendingPowerKeyAction();
1018
1019        if (!handled) {
1020            // Figure out how to handle the key now that it has been released.
1021            mPowerKeyPressCounter += 1;
1022
1023            final int maxCount = getMaxMultiPressPowerCount();
1024            final long eventTime = event.getDownTime();
1025            if (mPowerKeyPressCounter < maxCount) {
1026                // This could be a multi-press.  Wait a little bit longer to confirm.
1027                // Continue holding the wake lock.
1028                Message msg = mHandler.obtainMessage(MSG_POWER_DELAYED_PRESS,
1029                        interactive ? 1 : 0, mPowerKeyPressCounter, eventTime);
1030                msg.setAsynchronous(true);
1031                mHandler.sendMessageDelayed(msg, ViewConfiguration.getDoubleTapTimeout());
1032                return;
1033            }
1034
1035            // No other actions.  Handle it immediately.
1036            powerPress(eventTime, interactive, mPowerKeyPressCounter);
1037        }
1038
1039        // Done.  Reset our state.
1040        finishPowerKeyPress();
1041    }
1042
1043    private void finishPowerKeyPress() {
1044        mBeganFromNonInteractive = false;
1045        mPowerKeyPressCounter = 0;
1046        if (mPowerKeyWakeLock.isHeld()) {
1047            mPowerKeyWakeLock.release();
1048        }
1049    }
1050
1051    private void cancelPendingPowerKeyAction() {
1052        if (!mPowerKeyHandled) {
1053            mPowerKeyHandled = true;
1054            mHandler.removeMessages(MSG_POWER_LONG_PRESS);
1055        }
1056    }
1057
1058    private void powerPress(long eventTime, boolean interactive, int count) {
1059        if (mScreenOnEarly && !mScreenOnFully) {
1060            Slog.i(TAG, "Suppressed redundant power key press while "
1061                    + "already in the process of turning the screen on.");
1062            return;
1063        }
1064
1065        if (count == 2) {
1066            powerMultiPressAction(eventTime, interactive, mDoublePressOnPowerBehavior);
1067        } else if (count == 3) {
1068            powerMultiPressAction(eventTime, interactive, mTriplePressOnPowerBehavior);
1069        } else if (interactive && !mBeganFromNonInteractive) {
1070            switch (mShortPressOnPowerBehavior) {
1071                case SHORT_PRESS_POWER_NOTHING:
1072                    break;
1073                case SHORT_PRESS_POWER_GO_TO_SLEEP:
1074                    mPowerManager.goToSleep(eventTime,
1075                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
1076                    break;
1077                case SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP:
1078                    mPowerManager.goToSleep(eventTime,
1079                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON,
1080                            PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
1081                    break;
1082                case SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP_AND_GO_HOME:
1083                    mPowerManager.goToSleep(eventTime,
1084                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON,
1085                            PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
1086                    launchHomeFromHotKey();
1087                    break;
1088                case SHORT_PRESS_POWER_GO_HOME:
1089                    launchHomeFromHotKey(true /* awakenFromDreams */, false /*respectKeyguard*/);
1090                    break;
1091            }
1092        }
1093    }
1094
1095    private void powerMultiPressAction(long eventTime, boolean interactive, int behavior) {
1096        switch (behavior) {
1097            case MULTI_PRESS_POWER_NOTHING:
1098                break;
1099            case MULTI_PRESS_POWER_THEATER_MODE:
1100                if (!isUserSetupComplete()) {
1101                    Slog.i(TAG, "Ignoring toggling theater mode - device not setup.");
1102                    break;
1103                }
1104
1105                if (isTheaterModeEnabled()) {
1106                    Slog.i(TAG, "Toggling theater mode off.");
1107                    Settings.Global.putInt(mContext.getContentResolver(),
1108                            Settings.Global.THEATER_MODE_ON, 0);
1109                    if (!interactive) {
1110                        wakeUpFromPowerKey(eventTime);
1111                    }
1112                } else {
1113                    Slog.i(TAG, "Toggling theater mode on.");
1114                    Settings.Global.putInt(mContext.getContentResolver(),
1115                            Settings.Global.THEATER_MODE_ON, 1);
1116
1117                    if (mGoToSleepOnButtonPressTheaterMode && interactive) {
1118                        mPowerManager.goToSleep(eventTime,
1119                                PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
1120                    }
1121                }
1122                break;
1123            case MULTI_PRESS_POWER_BRIGHTNESS_BOOST:
1124                Slog.i(TAG, "Starting brightness boost.");
1125                if (!interactive) {
1126                    wakeUpFromPowerKey(eventTime);
1127                }
1128                mPowerManager.boostScreenBrightness(eventTime);
1129                break;
1130        }
1131    }
1132
1133    private int getMaxMultiPressPowerCount() {
1134        if (mTriplePressOnPowerBehavior != MULTI_PRESS_POWER_NOTHING) {
1135            return 3;
1136        }
1137        if (mDoublePressOnPowerBehavior != MULTI_PRESS_POWER_NOTHING) {
1138            return 2;
1139        }
1140        return 1;
1141    }
1142
1143    private void powerLongPress() {
1144        final int behavior = getResolvedLongPressOnPowerBehavior();
1145        switch (behavior) {
1146        case LONG_PRESS_POWER_NOTHING:
1147            break;
1148        case LONG_PRESS_POWER_GLOBAL_ACTIONS:
1149            mPowerKeyHandled = true;
1150            if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
1151                performAuditoryFeedbackForAccessibilityIfNeed();
1152            }
1153            showGlobalActionsInternal();
1154            break;
1155        case LONG_PRESS_POWER_SHUT_OFF:
1156        case LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM:
1157            mPowerKeyHandled = true;
1158            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
1159            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
1160            mWindowManagerFuncs.shutdown(behavior == LONG_PRESS_POWER_SHUT_OFF);
1161            break;
1162        }
1163    }
1164
1165    private void sleepPress(long eventTime) {
1166        if (mShortPressOnSleepBehavior == SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME) {
1167            launchHomeFromHotKey(false /* awakenDreams */, true /*respectKeyguard*/);
1168        }
1169    }
1170
1171    private void sleepRelease(long eventTime) {
1172        switch (mShortPressOnSleepBehavior) {
1173            case SHORT_PRESS_SLEEP_GO_TO_SLEEP:
1174            case SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME:
1175                Slog.i(TAG, "sleepRelease() calling goToSleep(GO_TO_SLEEP_REASON_SLEEP_BUTTON)");
1176                mPowerManager.goToSleep(eventTime,
1177                       PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON, 0);
1178                break;
1179        }
1180    }
1181
1182    private int getResolvedLongPressOnPowerBehavior() {
1183        if (FactoryTest.isLongPressOnPowerOffEnabled()) {
1184            return LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM;
1185        }
1186        return mLongPressOnPowerBehavior;
1187    }
1188
1189    private boolean hasLongPressOnPowerBehavior() {
1190        return getResolvedLongPressOnPowerBehavior() != LONG_PRESS_POWER_NOTHING;
1191    }
1192
1193    private void interceptScreenshotChord() {
1194        if (mScreenshotChordEnabled
1195                && mScreenshotChordVolumeDownKeyTriggered && mScreenshotChordPowerKeyTriggered
1196                && !mScreenshotChordVolumeUpKeyTriggered) {
1197            final long now = SystemClock.uptimeMillis();
1198            if (now <= mScreenshotChordVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
1199                    && now <= mScreenshotChordPowerKeyTime
1200                            + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
1201                mScreenshotChordVolumeDownKeyConsumed = true;
1202                cancelPendingPowerKeyAction();
1203
1204                mHandler.postDelayed(mScreenshotRunnable, getScreenshotChordLongPressDelay());
1205            }
1206        }
1207    }
1208
1209    private long getScreenshotChordLongPressDelay() {
1210        if (mKeyguardDelegate.isShowing()) {
1211            // Double the time it takes to take a screenshot from the keyguard
1212            return (long) (KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER *
1213                    ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
1214        }
1215        return ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout();
1216    }
1217
1218    private void cancelPendingScreenshotChordAction() {
1219        mHandler.removeCallbacks(mScreenshotRunnable);
1220    }
1221
1222    private final Runnable mEndCallLongPress = new Runnable() {
1223        @Override
1224        public void run() {
1225            mEndCallKeyHandled = true;
1226            if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
1227                performAuditoryFeedbackForAccessibilityIfNeed();
1228            }
1229            showGlobalActionsInternal();
1230        }
1231    };
1232
1233    private final Runnable mScreenshotRunnable = new Runnable() {
1234        @Override
1235        public void run() {
1236            takeScreenshot();
1237        }
1238    };
1239
1240    @Override
1241    public void showGlobalActions() {
1242        mHandler.removeMessages(MSG_DISPATCH_SHOW_GLOBAL_ACTIONS);
1243        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_GLOBAL_ACTIONS);
1244    }
1245
1246    void showGlobalActionsInternal() {
1247        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
1248        if (mGlobalActions == null) {
1249            mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs);
1250        }
1251        final boolean keyguardShowing = isKeyguardShowingAndNotOccluded();
1252        mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
1253        if (keyguardShowing) {
1254            // since it took two seconds of long press to bring this up,
1255            // poke the wake lock so they have some time to see the dialog.
1256            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
1257        }
1258    }
1259
1260    boolean isDeviceProvisioned() {
1261        return Settings.Global.getInt(
1262                mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1263    }
1264
1265    boolean isUserSetupComplete() {
1266        return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1267                Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
1268    }
1269
1270    private void handleShortPressOnHome() {
1271        // Turn on the connected TV and switch HDMI input if we're a HDMI playback device.
1272        getHdmiControl().turnOnTv();
1273
1274        // If there's a dream running then use home to escape the dream
1275        // but don't actually go home.
1276        if (mDreamManagerInternal != null && mDreamManagerInternal.isDreaming()) {
1277            mDreamManagerInternal.stopDream(false /*immediate*/);
1278            return;
1279        }
1280
1281        // Go home!
1282        launchHomeFromHotKey();
1283    }
1284
1285    /**
1286     * Creates an accessor to HDMI control service that performs the operation of
1287     * turning on TV (optional) and switching input to us. If HDMI control service
1288     * is not available or we're not a HDMI playback device, the operation is no-op.
1289     */
1290    private HdmiControl getHdmiControl() {
1291        if (null == mHdmiControl) {
1292            HdmiControlManager manager = (HdmiControlManager) mContext.getSystemService(
1293                        Context.HDMI_CONTROL_SERVICE);
1294            HdmiPlaybackClient client = null;
1295            if (manager != null) {
1296                client = manager.getPlaybackClient();
1297            }
1298            mHdmiControl = new HdmiControl(client);
1299        }
1300        return mHdmiControl;
1301    }
1302
1303    private static class HdmiControl {
1304        private final HdmiPlaybackClient mClient;
1305
1306        private HdmiControl(HdmiPlaybackClient client) {
1307            mClient = client;
1308        }
1309
1310        public void turnOnTv() {
1311            if (mClient == null) {
1312                return;
1313            }
1314            mClient.oneTouchPlay(new OneTouchPlayCallback() {
1315                @Override
1316                public void onComplete(int result) {
1317                    if (result != HdmiControlManager.RESULT_SUCCESS) {
1318                        Log.w(TAG, "One touch play failed: " + result);
1319                    }
1320                }
1321            });
1322        }
1323    }
1324
1325    private void handleLongPressOnHome(int deviceId, KeyEvent event) {
1326        if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_NOTHING) {
1327            return;
1328        }
1329        mHomeConsumed = true;
1330        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
1331
1332        switch (mLongPressOnHomeBehavior) {
1333            case LONG_PRESS_HOME_RECENT_SYSTEM_UI:
1334                toggleRecentApps();
1335                break;
1336            case LONG_PRESS_HOME_ASSIST:
1337                launchAssistAction(null, deviceId);
1338                break;
1339            case LONG_PRESS_HOME_PICTURE_IN_PICTURE:
1340                handlePipKey(event);
1341                break;
1342            default:
1343                Log.w(TAG, "Not defined home long press behavior: " + mLongPressOnHomeBehavior);
1344                break;
1345        }
1346    }
1347
1348    private void handleDoubleTapOnHome() {
1349        if (mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
1350            mHomeConsumed = true;
1351            toggleRecentApps();
1352        }
1353    }
1354
1355    private void handlePipKey(KeyEvent event) {
1356        if (DEBUG_INPUT) Log.d(TAG, "handlePipKey event=" + event);
1357        Intent intent = new Intent(Intent.ACTION_PICTURE_IN_PICTURE_BUTTON);
1358        intent.putExtra(Intent.EXTRA_KEY_EVENT, event);
1359        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1360    }
1361
1362    private final Runnable mHomeDoubleTapTimeoutRunnable = new Runnable() {
1363        @Override
1364        public void run() {
1365            if (mHomeDoubleTapPending) {
1366                mHomeDoubleTapPending = false;
1367                handleShortPressOnHome();
1368            }
1369        }
1370    };
1371
1372    private boolean isRoundWindow() {
1373        return mContext.getResources().getConfiguration().isScreenRound();
1374    }
1375
1376    /** {@inheritDoc} */
1377    @Override
1378    public void init(Context context, IWindowManager windowManager,
1379            WindowManagerFuncs windowManagerFuncs) {
1380        mContext = context;
1381        mWindowManager = windowManager;
1382        mWindowManagerFuncs = windowManagerFuncs;
1383        mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
1384        mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
1385        mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class);
1386        mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
1387        mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1388
1389        // Init display burn-in protection
1390        boolean burnInProtectionEnabled = context.getResources().getBoolean(
1391                com.android.internal.R.bool.config_enableBurnInProtection);
1392        // Allow a system property to override this. Used by developer settings.
1393        boolean burnInProtectionDevMode =
1394                SystemProperties.getBoolean("persist.debug.force_burn_in", false);
1395        if (burnInProtectionEnabled || burnInProtectionDevMode) {
1396            final int minHorizontal;
1397            final int maxHorizontal;
1398            final int minVertical;
1399            final int maxVertical;
1400            final int maxRadius;
1401            if (burnInProtectionDevMode) {
1402                minHorizontal = -8;
1403                maxHorizontal = 8;
1404                minVertical = -8;
1405                maxVertical = -4;
1406                maxRadius = (isRoundWindow()) ? 6 : -1;
1407            } else {
1408                Resources resources = context.getResources();
1409                minHorizontal = resources.getInteger(
1410                        com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset);
1411                maxHorizontal = resources.getInteger(
1412                        com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset);
1413                minVertical = resources.getInteger(
1414                        com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset);
1415                maxVertical = resources.getInteger(
1416                        com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset);
1417                maxRadius = resources.getInteger(
1418                        com.android.internal.R.integer.config_burnInProtectionMaxRadius);
1419            }
1420            mBurnInProtectionHelper = new BurnInProtectionHelper(
1421                    context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius);
1422        }
1423
1424        mHandler = new PolicyHandler();
1425        mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler);
1426        mOrientationListener = new MyOrientationListener(mContext, mHandler);
1427        try {
1428            mOrientationListener.setCurrentRotation(windowManager.getRotation());
1429        } catch (RemoteException ex) { }
1430        mSettingsObserver = new SettingsObserver(mHandler);
1431        mSettingsObserver.observe();
1432        mShortcutManager = new ShortcutManager(context);
1433        mUiMode = context.getResources().getInteger(
1434                com.android.internal.R.integer.config_defaultUiModeType);
1435        mHomeIntent =  new Intent(Intent.ACTION_MAIN, null);
1436        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
1437        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1438                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1439        mEnableCarDockHomeCapture = context.getResources().getBoolean(
1440                com.android.internal.R.bool.config_enableCarDockHomeLaunch);
1441        mCarDockIntent =  new Intent(Intent.ACTION_MAIN, null);
1442        mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
1443        mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1444                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1445        mDeskDockIntent =  new Intent(Intent.ACTION_MAIN, null);
1446        mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
1447        mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1448                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1449
1450        mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1451        mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1452                "PhoneWindowManager.mBroadcastWakeLock");
1453        mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1454                "PhoneWindowManager.mPowerKeyWakeLock");
1455        mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
1456        mSupportAutoRotation = mContext.getResources().getBoolean(
1457                com.android.internal.R.bool.config_supportAutoRotation);
1458        mLidOpenRotation = readRotation(
1459                com.android.internal.R.integer.config_lidOpenRotation);
1460        mCarDockRotation = readRotation(
1461                com.android.internal.R.integer.config_carDockRotation);
1462        mDeskDockRotation = readRotation(
1463                com.android.internal.R.integer.config_deskDockRotation);
1464        mUndockedHdmiRotation = readRotation(
1465                com.android.internal.R.integer.config_undockedHdmiRotation);
1466        mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
1467                com.android.internal.R.bool.config_carDockEnablesAccelerometer);
1468        mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
1469                com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
1470        mLidKeyboardAccessibility = mContext.getResources().getInteger(
1471                com.android.internal.R.integer.config_lidKeyboardAccessibility);
1472        mLidNavigationAccessibility = mContext.getResources().getInteger(
1473                com.android.internal.R.integer.config_lidNavigationAccessibility);
1474        mLidControlsScreenLock = mContext.getResources().getBoolean(
1475                com.android.internal.R.bool.config_lidControlsScreenLock);
1476        mLidControlsSleep = mContext.getResources().getBoolean(
1477                com.android.internal.R.bool.config_lidControlsSleep);
1478        mTranslucentDecorEnabled = mContext.getResources().getBoolean(
1479                com.android.internal.R.bool.config_enableTranslucentDecor);
1480
1481        mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean(
1482                com.android.internal.R.bool.config_allowTheaterModeWakeFromKey);
1483        mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey
1484                || mContext.getResources().getBoolean(
1485                    com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey);
1486        mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean(
1487                com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion);
1488        mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean(
1489                com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming);
1490        mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean(
1491                com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens);
1492        mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean(
1493                com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch);
1494        mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean(
1495                com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture);
1496
1497        mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean(
1498                com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode);
1499
1500        mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean(
1501                com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive);
1502
1503        mShortPressOnPowerBehavior = mContext.getResources().getInteger(
1504                com.android.internal.R.integer.config_shortPressOnPowerBehavior);
1505        mLongPressOnPowerBehavior = mContext.getResources().getInteger(
1506                com.android.internal.R.integer.config_longPressOnPowerBehavior);
1507        mDoublePressOnPowerBehavior = mContext.getResources().getInteger(
1508                com.android.internal.R.integer.config_doublePressOnPowerBehavior);
1509        mTriplePressOnPowerBehavior = mContext.getResources().getInteger(
1510                com.android.internal.R.integer.config_triplePressOnPowerBehavior);
1511        mShortPressOnSleepBehavior = mContext.getResources().getInteger(
1512                com.android.internal.R.integer.config_shortPressOnSleepBehavior);
1513
1514        mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION;
1515
1516        readConfigurationDependentBehaviors();
1517
1518        mAccessibilityManager = (AccessibilityManager) context.getSystemService(
1519                Context.ACCESSIBILITY_SERVICE);
1520
1521        // register for dock events
1522        IntentFilter filter = new IntentFilter();
1523        filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE);
1524        filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE);
1525        filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE);
1526        filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE);
1527        filter.addAction(Intent.ACTION_DOCK_EVENT);
1528        Intent intent = context.registerReceiver(mDockReceiver, filter);
1529        if (intent != null) {
1530            // Retrieve current sticky dock event broadcast.
1531            mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1532                    Intent.EXTRA_DOCK_STATE_UNDOCKED);
1533        }
1534
1535        // register for dream-related broadcasts
1536        filter = new IntentFilter();
1537        filter.addAction(Intent.ACTION_DREAMING_STARTED);
1538        filter.addAction(Intent.ACTION_DREAMING_STOPPED);
1539        context.registerReceiver(mDreamReceiver, filter);
1540
1541        // register for multiuser-relevant broadcasts
1542        filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
1543        context.registerReceiver(mMultiuserReceiver, filter);
1544
1545        // monitor for system gestures
1546        mSystemGestures = new SystemGesturesPointerEventListener(context,
1547                new SystemGesturesPointerEventListener.Callbacks() {
1548                    @Override
1549                    public void onSwipeFromTop() {
1550                        if (mStatusBar != null) {
1551                            requestTransientBars(mStatusBar);
1552                        }
1553                    }
1554                    @Override
1555                    public void onSwipeFromBottom() {
1556                        if (mNavigationBar != null && mNavigationBarOnBottom) {
1557                            requestTransientBars(mNavigationBar);
1558                        }
1559                    }
1560                    @Override
1561                    public void onSwipeFromRight() {
1562                        if (mNavigationBar != null && !mNavigationBarOnBottom) {
1563                            requestTransientBars(mNavigationBar);
1564                        }
1565                    }
1566                    @Override
1567                    public void onFling(int duration) {
1568                        if (mPowerManagerInternal != null) {
1569                            mPowerManagerInternal.powerHint(
1570                                    PowerManagerInternal.POWER_HINT_INTERACTION, duration);
1571                        }
1572                    }
1573                    @Override
1574                    public void onDebug() {
1575                        // no-op
1576                    }
1577                    @Override
1578                    public void onDown() {
1579                        mOrientationListener.onTouchStart();
1580                    }
1581                    @Override
1582                    public void onUpOrCancel() {
1583                        mOrientationListener.onTouchEnd();
1584                    }
1585                    @Override
1586                    public void onMouseHoverAtTop() {
1587                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1588                        Message msg = mHandler.obtainMessage(MSG_REQUEST_TRANSIENT_BARS);
1589                        msg.arg1 = MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS;
1590                        mHandler.sendMessageDelayed(msg, 500);
1591                    }
1592                    @Override
1593                    public void onMouseHoverAtBottom() {
1594                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1595                        Message msg = mHandler.obtainMessage(MSG_REQUEST_TRANSIENT_BARS);
1596                        msg.arg1 = MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION;
1597                        mHandler.sendMessageDelayed(msg, 500);
1598                    }
1599                    @Override
1600                    public void onMouseLeaveFromEdge() {
1601                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1602                    }
1603                });
1604        mImmersiveModeConfirmation = new ImmersiveModeConfirmation(mContext);
1605        mWindowManagerFuncs.registerPointerEventListener(mSystemGestures);
1606
1607        mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
1608        mLongPressVibePattern = getLongIntArray(mContext.getResources(),
1609                com.android.internal.R.array.config_longPressVibePattern);
1610        mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
1611                com.android.internal.R.array.config_virtualKeyVibePattern);
1612        mKeyboardTapVibePattern = getLongIntArray(mContext.getResources(),
1613                com.android.internal.R.array.config_keyboardTapVibePattern);
1614        mClockTickVibePattern = getLongIntArray(mContext.getResources(),
1615                com.android.internal.R.array.config_clockTickVibePattern);
1616        mCalendarDateVibePattern = getLongIntArray(mContext.getResources(),
1617                com.android.internal.R.array.config_calendarDateVibePattern);
1618        mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
1619                com.android.internal.R.array.config_safeModeDisabledVibePattern);
1620        mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
1621                com.android.internal.R.array.config_safeModeEnabledVibePattern);
1622        mContextClickVibePattern = getLongIntArray(mContext.getResources(),
1623                com.android.internal.R.array.config_contextClickVibePattern);
1624
1625        mScreenshotChordEnabled = mContext.getResources().getBoolean(
1626                com.android.internal.R.bool.config_enableScreenshotChord);
1627        mForceWindowDrawsStatusBarBackground = mContext.getResources().getBoolean(
1628                R.bool.config_forceWindowDrawsStatusBarBackground);
1629
1630        mGlobalKeyManager = new GlobalKeyManager(mContext);
1631
1632        // Controls rotation and the like.
1633        initializeHdmiState();
1634
1635        // Match current screen state.
1636        if (!mPowerManager.isInteractive()) {
1637            startedGoingToSleep(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1638            finishedGoingToSleep(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1639        }
1640
1641        mWindowManagerInternal.registerAppTransitionListener(
1642                mStatusBarController.getAppTransitionListener());
1643    }
1644
1645    /**
1646     * Read values from config.xml that may be overridden depending on
1647     * the configuration of the device.
1648     * eg. Disable long press on home goes to recents on sw600dp.
1649     */
1650    private void readConfigurationDependentBehaviors() {
1651        mLongPressOnHomeBehavior = mContext.getResources().getInteger(
1652                com.android.internal.R.integer.config_longPressOnHomeBehavior);
1653        if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING ||
1654                mLongPressOnHomeBehavior > LAST_LONG_PRESS_HOME_BEHAVIOR) {
1655            mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
1656        }
1657
1658        mDoubleTapOnHomeBehavior = mContext.getResources().getInteger(
1659                com.android.internal.R.integer.config_doubleTapOnHomeBehavior);
1660        if (mDoubleTapOnHomeBehavior < DOUBLE_TAP_HOME_NOTHING ||
1661                mDoubleTapOnHomeBehavior > DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
1662            mDoubleTapOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
1663        }
1664
1665        mShortPressWindowBehavior = SHORT_PRESS_WINDOW_NOTHING;
1666        if (mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE)) {
1667            mShortPressWindowBehavior = SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE;
1668        }
1669    }
1670
1671    @Override
1672    public void setInitialDisplaySize(Display display, int width, int height, int density) {
1673        // This method might be called before the policy has been fully initialized
1674        // or for other displays we don't care about.
1675        if (mContext == null || display.getDisplayId() != Display.DEFAULT_DISPLAY) {
1676            return;
1677        }
1678        mDisplay = display;
1679
1680        final Resources res = mContext.getResources();
1681        int shortSize, longSize;
1682        if (width > height) {
1683            shortSize = height;
1684            longSize = width;
1685            mLandscapeRotation = Surface.ROTATION_0;
1686            mSeascapeRotation = Surface.ROTATION_180;
1687            if (res.getBoolean(com.android.internal.R.bool.config_reverseDefaultRotation)) {
1688                mPortraitRotation = Surface.ROTATION_90;
1689                mUpsideDownRotation = Surface.ROTATION_270;
1690            } else {
1691                mPortraitRotation = Surface.ROTATION_270;
1692                mUpsideDownRotation = Surface.ROTATION_90;
1693            }
1694        } else {
1695            shortSize = width;
1696            longSize = height;
1697            mPortraitRotation = Surface.ROTATION_0;
1698            mUpsideDownRotation = Surface.ROTATION_180;
1699            if (res.getBoolean(com.android.internal.R.bool.config_reverseDefaultRotation)) {
1700                mLandscapeRotation = Surface.ROTATION_270;
1701                mSeascapeRotation = Surface.ROTATION_90;
1702            } else {
1703                mLandscapeRotation = Surface.ROTATION_90;
1704                mSeascapeRotation = Surface.ROTATION_270;
1705            }
1706        }
1707
1708        mStatusBarHeight =
1709                res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
1710
1711        // Height of the navigation bar when presented horizontally at bottom
1712        mNavigationBarHeightForRotationDefault[mPortraitRotation] =
1713        mNavigationBarHeightForRotationDefault[mUpsideDownRotation] =
1714                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_height);
1715        mNavigationBarHeightForRotationDefault[mLandscapeRotation] =
1716        mNavigationBarHeightForRotationDefault[mSeascapeRotation] = res.getDimensionPixelSize(
1717                com.android.internal.R.dimen.navigation_bar_height_landscape);
1718
1719        // Width of the navigation bar when presented vertically along one side
1720        mNavigationBarWidthForRotationDefault[mPortraitRotation] =
1721        mNavigationBarWidthForRotationDefault[mUpsideDownRotation] =
1722        mNavigationBarWidthForRotationDefault[mLandscapeRotation] =
1723        mNavigationBarWidthForRotationDefault[mSeascapeRotation] =
1724                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_width);
1725
1726        // Height of the navigation bar when presented horizontally at bottom
1727        mNavigationBarHeightForRotationInCarMode[mPortraitRotation] =
1728        mNavigationBarHeightForRotationInCarMode[mUpsideDownRotation] =
1729                res.getDimensionPixelSize(
1730                        com.android.internal.R.dimen.navigation_bar_height_car_mode);
1731        mNavigationBarHeightForRotationInCarMode[mLandscapeRotation] =
1732        mNavigationBarHeightForRotationInCarMode[mSeascapeRotation] = res.getDimensionPixelSize(
1733                com.android.internal.R.dimen.navigation_bar_height_landscape_car_mode);
1734
1735        // Width of the navigation bar when presented vertically along one side
1736        mNavigationBarWidthForRotationInCarMode[mPortraitRotation] =
1737        mNavigationBarWidthForRotationInCarMode[mUpsideDownRotation] =
1738        mNavigationBarWidthForRotationInCarMode[mLandscapeRotation] =
1739        mNavigationBarWidthForRotationInCarMode[mSeascapeRotation] =
1740                res.getDimensionPixelSize(
1741                        com.android.internal.R.dimen.navigation_bar_width_car_mode);
1742
1743        // SystemUI (status bar) layout policy
1744        int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density;
1745        int longSizeDp = longSize * DisplayMetrics.DENSITY_DEFAULT / density;
1746
1747        // Allow the navigation bar to move on non-square small devices (phones).
1748        mNavigationBarCanMove = width != height && shortSizeDp < 600;
1749
1750        mHasNavigationBar = res.getBoolean(com.android.internal.R.bool.config_showNavigationBar);
1751        // Allow a system property to override this. Used by the emulator.
1752        // See also hasNavigationBar().
1753        String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
1754        if ("1".equals(navBarOverride)) {
1755            mHasNavigationBar = false;
1756        } else if ("0".equals(navBarOverride)) {
1757            mHasNavigationBar = true;
1758        }
1759
1760        // For demo purposes, allow the rotation of the HDMI display to be controlled.
1761        // By default, HDMI locks rotation to landscape.
1762        if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) {
1763            mDemoHdmiRotation = mPortraitRotation;
1764        } else {
1765            mDemoHdmiRotation = mLandscapeRotation;
1766        }
1767        mDemoHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", false);
1768
1769        // For demo purposes, allow the rotation of the remote display to be controlled.
1770        // By default, remote display locks rotation to landscape.
1771        if ("portrait".equals(SystemProperties.get("persist.demo.remoterotation"))) {
1772            mDemoRotation = mPortraitRotation;
1773        } else {
1774            mDemoRotation = mLandscapeRotation;
1775        }
1776        mDemoRotationLock = SystemProperties.getBoolean(
1777                "persist.demo.rotationlock", false);
1778
1779        // Only force the default orientation if the screen is xlarge, at least 960dp x 720dp, per
1780        // http://developer.android.com/guide/practices/screens_support.html#range
1781        mForceDefaultOrientation = longSizeDp >= 960 && shortSizeDp >= 720 &&
1782                res.getBoolean(com.android.internal.R.bool.config_forceDefaultOrientation) &&
1783                // For debug purposes the next line turns this feature off with:
1784                // $ adb shell setprop config.override_forced_orient true
1785                // $ adb shell wm size reset
1786                !"true".equals(SystemProperties.get("config.override_forced_orient"));
1787    }
1788
1789    /**
1790     * @return whether the navigation bar can be hidden, e.g. the device has a
1791     *         navigation bar and touch exploration is not enabled
1792     */
1793    private boolean canHideNavigationBar() {
1794        return mHasNavigationBar;
1795    }
1796
1797    @Override
1798    public boolean isDefaultOrientationForced() {
1799        return mForceDefaultOrientation;
1800    }
1801
1802    @Override
1803    public void setDisplayOverscan(Display display, int left, int top, int right, int bottom) {
1804        if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
1805            mOverscanLeft = left;
1806            mOverscanTop = top;
1807            mOverscanRight = right;
1808            mOverscanBottom = bottom;
1809        }
1810    }
1811
1812    public void updateSettings() {
1813        ContentResolver resolver = mContext.getContentResolver();
1814        boolean updateRotation = false;
1815        synchronized (mLock) {
1816            mEndcallBehavior = Settings.System.getIntForUser(resolver,
1817                    Settings.System.END_BUTTON_BEHAVIOR,
1818                    Settings.System.END_BUTTON_BEHAVIOR_DEFAULT,
1819                    UserHandle.USER_CURRENT);
1820            mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver,
1821                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
1822                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT,
1823                    UserHandle.USER_CURRENT);
1824
1825            // Configure wake gesture.
1826            boolean wakeGestureEnabledSetting = Settings.Secure.getIntForUser(resolver,
1827                    Settings.Secure.WAKE_GESTURE_ENABLED, 0,
1828                    UserHandle.USER_CURRENT) != 0;
1829            if (mWakeGestureEnabledSetting != wakeGestureEnabledSetting) {
1830                mWakeGestureEnabledSetting = wakeGestureEnabledSetting;
1831                updateWakeGestureListenerLp();
1832            }
1833
1834            // Configure rotation lock.
1835            int userRotation = Settings.System.getIntForUser(resolver,
1836                    Settings.System.USER_ROTATION, Surface.ROTATION_0,
1837                    UserHandle.USER_CURRENT);
1838            if (mUserRotation != userRotation) {
1839                mUserRotation = userRotation;
1840                updateRotation = true;
1841            }
1842            int userRotationMode = Settings.System.getIntForUser(resolver,
1843                    Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
1844                            WindowManagerPolicy.USER_ROTATION_FREE :
1845                                    WindowManagerPolicy.USER_ROTATION_LOCKED;
1846            if (mUserRotationMode != userRotationMode) {
1847                mUserRotationMode = userRotationMode;
1848                updateRotation = true;
1849                updateOrientationListenerLp();
1850            }
1851
1852            if (mSystemReady) {
1853                int pointerLocation = Settings.System.getIntForUser(resolver,
1854                        Settings.System.POINTER_LOCATION, 0, UserHandle.USER_CURRENT);
1855                if (mPointerLocationMode != pointerLocation) {
1856                    mPointerLocationMode = pointerLocation;
1857                    mHandler.sendEmptyMessage(pointerLocation != 0 ?
1858                            MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION);
1859                }
1860            }
1861            // use screen off timeout setting as the timeout for the lockscreen
1862            mLockScreenTimeout = Settings.System.getIntForUser(resolver,
1863                    Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT);
1864            String imId = Settings.Secure.getStringForUser(resolver,
1865                    Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT);
1866            boolean hasSoftInput = imId != null && imId.length() > 0;
1867            if (mHasSoftInput != hasSoftInput) {
1868                mHasSoftInput = hasSoftInput;
1869                updateRotation = true;
1870            }
1871            if (mImmersiveModeConfirmation != null) {
1872                mImmersiveModeConfirmation.loadSetting(mCurrentUserId);
1873            }
1874        }
1875        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
1876            PolicyControl.reloadFromSetting(mContext);
1877        }
1878        if (updateRotation) {
1879            updateRotation(true);
1880        }
1881    }
1882
1883    private void updateWakeGestureListenerLp() {
1884        if (shouldEnableWakeGestureLp()) {
1885            mWakeGestureListener.requestWakeUpTrigger();
1886        } else {
1887            mWakeGestureListener.cancelWakeUpTrigger();
1888        }
1889    }
1890
1891    private boolean shouldEnableWakeGestureLp() {
1892        return mWakeGestureEnabledSetting && !mAwake
1893                && (!mLidControlsSleep || mLidState != LID_CLOSED)
1894                && mWakeGestureListener.isSupported();
1895    }
1896
1897    private void enablePointerLocation() {
1898        if (mPointerLocationView == null) {
1899            mPointerLocationView = new PointerLocationView(mContext);
1900            mPointerLocationView.setPrintCoords(false);
1901            WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1902                    WindowManager.LayoutParams.MATCH_PARENT,
1903                    WindowManager.LayoutParams.MATCH_PARENT);
1904            lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
1905            lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
1906                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
1907                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1908                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
1909            if (ActivityManager.isHighEndGfx()) {
1910                lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1911                lp.privateFlags |=
1912                        WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
1913            }
1914            lp.format = PixelFormat.TRANSLUCENT;
1915            lp.setTitle("PointerLocation");
1916            WindowManager wm = (WindowManager)
1917                    mContext.getSystemService(Context.WINDOW_SERVICE);
1918            lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
1919            wm.addView(mPointerLocationView, lp);
1920            mWindowManagerFuncs.registerPointerEventListener(mPointerLocationView);
1921        }
1922    }
1923
1924    private void disablePointerLocation() {
1925        if (mPointerLocationView != null) {
1926            mWindowManagerFuncs.unregisterPointerEventListener(mPointerLocationView);
1927            WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
1928            wm.removeView(mPointerLocationView);
1929            mPointerLocationView = null;
1930        }
1931    }
1932
1933    private int readRotation(int resID) {
1934        try {
1935            int rotation = mContext.getResources().getInteger(resID);
1936            switch (rotation) {
1937                case 0:
1938                    return Surface.ROTATION_0;
1939                case 90:
1940                    return Surface.ROTATION_90;
1941                case 180:
1942                    return Surface.ROTATION_180;
1943                case 270:
1944                    return Surface.ROTATION_270;
1945            }
1946        } catch (Resources.NotFoundException e) {
1947            // fall through
1948        }
1949        return -1;
1950    }
1951
1952    /** {@inheritDoc} */
1953    @Override
1954    public int checkAddPermission(WindowManager.LayoutParams attrs, int[] outAppOp) {
1955        int type = attrs.type;
1956
1957        outAppOp[0] = AppOpsManager.OP_NONE;
1958
1959        if (!((type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW)
1960                || (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW)
1961                || (type >= FIRST_SYSTEM_WINDOW && type <= LAST_SYSTEM_WINDOW))) {
1962            return WindowManagerGlobal.ADD_INVALID_TYPE;
1963        }
1964
1965        if (type < FIRST_SYSTEM_WINDOW || type > LAST_SYSTEM_WINDOW) {
1966            // Window manager will make sure these are okay.
1967            return WindowManagerGlobal.ADD_OKAY;
1968        }
1969        String permission = null;
1970        switch (type) {
1971            case TYPE_TOAST:
1972                // XXX right now the app process has complete control over
1973                // this...  should introduce a token to let the system
1974                // monitor/control what they are doing.
1975                outAppOp[0] = AppOpsManager.OP_TOAST_WINDOW;
1976                break;
1977            case TYPE_DREAM:
1978            case TYPE_INPUT_METHOD:
1979            case TYPE_WALLPAPER:
1980            case TYPE_PRIVATE_PRESENTATION:
1981            case TYPE_VOICE_INTERACTION:
1982            case TYPE_ACCESSIBILITY_OVERLAY:
1983            case TYPE_QS_DIALOG:
1984                // The window manager will check these.
1985                break;
1986            case TYPE_PHONE:
1987            case TYPE_PRIORITY_PHONE:
1988            case TYPE_SYSTEM_ALERT:
1989            case TYPE_SYSTEM_ERROR:
1990            case TYPE_SYSTEM_OVERLAY:
1991                permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
1992                outAppOp[0] = AppOpsManager.OP_SYSTEM_ALERT_WINDOW;
1993                break;
1994            default:
1995                permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
1996        }
1997        if (permission != null) {
1998            if (permission == android.Manifest.permission.SYSTEM_ALERT_WINDOW) {
1999                final int callingUid = Binder.getCallingUid();
2000                // system processes will be automatically allowed privilege to draw
2001                if (callingUid == Process.SYSTEM_UID) {
2002                    return WindowManagerGlobal.ADD_OKAY;
2003                }
2004
2005                // check if user has enabled this operation. SecurityException will be thrown if
2006                // this app has not been allowed by the user
2007                final int mode = mAppOpsManager.checkOp(outAppOp[0], callingUid,
2008                        attrs.packageName);
2009                switch (mode) {
2010                    case AppOpsManager.MODE_ALLOWED:
2011                    case AppOpsManager.MODE_IGNORED:
2012                        // although we return ADD_OKAY for MODE_IGNORED, the added window will
2013                        // actually be hidden in WindowManagerService
2014                        return WindowManagerGlobal.ADD_OKAY;
2015                    case AppOpsManager.MODE_ERRORED:
2016                        return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2017                    default:
2018                        // in the default mode, we will make a decision here based on
2019                        // checkCallingPermission()
2020                        if (mContext.checkCallingPermission(permission) !=
2021                                PackageManager.PERMISSION_GRANTED) {
2022                            return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2023                        } else {
2024                            return WindowManagerGlobal.ADD_OKAY;
2025                        }
2026                }
2027            }
2028
2029            if (mContext.checkCallingOrSelfPermission(permission)
2030                    != PackageManager.PERMISSION_GRANTED) {
2031                return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2032            }
2033        }
2034        return WindowManagerGlobal.ADD_OKAY;
2035    }
2036
2037    @Override
2038    public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) {
2039
2040        // If this switch statement is modified, modify the comment in the declarations of
2041        // the type in {@link WindowManager.LayoutParams} as well.
2042        switch (attrs.type) {
2043            default:
2044                // These are the windows that by default are shown only to the user that created
2045                // them. If this needs to be overridden, set
2046                // {@link WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS} in
2047                // {@link WindowManager.LayoutParams}. Note that permission
2048                // {@link android.Manifest.permission.INTERNAL_SYSTEM_WINDOW} is required as well.
2049                if ((attrs.privateFlags & PRIVATE_FLAG_SHOW_FOR_ALL_USERS) == 0) {
2050                    return true;
2051                }
2052                break;
2053
2054            // These are the windows that by default are shown to all users. However, to
2055            // protect against spoofing, check permissions below.
2056            case TYPE_APPLICATION_STARTING:
2057            case TYPE_BOOT_PROGRESS:
2058            case TYPE_DISPLAY_OVERLAY:
2059            case TYPE_INPUT_CONSUMER:
2060            case TYPE_KEYGUARD_SCRIM:
2061            case TYPE_KEYGUARD_DIALOG:
2062            case TYPE_MAGNIFICATION_OVERLAY:
2063            case TYPE_NAVIGATION_BAR:
2064            case TYPE_NAVIGATION_BAR_PANEL:
2065            case TYPE_PHONE:
2066            case TYPE_POINTER:
2067            case TYPE_PRIORITY_PHONE:
2068            case TYPE_SEARCH_BAR:
2069            case TYPE_STATUS_BAR:
2070            case TYPE_STATUS_BAR_PANEL:
2071            case TYPE_STATUS_BAR_SUB_PANEL:
2072            case TYPE_SYSTEM_DIALOG:
2073            case TYPE_VOLUME_OVERLAY:
2074            case TYPE_PRIVATE_PRESENTATION:
2075            case TYPE_DOCK_DIVIDER:
2076                break;
2077        }
2078
2079        // Check if third party app has set window to system window type.
2080        return mContext.checkCallingOrSelfPermission(
2081                android.Manifest.permission.INTERNAL_SYSTEM_WINDOW)
2082                        != PackageManager.PERMISSION_GRANTED;
2083    }
2084
2085    @Override
2086    public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
2087        switch (attrs.type) {
2088            case TYPE_SYSTEM_OVERLAY:
2089            case TYPE_SECURE_SYSTEM_OVERLAY:
2090                // These types of windows can't receive input events.
2091                attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
2092                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
2093                attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
2094                break;
2095            case TYPE_STATUS_BAR:
2096
2097                // If the Keyguard is in a hidden state (occluded by another window), we force to
2098                // remove the wallpaper and keyguard flag so that any change in-flight after setting
2099                // the keyguard as occluded wouldn't set these flags again.
2100                // See {@link #processKeyguardSetHiddenResultLw}.
2101                if (mKeyguardHidden) {
2102                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2103                    attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2104                }
2105                break;
2106        }
2107
2108        if (attrs.type != TYPE_STATUS_BAR) {
2109            // The status bar is the only window allowed to exhibit keyguard behavior.
2110            attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2111        }
2112
2113        if (ActivityManager.isHighEndGfx()) {
2114            if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0) {
2115                attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
2116            }
2117            if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
2118                    || (mForceWindowDrawsStatusBarBackground
2119                            && attrs.height == MATCH_PARENT && attrs.width == MATCH_PARENT)) {
2120                attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2121            }
2122        }
2123    }
2124
2125    void readLidState() {
2126        mLidState = mWindowManagerFuncs.getLidState();
2127    }
2128
2129    private void readCameraLensCoverState() {
2130        mCameraLensCoverState = mWindowManagerFuncs.getCameraLensCoverState();
2131    }
2132
2133    private boolean isHidden(int accessibilityMode) {
2134        switch (accessibilityMode) {
2135            case 1:
2136                return mLidState == LID_CLOSED;
2137            case 2:
2138                return mLidState == LID_OPEN;
2139            default:
2140                return false;
2141        }
2142    }
2143
2144    /** {@inheritDoc} */
2145    @Override
2146    public void adjustConfigurationLw(Configuration config, int keyboardPresence,
2147            int navigationPresence) {
2148        mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
2149
2150        readConfigurationDependentBehaviors();
2151        readLidState();
2152        applyLidSwitchState();
2153
2154        if (config.keyboard == Configuration.KEYBOARD_NOKEYS
2155                || (keyboardPresence == PRESENCE_INTERNAL
2156                        && isHidden(mLidKeyboardAccessibility))) {
2157            config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
2158            if (!mHasSoftInput) {
2159                config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
2160            }
2161        }
2162
2163        if (config.navigation == Configuration.NAVIGATION_NONAV
2164                || (navigationPresence == PRESENCE_INTERNAL
2165                        && isHidden(mLidNavigationAccessibility))) {
2166            config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
2167        }
2168    }
2169
2170    /** {@inheritDoc} */
2171    @Override
2172    public int windowTypeToLayerLw(int type) {
2173        if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
2174            return 2;
2175        }
2176        switch (type) {
2177        case TYPE_PRIVATE_PRESENTATION:
2178            return 2;
2179        case TYPE_WALLPAPER:
2180            // wallpaper is at the bottom, though the window manager may move it.
2181            return 2;
2182        case TYPE_DOCK_DIVIDER:
2183            return 2;
2184        case TYPE_QS_DIALOG:
2185            return 2;
2186        case TYPE_PHONE:
2187            return 3;
2188        case TYPE_SEARCH_BAR:
2189        case TYPE_VOICE_INTERACTION_STARTING:
2190            return 4;
2191        case TYPE_VOICE_INTERACTION:
2192            // voice interaction layer is almost immediately above apps.
2193            return 5;
2194        case TYPE_INPUT_CONSUMER:
2195            return 6;
2196        case TYPE_SYSTEM_DIALOG:
2197            return 7;
2198        case TYPE_TOAST:
2199            // toasts and the plugged-in battery thing
2200            return 8;
2201        case TYPE_PRIORITY_PHONE:
2202            // SIM errors and unlock.  Not sure if this really should be in a high layer.
2203            return 9;
2204        case TYPE_DREAM:
2205            // used for Dreams (screensavers with TYPE_DREAM windows)
2206            return 10;
2207        case TYPE_SYSTEM_ALERT:
2208            // like the ANR / app crashed dialogs
2209            return 11;
2210        case TYPE_INPUT_METHOD:
2211            // on-screen keyboards and other such input method user interfaces go here.
2212            return 12;
2213        case TYPE_INPUT_METHOD_DIALOG:
2214            // on-screen keyboards and other such input method user interfaces go here.
2215            return 13;
2216        case TYPE_KEYGUARD_SCRIM:
2217            // the safety window that shows behind keyguard while keyguard is starting
2218            return 14;
2219        case TYPE_STATUS_BAR_SUB_PANEL:
2220            return 15;
2221        case TYPE_STATUS_BAR:
2222            return 16;
2223        case TYPE_STATUS_BAR_PANEL:
2224            return 17;
2225        case TYPE_KEYGUARD_DIALOG:
2226            return 18;
2227        case TYPE_VOLUME_OVERLAY:
2228            // the on-screen volume indicator and controller shown when the user
2229            // changes the device volume
2230            return 19;
2231        case TYPE_SYSTEM_OVERLAY:
2232            // the on-screen volume indicator and controller shown when the user
2233            // changes the device volume
2234            return 20;
2235        case TYPE_NAVIGATION_BAR:
2236            // the navigation bar, if available, shows atop most things
2237            return 21;
2238        case TYPE_NAVIGATION_BAR_PANEL:
2239            // some panels (e.g. search) need to show on top of the navigation bar
2240            return 22;
2241        case TYPE_SYSTEM_ERROR:
2242            // system-level error dialogs
2243            return 23;
2244        case TYPE_MAGNIFICATION_OVERLAY:
2245            // used to highlight the magnified portion of a display
2246            return 24;
2247        case TYPE_DISPLAY_OVERLAY:
2248            // used to simulate secondary display devices
2249            return 25;
2250        case TYPE_DRAG:
2251            // the drag layer: input for drag-and-drop is associated with this window,
2252            // which sits above all other focusable windows
2253            return 26;
2254        case TYPE_ACCESSIBILITY_OVERLAY:
2255            // overlay put by accessibility services to intercept user interaction
2256            return 27;
2257        case TYPE_SECURE_SYSTEM_OVERLAY:
2258            return 28;
2259        case TYPE_BOOT_PROGRESS:
2260            return 29;
2261        case TYPE_POINTER:
2262            // the (mouse) pointer layer
2263            return 30;
2264        }
2265        Log.e(TAG, "Unknown window type: " + type);
2266        return 2;
2267    }
2268
2269    /** {@inheritDoc} */
2270    @Override
2271    public int subWindowTypeToLayerLw(int type) {
2272        switch (type) {
2273        case TYPE_APPLICATION_PANEL:
2274        case TYPE_APPLICATION_ATTACHED_DIALOG:
2275            return APPLICATION_PANEL_SUBLAYER;
2276        case TYPE_APPLICATION_MEDIA:
2277            return APPLICATION_MEDIA_SUBLAYER;
2278        case TYPE_APPLICATION_MEDIA_OVERLAY:
2279            return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
2280        case TYPE_APPLICATION_SUB_PANEL:
2281            return APPLICATION_SUB_PANEL_SUBLAYER;
2282        case TYPE_APPLICATION_ABOVE_SUB_PANEL:
2283            return APPLICATION_ABOVE_SUB_PANEL_SUBLAYER;
2284        }
2285        Log.e(TAG, "Unknown sub-window type: " + type);
2286        return 0;
2287    }
2288
2289    @Override
2290    public int getMaxWallpaperLayer() {
2291        return windowTypeToLayerLw(TYPE_STATUS_BAR);
2292    }
2293
2294    private int getNavigationBarWidth(int rotation, int uiMode) {
2295        if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2296            return mNavigationBarWidthForRotationInCarMode[rotation];
2297        } else {
2298            return mNavigationBarWidthForRotationDefault[rotation];
2299        }
2300    }
2301
2302    @Override
2303    public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation,
2304            int uiMode) {
2305        if (mHasNavigationBar) {
2306            // For a basic navigation bar, when we are in landscape mode we place
2307            // the navigation bar to the side.
2308            if (mNavigationBarCanMove && fullWidth > fullHeight) {
2309                return fullWidth - getNavigationBarWidth(rotation, uiMode);
2310            }
2311        }
2312        return fullWidth;
2313    }
2314
2315    private int getNavigationBarHeight(int rotation, int uiMode) {
2316        if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2317            return mNavigationBarHeightForRotationInCarMode[rotation];
2318        } else {
2319            return mNavigationBarHeightForRotationDefault[rotation];
2320        }
2321    }
2322
2323    @Override
2324    public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation,
2325            int uiMode) {
2326        if (mHasNavigationBar) {
2327            // For a basic navigation bar, when we are in portrait mode we place
2328            // the navigation bar to the bottom.
2329            if (!mNavigationBarCanMove || fullWidth < fullHeight) {
2330                return fullHeight - getNavigationBarHeight(rotation, uiMode);
2331            }
2332        }
2333        return fullHeight;
2334    }
2335
2336    @Override
2337    public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode) {
2338        return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation, uiMode);
2339    }
2340
2341    @Override
2342    public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation, int uiMode) {
2343        // There is a separate status bar at the top of the display.  We don't count that as part
2344        // of the fixed decor, since it can hide; however, for purposes of configurations,
2345        // we do want to exclude it since applications can't generally use that part
2346        // of the screen.
2347        return getNonDecorDisplayHeight(
2348                fullWidth, fullHeight, rotation, uiMode) - mStatusBarHeight;
2349    }
2350
2351    @Override
2352    public boolean isForceHiding(WindowManager.LayoutParams attrs) {
2353        return (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 ||
2354                (isKeyguardHostWindow(attrs) &&
2355                        (mKeyguardDelegate != null && mKeyguardDelegate.isShowing())) ||
2356                (attrs.type == TYPE_KEYGUARD_SCRIM);
2357    }
2358
2359    @Override
2360    public boolean isKeyguardHostWindow(WindowManager.LayoutParams attrs) {
2361        return attrs.type == TYPE_STATUS_BAR;
2362    }
2363
2364    @Override
2365    public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
2366        switch (attrs.type) {
2367            case TYPE_STATUS_BAR:
2368            case TYPE_NAVIGATION_BAR:
2369            case TYPE_WALLPAPER:
2370            case TYPE_DREAM:
2371            case TYPE_KEYGUARD_SCRIM:
2372            case TYPE_DOCK_DIVIDER:
2373                return false;
2374            default:
2375                // Hide only windows below the keyguard host window.
2376                return windowTypeToLayerLw(win.getBaseType())
2377                        < windowTypeToLayerLw(TYPE_STATUS_BAR);
2378        }
2379    }
2380
2381    @Override
2382    public WindowState getWinShowWhenLockedLw() {
2383        return mWinShowWhenLocked;
2384    }
2385
2386    /** {@inheritDoc} */
2387    @Override
2388    public View addStartingWindow(IBinder appToken, String packageName, int theme,
2389            CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes,
2390            int icon, int logo, int windowFlags) {
2391        if (!SHOW_STARTING_ANIMATIONS) {
2392            return null;
2393        }
2394        if (packageName == null) {
2395            return null;
2396        }
2397
2398        WindowManager wm = null;
2399        View view = null;
2400
2401        try {
2402            Context context = mContext;
2403            if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName
2404                    + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme="
2405                    + Integer.toHexString(theme));
2406            if (theme != context.getThemeResId() || labelRes != 0) {
2407                try {
2408                    context = context.createPackageContext(packageName, 0);
2409                    context.setTheme(theme);
2410                } catch (PackageManager.NameNotFoundException e) {
2411                    // Ignore
2412                }
2413            }
2414
2415            PhoneWindow win = new PhoneWindow(context);
2416            win.setIsStartingWindow(true);
2417
2418            Resources r = context.getResources();
2419            win.setTitle(r.getText(labelRes, nonLocalizedLabel));
2420
2421            win.setType(
2422                WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
2423
2424            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
2425                // Assumes it's safe to show starting windows of launched apps while
2426                // the keyguard is being hidden. This is okay because starting windows never show
2427                // secret information.
2428                if (mKeyguardHidden) {
2429                    windowFlags |= FLAG_SHOW_WHEN_LOCKED;
2430                }
2431            }
2432
2433            // Force the window flags: this is a fake window, so it is not really
2434            // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
2435            // flag because we do know that the next window will take input
2436            // focus, so we want to get the IME window up on top of us right away.
2437            win.setFlags(
2438                windowFlags|
2439                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2440                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2441                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
2442                windowFlags|
2443                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2444                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2445                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
2446
2447            win.setDefaultIcon(icon);
2448            win.setDefaultLogo(logo);
2449
2450            win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
2451                    WindowManager.LayoutParams.MATCH_PARENT);
2452
2453            final WindowManager.LayoutParams params = win.getAttributes();
2454            params.token = appToken;
2455            params.packageName = packageName;
2456            params.windowAnimations = win.getWindowStyle().getResourceId(
2457                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2458            params.privateFlags |=
2459                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
2460            params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
2461
2462            if (!compatInfo.supportsScreen()) {
2463                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2464            }
2465
2466            params.setTitle("Starting " + packageName);
2467
2468            wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
2469            view = win.getDecorView();
2470
2471            if (DEBUG_STARTING_WINDOW) Slog.d(
2472                TAG, "Adding starting window for " + packageName
2473                + " / " + appToken + ": "
2474                + (view.getParent() != null ? view : null));
2475
2476            wm.addView(view, params);
2477
2478            // Only return the view if it was successfully added to the
2479            // window manager... which we can tell by it having a parent.
2480            return view.getParent() != null ? view : null;
2481        } catch (WindowManager.BadTokenException e) {
2482            // ignore
2483            Log.w(TAG, appToken + " already running, starting window not displayed. " +
2484                    e.getMessage());
2485        } catch (RuntimeException e) {
2486            // don't crash if something else bad happens, for example a
2487            // failure loading resources because we are loading from an app
2488            // on external storage that has been unmounted.
2489            Log.w(TAG, appToken + " failed creating starting window", e);
2490        } finally {
2491            if (view != null && view.getParent() == null) {
2492                Log.w(TAG, "view not successfully added to wm, removing view");
2493                wm.removeViewImmediate(view);
2494            }
2495        }
2496
2497        return null;
2498    }
2499
2500    /** {@inheritDoc} */
2501    @Override
2502    public void removeStartingWindow(IBinder appToken, View window) {
2503        if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Removing starting window for " + appToken + ": "
2504                + window + " Callers=" + Debug.getCallers(4));
2505
2506        if (window != null) {
2507            WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
2508            wm.removeView(window);
2509        }
2510    }
2511
2512    /**
2513     * Preflight adding a window to the system.
2514     *
2515     * Currently enforces that three window types are singletons:
2516     * <ul>
2517     * <li>STATUS_BAR_TYPE</li>
2518     * <li>KEYGUARD_TYPE</li>
2519     * </ul>
2520     *
2521     * @param win The window to be added
2522     * @param attrs Information about the window to be added
2523     *
2524     * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
2525     * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
2526     */
2527    @Override
2528    public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
2529        switch (attrs.type) {
2530            case TYPE_STATUS_BAR:
2531                mContext.enforceCallingOrSelfPermission(
2532                        android.Manifest.permission.STATUS_BAR_SERVICE,
2533                        "PhoneWindowManager");
2534                if (mStatusBar != null) {
2535                    if (mStatusBar.isAlive()) {
2536                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2537                    }
2538                }
2539                mStatusBar = win;
2540                mStatusBarController.setWindow(win);
2541                break;
2542            case TYPE_NAVIGATION_BAR:
2543                mContext.enforceCallingOrSelfPermission(
2544                        android.Manifest.permission.STATUS_BAR_SERVICE,
2545                        "PhoneWindowManager");
2546                if (mNavigationBar != null) {
2547                    if (mNavigationBar.isAlive()) {
2548                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2549                    }
2550                }
2551                mNavigationBar = win;
2552                mNavigationBarController.setWindow(win);
2553                if (DEBUG_LAYOUT) Slog.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
2554                break;
2555            case TYPE_NAVIGATION_BAR_PANEL:
2556            case TYPE_STATUS_BAR_PANEL:
2557            case TYPE_STATUS_BAR_SUB_PANEL:
2558            case TYPE_VOICE_INTERACTION_STARTING:
2559                mContext.enforceCallingOrSelfPermission(
2560                        android.Manifest.permission.STATUS_BAR_SERVICE,
2561                        "PhoneWindowManager");
2562                break;
2563            case TYPE_KEYGUARD_SCRIM:
2564                if (mKeyguardScrim != null) {
2565                    return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2566                }
2567                mKeyguardScrim = win;
2568                break;
2569        }
2570        return WindowManagerGlobal.ADD_OKAY;
2571    }
2572
2573    /** {@inheritDoc} */
2574    @Override
2575    public void removeWindowLw(WindowState win) {
2576        if (mStatusBar == win) {
2577            mStatusBar = null;
2578            mStatusBarController.setWindow(null);
2579            mKeyguardDelegate.showScrim();
2580        } else if (mKeyguardScrim == win) {
2581            Log.v(TAG, "Removing keyguard scrim");
2582            mKeyguardScrim = null;
2583        } if (mNavigationBar == win) {
2584            mNavigationBar = null;
2585            mNavigationBarController.setWindow(null);
2586        }
2587    }
2588
2589    static final boolean PRINT_ANIM = false;
2590
2591    /** {@inheritDoc} */
2592    @Override
2593    public int selectAnimationLw(WindowState win, int transit) {
2594        if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
2595              + ": transit=" + transit);
2596        if (win == mStatusBar) {
2597            boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
2598            if (transit == TRANSIT_EXIT
2599                    || transit == TRANSIT_HIDE) {
2600                return isKeyguard ? -1 : R.anim.dock_top_exit;
2601            } else if (transit == TRANSIT_ENTER
2602                    || transit == TRANSIT_SHOW) {
2603                return isKeyguard ? -1 : R.anim.dock_top_enter;
2604            }
2605        } else if (win == mNavigationBar) {
2606            if (win.getAttrs().windowAnimations != 0) {
2607                return 0;
2608            }
2609            // This can be on either the bottom or the right.
2610            if (mNavigationBarOnBottom) {
2611                if (transit == TRANSIT_EXIT
2612                        || transit == TRANSIT_HIDE) {
2613                    return R.anim.dock_bottom_exit;
2614                } else if (transit == TRANSIT_ENTER
2615                        || transit == TRANSIT_SHOW) {
2616                    return R.anim.dock_bottom_enter;
2617                }
2618            } else {
2619                if (transit == TRANSIT_EXIT
2620                        || transit == TRANSIT_HIDE) {
2621                    return R.anim.dock_right_exit;
2622                } else if (transit == TRANSIT_ENTER
2623                        || transit == TRANSIT_SHOW) {
2624                    return R.anim.dock_right_enter;
2625                }
2626            }
2627        } else if (win.getAttrs().type == TYPE_DOCK_DIVIDER) {
2628            if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) {
2629                return R.anim.fade_in;
2630            } else if (transit == TRANSIT_EXIT) {
2631                return R.anim.fade_out;
2632            }
2633        }
2634
2635        if (transit == TRANSIT_PREVIEW_DONE) {
2636            if (win.hasAppShownWindows()) {
2637                if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
2638                return com.android.internal.R.anim.app_starting_exit;
2639            }
2640        } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
2641                && transit == TRANSIT_ENTER) {
2642            // Special case: we are animating in a dream, while the keyguard
2643            // is shown.  We don't want an animation on the dream, because
2644            // we need it shown immediately with the keyguard animating away
2645            // to reveal it.
2646            return -1;
2647        }
2648
2649        return 0;
2650    }
2651
2652    @Override
2653    public void selectRotationAnimationLw(int anim[]) {
2654        if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
2655                + mTopFullscreenOpaqueWindowState + " rotationAnimation="
2656                + (mTopFullscreenOpaqueWindowState == null ?
2657                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
2658        if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
2659            switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
2660                case ROTATION_ANIMATION_CROSSFADE:
2661                    anim[0] = R.anim.rotation_animation_xfade_exit;
2662                    anim[1] = R.anim.rotation_animation_enter;
2663                    break;
2664                case ROTATION_ANIMATION_JUMPCUT:
2665                    anim[0] = R.anim.rotation_animation_jump_exit;
2666                    anim[1] = R.anim.rotation_animation_enter;
2667                    break;
2668                case ROTATION_ANIMATION_ROTATE:
2669                default:
2670                    anim[0] = anim[1] = 0;
2671                    break;
2672            }
2673        } else {
2674            anim[0] = anim[1] = 0;
2675        }
2676    }
2677
2678    @Override
2679    public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
2680            boolean forceDefault) {
2681        switch (exitAnimId) {
2682            case R.anim.rotation_animation_xfade_exit:
2683            case R.anim.rotation_animation_jump_exit:
2684                // These are the only cases that matter.
2685                if (forceDefault) {
2686                    return false;
2687                }
2688                int anim[] = new int[2];
2689                selectRotationAnimationLw(anim);
2690                return (exitAnimId == anim[0] && enterAnimId == anim[1]);
2691            default:
2692                return true;
2693        }
2694    }
2695
2696    @Override
2697    public Animation createForceHideEnterAnimation(boolean onWallpaper,
2698            boolean goingToNotificationShade) {
2699        if (goingToNotificationShade) {
2700            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_behind_enter_fade_in);
2701        }
2702
2703        AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(mContext, onWallpaper ?
2704                    R.anim.lock_screen_behind_enter_wallpaper :
2705                    R.anim.lock_screen_behind_enter);
2706
2707        // TODO: Use XML interpolators when we have log interpolators available in XML.
2708        final List<Animation> animations = set.getAnimations();
2709        for (int i = animations.size() - 1; i >= 0; --i) {
2710            animations.get(i).setInterpolator(mLogDecelerateInterpolator);
2711        }
2712
2713        return set;
2714    }
2715
2716
2717    @Override
2718    public Animation createForceHideWallpaperExitAnimation(boolean goingToNotificationShade) {
2719        if (goingToNotificationShade) {
2720            return null;
2721        } else {
2722            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_wallpaper_exit);
2723        }
2724    }
2725
2726    private static void awakenDreams() {
2727        IDreamManager dreamManager = getDreamManager();
2728        if (dreamManager != null) {
2729            try {
2730                dreamManager.awaken();
2731            } catch (RemoteException e) {
2732                // fine, stay asleep then
2733            }
2734        }
2735    }
2736
2737    static IDreamManager getDreamManager() {
2738        return IDreamManager.Stub.asInterface(
2739                ServiceManager.checkService(DreamService.DREAM_SERVICE));
2740    }
2741
2742    TelecomManager getTelecommService() {
2743        return (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2744    }
2745
2746    static IAudioService getAudioService() {
2747        IAudioService audioService = IAudioService.Stub.asInterface(
2748                ServiceManager.checkService(Context.AUDIO_SERVICE));
2749        if (audioService == null) {
2750            Log.w(TAG, "Unable to find IAudioService interface.");
2751        }
2752        return audioService;
2753    }
2754
2755    boolean keyguardOn() {
2756        return isKeyguardShowingAndNotOccluded() || inKeyguardRestrictedKeyInputMode();
2757    }
2758
2759    private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
2760            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
2761            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
2762        };
2763
2764    /** {@inheritDoc} */
2765    @Override
2766    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
2767        final boolean keyguardOn = keyguardOn();
2768        final int keyCode = event.getKeyCode();
2769        final int repeatCount = event.getRepeatCount();
2770        final int metaState = event.getMetaState();
2771        final int flags = event.getFlags();
2772        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
2773        final boolean canceled = event.isCanceled();
2774
2775        if (DEBUG_INPUT) {
2776            Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
2777                    + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
2778                    + " canceled=" + canceled);
2779        }
2780
2781        // If we think we might have a volume down & power key chord on the way
2782        // but we're not sure, then tell the dispatcher to wait a little while and
2783        // try again later before dispatching.
2784        if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
2785            if (mScreenshotChordVolumeDownKeyTriggered && !mScreenshotChordPowerKeyTriggered) {
2786                final long now = SystemClock.uptimeMillis();
2787                final long timeoutTime = mScreenshotChordVolumeDownKeyTime
2788                        + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
2789                if (now < timeoutTime) {
2790                    return timeoutTime - now;
2791                }
2792            }
2793            if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
2794                    && mScreenshotChordVolumeDownKeyConsumed) {
2795                if (!down) {
2796                    mScreenshotChordVolumeDownKeyConsumed = false;
2797                }
2798                return -1;
2799            }
2800        }
2801
2802        // Cancel any pending meta actions if we see any other keys being pressed between the down
2803        // of the meta key and its corresponding up.
2804        if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) {
2805            mPendingMetaAction = false;
2806        }
2807
2808        // First we always handle the home key here, so applications
2809        // can never break it, although if keyguard is on, we do let
2810        // it handle it, because that gives us the correct 5 second
2811        // timeout.
2812        if (keyCode == KeyEvent.KEYCODE_HOME) {
2813
2814            // If we have released the home key, and didn't do anything else
2815            // while it was pressed, then it is time to go home!
2816            if (!down) {
2817                cancelPreloadRecentApps();
2818
2819                mHomePressed = false;
2820                if (mHomeConsumed) {
2821                    mHomeConsumed = false;
2822                    return -1;
2823                }
2824
2825                if (canceled) {
2826                    Log.i(TAG, "Ignoring HOME; event canceled.");
2827                    return -1;
2828                }
2829
2830                // If an incoming call is ringing, HOME is totally disabled.
2831                // (The user is already on the InCallUI at this point,
2832                // and his ONLY options are to answer or reject the call.)
2833                TelecomManager telecomManager = getTelecommService();
2834                if (telecomManager != null && telecomManager.isRinging()) {
2835                    Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
2836                    return -1;
2837                }
2838
2839                // Delay handling home if a double-tap is possible.
2840                if (mDoubleTapOnHomeBehavior != DOUBLE_TAP_HOME_NOTHING) {
2841                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable); // just in case
2842                    mHomeDoubleTapPending = true;
2843                    mHandler.postDelayed(mHomeDoubleTapTimeoutRunnable,
2844                            ViewConfiguration.getDoubleTapTimeout());
2845                    return -1;
2846                }
2847
2848                handleShortPressOnHome();
2849                return -1;
2850            }
2851
2852            // If a system window has focus, then it doesn't make sense
2853            // right now to interact with applications.
2854            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
2855            if (attrs != null) {
2856                final int type = attrs.type;
2857                if (type == WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM
2858                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
2859                        || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
2860                    // the "app" is keyguard, so give it the key
2861                    return 0;
2862                }
2863                final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
2864                for (int i=0; i<typeCount; i++) {
2865                    if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
2866                        // don't do anything, but also don't pass it to the app
2867                        return -1;
2868                    }
2869                }
2870            }
2871
2872            // Remember that home is pressed and handle special actions.
2873            if (repeatCount == 0) {
2874                mHomePressed = true;
2875                if (mHomeDoubleTapPending) {
2876                    mHomeDoubleTapPending = false;
2877                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable);
2878                    handleDoubleTapOnHome();
2879                } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI
2880                        || mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
2881                    preloadRecentApps();
2882                }
2883            } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
2884                if (!keyguardOn) {
2885                    handleLongPressOnHome(event.getDeviceId(), event);
2886                }
2887            }
2888            return -1;
2889        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
2890            // Hijack modified menu keys for debugging features
2891            final int chordBug = KeyEvent.META_SHIFT_ON;
2892
2893            if (down && repeatCount == 0) {
2894                if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
2895                    Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
2896                    mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
2897                            null, null, null, 0, null, null);
2898                    return -1;
2899                } else if (SHOW_PROCESSES_ON_ALT_MENU &&
2900                        (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
2901                    Intent service = new Intent();
2902                    service.setClassName(mContext, "com.android.server.LoadAverageService");
2903                    ContentResolver res = mContext.getContentResolver();
2904                    boolean shown = Settings.Global.getInt(
2905                            res, Settings.Global.SHOW_PROCESSES, 0) != 0;
2906                    if (!shown) {
2907                        mContext.startService(service);
2908                    } else {
2909                        mContext.stopService(service);
2910                    }
2911                    Settings.Global.putInt(
2912                            res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
2913                    return -1;
2914                }
2915            }
2916        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
2917            if (down) {
2918                if (repeatCount == 0) {
2919                    mSearchKeyShortcutPending = true;
2920                    mConsumeSearchKeyUp = false;
2921                }
2922            } else {
2923                mSearchKeyShortcutPending = false;
2924                if (mConsumeSearchKeyUp) {
2925                    mConsumeSearchKeyUp = false;
2926                    return -1;
2927                }
2928            }
2929            return 0;
2930        } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
2931            if (!keyguardOn) {
2932                if (down && repeatCount == 0) {
2933                    preloadRecentApps();
2934                } else if (!down) {
2935                    toggleRecentApps();
2936                }
2937            }
2938            return -1;
2939        } else if (keyCode == KeyEvent.KEYCODE_N && event.isMetaPressed()) {
2940            if (down) {
2941                IStatusBarService service = getStatusBarService();
2942                if (service != null) {
2943                    try {
2944                        service.expandNotificationsPanel();
2945                    } catch (RemoteException e) {
2946                        // do nothing.
2947                    }
2948                }
2949            }
2950        } else if (keyCode == KeyEvent.KEYCODE_SLASH && event.isMetaPressed()) {
2951            if (down) {
2952                if (repeatCount == 0) {
2953                    toggleKeyboardShortcutsMenu();
2954                }
2955            }
2956        } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
2957            if (down) {
2958                if (repeatCount == 0) {
2959                    mAssistKeyLongPressed = false;
2960                } else if (repeatCount == 1) {
2961                    mAssistKeyLongPressed = true;
2962                    if (!keyguardOn) {
2963                         launchAssistLongPressAction();
2964                    }
2965                }
2966            } else {
2967                if (mAssistKeyLongPressed) {
2968                    mAssistKeyLongPressed = false;
2969                } else {
2970                    if (!keyguardOn) {
2971                        launchAssistAction(null, event.getDeviceId());
2972                    }
2973                }
2974            }
2975            return -1;
2976        } else if (keyCode == KeyEvent.KEYCODE_VOICE_ASSIST) {
2977            if (!down) {
2978                Intent voiceIntent;
2979                if (!keyguardOn) {
2980                    voiceIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2981                } else {
2982                    IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
2983                            ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
2984                    if (dic != null) {
2985                        try {
2986                            dic.exitIdle("voice-search");
2987                        } catch (RemoteException e) {
2988                        }
2989                    }
2990                    voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
2991                    voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, true);
2992                }
2993                startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
2994            }
2995        } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
2996            if (down && repeatCount == 0) {
2997                mHandler.post(mScreenshotRunnable);
2998            }
2999            return -1;
3000        } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
3001                || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
3002            if (down) {
3003                int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
3004
3005                // Disable autobrightness if it's on
3006                int auto = Settings.System.getIntForUser(
3007                        mContext.getContentResolver(),
3008                        Settings.System.SCREEN_BRIGHTNESS_MODE,
3009                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3010                        UserHandle.USER_CURRENT_OR_SELF);
3011                if (auto != 0) {
3012                    Settings.System.putIntForUser(mContext.getContentResolver(),
3013                            Settings.System.SCREEN_BRIGHTNESS_MODE,
3014                            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3015                            UserHandle.USER_CURRENT_OR_SELF);
3016                }
3017
3018                int min = mPowerManager.getMinimumScreenBrightnessSetting();
3019                int max = mPowerManager.getMaximumScreenBrightnessSetting();
3020                int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
3021                int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
3022                        Settings.System.SCREEN_BRIGHTNESS,
3023                        mPowerManager.getDefaultScreenBrightnessSetting(),
3024                        UserHandle.USER_CURRENT_OR_SELF);
3025                brightness += step;
3026                // Make sure we don't go beyond the limits.
3027                brightness = Math.min(max, brightness);
3028                brightness = Math.max(min, brightness);
3029
3030                Settings.System.putIntForUser(mContext.getContentResolver(),
3031                        Settings.System.SCREEN_BRIGHTNESS, brightness,
3032                        UserHandle.USER_CURRENT_OR_SELF);
3033                startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG),
3034                        UserHandle.CURRENT_OR_SELF);
3035            }
3036            return -1;
3037        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP
3038                || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
3039                || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
3040            if (mUseTvRouting) {
3041                // On TVs volume keys never go to the foreground app.
3042                dispatchDirectAudioEvent(event);
3043                return -1;
3044            }
3045        } else if (KeyEvent.isMetaKey(keyCode)) {
3046            if (down) {
3047                mPendingMetaAction = true;
3048            } else if (mPendingMetaAction) {
3049                launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId());
3050            }
3051            return -1;
3052        }
3053
3054        // Shortcuts are invoked through Search+key, so intercept those here
3055        // Any printing key that is chorded with Search should be consumed
3056        // even if no shortcut was invoked.  This prevents text from being
3057        // inadvertently inserted when using a keyboard that has built-in macro
3058        // shortcut keys (that emit Search+x) and some of them are not registered.
3059        if (mSearchKeyShortcutPending) {
3060            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3061            if (kcm.isPrintingKey(keyCode)) {
3062                mConsumeSearchKeyUp = true;
3063                mSearchKeyShortcutPending = false;
3064                if (down && repeatCount == 0 && !keyguardOn) {
3065                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
3066                    if (shortcutIntent != null) {
3067                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3068                        try {
3069                            startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3070                        } catch (ActivityNotFoundException ex) {
3071                            Slog.w(TAG, "Dropping shortcut key combination because "
3072                                    + "the activity to which it is registered was not found: "
3073                                    + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
3074                        }
3075                    } else {
3076                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
3077                                + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
3078                    }
3079                }
3080                return -1;
3081            }
3082        }
3083
3084        // Invoke shortcuts using Meta.
3085        if (down && repeatCount == 0 && !keyguardOn
3086                && (metaState & KeyEvent.META_META_ON) != 0) {
3087            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3088            if (kcm.isPrintingKey(keyCode)) {
3089                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
3090                        metaState & ~(KeyEvent.META_META_ON
3091                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
3092                if (shortcutIntent != null) {
3093                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3094                    try {
3095                        startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3096                    } catch (ActivityNotFoundException ex) {
3097                        Slog.w(TAG, "Dropping shortcut key combination because "
3098                                + "the activity to which it is registered was not found: "
3099                                + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
3100                    }
3101                    return -1;
3102                }
3103            }
3104        }
3105
3106        // Handle application launch keys.
3107        if (down && repeatCount == 0 && !keyguardOn) {
3108            String category = sApplicationLaunchKeyCategories.get(keyCode);
3109            if (category != null) {
3110                Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
3111                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3112                try {
3113                    startActivityAsUser(intent, UserHandle.CURRENT);
3114                } catch (ActivityNotFoundException ex) {
3115                    Slog.w(TAG, "Dropping application launch key because "
3116                            + "the activity to which it is registered was not found: "
3117                            + "keyCode=" + keyCode + ", category=" + category, ex);
3118                }
3119                return -1;
3120            }
3121        }
3122
3123        // Display task switcher for ALT-TAB.
3124        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
3125            if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) {
3126                final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
3127                if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)) {
3128                    mRecentAppsHeldModifiers = shiftlessModifiers;
3129                    showRecentApps(true);
3130                    return -1;
3131                }
3132            }
3133        } else if (!down && mRecentAppsHeldModifiers != 0
3134                && (metaState & mRecentAppsHeldModifiers) == 0) {
3135            mRecentAppsHeldModifiers = 0;
3136            hideRecentApps(true, false);
3137        }
3138
3139        // Handle keyboard layout switching.
3140        // TODO: Deprecate this behavior when we fully migrate to IME subtype-based layout rotation.
3141        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_SPACE
3142                && ((metaState & KeyEvent.META_CTRL_MASK) != 0)) {
3143            int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1;
3144            mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction);
3145            return -1;
3146        }
3147
3148        // Handle input method switching.
3149        if (down && repeatCount == 0
3150                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3151                        || (keyCode == KeyEvent.KEYCODE_SPACE
3152                                && (metaState & KeyEvent.META_META_MASK) != 0))) {
3153            final boolean forwardDirection = (metaState & KeyEvent.META_SHIFT_MASK) == 0;
3154            mWindowManagerFuncs.switchInputMethod(forwardDirection);
3155            return -1;
3156        }
3157        if (mLanguageSwitchKeyPressed && !down
3158                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3159                        || keyCode == KeyEvent.KEYCODE_SPACE)) {
3160            mLanguageSwitchKeyPressed = false;
3161            return -1;
3162        }
3163
3164        if (isValidGlobalKey(keyCode)
3165                && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
3166            return -1;
3167        }
3168
3169        // Reserve all the META modifier combos for system behavior
3170        if ((metaState & KeyEvent.META_META_ON) != 0) {
3171            return -1;
3172        }
3173
3174        // Let the application handle the key.
3175        return 0;
3176    }
3177
3178    /** {@inheritDoc} */
3179    @Override
3180    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
3181        // Note: This method is only called if the initial down was unhandled.
3182        if (DEBUG_INPUT) {
3183            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
3184                    + ", flags=" + event.getFlags()
3185                    + ", keyCode=" + event.getKeyCode()
3186                    + ", scanCode=" + event.getScanCode()
3187                    + ", metaState=" + event.getMetaState()
3188                    + ", repeatCount=" + event.getRepeatCount()
3189                    + ", policyFlags=" + policyFlags);
3190        }
3191
3192        KeyEvent fallbackEvent = null;
3193        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3194            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3195            final int keyCode = event.getKeyCode();
3196            final int metaState = event.getMetaState();
3197            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
3198                    && event.getRepeatCount() == 0;
3199
3200            // Check for fallback actions specified by the key character map.
3201            final FallbackAction fallbackAction;
3202            if (initialDown) {
3203                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
3204            } else {
3205                fallbackAction = mFallbackActions.get(keyCode);
3206            }
3207
3208            if (fallbackAction != null) {
3209                if (DEBUG_INPUT) {
3210                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
3211                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
3212                }
3213
3214                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
3215                fallbackEvent = KeyEvent.obtain(
3216                        event.getDownTime(), event.getEventTime(),
3217                        event.getAction(), fallbackAction.keyCode,
3218                        event.getRepeatCount(), fallbackAction.metaState,
3219                        event.getDeviceId(), event.getScanCode(),
3220                        flags, event.getSource(), null);
3221
3222                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
3223                    fallbackEvent.recycle();
3224                    fallbackEvent = null;
3225                }
3226
3227                if (initialDown) {
3228                    mFallbackActions.put(keyCode, fallbackAction);
3229                } else if (event.getAction() == KeyEvent.ACTION_UP) {
3230                    mFallbackActions.remove(keyCode);
3231                    fallbackAction.recycle();
3232                }
3233            }
3234        }
3235
3236        if (DEBUG_INPUT) {
3237            if (fallbackEvent == null) {
3238                Slog.d(TAG, "No fallback.");
3239            } else {
3240                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
3241            }
3242        }
3243        return fallbackEvent;
3244    }
3245
3246    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
3247        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
3248        if ((actions & ACTION_PASS_TO_USER) != 0) {
3249            long delayMillis = interceptKeyBeforeDispatching(
3250                    win, fallbackEvent, policyFlags);
3251            if (delayMillis == 0) {
3252                return true;
3253            }
3254        }
3255        return false;
3256    }
3257
3258    private void launchAssistLongPressAction() {
3259        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3260        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3261
3262        // launch the search activity
3263        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
3264        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3265        try {
3266            // TODO: This only stops the factory-installed search manager.
3267            // Need to formalize an API to handle others
3268            SearchManager searchManager = getSearchManager();
3269            if (searchManager != null) {
3270                searchManager.stopSearch();
3271            }
3272            startActivityAsUser(intent, UserHandle.CURRENT);
3273        } catch (ActivityNotFoundException e) {
3274            Slog.w(TAG, "No activity to handle assist long press action.", e);
3275        }
3276    }
3277
3278    private void launchAssistAction(String hint, int deviceId) {
3279        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3280        if (!isUserSetupComplete()) {
3281            // Disable opening assist window during setup
3282            return;
3283        }
3284        Bundle args = null;
3285        if (deviceId > Integer.MIN_VALUE) {
3286            args = new Bundle();
3287            args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
3288        }
3289        if ((mContext.getResources().getConfiguration().uiMode
3290                & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
3291            // On TV, use legacy handling until assistants are implemented in the proper way.
3292            ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
3293                    .launchLegacyAssist(hint, UserHandle.myUserId(), args);
3294        } else {
3295            try {
3296                if (hint != null) {
3297                    if (args == null) {
3298                        args = new Bundle();
3299                    }
3300                    args.putBoolean(hint, true);
3301                }
3302                IStatusBarService statusbar = getStatusBarService();
3303                if (statusbar != null) {
3304                    statusbar.startAssist(args);
3305                }
3306            } catch (RemoteException e) {
3307                Slog.e(TAG, "RemoteException when starting assist", e);
3308                // re-acquire status bar service next time it is needed.
3309                mStatusBarService = null;
3310            }
3311        }
3312    }
3313
3314    private void startActivityAsUser(Intent intent, UserHandle handle) {
3315        if (isUserSetupComplete()) {
3316            mContext.startActivityAsUser(intent, handle);
3317        } else {
3318            Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
3319        }
3320    }
3321
3322    private SearchManager getSearchManager() {
3323        if (mSearchManager == null) {
3324            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3325        }
3326        return mSearchManager;
3327    }
3328
3329    private void preloadRecentApps() {
3330        mPreloadedRecentApps = true;
3331        try {
3332            IStatusBarService statusbar = getStatusBarService();
3333            if (statusbar != null) {
3334                statusbar.preloadRecentApps();
3335            }
3336        } catch (RemoteException e) {
3337            Slog.e(TAG, "RemoteException when preloading recent apps", e);
3338            // re-acquire status bar service next time it is needed.
3339            mStatusBarService = null;
3340        }
3341    }
3342
3343    private void cancelPreloadRecentApps() {
3344        if (mPreloadedRecentApps) {
3345            mPreloadedRecentApps = false;
3346            try {
3347                IStatusBarService statusbar = getStatusBarService();
3348                if (statusbar != null) {
3349                    statusbar.cancelPreloadRecentApps();
3350                }
3351            } catch (RemoteException e) {
3352                Slog.e(TAG, "RemoteException when cancelling recent apps preload", e);
3353                // re-acquire status bar service next time it is needed.
3354                mStatusBarService = null;
3355            }
3356        }
3357    }
3358
3359    private void toggleRecentApps() {
3360        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3361        try {
3362            IStatusBarService statusbar = getStatusBarService();
3363            if (statusbar != null) {
3364                statusbar.toggleRecentApps();
3365            }
3366        } catch (RemoteException e) {
3367            Slog.e(TAG, "RemoteException when toggling recent apps", e);
3368            // re-acquire status bar service next time it is needed.
3369            mStatusBarService = null;
3370        }
3371    }
3372
3373    @Override
3374    public void showRecentApps() {
3375        mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3376        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_RECENTS);
3377    }
3378
3379    private void showRecentApps(boolean triggeredFromAltTab) {
3380        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3381        try {
3382            IStatusBarService statusbar = getStatusBarService();
3383            if (statusbar != null) {
3384                statusbar.showRecentApps(triggeredFromAltTab);
3385            }
3386        } catch (RemoteException e) {
3387            Slog.e(TAG, "RemoteException when showing recent apps", e);
3388            // re-acquire status bar service next time it is needed.
3389            mStatusBarService = null;
3390        }
3391    }
3392
3393    private void toggleKeyboardShortcutsMenu() {
3394        try {
3395            IStatusBarService statusbar = getStatusBarService();
3396            if (statusbar != null) {
3397                statusbar.toggleKeyboardShortcutsMenu();
3398            }
3399        } catch (RemoteException e) {
3400            Slog.e(TAG, "RemoteException when showing keyboard shortcuts menu", e);
3401        }
3402    }
3403
3404    private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3405        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3406        try {
3407            IStatusBarService statusbar = getStatusBarService();
3408            if (statusbar != null) {
3409                statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3410            }
3411        } catch (RemoteException e) {
3412            Slog.e(TAG, "RemoteException when closing recent apps", e);
3413            // re-acquire status bar service next time it is needed.
3414            mStatusBarService = null;
3415        }
3416    }
3417
3418    void launchHomeFromHotKey() {
3419        launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3420    }
3421
3422    /**
3423     * A home key -> launch home action was detected.  Take the appropriate action
3424     * given the situation with the keyguard.
3425     */
3426    void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3427        if (respectKeyguard) {
3428            if (isKeyguardShowingAndNotOccluded()) {
3429                // don't launch home if keyguard showing
3430                return;
3431            }
3432
3433            if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3434                // when in keyguard restricted mode, must first verify unlock
3435                // before launching home
3436                mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3437                    @Override
3438                    public void onKeyguardExitResult(boolean success) {
3439                        if (success) {
3440                            try {
3441                                ActivityManagerNative.getDefault().stopAppSwitches();
3442                            } catch (RemoteException e) {
3443                            }
3444                            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3445                            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3446                        }
3447                    }
3448                });
3449                return;
3450            }
3451        }
3452
3453        // no keyguard stuff to worry about, just launch home!
3454        try {
3455            ActivityManagerNative.getDefault().stopAppSwitches();
3456        } catch (RemoteException e) {
3457        }
3458        if (mRecentsVisible) {
3459            // Hide Recents and notify it to launch Home
3460            if (awakenFromDreams) {
3461                awakenDreams();
3462            }
3463            hideRecentApps(false, true);
3464        } else {
3465            // Otherwise, just launch Home
3466            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3467            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3468        }
3469    }
3470
3471    private final Runnable mClearHideNavigationFlag = new Runnable() {
3472        @Override
3473        public void run() {
3474            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3475                // Clear flags.
3476                mForceClearedSystemUiFlags &=
3477                        ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3478            }
3479            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3480        }
3481    };
3482
3483    /**
3484     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3485     * to determine when the nav bar should be shown and prevent applications from
3486     * receiving those touches.
3487     */
3488    final class HideNavInputEventReceiver extends InputEventReceiver {
3489        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3490            super(inputChannel, looper);
3491        }
3492
3493        @Override
3494        public void onInputEvent(InputEvent event) {
3495            boolean handled = false;
3496            try {
3497                if (event instanceof MotionEvent
3498                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3499                    final MotionEvent motionEvent = (MotionEvent)event;
3500                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3501                        // When the user taps down, we re-show the nav bar.
3502                        boolean changed = false;
3503                        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3504                            // Any user activity always causes us to show the
3505                            // navigation controls, if they had been hidden.
3506                            // We also clear the low profile and only content
3507                            // flags so that tapping on the screen will atomically
3508                            // restore all currently hidden screen decorations.
3509                            int newVal = mResettingSystemUiFlags |
3510                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3511                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
3512                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
3513                            if (mResettingSystemUiFlags != newVal) {
3514                                mResettingSystemUiFlags = newVal;
3515                                changed = true;
3516                            }
3517                            // We don't allow the system's nav bar to be hidden
3518                            // again for 1 second, to prevent applications from
3519                            // spamming us and keeping it from being shown.
3520                            newVal = mForceClearedSystemUiFlags |
3521                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3522                            if (mForceClearedSystemUiFlags != newVal) {
3523                                mForceClearedSystemUiFlags = newVal;
3524                                changed = true;
3525                                mHandler.postDelayed(mClearHideNavigationFlag, 1000);
3526                            }
3527                        }
3528                        if (changed) {
3529                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3530                        }
3531                    }
3532                }
3533            } finally {
3534                finishInputEvent(event, handled);
3535            }
3536        }
3537    }
3538    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
3539            new InputEventReceiver.Factory() {
3540        @Override
3541        public InputEventReceiver createInputEventReceiver(
3542                InputChannel inputChannel, Looper looper) {
3543            return new HideNavInputEventReceiver(inputChannel, looper);
3544        }
3545    };
3546
3547    @Override
3548    public int adjustSystemUiVisibilityLw(int visibility) {
3549        mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3550        mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3551        mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
3552
3553        // Reset any bits in mForceClearingStatusBarVisibility that
3554        // are now clear.
3555        mResettingSystemUiFlags &= visibility;
3556        // Clear any bits in the new visibility that are currently being
3557        // force cleared, before reporting it.
3558        return visibility & ~mResettingSystemUiFlags
3559                & ~mForceClearedSystemUiFlags;
3560    }
3561
3562    @Override
3563    public void getInsetHintLw(WindowManager.LayoutParams attrs, int displayRotation,
3564            Rect outContentInsets, Rect outStableInsets, Rect outOutsets) {
3565        final int fl = PolicyControl.getWindowFlags(null, attrs);
3566        final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
3567        final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
3568
3569        final boolean useOutsets = outOutsets != null && shouldUseOutsets(attrs, fl);
3570        if (useOutsets) {
3571            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
3572            if (outset > 0) {
3573                if (displayRotation == Surface.ROTATION_0) {
3574                    outOutsets.bottom += outset;
3575                } else if (displayRotation == Surface.ROTATION_90) {
3576                    outOutsets.right += outset;
3577                } else if (displayRotation == Surface.ROTATION_180) {
3578                    outOutsets.top += outset;
3579                } else if (displayRotation == Surface.ROTATION_270) {
3580                    outOutsets.left += outset;
3581                }
3582            }
3583        }
3584
3585        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3586                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3587            int availRight, availBottom;
3588            if (canHideNavigationBar() &&
3589                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
3590                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3591                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3592            } else {
3593                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
3594                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3595            }
3596            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3597                if ((fl & FLAG_FULLSCREEN) != 0) {
3598                    outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
3599                            availRight - mStableFullscreenRight,
3600                            availBottom - mStableFullscreenBottom);
3601                } else {
3602                    outContentInsets.set(mStableLeft, mStableTop,
3603                            availRight - mStableRight, availBottom - mStableBottom);
3604                }
3605            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
3606                outContentInsets.setEmpty();
3607            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
3608                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
3609                outContentInsets.set(mCurLeft, mCurTop,
3610                        availRight - mCurRight, availBottom - mCurBottom);
3611            } else {
3612                outContentInsets.set(mCurLeft, mCurTop,
3613                        availRight - mCurRight, availBottom - mCurBottom);
3614            }
3615
3616            outStableInsets.set(mStableLeft, mStableTop,
3617                    availRight - mStableRight, availBottom - mStableBottom);
3618            return;
3619        }
3620        outContentInsets.setEmpty();
3621        outStableInsets.setEmpty();
3622    }
3623
3624    private boolean shouldUseOutsets(WindowManager.LayoutParams attrs, int fl) {
3625        return attrs.type == TYPE_WALLPAPER || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
3626                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
3627    }
3628
3629    /** {@inheritDoc} */
3630    @Override
3631    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
3632                              int displayRotation, int uiMode) {
3633        mDisplayRotation = displayRotation;
3634        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
3635        if (isDefaultDisplay) {
3636            switch (displayRotation) {
3637                case Surface.ROTATION_90:
3638                    overscanLeft = mOverscanTop;
3639                    overscanTop = mOverscanRight;
3640                    overscanRight = mOverscanBottom;
3641                    overscanBottom = mOverscanLeft;
3642                    break;
3643                case Surface.ROTATION_180:
3644                    overscanLeft = mOverscanRight;
3645                    overscanTop = mOverscanBottom;
3646                    overscanRight = mOverscanLeft;
3647                    overscanBottom = mOverscanTop;
3648                    break;
3649                case Surface.ROTATION_270:
3650                    overscanLeft = mOverscanBottom;
3651                    overscanTop = mOverscanLeft;
3652                    overscanRight = mOverscanTop;
3653                    overscanBottom = mOverscanRight;
3654                    break;
3655                default:
3656                    overscanLeft = mOverscanLeft;
3657                    overscanTop = mOverscanTop;
3658                    overscanRight = mOverscanRight;
3659                    overscanBottom = mOverscanBottom;
3660                    break;
3661            }
3662        } else {
3663            overscanLeft = 0;
3664            overscanTop = 0;
3665            overscanRight = 0;
3666            overscanBottom = 0;
3667        }
3668        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
3669        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
3670        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
3671        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
3672        mSystemLeft = 0;
3673        mSystemTop = 0;
3674        mSystemRight = displayWidth;
3675        mSystemBottom = displayHeight;
3676        mUnrestrictedScreenLeft = overscanLeft;
3677        mUnrestrictedScreenTop = overscanTop;
3678        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
3679        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
3680        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
3681        mRestrictedScreenTop = mUnrestrictedScreenTop;
3682        mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
3683        mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
3684        mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
3685                = mCurLeft = mUnrestrictedScreenLeft;
3686        mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
3687                = mCurTop = mUnrestrictedScreenTop;
3688        mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
3689                = mCurRight = displayWidth - overscanRight;
3690        mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
3691                = mCurBottom = displayHeight - overscanBottom;
3692        mDockLayer = 0x10000000;
3693        mStatusBarLayer = -1;
3694
3695        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
3696        final Rect pf = mTmpParentFrame;
3697        final Rect df = mTmpDisplayFrame;
3698        final Rect of = mTmpOverscanFrame;
3699        final Rect vf = mTmpVisibleFrame;
3700        final Rect dcf = mTmpDecorFrame;
3701        pf.left = df.left = of.left = vf.left = mDockLeft;
3702        pf.top = df.top = of.top = vf.top = mDockTop;
3703        pf.right = df.right = of.right = vf.right = mDockRight;
3704        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
3705        dcf.setEmpty();  // Decor frame N/A for system bars.
3706
3707        if (isDefaultDisplay) {
3708            // For purposes of putting out fake window up to steal focus, we will
3709            // drive nav being hidden only by whether it is requested.
3710            final int sysui = mLastSystemUiFlags;
3711            boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
3712            boolean navTranslucent = (sysui
3713                    & (View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT)) != 0;
3714            boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
3715            boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
3716            boolean navAllowedHidden = immersive || immersiveSticky;
3717            navTranslucent &= !immersiveSticky;  // transient trumps translucent
3718            boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
3719            if (!isKeyguardShowing) {
3720                navTranslucent &= areTranslucentBarsAllowed();
3721            }
3722
3723            // When the navigation bar isn't visible, we put up a fake
3724            // input window to catch all touch events.  This way we can
3725            // detect when the user presses anywhere to bring back the nav
3726            // bar and ensure the application doesn't see the event.
3727            if (navVisible || navAllowedHidden) {
3728                if (mInputConsumer != null) {
3729                    mInputConsumer.dismiss();
3730                    mInputConsumer = null;
3731                }
3732            } else if (mInputConsumer == null) {
3733                mInputConsumer = mWindowManagerFuncs.addInputConsumer(mHandler.getLooper(),
3734                        mHideNavInputEventReceiverFactory);
3735            }
3736
3737            // For purposes of positioning and showing the nav bar, if we have
3738            // decided that it can't be hidden (because of the screen aspect ratio),
3739            // then take that into account.
3740            navVisible |= !canHideNavigationBar();
3741
3742            boolean updateSysUiVisibility = layoutNavigationBar(displayWidth, displayHeight,
3743                    displayRotation, uiMode, overscanRight, overscanBottom, dcf, navVisible, navTranslucent,
3744                    navAllowedHidden);
3745            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
3746                    mDockLeft, mDockTop, mDockRight, mDockBottom));
3747            updateSysUiVisibility |= layoutStatusBar(pf, df, of, vf, dcf, sysui, isKeyguardShowing);
3748            if (updateSysUiVisibility) {
3749                updateSystemUiVisibilityLw();
3750            }
3751        }
3752    }
3753
3754    private boolean layoutStatusBar(Rect pf, Rect df, Rect of, Rect vf, Rect dcf, int sysui,
3755            boolean isKeyguardShowing) {
3756        // decide where the status bar goes ahead of time
3757        if (mStatusBar != null) {
3758            // apply any navigation bar insets
3759            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3760            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3761            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3762            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
3763                    + mUnrestrictedScreenTop;
3764            vf.left = mStableLeft;
3765            vf.top = mStableTop;
3766            vf.right = mStableRight;
3767            vf.bottom = mStableBottom;
3768
3769            mStatusBarLayer = mStatusBar.getSurfaceLayer();
3770
3771            // Let the status bar determine its size.
3772            mStatusBar.computeFrameLw(pf /* parentFrame */, df /* displayFrame */,
3773                    vf /* overlayFrame */, vf /* contentFrame */, vf /* visibleFrame */,
3774                    dcf /* decorFrame */, vf /* stableFrame */, vf /* outsetFrame */);
3775
3776            // For layout, the status bar is always at the top with our fixed height.
3777            mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
3778
3779            boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
3780            boolean statusBarTranslucent = (sysui
3781                    & (View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT)) != 0;
3782            if (!isKeyguardShowing) {
3783                statusBarTranslucent &= areTranslucentBarsAllowed();
3784            }
3785
3786            // If the status bar is hidden, we don't want to cause
3787            // windows behind it to scroll.
3788            if (mStatusBar.isVisibleLw() && !statusBarTransient) {
3789                // Status bar may go away, so the screen area it occupies
3790                // is available to apps but just covering them when the
3791                // status bar is visible.
3792                mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
3793
3794                mContentTop = mVoiceContentTop = mCurTop = mDockTop;
3795                mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
3796                mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
3797                mContentRight = mVoiceContentRight = mCurRight = mDockRight;
3798
3799                if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
3800                        String.format(
3801                                "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
3802                                mDockLeft, mDockTop, mDockRight, mDockBottom,
3803                                mContentLeft, mContentTop, mContentRight, mContentBottom,
3804                                mCurLeft, mCurTop, mCurRight, mCurBottom));
3805            }
3806            if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
3807                    && !statusBarTransient && !statusBarTranslucent
3808                    && !mStatusBarController.wasRecentlyTranslucent()) {
3809                // If the opaque status bar is currently requested to be visible,
3810                // and not in the process of animating on or off, then
3811                // we can tell the app that it is covered by it.
3812                mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
3813            }
3814            if (mStatusBarController.checkHiddenLw()) {
3815                return true;
3816            }
3817        }
3818        return false;
3819    }
3820
3821    private boolean layoutNavigationBar(int displayWidth, int displayHeight, int displayRotation,
3822            int uiMode, int overscanRight, int overscanBottom, Rect dcf, boolean navVisible,
3823            boolean navTranslucent, boolean navAllowedHidden) {
3824        if (mNavigationBar != null) {
3825            boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
3826            // Force the navigation bar to its appropriate place and
3827            // size.  We need to do this directly, instead of relying on
3828            // it to bubble up from the nav bar, because this needs to
3829            // change atomically with screen rotations.
3830            mNavigationBarOnBottom = isNavigationBarOnBottom(displayWidth, displayHeight);
3831            if (mNavigationBarOnBottom) {
3832                // It's a system nav bar or a portrait screen; nav bar goes on bottom.
3833                int top = displayHeight - overscanBottom
3834                        - getNavigationBarHeight(displayRotation, uiMode);
3835                mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
3836                mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
3837                if (transientNavBarShowing) {
3838                    mNavigationBarController.setBarShowingLw(true);
3839                } else if (navVisible) {
3840                    mNavigationBarController.setBarShowingLw(true);
3841                    mDockBottom = mTmpNavigationFrame.top;
3842                    mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
3843                    mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
3844                } else {
3845                    // We currently want to hide the navigation UI.
3846                    mNavigationBarController.setBarShowingLw(false);
3847                }
3848                if (navVisible && !navTranslucent && !navAllowedHidden
3849                        && !mNavigationBar.isAnimatingLw()
3850                        && !mNavigationBarController.wasRecentlyTranslucent()) {
3851                    // If the opaque nav bar is currently requested to be visible,
3852                    // and not in the process of animating on or off, then
3853                    // we can tell the app that it is covered by it.
3854                    mSystemBottom = mTmpNavigationFrame.top;
3855                }
3856            } else {
3857                // Landscape screen; nav bar goes to the right.
3858                int left = displayWidth - overscanRight
3859                        - getNavigationBarWidth(displayRotation, uiMode);
3860                mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
3861                mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
3862                if (transientNavBarShowing) {
3863                    mNavigationBarController.setBarShowingLw(true);
3864                } else if (navVisible) {
3865                    mNavigationBarController.setBarShowingLw(true);
3866                    mDockRight = mTmpNavigationFrame.left;
3867                    mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
3868                    mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
3869                } else {
3870                    // We currently want to hide the navigation UI.
3871                    mNavigationBarController.setBarShowingLw(false);
3872                }
3873                if (navVisible && !navTranslucent && !navAllowedHidden
3874                        && !mNavigationBar.isAnimatingLw()
3875                        && !mNavigationBarController.wasRecentlyTranslucent()) {
3876                    // If the nav bar is currently requested to be visible,
3877                    // and not in the process of animating on or off, then
3878                    // we can tell the app that it is covered by it.
3879                    mSystemRight = mTmpNavigationFrame.left;
3880                }
3881            }
3882            // Make sure the content and current rectangles are updated to
3883            // account for the restrictions from the navigation bar.
3884            mContentTop = mVoiceContentTop = mCurTop = mDockTop;
3885            mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
3886            mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
3887            mContentRight = mVoiceContentRight = mCurRight = mDockRight;
3888            mStatusBarLayer = mNavigationBar.getSurfaceLayer();
3889            // And compute the final frame.
3890            mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
3891                    mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
3892                    mTmpNavigationFrame, mTmpNavigationFrame);
3893            if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
3894            if (mNavigationBarController.checkHiddenLw()) {
3895                return true;
3896            }
3897        }
3898        return false;
3899    }
3900
3901    private boolean isNavigationBarOnBottom(int displayWidth, int displayHeight) {
3902        return !mNavigationBarCanMove || displayWidth < displayHeight;
3903    }
3904
3905    /** {@inheritDoc} */
3906    @Override
3907    public int getSystemDecorLayerLw() {
3908        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
3909            return mStatusBar.getSurfaceLayer();
3910        }
3911
3912        if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
3913            return mNavigationBar.getSurfaceLayer();
3914        }
3915
3916        return 0;
3917    }
3918
3919    @Override
3920    public void getContentRectLw(Rect r) {
3921        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
3922    }
3923
3924    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
3925            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
3926        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
3927            // Here's a special case: if this attached window is a panel that is
3928            // above the dock window, and the window it is attached to is below
3929            // the dock window, then the frames we computed for the window it is
3930            // attached to can not be used because the dock is effectively part
3931            // of the underlying window and the attached window is floating on top
3932            // of the whole thing.  So, we ignore the attached window and explicitly
3933            // compute the frames that would be appropriate without the dock.
3934            df.left = of.left = cf.left = vf.left = mDockLeft;
3935            df.top = of.top = cf.top = vf.top = mDockTop;
3936            df.right = of.right = cf.right = vf.right = mDockRight;
3937            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
3938        } else {
3939            // The effective display frame of the attached window depends on
3940            // whether it is taking care of insetting its content.  If not,
3941            // we need to use the parent's content frame so that the entire
3942            // window is positioned within that content.  Otherwise we can use
3943            // the overscan frame and let the attached window take care of
3944            // positioning its content appropriately.
3945            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3946                // Set the content frame of the attached window to the parent's decor frame
3947                // (same as content frame when IME isn't present) if specifically requested by
3948                // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
3949                // Otherwise, use the overscan frame.
3950                cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
3951                        ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
3952            } else {
3953                // If the window is resizing, then we want to base the content
3954                // frame on our attached content frame to resize...  however,
3955                // things can be tricky if the attached window is NOT in resize
3956                // mode, in which case its content frame will be larger.
3957                // Ungh.  So to deal with that, make sure the content frame
3958                // we end up using is not covering the IM dock.
3959                cf.set(attached.getContentFrameLw());
3960                if (attached.isVoiceInteraction()) {
3961                    if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
3962                    if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
3963                    if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
3964                    if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
3965                } else if (attached.getSurfaceLayer() < mDockLayer) {
3966                    if (cf.left < mContentLeft) cf.left = mContentLeft;
3967                    if (cf.top < mContentTop) cf.top = mContentTop;
3968                    if (cf.right > mContentRight) cf.right = mContentRight;
3969                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
3970                }
3971            }
3972            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
3973            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
3974            vf.set(attached.getVisibleFrameLw());
3975        }
3976        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
3977        // window should be positioned relative to its parent or the entire
3978        // screen.
3979        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
3980                ? attached.getFrameLw() : df);
3981    }
3982
3983    private void applyStableConstraints(int sysui, int fl, Rect r) {
3984        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3985            // If app is requesting a stable layout, don't let the
3986            // content insets go below the stable values.
3987            if ((fl & FLAG_FULLSCREEN) != 0) {
3988                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
3989                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
3990                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
3991                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
3992            } else {
3993                if (r.left < mStableLeft) r.left = mStableLeft;
3994                if (r.top < mStableTop) r.top = mStableTop;
3995                if (r.right > mStableRight) r.right = mStableRight;
3996                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
3997            }
3998        }
3999    }
4000
4001    private boolean canReceiveInput(WindowState win) {
4002        boolean notFocusable =
4003                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0;
4004        boolean altFocusableIm =
4005                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0;
4006        boolean notFocusableForIm = notFocusable ^ altFocusableIm;
4007        return !notFocusableForIm;
4008    }
4009
4010    /** {@inheritDoc} */
4011    @Override
4012    public void layoutWindowLw(WindowState win, WindowState attached) {
4013        // We've already done the navigation bar and status bar. If the status bar can receive
4014        // input, we need to layout it again to accomodate for the IME window.
4015        if ((win == mStatusBar && !canReceiveInput(win)) || win == mNavigationBar) {
4016            return;
4017        }
4018        final WindowManager.LayoutParams attrs = win.getAttrs();
4019        final boolean isDefaultDisplay = win.isDefaultDisplay();
4020        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
4021                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
4022        if (needsToOffsetInputMethodTarget) {
4023            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
4024            offsetInputMethodWindowLw(mLastInputMethodWindow);
4025        }
4026
4027        final int fl = PolicyControl.getWindowFlags(win, attrs);
4028        final int sim = attrs.softInputMode;
4029        final int sysUiFl = PolicyControl.getSystemUiVisibility(win, null);
4030
4031        final Rect pf = mTmpParentFrame;
4032        final Rect df = mTmpDisplayFrame;
4033        final Rect of = mTmpOverscanFrame;
4034        final Rect cf = mTmpContentFrame;
4035        final Rect vf = mTmpVisibleFrame;
4036        final Rect dcf = mTmpDecorFrame;
4037        final Rect sf = mTmpStableFrame;
4038        Rect osf = null;
4039        dcf.setEmpty();
4040
4041        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
4042                && mNavigationBar != null && mNavigationBar.isVisibleLw());
4043
4044        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
4045
4046        if (isDefaultDisplay) {
4047            sf.set(mStableLeft, mStableTop, mStableRight, mStableBottom);
4048        } else {
4049            sf.set(mOverscanLeft, mOverscanTop, mOverscanRight, mOverscanBottom);
4050        }
4051
4052        if (!isDefaultDisplay) {
4053            if (attached != null) {
4054                // If this window is attached to another, our display
4055                // frame is the same as the one we are attached to.
4056                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4057            } else {
4058                // Give the window full screen.
4059                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4060                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4061                pf.right = df.right = of.right = cf.right
4062                        = mOverscanScreenLeft + mOverscanScreenWidth;
4063                pf.bottom = df.bottom = of.bottom = cf.bottom
4064                        = mOverscanScreenTop + mOverscanScreenHeight;
4065            }
4066        } else if (attrs.type == TYPE_INPUT_METHOD) {
4067            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
4068            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
4069            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
4070            // IM dock windows layout below the nav bar...
4071            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4072            // ...with content insets above the nav bar
4073            cf.bottom = vf.bottom = mStableBottom;
4074            // IM dock windows always go to the bottom of the screen.
4075            attrs.gravity = Gravity.BOTTOM;
4076            mDockLayer = win.getSurfaceLayer();
4077        } else if (attrs.type == TYPE_VOICE_INTERACTION) {
4078            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4079            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4080            pf.right = df.right = of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4081            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4082            cf.bottom = vf.bottom = mStableBottom;
4083            // Note: In Phone landscape mode, the button bar should also be excluded.
4084            cf.right = vf.right = mStableRight;
4085            cf.left = vf.left = mStableLeft;
4086            cf.top = vf.top = mStableTop;
4087        } else if (win == mStatusBar) {
4088            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4089            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4090            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4091            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
4092            cf.left = vf.left = mStableLeft;
4093            cf.top = vf.top = mStableTop;
4094            cf.right = vf.right = mStableRight;
4095            vf.bottom = mStableBottom;
4096
4097            if (adjust == SOFT_INPUT_ADJUST_RESIZE) {
4098                cf.bottom = mContentBottom;
4099            } else {
4100                cf.bottom = mDockBottom;
4101                vf.bottom = mContentBottom;
4102            }
4103        } else {
4104
4105            // Default policy decor for the default display
4106            dcf.left = mSystemLeft;
4107            dcf.top = mSystemTop;
4108            dcf.right = mSystemRight;
4109            dcf.bottom = mSystemBottom;
4110            final boolean inheritTranslucentDecor = (attrs.privateFlags
4111                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
4112            final boolean isAppWindow =
4113                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
4114                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
4115            final boolean topAtRest =
4116                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
4117            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
4118                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
4119                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
4120                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
4121                        && (fl & WindowManager.LayoutParams.
4122                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
4123                        && !mForceWindowDrawsStatusBarBackground) {
4124                    // Ensure policy decor includes status bar
4125                    dcf.top = mStableTop;
4126                }
4127                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
4128                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
4129                        && (fl & WindowManager.LayoutParams.
4130                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
4131                    // Ensure policy decor includes navigation bar
4132                    dcf.bottom = mStableBottom;
4133                    dcf.right = mStableRight;
4134                }
4135            }
4136
4137            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
4138                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
4139                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
4140                            + "): IN_SCREEN, INSET_DECOR");
4141                // This is the case for a normal activity window: we want it
4142                // to cover all of the screen space, and it can take care of
4143                // moving its contents to account for screen decorations that
4144                // intrude into that space.
4145                if (attached != null) {
4146                    // If this window is attached to another, our display
4147                    // frame is the same as the one we are attached to.
4148                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4149                } else {
4150                    if (attrs.type == TYPE_STATUS_BAR_PANEL
4151                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
4152                        // Status bar panels are the only windows who can go on top of
4153                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
4154                        // permission, so they have the same privileges as the status
4155                        // bar itself.
4156                        //
4157                        // However, they should still dodge the navigation bar if it exists.
4158
4159                        pf.left = df.left = of.left = hasNavBar
4160                                ? mDockLeft : mUnrestrictedScreenLeft;
4161                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
4162                        pf.right = df.right = of.right = hasNavBar
4163                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
4164                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4165                        pf.bottom = df.bottom = of.bottom = hasNavBar
4166                                ? mRestrictedScreenTop+mRestrictedScreenHeight
4167                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4168
4169                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4170                                        "Laying out status bar window: (%d,%d - %d,%d)",
4171                                        pf.left, pf.top, pf.right, pf.bottom));
4172                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4173                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4174                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4175                        // Asking to layout into the overscan region, so give it that pure
4176                        // unrestricted area.
4177                        pf.left = df.left = of.left = mOverscanScreenLeft;
4178                        pf.top = df.top = of.top = mOverscanScreenTop;
4179                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
4180                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
4181                                + mOverscanScreenHeight;
4182                    } else if (canHideNavigationBar()
4183                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4184                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4185                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4186                        // Asking for layout as if the nav bar is hidden, lets the
4187                        // application extend into the unrestricted overscan screen area.  We
4188                        // only do this for application windows to ensure no window that
4189                        // can be above the nav bar can do this.
4190                        pf.left = df.left = mOverscanScreenLeft;
4191                        pf.top = df.top = mOverscanScreenTop;
4192                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4193                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4194                        // We need to tell the app about where the frame inside the overscan
4195                        // is, so it can inset its content by that amount -- it didn't ask
4196                        // to actually extend itself into the overscan region.
4197                        of.left = mUnrestrictedScreenLeft;
4198                        of.top = mUnrestrictedScreenTop;
4199                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4200                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4201                    } else {
4202                        pf.left = df.left = mRestrictedOverscanScreenLeft;
4203                        pf.top = df.top = mRestrictedOverscanScreenTop;
4204                        pf.right = df.right = mRestrictedOverscanScreenLeft
4205                                + mRestrictedOverscanScreenWidth;
4206                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
4207                                + mRestrictedOverscanScreenHeight;
4208                        // We need to tell the app about where the frame inside the overscan
4209                        // is, so it can inset its content by that amount -- it didn't ask
4210                        // to actually extend itself into the overscan region.
4211                        of.left = mUnrestrictedScreenLeft;
4212                        of.top = mUnrestrictedScreenTop;
4213                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4214                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4215                    }
4216
4217                    if ((fl & FLAG_FULLSCREEN) == 0) {
4218                        if (win.isVoiceInteraction()) {
4219                            cf.left = mVoiceContentLeft;
4220                            cf.top = mVoiceContentTop;
4221                            cf.right = mVoiceContentRight;
4222                            cf.bottom = mVoiceContentBottom;
4223                        } else {
4224                            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4225                                cf.left = mDockLeft;
4226                                cf.top = mDockTop;
4227                                cf.right = mDockRight;
4228                                cf.bottom = mDockBottom;
4229                            } else {
4230                                cf.left = mContentLeft;
4231                                cf.top = mContentTop;
4232                                cf.right = mContentRight;
4233                                cf.bottom = mContentBottom;
4234                            }
4235                        }
4236                    } else {
4237                        // Full screen windows are always given a layout that is as if the
4238                        // status bar and other transient decors are gone.  This is to avoid
4239                        // bad states when moving from a window that is not hding the
4240                        // status bar to one that is.
4241                        cf.left = mRestrictedScreenLeft;
4242                        cf.top = mRestrictedScreenTop;
4243                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4244                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
4245                    }
4246                    applyStableConstraints(sysUiFl, fl, cf);
4247                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4248                        vf.left = mCurLeft;
4249                        vf.top = mCurTop;
4250                        vf.right = mCurRight;
4251                        vf.bottom = mCurBottom;
4252                    } else {
4253                        vf.set(cf);
4254                    }
4255                }
4256            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
4257                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
4258                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
4259                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4260                        "): IN_SCREEN");
4261                // A window that has requested to fill the entire screen just
4262                // gets everything, period.
4263                if (attrs.type == TYPE_STATUS_BAR_PANEL
4264                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL
4265                        || attrs.type == TYPE_VOLUME_OVERLAY) {
4266                    pf.left = df.left = of.left = cf.left = hasNavBar
4267                            ? mDockLeft : mUnrestrictedScreenLeft;
4268                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4269                    pf.right = df.right = of.right = cf.right = hasNavBar
4270                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
4271                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4272                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
4273                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
4274                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4275                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4276                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
4277                                    pf.left, pf.top, pf.right, pf.bottom));
4278                } else if (attrs.type == TYPE_NAVIGATION_BAR
4279                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
4280                    // The navigation bar has Real Ultimate Power.
4281                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4282                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
4283                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
4284                            + mUnrestrictedScreenWidth;
4285                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
4286                            + mUnrestrictedScreenHeight;
4287                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4288                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
4289                                    pf.left, pf.top, pf.right, pf.bottom));
4290                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
4291                                || attrs.type == TYPE_BOOT_PROGRESS)
4292                        && ((fl & FLAG_FULLSCREEN) != 0)) {
4293                    // Fullscreen secure system overlays get what they ask for.
4294                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4295                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4296                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4297                            + mOverscanScreenWidth;
4298                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4299                            + mOverscanScreenHeight;
4300                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
4301                    // Boot progress screen always covers entire display.
4302                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4303                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4304                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4305                            + mOverscanScreenWidth;
4306                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4307                            + mOverscanScreenHeight;
4308                } else if (attrs.type == TYPE_WALLPAPER) {
4309                    // The wallpaper also has Real Ultimate Power, but we want to tell
4310                    // it about the overscan area.
4311                    pf.left = df.left = mOverscanScreenLeft;
4312                    pf.top = df.top = mOverscanScreenTop;
4313                    pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4314                    pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4315                    of.left = cf.left = mUnrestrictedScreenLeft;
4316                    of.top = cf.top = mUnrestrictedScreenTop;
4317                    of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4318                    of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4319                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4320                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4321                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4322                    // Asking to layout into the overscan region, so give it that pure
4323                    // unrestricted area.
4324                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4325                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4326                    pf.right = df.right = of.right = cf.right
4327                            = mOverscanScreenLeft + mOverscanScreenWidth;
4328                    pf.bottom = df.bottom = of.bottom = cf.bottom
4329                            = mOverscanScreenTop + mOverscanScreenHeight;
4330                } else if (canHideNavigationBar()
4331                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4332                        && (attrs.type == TYPE_STATUS_BAR
4333                            || attrs.type == TYPE_TOAST
4334                            || attrs.type == TYPE_DOCK_DIVIDER
4335                            || attrs.type == TYPE_VOICE_INTERACTION_STARTING
4336                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4337                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
4338                    // Asking for layout as if the nav bar is hidden, lets the
4339                    // application extend into the unrestricted screen area.  We
4340                    // only do this for application windows (or toasts) to ensure no window that
4341                    // can be above the nav bar can do this.
4342                    // XXX This assumes that an app asking for this will also
4343                    // ask for layout in only content.  We can't currently figure out
4344                    // what the screen would be if only laying out to hide the nav bar.
4345                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
4346                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4347                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
4348                            + mUnrestrictedScreenWidth;
4349                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
4350                            + mUnrestrictedScreenHeight;
4351                } else {
4352                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4353                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4354                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4355                            + mRestrictedScreenWidth;
4356                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4357                            + mRestrictedScreenHeight;
4358                }
4359
4360                applyStableConstraints(sysUiFl, fl, cf);
4361
4362                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4363                    vf.left = mCurLeft;
4364                    vf.top = mCurTop;
4365                    vf.right = mCurRight;
4366                    vf.bottom = mCurBottom;
4367                } else {
4368                    vf.set(cf);
4369                }
4370            } else if (attached != null) {
4371                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4372                        "): attached to " + attached);
4373                // A child window should be placed inside of the same visible
4374                // frame that its parent had.
4375                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
4376            } else {
4377                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4378                        "): normal window");
4379                // Otherwise, a normal window must be placed inside the content
4380                // of all screen decorations.
4381                if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_VOLUME_OVERLAY) {
4382                    // Status bar panels and the volume dialog are the only windows who can go on
4383                    // top of the status bar.  They are protected by the STATUS_BAR_SERVICE
4384                    // permission, so they have the same privileges as the status
4385                    // bar itself.
4386                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4387                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4388                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4389                            + mRestrictedScreenWidth;
4390                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4391                            + mRestrictedScreenHeight;
4392                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT) {
4393                    // These dialogs are stable to interim decor changes.
4394                    pf.left = df.left = of.left = cf.left = mStableLeft;
4395                    pf.top = df.top = of.top = cf.top = mStableTop;
4396                    pf.right = df.right = of.right = cf.right = mStableRight;
4397                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4398                } else {
4399                    pf.left = mContentLeft;
4400                    pf.top = mContentTop;
4401                    pf.right = mContentRight;
4402                    pf.bottom = mContentBottom;
4403                    if (win.isVoiceInteraction()) {
4404                        df.left = of.left = cf.left = mVoiceContentLeft;
4405                        df.top = of.top = cf.top = mVoiceContentTop;
4406                        df.right = of.right = cf.right = mVoiceContentRight;
4407                        df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4408                    } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4409                        df.left = of.left = cf.left = mDockLeft;
4410                        df.top = of.top = cf.top = mDockTop;
4411                        df.right = of.right = cf.right = mDockRight;
4412                        df.bottom = of.bottom = cf.bottom = mDockBottom;
4413                    } else {
4414                        df.left = of.left = cf.left = mContentLeft;
4415                        df.top = of.top = cf.top = mContentTop;
4416                        df.right = of.right = cf.right = mContentRight;
4417                        df.bottom = of.bottom = cf.bottom = mContentBottom;
4418                    }
4419                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4420                        vf.left = mCurLeft;
4421                        vf.top = mCurTop;
4422                        vf.right = mCurRight;
4423                        vf.bottom = mCurBottom;
4424                    } else {
4425                        vf.set(cf);
4426                    }
4427                }
4428            }
4429        }
4430
4431        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4432        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR) {
4433            df.left = df.top = -10000;
4434            df.right = df.bottom = 10000;
4435            if (attrs.type != TYPE_WALLPAPER) {
4436                of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
4437                of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
4438            }
4439        }
4440
4441        // If the device has a chin (e.g. some watches), a dead area at the bottom of the screen we
4442        // need to provide information to the clients that want to pretend that you can draw there.
4443        // We only want to apply outsets to certain types of windows. For example, we never want to
4444        // apply the outsets to floating dialogs, because they wouldn't make sense there.
4445        final boolean useOutsets = shouldUseOutsets(attrs, fl);
4446        if (isDefaultDisplay && useOutsets) {
4447            osf = mTmpOutsetFrame;
4448            osf.set(cf.left, cf.top, cf.right, cf.bottom);
4449            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
4450            if (outset > 0) {
4451                int rotation = mDisplayRotation;
4452                if (rotation == Surface.ROTATION_0) {
4453                    osf.bottom += outset;
4454                } else if (rotation == Surface.ROTATION_90) {
4455                    osf.right += outset;
4456                } else if (rotation == Surface.ROTATION_180) {
4457                    osf.top -= outset;
4458                } else if (rotation == Surface.ROTATION_270) {
4459                    osf.left -= outset;
4460                }
4461                if (DEBUG_LAYOUT) Slog.v(TAG, "applying bottom outset of " + outset
4462                        + " with rotation " + rotation + ", result: " + osf);
4463            }
4464        }
4465
4466        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
4467                + ": sim=#" + Integer.toHexString(sim)
4468                + " attach=" + attached + " type=" + attrs.type
4469                + String.format(" flags=0x%08x", fl)
4470                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
4471                + " of=" + of.toShortString()
4472                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
4473                + " dcf=" + dcf.toShortString()
4474                + " sf=" + sf.toShortString()
4475                + " osf=" + (osf == null ? "null" : osf.toShortString()));
4476
4477        win.computeFrameLw(pf, df, of, cf, vf, dcf, sf, osf);
4478
4479        // Dock windows carve out the bottom of the screen, so normal windows
4480        // can't appear underneath them.
4481        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
4482                && !win.getGivenInsetsPendingLw()) {
4483            setLastInputMethodWindowLw(null, null);
4484            offsetInputMethodWindowLw(win);
4485        }
4486        if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
4487                && !win.getGivenInsetsPendingLw()) {
4488            offsetVoiceInputWindowLw(win);
4489        }
4490    }
4491
4492    private void offsetInputMethodWindowLw(WindowState win) {
4493        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4494        top += win.getGivenContentInsetsLw().top;
4495        if (mContentBottom > top) {
4496            mContentBottom = top;
4497        }
4498        if (mVoiceContentBottom > top) {
4499            mVoiceContentBottom = top;
4500        }
4501        top = win.getVisibleFrameLw().top;
4502        top += win.getGivenVisibleInsetsLw().top;
4503        if (mCurBottom > top) {
4504            mCurBottom = top;
4505        }
4506        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
4507                + mDockBottom + " mContentBottom="
4508                + mContentBottom + " mCurBottom=" + mCurBottom);
4509    }
4510
4511    private void offsetVoiceInputWindowLw(WindowState win) {
4512        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4513        top += win.getGivenContentInsetsLw().top;
4514        if (mVoiceContentBottom > top) {
4515            mVoiceContentBottom = top;
4516        }
4517    }
4518
4519    /** {@inheritDoc} */
4520    @Override
4521    public void finishLayoutLw() {
4522        return;
4523    }
4524
4525    /** {@inheritDoc} */
4526    @Override
4527    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
4528        mTopFullscreenOpaqueWindowState = null;
4529        mTopFullscreenOpaqueOrDimmingWindowState = null;
4530        mAppsToBeHidden.clear();
4531        mAppsThatDismissKeyguard.clear();
4532        mForceStatusBar = false;
4533        mForceStatusBarFromKeyguard = false;
4534        mForceStatusBarTransparent = false;
4535        mForcingShowNavBar = false;
4536        mForcingShowNavBarLayer = -1;
4537
4538        mHideLockScreen = false;
4539        mAllowLockscreenWhenOn = false;
4540        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
4541        mShowingLockscreen = false;
4542        mShowingDream = false;
4543        mWinShowWhenLocked = null;
4544        mKeyguardSecure = isKeyguardSecure();
4545        mKeyguardSecureIncludingHidden = mKeyguardSecure
4546                && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
4547    }
4548
4549    /** {@inheritDoc} */
4550    @Override
4551    public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs,
4552            WindowState attached) {
4553        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
4554                + win.isVisibleOrBehindKeyguardLw());
4555        final int fl = PolicyControl.getWindowFlags(win, attrs);
4556        if (mTopFullscreenOpaqueWindowState == null
4557                && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
4558            mForcingShowNavBar = true;
4559            mForcingShowNavBarLayer = win.getSurfaceLayer();
4560        }
4561        if (attrs.type == TYPE_STATUS_BAR) {
4562            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4563                mForceStatusBarFromKeyguard = true;
4564                mShowingLockscreen = true;
4565            }
4566            if ((attrs.privateFlags & PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT) != 0) {
4567                mForceStatusBarTransparent = true;
4568            }
4569        }
4570
4571        boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
4572                && attrs.type < FIRST_SYSTEM_WINDOW;
4573        final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
4574        final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
4575
4576        if (mTopFullscreenOpaqueWindowState == null &&
4577                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
4578            if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
4579                if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4580                    mForceStatusBarFromKeyguard = true;
4581                } else {
4582                    mForceStatusBar = true;
4583                }
4584            }
4585            if (attrs.type == TYPE_DREAM) {
4586                // If the lockscreen was showing when the dream started then wait
4587                // for the dream to draw before hiding the lockscreen.
4588                if (!mDreamingLockscreen
4589                        || (win.isVisibleLw() && win.hasDrawnLw())) {
4590                    mShowingDream = true;
4591                    appWindow = true;
4592                }
4593            }
4594
4595            final IApplicationToken appToken = win.getAppToken();
4596
4597            // For app windows that are not attached, we decide if all windows in the app they
4598            // represent should be hidden or if we should hide the lockscreen. For attached app
4599            // windows we defer the decision to the window it is attached to.
4600            if (appWindow && attached == null) {
4601                if (showWhenLocked) {
4602                    // Remove any previous windows with the same appToken.
4603                    mAppsToBeHidden.remove(appToken);
4604                    mAppsThatDismissKeyguard.remove(appToken);
4605                    if (mAppsToBeHidden.isEmpty()) {
4606                        if (dismissKeyguard && !mKeyguardSecure) {
4607                            mAppsThatDismissKeyguard.add(appToken);
4608                        } else if (win.isDrawnLw() || win.hasAppShownWindows()) {
4609                            mWinShowWhenLocked = win;
4610                            mHideLockScreen = true;
4611                            mForceStatusBarFromKeyguard = false;
4612                        }
4613                    }
4614                } else if (dismissKeyguard) {
4615                    if (mKeyguardSecure) {
4616                        mAppsToBeHidden.add(appToken);
4617                    } else {
4618                        mAppsToBeHidden.remove(appToken);
4619                    }
4620                    mAppsThatDismissKeyguard.add(appToken);
4621                } else {
4622                    mAppsToBeHidden.add(appToken);
4623                }
4624                if (attrs.x == 0 && attrs.y == 0
4625                        && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
4626                        && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
4627                    if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
4628                    mTopFullscreenOpaqueWindowState = win;
4629                    if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
4630                        mTopFullscreenOpaqueOrDimmingWindowState = win;
4631                    }
4632                    if (!mAppsThatDismissKeyguard.isEmpty() &&
4633                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
4634                        if (DEBUG_LAYOUT) Slog.v(TAG,
4635                                "Setting mDismissKeyguard true by win " + win);
4636                        mDismissKeyguard = (mWinDismissingKeyguard == win
4637                                && mSecureDismissingKeyguard == mKeyguardSecure)
4638                                ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
4639                        mWinDismissingKeyguard = win;
4640                        mSecureDismissingKeyguard = mKeyguardSecure;
4641                        mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
4642                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked
4643                            && (win.isDrawnLw() || win.hasAppShownWindows())) {
4644                        if (DEBUG_LAYOUT) Slog.v(TAG,
4645                                "Setting mHideLockScreen to true by win " + win);
4646                        mHideLockScreen = true;
4647                        mForceStatusBarFromKeyguard = false;
4648                    }
4649                    if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
4650                        mAllowLockscreenWhenOn = true;
4651                    }
4652                }
4653
4654                if (mWinShowWhenLocked != null &&
4655                        mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
4656                        (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
4657                    win.hideLw(false);
4658                }
4659            }
4660        } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
4661            // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
4662            // that is being hidden in an animation - keep the
4663            // keyguard hidden until the new window shows up and
4664            // we know whether to show the keyguard or not.
4665            if (win.isAnimatingLw() && appWindow && showWhenLocked && mKeyguardHidden) {
4666                mHideLockScreen = true;
4667                mWinShowWhenLocked = win;
4668            }
4669        }
4670        if (mTopFullscreenOpaqueOrDimmingWindowState == null
4671                && win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()
4672                && win.isDimming()) {
4673            mTopFullscreenOpaqueOrDimmingWindowState = win;
4674        }
4675    }
4676
4677    /** {@inheritDoc} */
4678    @Override
4679    public int finishPostLayoutPolicyLw() {
4680        if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
4681                mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
4682                && isKeyguardLocked()) {
4683            // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
4684            // fullscreen window.
4685            // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
4686            mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4687            mTopFullscreenOpaqueWindowState.hideLw(false);
4688            mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
4689        }
4690
4691        int changes = 0;
4692        boolean topIsFullscreen = false;
4693
4694        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
4695                ? mTopFullscreenOpaqueWindowState.getAttrs()
4696                : null;
4697
4698        // If we are not currently showing a dream then remember the current
4699        // lockscreen state.  We will use this to determine whether the dream
4700        // started while the lockscreen was showing and remember this state
4701        // while the dream is showing.
4702        if (!mShowingDream) {
4703            mDreamingLockscreen = mShowingLockscreen;
4704            if (mDreamingSleepTokenNeeded) {
4705                mDreamingSleepTokenNeeded = false;
4706                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
4707            }
4708        } else {
4709            if (!mDreamingSleepTokenNeeded) {
4710                mDreamingSleepTokenNeeded = true;
4711                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
4712            }
4713        }
4714
4715        if (mStatusBar != null) {
4716            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
4717                    + " forcefkg=" + mForceStatusBarFromKeyguard
4718                    + " top=" + mTopFullscreenOpaqueWindowState);
4719            boolean shouldBeTransparent = mForceStatusBarTransparent
4720                    && !mForceStatusBar
4721                    && !mForceStatusBarFromKeyguard;
4722            if (!shouldBeTransparent) {
4723                mStatusBarController.setShowTransparent(false /* transparent */);
4724            } else if (!mStatusBar.isVisibleLw()) {
4725                mStatusBarController.setShowTransparent(true /* transparent */);
4726            }
4727            if (mForceStatusBar || mForceStatusBarFromKeyguard || mForceStatusBarTransparent) {
4728                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
4729                if (mStatusBarController.setBarShowingLw(true)) {
4730                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
4731                }
4732                // Maintain fullscreen layout until incoming animation is complete.
4733                topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
4734                // Transient status bar on the lockscreen is not allowed
4735                if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
4736                    mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
4737                            mLastSystemUiFlags, mLastSystemUiFlags);
4738                }
4739            } else if (mTopFullscreenOpaqueWindowState != null) {
4740                final int fl = PolicyControl.getWindowFlags(null, lp);
4741                if (localLOGV) {
4742                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
4743                            + " shown position: "
4744                            + mTopFullscreenOpaqueWindowState.getShownPositionLw());
4745                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
4746                            + " lp.flags=0x" + Integer.toHexString(fl));
4747                }
4748                topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
4749                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
4750                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
4751                // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
4752                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
4753                // case though.
4754                if (mStatusBarController.isTransientShowing()) {
4755                    if (mStatusBarController.setBarShowingLw(true)) {
4756                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4757                    }
4758                } else if (topIsFullscreen
4759                        && !mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID)
4760                        && !mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID)) {
4761                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
4762                    if (mStatusBarController.setBarShowingLw(false)) {
4763                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4764                    } else {
4765                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
4766                    }
4767                } else {
4768                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
4769                    if (mStatusBarController.setBarShowingLw(true)) {
4770                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4771                    }
4772                }
4773            }
4774        }
4775
4776        if (mTopIsFullscreen != topIsFullscreen) {
4777            if (!topIsFullscreen) {
4778                // Force another layout when status bar becomes fully shown.
4779                changes |= FINISH_LAYOUT_REDO_LAYOUT;
4780            }
4781            mTopIsFullscreen = topIsFullscreen;
4782        }
4783
4784        // Hide the key guard if a visible window explicitly specifies that it wants to be
4785        // displayed when the screen is locked.
4786        if (mKeyguardDelegate != null && mStatusBar != null) {
4787            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
4788                    + mHideLockScreen);
4789            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
4790                mKeyguardHidden = true;
4791                if (setKeyguardOccludedLw(true)) {
4792                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4793                            | FINISH_LAYOUT_REDO_CONFIG
4794                            | FINISH_LAYOUT_REDO_WALLPAPER;
4795                }
4796                if (mKeyguardDelegate.isShowing()) {
4797                    mHandler.post(new Runnable() {
4798                        @Override
4799                        public void run() {
4800                            mKeyguardDelegate.keyguardDone(false, false);
4801                        }
4802                    });
4803                }
4804            } else if (mHideLockScreen) {
4805                mKeyguardHidden = true;
4806                mWinDismissingKeyguard = null;
4807                if (setKeyguardOccludedLw(true)) {
4808                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4809                            | FINISH_LAYOUT_REDO_CONFIG
4810                            | FINISH_LAYOUT_REDO_WALLPAPER;
4811                }
4812            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
4813                mKeyguardHidden = false;
4814                if (setKeyguardOccludedLw(false)) {
4815                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4816                            | FINISH_LAYOUT_REDO_CONFIG
4817                            | FINISH_LAYOUT_REDO_WALLPAPER;
4818                }
4819                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
4820                    // Only launch the next keyguard unlock window once per window.
4821                    mHandler.post(new Runnable() {
4822                        @Override
4823                        public void run() {
4824                            mKeyguardDelegate.dismiss();
4825                        }
4826                    });
4827                }
4828            } else {
4829                mWinDismissingKeyguard = null;
4830                mSecureDismissingKeyguard = false;
4831                mKeyguardHidden = false;
4832                if (setKeyguardOccludedLw(false)) {
4833                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4834                            | FINISH_LAYOUT_REDO_CONFIG
4835                            | FINISH_LAYOUT_REDO_WALLPAPER;
4836                }
4837            }
4838        }
4839
4840        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4841            // If the navigation bar has been hidden or shown, we need to do another
4842            // layout pass to update that window.
4843            changes |= FINISH_LAYOUT_REDO_LAYOUT;
4844        }
4845
4846        // update since mAllowLockscreenWhenOn might have changed
4847        updateLockScreenTimeout();
4848        return changes;
4849    }
4850
4851    /**
4852     * Updates the occluded state of the Keyguard.
4853     *
4854     * @return Whether the flags have changed and we have to redo the layout.
4855     */
4856    private boolean setKeyguardOccludedLw(boolean isOccluded) {
4857        boolean wasOccluded = mKeyguardOccluded;
4858        boolean showing = mKeyguardDelegate.isShowing();
4859        if (wasOccluded && !isOccluded && showing) {
4860            mKeyguardOccluded = false;
4861            mKeyguardDelegate.setOccluded(false);
4862            mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
4863            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4864            return true;
4865        } else if (!wasOccluded && isOccluded && showing) {
4866            mKeyguardOccluded = true;
4867            mKeyguardDelegate.setOccluded(true);
4868            mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
4869            mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
4870            return true;
4871        } else {
4872            return false;
4873        }
4874    }
4875
4876    private boolean isStatusBarKeyguard() {
4877        return mStatusBar != null
4878                && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
4879    }
4880
4881    @Override
4882    public boolean allowAppAnimationsLw() {
4883        if (isStatusBarKeyguard() || mShowingDream) {
4884            // If keyguard or dreams is currently visible, no reason to animate behind it.
4885            return false;
4886        }
4887        return true;
4888    }
4889
4890    @Override
4891    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
4892        mFocusedWindow = newFocus;
4893        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4894            // If the navigation bar has been hidden or shown, we need to do another
4895            // layout pass to update that window.
4896            return FINISH_LAYOUT_REDO_LAYOUT;
4897        }
4898        return 0;
4899    }
4900
4901    /** {@inheritDoc} */
4902    @Override
4903    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
4904        // lid changed state
4905        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
4906        if (newLidState == mLidState) {
4907            return;
4908        }
4909
4910        mLidState = newLidState;
4911        applyLidSwitchState();
4912        updateRotation(true);
4913
4914        if (lidOpen) {
4915            wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch,
4916                    "android.policy:LID");
4917        } else if (!mLidControlsSleep) {
4918            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4919        }
4920    }
4921
4922    @Override
4923    public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
4924        int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
4925        if (mCameraLensCoverState == lensCoverState) {
4926            return;
4927        }
4928        if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
4929                lensCoverState == CAMERA_LENS_UNCOVERED) {
4930            Intent intent;
4931            final boolean keyguardActive = mKeyguardDelegate == null ? false :
4932                    mKeyguardDelegate.isShowing();
4933            if (keyguardActive) {
4934                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
4935            } else {
4936                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
4937            }
4938            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens,
4939                    "android.policy:CAMERA_COVER");
4940            startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
4941        }
4942        mCameraLensCoverState = lensCoverState;
4943    }
4944
4945    void setHdmiPlugged(boolean plugged) {
4946        if (mHdmiPlugged != plugged) {
4947            mHdmiPlugged = plugged;
4948            updateRotation(true, true);
4949            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
4950            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4951            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
4952            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4953        }
4954    }
4955
4956    void initializeHdmiState() {
4957        boolean plugged = false;
4958        // watch for HDMI plug messages if the hdmi switch exists
4959        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
4960            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
4961
4962            final String filename = "/sys/class/switch/hdmi/state";
4963            FileReader reader = null;
4964            try {
4965                reader = new FileReader(filename);
4966                char[] buf = new char[15];
4967                int n = reader.read(buf);
4968                if (n > 1) {
4969                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
4970                }
4971            } catch (IOException ex) {
4972                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4973            } catch (NumberFormatException ex) {
4974                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4975            } finally {
4976                if (reader != null) {
4977                    try {
4978                        reader.close();
4979                    } catch (IOException ex) {
4980                    }
4981                }
4982            }
4983        }
4984        // This dance forces the code in setHdmiPlugged to run.
4985        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
4986        mHdmiPlugged = !plugged;
4987        setHdmiPlugged(!mHdmiPlugged);
4988    }
4989
4990    final Object mScreenshotLock = new Object();
4991    ServiceConnection mScreenshotConnection = null;
4992
4993    final Runnable mScreenshotTimeout = new Runnable() {
4994        @Override public void run() {
4995            synchronized (mScreenshotLock) {
4996                if (mScreenshotConnection != null) {
4997                    mContext.unbindService(mScreenshotConnection);
4998                    mScreenshotConnection = null;
4999                }
5000            }
5001        }
5002    };
5003
5004    // Assume this is called from the Handler thread.
5005    private void takeScreenshot() {
5006        synchronized (mScreenshotLock) {
5007            if (mScreenshotConnection != null) {
5008                return;
5009            }
5010            ComponentName cn = new ComponentName("com.android.systemui",
5011                    "com.android.systemui.screenshot.TakeScreenshotService");
5012            Intent intent = new Intent();
5013            intent.setComponent(cn);
5014            ServiceConnection conn = new ServiceConnection() {
5015                @Override
5016                public void onServiceConnected(ComponentName name, IBinder service) {
5017                    synchronized (mScreenshotLock) {
5018                        if (mScreenshotConnection != this) {
5019                            return;
5020                        }
5021                        Messenger messenger = new Messenger(service);
5022                        Message msg = Message.obtain(null, 1);
5023                        final ServiceConnection myConn = this;
5024                        Handler h = new Handler(mHandler.getLooper()) {
5025                            @Override
5026                            public void handleMessage(Message msg) {
5027                                synchronized (mScreenshotLock) {
5028                                    if (mScreenshotConnection == myConn) {
5029                                        mContext.unbindService(mScreenshotConnection);
5030                                        mScreenshotConnection = null;
5031                                        mHandler.removeCallbacks(mScreenshotTimeout);
5032                                    }
5033                                }
5034                            }
5035                        };
5036                        msg.replyTo = new Messenger(h);
5037                        msg.arg1 = msg.arg2 = 0;
5038                        if (mStatusBar != null && mStatusBar.isVisibleLw())
5039                            msg.arg1 = 1;
5040                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
5041                            msg.arg2 = 1;
5042                        try {
5043                            messenger.send(msg);
5044                        } catch (RemoteException e) {
5045                        }
5046                    }
5047                }
5048                @Override
5049                public void onServiceDisconnected(ComponentName name) {}
5050            };
5051            if (mContext.bindServiceAsUser(
5052                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
5053                mScreenshotConnection = conn;
5054                mHandler.postDelayed(mScreenshotTimeout, 10000);
5055            }
5056        }
5057    }
5058
5059    /** {@inheritDoc} */
5060    @Override
5061    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
5062        if (!mSystemBooted) {
5063            // If we have not yet booted, don't let key events do anything.
5064            return 0;
5065        }
5066
5067        final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
5068        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
5069        final boolean canceled = event.isCanceled();
5070        final int keyCode = event.getKeyCode();
5071
5072        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
5073
5074        // If screen is off then we treat the case where the keyguard is open but hidden
5075        // the same as if it were open and in front.
5076        // This will prevent any keys other than the power button from waking the screen
5077        // when the keyguard is hidden by another activity.
5078        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
5079                                            (interactive ?
5080                                                isKeyguardShowingAndNotOccluded() :
5081                                                mKeyguardDelegate.isShowing()));
5082
5083        if (DEBUG_INPUT) {
5084            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
5085                    + " interactive=" + interactive + " keyguardActive=" + keyguardActive
5086                    + " policyFlags=" + Integer.toHexString(policyFlags));
5087        }
5088
5089        // Basic policy based on interactive state.
5090        int result;
5091        boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
5092                || event.isWakeKey();
5093        if (interactive || (isInjected && !isWakeKey)) {
5094            // When the device is interactive or the key is injected pass the
5095            // key to the application.
5096            result = ACTION_PASS_TO_USER;
5097            isWakeKey = false;
5098        } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
5099            // If we're currently dozing with the screen on and the keyguard showing, pass the key
5100            // to the application but preserve its wake key status to make sure we still move
5101            // from dozing to fully interactive if we would normally go from off to fully
5102            // interactive.
5103            result = ACTION_PASS_TO_USER;
5104        } else {
5105            // When the screen is off and the key is not injected, determine whether
5106            // to wake the device but don't pass the key to the application.
5107            result = 0;
5108            if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
5109                isWakeKey = false;
5110            }
5111        }
5112
5113        // If the key would be handled globally, just return the result, don't worry about special
5114        // key processing.
5115        if (isValidGlobalKey(keyCode)
5116                && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
5117            if (isWakeKey) {
5118                wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5119            }
5120            return result;
5121        }
5122
5123        boolean useHapticFeedback = down
5124                && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
5125                && event.getRepeatCount() == 0;
5126
5127        // Handle special keys.
5128        switch (keyCode) {
5129            case KeyEvent.KEYCODE_VOLUME_DOWN:
5130            case KeyEvent.KEYCODE_VOLUME_UP:
5131            case KeyEvent.KEYCODE_VOLUME_MUTE: {
5132                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
5133                    if (down) {
5134                        if (interactive && !mScreenshotChordVolumeDownKeyTriggered
5135                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5136                            mScreenshotChordVolumeDownKeyTriggered = true;
5137                            mScreenshotChordVolumeDownKeyTime = event.getDownTime();
5138                            mScreenshotChordVolumeDownKeyConsumed = false;
5139                            cancelPendingPowerKeyAction();
5140                            interceptScreenshotChord();
5141                        }
5142                    } else {
5143                        mScreenshotChordVolumeDownKeyTriggered = false;
5144                        cancelPendingScreenshotChordAction();
5145                    }
5146                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
5147                    if (down) {
5148                        if (interactive && !mScreenshotChordVolumeUpKeyTriggered
5149                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5150                            mScreenshotChordVolumeUpKeyTriggered = true;
5151                            cancelPendingPowerKeyAction();
5152                            cancelPendingScreenshotChordAction();
5153                        }
5154                    } else {
5155                        mScreenshotChordVolumeUpKeyTriggered = false;
5156                        cancelPendingScreenshotChordAction();
5157                    }
5158                }
5159                if (down) {
5160                    TelecomManager telecomManager = getTelecommService();
5161                    if (telecomManager != null) {
5162                        if (telecomManager.isRinging()) {
5163                            // If an incoming call is ringing, either VOLUME key means
5164                            // "silence ringer".  We handle these keys here, rather than
5165                            // in the InCallScreen, to make sure we'll respond to them
5166                            // even if the InCallScreen hasn't come to the foreground yet.
5167                            // Look for the DOWN event here, to agree with the "fallback"
5168                            // behavior in the InCallScreen.
5169                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5170                                  + " VOLUME key-down while ringing: Silence ringer!");
5171
5172                            // Silence the ringer.  (It's safe to call this
5173                            // even if the ringer has already been silenced.)
5174                            telecomManager.silenceRinger();
5175
5176                            // And *don't* pass this key thru to the current activity
5177                            // (which is probably the InCallScreen.)
5178                            result &= ~ACTION_PASS_TO_USER;
5179                            break;
5180                        }
5181                        if (telecomManager.isInCall()
5182                                && (result & ACTION_PASS_TO_USER) == 0) {
5183                            // If we are in call but we decided not to pass the key to
5184                            // the application, just pass it to the session service.
5185
5186                            MediaSessionLegacyHelper.getHelper(mContext)
5187                                    .sendVolumeKeyEvent(event, false);
5188                            break;
5189                        }
5190                    }
5191                }
5192                if (mUseTvRouting) {
5193                    // On TVs, defer special key handlings to
5194                    // {@link interceptKeyBeforeDispatching()}.
5195                    result |= ACTION_PASS_TO_USER;
5196                } else if ((result & ACTION_PASS_TO_USER) == 0) {
5197                    // If we aren't passing to the user and no one else
5198                    // handled it send it to the session manager to
5199                    // figure out.
5200                    MediaSessionLegacyHelper.getHelper(mContext)
5201                            .sendVolumeKeyEvent(event, true);
5202                }
5203                break;
5204            }
5205
5206            case KeyEvent.KEYCODE_ENDCALL: {
5207                result &= ~ACTION_PASS_TO_USER;
5208                if (down) {
5209                    TelecomManager telecomManager = getTelecommService();
5210                    boolean hungUp = false;
5211                    if (telecomManager != null) {
5212                        hungUp = telecomManager.endCall();
5213                    }
5214                    if (interactive && !hungUp) {
5215                        mEndCallKeyHandled = false;
5216                        mHandler.postDelayed(mEndCallLongPress,
5217                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5218                    } else {
5219                        mEndCallKeyHandled = true;
5220                    }
5221                } else {
5222                    if (!mEndCallKeyHandled) {
5223                        mHandler.removeCallbacks(mEndCallLongPress);
5224                        if (!canceled) {
5225                            if ((mEndcallBehavior
5226                                    & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
5227                                if (goHome()) {
5228                                    break;
5229                                }
5230                            }
5231                            if ((mEndcallBehavior
5232                                    & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
5233                                mPowerManager.goToSleep(event.getEventTime(),
5234                                        PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
5235                                isWakeKey = false;
5236                            }
5237                        }
5238                    }
5239                }
5240                break;
5241            }
5242
5243            case KeyEvent.KEYCODE_POWER: {
5244                result &= ~ACTION_PASS_TO_USER;
5245                isWakeKey = false; // wake-up will be handled separately
5246                if (down) {
5247                    interceptPowerKeyDown(event, interactive);
5248                } else {
5249                    interceptPowerKeyUp(event, interactive, canceled);
5250                }
5251                break;
5252            }
5253
5254            case KeyEvent.KEYCODE_SLEEP: {
5255                result &= ~ACTION_PASS_TO_USER;
5256                isWakeKey = false;
5257                if (!mPowerManager.isInteractive()) {
5258                    useHapticFeedback = false; // suppress feedback if already non-interactive
5259                }
5260                if (down) {
5261                    sleepPress(event.getEventTime());
5262                } else {
5263                    sleepRelease(event.getEventTime());
5264                }
5265                break;
5266            }
5267
5268            case KeyEvent.KEYCODE_SOFT_SLEEP: {
5269                result &= ~ACTION_PASS_TO_USER;
5270                isWakeKey = false;
5271                if (!down) {
5272                    mPowerManagerInternal.setUserInactiveOverrideFromWindowManager();
5273                }
5274                break;
5275            }
5276
5277            case KeyEvent.KEYCODE_WAKEUP: {
5278                result &= ~ACTION_PASS_TO_USER;
5279                isWakeKey = true;
5280                break;
5281            }
5282
5283            case KeyEvent.KEYCODE_MEDIA_PLAY:
5284            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5285            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5286            case KeyEvent.KEYCODE_HEADSETHOOK:
5287            case KeyEvent.KEYCODE_MUTE:
5288            case KeyEvent.KEYCODE_MEDIA_STOP:
5289            case KeyEvent.KEYCODE_MEDIA_NEXT:
5290            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5291            case KeyEvent.KEYCODE_MEDIA_REWIND:
5292            case KeyEvent.KEYCODE_MEDIA_RECORD:
5293            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5294            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
5295                if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
5296                    // If the global session is active pass all media keys to it
5297                    // instead of the active window.
5298                    result &= ~ACTION_PASS_TO_USER;
5299                }
5300                if ((result & ACTION_PASS_TO_USER) == 0) {
5301                    // Only do this if we would otherwise not pass it to the user. In that
5302                    // case, the PhoneWindow class will do the same thing, except it will
5303                    // only do it if the showing app doesn't process the key on its own.
5304                    // Note that we need to make a copy of the key event here because the
5305                    // original key event will be recycled when we return.
5306                    mBroadcastWakeLock.acquire();
5307                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
5308                            new KeyEvent(event));
5309                    msg.setAsynchronous(true);
5310                    msg.sendToTarget();
5311                }
5312                break;
5313            }
5314
5315            case KeyEvent.KEYCODE_CALL: {
5316                if (down) {
5317                    TelecomManager telecomManager = getTelecommService();
5318                    if (telecomManager != null) {
5319                        if (telecomManager.isRinging()) {
5320                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5321                                  + " CALL key-down while ringing: Answer the call!");
5322                            telecomManager.acceptRingingCall();
5323
5324                            // And *don't* pass this key thru to the current activity
5325                            // (which is presumably the InCallScreen.)
5326                            result &= ~ACTION_PASS_TO_USER;
5327                        }
5328                    }
5329                }
5330                break;
5331            }
5332            case KeyEvent.KEYCODE_VOICE_ASSIST: {
5333                // Only do this if we would otherwise not pass it to the user. In that case,
5334                // interceptKeyBeforeDispatching would apply a similar but different policy in
5335                // order to invoke voice assist actions. Note that we need to make a copy of the
5336                // key event here because the original key event will be recycled when we return.
5337                if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
5338                    mBroadcastWakeLock.acquire();
5339                    Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
5340                            keyguardActive ? 1 : 0, 0);
5341                    msg.setAsynchronous(true);
5342                    msg.sendToTarget();
5343                }
5344                break;
5345            }
5346            case KeyEvent.KEYCODE_WINDOW: {
5347                if (mShortPressWindowBehavior == SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE) {
5348                    if (!down) {
5349                        handlePipKey(event);
5350                    }
5351                    result &= ~ACTION_PASS_TO_USER;
5352                }
5353                break;
5354            }
5355        }
5356
5357        if (useHapticFeedback) {
5358            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
5359        }
5360
5361        if (isWakeKey) {
5362            wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5363        }
5364
5365        return result;
5366    }
5367
5368    /**
5369     * Returns true if the key can have global actions attached to it.
5370     * We reserve all power management keys for the system since they require
5371     * very careful handling.
5372     */
5373    private static boolean isValidGlobalKey(int keyCode) {
5374        switch (keyCode) {
5375            case KeyEvent.KEYCODE_POWER:
5376            case KeyEvent.KEYCODE_WAKEUP:
5377            case KeyEvent.KEYCODE_SLEEP:
5378                return false;
5379            default:
5380                return true;
5381        }
5382    }
5383
5384    /**
5385     * When the screen is off we ignore some keys that might otherwise typically
5386     * be considered wake keys.  We filter them out here.
5387     *
5388     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
5389     * is always considered a wake key.
5390     */
5391    private boolean isWakeKeyWhenScreenOff(int keyCode) {
5392        switch (keyCode) {
5393            // ignore volume keys unless docked
5394            case KeyEvent.KEYCODE_VOLUME_UP:
5395            case KeyEvent.KEYCODE_VOLUME_DOWN:
5396            case KeyEvent.KEYCODE_VOLUME_MUTE:
5397                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
5398
5399            // ignore media and camera keys
5400            case KeyEvent.KEYCODE_MUTE:
5401            case KeyEvent.KEYCODE_HEADSETHOOK:
5402            case KeyEvent.KEYCODE_MEDIA_PLAY:
5403            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5404            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5405            case KeyEvent.KEYCODE_MEDIA_STOP:
5406            case KeyEvent.KEYCODE_MEDIA_NEXT:
5407            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5408            case KeyEvent.KEYCODE_MEDIA_REWIND:
5409            case KeyEvent.KEYCODE_MEDIA_RECORD:
5410            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5411            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
5412            case KeyEvent.KEYCODE_CAMERA:
5413                return false;
5414        }
5415        return true;
5416    }
5417
5418
5419    /** {@inheritDoc} */
5420    @Override
5421    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
5422        if ((policyFlags & FLAG_WAKE) != 0) {
5423            if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion,
5424                    "android.policy:MOTION")) {
5425                return 0;
5426            }
5427        }
5428
5429        if (shouldDispatchInputWhenNonInteractive()) {
5430            return ACTION_PASS_TO_USER;
5431        }
5432
5433        // If we have not passed the action up and we are in theater mode without dreaming,
5434        // there will be no dream to intercept the touch and wake into ambient.  The device should
5435        // wake up in this case.
5436        if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
5437            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming,
5438                    "android.policy:MOTION");
5439        }
5440
5441        return 0;
5442    }
5443
5444    private boolean shouldDispatchInputWhenNonInteractive() {
5445        // Send events to keyguard while the screen is on.
5446        if (isKeyguardShowingAndNotOccluded() && mDisplay != null
5447                && mDisplay.getState() != Display.STATE_OFF) {
5448            return true;
5449        }
5450
5451        // Send events to a dozing dream even if the screen is off since the dream
5452        // is in control of the state of the screen.
5453        IDreamManager dreamManager = getDreamManager();
5454
5455        try {
5456            if (dreamManager != null && dreamManager.isDreaming()) {
5457                return true;
5458            }
5459        } catch (RemoteException e) {
5460            Slog.e(TAG, "RemoteException when checking if dreaming", e);
5461        }
5462
5463        // Otherwise, consume events since the user can't see what is being
5464        // interacted with.
5465        return false;
5466    }
5467
5468    private void dispatchDirectAudioEvent(KeyEvent event) {
5469        if (event.getAction() != KeyEvent.ACTION_DOWN) {
5470            return;
5471        }
5472        int keyCode = event.getKeyCode();
5473        int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
5474                | AudioManager.FLAG_FROM_KEY;
5475        String pkgName = mContext.getOpPackageName();
5476        switch (keyCode) {
5477            case KeyEvent.KEYCODE_VOLUME_UP:
5478                try {
5479                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
5480                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5481                } catch (RemoteException e) {
5482                    Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
5483                }
5484                break;
5485            case KeyEvent.KEYCODE_VOLUME_DOWN:
5486                try {
5487                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
5488                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5489                } catch (RemoteException e) {
5490                    Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
5491                }
5492                break;
5493            case KeyEvent.KEYCODE_VOLUME_MUTE:
5494                try {
5495                    if (event.getRepeatCount() == 0) {
5496                        getAudioService().adjustSuggestedStreamVolume(
5497                                AudioManager.ADJUST_TOGGLE_MUTE,
5498                                AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5499                    }
5500                } catch (RemoteException e) {
5501                    Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
5502                }
5503                break;
5504        }
5505    }
5506
5507    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
5508        if (DEBUG_INPUT) {
5509            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
5510        }
5511
5512        if (mHavePendingMediaKeyRepeatWithWakeLock) {
5513            if (DEBUG_INPUT) {
5514                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
5515            }
5516
5517            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
5518            mHavePendingMediaKeyRepeatWithWakeLock = false;
5519            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
5520        }
5521
5522        dispatchMediaKeyWithWakeLockToAudioService(event);
5523
5524        if (event.getAction() == KeyEvent.ACTION_DOWN
5525                && event.getRepeatCount() == 0) {
5526            mHavePendingMediaKeyRepeatWithWakeLock = true;
5527
5528            Message msg = mHandler.obtainMessage(
5529                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
5530            msg.setAsynchronous(true);
5531            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
5532        } else {
5533            mBroadcastWakeLock.release();
5534        }
5535    }
5536
5537    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
5538        mHavePendingMediaKeyRepeatWithWakeLock = false;
5539
5540        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
5541                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
5542        if (DEBUG_INPUT) {
5543            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
5544        }
5545
5546        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
5547        mBroadcastWakeLock.release();
5548    }
5549
5550    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
5551        if (ActivityManagerNative.isSystemReady()) {
5552            MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
5553        }
5554    }
5555
5556    void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
5557        IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
5558                ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
5559        if (dic != null) {
5560            try {
5561                dic.exitIdle("voice-search");
5562            } catch (RemoteException e) {
5563            }
5564        }
5565        Intent voiceIntent =
5566            new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
5567        voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
5568        startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
5569        mBroadcastWakeLock.release();
5570    }
5571
5572    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
5573        @Override
5574        public void onReceive(Context context, Intent intent) {
5575            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
5576                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5577                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
5578            } else {
5579                try {
5580                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
5581                            ServiceManager.getService(Context.UI_MODE_SERVICE));
5582                    mUiMode = uiModeService.getCurrentModeType();
5583                } catch (RemoteException e) {
5584                }
5585            }
5586            updateRotation(true);
5587            synchronized (mLock) {
5588                updateOrientationListenerLp();
5589            }
5590        }
5591    };
5592
5593    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
5594        @Override
5595        public void onReceive(Context context, Intent intent) {
5596            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
5597                if (mKeyguardDelegate != null) {
5598                    mKeyguardDelegate.onDreamingStarted();
5599                }
5600            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
5601                if (mKeyguardDelegate != null) {
5602                    mKeyguardDelegate.onDreamingStopped();
5603                }
5604            }
5605        }
5606    };
5607
5608    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
5609        @Override
5610        public void onReceive(Context context, Intent intent) {
5611            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
5612                // tickle the settings observer: this first ensures that we're
5613                // observing the relevant settings for the newly-active user,
5614                // and then updates our own bookkeeping based on the now-
5615                // current user.
5616                mSettingsObserver.onChange(false);
5617
5618                // force a re-application of focused window sysui visibility.
5619                // the window may never have been shown for this user
5620                // e.g. the keyguard when going through the new-user setup flow
5621                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5622                    mLastSystemUiFlags = 0;
5623                    updateSystemUiVisibilityLw();
5624                }
5625            }
5626        }
5627    };
5628
5629    private final Runnable mHiddenNavPanic = new Runnable() {
5630        @Override
5631        public void run() {
5632            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5633                if (!isUserSetupComplete()) {
5634                    // Swipe-up for navigation bar is disabled during setup
5635                    return;
5636                }
5637                mPendingPanicGestureUptime = SystemClock.uptimeMillis();
5638                mNavigationBarController.showTransient();
5639            }
5640        }
5641    };
5642
5643    private void requestTransientBars(WindowState swipeTarget) {
5644        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5645            if (!isUserSetupComplete()) {
5646                // Swipe-up for navigation bar is disabled during setup
5647                return;
5648            }
5649            boolean sb = mStatusBarController.checkShowTransientBarLw();
5650            boolean nb = mNavigationBarController.checkShowTransientBarLw();
5651            if (sb || nb) {
5652                // Don't show status bar when swiping on already visible navigation bar
5653                if (!nb && swipeTarget == mNavigationBar) {
5654                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
5655                    return;
5656                }
5657                if (sb) mStatusBarController.showTransient();
5658                if (nb) mNavigationBarController.showTransient();
5659                mImmersiveModeConfirmation.confirmCurrentPrompt();
5660                updateSystemUiVisibilityLw();
5661            }
5662        }
5663    }
5664
5665    // Called on the PowerManager's Notifier thread.
5666    @Override
5667    public void startedGoingToSleep(int why) {
5668        if (DEBUG_WAKEUP) Slog.i(TAG, "Started going to sleep... (why=" + why + ")");
5669        if (mKeyguardDelegate != null) {
5670            mKeyguardDelegate.onStartedGoingToSleep(why);
5671        }
5672    }
5673
5674    // Called on the PowerManager's Notifier thread.
5675    @Override
5676    public void finishedGoingToSleep(int why) {
5677        EventLog.writeEvent(70000, 0);
5678        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished going to sleep... (why=" + why + ")");
5679        MetricsLogger.histogram(mContext, "screen_timeout", mLockScreenTimeout / 1000);
5680
5681        // We must get this work done here because the power manager will drop
5682        // the wake lock and let the system suspend once this function returns.
5683        synchronized (mLock) {
5684            mAwake = false;
5685            updateWakeGestureListenerLp();
5686            updateOrientationListenerLp();
5687            updateLockScreenTimeout();
5688        }
5689        if (mKeyguardDelegate != null) {
5690            mKeyguardDelegate.onFinishedGoingToSleep(why);
5691        }
5692    }
5693
5694    // Called on the PowerManager's Notifier thread.
5695    @Override
5696    public void startedWakingUp() {
5697        EventLog.writeEvent(70000, 1);
5698        if (DEBUG_WAKEUP) Slog.i(TAG, "Started waking up...");
5699
5700        // Since goToSleep performs these functions synchronously, we must
5701        // do the same here.  We cannot post this work to a handler because
5702        // that might cause it to become reordered with respect to what
5703        // may happen in a future call to goToSleep.
5704        synchronized (mLock) {
5705            mAwake = true;
5706
5707            updateWakeGestureListenerLp();
5708            updateOrientationListenerLp();
5709            updateLockScreenTimeout();
5710        }
5711
5712        if (mKeyguardDelegate != null) {
5713            mKeyguardDelegate.onStartedWakingUp();
5714        }
5715    }
5716
5717    // Called on the PowerManager's Notifier thread.
5718    @Override
5719    public void finishedWakingUp() {
5720        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
5721    }
5722
5723    private void wakeUpFromPowerKey(long eventTime) {
5724        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey, "android.policy:POWER");
5725    }
5726
5727    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, String reason) {
5728        final boolean theaterModeEnabled = isTheaterModeEnabled();
5729        if (!wakeInTheaterMode && theaterModeEnabled) {
5730            return false;
5731        }
5732
5733        if (theaterModeEnabled) {
5734            Settings.Global.putInt(mContext.getContentResolver(),
5735                    Settings.Global.THEATER_MODE_ON, 0);
5736        }
5737
5738        mPowerManager.wakeUp(wakeTime, reason);
5739        return true;
5740    }
5741
5742    private void finishKeyguardDrawn() {
5743        synchronized (mLock) {
5744            if (!mScreenOnEarly || mKeyguardDrawComplete) {
5745                return; // We are not awake yet or we have already informed of this event.
5746            }
5747
5748            mKeyguardDrawComplete = true;
5749            if (mKeyguardDelegate != null) {
5750                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5751            }
5752            mWindowManagerDrawComplete = false;
5753        }
5754
5755        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
5756        // as well as enabling the orientation change logic/sensor.
5757        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
5758                WAITING_FOR_DRAWN_TIMEOUT);
5759    }
5760
5761    // Called on the DisplayManager's DisplayPowerController thread.
5762    @Override
5763    public void screenTurnedOff() {
5764        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
5765
5766        updateScreenOffSleepToken(true);
5767        synchronized (mLock) {
5768            mScreenOnEarly = false;
5769            mScreenOnFully = false;
5770            mKeyguardDrawComplete = false;
5771            mWindowManagerDrawComplete = false;
5772            mScreenOnListener = null;
5773            updateOrientationListenerLp();
5774
5775            if (mKeyguardDelegate != null) {
5776                mKeyguardDelegate.onScreenTurnedOff();
5777            }
5778        }
5779    }
5780
5781    // Called on the DisplayManager's DisplayPowerController thread.
5782    @Override
5783    public void screenTurningOn(final ScreenOnListener screenOnListener) {
5784        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
5785
5786        updateScreenOffSleepToken(false);
5787        synchronized (mLock) {
5788            mScreenOnEarly = true;
5789            mScreenOnFully = false;
5790            mKeyguardDrawComplete = false;
5791            mWindowManagerDrawComplete = false;
5792            mScreenOnListener = screenOnListener;
5793
5794            if (mKeyguardDelegate != null) {
5795                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5796                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
5797                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
5798            } else {
5799                if (DEBUG_WAKEUP) Slog.d(TAG,
5800                        "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
5801                finishKeyguardDrawn();
5802            }
5803        }
5804    }
5805
5806    // Called on the DisplayManager's DisplayPowerController thread.
5807    @Override
5808    public void screenTurnedOn() {
5809        synchronized (mLock) {
5810            if (mKeyguardDelegate != null) {
5811                mKeyguardDelegate.onScreenTurnedOn();
5812            }
5813        }
5814    }
5815
5816    private void finishWindowsDrawn() {
5817        synchronized (mLock) {
5818            if (!mScreenOnEarly || mWindowManagerDrawComplete) {
5819                return; // Screen is not turned on or we did already handle this case earlier.
5820            }
5821
5822            mWindowManagerDrawComplete = true;
5823        }
5824
5825        finishScreenTurningOn();
5826    }
5827
5828    private void finishScreenTurningOn() {
5829        synchronized (mLock) {
5830            // We have just finished drawing screen content. Since the orientation listener
5831            // gets only installed when all windows are drawn, we try to install it again.
5832            updateOrientationListenerLp();
5833        }
5834        final ScreenOnListener listener;
5835        final boolean enableScreen;
5836        synchronized (mLock) {
5837            if (DEBUG_WAKEUP) Slog.d(TAG,
5838                    "finishScreenTurningOn: mAwake=" + mAwake
5839                            + ", mScreenOnEarly=" + mScreenOnEarly
5840                            + ", mScreenOnFully=" + mScreenOnFully
5841                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
5842                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
5843
5844            if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
5845                    || (mAwake && !mKeyguardDrawComplete)) {
5846                return; // spurious or not ready yet
5847            }
5848
5849            if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
5850            listener = mScreenOnListener;
5851            mScreenOnListener = null;
5852            mScreenOnFully = true;
5853
5854            // Remember the first time we draw the keyguard so we know when we're done with
5855            // the main part of booting and can enable the screen and hide boot messages.
5856            if (!mKeyguardDrawnOnce && mAwake) {
5857                mKeyguardDrawnOnce = true;
5858                enableScreen = true;
5859                if (mBootMessageNeedsHiding) {
5860                    mBootMessageNeedsHiding = false;
5861                    hideBootMessages();
5862                }
5863            } else {
5864                enableScreen = false;
5865            }
5866        }
5867
5868        if (listener != null) {
5869            listener.onScreenOn();
5870        }
5871
5872        if (enableScreen) {
5873            try {
5874                mWindowManager.enableScreenIfNeeded();
5875            } catch (RemoteException unhandled) {
5876            }
5877        }
5878    }
5879
5880    private void handleHideBootMessage() {
5881        synchronized (mLock) {
5882            if (!mKeyguardDrawnOnce) {
5883                mBootMessageNeedsHiding = true;
5884                return; // keyguard hasn't drawn the first time yet, not done booting
5885            }
5886        }
5887
5888        if (mBootMsgDialog != null) {
5889            if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
5890            mBootMsgDialog.dismiss();
5891            mBootMsgDialog = null;
5892        }
5893    }
5894
5895    @Override
5896    public boolean isScreenOn() {
5897        return mScreenOnFully;
5898    }
5899
5900    /** {@inheritDoc} */
5901    @Override
5902    public void enableKeyguard(boolean enabled) {
5903        if (mKeyguardDelegate != null) {
5904            mKeyguardDelegate.setKeyguardEnabled(enabled);
5905        }
5906    }
5907
5908    /** {@inheritDoc} */
5909    @Override
5910    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
5911        if (mKeyguardDelegate != null) {
5912            mKeyguardDelegate.verifyUnlock(callback);
5913        }
5914    }
5915
5916    private boolean isKeyguardShowingAndNotOccluded() {
5917        if (mKeyguardDelegate == null) return false;
5918        return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
5919    }
5920
5921    /** {@inheritDoc} */
5922    @Override
5923    public boolean isKeyguardLocked() {
5924        return keyguardOn();
5925    }
5926
5927    /** {@inheritDoc} */
5928    @Override
5929    public boolean isKeyguardSecure() {
5930        if (mKeyguardDelegate == null) return false;
5931        return mKeyguardDelegate.isSecure();
5932    }
5933
5934    /** {@inheritDoc} */
5935    @Override
5936    public boolean isKeyguardShowingOrOccluded() {
5937        return mKeyguardDelegate == null ? false : mKeyguardDelegate.isShowing();
5938    }
5939
5940    /** {@inheritDoc} */
5941    @Override
5942    public boolean inKeyguardRestrictedKeyInputMode() {
5943        if (mKeyguardDelegate == null) return false;
5944        return mKeyguardDelegate.isInputRestricted();
5945    }
5946
5947    @Override
5948    public void dismissKeyguardLw() {
5949        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
5950            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
5951            mHandler.post(new Runnable() {
5952                @Override
5953                public void run() {
5954                    // ask the keyguard to prompt the user to authenticate if necessary
5955                    mKeyguardDelegate.dismiss();
5956                }
5957            });
5958        }
5959    }
5960
5961    public void notifyActivityDrawnForKeyguardLw() {
5962        if (mKeyguardDelegate != null) {
5963            mHandler.post(new Runnable() {
5964                @Override
5965                public void run() {
5966                    mKeyguardDelegate.onActivityDrawn();
5967                }
5968            });
5969        }
5970    }
5971
5972    @Override
5973    public boolean isKeyguardDrawnLw() {
5974        synchronized (mLock) {
5975            return mKeyguardDrawnOnce;
5976        }
5977    }
5978
5979    @Override
5980    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
5981        if (mKeyguardDelegate != null) {
5982            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
5983            mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
5984        }
5985    }
5986
5987    @Override
5988    public void getStableInsetsLw(int displayRotation, int displayWidth, int displayHeight,
5989            Rect outInsets) {
5990        outInsets.setEmpty();
5991        if (mStatusBar != null) {
5992            outInsets.top = mStatusBarHeight;
5993        }
5994        if (mNavigationBar != null) {
5995            if (isNavigationBarOnBottom(displayWidth, displayHeight)) {
5996                outInsets.bottom = getNavigationBarHeight(displayRotation, mUiMode);
5997            } else {
5998                outInsets.right = getNavigationBarWidth(displayRotation, mUiMode);
5999            }
6000        }
6001    }
6002
6003    void sendCloseSystemWindows() {
6004        PhoneWindow.sendCloseSystemWindows(mContext, null);
6005    }
6006
6007    void sendCloseSystemWindows(String reason) {
6008        PhoneWindow.sendCloseSystemWindows(mContext, reason);
6009    }
6010
6011    @Override
6012    public int rotationForOrientationLw(int orientation, int lastRotation) {
6013        if (false) {
6014            Slog.v(TAG, "rotationForOrientationLw(orient="
6015                        + orientation + ", last=" + lastRotation
6016                        + "); user=" + mUserRotation + " "
6017                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
6018                            ? "USER_ROTATION_LOCKED" : "")
6019                        );
6020        }
6021
6022        if (mForceDefaultOrientation) {
6023            return Surface.ROTATION_0;
6024        }
6025
6026        synchronized (mLock) {
6027            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
6028            if (sensorRotation < 0) {
6029                sensorRotation = lastRotation;
6030            }
6031
6032            final int preferredRotation;
6033            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
6034                // Ignore sensor when lid switch is open and rotation is forced.
6035                preferredRotation = mLidOpenRotation;
6036            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
6037                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
6038                // Ignore sensor when in car dock unless explicitly enabled.
6039                // This case can override the behavior of NOSENSOR, and can also
6040                // enable 180 degree rotation while docked.
6041                preferredRotation = mCarDockEnablesAccelerometer
6042                        ? sensorRotation : mCarDockRotation;
6043            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6044                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
6045                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
6046                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
6047                // Ignore sensor when in desk dock unless explicitly enabled.
6048                // This case can override the behavior of NOSENSOR, and can also
6049                // enable 180 degree rotation while docked.
6050                preferredRotation = mDeskDockEnablesAccelerometer
6051                        ? sensorRotation : mDeskDockRotation;
6052            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
6053                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
6054                // Note that the dock orientation overrides the HDMI orientation.
6055                preferredRotation = mDemoHdmiRotation;
6056            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
6057                    && mUndockedHdmiRotation >= 0) {
6058                // Ignore sensor when plugged into HDMI and an undocked orientation has
6059                // been specified in the configuration (only for legacy devices without
6060                // full multi-display support).
6061                // Note that the dock orientation overrides the HDMI orientation.
6062                preferredRotation = mUndockedHdmiRotation;
6063            } else if (mDemoRotationLock) {
6064                // Ignore sensor when demo rotation lock is enabled.
6065                // Note that the dock orientation and HDMI rotation lock override this.
6066                preferredRotation = mDemoRotation;
6067            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
6068                // Application just wants to remain locked in the last rotation.
6069                preferredRotation = lastRotation;
6070            } else if (!mSupportAutoRotation) {
6071                // If we don't support auto-rotation then bail out here and ignore
6072                // the sensor and any rotation lock settings.
6073                preferredRotation = -1;
6074            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
6075                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
6076                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
6077                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
6078                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
6079                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
6080                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
6081                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6082                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
6083                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
6084                // Otherwise, use sensor only if requested by the application or enabled
6085                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
6086                if (mAllowAllRotations < 0) {
6087                    // Can't read this during init() because the context doesn't
6088                    // have display metrics at that time so we cannot determine
6089                    // tablet vs. phone then.
6090                    mAllowAllRotations = mContext.getResources().getBoolean(
6091                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
6092                }
6093                if (sensorRotation != Surface.ROTATION_180
6094                        || mAllowAllRotations == 1
6095                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6096                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
6097                    preferredRotation = sensorRotation;
6098                } else {
6099                    preferredRotation = lastRotation;
6100                }
6101            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
6102                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
6103                // Apply rotation lock.  Does not apply to NOSENSOR.
6104                // The idea is that the user rotation expresses a weak preference for the direction
6105                // of gravity and as NOSENSOR is never affected by gravity, then neither should
6106                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
6107                preferredRotation = mUserRotation;
6108            } else {
6109                // No overriding preference.
6110                // We will do exactly what the application asked us to do.
6111                preferredRotation = -1;
6112            }
6113
6114            switch (orientation) {
6115                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6116                    // Return portrait unless overridden.
6117                    if (isAnyPortrait(preferredRotation)) {
6118                        return preferredRotation;
6119                    }
6120                    return mPortraitRotation;
6121
6122                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6123                    // Return landscape unless overridden.
6124                    if (isLandscapeOrSeascape(preferredRotation)) {
6125                        return preferredRotation;
6126                    }
6127                    return mLandscapeRotation;
6128
6129                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6130                    // Return reverse portrait unless overridden.
6131                    if (isAnyPortrait(preferredRotation)) {
6132                        return preferredRotation;
6133                    }
6134                    return mUpsideDownRotation;
6135
6136                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6137                    // Return seascape unless overridden.
6138                    if (isLandscapeOrSeascape(preferredRotation)) {
6139                        return preferredRotation;
6140                    }
6141                    return mSeascapeRotation;
6142
6143                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6144                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
6145                    // Return either landscape rotation.
6146                    if (isLandscapeOrSeascape(preferredRotation)) {
6147                        return preferredRotation;
6148                    }
6149                    if (isLandscapeOrSeascape(lastRotation)) {
6150                        return lastRotation;
6151                    }
6152                    return mLandscapeRotation;
6153
6154                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6155                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
6156                    // Return either portrait rotation.
6157                    if (isAnyPortrait(preferredRotation)) {
6158                        return preferredRotation;
6159                    }
6160                    if (isAnyPortrait(lastRotation)) {
6161                        return lastRotation;
6162                    }
6163                    return mPortraitRotation;
6164
6165                default:
6166                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
6167                    // just return the preferred orientation we already calculated.
6168                    if (preferredRotation >= 0) {
6169                        return preferredRotation;
6170                    }
6171                    return Surface.ROTATION_0;
6172            }
6173        }
6174    }
6175
6176    @Override
6177    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
6178        switch (orientation) {
6179            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6180            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6181            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6182                return isAnyPortrait(rotation);
6183
6184            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6185            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6186            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6187                return isLandscapeOrSeascape(rotation);
6188
6189            default:
6190                return true;
6191        }
6192    }
6193
6194    @Override
6195    public void setRotationLw(int rotation) {
6196        mOrientationListener.setCurrentRotation(rotation);
6197    }
6198
6199    private boolean isLandscapeOrSeascape(int rotation) {
6200        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
6201    }
6202
6203    private boolean isAnyPortrait(int rotation) {
6204        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
6205    }
6206
6207    @Override
6208    public int getUserRotationMode() {
6209        return Settings.System.getIntForUser(mContext.getContentResolver(),
6210                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
6211                        WindowManagerPolicy.USER_ROTATION_FREE :
6212                                WindowManagerPolicy.USER_ROTATION_LOCKED;
6213    }
6214
6215    // User rotation: to be used when all else fails in assigning an orientation to the device
6216    @Override
6217    public void setUserRotationMode(int mode, int rot) {
6218        ContentResolver res = mContext.getContentResolver();
6219
6220        // mUserRotationMode and mUserRotation will be assigned by the content observer
6221        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
6222            Settings.System.putIntForUser(res,
6223                    Settings.System.USER_ROTATION,
6224                    rot,
6225                    UserHandle.USER_CURRENT);
6226            Settings.System.putIntForUser(res,
6227                    Settings.System.ACCELEROMETER_ROTATION,
6228                    0,
6229                    UserHandle.USER_CURRENT);
6230        } else {
6231            Settings.System.putIntForUser(res,
6232                    Settings.System.ACCELEROMETER_ROTATION,
6233                    1,
6234                    UserHandle.USER_CURRENT);
6235        }
6236    }
6237
6238    @Override
6239    public void setSafeMode(boolean safeMode) {
6240        mSafeMode = safeMode;
6241        performHapticFeedbackLw(null, safeMode
6242                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
6243                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
6244    }
6245
6246    static long[] getLongIntArray(Resources r, int resid) {
6247        int[] ar = r.getIntArray(resid);
6248        if (ar == null) {
6249            return null;
6250        }
6251        long[] out = new long[ar.length];
6252        for (int i=0; i<ar.length; i++) {
6253            out[i] = ar[i];
6254        }
6255        return out;
6256    }
6257
6258    /** {@inheritDoc} */
6259    @Override
6260    public void systemReady() {
6261        mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
6262        mKeyguardDelegate.onSystemReady();
6263
6264        readCameraLensCoverState();
6265        updateUiMode();
6266        boolean bindKeyguardNow;
6267        synchronized (mLock) {
6268            updateOrientationListenerLp();
6269            mSystemReady = true;
6270            mHandler.post(new Runnable() {
6271                @Override
6272                public void run() {
6273                    updateSettings();
6274                }
6275            });
6276
6277            bindKeyguardNow = mDeferBindKeyguard;
6278            if (bindKeyguardNow) {
6279                // systemBooted ran but wasn't able to bind to the Keyguard, we'll do it now.
6280                mDeferBindKeyguard = false;
6281            }
6282        }
6283
6284        if (bindKeyguardNow) {
6285            mKeyguardDelegate.bindService(mContext);
6286            mKeyguardDelegate.onBootCompleted();
6287        }
6288        mSystemGestures.systemReady();
6289    }
6290
6291    /** {@inheritDoc} */
6292    @Override
6293    public void systemBooted() {
6294        boolean bindKeyguardNow = false;
6295        synchronized (mLock) {
6296            // Time to bind Keyguard; take care to only bind it once, either here if ready or
6297            // in systemReady if not.
6298            if (mKeyguardDelegate != null) {
6299                bindKeyguardNow = true;
6300            } else {
6301                // Because mKeyguardDelegate is null, we know that the synchronized block in
6302                // systemReady didn't run yet and setting this will actually have an effect.
6303                mDeferBindKeyguard = true;
6304            }
6305        }
6306        if (bindKeyguardNow) {
6307            mKeyguardDelegate.bindService(mContext);
6308            mKeyguardDelegate.onBootCompleted();
6309        }
6310        synchronized (mLock) {
6311            mSystemBooted = true;
6312        }
6313        startedWakingUp();
6314        screenTurningOn(null);
6315        screenTurnedOn();
6316    }
6317
6318    ProgressDialog mBootMsgDialog = null;
6319
6320    /** {@inheritDoc} */
6321    @Override
6322    public void showBootMessage(final CharSequence msg, final boolean always) {
6323        mHandler.post(new Runnable() {
6324            @Override public void run() {
6325                if (mBootMsgDialog == null) {
6326                    int theme;
6327                    if (mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
6328                        theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
6329                    } else if (mContext.getPackageManager().hasSystemFeature(FEATURE_TELEVISION)) {
6330                        theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
6331                    } else {
6332                        theme = 0;
6333                    }
6334
6335                    mBootMsgDialog = new ProgressDialog(mContext, theme) {
6336                        // This dialog will consume all events coming in to
6337                        // it, to avoid it trying to do things too early in boot.
6338                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
6339                            return true;
6340                        }
6341                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6342                            return true;
6343                        }
6344                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
6345                            return true;
6346                        }
6347                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
6348                            return true;
6349                        }
6350                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
6351                            return true;
6352                        }
6353                        @Override public boolean dispatchPopulateAccessibilityEvent(
6354                                AccessibilityEvent event) {
6355                            return true;
6356                        }
6357                    };
6358                    if (mContext.getPackageManager().isUpgrade()) {
6359                        mBootMsgDialog.setTitle(R.string.android_upgrading_title);
6360                    } else {
6361                        mBootMsgDialog.setTitle(R.string.android_start_title);
6362                    }
6363                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
6364                    mBootMsgDialog.setIndeterminate(true);
6365                    mBootMsgDialog.getWindow().setType(
6366                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
6367                    mBootMsgDialog.getWindow().addFlags(
6368                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
6369                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
6370                    mBootMsgDialog.getWindow().setDimAmount(1);
6371                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
6372                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
6373                    mBootMsgDialog.getWindow().setAttributes(lp);
6374                    mBootMsgDialog.setCancelable(false);
6375                    mBootMsgDialog.show();
6376                }
6377                mBootMsgDialog.setMessage(msg);
6378            }
6379        });
6380    }
6381
6382    /** {@inheritDoc} */
6383    @Override
6384    public void hideBootMessages() {
6385        mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
6386    }
6387
6388    /** {@inheritDoc} */
6389    @Override
6390    public void userActivity() {
6391        // ***************************************
6392        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
6393        // ***************************************
6394        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
6395        // WITH ITS LOCKS HELD.
6396        //
6397        // This code must be VERY careful about the locks
6398        // it acquires.
6399        // In fact, the current code acquires way too many,
6400        // and probably has lurking deadlocks.
6401
6402        synchronized (mScreenLockTimeout) {
6403            if (mLockScreenTimerActive) {
6404                // reset the timer
6405                mHandler.removeCallbacks(mScreenLockTimeout);
6406                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6407            }
6408        }
6409    }
6410
6411    class ScreenLockTimeout implements Runnable {
6412        Bundle options;
6413
6414        @Override
6415        public void run() {
6416            synchronized (this) {
6417                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
6418                if (mKeyguardDelegate != null) {
6419                    mKeyguardDelegate.doKeyguardTimeout(options);
6420                }
6421                mLockScreenTimerActive = false;
6422                options = null;
6423            }
6424        }
6425
6426        public void setLockOptions(Bundle options) {
6427            this.options = options;
6428        }
6429    }
6430
6431    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
6432
6433    @Override
6434    public void lockNow(Bundle options) {
6435        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
6436        mHandler.removeCallbacks(mScreenLockTimeout);
6437        if (options != null) {
6438            // In case multiple calls are made to lockNow, we don't wipe out the options
6439            // until the runnable actually executes.
6440            mScreenLockTimeout.setLockOptions(options);
6441        }
6442        mHandler.post(mScreenLockTimeout);
6443    }
6444
6445    private void updateLockScreenTimeout() {
6446        synchronized (mScreenLockTimeout) {
6447            boolean enable = (mAllowLockscreenWhenOn && mAwake &&
6448                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
6449            if (mLockScreenTimerActive != enable) {
6450                if (enable) {
6451                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
6452                    mHandler.removeCallbacks(mScreenLockTimeout); // remove any pending requests
6453                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6454                } else {
6455                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
6456                    mHandler.removeCallbacks(mScreenLockTimeout);
6457                }
6458                mLockScreenTimerActive = enable;
6459            }
6460        }
6461    }
6462
6463    private void updateDreamingSleepToken(boolean acquire) {
6464        if (acquire) {
6465            if (mDreamingSleepToken == null) {
6466                mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
6467            }
6468        } else {
6469            if (mDreamingSleepToken != null) {
6470                mDreamingSleepToken.release();
6471                mDreamingSleepToken = null;
6472            }
6473        }
6474    }
6475
6476    private void updateScreenOffSleepToken(boolean acquire) {
6477        if (acquire) {
6478            if (mScreenOffSleepToken == null) {
6479                mScreenOffSleepToken = mActivityManagerInternal.acquireSleepToken("ScreenOff");
6480            }
6481        } else {
6482            if (mScreenOffSleepToken != null) {
6483                mScreenOffSleepToken.release();
6484                mScreenOffSleepToken = null;
6485            }
6486        }
6487    }
6488
6489    /** {@inheritDoc} */
6490    @Override
6491    public void enableScreenAfterBoot() {
6492        readLidState();
6493        applyLidSwitchState();
6494        updateRotation(true);
6495    }
6496
6497    private void applyLidSwitchState() {
6498        if (mLidState == LID_CLOSED && mLidControlsSleep) {
6499            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
6500                    PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
6501                    PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
6502        } else if (mLidState == LID_CLOSED && mLidControlsScreenLock) {
6503            mWindowManagerFuncs.lockDeviceNow();
6504        }
6505
6506        synchronized (mLock) {
6507            updateWakeGestureListenerLp();
6508        }
6509    }
6510
6511    void updateUiMode() {
6512        if (mUiModeManager == null) {
6513            mUiModeManager = IUiModeManager.Stub.asInterface(
6514                    ServiceManager.getService(Context.UI_MODE_SERVICE));
6515        }
6516        try {
6517            mUiMode = mUiModeManager.getCurrentModeType();
6518        } catch (RemoteException e) {
6519        }
6520    }
6521
6522    void updateRotation(boolean alwaysSendConfiguration) {
6523        try {
6524            //set orientation on WindowManager
6525            mWindowManager.updateRotation(alwaysSendConfiguration, false);
6526        } catch (RemoteException e) {
6527            // Ignore
6528        }
6529    }
6530
6531    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
6532        try {
6533            //set orientation on WindowManager
6534            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
6535        } catch (RemoteException e) {
6536            // Ignore
6537        }
6538    }
6539
6540    /**
6541     * Return an Intent to launch the currently active dock app as home.  Returns
6542     * null if the standard home should be launched, which is the case if any of the following is
6543     * true:
6544     * <ul>
6545     *  <li>The device is not in either car mode or desk mode
6546     *  <li>The device is in car mode but mEnableCarDockHomeCapture is false
6547     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
6548     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
6549     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
6550     * </ul>
6551     * @return A dock intent.
6552     */
6553    Intent createHomeDockIntent() {
6554        Intent intent = null;
6555
6556        // What home does is based on the mode, not the dock state.  That
6557        // is, when in car mode you should be taken to car home regardless
6558        // of whether we are actually in a car dock.
6559        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6560            if (mEnableCarDockHomeCapture) {
6561                intent = mCarDockIntent;
6562            }
6563        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
6564            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
6565                intent = mDeskDockIntent;
6566            }
6567        } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
6568                && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6569                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
6570                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
6571            // Always launch dock home from home when watch is docked, if it exists.
6572            intent = mDeskDockIntent;
6573        }
6574
6575        if (intent == null) {
6576            return null;
6577        }
6578
6579        ActivityInfo ai = null;
6580        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
6581                intent,
6582                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
6583                mCurrentUserId);
6584        if (info != null) {
6585            ai = info.activityInfo;
6586        }
6587        if (ai != null
6588                && ai.metaData != null
6589                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
6590            intent = new Intent(intent);
6591            intent.setClassName(ai.packageName, ai.name);
6592            return intent;
6593        }
6594
6595        return null;
6596    }
6597
6598    void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
6599        if (awakenFromDreams) {
6600            awakenDreams();
6601        }
6602
6603        Intent dock = createHomeDockIntent();
6604        if (dock != null) {
6605            try {
6606                if (fromHomeKey) {
6607                    dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6608                }
6609                startActivityAsUser(dock, UserHandle.CURRENT);
6610                return;
6611            } catch (ActivityNotFoundException e) {
6612            }
6613        }
6614
6615        Intent intent;
6616
6617        if (fromHomeKey) {
6618            intent = new Intent(mHomeIntent);
6619            intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6620        } else {
6621            intent = mHomeIntent;
6622        }
6623
6624        startActivityAsUser(intent, UserHandle.CURRENT);
6625    }
6626
6627    /**
6628     * goes to the home screen
6629     * @return whether it did anything
6630     */
6631    boolean goHome() {
6632        if (!isUserSetupComplete()) {
6633            Slog.i(TAG, "Not going home because user setup is in progress.");
6634            return false;
6635        }
6636        if (false) {
6637            // This code always brings home to the front.
6638            try {
6639                ActivityManagerNative.getDefault().stopAppSwitches();
6640            } catch (RemoteException e) {
6641            }
6642            sendCloseSystemWindows();
6643            startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
6644        } else {
6645            // This code brings home to the front or, if it is already
6646            // at the front, puts the device to sleep.
6647            try {
6648                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
6649                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
6650                    Log.d(TAG, "UTS-TEST-MODE");
6651                } else {
6652                    ActivityManagerNative.getDefault().stopAppSwitches();
6653                    sendCloseSystemWindows();
6654                    Intent dock = createHomeDockIntent();
6655                    if (dock != null) {
6656                        int result = ActivityManagerNative.getDefault()
6657                                .startActivityAsUser(null, null, dock,
6658                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
6659                                        null, null, 0,
6660                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6661                                        null, null, UserHandle.USER_CURRENT);
6662                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6663                            return false;
6664                        }
6665                    }
6666                }
6667                int result = ActivityManagerNative.getDefault()
6668                        .startActivityAsUser(null, null, mHomeIntent,
6669                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
6670                                null, null, 0,
6671                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6672                                null, null, UserHandle.USER_CURRENT);
6673                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6674                    return false;
6675                }
6676            } catch (RemoteException ex) {
6677                // bummer, the activity manager, which is in this process, is dead
6678            }
6679        }
6680        return true;
6681    }
6682
6683    @Override
6684    public void setCurrentOrientationLw(int newOrientation) {
6685        synchronized (mLock) {
6686            if (newOrientation != mCurrentAppOrientation) {
6687                mCurrentAppOrientation = newOrientation;
6688                updateOrientationListenerLp();
6689            }
6690        }
6691    }
6692
6693    private void performAuditoryFeedbackForAccessibilityIfNeed() {
6694        if (!isGlobalAccessibilityGestureEnabled()) {
6695            return;
6696        }
6697        AudioManager audioManager = (AudioManager) mContext.getSystemService(
6698                Context.AUDIO_SERVICE);
6699        if (audioManager.isSilentMode()) {
6700            return;
6701        }
6702        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
6703                Settings.System.DEFAULT_NOTIFICATION_URI);
6704        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
6705        ringTone.play();
6706    }
6707
6708    private boolean isTheaterModeEnabled() {
6709        return Settings.Global.getInt(mContext.getContentResolver(),
6710                Settings.Global.THEATER_MODE_ON, 0) == 1;
6711    }
6712
6713    private boolean isGlobalAccessibilityGestureEnabled() {
6714        return Settings.Global.getInt(mContext.getContentResolver(),
6715                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
6716    }
6717
6718    @Override
6719    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
6720        if (!mVibrator.hasVibrator()) {
6721            return false;
6722        }
6723        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
6724                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
6725        if (hapticsDisabled && !always) {
6726            return false;
6727        }
6728        long[] pattern = null;
6729        switch (effectId) {
6730            case HapticFeedbackConstants.LONG_PRESS:
6731                pattern = mLongPressVibePattern;
6732                break;
6733            case HapticFeedbackConstants.VIRTUAL_KEY:
6734                pattern = mVirtualKeyVibePattern;
6735                break;
6736            case HapticFeedbackConstants.KEYBOARD_TAP:
6737                pattern = mKeyboardTapVibePattern;
6738                break;
6739            case HapticFeedbackConstants.CLOCK_TICK:
6740                pattern = mClockTickVibePattern;
6741                break;
6742            case HapticFeedbackConstants.CALENDAR_DATE:
6743                pattern = mCalendarDateVibePattern;
6744                break;
6745            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
6746                pattern = mSafeModeDisabledVibePattern;
6747                break;
6748            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
6749                pattern = mSafeModeEnabledVibePattern;
6750                break;
6751            case HapticFeedbackConstants.CONTEXT_CLICK:
6752                pattern = mContextClickVibePattern;
6753                break;
6754            default:
6755                return false;
6756        }
6757        int owningUid;
6758        String owningPackage;
6759        if (win != null) {
6760            owningUid = win.getOwningUid();
6761            owningPackage = win.getOwningPackage();
6762        } else {
6763            owningUid = android.os.Process.myUid();
6764            owningPackage = mContext.getOpPackageName();
6765        }
6766        if (pattern.length == 1) {
6767            // One-shot vibration
6768            mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
6769        } else {
6770            // Pattern vibration
6771            mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
6772        }
6773        return true;
6774    }
6775
6776    @Override
6777    public void keepScreenOnStartedLw() {
6778    }
6779
6780    @Override
6781    public void keepScreenOnStoppedLw() {
6782        if (isKeyguardShowingAndNotOccluded()) {
6783            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
6784        }
6785    }
6786
6787    private int updateSystemUiVisibilityLw() {
6788        // If there is no window focused, there will be nobody to handle the events
6789        // anyway, so just hang on in whatever state we're in until things settle down.
6790        final WindowState win = mFocusedWindow != null ? mFocusedWindow
6791                : mTopFullscreenOpaqueWindowState;
6792        if (win == null) {
6793            return 0;
6794        }
6795        if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
6796            // We are updating at a point where the keyguard has gotten
6797            // focus, but we were last in a state where the top window is
6798            // hiding it.  This is probably because the keyguard as been
6799            // shown while the top window was displayed, so we want to ignore
6800            // it here because this is just a very transient change and it
6801            // will quickly lose focus once it correctly gets hidden.
6802            return 0;
6803        }
6804
6805        int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
6806                & ~mResettingSystemUiFlags
6807                & ~mForceClearedSystemUiFlags;
6808        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
6809            tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
6810        }
6811
6812        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6813            tmpVisibility |= StatusBarManager.DISABLE_RECENT;
6814        }
6815
6816        tmpVisibility = updateLightStatusBarLw(tmpVisibility);
6817        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
6818        final int diff = visibility ^ mLastSystemUiFlags;
6819        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
6820        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
6821                && mFocusedApp == win.getAppToken()) {
6822            return 0;
6823        }
6824        mLastSystemUiFlags = visibility;
6825        mLastFocusNeedsMenu = needsMenu;
6826        mFocusedApp = win.getAppToken();
6827        mHandler.post(new Runnable() {
6828                @Override
6829                public void run() {
6830                    try {
6831                        IStatusBarService statusbar = getStatusBarService();
6832                        if (statusbar != null) {
6833                            statusbar.setSystemUiVisibility(visibility, 0xffffffff, win.toString());
6834                            statusbar.topAppWindowChanged(needsMenu);
6835                        }
6836                    } catch (RemoteException e) {
6837                        // re-acquire status bar service next time it is needed.
6838                        mStatusBarService = null;
6839                    }
6840                }
6841            });
6842        return diff;
6843    }
6844
6845    private int updateLightStatusBarLw(int vis) {
6846        WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
6847                ? mStatusBar
6848                : mTopFullscreenOpaqueOrDimmingWindowState;
6849
6850        if (statusColorWin != null) {
6851            if (statusColorWin == mTopFullscreenOpaqueWindowState) {
6852                // If the top fullscreen-or-dimming window is also the top fullscreen, respect
6853                // its light flag.
6854                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6855                vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
6856                        & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6857            } else if (statusColorWin != null && statusColorWin.isDimming()) {
6858                // Otherwise if it's dimming, clear the light flag.
6859                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6860            }
6861        }
6862        return vis;
6863    }
6864
6865    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
6866        final boolean dockedStackVisible = mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID);
6867        final boolean freeformStackVisible =
6868                mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID);
6869        final boolean forceShowSystemBars = dockedStackVisible || freeformStackVisible;
6870        final boolean forceOpaqueSystemBars = forceShowSystemBars && !mForceStatusBarFromKeyguard;
6871
6872        // apply translucent bar vis flags
6873        WindowState transWin = isStatusBarKeyguard() && !mHideLockScreen
6874                ? mStatusBar
6875                : mTopFullscreenOpaqueWindowState;
6876        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6877        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6878
6879        // prevent status bar interaction from clearing certain flags
6880        int type = win.getAttrs().type;
6881        boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
6882        if (statusBarHasFocus && !isStatusBarKeyguard()) {
6883            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
6884                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
6885                    | View.SYSTEM_UI_FLAG_IMMERSIVE
6886                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
6887                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6888            if (mHideLockScreen) {
6889                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
6890            }
6891            vis = (vis & ~flags) | (oldVis & flags);
6892        }
6893
6894        if ((!areTranslucentBarsAllowed() && transWin != mStatusBar)
6895                || forceOpaqueSystemBars) {
6896            vis &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSLUCENT
6897                    | View.SYSTEM_UI_TRANSPARENT);
6898        }
6899
6900        if (mForceWindowDrawsStatusBarBackground) {
6901            vis |= View.STATUS_BAR_TRANSPARENT;
6902            vis &= ~View.STATUS_BAR_TRANSLUCENT;
6903        }
6904
6905        // update status bar
6906        boolean immersiveSticky =
6907                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
6908        final boolean hideStatusBarWM =
6909                mTopFullscreenOpaqueWindowState != null
6910                && (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
6911                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
6912        final boolean hideStatusBarSysui =
6913                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
6914        final boolean hideNavBarSysui =
6915                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
6916
6917        final boolean transientStatusBarAllowed = mStatusBar != null
6918                && (statusBarHasFocus || (!forceShowSystemBars
6919                        && (hideStatusBarWM || (hideStatusBarSysui && immersiveSticky))));
6920
6921        final boolean transientNavBarAllowed = mNavigationBar != null
6922                && !forceShowSystemBars && hideNavBarSysui && immersiveSticky;
6923
6924        final long now = SystemClock.uptimeMillis();
6925        final boolean pendingPanic = mPendingPanicGestureUptime != 0
6926                && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
6927        if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
6928            // The user performed the panic gesture recently, we're about to hide the bars,
6929            // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
6930            mPendingPanicGestureUptime = 0;
6931            mStatusBarController.showTransient();
6932            mNavigationBarController.showTransient();
6933        }
6934
6935        final boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
6936                && !transientStatusBarAllowed && hideStatusBarSysui;
6937        final boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
6938                && !transientNavBarAllowed;
6939        if (denyTransientStatus || denyTransientNav || forceShowSystemBars) {
6940            // clear the clearable flags instead
6941            clearClearableFlagsLw();
6942            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
6943        }
6944
6945        final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
6946        immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
6947        final boolean navAllowedHidden = immersive || immersiveSticky;
6948
6949        if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
6950                > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
6951            // We can't hide the navbar from this window otherwise the input consumer would not get
6952            // the input events.
6953            vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
6954        }
6955
6956        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
6957
6958        // update navigation bar
6959        boolean oldImmersiveMode = isImmersiveMode(oldVis);
6960        boolean newImmersiveMode = isImmersiveMode(vis);
6961        if (win != null && oldImmersiveMode != newImmersiveMode) {
6962            final String pkg = win.getOwningPackage();
6963            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
6964                    isUserSetupComplete());
6965        }
6966
6967        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
6968
6969        return vis;
6970    }
6971
6972    private void clearClearableFlagsLw() {
6973        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
6974        if (newVal != mResettingSystemUiFlags) {
6975            mResettingSystemUiFlags = newVal;
6976            mWindowManagerFuncs.reevaluateStatusBarVisibility();
6977        }
6978    }
6979
6980    private boolean isImmersiveMode(int vis) {
6981        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
6982        return mNavigationBar != null
6983                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
6984                && (vis & flags) != 0
6985                && canHideNavigationBar();
6986    }
6987
6988    /**
6989     * @return whether the navigation or status bar can be made translucent
6990     *
6991     * This should return true unless touch exploration is not enabled or
6992     * R.boolean.config_enableTranslucentDecor is false.
6993     */
6994    private boolean areTranslucentBarsAllowed() {
6995        return mTranslucentDecorEnabled;
6996    }
6997
6998    // Use this instead of checking config_showNavigationBar so that it can be consistently
6999    // overridden by qemu.hw.mainkeys in the emulator.
7000    @Override
7001    public boolean hasNavigationBar() {
7002        return mHasNavigationBar;
7003    }
7004
7005    @Override
7006    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
7007        mLastInputMethodWindow = ime;
7008        mLastInputMethodTargetWindow = target;
7009    }
7010
7011    @Override
7012    public int getInputMethodWindowVisibleHeightLw() {
7013        return mDockBottom - mCurBottom;
7014    }
7015
7016    @Override
7017    public void setCurrentUserLw(int newUserId) {
7018        mCurrentUserId = newUserId;
7019        if (mKeyguardDelegate != null) {
7020            mKeyguardDelegate.setCurrentUser(newUserId);
7021        }
7022        if (mStatusBarService != null) {
7023            try {
7024                mStatusBarService.setCurrentUser(newUserId);
7025            } catch (RemoteException e) {
7026                // oh well
7027            }
7028        }
7029        setLastInputMethodWindowLw(null, null);
7030    }
7031
7032    @Override
7033    public boolean canMagnifyWindow(int windowType) {
7034        switch (windowType) {
7035            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
7036            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
7037            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
7038            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
7039                return false;
7040            }
7041        }
7042        return true;
7043    }
7044
7045    @Override
7046    public boolean isTopLevelWindow(int windowType) {
7047        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
7048                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
7049            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
7050        }
7051        return true;
7052    }
7053
7054    @Override
7055    public void dump(String prefix, PrintWriter pw, String[] args) {
7056        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
7057                pw.print(" mSystemReady="); pw.print(mSystemReady);
7058                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
7059        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
7060                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
7061                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
7062                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
7063        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
7064                || mForceClearedSystemUiFlags != 0) {
7065            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
7066                    pw.print(Integer.toHexString(mLastSystemUiFlags));
7067                    pw.print(" mResettingSystemUiFlags=0x");
7068                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
7069                    pw.print(" mForceClearedSystemUiFlags=0x");
7070                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
7071        }
7072        if (mLastFocusNeedsMenu) {
7073            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
7074                    pw.println(mLastFocusNeedsMenu);
7075        }
7076        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
7077                pw.println(mWakeGestureEnabledSetting);
7078
7079        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
7080        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
7081                pw.print(" mDockMode="); pw.print(mDockMode);
7082                pw.print(" mEnableCarDockHomeCapture="); pw.print(mEnableCarDockHomeCapture);
7083                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
7084                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
7085        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
7086                pw.print(" mUserRotation="); pw.print(mUserRotation);
7087                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
7088        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
7089        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
7090                pw.print(mCarDockEnablesAccelerometer);
7091                pw.print(" mDeskDockEnablesAccelerometer=");
7092                pw.println(mDeskDockEnablesAccelerometer);
7093        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
7094                pw.print(mLidKeyboardAccessibility);
7095                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
7096                pw.print(" mLidControlsScreenLock="); pw.println(mLidControlsScreenLock);
7097                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
7098        pw.print(prefix);
7099                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
7100                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
7101        pw.print(prefix);
7102                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
7103                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
7104        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
7105        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
7106        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
7107                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
7108        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
7109                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
7110        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
7111                pw.println(mOrientationSensorEnabled);
7112        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
7113                pw.print(","); pw.print(mOverscanScreenTop);
7114                pw.print(") "); pw.print(mOverscanScreenWidth);
7115                pw.print("x"); pw.println(mOverscanScreenHeight);
7116        if (mOverscanLeft != 0 || mOverscanTop != 0
7117                || mOverscanRight != 0 || mOverscanBottom != 0) {
7118            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
7119                    pw.print(" top="); pw.print(mOverscanTop);
7120                    pw.print(" right="); pw.print(mOverscanRight);
7121                    pw.print(" bottom="); pw.println(mOverscanBottom);
7122        }
7123        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
7124                pw.print(mRestrictedOverscanScreenLeft);
7125                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
7126                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
7127                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
7128        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
7129                pw.print(","); pw.print(mUnrestrictedScreenTop);
7130                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
7131                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
7132        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
7133                pw.print(","); pw.print(mRestrictedScreenTop);
7134                pw.print(") "); pw.print(mRestrictedScreenWidth);
7135                pw.print("x"); pw.println(mRestrictedScreenHeight);
7136        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
7137                pw.print(","); pw.print(mStableFullscreenTop);
7138                pw.print(")-("); pw.print(mStableFullscreenRight);
7139                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
7140        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
7141                pw.print(","); pw.print(mStableTop);
7142                pw.print(")-("); pw.print(mStableRight);
7143                pw.print(","); pw.print(mStableBottom); pw.println(")");
7144        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
7145                pw.print(","); pw.print(mSystemTop);
7146                pw.print(")-("); pw.print(mSystemRight);
7147                pw.print(","); pw.print(mSystemBottom); pw.println(")");
7148        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
7149                pw.print(","); pw.print(mCurTop);
7150                pw.print(")-("); pw.print(mCurRight);
7151                pw.print(","); pw.print(mCurBottom); pw.println(")");
7152        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
7153                pw.print(","); pw.print(mContentTop);
7154                pw.print(")-("); pw.print(mContentRight);
7155                pw.print(","); pw.print(mContentBottom); pw.println(")");
7156        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
7157                pw.print(","); pw.print(mVoiceContentTop);
7158                pw.print(")-("); pw.print(mVoiceContentRight);
7159                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
7160        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
7161                pw.print(","); pw.print(mDockTop);
7162                pw.print(")-("); pw.print(mDockRight);
7163                pw.print(","); pw.print(mDockBottom); pw.println(")");
7164        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
7165                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
7166        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
7167                pw.print(" mShowingDream="); pw.print(mShowingDream);
7168                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
7169                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
7170        if (mLastInputMethodWindow != null) {
7171            pw.print(prefix); pw.print("mLastInputMethodWindow=");
7172                    pw.println(mLastInputMethodWindow);
7173        }
7174        if (mLastInputMethodTargetWindow != null) {
7175            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
7176                    pw.println(mLastInputMethodTargetWindow);
7177        }
7178        if (mStatusBar != null) {
7179            pw.print(prefix); pw.print("mStatusBar=");
7180                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
7181                    pw.println(isStatusBarKeyguard());
7182        }
7183        if (mNavigationBar != null) {
7184            pw.print(prefix); pw.print("mNavigationBar=");
7185                    pw.println(mNavigationBar);
7186        }
7187        if (mFocusedWindow != null) {
7188            pw.print(prefix); pw.print("mFocusedWindow=");
7189                    pw.println(mFocusedWindow);
7190        }
7191        if (mFocusedApp != null) {
7192            pw.print(prefix); pw.print("mFocusedApp=");
7193                    pw.println(mFocusedApp);
7194        }
7195        if (mWinDismissingKeyguard != null) {
7196            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
7197                    pw.println(mWinDismissingKeyguard);
7198        }
7199        if (mTopFullscreenOpaqueWindowState != null) {
7200            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
7201                    pw.println(mTopFullscreenOpaqueWindowState);
7202        }
7203        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
7204            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
7205                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
7206        }
7207        if (mForcingShowNavBar) {
7208            pw.print(prefix); pw.print("mForcingShowNavBar=");
7209                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
7210                    pw.println(mForcingShowNavBarLayer);
7211        }
7212        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
7213                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
7214        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
7215                pw.print(" mForceStatusBarFromKeyguard=");
7216                pw.println(mForceStatusBarFromKeyguard);
7217        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
7218                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
7219                pw.print(" mHomePressed="); pw.println(mHomePressed);
7220        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
7221                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
7222                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
7223        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
7224                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
7225                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
7226        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
7227                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
7228        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
7229                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
7230        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
7231                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
7232        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
7233
7234        mGlobalKeyManager.dump(prefix, pw);
7235        mStatusBarController.dump(pw, prefix);
7236        mNavigationBarController.dump(pw, prefix);
7237        PolicyControl.dump(prefix, pw);
7238
7239        if (mWakeGestureListener != null) {
7240            mWakeGestureListener.dump(pw, prefix);
7241        }
7242        if (mOrientationListener != null) {
7243            mOrientationListener.dump(pw, prefix);
7244        }
7245        if (mBurnInProtectionHelper != null) {
7246            mBurnInProtectionHelper.dump(prefix, pw);
7247        }
7248        if (mKeyguardDelegate != null) {
7249            mKeyguardDelegate.dump(prefix, pw);
7250        }
7251    }
7252}
7253