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