Home | History | Annotate | Download | only in impl
      1 /*
      2  *
      3  * Licensed under the Apache License, Version 2.0 (the "License");
      4  * you may not use this file except in compliance with the License.
      5  * You may obtain a copy of the License at
      6  *
      7  *      http://www.apache.org/licenses/LICENSE-2.0
      8  *
      9  * Unless required by applicable law or agreed to in writing, software
     10  * distributed under the License is distributed on an "AS IS" BASIS,
     11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12  * See the License for the specific language governing permissions and
     13  * limitations under the License.
     14  */
     15 
     16 package com.android.internal.policy.impl;
     17 
     18 import android.app.ActivityManager;
     19 import android.app.ActivityManagerNative;
     20 import android.app.AppOpsManager;
     21 import android.app.IUiModeManager;
     22 import android.app.ProgressDialog;
     23 import android.app.SearchManager;
     24 import android.app.UiModeManager;
     25 import android.content.ActivityNotFoundException;
     26 import android.content.BroadcastReceiver;
     27 import android.content.ComponentName;
     28 import android.content.ContentResolver;
     29 import android.content.Context;
     30 import android.content.Intent;
     31 import android.content.IntentFilter;
     32 import android.content.ServiceConnection;
     33 import android.content.pm.ActivityInfo;
     34 import android.content.pm.PackageManager;
     35 import android.content.pm.ResolveInfo;
     36 import android.content.res.CompatibilityInfo;
     37 import android.content.res.Configuration;
     38 import android.content.res.Resources;
     39 import android.content.res.TypedArray;
     40 import android.database.ContentObserver;
     41 import android.graphics.PixelFormat;
     42 import android.graphics.Rect;
     43 import android.media.AudioManager;
     44 import android.media.IAudioService;
     45 import android.media.Ringtone;
     46 import android.media.RingtoneManager;
     47 import android.os.Bundle;
     48 import android.os.FactoryTest;
     49 import android.os.Handler;
     50 import android.os.IBinder;
     51 import android.os.IRemoteCallback;
     52 import android.os.Looper;
     53 import android.os.Message;
     54 import android.os.Messenger;
     55 import android.os.PowerManager;
     56 import android.os.RemoteException;
     57 import android.os.ServiceManager;
     58 import android.os.SystemClock;
     59 import android.os.SystemProperties;
     60 import android.os.UEventObserver;
     61 import android.os.UserHandle;
     62 import android.os.Vibrator;
     63 import android.provider.Settings;
     64 import android.service.dreams.DreamService;
     65 import android.service.dreams.IDreamManager;
     66 import android.util.DisplayMetrics;
     67 import android.util.EventLog;
     68 import android.util.Log;
     69 import android.util.Slog;
     70 import android.util.SparseArray;
     71 import android.view.Display;
     72 import android.view.Gravity;
     73 import android.view.HapticFeedbackConstants;
     74 import android.view.IApplicationToken;
     75 import android.view.IWindowManager;
     76 import android.view.InputChannel;
     77 import android.view.InputDevice;
     78 import android.view.InputEvent;
     79 import android.view.InputEventReceiver;
     80 import android.view.KeyCharacterMap;
     81 import android.view.KeyCharacterMap.FallbackAction;
     82 import android.view.KeyEvent;
     83 import android.view.MotionEvent;
     84 import android.view.Surface;
     85 import android.view.View;
     86 import android.view.ViewConfiguration;
     87 import android.view.Window;
     88 import android.view.WindowManager;
     89 import android.view.WindowManagerGlobal;
     90 import android.view.WindowManagerPolicy;
     91 import android.view.accessibility.AccessibilityEvent;
     92 import android.view.animation.Animation;
     93 import android.view.animation.AnimationUtils;
     94 
     95 import com.android.internal.R;
     96 import com.android.internal.policy.PolicyManager;
     97 import com.android.internal.policy.impl.keyguard.KeyguardViewManager;
     98 import com.android.internal.policy.impl.keyguard.KeyguardViewMediator;
     99 import com.android.internal.statusbar.IStatusBarService;
    100 import com.android.internal.telephony.ITelephony;
    101 import com.android.internal.widget.PointerLocationView;
    102 
    103 import java.io.File;
    104 import java.io.FileReader;
    105 import java.io.IOException;
    106 import java.io.PrintWriter;
    107 
    108 import static android.view.WindowManager.LayoutParams.*;
    109 import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT;
    110 import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
    111 import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED;
    112 
    113 /**
    114  * WindowManagerPolicy implementation for the Android phone UI.  This
    115  * introduces a new method suffix, Lp, for an internal lock of the
    116  * PhoneWindowManager.  This is used to protect some internal state, and
    117  * can be acquired with either thw Lw and Li lock held, so has the restrictions
    118  * of both of those when held.
    119  */
    120 public class PhoneWindowManager implements WindowManagerPolicy {
    121     static final String TAG = "WindowManager";
    122     static final boolean DEBUG = false;
    123     static final boolean localLOGV = false;
    124     static final boolean DEBUG_LAYOUT = false;
    125     static final boolean DEBUG_INPUT = false;
    126     static final boolean DEBUG_STARTING_WINDOW = false;
    127     static final boolean SHOW_STARTING_ANIMATIONS = true;
    128     static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
    129 
    130     // Whether to allow dock apps with METADATA_DOCK_HOME to temporarily take over the Home key.
    131     // No longer recommended for desk docks; still useful in car docks.
    132     static final boolean ENABLE_CAR_DOCK_HOME_CAPTURE = true;
    133     static final boolean ENABLE_DESK_DOCK_HOME_CAPTURE = false;
    134 
    135     static final int LONG_PRESS_POWER_NOTHING = 0;
    136     static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
    137     static final int LONG_PRESS_POWER_SHUT_OFF = 2;
    138     static final int LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM = 3;
    139 
    140     // These need to match the documentation/constant in
    141     // core/res/res/values/config.xml
    142     static final int LONG_PRESS_HOME_NOTHING = 0;
    143     static final int LONG_PRESS_HOME_RECENT_SYSTEM_UI = 1;
    144     static final int LONG_PRESS_HOME_ASSIST = 2;
    145 
    146     static final int DOUBLE_TAP_HOME_NOTHING = 0;
    147     static final int DOUBLE_TAP_HOME_RECENT_SYSTEM_UI = 1;
    148 
    149     static final int APPLICATION_MEDIA_SUBLAYER = -2;
    150     static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
    151     static final int APPLICATION_PANEL_SUBLAYER = 1;
    152     static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
    153 
    154     static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
    155     static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
    156     static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
    157     static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
    158     static public final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
    159 
    160     /**
    161      * These are the system UI flags that, when changing, can cause the layout
    162      * of the screen to change.
    163      */
    164     static final int SYSTEM_UI_CHANGING_LAYOUT =
    165             View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
    166 
    167     /* Table of Application Launch keys.  Maps from key codes to intent categories.
    168      *
    169      * These are special keys that are used to launch particular kinds of applications,
    170      * such as a web browser.  HID defines nearly a hundred of them in the Consumer (0x0C)
    171      * usage page.  We don't support quite that many yet...
    172      */
    173     static SparseArray<String> sApplicationLaunchKeyCategories;
    174     static {
    175         sApplicationLaunchKeyCategories = new SparseArray<String>();
    176         sApplicationLaunchKeyCategories.append(
    177                 KeyEvent.KEYCODE_EXPLORER, Intent.CATEGORY_APP_BROWSER);
    178         sApplicationLaunchKeyCategories.append(
    179                 KeyEvent.KEYCODE_ENVELOPE, Intent.CATEGORY_APP_EMAIL);
    180         sApplicationLaunchKeyCategories.append(
    181                 KeyEvent.KEYCODE_CONTACTS, Intent.CATEGORY_APP_CONTACTS);
    182         sApplicationLaunchKeyCategories.append(
    183                 KeyEvent.KEYCODE_CALENDAR, Intent.CATEGORY_APP_CALENDAR);
    184         sApplicationLaunchKeyCategories.append(
    185                 KeyEvent.KEYCODE_MUSIC, Intent.CATEGORY_APP_MUSIC);
    186         sApplicationLaunchKeyCategories.append(
    187                 KeyEvent.KEYCODE_CALCULATOR, Intent.CATEGORY_APP_CALCULATOR);
    188     }
    189 
    190     /**
    191      * Lock protecting internal state.  Must not call out into window
    192      * manager with lock held.  (This lock will be acquired in places
    193      * where the window manager is calling in with its own lock held.)
    194      */
    195     private final Object mLock = new Object();
    196 
    197     Context mContext;
    198     IWindowManager mWindowManager;
    199     WindowManagerFuncs mWindowManagerFuncs;
    200     PowerManager mPowerManager;
    201     IStatusBarService mStatusBarService;
    202     boolean mPreloadedRecentApps;
    203     final Object mServiceAquireLock = new Object();
    204     Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
    205     SearchManager mSearchManager;
    206 
    207     // Vibrator pattern for haptic feedback of a long press.
    208     long[] mLongPressVibePattern;
    209 
    210     // Vibrator pattern for haptic feedback of virtual key press.
    211     long[] mVirtualKeyVibePattern;
    212 
    213     // Vibrator pattern for a short vibration.
    214     long[] mKeyboardTapVibePattern;
    215 
    216     // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
    217     long[] mSafeModeDisabledVibePattern;
    218 
    219     // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
    220     long[] mSafeModeEnabledVibePattern;
    221 
    222     /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
    223     boolean mEnableShiftMenuBugReports = false;
    224 
    225     boolean mHeadless;
    226     boolean mSafeMode;
    227     WindowState mStatusBar = null;
    228     boolean mHasSystemNavBar;
    229     int mStatusBarHeight;
    230     WindowState mNavigationBar = null;
    231     boolean mHasNavigationBar = false;
    232     boolean mCanHideNavigationBar = false;
    233     boolean mNavigationBarCanMove = false; // can the navigation bar ever move to the side?
    234     boolean mNavigationBarOnBottom = true; // is the navigation bar on the bottom *right now*?
    235     int[] mNavigationBarHeightForRotation = new int[4];
    236     int[] mNavigationBarWidthForRotation = new int[4];
    237 
    238     WindowState mKeyguard = null;
    239     KeyguardViewMediator mKeyguardMediator;
    240     GlobalActions mGlobalActions;
    241     volatile boolean mPowerKeyHandled; // accessed from input reader and handler thread
    242     boolean mPendingPowerKeyUpCanceled;
    243     Handler mHandler;
    244     WindowState mLastInputMethodWindow = null;
    245     WindowState mLastInputMethodTargetWindow = null;
    246 
    247     static final int RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS = 0;
    248     static final int RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW = 1;
    249     static final int RECENT_APPS_BEHAVIOR_DISMISS = 2;
    250     static final int RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH = 3;
    251 
    252     RecentApplicationsDialog mRecentAppsDialog;
    253     int mRecentAppsDialogHeldModifiers;
    254     boolean mLanguageSwitchKeyPressed;
    255 
    256     int mLidState = LID_ABSENT;
    257     boolean mHaveBuiltInKeyboard;
    258 
    259     boolean mSystemReady;
    260     boolean mSystemBooted;
    261     boolean mHdmiPlugged;
    262     int mUiMode;
    263     int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED;
    264     int mLidOpenRotation;
    265     int mCarDockRotation;
    266     int mDeskDockRotation;
    267     int mUndockedHdmiRotation;
    268     int mDemoHdmiRotation;
    269     boolean mDemoHdmiRotationLock;
    270 
    271     int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
    272     int mUserRotation = Surface.ROTATION_0;
    273     boolean mAccelerometerDefault;
    274 
    275     int mAllowAllRotations = -1;
    276     boolean mCarDockEnablesAccelerometer;
    277     boolean mDeskDockEnablesAccelerometer;
    278     int mLidKeyboardAccessibility;
    279     int mLidNavigationAccessibility;
    280     boolean mLidControlsSleep;
    281     int mLongPressOnPowerBehavior = -1;
    282     boolean mScreenOnEarly = false;
    283     boolean mScreenOnFully = false;
    284     boolean mOrientationSensorEnabled = false;
    285     int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
    286     boolean mHasSoftInput = false;
    287 
    288     int mPointerLocationMode = 0; // guarded by mLock
    289 
    290     // The last window we were told about in focusChanged.
    291     WindowState mFocusedWindow;
    292     IApplicationToken mFocusedApp;
    293 
    294     private static final class PointerLocationInputEventReceiver extends InputEventReceiver {
    295         private final PointerLocationView mView;
    296 
    297         public PointerLocationInputEventReceiver(InputChannel inputChannel, Looper looper,
    298                 PointerLocationView view) {
    299             super(inputChannel, looper);
    300             mView = view;
    301         }
    302 
    303         @Override
    304         public void onInputEvent(InputEvent event) {
    305             boolean handled = false;
    306             try {
    307                 if (event instanceof MotionEvent
    308                         && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
    309                     final MotionEvent motionEvent = (MotionEvent)event;
    310                     mView.addPointerEvent(motionEvent);
    311                     handled = true;
    312                 }
    313             } finally {
    314                 finishInputEvent(event, handled);
    315             }
    316         }
    317     }
    318 
    319     // Pointer location view state, only modified on the mHandler Looper.
    320     PointerLocationInputEventReceiver mPointerLocationInputEventReceiver;
    321     PointerLocationView mPointerLocationView;
    322     InputChannel mPointerLocationInputChannel;
    323 
    324     // The current size of the screen; really; extends into the overscan area of
    325     // the screen and doesn't account for any system elements like the status bar.
    326     int mOverscanScreenLeft, mOverscanScreenTop;
    327     int mOverscanScreenWidth, mOverscanScreenHeight;
    328     // The current visible size of the screen; really; (ir)regardless of whether the status
    329     // bar can be hidden but not extending into the overscan area.
    330     int mUnrestrictedScreenLeft, mUnrestrictedScreenTop;
    331     int mUnrestrictedScreenWidth, mUnrestrictedScreenHeight;
    332     // Like mOverscanScreen*, but allowed to move into the overscan region where appropriate.
    333     int mRestrictedOverscanScreenLeft, mRestrictedOverscanScreenTop;
    334     int mRestrictedOverscanScreenWidth, mRestrictedOverscanScreenHeight;
    335     // The current size of the screen; these may be different than (0,0)-(dw,dh)
    336     // if the status bar can't be hidden; in that case it effectively carves out
    337     // that area of the display from all other windows.
    338     int mRestrictedScreenLeft, mRestrictedScreenTop;
    339     int mRestrictedScreenWidth, mRestrictedScreenHeight;
    340     // During layout, the current screen borders accounting for any currently
    341     // visible system UI elements.
    342     int mSystemLeft, mSystemTop, mSystemRight, mSystemBottom;
    343     // For applications requesting stable content insets, these are them.
    344     int mStableLeft, mStableTop, mStableRight, mStableBottom;
    345     // For applications requesting stable content insets but have also set the
    346     // fullscreen window flag, these are the stable dimensions without the status bar.
    347     int mStableFullscreenLeft, mStableFullscreenTop;
    348     int mStableFullscreenRight, mStableFullscreenBottom;
    349     // During layout, the current screen borders with all outer decoration
    350     // (status bar, input method dock) accounted for.
    351     int mCurLeft, mCurTop, mCurRight, mCurBottom;
    352     // During layout, the frame in which content should be displayed
    353     // to the user, accounting for all screen decoration except for any
    354     // space they deem as available for other content.  This is usually
    355     // the same as mCur*, but may be larger if the screen decor has supplied
    356     // content insets.
    357     int mContentLeft, mContentTop, mContentRight, mContentBottom;
    358     // During layout, the current screen borders along which input method
    359     // windows are placed.
    360     int mDockLeft, mDockTop, mDockRight, mDockBottom;
    361     // During layout, the layer at which the doc window is placed.
    362     int mDockLayer;
    363     // During layout, this is the layer of the status bar.
    364     int mStatusBarLayer;
    365     int mLastSystemUiFlags;
    366     // Bits that we are in the process of clearing, so we want to prevent
    367     // them from being set by applications until everything has been updated
    368     // to have them clear.
    369     int mResettingSystemUiFlags = 0;
    370     // Bits that we are currently always keeping cleared.
    371     int mForceClearedSystemUiFlags = 0;
    372     // What we last reported to system UI about whether the compatibility
    373     // menu needs to be displayed.
    374     boolean mLastFocusNeedsMenu = false;
    375 
    376     FakeWindow mHideNavFakeWindow = null;
    377 
    378     static final Rect mTmpParentFrame = new Rect();
    379     static final Rect mTmpDisplayFrame = new Rect();
    380     static final Rect mTmpOverscanFrame = new Rect();
    381     static final Rect mTmpContentFrame = new Rect();
    382     static final Rect mTmpVisibleFrame = new Rect();
    383     static final Rect mTmpNavigationFrame = new Rect();
    384 
    385     WindowState mTopFullscreenOpaqueWindowState;
    386     boolean mTopIsFullscreen;
    387     boolean mForceStatusBar;
    388     boolean mForceStatusBarFromKeyguard;
    389     boolean mHideLockScreen;
    390     boolean mForcingShowNavBar;
    391     int mForcingShowNavBarLayer;
    392 
    393     // States of keyguard dismiss.
    394     private static final int DISMISS_KEYGUARD_NONE = 0; // Keyguard not being dismissed.
    395     private static final int DISMISS_KEYGUARD_START = 1; // Keyguard needs to be dismissed.
    396     private static final int DISMISS_KEYGUARD_CONTINUE = 2; // Keyguard has been dismissed.
    397     int mDismissKeyguard = DISMISS_KEYGUARD_NONE;
    398 
    399     /** The window that is currently dismissing the keyguard. Dismissing the keyguard must only
    400      * be done once per window. */
    401     private WindowState mWinDismissingKeyguard;
    402 
    403     boolean mShowingLockscreen;
    404     boolean mShowingDream;
    405     boolean mDreamingLockscreen;
    406     boolean mHomePressed;
    407     boolean mHomeConsumed;
    408     boolean mHomeDoubleTapPending;
    409     Intent mHomeIntent;
    410     Intent mCarDockIntent;
    411     Intent mDeskDockIntent;
    412     boolean mSearchKeyShortcutPending;
    413     boolean mConsumeSearchKeyUp;
    414     boolean mAssistKeyLongPressed;
    415 
    416     // support for activating the lock screen while the screen is on
    417     boolean mAllowLockscreenWhenOn;
    418     int mLockScreenTimeout;
    419     boolean mLockScreenTimerActive;
    420 
    421     // Behavior of ENDCALL Button.  (See Settings.System.END_BUTTON_BEHAVIOR.)
    422     int mEndcallBehavior;
    423 
    424     // Behavior of POWER button while in-call and screen on.
    425     // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
    426     int mIncallPowerBehavior;
    427 
    428     Display mDisplay;
    429 
    430     int mLandscapeRotation = 0;  // default landscape rotation
    431     int mSeascapeRotation = 0;   // "other" landscape rotation, 180 degrees from mLandscapeRotation
    432     int mPortraitRotation = 0;   // default portrait rotation
    433     int mUpsideDownRotation = 0; // "other" portrait rotation
    434 
    435     int mOverscanLeft = 0;
    436     int mOverscanTop = 0;
    437     int mOverscanRight = 0;
    438     int mOverscanBottom = 0;
    439 
    440     // What we do when the user long presses on home
    441     private int mLongPressOnHomeBehavior;
    442 
    443     // What we do when the user double-taps on home
    444     private int mDoubleTapOnHomeBehavior;
    445 
    446     // Screenshot trigger states
    447     // Time to volume and power must be pressed within this interval of each other.
    448     private static final long SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS = 150;
    449     // Increase the chord delay when taking a screenshot from the keyguard
    450     private static final float KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER = 2.5f;
    451     private boolean mScreenshotChordEnabled;
    452     private boolean mVolumeDownKeyTriggered;
    453     private long mVolumeDownKeyTime;
    454     private boolean mVolumeDownKeyConsumedByScreenshotChord;
    455     private boolean mVolumeUpKeyTriggered;
    456     private boolean mPowerKeyTriggered;
    457     private long mPowerKeyTime;
    458 
    459     SettingsObserver mSettingsObserver;
    460     ShortcutManager mShortcutManager;
    461     PowerManager.WakeLock mBroadcastWakeLock;
    462     boolean mHavePendingMediaKeyRepeatWithWakeLock;
    463 
    464     // Maps global key codes to the components that will handle them.
    465     private GlobalKeyManager mGlobalKeyManager;
    466 
    467     // Fallback actions by key code.
    468     private final SparseArray<KeyCharacterMap.FallbackAction> mFallbackActions =
    469             new SparseArray<KeyCharacterMap.FallbackAction>();
    470 
    471     private static final int MSG_ENABLE_POINTER_LOCATION = 1;
    472     private static final int MSG_DISABLE_POINTER_LOCATION = 2;
    473     private static final int MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK = 3;
    474     private static final int MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK = 4;
    475 
    476     private class PolicyHandler extends Handler {
    477         @Override
    478         public void handleMessage(Message msg) {
    479             switch (msg.what) {
    480                 case MSG_ENABLE_POINTER_LOCATION:
    481                     enablePointerLocation();
    482                     break;
    483                 case MSG_DISABLE_POINTER_LOCATION:
    484                     disablePointerLocation();
    485                     break;
    486                 case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK:
    487                     dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj);
    488                     break;
    489                 case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK:
    490                     dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj);
    491                     break;
    492             }
    493         }
    494     }
    495 
    496     private UEventObserver mHDMIObserver = new UEventObserver() {
    497         @Override
    498         public void onUEvent(UEventObserver.UEvent event) {
    499             setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
    500         }
    501     };
    502 
    503     class SettingsObserver extends ContentObserver {
    504         SettingsObserver(Handler handler) {
    505             super(handler);
    506         }
    507 
    508         void observe() {
    509             // Observe all users' changes
    510             ContentResolver resolver = mContext.getContentResolver();
    511             resolver.registerContentObserver(Settings.System.getUriFor(
    512                     Settings.System.END_BUTTON_BEHAVIOR), false, this,
    513                     UserHandle.USER_ALL);
    514             resolver.registerContentObserver(Settings.Secure.getUriFor(
    515                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this,
    516                     UserHandle.USER_ALL);
    517             resolver.registerContentObserver(Settings.System.getUriFor(
    518                     Settings.System.ACCELEROMETER_ROTATION), false, this,
    519                     UserHandle.USER_ALL);
    520             resolver.registerContentObserver(Settings.System.getUriFor(
    521                     Settings.System.USER_ROTATION), false, this,
    522                     UserHandle.USER_ALL);
    523             resolver.registerContentObserver(Settings.System.getUriFor(
    524                     Settings.System.SCREEN_OFF_TIMEOUT), false, this,
    525                     UserHandle.USER_ALL);
    526             resolver.registerContentObserver(Settings.System.getUriFor(
    527                     Settings.System.POINTER_LOCATION), false, this,
    528                     UserHandle.USER_ALL);
    529             resolver.registerContentObserver(Settings.Secure.getUriFor(
    530                     Settings.Secure.DEFAULT_INPUT_METHOD), false, this,
    531                     UserHandle.USER_ALL);
    532             resolver.registerContentObserver(Settings.System.getUriFor(
    533                     "fancy_rotation_anim"), false, this,
    534                     UserHandle.USER_ALL);
    535             updateSettings();
    536         }
    537 
    538         @Override public void onChange(boolean selfChange) {
    539             updateSettings();
    540             updateRotation(false);
    541         }
    542     }
    543 
    544     class MyOrientationListener extends WindowOrientationListener {
    545         MyOrientationListener(Context context, Handler handler) {
    546             super(context, handler);
    547         }
    548 
    549         @Override
    550         public void onProposedRotationChanged(int rotation) {
    551             if (localLOGV) Log.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
    552             updateRotation(false);
    553         }
    554     }
    555     MyOrientationListener mOrientationListener;
    556 
    557     IStatusBarService getStatusBarService() {
    558         synchronized (mServiceAquireLock) {
    559             if (mStatusBarService == null) {
    560                 mStatusBarService = IStatusBarService.Stub.asInterface(
    561                         ServiceManager.getService("statusbar"));
    562             }
    563             return mStatusBarService;
    564         }
    565     }
    566 
    567     /*
    568      * We always let the sensor be switched on by default except when
    569      * the user has explicitly disabled sensor based rotation or when the
    570      * screen is switched off.
    571      */
    572     boolean needSensorRunningLp() {
    573         if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
    574                 || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
    575                 || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
    576                 || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
    577             // If the application has explicitly requested to follow the
    578             // orientation, then we need to turn the sensor or.
    579             return true;
    580         }
    581         if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
    582                 (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
    583                         || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
    584                         || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) {
    585             // enable accelerometer if we are docked in a dock that enables accelerometer
    586             // orientation management,
    587             return true;
    588         }
    589         if (mUserRotationMode == USER_ROTATION_LOCKED) {
    590             // If the setting for using the sensor by default is enabled, then
    591             // we will always leave it on.  Note that the user could go to
    592             // a window that forces an orientation that does not use the
    593             // sensor and in theory we could turn it off... however, when next
    594             // turning it on we won't have a good value for the current
    595             // orientation for a little bit, which can cause orientation
    596             // changes to lag, so we'd like to keep it always on.  (It will
    597             // still be turned off when the screen is off.)
    598             return false;
    599         }
    600         return true;
    601     }
    602 
    603     /*
    604      * Various use cases for invoking this function
    605      * screen turning off, should always disable listeners if already enabled
    606      * screen turned on and current app has sensor based orientation, enable listeners
    607      * if not already enabled
    608      * screen turned on and current app does not have sensor orientation, disable listeners if
    609      * already enabled
    610      * screen turning on and current app has sensor based orientation, enable listeners if needed
    611      * screen turning on and current app has nosensor based orientation, do nothing
    612      */
    613     void updateOrientationListenerLp() {
    614         if (!mOrientationListener.canDetectOrientation()) {
    615             // If sensor is turned off or nonexistent for some reason
    616             return;
    617         }
    618         //Could have been invoked due to screen turning on or off or
    619         //change of the currently visible window's orientation
    620         if (localLOGV) Log.v(TAG, "Screen status="+mScreenOnEarly+
    621                 ", current orientation="+mCurrentAppOrientation+
    622                 ", SensorEnabled="+mOrientationSensorEnabled);
    623         boolean disable = true;
    624         if (mScreenOnEarly) {
    625             if (needSensorRunningLp()) {
    626                 disable = false;
    627                 //enable listener if not already enabled
    628                 if (!mOrientationSensorEnabled) {
    629                     mOrientationListener.enable();
    630                     if(localLOGV) Log.v(TAG, "Enabling listeners");
    631                     mOrientationSensorEnabled = true;
    632                 }
    633             }
    634         }
    635         //check if sensors need to be disabled
    636         if (disable && mOrientationSensorEnabled) {
    637             mOrientationListener.disable();
    638             if(localLOGV) Log.v(TAG, "Disabling listeners");
    639             mOrientationSensorEnabled = false;
    640         }
    641     }
    642 
    643     private void interceptPowerKeyDown(boolean handled) {
    644         mPowerKeyHandled = handled;
    645         if (!handled) {
    646             mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
    647         }
    648     }
    649 
    650     private boolean interceptPowerKeyUp(boolean canceled) {
    651         if (!mPowerKeyHandled) {
    652             mHandler.removeCallbacks(mPowerLongPress);
    653             return !canceled;
    654         }
    655         return false;
    656     }
    657 
    658     private void cancelPendingPowerKeyAction() {
    659         if (!mPowerKeyHandled) {
    660             mHandler.removeCallbacks(mPowerLongPress);
    661         }
    662         if (mPowerKeyTriggered) {
    663             mPendingPowerKeyUpCanceled = true;
    664         }
    665     }
    666 
    667     private void interceptScreenshotChord() {
    668         if (mScreenshotChordEnabled
    669                 && mVolumeDownKeyTriggered && mPowerKeyTriggered && !mVolumeUpKeyTriggered) {
    670             final long now = SystemClock.uptimeMillis();
    671             if (now <= mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
    672                     && now <= mPowerKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
    673                 mVolumeDownKeyConsumedByScreenshotChord = true;
    674                 cancelPendingPowerKeyAction();
    675 
    676                 mHandler.postDelayed(mScreenshotRunnable, getScreenshotChordLongPressDelay());
    677             }
    678         }
    679     }
    680 
    681     private long getScreenshotChordLongPressDelay() {
    682         if (mKeyguardMediator.isShowing()) {
    683             // Double the time it takes to take a screenshot from the keyguard
    684             return (long) (KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER *
    685                     ViewConfiguration.getGlobalActionKeyTimeout());
    686         }
    687         return ViewConfiguration.getGlobalActionKeyTimeout();
    688     }
    689 
    690     private void cancelPendingScreenshotChordAction() {
    691         mHandler.removeCallbacks(mScreenshotRunnable);
    692     }
    693 
    694     private final Runnable mPowerLongPress = new Runnable() {
    695         @Override
    696         public void run() {
    697             // The context isn't read
    698             if (mLongPressOnPowerBehavior < 0) {
    699                 mLongPressOnPowerBehavior = mContext.getResources().getInteger(
    700                         com.android.internal.R.integer.config_longPressOnPowerBehavior);
    701             }
    702             int resolvedBehavior = mLongPressOnPowerBehavior;
    703             if (FactoryTest.isLongPressOnPowerOffEnabled()) {
    704                 resolvedBehavior = LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM;
    705             }
    706 
    707             switch (resolvedBehavior) {
    708             case LONG_PRESS_POWER_NOTHING:
    709                 break;
    710             case LONG_PRESS_POWER_GLOBAL_ACTIONS:
    711                 mPowerKeyHandled = true;
    712                 if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
    713                     performAuditoryFeedbackForAccessibilityIfNeed();
    714                 }
    715                 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
    716                 showGlobalActionsDialog();
    717                 break;
    718             case LONG_PRESS_POWER_SHUT_OFF:
    719             case LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM:
    720                 mPowerKeyHandled = true;
    721                 performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
    722                 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
    723                 mWindowManagerFuncs.shutdown(resolvedBehavior == LONG_PRESS_POWER_SHUT_OFF);
    724                 break;
    725             }
    726         }
    727     };
    728 
    729     private final Runnable mScreenshotRunnable = new Runnable() {
    730         @Override
    731         public void run() {
    732             takeScreenshot();
    733         }
    734     };
    735 
    736     void showGlobalActionsDialog() {
    737         if (mGlobalActions == null) {
    738             mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs);
    739         }
    740         final boolean keyguardShowing = keyguardIsShowingTq();
    741         mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
    742         if (keyguardShowing) {
    743             // since it took two seconds of long press to bring this up,
    744             // poke the wake lock so they have some time to see the dialog.
    745             mKeyguardMediator.userActivity();
    746         }
    747     }
    748 
    749     boolean isDeviceProvisioned() {
    750         return Settings.Global.getInt(
    751                 mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
    752     }
    753 
    754     private void handleLongPressOnHome() {
    755         if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {
    756             mHomeConsumed = true;
    757             performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
    758 
    759             if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
    760                 toggleRecentApps();
    761             } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_ASSIST) {
    762                 launchAssistAction();
    763             }
    764         }
    765     }
    766 
    767     private void handleDoubleTapOnHome() {
    768         if (mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
    769             mHomeConsumed = true;
    770             toggleRecentApps();
    771         }
    772     }
    773 
    774     private final Runnable mHomeDoubleTapTimeoutRunnable = new Runnable() {
    775         @Override
    776         public void run() {
    777             if (mHomeDoubleTapPending) {
    778                 mHomeDoubleTapPending = false;
    779                 launchHomeFromHotKey();
    780             }
    781         }
    782     };
    783 
    784     /**
    785      * Create (if necessary) and show or dismiss the recent apps dialog according
    786      * according to the requested behavior.
    787      */
    788     void showOrHideRecentAppsDialog(final int behavior) {
    789         mHandler.post(new Runnable() {
    790             @Override
    791             public void run() {
    792                 if (mRecentAppsDialog == null) {
    793                     mRecentAppsDialog = new RecentApplicationsDialog(mContext);
    794                 }
    795                 if (mRecentAppsDialog.isShowing()) {
    796                     switch (behavior) {
    797                         case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS:
    798                         case RECENT_APPS_BEHAVIOR_DISMISS:
    799                             mRecentAppsDialog.dismiss();
    800                             break;
    801                         case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH:
    802                             mRecentAppsDialog.dismissAndSwitch();
    803                             break;
    804                         case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW:
    805                         default:
    806                             break;
    807                     }
    808                 } else {
    809                     switch (behavior) {
    810                         case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS:
    811                             mRecentAppsDialog.show();
    812                             break;
    813                         case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW:
    814                             try {
    815                                 mWindowManager.setInTouchMode(false);
    816                             } catch (RemoteException e) {
    817                             }
    818                             mRecentAppsDialog.show();
    819                             break;
    820                         case RECENT_APPS_BEHAVIOR_DISMISS:
    821                         case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH:
    822                         default:
    823                             break;
    824                     }
    825                 }
    826             }
    827         });
    828     }
    829 
    830     /** {@inheritDoc} */
    831     @Override
    832     public void init(Context context, IWindowManager windowManager,
    833             WindowManagerFuncs windowManagerFuncs) {
    834         mContext = context;
    835         mWindowManager = windowManager;
    836         mWindowManagerFuncs = windowManagerFuncs;
    837         mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
    838         if (!mHeadless) {
    839             // don't create KeyguardViewMediator if headless
    840             mKeyguardMediator = new KeyguardViewMediator(context, null);
    841         }
    842         mHandler = new PolicyHandler();
    843         mOrientationListener = new MyOrientationListener(mContext, mHandler);
    844         try {
    845             mOrientationListener.setCurrentRotation(windowManager.getRotation());
    846         } catch (RemoteException ex) { }
    847         mSettingsObserver = new SettingsObserver(mHandler);
    848         mSettingsObserver.observe();
    849         mShortcutManager = new ShortcutManager(context, mHandler);
    850         mShortcutManager.observe();
    851         mUiMode = context.getResources().getInteger(
    852                 com.android.internal.R.integer.config_defaultUiModeType);
    853         mHomeIntent =  new Intent(Intent.ACTION_MAIN, null);
    854         mHomeIntent.addCategory(Intent.CATEGORY_HOME);
    855         mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    856                 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    857         mCarDockIntent =  new Intent(Intent.ACTION_MAIN, null);
    858         mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
    859         mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    860                 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    861         mDeskDockIntent =  new Intent(Intent.ACTION_MAIN, null);
    862         mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
    863         mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    864                 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    865 
    866         mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    867         mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
    868                 "PhoneWindowManager.mBroadcastWakeLock");
    869         mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
    870         mLidOpenRotation = readRotation(
    871                 com.android.internal.R.integer.config_lidOpenRotation);
    872         mCarDockRotation = readRotation(
    873                 com.android.internal.R.integer.config_carDockRotation);
    874         mDeskDockRotation = readRotation(
    875                 com.android.internal.R.integer.config_deskDockRotation);
    876         mUndockedHdmiRotation = readRotation(
    877                 com.android.internal.R.integer.config_undockedHdmiRotation);
    878         mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
    879                 com.android.internal.R.bool.config_carDockEnablesAccelerometer);
    880         mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
    881                 com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
    882         mLidKeyboardAccessibility = mContext.getResources().getInteger(
    883                 com.android.internal.R.integer.config_lidKeyboardAccessibility);
    884         mLidNavigationAccessibility = mContext.getResources().getInteger(
    885                 com.android.internal.R.integer.config_lidNavigationAccessibility);
    886         mLidControlsSleep = mContext.getResources().getBoolean(
    887                 com.android.internal.R.bool.config_lidControlsSleep);
    888         readConfigurationDependentBehaviors();
    889 
    890         // register for dock events
    891         IntentFilter filter = new IntentFilter();
    892         filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE);
    893         filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE);
    894         filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE);
    895         filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE);
    896         filter.addAction(Intent.ACTION_DOCK_EVENT);
    897         Intent intent = context.registerReceiver(mDockReceiver, filter);
    898         if (intent != null) {
    899             // Retrieve current sticky dock event broadcast.
    900             mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
    901                     Intent.EXTRA_DOCK_STATE_UNDOCKED);
    902         }
    903 
    904         // register for dream-related broadcasts
    905         filter = new IntentFilter();
    906         filter.addAction(Intent.ACTION_DREAMING_STARTED);
    907         filter.addAction(Intent.ACTION_DREAMING_STOPPED);
    908         context.registerReceiver(mDreamReceiver, filter);
    909 
    910         // register for multiuser-relevant broadcasts
    911         filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
    912         context.registerReceiver(mMultiuserReceiver, filter);
    913 
    914         mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
    915         mLongPressVibePattern = getLongIntArray(mContext.getResources(),
    916                 com.android.internal.R.array.config_longPressVibePattern);
    917         mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
    918                 com.android.internal.R.array.config_virtualKeyVibePattern);
    919         mKeyboardTapVibePattern = getLongIntArray(mContext.getResources(),
    920                 com.android.internal.R.array.config_keyboardTapVibePattern);
    921         mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
    922                 com.android.internal.R.array.config_safeModeDisabledVibePattern);
    923         mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
    924                 com.android.internal.R.array.config_safeModeEnabledVibePattern);
    925 
    926         mScreenshotChordEnabled = mContext.getResources().getBoolean(
    927                 com.android.internal.R.bool.config_enableScreenshotChord);
    928 
    929         mGlobalKeyManager = new GlobalKeyManager(mContext);
    930 
    931         // Controls rotation and the like.
    932         initializeHdmiState();
    933 
    934         // Match current screen state.
    935         if (mPowerManager.isScreenOn()) {
    936             screenTurningOn(null);
    937         } else {
    938             screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
    939         }
    940     }
    941 
    942     /**
    943      * Read values from config.xml that may be overridden depending on
    944      * the configuration of the device.
    945      * eg. Disable long press on home goes to recents on sw600dp.
    946      */
    947     private void readConfigurationDependentBehaviors() {
    948         mLongPressOnHomeBehavior = mContext.getResources().getInteger(
    949                 com.android.internal.R.integer.config_longPressOnHomeBehavior);
    950         if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING ||
    951                 mLongPressOnHomeBehavior > LONG_PRESS_HOME_ASSIST) {
    952             mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
    953         }
    954 
    955         mDoubleTapOnHomeBehavior = mContext.getResources().getInteger(
    956                 com.android.internal.R.integer.config_doubleTapOnHomeBehavior);
    957         if (mDoubleTapOnHomeBehavior < DOUBLE_TAP_HOME_NOTHING ||
    958                 mDoubleTapOnHomeBehavior > DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
    959             mDoubleTapOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
    960         }
    961     }
    962 
    963     @Override
    964     public void setInitialDisplaySize(Display display, int width, int height, int density) {
    965         if (display.getDisplayId() != Display.DEFAULT_DISPLAY) {
    966             throw new IllegalArgumentException("Can only set the default display");
    967         }
    968         mDisplay = display;
    969 
    970         int shortSize, longSize;
    971         if (width > height) {
    972             shortSize = height;
    973             longSize = width;
    974             mLandscapeRotation = Surface.ROTATION_0;
    975             mSeascapeRotation = Surface.ROTATION_180;
    976             if (mContext.getResources().getBoolean(
    977                     com.android.internal.R.bool.config_reverseDefaultRotation)) {
    978                 mPortraitRotation = Surface.ROTATION_90;
    979                 mUpsideDownRotation = Surface.ROTATION_270;
    980             } else {
    981                 mPortraitRotation = Surface.ROTATION_270;
    982                 mUpsideDownRotation = Surface.ROTATION_90;
    983             }
    984         } else {
    985             shortSize = width;
    986             longSize = height;
    987             mPortraitRotation = Surface.ROTATION_0;
    988             mUpsideDownRotation = Surface.ROTATION_180;
    989             if (mContext.getResources().getBoolean(
    990                     com.android.internal.R.bool.config_reverseDefaultRotation)) {
    991                 mLandscapeRotation = Surface.ROTATION_270;
    992                 mSeascapeRotation = Surface.ROTATION_90;
    993             } else {
    994                 mLandscapeRotation = Surface.ROTATION_90;
    995                 mSeascapeRotation = Surface.ROTATION_270;
    996             }
    997         }
    998 
    999         mStatusBarHeight = mContext.getResources().getDimensionPixelSize(
   1000                 com.android.internal.R.dimen.status_bar_height);
   1001 
   1002         // Height of the navigation bar when presented horizontally at bottom
   1003         mNavigationBarHeightForRotation[mPortraitRotation] =
   1004         mNavigationBarHeightForRotation[mUpsideDownRotation] =
   1005                 mContext.getResources().getDimensionPixelSize(
   1006                         com.android.internal.R.dimen.navigation_bar_height);
   1007         mNavigationBarHeightForRotation[mLandscapeRotation] =
   1008         mNavigationBarHeightForRotation[mSeascapeRotation] =
   1009                 mContext.getResources().getDimensionPixelSize(
   1010                         com.android.internal.R.dimen.navigation_bar_height_landscape);
   1011 
   1012         // Width of the navigation bar when presented vertically along one side
   1013         mNavigationBarWidthForRotation[mPortraitRotation] =
   1014         mNavigationBarWidthForRotation[mUpsideDownRotation] =
   1015         mNavigationBarWidthForRotation[mLandscapeRotation] =
   1016         mNavigationBarWidthForRotation[mSeascapeRotation] =
   1017                 mContext.getResources().getDimensionPixelSize(
   1018                         com.android.internal.R.dimen.navigation_bar_width);
   1019 
   1020         // SystemUI (status bar) layout policy
   1021         int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density;
   1022 
   1023         if (shortSizeDp < 600) {
   1024             // 0-599dp: "phone" UI with a separate status & navigation bar
   1025             mHasSystemNavBar = false;
   1026             mNavigationBarCanMove = true;
   1027         } else if (shortSizeDp < 720) {
   1028             // 600+dp: "phone" UI with modifications for larger screens
   1029             mHasSystemNavBar = false;
   1030             mNavigationBarCanMove = false;
   1031         }
   1032 
   1033         if (!mHasSystemNavBar) {
   1034             mHasNavigationBar = mContext.getResources().getBoolean(
   1035                     com.android.internal.R.bool.config_showNavigationBar);
   1036             // Allow a system property to override this. Used by the emulator.
   1037             // See also hasNavigationBar().
   1038             String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
   1039             if (! "".equals(navBarOverride)) {
   1040                 if      (navBarOverride.equals("1")) mHasNavigationBar = false;
   1041                 else if (navBarOverride.equals("0")) mHasNavigationBar = true;
   1042             }
   1043         } else {
   1044             mHasNavigationBar = false;
   1045         }
   1046 
   1047         if (mHasSystemNavBar) {
   1048             // The system bar is always at the bottom.  If you are watching
   1049             // a video in landscape, we don't need to hide it if we can still
   1050             // show a 16:9 aspect ratio with it.
   1051             int longSizeDp = longSize * DisplayMetrics.DENSITY_DEFAULT / density;
   1052             int barHeightDp = mNavigationBarHeightForRotation[mLandscapeRotation]
   1053                     * DisplayMetrics.DENSITY_DEFAULT / density;
   1054             int aspect = ((shortSizeDp-barHeightDp) * 16) / longSizeDp;
   1055             // We have computed the aspect ratio with the bar height taken
   1056             // out to be 16:aspect.  If this is less than 9, then hiding
   1057             // the navigation bar will provide more useful space for wide
   1058             // screen movies.
   1059             mCanHideNavigationBar = aspect < 9;
   1060         } else if (mHasNavigationBar) {
   1061             // The navigation bar is at the right in landscape; it seems always
   1062             // useful to hide it for showing a video.
   1063             mCanHideNavigationBar = true;
   1064         } else {
   1065             mCanHideNavigationBar = false;
   1066         }
   1067 
   1068         // For demo purposes, allow the rotation of the HDMI display to be controlled.
   1069         // By default, HDMI locks rotation to landscape.
   1070         if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) {
   1071             mDemoHdmiRotation = mPortraitRotation;
   1072         } else {
   1073             mDemoHdmiRotation = mLandscapeRotation;
   1074         }
   1075         mDemoHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", false);
   1076     }
   1077 
   1078     @Override
   1079     public void setDisplayOverscan(Display display, int left, int top, int right, int bottom) {
   1080         if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
   1081             mOverscanLeft = left;
   1082             mOverscanTop = top;
   1083             mOverscanRight = right;
   1084             mOverscanBottom = bottom;
   1085         }
   1086     }
   1087 
   1088     public void updateSettings() {
   1089         ContentResolver resolver = mContext.getContentResolver();
   1090         boolean updateRotation = false;
   1091         synchronized (mLock) {
   1092             mEndcallBehavior = Settings.System.getIntForUser(resolver,
   1093                     Settings.System.END_BUTTON_BEHAVIOR,
   1094                     Settings.System.END_BUTTON_BEHAVIOR_DEFAULT,
   1095                     UserHandle.USER_CURRENT);
   1096             mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver,
   1097                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
   1098                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT,
   1099                     UserHandle.USER_CURRENT);
   1100 
   1101             // Configure rotation lock.
   1102             int userRotation = Settings.System.getIntForUser(resolver,
   1103                     Settings.System.USER_ROTATION, Surface.ROTATION_0,
   1104                     UserHandle.USER_CURRENT);
   1105             if (mUserRotation != userRotation) {
   1106                 mUserRotation = userRotation;
   1107                 updateRotation = true;
   1108             }
   1109             int userRotationMode = Settings.System.getIntForUser(resolver,
   1110                     Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
   1111                             WindowManagerPolicy.USER_ROTATION_FREE :
   1112                                     WindowManagerPolicy.USER_ROTATION_LOCKED;
   1113             if (mUserRotationMode != userRotationMode) {
   1114                 mUserRotationMode = userRotationMode;
   1115                 updateRotation = true;
   1116                 updateOrientationListenerLp();
   1117             }
   1118 
   1119             if (mSystemReady) {
   1120                 int pointerLocation = Settings.System.getIntForUser(resolver,
   1121                         Settings.System.POINTER_LOCATION, 0, UserHandle.USER_CURRENT);
   1122                 if (mPointerLocationMode != pointerLocation) {
   1123                     mPointerLocationMode = pointerLocation;
   1124                     mHandler.sendEmptyMessage(pointerLocation != 0 ?
   1125                             MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION);
   1126                 }
   1127             }
   1128             // use screen off timeout setting as the timeout for the lockscreen
   1129             mLockScreenTimeout = Settings.System.getIntForUser(resolver,
   1130                     Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT);
   1131             String imId = Settings.Secure.getStringForUser(resolver,
   1132                     Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT);
   1133             boolean hasSoftInput = imId != null && imId.length() > 0;
   1134             if (mHasSoftInput != hasSoftInput) {
   1135                 mHasSoftInput = hasSoftInput;
   1136                 updateRotation = true;
   1137             }
   1138         }
   1139         if (updateRotation) {
   1140             updateRotation(true);
   1141         }
   1142     }
   1143 
   1144     private void enablePointerLocation() {
   1145         if (mPointerLocationView == null) {
   1146             mPointerLocationView = new PointerLocationView(mContext);
   1147             mPointerLocationView.setPrintCoords(false);
   1148 
   1149             WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
   1150                     WindowManager.LayoutParams.MATCH_PARENT,
   1151                     WindowManager.LayoutParams.MATCH_PARENT);
   1152             lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
   1153             lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
   1154                     | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
   1155                     | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
   1156                     | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
   1157             if (ActivityManager.isHighEndGfx()) {
   1158                 lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
   1159                 lp.privateFlags |=
   1160                         WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
   1161             }
   1162             lp.format = PixelFormat.TRANSLUCENT;
   1163             lp.setTitle("PointerLocation");
   1164             WindowManager wm = (WindowManager)
   1165                     mContext.getSystemService(Context.WINDOW_SERVICE);
   1166             lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
   1167             wm.addView(mPointerLocationView, lp);
   1168 
   1169             mPointerLocationInputChannel =
   1170                     mWindowManagerFuncs.monitorInput("PointerLocationView");
   1171             mPointerLocationInputEventReceiver =
   1172                     new PointerLocationInputEventReceiver(mPointerLocationInputChannel,
   1173                             Looper.myLooper(), mPointerLocationView);
   1174         }
   1175     }
   1176 
   1177     private void disablePointerLocation() {
   1178         if (mPointerLocationInputEventReceiver != null) {
   1179             mPointerLocationInputEventReceiver.dispose();
   1180             mPointerLocationInputEventReceiver = null;
   1181         }
   1182 
   1183         if (mPointerLocationInputChannel != null) {
   1184             mPointerLocationInputChannel.dispose();
   1185             mPointerLocationInputChannel = null;
   1186         }
   1187 
   1188         if (mPointerLocationView != null) {
   1189             WindowManager wm = (WindowManager)
   1190                     mContext.getSystemService(Context.WINDOW_SERVICE);
   1191             wm.removeView(mPointerLocationView);
   1192             mPointerLocationView = null;
   1193         }
   1194     }
   1195 
   1196     private int readRotation(int resID) {
   1197         try {
   1198             int rotation = mContext.getResources().getInteger(resID);
   1199             switch (rotation) {
   1200                 case 0:
   1201                     return Surface.ROTATION_0;
   1202                 case 90:
   1203                     return Surface.ROTATION_90;
   1204                 case 180:
   1205                     return Surface.ROTATION_180;
   1206                 case 270:
   1207                     return Surface.ROTATION_270;
   1208             }
   1209         } catch (Resources.NotFoundException e) {
   1210             // fall through
   1211         }
   1212         return -1;
   1213     }
   1214 
   1215     /** {@inheritDoc} */
   1216     @Override
   1217     public int checkAddPermission(WindowManager.LayoutParams attrs, int[] outAppOp) {
   1218         int type = attrs.type;
   1219 
   1220         outAppOp[0] = AppOpsManager.OP_NONE;
   1221 
   1222         if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
   1223                 || type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
   1224             return WindowManagerGlobal.ADD_OKAY;
   1225         }
   1226         String permission = null;
   1227         switch (type) {
   1228             case TYPE_TOAST:
   1229                 // XXX right now the app process has complete control over
   1230                 // this...  should introduce a token to let the system
   1231                 // monitor/control what they are doing.
   1232                 break;
   1233             case TYPE_DREAM:
   1234             case TYPE_INPUT_METHOD:
   1235             case TYPE_WALLPAPER:
   1236                 // The window manager will check these.
   1237                 break;
   1238             case TYPE_PHONE:
   1239             case TYPE_PRIORITY_PHONE:
   1240             case TYPE_SYSTEM_ALERT:
   1241             case TYPE_SYSTEM_ERROR:
   1242             case TYPE_SYSTEM_OVERLAY:
   1243                 permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
   1244                 outAppOp[0] = AppOpsManager.OP_SYSTEM_ALERT_WINDOW;
   1245                 break;
   1246             default:
   1247                 permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
   1248         }
   1249         if (permission != null) {
   1250             if (mContext.checkCallingOrSelfPermission(permission)
   1251                     != PackageManager.PERMISSION_GRANTED) {
   1252                 return WindowManagerGlobal.ADD_PERMISSION_DENIED;
   1253             }
   1254         }
   1255         return WindowManagerGlobal.ADD_OKAY;
   1256     }
   1257 
   1258     @Override
   1259     public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) {
   1260 
   1261         // If this switch statement is modified, modify the comment in the declarations of
   1262         // the type in {@link WindowManager.LayoutParams} as well.
   1263         switch (attrs.type) {
   1264             default:
   1265                 // These are the windows that by default are shown only to the user that created
   1266                 // them. If this needs to be overridden, set
   1267                 // {@link WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS} in
   1268                 // {@link WindowManager.LayoutParams}. Note that permission
   1269                 // {@link android.Manifest.permission.INTERNAL_SYSTEM_WINDOW} is required as well.
   1270                 if ((attrs.privateFlags & PRIVATE_FLAG_SHOW_FOR_ALL_USERS) == 0) {
   1271                     return true;
   1272                 }
   1273                 break;
   1274 
   1275             // These are the windows that by default are shown to all users. However, to
   1276             // protect against spoofing, check permissions below.
   1277             case TYPE_APPLICATION_STARTING:
   1278             case TYPE_BOOT_PROGRESS:
   1279             case TYPE_DISPLAY_OVERLAY:
   1280             case TYPE_HIDDEN_NAV_CONSUMER:
   1281             case TYPE_KEYGUARD:
   1282             case TYPE_KEYGUARD_DIALOG:
   1283             case TYPE_MAGNIFICATION_OVERLAY:
   1284             case TYPE_NAVIGATION_BAR:
   1285             case TYPE_NAVIGATION_BAR_PANEL:
   1286             case TYPE_PHONE:
   1287             case TYPE_POINTER:
   1288             case TYPE_PRIORITY_PHONE:
   1289             case TYPE_RECENTS_OVERLAY:
   1290             case TYPE_SEARCH_BAR:
   1291             case TYPE_STATUS_BAR:
   1292             case TYPE_STATUS_BAR_PANEL:
   1293             case TYPE_STATUS_BAR_SUB_PANEL:
   1294             case TYPE_SYSTEM_DIALOG:
   1295             case TYPE_UNIVERSE_BACKGROUND:
   1296             case TYPE_VOLUME_OVERLAY:
   1297                 break;
   1298         }
   1299 
   1300         // Check if third party app has set window to system window type.
   1301         return mContext.checkCallingOrSelfPermission(
   1302                 android.Manifest.permission.INTERNAL_SYSTEM_WINDOW)
   1303                         != PackageManager.PERMISSION_GRANTED;
   1304     }
   1305 
   1306     public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
   1307         switch (attrs.type) {
   1308             case TYPE_SYSTEM_OVERLAY:
   1309             case TYPE_SECURE_SYSTEM_OVERLAY:
   1310             case TYPE_TOAST:
   1311                 // These types of windows can't receive input events.
   1312                 attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
   1313                         | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
   1314                 attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
   1315                 break;
   1316         }
   1317     }
   1318 
   1319     void readLidState() {
   1320         mLidState = mWindowManagerFuncs.getLidState();
   1321     }
   1322 
   1323     private boolean isHidden(int accessibilityMode) {
   1324         switch (accessibilityMode) {
   1325             case 1:
   1326                 return mLidState == LID_CLOSED;
   1327             case 2:
   1328                 return mLidState == LID_OPEN;
   1329             default:
   1330                 return false;
   1331         }
   1332     }
   1333 
   1334     private boolean isBuiltInKeyboardVisible() {
   1335         return mHaveBuiltInKeyboard && !isHidden(mLidKeyboardAccessibility);
   1336     }
   1337 
   1338     /** {@inheritDoc} */
   1339     public void adjustConfigurationLw(Configuration config, int keyboardPresence,
   1340             int navigationPresence) {
   1341         mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
   1342 
   1343         readConfigurationDependentBehaviors();
   1344         readLidState();
   1345         applyLidSwitchState();
   1346 
   1347         if (config.keyboard == Configuration.KEYBOARD_NOKEYS
   1348                 || (keyboardPresence == PRESENCE_INTERNAL
   1349                         && isHidden(mLidKeyboardAccessibility))) {
   1350             config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
   1351             if (!mHasSoftInput) {
   1352                 config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
   1353             }
   1354         }
   1355 
   1356         if (config.navigation == Configuration.NAVIGATION_NONAV
   1357                 || (navigationPresence == PRESENCE_INTERNAL
   1358                         && isHidden(mLidNavigationAccessibility))) {
   1359             config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
   1360         }
   1361     }
   1362 
   1363     /** {@inheritDoc} */
   1364     public int windowTypeToLayerLw(int type) {
   1365         if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
   1366             return 2;
   1367         }
   1368         switch (type) {
   1369         case TYPE_UNIVERSE_BACKGROUND:
   1370             return 1;
   1371         case TYPE_WALLPAPER:
   1372             // wallpaper is at the bottom, though the window manager may move it.
   1373             return 2;
   1374         case TYPE_PHONE:
   1375             return 3;
   1376         case TYPE_SEARCH_BAR:
   1377             return 4;
   1378         case TYPE_RECENTS_OVERLAY:
   1379         case TYPE_SYSTEM_DIALOG:
   1380             return 5;
   1381         case TYPE_TOAST:
   1382             // toasts and the plugged-in battery thing
   1383             return 6;
   1384         case TYPE_PRIORITY_PHONE:
   1385             // SIM errors and unlock.  Not sure if this really should be in a high layer.
   1386             return 7;
   1387         case TYPE_DREAM:
   1388             // used for Dreams (screensavers with TYPE_DREAM windows)
   1389             return 8;
   1390         case TYPE_SYSTEM_ALERT:
   1391             // like the ANR / app crashed dialogs
   1392             return 9;
   1393         case TYPE_INPUT_METHOD:
   1394             // on-screen keyboards and other such input method user interfaces go here.
   1395             return 10;
   1396         case TYPE_INPUT_METHOD_DIALOG:
   1397             // on-screen keyboards and other such input method user interfaces go here.
   1398             return 11;
   1399         case TYPE_KEYGUARD:
   1400             // the keyguard; nothing on top of these can take focus, since they are
   1401             // responsible for power management when displayed.
   1402             return 12;
   1403         case TYPE_KEYGUARD_DIALOG:
   1404             return 13;
   1405         case TYPE_STATUS_BAR_SUB_PANEL:
   1406             return 14;
   1407         case TYPE_STATUS_BAR:
   1408             return 15;
   1409         case TYPE_STATUS_BAR_PANEL:
   1410             return 16;
   1411         case TYPE_VOLUME_OVERLAY:
   1412             // the on-screen volume indicator and controller shown when the user
   1413             // changes the device volume
   1414             return 17;
   1415         case TYPE_SYSTEM_OVERLAY:
   1416             // the on-screen volume indicator and controller shown when the user
   1417             // changes the device volume
   1418             return 18;
   1419         case TYPE_NAVIGATION_BAR:
   1420             // the navigation bar, if available, shows atop most things
   1421             return 19;
   1422         case TYPE_NAVIGATION_BAR_PANEL:
   1423             // some panels (e.g. search) need to show on top of the navigation bar
   1424             return 20;
   1425         case TYPE_SYSTEM_ERROR:
   1426             // system-level error dialogs
   1427             return 21;
   1428         case TYPE_MAGNIFICATION_OVERLAY:
   1429             // used to highlight the magnified portion of a display
   1430             return 22;
   1431         case TYPE_DISPLAY_OVERLAY:
   1432             // used to simulate secondary display devices
   1433             return 23;
   1434         case TYPE_DRAG:
   1435             // the drag layer: input for drag-and-drop is associated with this window,
   1436             // which sits above all other focusable windows
   1437             return 24;
   1438         case TYPE_SECURE_SYSTEM_OVERLAY:
   1439             return 25;
   1440         case TYPE_BOOT_PROGRESS:
   1441             return 26;
   1442         case TYPE_POINTER:
   1443             // the (mouse) pointer layer
   1444             return 27;
   1445         case TYPE_HIDDEN_NAV_CONSUMER:
   1446             return 28;
   1447         }
   1448         Log.e(TAG, "Unknown window type: " + type);
   1449         return 2;
   1450     }
   1451 
   1452     /** {@inheritDoc} */
   1453     public int subWindowTypeToLayerLw(int type) {
   1454         switch (type) {
   1455         case TYPE_APPLICATION_PANEL:
   1456         case TYPE_APPLICATION_ATTACHED_DIALOG:
   1457             return APPLICATION_PANEL_SUBLAYER;
   1458         case TYPE_APPLICATION_MEDIA:
   1459             return APPLICATION_MEDIA_SUBLAYER;
   1460         case TYPE_APPLICATION_MEDIA_OVERLAY:
   1461             return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
   1462         case TYPE_APPLICATION_SUB_PANEL:
   1463             return APPLICATION_SUB_PANEL_SUBLAYER;
   1464         }
   1465         Log.e(TAG, "Unknown sub-window type: " + type);
   1466         return 0;
   1467     }
   1468 
   1469     public int getMaxWallpaperLayer() {
   1470         return windowTypeToLayerLw(TYPE_STATUS_BAR);
   1471     }
   1472 
   1473     public int getAboveUniverseLayer() {
   1474         return windowTypeToLayerLw(TYPE_SYSTEM_ERROR);
   1475     }
   1476 
   1477     public boolean hasSystemNavBar() {
   1478         return mHasSystemNavBar;
   1479     }
   1480 
   1481     public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation) {
   1482         if (mHasNavigationBar) {
   1483             // For a basic navigation bar, when we are in landscape mode we place
   1484             // the navigation bar to the side.
   1485             if (mNavigationBarCanMove && fullWidth > fullHeight) {
   1486                 return fullWidth - mNavigationBarWidthForRotation[rotation];
   1487             }
   1488         }
   1489         return fullWidth;
   1490     }
   1491 
   1492     public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation) {
   1493         if (mHasSystemNavBar) {
   1494             // For the system navigation bar, we always place it at the bottom.
   1495             return fullHeight - mNavigationBarHeightForRotation[rotation];
   1496         }
   1497         if (mHasNavigationBar) {
   1498             // For a basic navigation bar, when we are in portrait mode we place
   1499             // the navigation bar to the bottom.
   1500             if (!mNavigationBarCanMove || fullWidth < fullHeight) {
   1501                 return fullHeight - mNavigationBarHeightForRotation[rotation];
   1502             }
   1503         }
   1504         return fullHeight;
   1505     }
   1506 
   1507     public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation) {
   1508         return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation);
   1509     }
   1510 
   1511     public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation) {
   1512         // If we don't have a system nav bar, then there is a separate status
   1513         // bar at the top of the display.  We don't count that as part of the
   1514         // fixed decor, since it can hide; however, for purposes of configurations,
   1515         // we do want to exclude it since applications can't generally use that part
   1516         // of the screen.
   1517         if (!mHasSystemNavBar) {
   1518             return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation) - mStatusBarHeight;
   1519         }
   1520         return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation);
   1521     }
   1522 
   1523     @Override
   1524     public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
   1525         return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
   1526     }
   1527 
   1528     @Override
   1529     public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
   1530         switch (attrs.type) {
   1531             case TYPE_STATUS_BAR:
   1532             case TYPE_NAVIGATION_BAR:
   1533             case TYPE_WALLPAPER:
   1534             case TYPE_DREAM:
   1535             case TYPE_UNIVERSE_BACKGROUND:
   1536             case TYPE_KEYGUARD:
   1537                 return false;
   1538             default:
   1539                 return true;
   1540         }
   1541     }
   1542 
   1543     /** {@inheritDoc} */
   1544     @Override
   1545     public View addStartingWindow(IBinder appToken, String packageName, int theme,
   1546             CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes,
   1547             int icon, int windowFlags) {
   1548         if (!SHOW_STARTING_ANIMATIONS) {
   1549             return null;
   1550         }
   1551         if (packageName == null) {
   1552             return null;
   1553         }
   1554 
   1555         WindowManager wm = null;
   1556         View view = null;
   1557 
   1558         try {
   1559             Context context = mContext;
   1560             if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName
   1561                     + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme="
   1562                     + Integer.toHexString(theme));
   1563             if (theme != context.getThemeResId() || labelRes != 0) {
   1564                 try {
   1565                     context = context.createPackageContext(packageName, 0);
   1566                     context.setTheme(theme);
   1567                 } catch (PackageManager.NameNotFoundException e) {
   1568                     // Ignore
   1569                 }
   1570             }
   1571 
   1572             Window win = PolicyManager.makeNewWindow(context);
   1573             final TypedArray ta = win.getWindowStyle();
   1574             if (ta.getBoolean(
   1575                         com.android.internal.R.styleable.Window_windowDisablePreview, false)
   1576                 || ta.getBoolean(
   1577                         com.android.internal.R.styleable.Window_windowShowWallpaper,false)) {
   1578                 return null;
   1579             }
   1580 
   1581             Resources r = context.getResources();
   1582             win.setTitle(r.getText(labelRes, nonLocalizedLabel));
   1583 
   1584             win.setType(
   1585                 WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
   1586             // Force the window flags: this is a fake window, so it is not really
   1587             // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
   1588             // flag because we do know that the next window will take input
   1589             // focus, so we want to get the IME window up on top of us right away.
   1590             win.setFlags(
   1591                 windowFlags|
   1592                 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
   1593                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
   1594                 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
   1595                 windowFlags|
   1596                 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
   1597                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
   1598                 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
   1599 
   1600             if (!compatInfo.supportsScreen()) {
   1601                 win.addFlags(WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW);
   1602             }
   1603 
   1604             win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
   1605                     WindowManager.LayoutParams.MATCH_PARENT);
   1606 
   1607             final WindowManager.LayoutParams params = win.getAttributes();
   1608             params.token = appToken;
   1609             params.packageName = packageName;
   1610             params.windowAnimations = win.getWindowStyle().getResourceId(
   1611                     com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
   1612             params.privateFlags |=
   1613                     WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
   1614             params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
   1615             params.setTitle("Starting " + packageName);
   1616 
   1617             wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
   1618             view = win.getDecorView();
   1619 
   1620             if (win.isFloating()) {
   1621                 // Whoops, there is no way to display an animation/preview
   1622                 // of such a thing!  After all that work...  let's skip it.
   1623                 // (Note that we must do this here because it is in
   1624                 // getDecorView() where the theme is evaluated...  maybe
   1625                 // we should peek the floating attribute from the theme
   1626                 // earlier.)
   1627                 return null;
   1628             }
   1629 
   1630             if (DEBUG_STARTING_WINDOW) Slog.d(
   1631                 TAG, "Adding starting window for " + packageName
   1632                 + " / " + appToken + ": "
   1633                 + (view.getParent() != null ? view : null));
   1634 
   1635             wm.addView(view, params);
   1636 
   1637             // Only return the view if it was successfully added to the
   1638             // window manager... which we can tell by it having a parent.
   1639             return view.getParent() != null ? view : null;
   1640         } catch (WindowManager.BadTokenException e) {
   1641             // ignore
   1642             Log.w(TAG, appToken + " already running, starting window not displayed");
   1643         } catch (RuntimeException e) {
   1644             // don't crash if something else bad happens, for example a
   1645             // failure loading resources because we are loading from an app
   1646             // on external storage that has been unmounted.
   1647             Log.w(TAG, appToken + " failed creating starting window", e);
   1648         } finally {
   1649             if (view != null && view.getParent() == null) {
   1650                 Log.w(TAG, "view not successfully added to wm, removing view");
   1651                 wm.removeViewImmediate(view);
   1652             }
   1653         }
   1654 
   1655         return null;
   1656     }
   1657 
   1658     /** {@inheritDoc} */
   1659     public void removeStartingWindow(IBinder appToken, View window) {
   1660         if (DEBUG_STARTING_WINDOW) {
   1661             RuntimeException e = new RuntimeException("here");
   1662             e.fillInStackTrace();
   1663             Log.v(TAG, "Removing starting window for " + appToken + ": " + window, e);
   1664         }
   1665 
   1666         if (window != null) {
   1667             WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
   1668             wm.removeView(window);
   1669         }
   1670     }
   1671 
   1672     /**
   1673      * Preflight adding a window to the system.
   1674      *
   1675      * Currently enforces that three window types are singletons:
   1676      * <ul>
   1677      * <li>STATUS_BAR_TYPE</li>
   1678      * <li>KEYGUARD_TYPE</li>
   1679      * </ul>
   1680      *
   1681      * @param win The window to be added
   1682      * @param attrs Information about the window to be added
   1683      *
   1684      * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
   1685      * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
   1686      */
   1687     public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
   1688         switch (attrs.type) {
   1689             case TYPE_STATUS_BAR:
   1690                 mContext.enforceCallingOrSelfPermission(
   1691                         android.Manifest.permission.STATUS_BAR_SERVICE,
   1692                         "PhoneWindowManager");
   1693                 if (mStatusBar != null) {
   1694                     if (mStatusBar.isAlive()) {
   1695                         return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
   1696                     }
   1697                 }
   1698                 mStatusBar = win;
   1699                 break;
   1700             case TYPE_NAVIGATION_BAR:
   1701                 mContext.enforceCallingOrSelfPermission(
   1702                         android.Manifest.permission.STATUS_BAR_SERVICE,
   1703                         "PhoneWindowManager");
   1704                 if (mNavigationBar != null) {
   1705                     if (mNavigationBar.isAlive()) {
   1706                         return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
   1707                     }
   1708                 }
   1709                 mNavigationBar = win;
   1710                 if (DEBUG_LAYOUT) Log.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
   1711                 break;
   1712             case TYPE_NAVIGATION_BAR_PANEL:
   1713                 mContext.enforceCallingOrSelfPermission(
   1714                         android.Manifest.permission.STATUS_BAR_SERVICE,
   1715                         "PhoneWindowManager");
   1716                 break;
   1717             case TYPE_STATUS_BAR_PANEL:
   1718                 mContext.enforceCallingOrSelfPermission(
   1719                         android.Manifest.permission.STATUS_BAR_SERVICE,
   1720                         "PhoneWindowManager");
   1721                 break;
   1722             case TYPE_STATUS_BAR_SUB_PANEL:
   1723                 mContext.enforceCallingOrSelfPermission(
   1724                         android.Manifest.permission.STATUS_BAR_SERVICE,
   1725                         "PhoneWindowManager");
   1726                 break;
   1727             case TYPE_KEYGUARD:
   1728                 if (mKeyguard != null) {
   1729                     return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
   1730                 }
   1731                 mKeyguard = win;
   1732                 break;
   1733         }
   1734         return WindowManagerGlobal.ADD_OKAY;
   1735     }
   1736 
   1737     /** {@inheritDoc} */
   1738     public void removeWindowLw(WindowState win) {
   1739         if (mStatusBar == win) {
   1740             mStatusBar = null;
   1741         } else if (mKeyguard == win) {
   1742             mKeyguard = null;
   1743         } else if (mNavigationBar == win) {
   1744             mNavigationBar = null;
   1745         }
   1746     }
   1747 
   1748     static final boolean PRINT_ANIM = false;
   1749 
   1750     /** {@inheritDoc} */
   1751     @Override
   1752     public int selectAnimationLw(WindowState win, int transit) {
   1753         if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
   1754               + ": transit=" + transit);
   1755         if (win == mStatusBar) {
   1756             if (transit == TRANSIT_EXIT
   1757                     || transit == TRANSIT_HIDE) {
   1758                 return R.anim.dock_top_exit;
   1759             } else if (transit == TRANSIT_ENTER
   1760                     || transit == TRANSIT_SHOW) {
   1761                 return R.anim.dock_top_enter;
   1762             }
   1763         } else if (win == mNavigationBar) {
   1764             // This can be on either the bottom or the right.
   1765             if (mNavigationBarOnBottom) {
   1766                 if (transit == TRANSIT_EXIT
   1767                         || transit == TRANSIT_HIDE) {
   1768                     return R.anim.dock_bottom_exit;
   1769                 } else if (transit == TRANSIT_ENTER
   1770                         || transit == TRANSIT_SHOW) {
   1771                     return R.anim.dock_bottom_enter;
   1772                 }
   1773             } else {
   1774                 if (transit == TRANSIT_EXIT
   1775                         || transit == TRANSIT_HIDE) {
   1776                     return R.anim.dock_right_exit;
   1777                 } else if (transit == TRANSIT_ENTER
   1778                         || transit == TRANSIT_SHOW) {
   1779                     return R.anim.dock_right_enter;
   1780                 }
   1781             }
   1782         }
   1783 
   1784         if (transit == TRANSIT_PREVIEW_DONE) {
   1785             if (win.hasAppShownWindows()) {
   1786                 if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
   1787                 return com.android.internal.R.anim.app_starting_exit;
   1788             }
   1789         } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
   1790                 && transit == TRANSIT_ENTER) {
   1791             // Special case: we are animating in a dream, while the keyguard
   1792             // is shown.  We don't want an animation on the dream, because
   1793             // we need it shown immediately with the keyguard animating away
   1794             // to reveal it.
   1795             return -1;
   1796         }
   1797 
   1798         return 0;
   1799     }
   1800 
   1801     @Override
   1802     public void selectRotationAnimationLw(int anim[]) {
   1803         if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
   1804                 + mTopFullscreenOpaqueWindowState + " rotationAnimation="
   1805                 + (mTopFullscreenOpaqueWindowState == null ?
   1806                         "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
   1807         if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
   1808             switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
   1809                 case ROTATION_ANIMATION_CROSSFADE:
   1810                     anim[0] = R.anim.rotation_animation_xfade_exit;
   1811                     anim[1] = R.anim.rotation_animation_enter;
   1812                     break;
   1813                 case ROTATION_ANIMATION_JUMPCUT:
   1814                     anim[0] = R.anim.rotation_animation_jump_exit;
   1815                     anim[1] = R.anim.rotation_animation_enter;
   1816                     break;
   1817                 case ROTATION_ANIMATION_ROTATE:
   1818                 default:
   1819                     anim[0] = anim[1] = 0;
   1820                     break;
   1821             }
   1822         } else {
   1823             anim[0] = anim[1] = 0;
   1824         }
   1825     }
   1826 
   1827     @Override
   1828     public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
   1829             boolean forceDefault) {
   1830         switch (exitAnimId) {
   1831             case R.anim.rotation_animation_xfade_exit:
   1832             case R.anim.rotation_animation_jump_exit:
   1833                 // These are the only cases that matter.
   1834                 if (forceDefault) {
   1835                     return false;
   1836                 }
   1837                 int anim[] = new int[2];
   1838                 selectRotationAnimationLw(anim);
   1839                 return (exitAnimId == anim[0] && enterAnimId == anim[1]);
   1840             default:
   1841                 return true;
   1842         }
   1843     }
   1844 
   1845     @Override
   1846     public Animation createForceHideEnterAnimation(boolean onWallpaper) {
   1847         return AnimationUtils.loadAnimation(mContext, onWallpaper
   1848                 ? com.android.internal.R.anim.lock_screen_wallpaper_behind_enter
   1849                 : com.android.internal.R.anim.lock_screen_behind_enter);
   1850     }
   1851 
   1852     private static void awakenDreams() {
   1853         IDreamManager dreamManager = getDreamManager();
   1854         if (dreamManager != null) {
   1855             try {
   1856                 dreamManager.awaken();
   1857             } catch (RemoteException e) {
   1858                 // fine, stay asleep then
   1859             }
   1860         }
   1861     }
   1862 
   1863     static IDreamManager getDreamManager() {
   1864         return IDreamManager.Stub.asInterface(
   1865                 ServiceManager.checkService(DreamService.DREAM_SERVICE));
   1866     }
   1867 
   1868     static ITelephony getTelephonyService() {
   1869         return ITelephony.Stub.asInterface(
   1870                 ServiceManager.checkService(Context.TELEPHONY_SERVICE));
   1871     }
   1872 
   1873     static IAudioService getAudioService() {
   1874         IAudioService audioService = IAudioService.Stub.asInterface(
   1875                 ServiceManager.checkService(Context.AUDIO_SERVICE));
   1876         if (audioService == null) {
   1877             Log.w(TAG, "Unable to find IAudioService interface.");
   1878         }
   1879         return audioService;
   1880     }
   1881 
   1882     boolean keyguardOn() {
   1883         return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
   1884     }
   1885 
   1886     private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
   1887             WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
   1888             WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
   1889         };
   1890 
   1891     /** {@inheritDoc} */
   1892     @Override
   1893     public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
   1894         final boolean keyguardOn = keyguardOn();
   1895         final int keyCode = event.getKeyCode();
   1896         final int repeatCount = event.getRepeatCount();
   1897         final int metaState = event.getMetaState();
   1898         final int flags = event.getFlags();
   1899         final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
   1900         final boolean canceled = event.isCanceled();
   1901 
   1902         if (DEBUG_INPUT) {
   1903             Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
   1904                     + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
   1905                     + " canceled=" + canceled);
   1906         }
   1907 
   1908         // If we think we might have a volume down & power key chord on the way
   1909         // but we're not sure, then tell the dispatcher to wait a little while and
   1910         // try again later before dispatching.
   1911         if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
   1912             if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) {
   1913                 final long now = SystemClock.uptimeMillis();
   1914                 final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
   1915                 if (now < timeoutTime) {
   1916                     return timeoutTime - now;
   1917                 }
   1918             }
   1919             if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
   1920                     && mVolumeDownKeyConsumedByScreenshotChord) {
   1921                 if (!down) {
   1922                     mVolumeDownKeyConsumedByScreenshotChord = false;
   1923                 }
   1924                 return -1;
   1925             }
   1926         }
   1927 
   1928         // First we always handle the home key here, so applications
   1929         // can never break it, although if keyguard is on, we do let
   1930         // it handle it, because that gives us the correct 5 second
   1931         // timeout.
   1932         if (keyCode == KeyEvent.KEYCODE_HOME) {
   1933 
   1934             // If we have released the home key, and didn't do anything else
   1935             // while it was pressed, then it is time to go home!
   1936             if (!down) {
   1937                 cancelPreloadRecentApps();
   1938 
   1939                 mHomePressed = false;
   1940                 if (mHomeConsumed) {
   1941                     mHomeConsumed = false;
   1942                     return -1;
   1943                 }
   1944 
   1945                 if (canceled) {
   1946                     Log.i(TAG, "Ignoring HOME; event canceled.");
   1947                     return -1;
   1948                 }
   1949 
   1950                 // If an incoming call is ringing, HOME is totally disabled.
   1951                 // (The user is already on the InCallScreen at this point,
   1952                 // and his ONLY options are to answer or reject the call.)
   1953                 try {
   1954                     ITelephony telephonyService = getTelephonyService();
   1955                     if (telephonyService != null && telephonyService.isRinging()) {
   1956                         Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
   1957                         return -1;
   1958                     }
   1959                 } catch (RemoteException ex) {
   1960                     Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
   1961                 }
   1962 
   1963                 // Delay handling home if a double-tap is possible.
   1964                 if (mDoubleTapOnHomeBehavior != DOUBLE_TAP_HOME_NOTHING) {
   1965                     mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable); // just in case
   1966                     mHomeDoubleTapPending = true;
   1967                     mHandler.postDelayed(mHomeDoubleTapTimeoutRunnable,
   1968                             ViewConfiguration.getDoubleTapTimeout());
   1969                     return -1;
   1970                 }
   1971 
   1972                 // Go home!
   1973                 launchHomeFromHotKey();
   1974                 return -1;
   1975             }
   1976 
   1977             // If a system window has focus, then it doesn't make sense
   1978             // right now to interact with applications.
   1979             WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
   1980             if (attrs != null) {
   1981                 final int type = attrs.type;
   1982                 if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
   1983                         || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
   1984                     // the "app" is keyguard, so give it the key
   1985                     return 0;
   1986                 }
   1987                 final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
   1988                 for (int i=0; i<typeCount; i++) {
   1989                     if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
   1990                         // don't do anything, but also don't pass it to the app
   1991                         return -1;
   1992                     }
   1993                 }
   1994             }
   1995 
   1996             // Remember that home is pressed and handle special actions.
   1997             if (repeatCount == 0) {
   1998                 mHomePressed = true;
   1999                 if (mHomeDoubleTapPending) {
   2000                     mHomeDoubleTapPending = false;
   2001                     mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable);
   2002                     handleDoubleTapOnHome();
   2003                 } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI
   2004                         || mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
   2005                     preloadRecentApps();
   2006                 }
   2007             } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
   2008                 if (!keyguardOn) {
   2009                     handleLongPressOnHome();
   2010                 }
   2011             }
   2012             return -1;
   2013         } else if (keyCode == KeyEvent.KEYCODE_MENU) {
   2014             // Hijack modified menu keys for debugging features
   2015             final int chordBug = KeyEvent.META_SHIFT_ON;
   2016 
   2017             if (down && repeatCount == 0) {
   2018                 if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
   2019                     Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
   2020                     mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
   2021                             null, null, null, 0, null, null);
   2022                     return -1;
   2023                 } else if (SHOW_PROCESSES_ON_ALT_MENU &&
   2024                         (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
   2025                     Intent service = new Intent();
   2026                     service.setClassName(mContext, "com.android.server.LoadAverageService");
   2027                     ContentResolver res = mContext.getContentResolver();
   2028                     boolean shown = Settings.Global.getInt(
   2029                             res, Settings.Global.SHOW_PROCESSES, 0) != 0;
   2030                     if (!shown) {
   2031                         mContext.startService(service);
   2032                     } else {
   2033                         mContext.stopService(service);
   2034                     }
   2035                     Settings.Global.putInt(
   2036                             res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
   2037                     return -1;
   2038                 }
   2039             }
   2040         } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
   2041             if (down) {
   2042                 if (repeatCount == 0) {
   2043                     mSearchKeyShortcutPending = true;
   2044                     mConsumeSearchKeyUp = false;
   2045                 }
   2046             } else {
   2047                 mSearchKeyShortcutPending = false;
   2048                 if (mConsumeSearchKeyUp) {
   2049                     mConsumeSearchKeyUp = false;
   2050                     return -1;
   2051                 }
   2052             }
   2053             return 0;
   2054         } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
   2055             if (!keyguardOn) {
   2056                 if (down && repeatCount == 0) {
   2057                     preloadRecentApps();
   2058                 } else if (!down) {
   2059                     toggleRecentApps();
   2060                 }
   2061             }
   2062             return -1;
   2063         } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
   2064             if (down) {
   2065                 if (repeatCount == 0) {
   2066                     mAssistKeyLongPressed = false;
   2067                 } else if (repeatCount == 1) {
   2068                     mAssistKeyLongPressed = true;
   2069                     if (!keyguardOn) {
   2070                          launchAssistLongPressAction();
   2071                     }
   2072                 }
   2073             } else {
   2074                 if (mAssistKeyLongPressed) {
   2075                     mAssistKeyLongPressed = false;
   2076                 } else {
   2077                     if (!keyguardOn) {
   2078                         launchAssistAction();
   2079                     }
   2080                 }
   2081             }
   2082             return -1;
   2083         } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
   2084             if (down && repeatCount == 0) {
   2085                 mHandler.post(mScreenshotRunnable);
   2086             }
   2087             return -1;
   2088         }
   2089 
   2090         // Shortcuts are invoked through Search+key, so intercept those here
   2091         // Any printing key that is chorded with Search should be consumed
   2092         // even if no shortcut was invoked.  This prevents text from being
   2093         // inadvertently inserted when using a keyboard that has built-in macro
   2094         // shortcut keys (that emit Search+x) and some of them are not registered.
   2095         if (mSearchKeyShortcutPending) {
   2096             final KeyCharacterMap kcm = event.getKeyCharacterMap();
   2097             if (kcm.isPrintingKey(keyCode)) {
   2098                 mConsumeSearchKeyUp = true;
   2099                 mSearchKeyShortcutPending = false;
   2100                 if (down && repeatCount == 0 && !keyguardOn) {
   2101                     Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
   2102                     if (shortcutIntent != null) {
   2103                         shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   2104                         try {
   2105                             mContext.startActivity(shortcutIntent);
   2106                         } catch (ActivityNotFoundException ex) {
   2107                             Slog.w(TAG, "Dropping shortcut key combination because "
   2108                                     + "the activity to which it is registered was not found: "
   2109                                     + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
   2110                         }
   2111                     } else {
   2112                         Slog.i(TAG, "Dropping unregistered shortcut key combination: "
   2113                                 + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
   2114                     }
   2115                 }
   2116                 return -1;
   2117             }
   2118         }
   2119 
   2120         // Invoke shortcuts using Meta.
   2121         if (down && repeatCount == 0 && !keyguardOn
   2122                 && (metaState & KeyEvent.META_META_ON) != 0) {
   2123             final KeyCharacterMap kcm = event.getKeyCharacterMap();
   2124             if (kcm.isPrintingKey(keyCode)) {
   2125                 Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
   2126                         metaState & ~(KeyEvent.META_META_ON
   2127                                 | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
   2128                 if (shortcutIntent != null) {
   2129                     shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   2130                     try {
   2131                         mContext.startActivity(shortcutIntent);
   2132                     } catch (ActivityNotFoundException ex) {
   2133                         Slog.w(TAG, "Dropping shortcut key combination because "
   2134                                 + "the activity to which it is registered was not found: "
   2135                                 + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
   2136                     }
   2137                     return -1;
   2138                 }
   2139             }
   2140         }
   2141 
   2142         // Handle application launch keys.
   2143         if (down && repeatCount == 0 && !keyguardOn) {
   2144             String category = sApplicationLaunchKeyCategories.get(keyCode);
   2145             if (category != null) {
   2146                 Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
   2147                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   2148                 try {
   2149                     mContext.startActivity(intent);
   2150                 } catch (ActivityNotFoundException ex) {
   2151                     Slog.w(TAG, "Dropping application launch key because "
   2152                             + "the activity to which it is registered was not found: "
   2153                             + "keyCode=" + keyCode + ", category=" + category, ex);
   2154                 }
   2155                 return -1;
   2156             }
   2157         }
   2158 
   2159         // Display task switcher for ALT-TAB or Meta-TAB.
   2160         if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
   2161             if (mRecentAppsDialogHeldModifiers == 0 && !keyguardOn) {
   2162                 final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
   2163                 if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)
   2164                         || KeyEvent.metaStateHasModifiers(
   2165                                 shiftlessModifiers, KeyEvent.META_META_ON)) {
   2166                     mRecentAppsDialogHeldModifiers = shiftlessModifiers;
   2167                     showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW);
   2168                     return -1;
   2169                 }
   2170             }
   2171         } else if (!down && mRecentAppsDialogHeldModifiers != 0
   2172                 && (metaState & mRecentAppsDialogHeldModifiers) == 0) {
   2173             mRecentAppsDialogHeldModifiers = 0;
   2174             showOrHideRecentAppsDialog(keyguardOn ? RECENT_APPS_BEHAVIOR_DISMISS :
   2175                     RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH);
   2176         }
   2177 
   2178         // Handle keyboard language switching.
   2179         if (down && repeatCount == 0
   2180                 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
   2181                         || (keyCode == KeyEvent.KEYCODE_SPACE
   2182                                 && (metaState & KeyEvent.META_CTRL_MASK) != 0))) {
   2183             int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1;
   2184             mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction);
   2185             return -1;
   2186         }
   2187         if (mLanguageSwitchKeyPressed && !down
   2188                 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
   2189                         || keyCode == KeyEvent.KEYCODE_SPACE)) {
   2190             mLanguageSwitchKeyPressed = false;
   2191             return -1;
   2192         }
   2193 
   2194         if (mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
   2195             return -1;
   2196         }
   2197 
   2198         // Let the application handle the key.
   2199         return 0;
   2200     }
   2201 
   2202     /** {@inheritDoc} */
   2203     @Override
   2204     public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
   2205         // Note: This method is only called if the initial down was unhandled.
   2206         if (DEBUG_INPUT) {
   2207             Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
   2208                     + ", flags=" + event.getFlags()
   2209                     + ", keyCode=" + event.getKeyCode()
   2210                     + ", scanCode=" + event.getScanCode()
   2211                     + ", metaState=" + event.getMetaState()
   2212                     + ", repeatCount=" + event.getRepeatCount()
   2213                     + ", policyFlags=" + policyFlags);
   2214         }
   2215 
   2216         KeyEvent fallbackEvent = null;
   2217         if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
   2218             final KeyCharacterMap kcm = event.getKeyCharacterMap();
   2219             final int keyCode = event.getKeyCode();
   2220             final int metaState = event.getMetaState();
   2221             final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
   2222                     && event.getRepeatCount() == 0;
   2223 
   2224             // Check for fallback actions specified by the key character map.
   2225             final FallbackAction fallbackAction;
   2226             if (initialDown) {
   2227                 fallbackAction = kcm.getFallbackAction(keyCode, metaState);
   2228             } else {
   2229                 fallbackAction = mFallbackActions.get(keyCode);
   2230             }
   2231 
   2232             if (fallbackAction != null) {
   2233                 if (DEBUG_INPUT) {
   2234                     Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
   2235                             + " metaState=" + Integer.toHexString(fallbackAction.metaState));
   2236                 }
   2237 
   2238                 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
   2239                 fallbackEvent = KeyEvent.obtain(
   2240                         event.getDownTime(), event.getEventTime(),
   2241                         event.getAction(), fallbackAction.keyCode,
   2242                         event.getRepeatCount(), fallbackAction.metaState,
   2243                         event.getDeviceId(), event.getScanCode(),
   2244                         flags, event.getSource(), null);
   2245 
   2246                 if (!interceptFallback(win, fallbackEvent, policyFlags)) {
   2247                     fallbackEvent.recycle();
   2248                     fallbackEvent = null;
   2249                 }
   2250 
   2251                 if (initialDown) {
   2252                     mFallbackActions.put(keyCode, fallbackAction);
   2253                 } else if (event.getAction() == KeyEvent.ACTION_UP) {
   2254                     mFallbackActions.remove(keyCode);
   2255                     fallbackAction.recycle();
   2256                 }
   2257             }
   2258         }
   2259 
   2260         if (DEBUG_INPUT) {
   2261             if (fallbackEvent == null) {
   2262                 Slog.d(TAG, "No fallback.");
   2263             } else {
   2264                 Slog.d(TAG, "Performing fallback: " + fallbackEvent);
   2265             }
   2266         }
   2267         return fallbackEvent;
   2268     }
   2269 
   2270     private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
   2271         int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags, true);
   2272         if ((actions & ACTION_PASS_TO_USER) != 0) {
   2273             long delayMillis = interceptKeyBeforeDispatching(
   2274                     win, fallbackEvent, policyFlags);
   2275             if (delayMillis == 0) {
   2276                 return true;
   2277             }
   2278         }
   2279         return false;
   2280     }
   2281 
   2282     private void launchAssistLongPressAction() {
   2283         performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
   2284         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
   2285 
   2286         // launch the search activity
   2287         Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
   2288         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   2289         try {
   2290             // TODO: This only stops the factory-installed search manager.
   2291             // Need to formalize an API to handle others
   2292             SearchManager searchManager = getSearchManager();
   2293             if (searchManager != null) {
   2294                 searchManager.stopSearch();
   2295             }
   2296             mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
   2297         } catch (ActivityNotFoundException e) {
   2298             Slog.w(TAG, "No activity to handle assist long press action.", e);
   2299         }
   2300     }
   2301 
   2302     private void launchAssistAction() {
   2303         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
   2304         Intent intent = ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
   2305                 .getAssistIntent(mContext, true, UserHandle.USER_CURRENT);
   2306         if (intent != null) {
   2307             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
   2308                     | Intent.FLAG_ACTIVITY_SINGLE_TOP
   2309                     | Intent.FLAG_ACTIVITY_CLEAR_TOP);
   2310             try {
   2311                 mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
   2312             } catch (ActivityNotFoundException e) {
   2313                 Slog.w(TAG, "No activity to handle assist action.", e);
   2314             }
   2315         }
   2316     }
   2317 
   2318     private SearchManager getSearchManager() {
   2319         if (mSearchManager == null) {
   2320             mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
   2321         }
   2322         return mSearchManager;
   2323     }
   2324 
   2325     private void preloadRecentApps() {
   2326         mPreloadedRecentApps = true;
   2327         try {
   2328             IStatusBarService statusbar = getStatusBarService();
   2329             if (statusbar != null) {
   2330                 statusbar.preloadRecentApps();
   2331             }
   2332         } catch (RemoteException e) {
   2333             Slog.e(TAG, "RemoteException when preloading recent apps", e);
   2334             // re-acquire status bar service next time it is needed.
   2335             mStatusBarService = null;
   2336         }
   2337     }
   2338 
   2339     private void cancelPreloadRecentApps() {
   2340         if (mPreloadedRecentApps) {
   2341             mPreloadedRecentApps = false;
   2342             try {
   2343                 IStatusBarService statusbar = getStatusBarService();
   2344                 if (statusbar != null) {
   2345                     statusbar.cancelPreloadRecentApps();
   2346                 }
   2347             } catch (RemoteException e) {
   2348                 Slog.e(TAG, "RemoteException when showing recent apps", e);
   2349                 // re-acquire status bar service next time it is needed.
   2350                 mStatusBarService = null;
   2351             }
   2352         }
   2353     }
   2354 
   2355     private void toggleRecentApps() {
   2356         mPreloadedRecentApps = false; // preloading no longer needs to be canceled
   2357         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
   2358         try {
   2359             IStatusBarService statusbar = getStatusBarService();
   2360             if (statusbar != null) {
   2361                 statusbar.toggleRecentApps();
   2362             }
   2363         } catch (RemoteException e) {
   2364             Slog.e(TAG, "RemoteException when showing recent apps", e);
   2365             // re-acquire status bar service next time it is needed.
   2366             mStatusBarService = null;
   2367         }
   2368     }
   2369 
   2370     /**
   2371      * A home key -> launch home action was detected.  Take the appropriate action
   2372      * given the situation with the keyguard.
   2373      */
   2374     void launchHomeFromHotKey() {
   2375         if (mKeyguardMediator != null && mKeyguardMediator.isShowingAndNotHidden()) {
   2376             // don't launch home if keyguard showing
   2377         } else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) {
   2378             // when in keyguard restricted mode, must first verify unlock
   2379             // before launching home
   2380             mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() {
   2381                 public void onKeyguardExitResult(boolean success) {
   2382                     if (success) {
   2383                         try {
   2384                             ActivityManagerNative.getDefault().stopAppSwitches();
   2385                         } catch (RemoteException e) {
   2386                         }
   2387                         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
   2388                         startDockOrHome();
   2389                     }
   2390                 }
   2391             });
   2392         } else {
   2393             // no keyguard stuff to worry about, just launch home!
   2394             try {
   2395                 ActivityManagerNative.getDefault().stopAppSwitches();
   2396             } catch (RemoteException e) {
   2397             }
   2398             sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
   2399             startDockOrHome();
   2400         }
   2401     }
   2402 
   2403     /**
   2404      * A delayed callback use to determine when it is okay to re-allow applications
   2405      * to use certain system UI flags.  This is used to prevent applications from
   2406      * spamming system UI changes that prevent the navigation bar from being shown.
   2407      */
   2408     final Runnable mAllowSystemUiDelay = new Runnable() {
   2409         @Override public void run() {
   2410         }
   2411     };
   2412 
   2413     /**
   2414      * Input handler used while nav bar is hidden.  Captures any touch on the screen,
   2415      * to determine when the nav bar should be shown and prevent applications from
   2416      * receiving those touches.
   2417      */
   2418     final class HideNavInputEventReceiver extends InputEventReceiver {
   2419         public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
   2420             super(inputChannel, looper);
   2421         }
   2422 
   2423         @Override
   2424         public void onInputEvent(InputEvent event) {
   2425             boolean handled = false;
   2426             try {
   2427                 if (event instanceof MotionEvent
   2428                         && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
   2429                     final MotionEvent motionEvent = (MotionEvent)event;
   2430                     if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
   2431                         // When the user taps down, we re-show the nav bar.
   2432                         boolean changed = false;
   2433                         synchronized (mLock) {
   2434                             // Any user activity always causes us to show the
   2435                             // navigation controls, if they had been hidden.
   2436                             // We also clear the low profile and only content
   2437                             // flags so that tapping on the screen will atomically
   2438                             // restore all currently hidden screen decorations.
   2439                             int newVal = mResettingSystemUiFlags |
   2440                                     View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
   2441                                     View.SYSTEM_UI_FLAG_LOW_PROFILE |
   2442                                     View.SYSTEM_UI_FLAG_FULLSCREEN;
   2443                             if (mResettingSystemUiFlags != newVal) {
   2444                                 mResettingSystemUiFlags = newVal;
   2445                                 changed = true;
   2446                             }
   2447                             // We don't allow the system's nav bar to be hidden
   2448                             // again for 1 second, to prevent applications from
   2449                             // spamming us and keeping it from being shown.
   2450                             newVal = mForceClearedSystemUiFlags |
   2451                                     View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
   2452                             if (mForceClearedSystemUiFlags != newVal) {
   2453                                 mForceClearedSystemUiFlags = newVal;
   2454                                 changed = true;
   2455                                 mHandler.postDelayed(new Runnable() {
   2456                                     @Override public void run() {
   2457                                         synchronized (mLock) {
   2458                                             // Clear flags.
   2459                                             mForceClearedSystemUiFlags &=
   2460                                                     ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
   2461                                         }
   2462                                         mWindowManagerFuncs.reevaluateStatusBarVisibility();
   2463                                     }
   2464                                 }, 1000);
   2465                             }
   2466                         }
   2467                         if (changed) {
   2468                             mWindowManagerFuncs.reevaluateStatusBarVisibility();
   2469                         }
   2470                     }
   2471                 }
   2472             } finally {
   2473                 finishInputEvent(event, handled);
   2474             }
   2475         }
   2476     }
   2477     final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
   2478             new InputEventReceiver.Factory() {
   2479         @Override
   2480         public InputEventReceiver createInputEventReceiver(
   2481                 InputChannel inputChannel, Looper looper) {
   2482             return new HideNavInputEventReceiver(inputChannel, looper);
   2483         }
   2484     };
   2485 
   2486     @Override
   2487     public int adjustSystemUiVisibilityLw(int visibility) {
   2488         // Reset any bits in mForceClearingStatusBarVisibility that
   2489         // are now clear.
   2490         mResettingSystemUiFlags &= visibility;
   2491         // Clear any bits in the new visibility that are currently being
   2492         // force cleared, before reporting it.
   2493         return visibility & ~mResettingSystemUiFlags
   2494                 & ~mForceClearedSystemUiFlags;
   2495     }
   2496 
   2497     @Override
   2498     public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
   2499         final int fl = attrs.flags;
   2500         final int systemUiVisibility = (attrs.systemUiVisibility|attrs.subtreeSystemUiVisibility);
   2501 
   2502         if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
   2503                 == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
   2504             int availRight, availBottom;
   2505             if (mCanHideNavigationBar &&
   2506                     (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
   2507                 availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
   2508                 availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
   2509             } else {
   2510                 availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
   2511                 availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
   2512             }
   2513             if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
   2514                 if ((fl & FLAG_FULLSCREEN) != 0) {
   2515                     contentInset.set(mStableFullscreenLeft, mStableFullscreenTop,
   2516                             availRight - mStableFullscreenRight,
   2517                             availBottom - mStableFullscreenBottom);
   2518                 } else {
   2519                     contentInset.set(mStableLeft, mStableTop,
   2520                             availRight - mStableRight, availBottom - mStableBottom);
   2521                 }
   2522             } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
   2523                 contentInset.setEmpty();
   2524             } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
   2525                         | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
   2526                 contentInset.set(mCurLeft, mCurTop,
   2527                         availRight - mCurRight, availBottom - mCurBottom);
   2528             } else {
   2529                 contentInset.set(mCurLeft, mCurTop,
   2530                         availRight - mCurRight, availBottom - mCurBottom);
   2531             }
   2532             return;
   2533         }
   2534         contentInset.setEmpty();
   2535     }
   2536 
   2537     /** {@inheritDoc} */
   2538     @Override
   2539     public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
   2540                               int displayRotation) {
   2541         final int overscanLeft, overscanTop, overscanRight, overscanBottom;
   2542         if (isDefaultDisplay) {
   2543             switch (displayRotation) {
   2544                 case Surface.ROTATION_90:
   2545                     overscanLeft = mOverscanTop;
   2546                     overscanTop = mOverscanRight;
   2547                     overscanRight = mOverscanBottom;
   2548                     overscanBottom = mOverscanLeft;
   2549                     break;
   2550                 case Surface.ROTATION_180:
   2551                     overscanLeft = mOverscanRight;
   2552                     overscanTop = mOverscanBottom;
   2553                     overscanRight = mOverscanLeft;
   2554                     overscanBottom = mOverscanTop;
   2555                     break;
   2556                 case Surface.ROTATION_270:
   2557                     overscanLeft = mOverscanBottom;
   2558                     overscanTop = mOverscanLeft;
   2559                     overscanRight = mOverscanTop;
   2560                     overscanBottom = mOverscanRight;
   2561                     break;
   2562                 default:
   2563                     overscanLeft = mOverscanLeft;
   2564                     overscanTop = mOverscanTop;
   2565                     overscanRight = mOverscanRight;
   2566                     overscanBottom = mOverscanBottom;
   2567                     break;
   2568             }
   2569         } else {
   2570             overscanLeft = 0;
   2571             overscanTop = 0;
   2572             overscanRight = 0;
   2573             overscanBottom = 0;
   2574         }
   2575         mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
   2576         mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
   2577         mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
   2578         mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
   2579         mSystemLeft = 0;
   2580         mSystemTop = 0;
   2581         mSystemRight = displayWidth;
   2582         mSystemBottom = displayHeight;
   2583         mUnrestrictedScreenLeft = overscanLeft;
   2584         mUnrestrictedScreenTop = overscanTop;
   2585         mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
   2586         mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
   2587         mRestrictedScreenLeft = mUnrestrictedScreenLeft;
   2588         mRestrictedScreenTop = mUnrestrictedScreenTop;
   2589         mRestrictedScreenWidth = mUnrestrictedScreenWidth;
   2590         mRestrictedScreenHeight = mUnrestrictedScreenHeight;
   2591         mDockLeft = mContentLeft = mStableLeft = mStableFullscreenLeft
   2592                 = mCurLeft = mUnrestrictedScreenLeft;
   2593         mDockTop = mContentTop = mStableTop = mStableFullscreenTop
   2594                 = mCurTop = mUnrestrictedScreenTop;
   2595         mDockRight = mContentRight = mStableRight = mStableFullscreenRight
   2596                 = mCurRight = displayWidth - overscanRight;
   2597         mDockBottom = mContentBottom = mStableBottom = mStableFullscreenBottom
   2598                 = mCurBottom = displayHeight - overscanBottom;
   2599         mDockLayer = 0x10000000;
   2600         mStatusBarLayer = -1;
   2601 
   2602         // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
   2603         final Rect pf = mTmpParentFrame;
   2604         final Rect df = mTmpDisplayFrame;
   2605         final Rect of = mTmpOverscanFrame;
   2606         final Rect vf = mTmpVisibleFrame;
   2607         pf.left = df.left = of.left = vf.left = mDockLeft;
   2608         pf.top = df.top = of.top = vf.top = mDockTop;
   2609         pf.right = df.right = of.right = vf.right = mDockRight;
   2610         pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
   2611 
   2612         if (isDefaultDisplay) {
   2613             // For purposes of putting out fake window up to steal focus, we will
   2614             // drive nav being hidden only by whether it is requested.
   2615             boolean navVisible = (mLastSystemUiFlags&View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
   2616 
   2617             // When the navigation bar isn't visible, we put up a fake
   2618             // input window to catch all touch events.  This way we can
   2619             // detect when the user presses anywhere to bring back the nav
   2620             // bar and ensure the application doesn't see the event.
   2621             if (navVisible) {
   2622                 if (mHideNavFakeWindow != null) {
   2623                     mHideNavFakeWindow.dismiss();
   2624                     mHideNavFakeWindow = null;
   2625                 }
   2626             } else if (mHideNavFakeWindow == null) {
   2627                 mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow(
   2628                         mHandler.getLooper(), mHideNavInputEventReceiverFactory,
   2629                         "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER,
   2630                         0, false, false, true);
   2631             }
   2632 
   2633             // For purposes of positioning and showing the nav bar, if we have
   2634             // decided that it can't be hidden (because of the screen aspect ratio),
   2635             // then take that into account.
   2636             navVisible |= !mCanHideNavigationBar;
   2637 
   2638             if (mNavigationBar != null) {
   2639                 // Force the navigation bar to its appropriate place and
   2640                 // size.  We need to do this directly, instead of relying on
   2641                 // it to bubble up from the nav bar, because this needs to
   2642                 // change atomically with screen rotations.
   2643                 mNavigationBarOnBottom = (!mNavigationBarCanMove || displayWidth < displayHeight);
   2644                 if (mNavigationBarOnBottom) {
   2645                     // It's a system nav bar or a portrait screen; nav bar goes on bottom.
   2646                     int top = displayHeight - overscanBottom
   2647                             - mNavigationBarHeightForRotation[displayRotation];
   2648                     mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
   2649                     mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
   2650                     if (navVisible) {
   2651                         mNavigationBar.showLw(true);
   2652                         mDockBottom = mTmpNavigationFrame.top;
   2653                         mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
   2654                         mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
   2655                     } else {
   2656                         // We currently want to hide the navigation UI.
   2657                         mNavigationBar.hideLw(true);
   2658                     }
   2659                     if (navVisible && !mNavigationBar.isAnimatingLw()) {
   2660                         // If the nav bar is currently requested to be visible,
   2661                         // and not in the process of animating on or off, then
   2662                         // we can tell the app that it is covered by it.
   2663                         mSystemBottom = mTmpNavigationFrame.top;
   2664                     }
   2665                 } else {
   2666                     // Landscape screen; nav bar goes to the right.
   2667                     int left = displayWidth - overscanRight
   2668                             - mNavigationBarWidthForRotation[displayRotation];
   2669                     mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
   2670                     mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
   2671                     if (navVisible) {
   2672                         mNavigationBar.showLw(true);
   2673                         mDockRight = mTmpNavigationFrame.left;
   2674                         mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
   2675                         mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
   2676                     } else {
   2677                         // We currently want to hide the navigation UI.
   2678                         mNavigationBar.hideLw(true);
   2679                     }
   2680                     if (navVisible && !mNavigationBar.isAnimatingLw()) {
   2681                         // If the nav bar is currently requested to be visible,
   2682                         // and not in the process of animating on or off, then
   2683                         // we can tell the app that it is covered by it.
   2684                         mSystemRight = mTmpNavigationFrame.left;
   2685                     }
   2686                 }
   2687                 // Make sure the content and current rectangles are updated to
   2688                 // account for the restrictions from the navigation bar.
   2689                 mContentTop = mCurTop = mDockTop;
   2690                 mContentBottom = mCurBottom = mDockBottom;
   2691                 mContentLeft = mCurLeft = mDockLeft;
   2692                 mContentRight = mCurRight = mDockRight;
   2693                 mStatusBarLayer = mNavigationBar.getSurfaceLayer();
   2694                 // And compute the final frame.
   2695                 mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
   2696                         mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame);
   2697                 if (DEBUG_LAYOUT) Log.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
   2698             }
   2699             if (DEBUG_LAYOUT) Log.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
   2700                     mDockLeft, mDockTop, mDockRight, mDockBottom));
   2701 
   2702             // decide where the status bar goes ahead of time
   2703             if (mStatusBar != null) {
   2704                 // apply any navigation bar insets
   2705                 pf.left = df.left = of.left = mUnrestrictedScreenLeft;
   2706                 pf.top = df.top = of.top = mUnrestrictedScreenTop;
   2707                 pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
   2708                 pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
   2709                         + mUnrestrictedScreenTop;
   2710                 vf.left = mStableLeft;
   2711                 vf.top = mStableTop;
   2712                 vf.right = mStableRight;
   2713                 vf.bottom = mStableBottom;
   2714 
   2715                 mStatusBarLayer = mStatusBar.getSurfaceLayer();
   2716 
   2717                 // Let the status bar determine its size.
   2718                 mStatusBar.computeFrameLw(pf, df, vf, vf, vf);
   2719 
   2720                 // For layout, the status bar is always at the top with our fixed height.
   2721                 mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
   2722 
   2723                 // If the status bar is hidden, we don't want to cause
   2724                 // windows behind it to scroll.
   2725                 if (mStatusBar.isVisibleLw()) {
   2726                     // Status bar may go away, so the screen area it occupies
   2727                     // is available to apps but just covering them when the
   2728                     // status bar is visible.
   2729                     mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
   2730 
   2731                     mContentTop = mCurTop = mDockTop;
   2732                     mContentBottom = mCurBottom = mDockBottom;
   2733                     mContentLeft = mCurLeft = mDockLeft;
   2734                     mContentRight = mCurRight = mDockRight;
   2735 
   2736                     if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: " +
   2737                         String.format(
   2738                             "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
   2739                             mDockLeft, mDockTop, mDockRight, mDockBottom,
   2740                             mContentLeft, mContentTop, mContentRight, mContentBottom,
   2741                             mCurLeft, mCurTop, mCurRight, mCurBottom));
   2742                 }
   2743                 if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()) {
   2744                     // If the status bar is currently requested to be visible,
   2745                     // and not in the process of animating on or off, then
   2746                     // we can tell the app that it is covered by it.
   2747                     mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
   2748                 }
   2749             }
   2750         }
   2751     }
   2752 
   2753     /** {@inheritDoc} */
   2754     public int getSystemDecorRectLw(Rect systemRect) {
   2755         systemRect.left = mSystemLeft;
   2756         systemRect.top = mSystemTop;
   2757         systemRect.right = mSystemRight;
   2758         systemRect.bottom = mSystemBottom;
   2759         if (mStatusBar != null) return mStatusBar.getSurfaceLayer();
   2760         if (mNavigationBar != null) return mNavigationBar.getSurfaceLayer();
   2761         return 0;
   2762     }
   2763 
   2764     void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
   2765             boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
   2766         if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
   2767             // Here's a special case: if this attached window is a panel that is
   2768             // above the dock window, and the window it is attached to is below
   2769             // the dock window, then the frames we computed for the window it is
   2770             // attached to can not be used because the dock is effectively part
   2771             // of the underlying window and the attached window is floating on top
   2772             // of the whole thing.  So, we ignore the attached window and explicitly
   2773             // compute the frames that would be appropriate without the dock.
   2774             df.left = of.left = cf.left = vf.left = mDockLeft;
   2775             df.top = of.top = cf.top = vf.top = mDockTop;
   2776             df.right = of.right = cf.right = vf.right = mDockRight;
   2777             df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
   2778         } else {
   2779             // The effective display frame of the attached window depends on
   2780             // whether it is taking care of insetting its content.  If not,
   2781             // we need to use the parent's content frame so that the entire
   2782             // window is positioned within that content.  Otherwise we can use
   2783             // the display frame and let the attached window take care of
   2784             // positioning its content appropriately.
   2785             if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
   2786                 cf.set(attached.getOverscanFrameLw());
   2787             } else {
   2788                 // If the window is resizing, then we want to base the content
   2789                 // frame on our attached content frame to resize...  however,
   2790                 // things can be tricky if the attached window is NOT in resize
   2791                 // mode, in which case its content frame will be larger.
   2792                 // Ungh.  So to deal with that, make sure the content frame
   2793                 // we end up using is not covering the IM dock.
   2794                 cf.set(attached.getContentFrameLw());
   2795                 if (attached.getSurfaceLayer() < mDockLayer) {
   2796                     if (cf.left < mContentLeft) cf.left = mContentLeft;
   2797                     if (cf.top < mContentTop) cf.top = mContentTop;
   2798                     if (cf.right > mContentRight) cf.right = mContentRight;
   2799                     if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
   2800                 }
   2801             }
   2802             df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
   2803             of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
   2804             vf.set(attached.getVisibleFrameLw());
   2805         }
   2806         // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
   2807         // window should be positioned relative to its parent or the entire
   2808         // screen.
   2809         pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
   2810                 ? attached.getFrameLw() : df);
   2811     }
   2812 
   2813     private void applyStableConstraints(int sysui, int fl, Rect r) {
   2814         if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
   2815             // If app is requesting a stable layout, don't let the
   2816             // content insets go below the stable values.
   2817             if ((fl & FLAG_FULLSCREEN) != 0) {
   2818                 if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
   2819                 if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
   2820                 if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
   2821                 if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
   2822             } else {
   2823                 if (r.left < mStableLeft) r.left = mStableLeft;
   2824                 if (r.top < mStableTop) r.top = mStableTop;
   2825                 if (r.right > mStableRight) r.right = mStableRight;
   2826                 if (r.bottom > mStableBottom) r.bottom = mStableBottom;
   2827             }
   2828         }
   2829     }
   2830 
   2831     /** {@inheritDoc} */
   2832     @Override
   2833     public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
   2834             WindowState attached) {
   2835         // we've already done the status bar
   2836         if (win == mStatusBar || win == mNavigationBar) {
   2837             return;
   2838         }
   2839         final boolean isDefaultDisplay = win.isDefaultDisplay();
   2840         final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
   2841                 (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
   2842         if (needsToOffsetInputMethodTarget) {
   2843             if (DEBUG_LAYOUT) {
   2844                 Slog.i(TAG, "Offset ime target window by the last ime window state");
   2845             }
   2846             offsetInputMethodWindowLw(mLastInputMethodWindow);
   2847         }
   2848 
   2849         final int fl = attrs.flags;
   2850         final int sim = attrs.softInputMode;
   2851         final int sysUiFl = win.getSystemUiVisibility();
   2852 
   2853         final Rect pf = mTmpParentFrame;
   2854         final Rect df = mTmpDisplayFrame;
   2855         final Rect of = mTmpOverscanFrame;
   2856         final Rect cf = mTmpContentFrame;
   2857         final Rect vf = mTmpVisibleFrame;
   2858 
   2859         final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
   2860                 && mNavigationBar != null && mNavigationBar.isVisibleLw());
   2861 
   2862         final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
   2863 
   2864         if (!isDefaultDisplay) {
   2865             if (attached != null) {
   2866                 // If this window is attached to another, our display
   2867                 // frame is the same as the one we are attached to.
   2868                 setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
   2869             } else {
   2870                 // Give the window full screen.
   2871                 pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
   2872                 pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
   2873                 pf.right = df.right = of.right = cf.right
   2874                         = mOverscanScreenLeft + mOverscanScreenWidth;
   2875                 pf.bottom = df.bottom = of.bottom = cf.bottom
   2876                         = mOverscanScreenTop + mOverscanScreenHeight;
   2877             }
   2878         } else  if (attrs.type == TYPE_INPUT_METHOD) {
   2879             pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
   2880             pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
   2881             pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
   2882             pf.bottom = df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
   2883             // IM dock windows always go to the bottom of the screen.
   2884             attrs.gravity = Gravity.BOTTOM;
   2885             mDockLayer = win.getSurfaceLayer();
   2886         } else {
   2887             if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
   2888                     == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
   2889                 if (DEBUG_LAYOUT)
   2890                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle()
   2891                             + "): IN_SCREEN, INSET_DECOR");
   2892                 // This is the case for a normal activity window: we want it
   2893                 // to cover all of the screen space, and it can take care of
   2894                 // moving its contents to account for screen decorations that
   2895                 // intrude into that space.
   2896                 if (attached != null) {
   2897                     // If this window is attached to another, our display
   2898                     // frame is the same as the one we are attached to.
   2899                     setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
   2900                 } else {
   2901                     if (attrs.type == TYPE_STATUS_BAR_PANEL
   2902                             || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
   2903                         // Status bar panels are the only windows who can go on top of
   2904                         // the status bar.  They are protected by the STATUS_BAR_SERVICE
   2905                         // permission, so they have the same privileges as the status
   2906                         // bar itself.
   2907                         //
   2908                         // However, they should still dodge the navigation bar if it exists.
   2909 
   2910                         pf.left = df.left = of.left = hasNavBar
   2911                                 ? mDockLeft : mUnrestrictedScreenLeft;
   2912                         pf.top = df.top = of.top = mUnrestrictedScreenTop;
   2913                         pf.right = df.right = of.right = hasNavBar
   2914                                 ? mRestrictedScreenLeft+mRestrictedScreenWidth
   2915                                 : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
   2916                         pf.bottom = df.bottom = of.bottom = hasNavBar
   2917                                 ? mRestrictedScreenTop+mRestrictedScreenHeight
   2918                                 : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
   2919 
   2920                         if (DEBUG_LAYOUT) {
   2921                             Log.v(TAG, String.format(
   2922                                         "Laying out status bar window: (%d,%d - %d,%d)",
   2923                                         pf.left, pf.top, pf.right, pf.bottom));
   2924                         }
   2925                     } else if ((attrs.flags&FLAG_LAYOUT_IN_OVERSCAN) != 0
   2926                             && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
   2927                             && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
   2928                         // Asking to layout into the overscan region, so give it that pure
   2929                         // unrestricted area.
   2930                         pf.left = df.left = of.left = mOverscanScreenLeft;
   2931                         pf.top = df.top = of.top = mOverscanScreenTop;
   2932                         pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
   2933                         pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
   2934                                 + mOverscanScreenHeight;
   2935                     } else if (mCanHideNavigationBar
   2936                             && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
   2937                             && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
   2938                             && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
   2939                         // Asking for layout as if the nav bar is hidden, lets the
   2940                         // application extend into the unrestricted overscan screen area.  We
   2941                         // only do this for application windows to ensure no window that
   2942                         // can be above the nav bar can do this.
   2943                         pf.left = df.left = mOverscanScreenLeft;
   2944                         pf.top = df.top = mOverscanScreenTop;
   2945                         pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
   2946                         pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
   2947                         // We need to tell the app about where the frame inside the overscan
   2948                         // is, so it can inset its content by that amount -- it didn't ask
   2949                         // to actually extend itself into the overscan region.
   2950                         of.left = mUnrestrictedScreenLeft;
   2951                         of.top = mUnrestrictedScreenTop;
   2952                         of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
   2953                         of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
   2954                     } else {
   2955                         pf.left = df.left = mRestrictedOverscanScreenLeft;
   2956                         pf.top = df.top = mRestrictedOverscanScreenTop;
   2957                         pf.right = df.right = mRestrictedOverscanScreenLeft
   2958                                 + mRestrictedOverscanScreenWidth;
   2959                         pf.bottom = df.bottom = mRestrictedOverscanScreenTop
   2960                                 + mRestrictedOverscanScreenHeight;
   2961                         // We need to tell the app about where the frame inside the overscan
   2962                         // is, so it can inset its content by that amount -- it didn't ask
   2963                         // to actually extend itself into the overscan region.
   2964                         of.left = mUnrestrictedScreenLeft;
   2965                         of.top = mUnrestrictedScreenTop;
   2966                         of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
   2967                         of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
   2968                     }
   2969 
   2970                     if ((attrs.flags&FLAG_FULLSCREEN) == 0) {
   2971                         if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
   2972                             cf.left = mDockLeft;
   2973                             cf.top = mDockTop;
   2974                             cf.right = mDockRight;
   2975                             cf.bottom = mDockBottom;
   2976                         } else {
   2977                             cf.left = mContentLeft;
   2978                             cf.top = mContentTop;
   2979                             cf.right = mContentRight;
   2980                             cf.bottom = mContentBottom;
   2981                         }
   2982                     } else {
   2983                         // Full screen windows are always given a layout that is as if the
   2984                         // status bar and other transient decors are gone.  This is to avoid
   2985                         // bad states when moving from a window that is not hding the
   2986                         // status bar to one that is.
   2987                         cf.left = mRestrictedScreenLeft;
   2988                         cf.top = mRestrictedScreenTop;
   2989                         cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
   2990                         cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
   2991                     }
   2992 
   2993                     applyStableConstraints(sysUiFl, fl, cf);
   2994                     if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
   2995                         vf.left = mCurLeft;
   2996                         vf.top = mCurTop;
   2997                         vf.right = mCurRight;
   2998                         vf.bottom = mCurBottom;
   2999                     } else {
   3000                         vf.set(cf);
   3001                     }
   3002                 }
   3003             } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
   3004                     & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
   3005                             | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
   3006                 if (DEBUG_LAYOUT)
   3007                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): IN_SCREEN");
   3008                 // A window that has requested to fill the entire screen just
   3009                 // gets everything, period.
   3010                 if (attrs.type == TYPE_STATUS_BAR_PANEL
   3011                         || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
   3012                     pf.left = df.left = of.left = cf.left = hasNavBar
   3013                             ? mDockLeft : mUnrestrictedScreenLeft;
   3014                     pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
   3015                     pf.right = df.right = of.right = cf.right = hasNavBar
   3016                                         ? mRestrictedScreenLeft+mRestrictedScreenWidth
   3017                                         : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
   3018                     pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
   3019                                           ? mRestrictedScreenTop+mRestrictedScreenHeight
   3020                                           : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
   3021                     if (DEBUG_LAYOUT) {
   3022                         Log.v(TAG, String.format(
   3023                                     "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
   3024                                     pf.left, pf.top, pf.right, pf.bottom));
   3025                     }
   3026                 } else if (attrs.type == TYPE_NAVIGATION_BAR
   3027                         || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
   3028                     // The navigation bar has Real Ultimate Power.
   3029                     pf.left = df.left = of.left = mUnrestrictedScreenLeft;
   3030                     pf.top = df.top = of.top = mUnrestrictedScreenTop;
   3031                     pf.right = df.right = of.right = mUnrestrictedScreenLeft
   3032                             + mUnrestrictedScreenWidth;
   3033                     pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
   3034                             + mUnrestrictedScreenHeight;
   3035                     if (DEBUG_LAYOUT) {
   3036                         Log.v(TAG, String.format(
   3037                                     "Laying out navigation bar window: (%d,%d - %d,%d)",
   3038                                     pf.left, pf.top, pf.right, pf.bottom));
   3039                     }
   3040                 } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
   3041                                 || attrs.type == TYPE_BOOT_PROGRESS)
   3042                         && ((fl & FLAG_FULLSCREEN) != 0)) {
   3043                     // Fullscreen secure system overlays get what they ask for.
   3044                     pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
   3045                     pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
   3046                     pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
   3047                             + mOverscanScreenWidth;
   3048                     pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
   3049                             + mOverscanScreenHeight;
   3050                 } else if (attrs.type == TYPE_BOOT_PROGRESS
   3051                         || attrs.type == TYPE_UNIVERSE_BACKGROUND) {
   3052                     // Boot progress screen always covers entire display.
   3053                     pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
   3054                     pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
   3055                     pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
   3056                             + mOverscanScreenWidth;
   3057                     pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
   3058                             + mOverscanScreenHeight;
   3059                 } else if (attrs.type == WindowManager.LayoutParams.TYPE_WALLPAPER) {
   3060                     // The wallpaper mostly goes into the overscan region.
   3061                     pf.left = df.left = of.left = cf.left = mRestrictedOverscanScreenLeft;
   3062                     pf.top = df.top = of.top = cf.top = mRestrictedOverscanScreenTop;
   3063                     pf.right = df.right = of.right = cf.right
   3064                             = mRestrictedOverscanScreenLeft + mRestrictedOverscanScreenWidth;
   3065                     pf.bottom = df.bottom = of.bottom = cf.bottom
   3066                             = mRestrictedOverscanScreenTop + mRestrictedOverscanScreenHeight;
   3067                 } else if ((attrs.flags & FLAG_LAYOUT_IN_OVERSCAN) != 0
   3068                         && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
   3069                         && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
   3070                     // Asking to layout into the overscan region, so give it that pure
   3071                     // unrestricted area.
   3072                     pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
   3073                     pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
   3074                     pf.right = df.right = of.right = cf.right
   3075                             = mOverscanScreenLeft + mOverscanScreenWidth;
   3076                     pf.bottom = df.bottom = of.bottom = cf.bottom
   3077                             = mOverscanScreenTop + mOverscanScreenHeight;
   3078                 } else if (mCanHideNavigationBar
   3079                         && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
   3080                         && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
   3081                         && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
   3082                     // Asking for layout as if the nav bar is hidden, lets the
   3083                     // application extend into the unrestricted screen area.  We
   3084                     // only do this for application windows to ensure no window that
   3085                     // can be above the nav bar can do this.
   3086                     // XXX This assumes that an app asking for this will also
   3087                     // ask for layout in only content.  We can't currently figure out
   3088                     // what the screen would be if only laying out to hide the nav bar.
   3089                     pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
   3090                     pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
   3091                     pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
   3092                             + mUnrestrictedScreenWidth;
   3093                     pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
   3094                             + mUnrestrictedScreenHeight;
   3095                 } else {
   3096                     pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
   3097                     pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
   3098                     pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
   3099                             + mRestrictedScreenWidth;
   3100                     pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
   3101                             + mRestrictedScreenHeight;
   3102                 }
   3103 
   3104                 applyStableConstraints(sysUiFl, fl, cf);
   3105 
   3106                 if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
   3107                     vf.left = mCurLeft;
   3108                     vf.top = mCurTop;
   3109                     vf.right = mCurRight;
   3110                     vf.bottom = mCurBottom;
   3111                 } else {
   3112                     vf.set(cf);
   3113                 }
   3114             } else if (attached != null) {
   3115                 if (DEBUG_LAYOUT)
   3116                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): attached to " + attached);
   3117                 // A child window should be placed inside of the same visible
   3118                 // frame that its parent had.
   3119                 setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
   3120             } else {
   3121                 if (DEBUG_LAYOUT)
   3122                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): normal window");
   3123                 // Otherwise, a normal window must be placed inside the content
   3124                 // of all screen decorations.
   3125                 if (attrs.type == TYPE_STATUS_BAR_PANEL) {
   3126                     // Status bar panels are the only windows who can go on top of
   3127                     // the status bar.  They are protected by the STATUS_BAR_SERVICE
   3128                     // permission, so they have the same privileges as the status
   3129                     // bar itself.
   3130                     pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
   3131                     pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
   3132                     pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
   3133                             + mRestrictedScreenWidth;
   3134                     pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
   3135                             + mRestrictedScreenHeight;
   3136                 } else {
   3137                     pf.left = mContentLeft;
   3138                     pf.top = mContentTop;
   3139                     pf.right = mContentRight;
   3140                     pf.bottom = mContentBottom;
   3141                     if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
   3142                         df.left = of.left = cf.left = mDockLeft;
   3143                         df.top = of.top = cf.top = mDockTop;
   3144                         df.right = of.right = cf.right = mDockRight;
   3145                         df.bottom = of.bottom = cf.bottom = mDockBottom;
   3146                     } else {
   3147                         df.left = of.left = cf.left = mContentLeft;
   3148                         df.top = of.top = cf.top = mContentTop;
   3149                         df.right = of.right = cf.right = mContentRight;
   3150                         df.bottom = of.bottom = cf.bottom = mContentBottom;
   3151                     }
   3152                     if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
   3153                         vf.left = mCurLeft;
   3154                         vf.top = mCurTop;
   3155                         vf.right = mCurRight;
   3156                         vf.bottom = mCurBottom;
   3157                     } else {
   3158                         vf.set(cf);
   3159                     }
   3160                 }
   3161             }
   3162         }
   3163 
   3164         if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
   3165             df.left = df.top = of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
   3166             df.right = df.bottom = of.right = of.bottom = cf.right = cf.bottom
   3167                     = vf.right = vf.bottom = 10000;
   3168         }
   3169 
   3170         if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
   3171                 + ": sim=#" + Integer.toHexString(sim)
   3172                 + " attach=" + attached + " type=" + attrs.type
   3173                 + String.format(" flags=0x%08x", fl)
   3174                 + " pf=" + pf.toShortString() + " df=" + df.toShortString()
   3175                 + " of=" + of.toShortString()
   3176                 + " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
   3177 
   3178         win.computeFrameLw(pf, df, of, cf, vf);
   3179 
   3180         // Dock windows carve out the bottom of the screen, so normal windows
   3181         // can't appear underneath them.
   3182         if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
   3183                 && !win.getGivenInsetsPendingLw()) {
   3184             setLastInputMethodWindowLw(null, null);
   3185             offsetInputMethodWindowLw(win);
   3186         }
   3187     }
   3188 
   3189     private void offsetInputMethodWindowLw(WindowState win) {
   3190         int top = win.getContentFrameLw().top;
   3191         top += win.getGivenContentInsetsLw().top;
   3192         if (mContentBottom > top) {
   3193             mContentBottom = top;
   3194         }
   3195         top = win.getVisibleFrameLw().top;
   3196         top += win.getGivenVisibleInsetsLw().top;
   3197         if (mCurBottom > top) {
   3198             mCurBottom = top;
   3199         }
   3200         if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
   3201                 + mDockBottom + " mContentBottom="
   3202                 + mContentBottom + " mCurBottom=" + mCurBottom);
   3203     }
   3204 
   3205     /** {@inheritDoc} */
   3206     @Override
   3207     public void finishLayoutLw() {
   3208         return;
   3209     }
   3210 
   3211     /** {@inheritDoc} */
   3212     @Override
   3213     public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
   3214         mTopFullscreenOpaqueWindowState = null;
   3215         mForceStatusBar = false;
   3216         mForceStatusBarFromKeyguard = false;
   3217         mForcingShowNavBar = false;
   3218         mForcingShowNavBarLayer = -1;
   3219 
   3220         mHideLockScreen = false;
   3221         mAllowLockscreenWhenOn = false;
   3222         mDismissKeyguard = DISMISS_KEYGUARD_NONE;
   3223         mShowingLockscreen = false;
   3224         mShowingDream = false;
   3225     }
   3226 
   3227     /** {@inheritDoc} */
   3228     @Override
   3229     public void applyPostLayoutPolicyLw(WindowState win,
   3230                                 WindowManager.LayoutParams attrs) {
   3231         if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
   3232                 + win.isVisibleOrBehindKeyguardLw());
   3233         if (mTopFullscreenOpaqueWindowState == null && (win.getAttrs().privateFlags
   3234                 &WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_SHOW_NAV_BAR) != 0) {
   3235             if (mForcingShowNavBarLayer < 0) {
   3236                 mForcingShowNavBar = true;
   3237                 mForcingShowNavBarLayer = win.getSurfaceLayer();
   3238             }
   3239         }
   3240         if (mTopFullscreenOpaqueWindowState == null &&
   3241                 win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
   3242             if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
   3243                 if (attrs.type == TYPE_KEYGUARD) {
   3244                     mForceStatusBarFromKeyguard = true;
   3245                 } else {
   3246                     mForceStatusBar = true;
   3247                 }
   3248             }
   3249             if (attrs.type == TYPE_KEYGUARD) {
   3250                 mShowingLockscreen = true;
   3251             }
   3252             boolean applyWindow = attrs.type >= FIRST_APPLICATION_WINDOW
   3253                     && attrs.type <= LAST_APPLICATION_WINDOW;
   3254             if (attrs.type == TYPE_DREAM) {
   3255                 // If the lockscreen was showing when the dream started then wait
   3256                 // for the dream to draw before hiding the lockscreen.
   3257                 if (!mDreamingLockscreen
   3258                         || (win.isVisibleLw() && win.hasDrawnLw())) {
   3259                     mShowingDream = true;
   3260                     applyWindow = true;
   3261                 }
   3262             }
   3263             if (applyWindow
   3264                     && attrs.x == 0 && attrs.y == 0
   3265                     && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
   3266                     && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
   3267                 if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
   3268                 mTopFullscreenOpaqueWindowState = win;
   3269                 if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
   3270                     if (DEBUG_LAYOUT) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
   3271                     mHideLockScreen = true;
   3272                     mForceStatusBarFromKeyguard = false;
   3273                 }
   3274                 if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0
   3275                         && mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
   3276                     if (DEBUG_LAYOUT) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
   3277                     mDismissKeyguard = mWinDismissingKeyguard == win ?
   3278                             DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
   3279                     mWinDismissingKeyguard = win;
   3280                     mForceStatusBarFromKeyguard =
   3281                             mShowingLockscreen && mKeyguardMediator.isSecure();
   3282                 }
   3283                 if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
   3284                     mAllowLockscreenWhenOn = true;
   3285                 }
   3286             }
   3287         }
   3288     }
   3289 
   3290     /** {@inheritDoc} */
   3291     @Override
   3292     public int finishPostLayoutPolicyLw() {
   3293         int changes = 0;
   3294         boolean topIsFullscreen = false;
   3295 
   3296         final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
   3297                 ? mTopFullscreenOpaqueWindowState.getAttrs()
   3298                 : null;
   3299 
   3300         // If we are not currently showing a dream then remember the current
   3301         // lockscreen state.  We will use this to determine whether the dream
   3302         // started while the lockscreen was showing and remember this state
   3303         // while the dream is showing.
   3304         if (!mShowingDream) {
   3305             mDreamingLockscreen = mShowingLockscreen;
   3306         }
   3307 
   3308         if (mStatusBar != null) {
   3309             if (DEBUG_LAYOUT) Log.i(TAG, "force=" + mForceStatusBar
   3310                     + " forcefkg=" + mForceStatusBarFromKeyguard
   3311                     + " top=" + mTopFullscreenOpaqueWindowState);
   3312             if (mForceStatusBar || mForceStatusBarFromKeyguard) {
   3313                 if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar: forced");
   3314                 if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
   3315             } else if (mTopFullscreenOpaqueWindowState != null) {
   3316                 if (localLOGV) {
   3317                     Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
   3318                             + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
   3319                     Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
   3320                             + " lp.flags=0x" + Integer.toHexString(lp.flags));
   3321                 }
   3322                 topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
   3323                         || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
   3324                 // The subtle difference between the window for mTopFullscreenOpaqueWindowState
   3325                 // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
   3326                 // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
   3327                 // case though.
   3328                 if (topIsFullscreen) {
   3329                     if (DEBUG_LAYOUT) Log.v(TAG, "** HIDING status bar");
   3330                     if (mStatusBar.hideLw(true)) {
   3331                         changes |= FINISH_LAYOUT_REDO_LAYOUT;
   3332 
   3333                         mHandler.post(new Runnable() {
   3334                             @Override
   3335                             public void run() {
   3336                             try {
   3337                                 IStatusBarService statusbar = getStatusBarService();
   3338                                 if (statusbar != null) {
   3339                                     statusbar.collapsePanels();
   3340                                 }
   3341                             } catch (RemoteException ex) {
   3342                                 // re-acquire status bar service next time it is needed.
   3343                                 mStatusBarService = null;
   3344                             }
   3345                         }});
   3346                     } else if (DEBUG_LAYOUT) {
   3347                         Log.v(TAG, "Preventing status bar from hiding by policy");
   3348                     }
   3349                 } else {
   3350                     if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen");
   3351                     if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
   3352                 }
   3353             }
   3354         }
   3355 
   3356         mTopIsFullscreen = topIsFullscreen;
   3357 
   3358         // Hide the key guard if a visible window explicitly specifies that it wants to be
   3359         // displayed when the screen is locked.
   3360         if (mKeyguard != null) {
   3361             if (localLOGV) Log.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
   3362                     + mHideLockScreen);
   3363             if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardMediator.isSecure()) {
   3364                 if (mKeyguard.hideLw(true)) {
   3365                     changes |= FINISH_LAYOUT_REDO_LAYOUT
   3366                             | FINISH_LAYOUT_REDO_CONFIG
   3367                             | FINISH_LAYOUT_REDO_WALLPAPER;
   3368                 }
   3369                 if (mKeyguardMediator.isShowing()) {
   3370                     mHandler.post(new Runnable() {
   3371                         @Override
   3372                         public void run() {
   3373                             mKeyguardMediator.keyguardDone(false, false);
   3374                         }
   3375                     });
   3376                 }
   3377             } else if (mHideLockScreen) {
   3378                 if (mKeyguard.hideLw(true)) {
   3379                     changes |= FINISH_LAYOUT_REDO_LAYOUT
   3380                             | FINISH_LAYOUT_REDO_CONFIG
   3381                             | FINISH_LAYOUT_REDO_WALLPAPER;
   3382                 }
   3383                 mKeyguardMediator.setHidden(true);
   3384             } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
   3385                 // This is the case of keyguard isSecure() and not mHideLockScreen.
   3386                 if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
   3387                     // Only launch the next keyguard unlock window once per window.
   3388                     if (mKeyguard.showLw(true)) {
   3389                         changes |= FINISH_LAYOUT_REDO_LAYOUT
   3390                                 | FINISH_LAYOUT_REDO_CONFIG
   3391                                 | FINISH_LAYOUT_REDO_WALLPAPER;
   3392                     }
   3393                     mKeyguardMediator.setHidden(false);
   3394                     mHandler.post(new Runnable() {
   3395                         @Override
   3396                         public void run() {
   3397                             mKeyguardMediator.dismiss();
   3398                         }
   3399                     });
   3400                 }
   3401             } else {
   3402                 mWinDismissingKeyguard = null;
   3403                 if (mKeyguard.showLw(true)) {
   3404                     changes |= FINISH_LAYOUT_REDO_LAYOUT
   3405                             | FINISH_LAYOUT_REDO_CONFIG
   3406                             | FINISH_LAYOUT_REDO_WALLPAPER;
   3407                 }
   3408                 mKeyguardMediator.setHidden(false);
   3409             }
   3410         }
   3411 
   3412         if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
   3413             // If the navigation bar has been hidden or shown, we need to do another
   3414             // layout pass to update that window.
   3415             changes |= FINISH_LAYOUT_REDO_LAYOUT;
   3416         }
   3417 
   3418         // update since mAllowLockscreenWhenOn might have changed
   3419         updateLockScreenTimeout();
   3420         return changes;
   3421     }
   3422 
   3423     public boolean allowAppAnimationsLw() {
   3424         if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
   3425             // If keyguard is currently visible, no reason to animate
   3426             // behind it.
   3427             return false;
   3428         }
   3429         return true;
   3430     }
   3431 
   3432     public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
   3433         mFocusedWindow = newFocus;
   3434         if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
   3435             // If the navigation bar has been hidden or shown, we need to do another
   3436             // layout pass to update that window.
   3437             return FINISH_LAYOUT_REDO_LAYOUT;
   3438         }
   3439         return 0;
   3440     }
   3441 
   3442     /** {@inheritDoc} */
   3443     public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
   3444         // do nothing if headless
   3445         if (mHeadless) return;
   3446 
   3447         // lid changed state
   3448         final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
   3449         if (newLidState == mLidState) {
   3450             return;
   3451         }
   3452 
   3453         mLidState = newLidState;
   3454         applyLidSwitchState();
   3455         updateRotation(true);
   3456 
   3457         if (lidOpen) {
   3458             if (keyguardIsShowingTq()) {
   3459                 mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(KeyEvent.KEYCODE_POWER);
   3460             } else {
   3461                 mPowerManager.wakeUp(SystemClock.uptimeMillis());
   3462             }
   3463         } else if (!mLidControlsSleep) {
   3464             mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
   3465         }
   3466     }
   3467 
   3468     void setHdmiPlugged(boolean plugged) {
   3469         if (mHdmiPlugged != plugged) {
   3470             mHdmiPlugged = plugged;
   3471             updateRotation(true, true);
   3472             Intent intent = new Intent(ACTION_HDMI_PLUGGED);
   3473             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
   3474             intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
   3475             mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
   3476         }
   3477     }
   3478 
   3479     void initializeHdmiState() {
   3480         boolean plugged = false;
   3481         // watch for HDMI plug messages if the hdmi switch exists
   3482         if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
   3483             mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
   3484 
   3485             final String filename = "/sys/class/switch/hdmi/state";
   3486             FileReader reader = null;
   3487             try {
   3488                 reader = new FileReader(filename);
   3489                 char[] buf = new char[15];
   3490                 int n = reader.read(buf);
   3491                 if (n > 1) {
   3492                     plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
   3493                 }
   3494             } catch (IOException ex) {
   3495                 Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
   3496             } catch (NumberFormatException ex) {
   3497                 Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
   3498             } finally {
   3499                 if (reader != null) {
   3500                     try {
   3501                         reader.close();
   3502                     } catch (IOException ex) {
   3503                     }
   3504                 }
   3505             }
   3506         }
   3507         // This dance forces the code in setHdmiPlugged to run.
   3508         // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
   3509         mHdmiPlugged = !plugged;
   3510         setHdmiPlugged(!mHdmiPlugged);
   3511     }
   3512 
   3513     /**
   3514      * @return Whether music is being played right now.
   3515      */
   3516     boolean isMusicActive() {
   3517         final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
   3518         if (am == null) {
   3519             Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
   3520             return false;
   3521         }
   3522         return am.isMusicActive();
   3523     }
   3524 
   3525     /**
   3526      * Tell the audio service to adjust the volume appropriate to the event.
   3527      * @param keycode
   3528      */
   3529     void handleVolumeKey(int stream, int keycode) {
   3530         IAudioService audioService = getAudioService();
   3531         if (audioService == null) {
   3532             return;
   3533         }
   3534         try {
   3535             // since audio is playing, we shouldn't have to hold a wake lock
   3536             // during the call, but we do it as a precaution for the rare possibility
   3537             // that the music stops right before we call this
   3538             // TODO: Actually handle MUTE.
   3539             mBroadcastWakeLock.acquire();
   3540             audioService.adjustStreamVolume(stream,
   3541                 keycode == KeyEvent.KEYCODE_VOLUME_UP
   3542                             ? AudioManager.ADJUST_RAISE
   3543                             : AudioManager.ADJUST_LOWER,
   3544                     0);
   3545         } catch (RemoteException e) {
   3546             Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
   3547         } finally {
   3548             mBroadcastWakeLock.release();
   3549         }
   3550     }
   3551 
   3552     final Object mScreenshotLock = new Object();
   3553     ServiceConnection mScreenshotConnection = null;
   3554 
   3555     final Runnable mScreenshotTimeout = new Runnable() {
   3556         @Override public void run() {
   3557             synchronized (mScreenshotLock) {
   3558                 if (mScreenshotConnection != null) {
   3559                     mContext.unbindService(mScreenshotConnection);
   3560                     mScreenshotConnection = null;
   3561                 }
   3562             }
   3563         }
   3564     };
   3565 
   3566     // Assume this is called from the Handler thread.
   3567     private void takeScreenshot() {
   3568         synchronized (mScreenshotLock) {
   3569             if (mScreenshotConnection != null) {
   3570                 return;
   3571             }
   3572             ComponentName cn = new ComponentName("com.android.systemui",
   3573                     "com.android.systemui.screenshot.TakeScreenshotService");
   3574             Intent intent = new Intent();
   3575             intent.setComponent(cn);
   3576             ServiceConnection conn = new ServiceConnection() {
   3577                 @Override
   3578                 public void onServiceConnected(ComponentName name, IBinder service) {
   3579                     synchronized (mScreenshotLock) {
   3580                         if (mScreenshotConnection != this) {
   3581                             return;
   3582                         }
   3583                         Messenger messenger = new Messenger(service);
   3584                         Message msg = Message.obtain(null, 1);
   3585                         final ServiceConnection myConn = this;
   3586                         Handler h = new Handler(mHandler.getLooper()) {
   3587                             @Override
   3588                             public void handleMessage(Message msg) {
   3589                                 synchronized (mScreenshotLock) {
   3590                                     if (mScreenshotConnection == myConn) {
   3591                                         mContext.unbindService(mScreenshotConnection);
   3592                                         mScreenshotConnection = null;
   3593                                         mHandler.removeCallbacks(mScreenshotTimeout);
   3594                                     }
   3595                                 }
   3596                             }
   3597                         };
   3598                         msg.replyTo = new Messenger(h);
   3599                         msg.arg1 = msg.arg2 = 0;
   3600                         if (mStatusBar != null && mStatusBar.isVisibleLw())
   3601                             msg.arg1 = 1;
   3602                         if (mNavigationBar != null && mNavigationBar.isVisibleLw())
   3603                             msg.arg2 = 1;
   3604                         try {
   3605                             messenger.send(msg);
   3606                         } catch (RemoteException e) {
   3607                         }
   3608                     }
   3609                 }
   3610                 @Override
   3611                 public void onServiceDisconnected(ComponentName name) {}
   3612             };
   3613             if (mContext.bindServiceAsUser(
   3614                     intent, conn, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
   3615                 mScreenshotConnection = conn;
   3616                 mHandler.postDelayed(mScreenshotTimeout, 10000);
   3617             }
   3618         }
   3619     }
   3620 
   3621     /** {@inheritDoc} */
   3622     @Override
   3623     public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
   3624         if (!mSystemBooted) {
   3625             // If we have not yet booted, don't let key events do anything.
   3626             return 0;
   3627         }
   3628 
   3629         final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
   3630         final boolean canceled = event.isCanceled();
   3631         final int keyCode = event.getKeyCode();
   3632 
   3633         final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
   3634 
   3635         // If screen is off then we treat the case where the keyguard is open but hidden
   3636         // the same as if it were open and in front.
   3637         // This will prevent any keys other than the power button from waking the screen
   3638         // when the keyguard is hidden by another activity.
   3639         final boolean keyguardActive = (mKeyguardMediator == null ? false :
   3640                                             (isScreenOn ?
   3641                                                 mKeyguardMediator.isShowingAndNotHidden() :
   3642                                                 mKeyguardMediator.isShowing()));
   3643 
   3644         if (keyCode == KeyEvent.KEYCODE_POWER) {
   3645             policyFlags |= WindowManagerPolicy.FLAG_WAKE;
   3646         }
   3647         final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
   3648                 | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
   3649 
   3650         if (DEBUG_INPUT) {
   3651             Log.d(TAG, "interceptKeyTq keycode=" + keyCode
   3652                     + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive
   3653                     + " policyFlags=" + Integer.toHexString(policyFlags)
   3654                     + " isWakeKey=" + isWakeKey);
   3655         }
   3656 
   3657         if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
   3658                 && event.getRepeatCount() == 0) {
   3659             performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
   3660         }
   3661 
   3662         // Basic policy based on screen state and keyguard.
   3663         // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
   3664         //        is on or off, really.  We should care about whether the device is in an
   3665         //        interactive state or is in suspend pretending to be "off".
   3666         //        The primary screen might be turned off due to proximity sensor or
   3667         //        because we are presenting media on an auxiliary screen or remotely controlling
   3668         //        the device some other way (which is why we have an exemption here for injected
   3669         //        events).
   3670         int result;
   3671         if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) {
   3672             // When the screen is on or if the key is injected pass the key to the application.
   3673             result = ACTION_PASS_TO_USER;
   3674         } else {
   3675             // When the screen is off and the key is not injected, determine whether
   3676             // to wake the device but don't pass the key to the application.
   3677             result = 0;
   3678             if (down && isWakeKey && isWakeKeyWhenScreenOff(keyCode)) {
   3679                 if (keyguardActive) {
   3680                     // If the keyguard is showing, let it wake the device when ready.
   3681                     mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode);
   3682                 } else {
   3683                     // Otherwise, wake the device ourselves.
   3684                     result |= ACTION_WAKE_UP;
   3685                 }
   3686             }
   3687         }
   3688 
   3689         // If the key would be handled globally, just return the result, don't worry about special
   3690         // key processing.
   3691         if (mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
   3692             return result;
   3693         }
   3694 
   3695         // Handle special keys.
   3696         switch (keyCode) {
   3697             case KeyEvent.KEYCODE_VOLUME_DOWN:
   3698             case KeyEvent.KEYCODE_VOLUME_UP:
   3699             case KeyEvent.KEYCODE_VOLUME_MUTE: {
   3700                 if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
   3701                     if (down) {
   3702                         if (isScreenOn && !mVolumeDownKeyTriggered
   3703                                 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
   3704                             mVolumeDownKeyTriggered = true;
   3705                             mVolumeDownKeyTime = event.getDownTime();
   3706                             mVolumeDownKeyConsumedByScreenshotChord = false;
   3707                             cancelPendingPowerKeyAction();
   3708                             interceptScreenshotChord();
   3709                         }
   3710                     } else {
   3711                         mVolumeDownKeyTriggered = false;
   3712                         cancelPendingScreenshotChordAction();
   3713                     }
   3714                 } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
   3715                     if (down) {
   3716                         if (isScreenOn && !mVolumeUpKeyTriggered
   3717                                 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
   3718                             mVolumeUpKeyTriggered = true;
   3719                             cancelPendingPowerKeyAction();
   3720                             cancelPendingScreenshotChordAction();
   3721                         }
   3722                     } else {
   3723                         mVolumeUpKeyTriggered = false;
   3724                         cancelPendingScreenshotChordAction();
   3725                     }
   3726                 }
   3727                 if (down) {
   3728                     ITelephony telephonyService = getTelephonyService();
   3729                     if (telephonyService != null) {
   3730                         try {
   3731                             if (telephonyService.isRinging()) {
   3732                                 // If an incoming call is ringing, either VOLUME key means
   3733                                 // "silence ringer".  We handle these keys here, rather than
   3734                                 // in the InCallScreen, to make sure we'll respond to them
   3735                                 // even if the InCallScreen hasn't come to the foreground yet.
   3736                                 // Look for the DOWN event here, to agree with the "fallback"
   3737                                 // behavior in the InCallScreen.
   3738                                 Log.i(TAG, "interceptKeyBeforeQueueing:"
   3739                                       + " VOLUME key-down while ringing: Silence ringer!");
   3740 
   3741                                 // Silence the ringer.  (It's safe to call this
   3742                                 // even if the ringer has already been silenced.)
   3743                                 telephonyService.silenceRinger();
   3744 
   3745                                 // And *don't* pass this key thru to the current activity
   3746                                 // (which is probably the InCallScreen.)
   3747                                 result &= ~ACTION_PASS_TO_USER;
   3748                                 break;
   3749                             }
   3750                             if (telephonyService.isOffhook()
   3751                                     && (result & ACTION_PASS_TO_USER) == 0) {
   3752                                 // If we are in call but we decided not to pass the key to
   3753                                 // the application, handle the volume change here.
   3754                                 handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
   3755                                 break;
   3756                             }
   3757                         } catch (RemoteException ex) {
   3758                             Log.w(TAG, "ITelephony threw RemoteException", ex);
   3759                         }
   3760                     }
   3761 
   3762                     if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
   3763                         // If music is playing but we decided not to pass the key to the
   3764                         // application, handle the volume change here.
   3765                         handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
   3766                         break;
   3767                     }
   3768                 }
   3769                 break;
   3770             }
   3771 
   3772             case KeyEvent.KEYCODE_ENDCALL: {
   3773                 result &= ~ACTION_PASS_TO_USER;
   3774                 if (down) {
   3775                     ITelephony telephonyService = getTelephonyService();
   3776                     boolean hungUp = false;
   3777                     if (telephonyService != null) {
   3778                         try {
   3779                             hungUp = telephonyService.endCall();
   3780                         } catch (RemoteException ex) {
   3781                             Log.w(TAG, "ITelephony threw RemoteException", ex);
   3782                         }
   3783                     }
   3784                     interceptPowerKeyDown(!isScreenOn || hungUp);
   3785                 } else {
   3786                     if (interceptPowerKeyUp(canceled)) {
   3787                         if ((mEndcallBehavior
   3788                                 & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
   3789                             if (goHome()) {
   3790                                 break;
   3791                             }
   3792                         }
   3793                         if ((mEndcallBehavior
   3794                                 & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
   3795                             result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
   3796                         }
   3797                     }
   3798                 }
   3799                 break;
   3800             }
   3801 
   3802             case KeyEvent.KEYCODE_POWER: {
   3803                 result &= ~ACTION_PASS_TO_USER;
   3804                 if (down) {
   3805                     if (isScreenOn && !mPowerKeyTriggered
   3806                             && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
   3807                         mPowerKeyTriggered = true;
   3808                         mPowerKeyTime = event.getDownTime();
   3809                         interceptScreenshotChord();
   3810                     }
   3811 
   3812                     ITelephony telephonyService = getTelephonyService();
   3813                     boolean hungUp = false;
   3814                     if (telephonyService != null) {
   3815                         try {
   3816                             if (telephonyService.isRinging()) {
   3817                                 // Pressing Power while there's a ringing incoming
   3818                                 // call should silence the ringer.
   3819                                 telephonyService.silenceRinger();
   3820                             } else if ((mIncallPowerBehavior
   3821                                     & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
   3822                                     && telephonyService.isOffhook()) {
   3823                                 // Otherwise, if "Power button ends call" is enabled,
   3824                                 // the Power button will hang up any current active call.
   3825                                 hungUp = telephonyService.endCall();
   3826                             }
   3827                         } catch (RemoteException ex) {
   3828                             Log.w(TAG, "ITelephony threw RemoteException", ex);
   3829                         }
   3830                     }
   3831                     interceptPowerKeyDown(!isScreenOn || hungUp
   3832                             || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
   3833                 } else {
   3834                     mPowerKeyTriggered = false;
   3835                     cancelPendingScreenshotChordAction();
   3836                     if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
   3837                         result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
   3838                     }
   3839                     mPendingPowerKeyUpCanceled = false;
   3840                 }
   3841                 break;
   3842             }
   3843 
   3844             case KeyEvent.KEYCODE_MEDIA_PLAY:
   3845             case KeyEvent.KEYCODE_MEDIA_PAUSE:
   3846             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
   3847                 if (down) {
   3848                     ITelephony telephonyService = getTelephonyService();
   3849                     if (telephonyService != null) {
   3850                         try {
   3851                             if (!telephonyService.isIdle()) {
   3852                                 // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
   3853                                 // to avoid music playback.
   3854                                 break;
   3855                             }
   3856                         } catch (RemoteException ex) {
   3857                             Log.w(TAG, "ITelephony threw RemoteException", ex);
   3858                         }
   3859                     }
   3860                 }
   3861             case KeyEvent.KEYCODE_HEADSETHOOK:
   3862             case KeyEvent.KEYCODE_MUTE:
   3863             case KeyEvent.KEYCODE_MEDIA_STOP:
   3864             case KeyEvent.KEYCODE_MEDIA_NEXT:
   3865             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
   3866             case KeyEvent.KEYCODE_MEDIA_REWIND:
   3867             case KeyEvent.KEYCODE_MEDIA_RECORD:
   3868             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
   3869                 if ((result & ACTION_PASS_TO_USER) == 0) {
   3870                     // Only do this if we would otherwise not pass it to the user. In that
   3871                     // case, the PhoneWindow class will do the same thing, except it will
   3872                     // only do it if the showing app doesn't process the key on its own.
   3873                     // Note that we need to make a copy of the key event here because the
   3874                     // original key event will be recycled when we return.
   3875                     mBroadcastWakeLock.acquire();
   3876                     Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
   3877                             new KeyEvent(event));
   3878                     msg.setAsynchronous(true);
   3879                     msg.sendToTarget();
   3880                 }
   3881                 break;
   3882             }
   3883 
   3884             case KeyEvent.KEYCODE_CALL: {
   3885                 if (down) {
   3886                     ITelephony telephonyService = getTelephonyService();
   3887                     if (telephonyService != null) {
   3888                         try {
   3889                             if (telephonyService.isRinging()) {
   3890                                 Log.i(TAG, "interceptKeyBeforeQueueing:"
   3891                                       + " CALL key-down while ringing: Answer the call!");
   3892                                 telephonyService.answerRingingCall();
   3893 
   3894                                 // And *don't* pass this key thru to the current activity
   3895                                 // (which is presumably the InCallScreen.)
   3896                                 result &= ~ACTION_PASS_TO_USER;
   3897                             }
   3898                         } catch (RemoteException ex) {
   3899                             Log.w(TAG, "ITelephony threw RemoteException", ex);
   3900                         }
   3901                     }
   3902                 }
   3903                 break;
   3904             }
   3905         }
   3906         return result;
   3907     }
   3908 
   3909     /**
   3910      * When the screen is off we ignore some keys that might otherwise typically
   3911      * be considered wake keys.  We filter them out here.
   3912      *
   3913      * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
   3914      * is always considered a wake key.
   3915      */
   3916     private boolean isWakeKeyWhenScreenOff(int keyCode) {
   3917         switch (keyCode) {
   3918             // ignore volume keys unless docked
   3919             case KeyEvent.KEYCODE_VOLUME_UP:
   3920             case KeyEvent.KEYCODE_VOLUME_DOWN:
   3921             case KeyEvent.KEYCODE_VOLUME_MUTE:
   3922                 return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
   3923 
   3924             // ignore media and camera keys
   3925             case KeyEvent.KEYCODE_MUTE:
   3926             case KeyEvent.KEYCODE_HEADSETHOOK:
   3927             case KeyEvent.KEYCODE_MEDIA_PLAY:
   3928             case KeyEvent.KEYCODE_MEDIA_PAUSE:
   3929             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
   3930             case KeyEvent.KEYCODE_MEDIA_STOP:
   3931             case KeyEvent.KEYCODE_MEDIA_NEXT:
   3932             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
   3933             case KeyEvent.KEYCODE_MEDIA_REWIND:
   3934             case KeyEvent.KEYCODE_MEDIA_RECORD:
   3935             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
   3936             case KeyEvent.KEYCODE_CAMERA:
   3937                 return false;
   3938         }
   3939         return true;
   3940     }
   3941 
   3942 
   3943     /** {@inheritDoc} */
   3944     @Override
   3945     public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
   3946         int result = 0;
   3947 
   3948         final boolean isWakeMotion = (policyFlags
   3949                 & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
   3950         if (isWakeMotion) {
   3951             if (mKeyguardMediator != null && mKeyguardMediator.isShowing()) {
   3952                 // If the keyguard is showing, let it decide what to do with the wake motion.
   3953                 mKeyguardMediator.onWakeMotionWhenKeyguardShowingTq();
   3954             } else {
   3955                 // Otherwise, wake the device ourselves.
   3956                 result |= ACTION_WAKE_UP;
   3957             }
   3958         }
   3959         return result;
   3960     }
   3961 
   3962     void dispatchMediaKeyWithWakeLock(KeyEvent event) {
   3963         if (DEBUG_INPUT) {
   3964             Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
   3965         }
   3966 
   3967         if (mHavePendingMediaKeyRepeatWithWakeLock) {
   3968             if (DEBUG_INPUT) {
   3969                 Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
   3970             }
   3971 
   3972             mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
   3973             mHavePendingMediaKeyRepeatWithWakeLock = false;
   3974             mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
   3975         }
   3976 
   3977         dispatchMediaKeyWithWakeLockToAudioService(event);
   3978 
   3979         if (event.getAction() == KeyEvent.ACTION_DOWN
   3980                 && event.getRepeatCount() == 0) {
   3981             mHavePendingMediaKeyRepeatWithWakeLock = true;
   3982 
   3983             Message msg = mHandler.obtainMessage(
   3984                     MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
   3985             msg.setAsynchronous(true);
   3986             mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
   3987         } else {
   3988             mBroadcastWakeLock.release();
   3989         }
   3990     }
   3991 
   3992     void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
   3993         mHavePendingMediaKeyRepeatWithWakeLock = false;
   3994 
   3995         KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
   3996                 SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
   3997         if (DEBUG_INPUT) {
   3998             Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
   3999         }
   4000 
   4001         dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
   4002         mBroadcastWakeLock.release();
   4003     }
   4004 
   4005     void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
   4006         if (ActivityManagerNative.isSystemReady()) {
   4007             IAudioService audioService = getAudioService();
   4008             if (audioService != null) {
   4009                 try {
   4010                     audioService.dispatchMediaKeyEventUnderWakelock(event);
   4011                 } catch (RemoteException e) {
   4012                     Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
   4013                 }
   4014             }
   4015         }
   4016     }
   4017 
   4018     BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
   4019         @Override
   4020         public void onReceive(Context context, Intent intent) {
   4021             if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
   4022                 mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
   4023                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
   4024             } else {
   4025                 try {
   4026                     IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
   4027                             ServiceManager.getService(Context.UI_MODE_SERVICE));
   4028                     mUiMode = uiModeService.getCurrentModeType();
   4029                 } catch (RemoteException e) {
   4030                 }
   4031             }
   4032             updateRotation(true);
   4033             synchronized (mLock) {
   4034                 updateOrientationListenerLp();
   4035             }
   4036         }
   4037     };
   4038 
   4039     BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
   4040         @Override
   4041         public void onReceive(Context context, Intent intent) {
   4042             if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
   4043                 if (mKeyguardMediator != null) {
   4044                     mKeyguardMediator.onDreamingStarted();
   4045                 }
   4046             } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
   4047                 if (mKeyguardMediator != null) {
   4048                     mKeyguardMediator.onDreamingStopped();
   4049                 }
   4050             }
   4051         }
   4052     };
   4053 
   4054     BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
   4055         @Override
   4056         public void onReceive(Context context, Intent intent) {
   4057             if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
   4058                 // tickle the settings observer: this first ensures that we're
   4059                 // observing the relevant settings for the newly-active user,
   4060                 // and then updates our own bookkeeping based on the now-
   4061                 // current user.
   4062                 mSettingsObserver.onChange(false);
   4063 
   4064                 // force a re-application of focused window sysui visibility.
   4065                 // the window may never have been shown for this user
   4066                 // e.g. the keyguard when going through the new-user setup flow
   4067                 synchronized(mLock) {
   4068                     mLastSystemUiFlags = 0;
   4069                     updateSystemUiVisibilityLw();
   4070                 }
   4071             }
   4072         }
   4073     };
   4074 
   4075     @Override
   4076     public void screenTurnedOff(int why) {
   4077         EventLog.writeEvent(70000, 0);
   4078         synchronized (mLock) {
   4079             mScreenOnEarly = false;
   4080             mScreenOnFully = false;
   4081         }
   4082         if (mKeyguardMediator != null) {
   4083             mKeyguardMediator.onScreenTurnedOff(why);
   4084         }
   4085         synchronized (mLock) {
   4086             updateOrientationListenerLp();
   4087             updateLockScreenTimeout();
   4088         }
   4089     }
   4090 
   4091     @Override
   4092     public void screenTurningOn(final ScreenOnListener screenOnListener) {
   4093         EventLog.writeEvent(70000, 1);
   4094         if (false) {
   4095             RuntimeException here = new RuntimeException("here");
   4096             here.fillInStackTrace();
   4097             Slog.i(TAG, "Screen turning on...", here);
   4098         }
   4099 
   4100         synchronized (mLock) {
   4101             mScreenOnEarly = true;
   4102             updateOrientationListenerLp();
   4103             updateLockScreenTimeout();
   4104         }
   4105 
   4106         waitForKeyguard(screenOnListener);
   4107     }
   4108 
   4109     private void waitForKeyguard(final ScreenOnListener screenOnListener) {
   4110         if (mKeyguardMediator != null) {
   4111             if (screenOnListener != null) {
   4112                 mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
   4113                     @Override
   4114                     public void onShown(IBinder windowToken) {
   4115                         waitForKeyguardWindowDrawn(windowToken, screenOnListener);
   4116                     }
   4117                 });
   4118                 return;
   4119             } else {
   4120                 mKeyguardMediator.onScreenTurnedOn(null);
   4121             }
   4122         } else {
   4123             Slog.i(TAG, "No keyguard mediator!");
   4124         }
   4125         finishScreenTurningOn(screenOnListener);
   4126     }
   4127 
   4128     private void waitForKeyguardWindowDrawn(IBinder windowToken,
   4129             final ScreenOnListener screenOnListener) {
   4130         if (windowToken != null) {
   4131             try {
   4132                 if (mWindowManager.waitForWindowDrawn(
   4133                         windowToken, new IRemoteCallback.Stub() {
   4134                     @Override
   4135                     public void sendResult(Bundle data) {
   4136                         Slog.i(TAG, "Lock screen displayed!");
   4137                         finishScreenTurningOn(screenOnListener);
   4138                     }
   4139                 })) {
   4140                     return;
   4141                 }
   4142             } catch (RemoteException ex) {
   4143                 // Can't happen in system process.
   4144             }
   4145         }
   4146 
   4147         Slog.i(TAG, "No lock screen!");
   4148         finishScreenTurningOn(screenOnListener);
   4149     }
   4150 
   4151     private void finishScreenTurningOn(ScreenOnListener screenOnListener) {
   4152         synchronized (mLock) {
   4153             mScreenOnFully = true;
   4154         }
   4155 
   4156         try {
   4157             mWindowManager.setEventDispatching(true);
   4158         } catch (RemoteException unhandled) {
   4159         }
   4160 
   4161         if (screenOnListener != null) {
   4162             screenOnListener.onScreenOn();
   4163         }
   4164     }
   4165 
   4166     @Override
   4167     public boolean isScreenOnEarly() {
   4168         return mScreenOnEarly;
   4169     }
   4170 
   4171     @Override
   4172     public boolean isScreenOnFully() {
   4173         return mScreenOnFully;
   4174     }
   4175 
   4176     /** {@inheritDoc} */
   4177     public void enableKeyguard(boolean enabled) {
   4178         if (mKeyguardMediator != null) {
   4179             mKeyguardMediator.setKeyguardEnabled(enabled);
   4180         }
   4181     }
   4182 
   4183     /** {@inheritDoc} */
   4184     public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
   4185         if (mKeyguardMediator != null) {
   4186             mKeyguardMediator.verifyUnlock(callback);
   4187         }
   4188     }
   4189 
   4190     private boolean keyguardIsShowingTq() {
   4191         if (mKeyguardMediator == null) return false;
   4192         return mKeyguardMediator.isShowingAndNotHidden();
   4193     }
   4194 
   4195 
   4196     /** {@inheritDoc} */
   4197     public boolean isKeyguardLocked() {
   4198         return keyguardOn();
   4199     }
   4200 
   4201     /** {@inheritDoc} */
   4202     public boolean isKeyguardSecure() {
   4203         if (mKeyguardMediator == null) return false;
   4204         return mKeyguardMediator.isSecure();
   4205     }
   4206 
   4207     /** {@inheritDoc} */
   4208     public boolean inKeyguardRestrictedKeyInputMode() {
   4209         if (mKeyguardMediator == null) return false;
   4210         return mKeyguardMediator.isInputRestricted();
   4211     }
   4212 
   4213     public void dismissKeyguardLw() {
   4214         if (mKeyguardMediator.isShowing()) {
   4215             mHandler.post(new Runnable() {
   4216                 public void run() {
   4217                     if (mKeyguardMediator.isDismissable()) {
   4218                         // Can we just finish the keyguard straight away?
   4219                         mKeyguardMediator.keyguardDone(false, true);
   4220                     } else {
   4221                         // ask the keyguard to prompt the user to authenticate if necessary
   4222                         mKeyguardMediator.dismiss();
   4223                     }
   4224                 }
   4225             });
   4226         }
   4227     }
   4228 
   4229     void sendCloseSystemWindows() {
   4230         sendCloseSystemWindows(mContext, null);
   4231     }
   4232 
   4233     void sendCloseSystemWindows(String reason) {
   4234         sendCloseSystemWindows(mContext, reason);
   4235     }
   4236 
   4237     static void sendCloseSystemWindows(Context context, String reason) {
   4238         if (ActivityManagerNative.isSystemReady()) {
   4239             try {
   4240                 ActivityManagerNative.getDefault().closeSystemDialogs(reason);
   4241             } catch (RemoteException e) {
   4242             }
   4243         }
   4244     }
   4245 
   4246     @Override
   4247     public int rotationForOrientationLw(int orientation, int lastRotation) {
   4248         if (false) {
   4249             Slog.v(TAG, "rotationForOrientationLw(orient="
   4250                         + orientation + ", last=" + lastRotation
   4251                         + "); user=" + mUserRotation + " "
   4252                         + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
   4253                             ? "USER_ROTATION_LOCKED" : "")
   4254                         );
   4255         }
   4256 
   4257         synchronized (mLock) {
   4258             int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
   4259             if (sensorRotation < 0) {
   4260                 sensorRotation = lastRotation;
   4261             }
   4262 
   4263             final int preferredRotation;
   4264             if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
   4265                 // Ignore sensor when lid switch is open and rotation is forced.
   4266                 preferredRotation = mLidOpenRotation;
   4267             } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
   4268                     && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
   4269                 // Ignore sensor when in car dock unless explicitly enabled.
   4270                 // This case can override the behavior of NOSENSOR, and can also
   4271                 // enable 180 degree rotation while docked.
   4272                 preferredRotation = mCarDockEnablesAccelerometer
   4273                         ? sensorRotation : mCarDockRotation;
   4274             } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
   4275                     || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
   4276                     || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
   4277                     && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
   4278                 // Ignore sensor when in desk dock unless explicitly enabled.
   4279                 // This case can override the behavior of NOSENSOR, and can also
   4280                 // enable 180 degree rotation while docked.
   4281                 preferredRotation = mDeskDockEnablesAccelerometer
   4282                         ? sensorRotation : mDeskDockRotation;
   4283             } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
   4284                 // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
   4285                 // Note that the dock orientation overrides the HDMI orientation.
   4286                 preferredRotation = mDemoHdmiRotation;
   4287             } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
   4288                     && mUndockedHdmiRotation >= 0) {
   4289                 // Ignore sensor when plugged into HDMI and an undocked orientation has
   4290                 // been specified in the configuration (only for legacy devices without
   4291                 // full multi-display support).
   4292                 // Note that the dock orientation overrides the HDMI orientation.
   4293                 preferredRotation = mUndockedHdmiRotation;
   4294             } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
   4295                 // Application just wants to remain locked in the last rotation.
   4296                 preferredRotation = lastRotation;
   4297             } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
   4298                             && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
   4299                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
   4300                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
   4301                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
   4302                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
   4303                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
   4304                     || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
   4305                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
   4306                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
   4307                 // Otherwise, use sensor only if requested by the application or enabled
   4308                 // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
   4309                 if (mAllowAllRotations < 0) {
   4310                     // Can't read this during init() because the context doesn't
   4311                     // have display metrics at that time so we cannot determine
   4312                     // tablet vs. phone then.
   4313                     mAllowAllRotations = mContext.getResources().getBoolean(
   4314                             com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
   4315                 }
   4316                 if (sensorRotation != Surface.ROTATION_180
   4317                         || mAllowAllRotations == 1
   4318                         || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
   4319                         || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
   4320                     preferredRotation = sensorRotation;
   4321                 } else {
   4322                     preferredRotation = lastRotation;
   4323                 }
   4324             } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
   4325                     && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
   4326                 // Apply rotation lock.  Does not apply to NOSENSOR.
   4327                 // The idea is that the user rotation expresses a weak preference for the direction
   4328                 // of gravity and as NOSENSOR is never affected by gravity, then neither should
   4329                 // NOSENSOR be affected by rotation lock (although it will be affected by docks).
   4330                 preferredRotation = mUserRotation;
   4331             } else {
   4332                 // No overriding preference.
   4333                 // We will do exactly what the application asked us to do.
   4334                 preferredRotation = -1;
   4335             }
   4336 
   4337             switch (orientation) {
   4338                 case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
   4339                     // Return portrait unless overridden.
   4340                     if (isAnyPortrait(preferredRotation)) {
   4341                         return preferredRotation;
   4342                     }
   4343                     return mPortraitRotation;
   4344 
   4345                 case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
   4346                     // Return landscape unless overridden.
   4347                     if (isLandscapeOrSeascape(preferredRotation)) {
   4348                         return preferredRotation;
   4349                     }
   4350                     return mLandscapeRotation;
   4351 
   4352                 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
   4353                     // Return reverse portrait unless overridden.
   4354                     if (isAnyPortrait(preferredRotation)) {
   4355                         return preferredRotation;
   4356                     }
   4357                     return mUpsideDownRotation;
   4358 
   4359                 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
   4360                     // Return seascape unless overridden.
   4361                     if (isLandscapeOrSeascape(preferredRotation)) {
   4362                         return preferredRotation;
   4363                     }
   4364                     return mSeascapeRotation;
   4365 
   4366                 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
   4367                 case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
   4368                     // Return either landscape rotation.
   4369                     if (isLandscapeOrSeascape(preferredRotation)) {
   4370                         return preferredRotation;
   4371                     }
   4372                     if (isLandscapeOrSeascape(lastRotation)) {
   4373                         return lastRotation;
   4374                     }
   4375                     return mLandscapeRotation;
   4376 
   4377                 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
   4378                 case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
   4379                     // Return either portrait rotation.
   4380                     if (isAnyPortrait(preferredRotation)) {
   4381                         return preferredRotation;
   4382                     }
   4383                     if (isAnyPortrait(lastRotation)) {
   4384                         return lastRotation;
   4385                     }
   4386                     return mPortraitRotation;
   4387 
   4388                 default:
   4389                     // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
   4390                     // just return the preferred orientation we already calculated.
   4391                     if (preferredRotation >= 0) {
   4392                         return preferredRotation;
   4393                     }
   4394                     return Surface.ROTATION_0;
   4395             }
   4396         }
   4397     }
   4398 
   4399     @Override
   4400     public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
   4401         switch (orientation) {
   4402             case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
   4403             case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
   4404             case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
   4405                 return isAnyPortrait(rotation);
   4406 
   4407             case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
   4408             case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
   4409             case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
   4410                 return isLandscapeOrSeascape(rotation);
   4411 
   4412             default:
   4413                 return true;
   4414         }
   4415     }
   4416 
   4417     @Override
   4418     public void setRotationLw(int rotation) {
   4419         mOrientationListener.setCurrentRotation(rotation);
   4420     }
   4421 
   4422     private boolean isLandscapeOrSeascape(int rotation) {
   4423         return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
   4424     }
   4425 
   4426     private boolean isAnyPortrait(int rotation) {
   4427         return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
   4428     }
   4429 
   4430     public int getUserRotationMode() {
   4431         return Settings.System.getIntForUser(mContext.getContentResolver(),
   4432                 Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
   4433                         WindowManagerPolicy.USER_ROTATION_FREE :
   4434                                 WindowManagerPolicy.USER_ROTATION_LOCKED;
   4435     }
   4436 
   4437     // User rotation: to be used when all else fails in assigning an orientation to the device
   4438     public void setUserRotationMode(int mode, int rot) {
   4439         ContentResolver res = mContext.getContentResolver();
   4440 
   4441         // mUserRotationMode and mUserRotation will be assigned by the content observer
   4442         if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
   4443             Settings.System.putIntForUser(res,
   4444                     Settings.System.USER_ROTATION,
   4445                     rot,
   4446                     UserHandle.USER_CURRENT);
   4447             Settings.System.putIntForUser(res,
   4448                     Settings.System.ACCELEROMETER_ROTATION,
   4449                     0,
   4450                     UserHandle.USER_CURRENT);
   4451         } else {
   4452             Settings.System.putIntForUser(res,
   4453                     Settings.System.ACCELEROMETER_ROTATION,
   4454                     1,
   4455                     UserHandle.USER_CURRENT);
   4456         }
   4457     }
   4458 
   4459     public void setSafeMode(boolean safeMode) {
   4460         mSafeMode = safeMode;
   4461         performHapticFeedbackLw(null, safeMode
   4462                 ? HapticFeedbackConstants.SAFE_MODE_ENABLED
   4463                 : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
   4464     }
   4465 
   4466     static long[] getLongIntArray(Resources r, int resid) {
   4467         int[] ar = r.getIntArray(resid);
   4468         if (ar == null) {
   4469             return null;
   4470         }
   4471         long[] out = new long[ar.length];
   4472         for (int i=0; i<ar.length; i++) {
   4473             out[i] = ar[i];
   4474         }
   4475         return out;
   4476     }
   4477 
   4478     /** {@inheritDoc} */
   4479     public void systemReady() {
   4480         if (mKeyguardMediator != null) {
   4481             // tell the keyguard
   4482             mKeyguardMediator.onSystemReady();
   4483         }
   4484         synchronized (mLock) {
   4485             updateOrientationListenerLp();
   4486             mSystemReady = true;
   4487             mHandler.post(new Runnable() {
   4488                 public void run() {
   4489                     updateSettings();
   4490                 }
   4491             });
   4492         }
   4493     }
   4494 
   4495     /** {@inheritDoc} */
   4496     public void systemBooted() {
   4497         synchronized (mLock) {
   4498             mSystemBooted = true;
   4499         }
   4500     }
   4501 
   4502     ProgressDialog mBootMsgDialog = null;
   4503 
   4504     /** {@inheritDoc} */
   4505     public void showBootMessage(final CharSequence msg, final boolean always) {
   4506         if (mHeadless) return;
   4507         mHandler.post(new Runnable() {
   4508             @Override public void run() {
   4509                 if (mBootMsgDialog == null) {
   4510                     mBootMsgDialog = new ProgressDialog(mContext) {
   4511                         // This dialog will consume all events coming in to
   4512                         // it, to avoid it trying to do things too early in boot.
   4513                         @Override public boolean dispatchKeyEvent(KeyEvent event) {
   4514                             return true;
   4515                         }
   4516                         @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
   4517                             return true;
   4518                         }
   4519                         @Override public boolean dispatchTouchEvent(MotionEvent ev) {
   4520                             return true;
   4521                         }
   4522                         @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
   4523                             return true;
   4524                         }
   4525                         @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
   4526                             return true;
   4527                         }
   4528                         @Override public boolean dispatchPopulateAccessibilityEvent(
   4529                                 AccessibilityEvent event) {
   4530                             return true;
   4531                         }
   4532                     };
   4533                     mBootMsgDialog.setTitle(R.string.android_upgrading_title);
   4534                     mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
   4535                     mBootMsgDialog.setIndeterminate(true);
   4536                     mBootMsgDialog.getWindow().setType(
   4537                             WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
   4538                     mBootMsgDialog.getWindow().addFlags(
   4539                             WindowManager.LayoutParams.FLAG_DIM_BEHIND
   4540                             | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
   4541                     mBootMsgDialog.getWindow().setDimAmount(1);
   4542                     WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
   4543                     lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
   4544                     mBootMsgDialog.getWindow().setAttributes(lp);
   4545                     mBootMsgDialog.setCancelable(false);
   4546                     mBootMsgDialog.show();
   4547                 }
   4548                 mBootMsgDialog.setMessage(msg);
   4549             }
   4550         });
   4551     }
   4552 
   4553     /** {@inheritDoc} */
   4554     public void hideBootMessages() {
   4555         mHandler.post(new Runnable() {
   4556             @Override public void run() {
   4557                 if (mBootMsgDialog != null) {
   4558                     mBootMsgDialog.dismiss();
   4559                     mBootMsgDialog = null;
   4560                 }
   4561             }
   4562         });
   4563     }
   4564 
   4565     /** {@inheritDoc} */
   4566     public void userActivity() {
   4567         // ***************************************
   4568         // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
   4569         // ***************************************
   4570         // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
   4571         // WITH ITS LOCKS HELD.
   4572         //
   4573         // This code must be VERY careful about the locks
   4574         // it acquires.
   4575         // In fact, the current code acquires way too many,
   4576         // and probably has lurking deadlocks.
   4577 
   4578         synchronized (mScreenLockTimeout) {
   4579             if (mLockScreenTimerActive) {
   4580                 // reset the timer
   4581                 mHandler.removeCallbacks(mScreenLockTimeout);
   4582                 mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
   4583             }
   4584         }
   4585     }
   4586 
   4587     class ScreenLockTimeout implements Runnable {
   4588         Bundle options;
   4589 
   4590         @Override
   4591         public void run() {
   4592             synchronized (this) {
   4593                 if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
   4594                 if (mKeyguardMediator != null) {
   4595                     mKeyguardMediator.doKeyguardTimeout(options);
   4596                 }
   4597                 mLockScreenTimerActive = false;
   4598                 options = null;
   4599             }
   4600         }
   4601 
   4602         public void setLockOptions(Bundle options) {
   4603             this.options = options;
   4604         }
   4605     }
   4606 
   4607     ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
   4608 
   4609     public void lockNow(Bundle options) {
   4610         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   4611         mHandler.removeCallbacks(mScreenLockTimeout);
   4612         if (options != null) {
   4613             // In case multiple calls are made to lockNow, we don't wipe out the options
   4614             // until the runnable actually executes.
   4615             mScreenLockTimeout.setLockOptions(options);
   4616         }
   4617         mHandler.post(mScreenLockTimeout);
   4618     }
   4619 
   4620     private void updateLockScreenTimeout() {
   4621         synchronized (mScreenLockTimeout) {
   4622             boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
   4623                     mKeyguardMediator != null && mKeyguardMediator.isSecure());
   4624             if (mLockScreenTimerActive != enable) {
   4625                 if (enable) {
   4626                     if (localLOGV) Log.v(TAG, "setting lockscreen timer");
   4627                     mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
   4628                 } else {
   4629                     if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
   4630                     mHandler.removeCallbacks(mScreenLockTimeout);
   4631                 }
   4632                 mLockScreenTimerActive = enable;
   4633             }
   4634         }
   4635     }
   4636 
   4637     /** {@inheritDoc} */
   4638     public void enableScreenAfterBoot() {
   4639         readLidState();
   4640         applyLidSwitchState();
   4641         updateRotation(true);
   4642     }
   4643 
   4644     private void applyLidSwitchState() {
   4645         if (mLidState == LID_CLOSED && mLidControlsSleep) {
   4646             mPowerManager.goToSleep(SystemClock.uptimeMillis());
   4647         }
   4648     }
   4649 
   4650     void updateRotation(boolean alwaysSendConfiguration) {
   4651         try {
   4652             //set orientation on WindowManager
   4653             mWindowManager.updateRotation(alwaysSendConfiguration, false);
   4654         } catch (RemoteException e) {
   4655             // Ignore
   4656         }
   4657     }
   4658 
   4659     void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
   4660         try {
   4661             //set orientation on WindowManager
   4662             mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
   4663         } catch (RemoteException e) {
   4664             // Ignore
   4665         }
   4666     }
   4667 
   4668     /**
   4669      * Return an Intent to launch the currently active dock app as home.  Returns
   4670      * null if the standard home should be launched, which is the case if any of the following is
   4671      * true:
   4672      * <ul>
   4673      *  <li>The device is not in either car mode or desk mode
   4674      *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
   4675      *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
   4676      *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
   4677      *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
   4678      * </ul>
   4679      * @return
   4680      */
   4681     Intent createHomeDockIntent() {
   4682         Intent intent = null;
   4683 
   4684         // What home does is based on the mode, not the dock state.  That
   4685         // is, when in car mode you should be taken to car home regardless
   4686         // of whether we are actually in a car dock.
   4687         if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
   4688             if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
   4689                 intent = mCarDockIntent;
   4690             }
   4691         } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
   4692             if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
   4693                 intent = mDeskDockIntent;
   4694             }
   4695         }
   4696 
   4697         if (intent == null) {
   4698             return null;
   4699         }
   4700 
   4701         ActivityInfo ai = null;
   4702         ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
   4703                 intent,
   4704                 PackageManager.MATCH_DEFAULT_ONLY,
   4705                 UserHandle.USER_CURRENT);
   4706         if (info != null) {
   4707             ai = info.activityInfo;
   4708         }
   4709         if (ai != null
   4710                 && ai.metaData != null
   4711                 && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
   4712             intent = new Intent(intent);
   4713             intent.setClassName(ai.packageName, ai.name);
   4714             return intent;
   4715         }
   4716 
   4717         return null;
   4718     }
   4719 
   4720     void startDockOrHome() {
   4721         awakenDreams();
   4722 
   4723         Intent dock = createHomeDockIntent();
   4724         if (dock != null) {
   4725             try {
   4726                 mContext.startActivityAsUser(dock, UserHandle.CURRENT);
   4727                 return;
   4728             } catch (ActivityNotFoundException e) {
   4729             }
   4730         }
   4731 
   4732         mContext.startActivityAsUser(mHomeIntent, UserHandle.CURRENT);
   4733     }
   4734 
   4735     /**
   4736      * goes to the home screen
   4737      * @return whether it did anything
   4738      */
   4739     boolean goHome() {
   4740         if (false) {
   4741             // This code always brings home to the front.
   4742             try {
   4743                 ActivityManagerNative.getDefault().stopAppSwitches();
   4744             } catch (RemoteException e) {
   4745             }
   4746             sendCloseSystemWindows();
   4747             startDockOrHome();
   4748         } else {
   4749             // This code brings home to the front or, if it is already
   4750             // at the front, puts the device to sleep.
   4751             try {
   4752                 if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
   4753                     /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
   4754                     Log.d(TAG, "UTS-TEST-MODE");
   4755                 } else {
   4756                     ActivityManagerNative.getDefault().stopAppSwitches();
   4757                     sendCloseSystemWindows();
   4758                     Intent dock = createHomeDockIntent();
   4759                     if (dock != null) {
   4760                         int result = ActivityManagerNative.getDefault()
   4761                                 .startActivityAsUser(null, null, dock,
   4762                                         dock.resolveTypeIfNeeded(mContext.getContentResolver()),
   4763                                         null, null, 0,
   4764                                         ActivityManager.START_FLAG_ONLY_IF_NEEDED,
   4765                                         null, null, null, UserHandle.USER_CURRENT);
   4766                         if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
   4767                             return false;
   4768                         }
   4769                     }
   4770                 }
   4771                 int result = ActivityManagerNative.getDefault()
   4772                         .startActivityAsUser(null, null, mHomeIntent,
   4773                                 mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
   4774                                 null, null, 0,
   4775                                 ActivityManager.START_FLAG_ONLY_IF_NEEDED,
   4776                                 null, null, null, UserHandle.USER_CURRENT);
   4777                 if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
   4778                     return false;
   4779                 }
   4780             } catch (RemoteException ex) {
   4781                 // bummer, the activity manager, which is in this process, is dead
   4782             }
   4783         }
   4784         return true;
   4785     }
   4786 
   4787     public void setCurrentOrientationLw(int newOrientation) {
   4788         synchronized (mLock) {
   4789             if (newOrientation != mCurrentAppOrientation) {
   4790                 mCurrentAppOrientation = newOrientation;
   4791                 updateOrientationListenerLp();
   4792             }
   4793         }
   4794     }
   4795 
   4796     private void performAuditoryFeedbackForAccessibilityIfNeed() {
   4797         if (!isGlobalAccessibilityGestureEnabled()) {
   4798             return;
   4799         }
   4800         AudioManager audioManager = (AudioManager) mContext.getSystemService(
   4801                 Context.AUDIO_SERVICE);
   4802         if (audioManager.isSilentMode()) {
   4803             return;
   4804         }
   4805         Ringtone ringTone = RingtoneManager.getRingtone(mContext,
   4806                 Settings.System.DEFAULT_NOTIFICATION_URI);
   4807         ringTone.setStreamType(AudioManager.STREAM_MUSIC);
   4808         ringTone.play();
   4809     }
   4810     private boolean isGlobalAccessibilityGestureEnabled() {
   4811         return Settings.Global.getInt(mContext.getContentResolver(),
   4812                 Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
   4813     }
   4814 
   4815     public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
   4816         if (!mVibrator.hasVibrator()) {
   4817             return false;
   4818         }
   4819         final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
   4820                 Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
   4821         if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
   4822             return false;
   4823         }
   4824         long[] pattern = null;
   4825         switch (effectId) {
   4826             case HapticFeedbackConstants.LONG_PRESS:
   4827                 pattern = mLongPressVibePattern;
   4828                 break;
   4829             case HapticFeedbackConstants.VIRTUAL_KEY:
   4830                 pattern = mVirtualKeyVibePattern;
   4831                 break;
   4832             case HapticFeedbackConstants.KEYBOARD_TAP:
   4833                 pattern = mKeyboardTapVibePattern;
   4834                 break;
   4835             case HapticFeedbackConstants.SAFE_MODE_DISABLED:
   4836                 pattern = mSafeModeDisabledVibePattern;
   4837                 break;
   4838             case HapticFeedbackConstants.SAFE_MODE_ENABLED:
   4839                 pattern = mSafeModeEnabledVibePattern;
   4840                 break;
   4841             default:
   4842                 return false;
   4843         }
   4844         int owningUid;
   4845         String owningPackage;
   4846         if (win != null) {
   4847             owningUid = win.getOwningUid();
   4848             owningPackage = win.getOwningPackage();
   4849         } else {
   4850             owningUid = android.os.Process.myUid();
   4851             owningPackage = mContext.getBasePackageName();
   4852         }
   4853         if (pattern.length == 1) {
   4854             // One-shot vibration
   4855             mVibrator.vibrate(owningUid, owningPackage, pattern[0]);
   4856         } else {
   4857             // Pattern vibration
   4858             mVibrator.vibrate(owningUid, owningPackage, pattern, -1);
   4859         }
   4860         return true;
   4861     }
   4862 
   4863     @Override
   4864     public void keepScreenOnStartedLw() {
   4865     }
   4866 
   4867     @Override
   4868     public void keepScreenOnStoppedLw() {
   4869         if (mKeyguardMediator != null && !mKeyguardMediator.isShowingAndNotHidden()) {
   4870             long curTime = SystemClock.uptimeMillis();
   4871             mPowerManager.userActivity(curTime, false);
   4872         }
   4873     }
   4874 
   4875     private int updateSystemUiVisibilityLw() {
   4876         // If there is no window focused, there will be nobody to handle the events
   4877         // anyway, so just hang on in whatever state we're in until things settle down.
   4878         if (mFocusedWindow == null) {
   4879             return 0;
   4880         }
   4881         if (mFocusedWindow.getAttrs().type == TYPE_KEYGUARD && mHideLockScreen == true) {
   4882             // We are updating at a point where the keyguard has gotten
   4883             // focus, but we were last in a state where the top window is
   4884             // hiding it.  This is probably because the keyguard as been
   4885             // shown while the top window was displayed, so we want to ignore
   4886             // it here because this is just a very transient change and it
   4887             // will quickly lose focus once it correctly gets hidden.
   4888             return 0;
   4889         }
   4890         int tmpVisibility = mFocusedWindow.getSystemUiVisibility()
   4891                 & ~mResettingSystemUiFlags
   4892                 & ~mForceClearedSystemUiFlags;
   4893         if (mForcingShowNavBar && mFocusedWindow.getSurfaceLayer() < mForcingShowNavBarLayer) {
   4894             tmpVisibility &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
   4895         }
   4896         final int visibility = tmpVisibility;
   4897         int diff = visibility ^ mLastSystemUiFlags;
   4898         final boolean needsMenu = mFocusedWindow.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
   4899         if (diff == 0 && mLastFocusNeedsMenu == needsMenu
   4900                 && mFocusedApp == mFocusedWindow.getAppToken()) {
   4901             return 0;
   4902         }
   4903         mLastSystemUiFlags = visibility;
   4904         mLastFocusNeedsMenu = needsMenu;
   4905         mFocusedApp = mFocusedWindow.getAppToken();
   4906         mHandler.post(new Runnable() {
   4907                 public void run() {
   4908                     try {
   4909                         IStatusBarService statusbar = getStatusBarService();
   4910                         if (statusbar != null) {
   4911                             statusbar.setSystemUiVisibility(visibility, 0xffffffff);
   4912                             statusbar.topAppWindowChanged(needsMenu);
   4913                         }
   4914                     } catch (RemoteException e) {
   4915                         // re-acquire status bar service next time it is needed.
   4916                         mStatusBarService = null;
   4917                     }
   4918                 }
   4919             });
   4920         return diff;
   4921     }
   4922 
   4923     // Use this instead of checking config_showNavigationBar so that it can be consistently
   4924     // overridden by qemu.hw.mainkeys in the emulator.
   4925     public boolean hasNavigationBar() {
   4926         return mHasNavigationBar;
   4927     }
   4928 
   4929     @Override
   4930     public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
   4931         mLastInputMethodWindow = ime;
   4932         mLastInputMethodTargetWindow = target;
   4933     }
   4934 
   4935     @Override
   4936     public void setCurrentUserLw(int newUserId) {
   4937         if (mKeyguardMediator != null) {
   4938             mKeyguardMediator.setCurrentUser(newUserId);
   4939         }
   4940         if (mStatusBarService != null) {
   4941             try {
   4942                 mStatusBarService.setCurrentUser(newUserId);
   4943             } catch (RemoteException e) {
   4944                 // oh well
   4945             }
   4946         }
   4947         setLastInputMethodWindowLw(null, null);
   4948     }
   4949 
   4950     @Override
   4951     public void showAssistant() {
   4952         mKeyguardMediator.showAssistant();
   4953     }
   4954 
   4955     @Override
   4956     public boolean canMagnifyWindow(int windowType) {
   4957         switch (windowType) {
   4958             case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
   4959             case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
   4960             case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
   4961             case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
   4962                 return false;
   4963             }
   4964         }
   4965         return true;
   4966     }
   4967 
   4968     @Override
   4969     public boolean isTopLevelWindow(int windowType) {
   4970         if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
   4971                 && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
   4972             return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
   4973         }
   4974         return true;
   4975     }
   4976 
   4977     @Override
   4978     public void dump(String prefix, PrintWriter pw, String[] args) {
   4979         pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
   4980                 pw.print(" mSystemReady="); pw.print(mSystemReady);
   4981                 pw.print(" mSystemBooted="); pw.println(mSystemBooted);
   4982         pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
   4983                 pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
   4984                 pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
   4985         if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
   4986                 || mForceClearedSystemUiFlags != 0) {
   4987             pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
   4988                     pw.print(Integer.toHexString(mLastSystemUiFlags));
   4989                     pw.print(" mResettingSystemUiFlags=0x");
   4990                     pw.print(Integer.toHexString(mResettingSystemUiFlags));
   4991                     pw.print(" mForceClearedSystemUiFlags=0x");
   4992                     pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
   4993         }
   4994         if (mLastFocusNeedsMenu) {
   4995             pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
   4996                     pw.println(mLastFocusNeedsMenu);
   4997         }
   4998         pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
   4999                 pw.print(" mDockMode="); pw.print(mDockMode);
   5000                 pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
   5001                 pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
   5002         pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
   5003                 pw.print(" mUserRotation="); pw.print(mUserRotation);
   5004                 pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
   5005         pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
   5006         pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
   5007                 pw.print(mCarDockEnablesAccelerometer);
   5008                 pw.print(" mDeskDockEnablesAccelerometer=");
   5009                 pw.println(mDeskDockEnablesAccelerometer);
   5010         pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
   5011                 pw.print(mLidKeyboardAccessibility);
   5012                 pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
   5013                 pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
   5014         pw.print(prefix); pw.print("mLongPressOnPowerBehavior=");
   5015                 pw.print(mLongPressOnPowerBehavior);
   5016                 pw.print(" mHasSoftInput="); pw.println(mHasSoftInput);
   5017         pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
   5018                 pw.print(" mScreenOnFully="); pw.print(mScreenOnFully);
   5019                 pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled);
   5020         pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
   5021                 pw.print(","); pw.print(mOverscanScreenTop);
   5022                 pw.print(") "); pw.print(mOverscanScreenWidth);
   5023                 pw.print("x"); pw.println(mOverscanScreenHeight);
   5024         if (mOverscanLeft != 0 || mOverscanTop != 0
   5025                 || mOverscanRight != 0 || mOverscanBottom != 0) {
   5026             pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
   5027                     pw.print(" top="); pw.print(mOverscanTop);
   5028                     pw.print(" right="); pw.print(mOverscanRight);
   5029                     pw.print(" bottom="); pw.println(mOverscanBottom);
   5030         }
   5031         pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
   5032                 pw.print(mRestrictedOverscanScreenLeft);
   5033                 pw.print(","); pw.print(mRestrictedOverscanScreenTop);
   5034                 pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
   5035                 pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
   5036         pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
   5037                 pw.print(","); pw.print(mUnrestrictedScreenTop);
   5038                 pw.print(") "); pw.print(mUnrestrictedScreenWidth);
   5039                 pw.print("x"); pw.println(mUnrestrictedScreenHeight);
   5040         pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
   5041                 pw.print(","); pw.print(mRestrictedScreenTop);
   5042                 pw.print(") "); pw.print(mRestrictedScreenWidth);
   5043                 pw.print("x"); pw.println(mRestrictedScreenHeight);
   5044         pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
   5045                 pw.print(","); pw.print(mStableFullscreenTop);
   5046                 pw.print(")-("); pw.print(mStableFullscreenRight);
   5047                 pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
   5048         pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
   5049                 pw.print(","); pw.print(mStableTop);
   5050                 pw.print(")-("); pw.print(mStableRight);
   5051                 pw.print(","); pw.print(mStableBottom); pw.println(")");
   5052         pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
   5053                 pw.print(","); pw.print(mSystemTop);
   5054                 pw.print(")-("); pw.print(mSystemRight);
   5055                 pw.print(","); pw.print(mSystemBottom); pw.println(")");
   5056         pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
   5057                 pw.print(","); pw.print(mCurTop);
   5058                 pw.print(")-("); pw.print(mCurRight);
   5059                 pw.print(","); pw.print(mCurBottom); pw.println(")");
   5060         pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
   5061                 pw.print(","); pw.print(mContentTop);
   5062                 pw.print(")-("); pw.print(mContentRight);
   5063                 pw.print(","); pw.print(mContentBottom); pw.println(")");
   5064         pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
   5065                 pw.print(","); pw.print(mDockTop);
   5066                 pw.print(")-("); pw.print(mDockRight);
   5067                 pw.print(","); pw.print(mDockBottom); pw.println(")");
   5068         pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
   5069                 pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
   5070         pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
   5071                 pw.print(" mShowingDream="); pw.print(mShowingDream);
   5072                 pw.print(" mDreamingLockscreen="); pw.println(mDreamingLockscreen);
   5073         if (mLastInputMethodWindow != null) {
   5074             pw.print(prefix); pw.print("mLastInputMethodWindow=");
   5075                     pw.println(mLastInputMethodWindow);
   5076         }
   5077         if (mLastInputMethodTargetWindow != null) {
   5078             pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
   5079                     pw.println(mLastInputMethodTargetWindow);
   5080         }
   5081         if (mStatusBar != null) {
   5082             pw.print(prefix); pw.print("mStatusBar=");
   5083                     pw.println(mStatusBar);
   5084         }
   5085         if (mNavigationBar != null) {
   5086             pw.print(prefix); pw.print("mNavigationBar=");
   5087                     pw.println(mNavigationBar);
   5088         }
   5089         if (mKeyguard != null) {
   5090             pw.print(prefix); pw.print("mKeyguard=");
   5091                     pw.println(mKeyguard);
   5092         }
   5093         if (mFocusedWindow != null) {
   5094             pw.print(prefix); pw.print("mFocusedWindow=");
   5095                     pw.println(mFocusedWindow);
   5096         }
   5097         if (mFocusedApp != null) {
   5098             pw.print(prefix); pw.print("mFocusedApp=");
   5099                     pw.println(mFocusedApp);
   5100         }
   5101         if (mWinDismissingKeyguard != null) {
   5102             pw.print(prefix); pw.print("mWinDismissingKeyguard=");
   5103                     pw.println(mWinDismissingKeyguard);
   5104         }
   5105         if (mTopFullscreenOpaqueWindowState != null) {
   5106             pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
   5107                     pw.println(mTopFullscreenOpaqueWindowState);
   5108         }
   5109         if (mForcingShowNavBar) {
   5110             pw.print(prefix); pw.print("mForcingShowNavBar=");
   5111                     pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
   5112                     pw.println(mForcingShowNavBarLayer);
   5113         }
   5114         pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
   5115                 pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
   5116         pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
   5117                 pw.print(" mForceStatusBarFromKeyguard=");
   5118                 pw.println(mForceStatusBarFromKeyguard);
   5119         pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
   5120                 pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
   5121                 pw.print(" mHomePressed="); pw.println(mHomePressed);
   5122         pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
   5123                 pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
   5124                 pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
   5125         pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
   5126                 pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
   5127                 pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
   5128         pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
   5129                 pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
   5130         pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
   5131                 pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
   5132         pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
   5133                 pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
   5134         pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
   5135     }
   5136 }
   5137