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