Merge "Track rename of base/ to android-base/."
diff --git a/api/current.txt b/api/current.txt
index bb6b52c..2e2a604 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -5802,6 +5802,7 @@
     method public void lockNow();
     method public void removeActiveAdmin(android.content.ComponentName);
     method public boolean removeCrossProfileWidgetProvider(android.content.ComponentName, java.lang.String);
+    method public boolean removeKeyPair(android.content.ComponentName, java.lang.String);
     method public boolean removeUser(android.content.ComponentName, android.os.UserHandle);
     method public boolean resetPassword(java.lang.String, int);
     method public void setAccountManagementDisabled(android.content.ComponentName, java.lang.String, boolean);
@@ -7823,6 +7824,7 @@
     method public abstract android.content.res.Resources getResources();
     method public abstract android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public abstract android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public abstract java.io.File getSharedPreferencesPath(java.lang.String);
     method public final java.lang.String getString(int);
     method public final java.lang.String getString(int, java.lang.Object...);
     method public abstract java.lang.Object getSystemService(java.lang.String);
@@ -8007,6 +8009,7 @@
     method public android.content.res.Resources getResources();
     method public android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public java.io.File getSharedPreferencesPath(java.lang.String);
     method public java.lang.Object getSystemService(java.lang.String);
     method public java.lang.String getSystemServiceName(java.lang.Class<?>);
     method public android.content.res.Resources.Theme getTheme();
@@ -28468,6 +28471,7 @@
     method public android.preference.PreferenceScreen createPreferenceScreen(android.content.Context);
     method public android.preference.Preference findPreference(java.lang.CharSequence);
     method public static android.content.SharedPreferences getDefaultSharedPreferences(android.content.Context);
+    method public static java.lang.String getDefaultSharedPreferencesName(android.content.Context);
     method public android.content.SharedPreferences getSharedPreferences();
     method public int getSharedPreferencesMode();
     method public java.lang.String getSharedPreferencesName();
@@ -36272,6 +36276,7 @@
     method public android.content.res.Resources getResources();
     method public android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public java.io.File getSharedPreferencesPath(java.lang.String);
     method public java.lang.Object getSystemService(java.lang.String);
     method public java.lang.String getSystemServiceName(java.lang.Class<?>);
     method public android.content.res.Resources.Theme getTheme();
diff --git a/api/system-current.txt b/api/system-current.txt
index ad722f4..30be4c7 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -5935,6 +5935,7 @@
     method public void notifyPendingSystemUpdate(long);
     method public void removeActiveAdmin(android.content.ComponentName);
     method public boolean removeCrossProfileWidgetProvider(android.content.ComponentName, java.lang.String);
+    method public boolean removeKeyPair(android.content.ComponentName, java.lang.String);
     method public boolean removeUser(android.content.ComponentName, android.os.UserHandle);
     method public boolean resetPassword(java.lang.String, int);
     method public void setAccountManagementDisabled(android.content.ComponentName, java.lang.String, boolean);
@@ -8068,6 +8069,7 @@
     method public abstract android.content.res.Resources getResources();
     method public abstract android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public abstract android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public abstract java.io.File getSharedPreferencesPath(java.lang.String);
     method public final java.lang.String getString(int);
     method public final java.lang.String getString(int, java.lang.Object...);
     method public abstract java.lang.Object getSystemService(java.lang.String);
@@ -8261,6 +8263,7 @@
     method public android.content.res.Resources getResources();
     method public android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public java.io.File getSharedPreferencesPath(java.lang.String);
     method public java.lang.Object getSystemService(java.lang.String);
     method public java.lang.String getSystemServiceName(java.lang.Class<?>);
     method public android.content.res.Resources.Theme getTheme();
@@ -30461,6 +30464,7 @@
     method public android.preference.PreferenceScreen createPreferenceScreen(android.content.Context);
     method public android.preference.Preference findPreference(java.lang.CharSequence);
     method public static android.content.SharedPreferences getDefaultSharedPreferences(android.content.Context);
+    method public static java.lang.String getDefaultSharedPreferencesName(android.content.Context);
     method public android.content.SharedPreferences getSharedPreferences();
     method public int getSharedPreferencesMode();
     method public java.lang.String getSharedPreferencesName();
@@ -38599,6 +38603,7 @@
     method public android.content.res.Resources getResources();
     method public android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public java.io.File getSharedPreferencesPath(java.lang.String);
     method public java.lang.Object getSystemService(java.lang.String);
     method public java.lang.String getSystemServiceName(java.lang.Class<?>);
     method public android.content.res.Resources.Theme getTheme();
diff --git a/api/test-current.txt b/api/test-current.txt
index 1cf9a53..7be966e 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -7823,6 +7823,7 @@
     method public abstract android.content.res.Resources getResources();
     method public abstract android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public abstract android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public abstract java.io.File getSharedPreferencesPath(java.lang.String);
     method public final java.lang.String getString(int);
     method public final java.lang.String getString(int, java.lang.Object...);
     method public abstract java.lang.Object getSystemService(java.lang.String);
@@ -8007,6 +8008,7 @@
     method public android.content.res.Resources getResources();
     method public android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public java.io.File getSharedPreferencesPath(java.lang.String);
     method public java.lang.Object getSystemService(java.lang.String);
     method public java.lang.String getSystemServiceName(java.lang.Class<?>);
     method public android.content.res.Resources.Theme getTheme();
@@ -28468,6 +28470,7 @@
     method public android.preference.PreferenceScreen createPreferenceScreen(android.content.Context);
     method public android.preference.Preference findPreference(java.lang.CharSequence);
     method public static android.content.SharedPreferences getDefaultSharedPreferences(android.content.Context);
+    method public static java.lang.String getDefaultSharedPreferencesName(android.content.Context);
     method public android.content.SharedPreferences getSharedPreferences();
     method public int getSharedPreferencesMode();
     method public java.lang.String getSharedPreferencesName();
@@ -36274,6 +36277,7 @@
     method public android.content.res.Resources getResources();
     method public android.content.SharedPreferences getSharedPreferences(java.lang.String, int);
     method public android.content.SharedPreferences getSharedPreferences(java.io.File, int);
+    method public java.io.File getSharedPreferencesPath(java.lang.String);
     method public java.lang.Object getSystemService(java.lang.String);
     method public java.lang.String getSystemServiceName(java.lang.Class<?>);
     method public android.content.res.Resources.Theme getTheme();
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index 544fd6a..478164a 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -16,11 +16,11 @@
 
 package com.android.commands.pm;
 
-import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
-import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
 
 import android.accounts.IAccountManager;
 import android.app.ActivityManager;
@@ -798,6 +798,10 @@
                 flags |= UserInfo.FLAG_MANAGED_PROFILE;
             } else if ("--restricted".equals(opt)) {
                 flags |= UserInfo.FLAG_RESTRICTED;
+            } else if ("--ephemeral".equals(opt)) {
+                flags |= UserInfo.FLAG_EPHEMERAL;
+            } else if ("--guest".equals(opt)) {
+                flags |= UserInfo.FLAG_GUEST;
             } else {
                 System.err.println("Error: unknown option " + opt);
                 return showUsage();
@@ -1356,7 +1360,7 @@
         System.err.println("       pm get-install-location");
         System.err.println("       pm set-permission-enforced PERMISSION [true|false]");
         System.err.println("       pm trim-caches DESIRED_FREE_SPACE [internal|UUID]");
-        System.err.println("       pm create-user [--profileOf USER_ID] [--managed] [--restricted] USER_NAME");
+        System.err.println("       pm create-user [--profileOf USER_ID] [--managed] [--restricted] [--ephemeral] [--guest] USER_NAME");
         System.err.println("       pm remove-user USER_ID");
         System.err.println("       pm get-max-users");
         System.err.println("");
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index b11a12f..81fe23c 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -559,6 +559,14 @@
         public static boolean isAlwaysOnTop(int stackId) {
             return stackId == PINNED_STACK_ID;
         }
+
+        /**
+         * Returns true if the application windows in this stack should be displayed above all
+         * other application windows, including during the animation.
+         */
+        public static boolean shouldIncreaseApplicationWindowLayer(int stackId) {
+            return stackId == PINNED_STACK_ID || stackId == DOCKED_STACK_ID;
+        }
     }
 
     /**
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 23c4198..a703c53 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -321,11 +321,6 @@
     }
 
     @Override
-    public File getSharedPrefsFile(String name) {
-        return makeFilename(getPreferencesDir(), name + ".xml");
-    }
-
-    @Override
     public SharedPreferences getSharedPreferences(String name, int mode) {
         // At least one application in the world actually passes in a null
         // name.  This happened to work because when we generated the file name
@@ -337,7 +332,7 @@
             }
         }
 
-        final File file = getSharedPrefsFile(name);
+        final File file = getSharedPreferencesPath(name);
         return getSharedPreferences(file, mode);
     }
 
@@ -571,6 +566,11 @@
     }
 
     @Override
+    public File getSharedPreferencesPath(String name) {
+        return makeFilename(getPreferencesDir(), name + ".xml");
+    }
+
+    @Override
     public String[] fileList() {
         final String[] list = getFilesDir().list();
         return (list != null) ? list : EMPTY_STRING_ARRAY;
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 471750e..6b900a8 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -2325,8 +2325,8 @@
      * with that alias already exists, it will be overwritten.
      * @return {@code true} if the keys were installed, {@code false} otherwise.
      */
-    public boolean installKeyPair(@Nullable ComponentName admin, PrivateKey privKey, Certificate cert,
-            String alias) {
+    public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
+            @NonNull Certificate cert, @NonNull String alias) {
         try {
             final byte[] pemCert = Credentials.convertToPem(cert);
             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
@@ -2343,6 +2343,24 @@
     }
 
     /**
+     * Called by a device or profile owner to remove all user credentials installed under a given
+     * alias.
+     *
+     * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
+     *            {@code null} if calling from a delegated certificate installer.
+     * @param alias The private key alias under which the certificate is installed.
+     * @return {@code true} if the keys were both removed, {@code false} otherwise.
+     */
+    public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
+        try {
+            return mService.removeKeyPair(admin, alias);
+        } catch (RemoteException e) {
+            Log.w(TAG, "Failed talking with device policy service", e);
+        }
+        return false;
+    }
+
+    /**
      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
      * doesn't exist.
      */
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index 6b4567c..1708ee3 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -135,6 +135,7 @@
     void enforceCanManageCaCerts(in ComponentName admin);
 
     boolean installKeyPair(in ComponentName who, in byte[] privKeyBuffer, in byte[] certBuffer, String alias);
+    boolean removeKeyPair(in ComponentName who, String alias);
     void choosePrivateKeyAlias(int uid, in Uri uri, in String alias, IBinder aliasCallback);
 
     void setCertInstallerPackage(in ComponentName who, String installerPackage);
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 6cc5497..4c7e853 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -606,13 +606,13 @@
     public abstract String getPackageCodePath();
 
     /**
-     * {@hide}
-     * Return the full path to the shared prefs file for the given prefs group name.
-     *
-     * <p>Note: this is not generally useful for applications, since they should
-     * not be directly accessing the file system.
+     * @hide
+     * @deprecated use {@link #getSharedPreferencesPath(String)}
      */
-    public abstract File getSharedPrefsFile(String name);
+    @Deprecated
+    public File getSharedPrefsFile(String name) {
+        return getSharedPreferencesPath(name);
+    }
 
     /**
      * Retrieve and hold the contents of the preferences file 'name', returning
@@ -654,6 +654,7 @@
      * @return The single {@link SharedPreferences} instance that can be used
      *         to retrieve and modify the preference values.
      *
+     * @see #getSharedPreferencesPath(String)
      * @see #MODE_PRIVATE
      * @see #MODE_WORLD_READABLE
      * @see #MODE_WORLD_WRITEABLE
@@ -739,6 +740,20 @@
     public abstract File getFileStreamPath(String name);
 
     /**
+     * Returns the absolute path on the filesystem where a file created with
+     * {@link #getSharedPreferences(String, int)} is stored.
+     * <p>
+     * The returned path may change over time if the calling app is moved to an
+     * adopted storage device, so only relative paths should be persisted.
+     *
+     * @param name The name of the shared preferences for which you would like
+     *            to get a path.
+     * @return An absolute path to the given file.
+     * @see #getSharedPreferences(String, int)
+     */
+    public abstract File getSharedPreferencesPath(String name);
+
+    /**
      * Returns the absolute path to the directory on the filesystem where files
      * created with {@link #openFileOutput} are stored.
      * <p>
diff --git a/core/java/android/content/ContextWrapper.java b/core/java/android/content/ContextWrapper.java
index a345aae..f5e9159 100644
--- a/core/java/android/content/ContextWrapper.java
+++ b/core/java/android/content/ContextWrapper.java
@@ -160,12 +160,6 @@
         return mBase.getPackageCodePath();
     }
 
-    /** @hide */
-    @Override
-    public File getSharedPrefsFile(String name) {
-        return mBase.getSharedPrefsFile(name);
-    }
-
     @Override
     public SharedPreferences getSharedPreferences(String name, int mode) {
         return mBase.getSharedPreferences(name, mode);
@@ -199,6 +193,11 @@
     }
 
     @Override
+    public File getSharedPreferencesPath(String name) {
+        return mBase.getSharedPreferencesPath(name);
+    }
+
+    @Override
     public String[] fileList() {
         return mBase.fileList();
     }
diff --git a/core/java/android/content/pm/UserInfo.java b/core/java/android/content/pm/UserInfo.java
index 6e09595..e3050fe 100644
--- a/core/java/android/content/pm/UserInfo.java
+++ b/core/java/android/content/pm/UserInfo.java
@@ -78,6 +78,12 @@
 
     public static final int FLAG_QUIET_MODE = 0x00000080;
 
+    /**
+     * Indicates that this user is ephemeral. I.e. the user will be removed after leaving
+     * the foreground.
+     */
+    public static final int FLAG_EPHEMERAL = 0x00000100;
+
     public static final int NO_PROFILE_GROUP_ID = UserHandle.USER_NULL;
 
     public int id;
@@ -134,6 +140,11 @@
     public boolean isQuietModeEnabled() {
         return (flags & FLAG_QUIET_MODE) == FLAG_QUIET_MODE;
     }
+
+    public boolean isEphemeral() {
+        return (flags & FLAG_EPHEMERAL) == FLAG_EPHEMERAL;
+    }
+
     /**
      * Returns true if the user is a split system user.
      * <p>If {@link UserManager#isSplitSystemUser split system user mode} is not enabled,
diff --git a/core/java/android/os/IUserManager.aidl b/core/java/android/os/IUserManager.aidl
index 4af89c9..2db1d15 100644
--- a/core/java/android/os/IUserManager.aidl
+++ b/core/java/android/os/IUserManager.aidl
@@ -54,6 +54,7 @@
     int getUserSerialNumber(int userHandle);
     int getUserHandle(int userSerialNumber);
     Bundle getUserRestrictions(int userHandle);
+    boolean hasBaseUserRestriction(String restrictionKey, int userHandle);
     boolean hasUserRestriction(in String restrictionKey, int userHandle);
     void setUserRestriction(String key, boolean value, int userId);
     void setApplicationRestrictions(in String packageName, in Bundle restrictions,
diff --git a/core/java/android/os/Parcel.java b/core/java/android/os/Parcel.java
index f2aea08..8d035b7 100644
--- a/core/java/android/os/Parcel.java
+++ b/core/java/android/os/Parcel.java
@@ -61,12 +61,12 @@
  * appropriate to place any Parcel data in to persistent storage: changes
  * in the underlying implementation of any of the data in the Parcel can
  * render older data unreadable.</p>
- * 
+ *
  * <p>The bulk of the Parcel API revolves around reading and writing data
  * of various types.  There are six major classes of such functions available.</p>
- * 
+ *
  * <h3>Primitives</h3>
- * 
+ *
  * <p>The most basic data functions are for writing and reading primitive
  * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
  * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
@@ -74,15 +74,15 @@
  * {@link #writeString}, {@link #readString}.  Most other
  * data operations are built on top of these.  The given data is written and
  * read using the endianess of the host CPU.</p>
- * 
+ *
  * <h3>Primitive Arrays</h3>
- * 
+ *
  * <p>There are a variety of methods for reading and writing raw arrays
  * of primitive objects, which generally result in writing a 4-byte length
  * followed by the primitive data items.  The methods for reading can either
  * read the data into an existing array, or create and return a new array.
  * These available types are:</p>
- * 
+ *
  * <ul>
  * <li> {@link #writeBooleanArray(boolean[])},
  * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
@@ -104,9 +104,9 @@
  * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
  * {@link #readSparseBooleanArray()}.
  * </ul>
- * 
+ *
  * <h3>Parcelables</h3>
- * 
+ *
  * <p>The {@link Parcelable} protocol provides an extremely efficient (but
  * low-level) protocol for objects to write and read themselves from Parcels.
  * You can use the direct methods {@link #writeParcelable(Parcelable, int)}
@@ -116,7 +116,7 @@
  * methods write both the class type and its data to the Parcel, allowing
  * that class to be reconstructed from the appropriate class loader when
  * later reading.</p>
- * 
+ *
  * <p>There are also some methods that provide a more efficient way to work
  * with Parcelables: {@link #writeTypedObject}, {@link #writeTypedArray},
  * {@link #writeTypedList}, {@link #readTypedObject},
@@ -129,9 +129,9 @@
  * call {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
  * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
  * yourself.)</p>
- * 
+ *
  * <h3>Bundles</h3>
- * 
+ *
  * <p>A special type-safe container, called {@link Bundle}, is available
  * for key/value maps of heterogeneous values.  This has many optimizations
  * for improved performance when reading and writing data, and its type-safe
@@ -139,16 +139,16 @@
  * data contents into a Parcel.  The methods to use are
  * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
  * {@link #readBundle(ClassLoader)}.
- * 
+ *
  * <h3>Active Objects</h3>
- * 
+ *
  * <p>An unusual feature of Parcel is the ability to read and write active
  * objects.  For these objects the actual contents of the object is not
  * written, rather a special token referencing the object is written.  When
  * reading the object back from the Parcel, you do not get a new instance of
  * the object, but rather a handle that operates on the exact same object that
  * was originally written.  There are two forms of active objects available.</p>
- * 
+ *
  * <p>{@link Binder} objects are a core facility of Android's general cross-process
  * communication system.  The {@link IBinder} interface describes an abstract
  * protocol with a Binder object.  Any such interface can be written in to
@@ -161,7 +161,7 @@
  * {@link #createBinderArray()},
  * {@link #writeBinderList(List)}, {@link #readBinderList(List)},
  * {@link #createBinderArrayList()}.</p>
- * 
+ *
  * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
  * can be written and {@link ParcelFileDescriptor} objects returned to operate
  * on the original file descriptor.  The returned file descriptor is a dup
@@ -169,9 +169,9 @@
  * operating on the same underlying file stream, with the same position, etc.
  * The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
  * {@link #readFileDescriptor()}.
- * 
+ *
  * <h3>Untyped Containers</h3>
- * 
+ *
  * <p>A final class of methods are for writing and reading standard Java
  * containers of arbitrary types.  These all revolve around the
  * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
@@ -233,6 +233,7 @@
     private static final int VAL_PERSISTABLEBUNDLE = 25;
     private static final int VAL_SIZE = 26;
     private static final int VAL_SIZEF = 27;
+    private static final int VAL_DOUBLEARRAY = 28;
 
     // The initial int32 in a Binder call's reply Parcel header:
     private static final int EX_SECURITY = -1;
@@ -663,7 +664,7 @@
      * growing dataCapacity() if needed.  The Map keys must be String objects.
      * The Map values are written using {@link #writeValue} and must follow
      * the specification there.
-     * 
+     *
      * <p>It is strongly recommended to use {@link #writeBundle} instead of
      * this method, since the Bundle class provides a type-safe API that
      * allows you to avoid mysterious type errors at the point of marshalling.
@@ -1429,6 +1430,9 @@
         } else if (v instanceof SizeF) {
             writeInt(VAL_SIZEF);
             writeSizeF((SizeF) v);
+        } else if (v instanceof double[]) {
+            writeInt(VAL_DOUBLEARRAY);
+            writeDoubleArray((double[]) v);
         } else {
             Class<?> clazz = v.getClass();
             if (clazz.isArray() && clazz.getComponentType() == Object.class) {
@@ -1504,7 +1508,7 @@
      * exception will be re-thrown by this function as a RuntimeException
      * (to be caught by the system's last-resort exception handling when
      * dispatching a transaction).
-     * 
+     *
      * <p>The supported exception types are:
      * <ul>
      * <li>{@link BadParcelableException}
@@ -1514,7 +1518,7 @@
      * <li>{@link SecurityException}
      * <li>{@link NetworkOnMainThreadException}
      * </ul>
-     * 
+     *
      * @param e The Exception to be written.
      *
      * @see #writeNoException
@@ -1835,7 +1839,7 @@
             if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
             return null;
         }
-        
+
         final Bundle bundle = new Bundle(this, length);
         if (loader != null) {
             bundle.setClassLoader(loader);
@@ -2346,7 +2350,7 @@
             return readArrayList(loader);
 
         case VAL_BOOLEANARRAY:
-            return createBooleanArray();        
+            return createBooleanArray();
 
         case VAL_BYTEARRAY:
             return createByteArray();
@@ -2396,6 +2400,9 @@
         case VAL_SIZEF:
             return readSizeF();
 
+        case VAL_DOUBLEARRAY:
+            return createDoubleArray();
+
         default:
             int off = dataPosition() - 4;
             throw new RuntimeException(
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 4781a6c..c8abcef 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -721,6 +721,25 @@
     }
 
     /**
+     * Checks if the calling app is running as an ephemeral user.
+     *
+     * @return whether the caller is an ephemeral user.
+     * @hide
+     */
+    public boolean isEphemeralUser() {
+        return isUserEphemeral(UserHandle.myUserId());
+    }
+
+    /**
+     * Returns whether the specified user is ephemeral.
+     * @hide
+     */
+    public boolean isUserEphemeral(int userId) {
+        final UserInfo user = getUserInfo(userId);
+        return user != null && user.isEphemeral();
+    }
+
+    /**
      * Return whether the given user is actively running.  This means that
      * the user is in the "started" state, not "stopped" -- it is currently
      * allowed to run code through scheduled alarms, receiving broadcasts,
@@ -826,6 +845,24 @@
         }
     }
 
+     /**
+     * @hide
+     * Returns whether the given user has been disallowed from performing certain actions
+     * or setting certain settings through UserManager. This method disregards restrictions
+     * set by device policy.
+     * @param restrictionKey the string key representing the restriction
+     * @param userHandle the UserHandle of the user for whom to retrieve the restrictions.
+     */
+    public boolean hasBaseUserRestriction(String restrictionKey, UserHandle userHandle) {
+        try {
+            return mService.hasBaseUserRestriction(restrictionKey, userHandle.getIdentifier());
+        } catch (RemoteException re) {
+            Log.w(TAG, "Could not get base user restrictions for user " +
+                    userHandle.getIdentifier(), re);
+            return false;
+        }
+    }
+
     /**
      * This will no longer work.  Device owners and profile owners should use
      * {@link DevicePolicyManager#addUserRestriction(ComponentName, String)} instead.
diff --git a/core/java/android/os/storage/IMountService.java b/core/java/android/os/storage/IMountService.java
index c6510f0..9b3f02d 100644
--- a/core/java/android/os/storage/IMountService.java
+++ b/core/java/android/os/storage/IMountService.java
@@ -25,8 +25,6 @@
 import android.os.Parcelable;
 import android.os.RemoteException;
 
-import java.io.FileDescriptor;
-
 /**
  * WARNING! Update IMountService.h and IMountService.cpp if you change this
  * file. In particular, the ordering of the methods below must match the
@@ -1202,13 +1200,15 @@
             }
 
             @Override
-            public void createUserKey(int userId, int serialNumber) throws RemoteException {
+            public void createUserKey(int userId, int serialNumber, boolean ephemeral)
+                    throws RemoteException {
                 Parcel _data = Parcel.obtain();
                 Parcel _reply = Parcel.obtain();
                 try {
                     _data.writeInterfaceToken(DESCRIPTOR);
                     _data.writeInt(userId);
                     _data.writeInt(serialNumber);
+                    _data.writeInt(ephemeral ? 1 : 0);
                     mRemote.transact(Stub.TRANSACTION_createUserKey, _data, _reply, 0);
                     _reply.readException();
                 } finally {
@@ -1283,7 +1283,8 @@
             }
 
             @Override
-            public void prepareUserStorage(String volumeUuid, int userId, int serialNumber)
+            public void prepareUserStorage(
+                    String volumeUuid, int userId, int serialNumber, boolean ephemeral)
                     throws RemoteException {
                 Parcel _data = Parcel.obtain();
                 Parcel _reply = Parcel.obtain();
@@ -1292,6 +1293,7 @@
                     _data.writeString(volumeUuid);
                     _data.writeInt(userId);
                     _data.writeInt(serialNumber);
+                    _data.writeInt(ephemeral ? 1 : 0);
                     mRemote.transact(Stub.TRANSACTION_prepareUserStorage, _data, _reply, 0);
                     _reply.readException();
                 } finally {
@@ -2012,7 +2014,8 @@
                     data.enforceInterface(DESCRIPTOR);
                     int userId = data.readInt();
                     int serialNumber = data.readInt();
-                    createUserKey(userId, serialNumber);
+                    boolean ephemeral = data.readInt() != 0;
+                    createUserKey(userId, serialNumber, ephemeral);
                     reply.writeNoException();
                     return true;
                 }
@@ -2052,7 +2055,8 @@
                     String volumeUuid = data.readString();
                     int userId = data.readInt();
                     int serialNumber = data.readInt();
-                    prepareUserStorage(volumeUuid, userId, serialNumber);
+                    boolean ephemeral = data.readInt() != 0;
+                    prepareUserStorage(volumeUuid, userId, serialNumber, ephemeral);
                     reply.writeNoException();
                     return true;
                 }
@@ -2376,15 +2380,16 @@
     public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback)
             throws RemoteException;
 
-    public void createUserKey(int userId, int serialNumber) throws RemoteException;
+    public void createUserKey(int userId, int serialNumber, boolean ephemeral)
+            throws RemoteException;
     public void destroyUserKey(int userId) throws RemoteException;
 
     public void unlockUserKey(int userId, int serialNumber, byte[] token) throws RemoteException;
     public void lockUserKey(int userId) throws RemoteException;
     public boolean isUserKeyUnlocked(int userId) throws RemoteException;
 
-    public void prepareUserStorage(String volumeUuid, int userId, int serialNumber)
-            throws RemoteException;
+    public void prepareUserStorage(String volumeUuid, int userId, int serialNumber,
+            boolean ephemeral) throws RemoteException;
 
     public ParcelFileDescriptor mountAppFuse(String name) throws RemoteException;
 }
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index db12564..beda169 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -966,9 +966,9 @@
     }
 
     /** {@hide} */
-    public void createUserKey(int userId, int serialNumber) {
+    public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
         try {
-            mMountService.createUserKey(userId, serialNumber);
+            mMountService.createUserKey(userId, serialNumber, ephemeral);
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
         }
@@ -1002,9 +1002,10 @@
     }
 
     /** {@hide} */
-    public void prepareUserStorage(String volumeUuid, int userId, int serialNumber) {
+    public void prepareUserStorage(
+            String volumeUuid, int userId, int serialNumber, boolean ephemeral) {
         try {
-            mMountService.prepareUserStorage(volumeUuid, userId, serialNumber);
+            mMountService.prepareUserStorage(volumeUuid, userId, serialNumber, ephemeral);
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
         }
@@ -1021,8 +1022,17 @@
 
     /** {@hide} */
     public static boolean isFileBasedEncryptionEnabled() {
-        return "file".equals(SystemProperties.get("ro.crypto.type", "none"))
-                || SystemProperties.getBoolean(StorageManager.PROP_EMULATE_FBE, false);
+        return isNativeFileBasedEncryptionEnabled() || isEmulatedFileBasedEncryptionEnabled();
+    }
+
+    /** {@hide} */
+    public static boolean isNativeFileBasedEncryptionEnabled() {
+        return "file".equals(SystemProperties.get("ro.crypto.type", "none"));
+    }
+
+    /** {@hide} */
+    public static boolean isEmulatedFileBasedEncryptionEnabled() {
+        return SystemProperties.getBoolean(StorageManager.PROP_EMULATE_FBE, false);
     }
 
     /** {@hide} */
diff --git a/core/java/android/preference/PreferenceManager.java b/core/java/android/preference/PreferenceManager.java
index 4e4b1c9..fda6326 100644
--- a/core/java/android/preference/PreferenceManager.java
+++ b/core/java/android/preference/PreferenceManager.java
@@ -371,7 +371,13 @@
                 getDefaultSharedPreferencesMode());
     }
 
-    private static String getDefaultSharedPreferencesName(Context context) {
+    /**
+     * Returns the name used for storing default shared preferences.
+     *
+     * @see #getDefaultSharedPreferences(Context)
+     * @see Context#getSharedPreferencesPath(String)
+     */
+    public static String getDefaultSharedPreferencesName(Context context) {
         return context.getPackageName() + "_preferences";
     }
 
diff --git a/core/java/android/util/ArrayMap.java b/core/java/android/util/ArrayMap.java
index 4ee9807..bdb1fdc 100644
--- a/core/java/android/util/ArrayMap.java
+++ b/core/java/android/util/ArrayMap.java
@@ -60,6 +60,11 @@
     private static final int CACHE_SIZE = 10;
 
     /**
+     * Special hash array value that indicates the container is immutable.
+     */
+    static final int[] EMPTY_IMMUTABLE_INTS = new int[0];
+
+    /**
      * @hide Special immutable empty ArrayMap.
      */
     public static final ArrayMap EMPTY = new ArrayMap(true);
@@ -75,11 +80,6 @@
     static Object[] mTwiceBaseCache;
     static int mTwiceBaseCacheSize;
 
-    /**
-     * Special hash array value that indicates the container is immutable.
-     */
-    static final int[] EMPTY_IMMUTABLE_INTS = new int[0];
-
     int[] mHashes;
     Object[] mArray;
     int mSize;
diff --git a/core/java/android/view/InputDevice.java b/core/java/android/view/InputDevice.java
index bae51d3..46b9a46 100644
--- a/core/java/android/view/InputDevice.java
+++ b/core/java/android/view/InputDevice.java
@@ -256,6 +256,15 @@
     public static final int SOURCE_TOUCH_NAVIGATION = 0x00200000 | SOURCE_CLASS_NONE;
 
     /**
+     * The input source is a rotating encoder device whose motions should be interpreted as akin to
+     * those of a scroll wheel.
+     *
+     * @see #SOURCE_CLASS_NONE
+     * {@hide}
+     */
+    public static final int SOURCE_ROTARY_ENCODER = 0x00400000 | SOURCE_CLASS_NONE;
+
+    /**
      * The input source is a joystick.
      * (It may also be a {@link #SOURCE_GAMEPAD}).
      *
diff --git a/core/java/android/view/MotionEvent.java b/core/java/android/view/MotionEvent.java
index 6026d04..527d7e5 100644
--- a/core/java/android/view/MotionEvent.java
+++ b/core/java/android/view/MotionEvent.java
@@ -962,6 +962,22 @@
     public static final int AXIS_TILT = 25;
 
     /**
+     * Axis constant: Generic scroll axis of a motion event.
+     * <p>
+     * <ul>
+     * <li>Reports the relative movement of the generic scrolling device.
+     * </ul>
+     * </p><p>
+     * This axis should be used for scroll events that are neither strictly vertical nor horizontal.
+     * A good example would be the rotation of a rotary encoder input device.
+     * </p>
+     *
+     * @see #getAxisValue(int, int)
+     * {@hide}
+     */
+    public static final int AXIS_SCROLL = 26;
+
+    /**
      * Axis constant: Generic 1 axis of a motion event.
      * The interpretation of a generic axis is device-specific.
      *
@@ -1171,6 +1187,7 @@
         names.append(AXIS_BRAKE, "AXIS_BRAKE");
         names.append(AXIS_DISTANCE, "AXIS_DISTANCE");
         names.append(AXIS_TILT, "AXIS_TILT");
+        names.append(AXIS_SCROLL, "AXIS_SCROLL");
         names.append(AXIS_GENERIC_1, "AXIS_GENERIC_1");
         names.append(AXIS_GENERIC_2, "AXIS_GENERIC_2");
         names.append(AXIS_GENERIC_3, "AXIS_GENERIC_3");
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index 7e45bbb..b1a8479 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -431,6 +431,11 @@
         public int getLidState();
 
         /**
+         * Lock the device now.
+         */
+        public void lockDeviceNow();
+
+        /**
          * Returns a code that descripbes whether the camera lens is covered or not.
          */
         public int getCameraLensCoverState();
diff --git a/core/java/com/android/internal/util/StateMachine.java b/core/java/com/android/internal/util/StateMachine.java
index 6816646..554d367 100644
--- a/core/java/com/android/internal/util/StateMachine.java
+++ b/core/java/com/android/internal/util/StateMachine.java
@@ -1879,6 +1879,33 @@
     }
 
     /**
+     * Check if there are any pending messages with code 'what' in deferred messages queue.
+     */
+    protected final boolean hasDeferredMessages(int what) {
+        SmHandler smh = mSmHandler;
+        if (smh == null) return false;
+
+        Iterator<Message> iterator = smh.mDeferredMessages.iterator();
+        while (iterator.hasNext()) {
+            Message msg = iterator.next();
+            if (msg.what == what) return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Check if there are any pending posts of messages with code 'what' in
+     * the message queue. This does NOT check messages in deferred message queue.
+     */
+    protected final boolean hasMessages(int what) {
+        SmHandler smh = mSmHandler;
+        if (smh == null) return false;
+
+        return smh.hasMessages(what);
+    }
+
+    /**
      * Validate that the message was sent by
      * {@link StateMachine#quit} or {@link StateMachine#quitNow}.
      * */
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 8f3822f..4fda222 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -325,6 +325,49 @@
 
     <protected-broadcast android:name="android.intent.action.MANAGED_PROFILE_AVAILABILITY_CHANGED" />
     <protected-broadcast android:name="android.intent.action.AVAILABILITY_CHANGED" />
+
+    <!-- Added in N -->
+    <protected-broadcast android:name="android.intent.action.ANR" />
+    <protected-broadcast android:name="android.intent.action.CALL" />
+    <protected-broadcast android:name="android.intent.action.DROPBOX_ENTRY_ADDED" />
+    <protected-broadcast android:name="android.intent.action.INPUT_METHOD_CHANGED" />
+    <protected-broadcast android:name="android.intent.action.internal_sim_state_changed" />
+    <protected-broadcast android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
+    <protected-broadcast android:name="android.intent.action.PRECISE_CALL_STATE" />
+    <protected-broadcast android:name="android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED" />
+    <protected-broadcast android:name="android.intent.action.SUBSCRIPTION_PHONE_STATE" />
+    <protected-broadcast android:name="android.intent.action.USER_INFO_CHANGED" />
+    <protected-broadcast android:name="android.intent.action.USER_UNLOCKED" />
+    <protected-broadcast android:name="android.intent.action.WALLPAPER_CHANGED" />
+
+    <protected-broadcast android:name="android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED" />
+    <protected-broadcast android:name="android.bluetooth.adapter.action.BLE_STATE_CHANGED" />
+    <protected-broadcast android:name="android.content.jobscheduler.JOB_DELAY_EXPIRED" />
+    <protected-broadcast android:name="android.content.syncmanager.SYNC_ALARM" />
+    <protected-broadcast android:name="android.media.INTERNAL_RINGER_MODE_CHANGED_ACTION" />
+    <protected-broadcast android:name="android.media.STREAM_DEVICES_CHANGED_ACTION" />
+    <protected-broadcast android:name="android.media.STREAM_MUTE_CHANGED_ACTION" />
+    <protected-broadcast android:name="android.net.sip.SIP_SERVICE_UP" />
+    <protected-broadcast android:name="android.nfc.action.ADAPTER_STATE_CHANGED" />
+    <protected-broadcast android:name="android.os.action.CHARGING" />
+    <protected-broadcast android:name="android.os.action.DISCHARGING" />
+    <protected-broadcast android:name="android.search.action.SEARCHABLES_CHANGED" />
+    <protected-broadcast android:name="android.security.STORAGE_CHANGED" />
+    <protected-broadcast android:name="android.telecom.action.PHONE_ACCOUNT_REGISTERED" />
+    <protected-broadcast android:name="android.telecom.action.PHONE_ACCOUNT_UNREGISTERED" />
+    <protected-broadcast android:name="android.telephony.action.CARRIER_CONFIG_CHANGED" />
+
+    <protected-broadcast android:name="com.android.bluetooth.btservice.action.ALARM_WAKEUP" />
+    <protected-broadcast android:name="com.android.ims.IMS_SERVICE_UP" />
+    <protected-broadcast android:name="com.android.server.action.NETWORK_STATS_POLL" />
+    <protected-broadcast android:name="com.android.server.action.NETWORK_STATS_UPDATED" />
+    <protected-broadcast android:name="com.android.server.NetworkTimeUpdateService.action.POLL" />
+    <protected-broadcast android:name="com.android.server.telecom.intent.action.CALLS_ADD_ENTRY" />
+    <protected-broadcast android:name="com.android.settings.location.MODE_CHANGING" />
+
+    <protected-broadcast android:name="ScheduleConditionProvider.EVALUATE" />
+    <protected-broadcast android:name="wifi_scan_available" />
+
     <!-- ====================================================================== -->
     <!--                          RUNTIME PERMISSIONS                           -->
     <!-- ====================================================================== -->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index decb1ef..97c0e07 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -673,6 +673,10 @@
          closed.  The default is 0. -->
     <integer name="config_lidNavigationAccessibility">0</integer>
 
+    <!-- Indicate whether closing the lid causes the lockscreen to appear.
+         The default is false. -->
+    <bool name="config_lidControlsScreenLock">false</bool>
+
     <!-- Indicate whether closing the lid causes the device to go to sleep and opening
          it causes the device to wake up.
          The default is false. -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index d92adc2..1de4c45 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -1480,6 +1480,7 @@
   <java-symbol type="bool" name="config_enableLockScreenRotation" />
   <java-symbol type="bool" name="config_enableLockScreenTranslucentDecor" />
   <java-symbol type="bool" name="config_enableTranslucentDecor" />
+  <java-symbol type="bool" name="config_lidControlsScreenLock" />
   <java-symbol type="bool" name="config_lidControlsSleep" />
   <java-symbol type="bool" name="config_lockDayNightMode" />
   <java-symbol type="bool" name="config_lockUiMode" />
diff --git a/core/tests/benchmarks/Android.mk b/core/tests/benchmarks/Android.mk
new file mode 100644
index 0000000..25181b5
--- /dev/null
+++ b/core/tests/benchmarks/Android.mk
@@ -0,0 +1,30 @@
+# -*- mode: makefile -*-
+# Copyright (C) 2015 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+# build framework base core benchmarks
+# ============================================================
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := frameworks-base-core-benchmarks
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+LOCAL_SRC_FILES := $(call all-java-files-under, src/)
+
+LOCAL_JAVA_LIBRARIES := \
+  caliper-api-target
+
+include $(BUILD_JAVA_LIBRARY)
diff --git a/core/tests/benchmarks/src/android/content/res/ResourcesBenchmark.java b/core/tests/benchmarks/src/android/content/res/ResourcesBenchmark.java
index 3638473..426b0dc 100644
--- a/core/tests/benchmarks/src/android/content/res/ResourcesBenchmark.java
+++ b/core/tests/benchmarks/src/android/content/res/ResourcesBenchmark.java
@@ -20,11 +20,13 @@
 import android.util.Xml;
 
 import com.android.internal.R;
-import com.google.caliper.SimpleBenchmark;
 
 import org.xmlpull.v1.XmlPullParser;
 
-public class ResourcesBenchmark extends SimpleBenchmark {
+import com.google.caliper.AfterExperiment;
+import com.google.caliper.BeforeExperiment;
+
+public class ResourcesBenchmark {
 
     private AssetManager mAsset;
     private Resources mRes;
@@ -34,7 +36,7 @@
     private int mIntegerId;
     private int mLayoutId;
 
-    @Override
+    @BeforeExperiment
     protected void setUp() {
         mAsset = new AssetManager();
         mAsset.addAssetPath("/system/framework/framework-res.apk");
@@ -46,7 +48,7 @@
         mLayoutId = mRes.getIdentifier("two_line_list_item", "layout", "android");
     }
 
-    @Override
+    @AfterExperiment
     protected void tearDown() {
         mAsset.close();
     }
diff --git a/core/tests/benchmarks/src/android/net/NetworkStatsBenchmark.java b/core/tests/benchmarks/src/android/net/NetworkStatsBenchmark.java
index 1a50432..1b65603 100644
--- a/core/tests/benchmarks/src/android/net/NetworkStatsBenchmark.java
+++ b/core/tests/benchmarks/src/android/net/NetworkStatsBenchmark.java
@@ -16,10 +16,10 @@
 
 package android.net;
 
+import com.google.caliper.BeforeExperiment;
 import com.google.caliper.Param;
-import com.google.caliper.SimpleBenchmark;
 
-public class NetworkStatsBenchmark extends SimpleBenchmark {
+public class NetworkStatsBenchmark {
     private static final String UNDERLYING_IFACE = "wlan0";
     private static final String TUN_IFACE = "tun0";
     private static final int TUN_UID = 999999999;
@@ -28,10 +28,8 @@
     private int mSize;
     private NetworkStats mNetworkStats;
 
-    @Override
+    @BeforeExperiment
     protected void setUp() throws Exception {
-        super.setUp();
-
         mNetworkStats = new NetworkStats(0, mSize + 2);
         int uid = 0;
         NetworkStats.Entry recycle = new NetworkStats.Entry();
diff --git a/core/tests/benchmarks/src/android/net/TrafficStatsBenchmark.java b/core/tests/benchmarks/src/android/net/TrafficStatsBenchmark.java
index 5a29adc..09de412 100644
--- a/core/tests/benchmarks/src/android/net/TrafficStatsBenchmark.java
+++ b/core/tests/benchmarks/src/android/net/TrafficStatsBenchmark.java
@@ -16,9 +16,7 @@
 
 package android.net;
 
-import com.google.caliper.SimpleBenchmark;
-
-public class TrafficStatsBenchmark extends SimpleBenchmark {
+public class TrafficStatsBenchmark {
     public void timeGetUidRxBytes(int reps) {
         for (int i = 0; i < reps; i++) {
             TrafficStats.getUidRxBytes(android.os.Process.myUid());
diff --git a/core/tests/benchmarks/src/android/os/ParcelArrayBenchmark.java b/core/tests/benchmarks/src/android/os/ParcelArrayBenchmark.java
index 21cfb09..eff8c8e 100644
--- a/core/tests/benchmarks/src/android/os/ParcelArrayBenchmark.java
+++ b/core/tests/benchmarks/src/android/os/ParcelArrayBenchmark.java
@@ -16,10 +16,11 @@
 
 package android.os;
 
+import com.google.caliper.AfterExperiment;
+import com.google.caliper.BeforeExperiment;
 import com.google.caliper.Param;
-import com.google.caliper.SimpleBenchmark;
 
-public class ParcelArrayBenchmark extends SimpleBenchmark {
+public class ParcelArrayBenchmark {
 
     @Param({ "1", "10", "100", "1000" })
     private int mSize;
@@ -34,7 +35,7 @@
     private Parcel mIntParcel;
     private Parcel mLongParcel;
 
-    @Override
+    @BeforeExperiment
     protected void setUp() {
         mWriteParcel = Parcel.obtain();
 
@@ -50,7 +51,7 @@
         mLongParcel.writeLongArray(mLongArray);
     }
 
-    @Override
+    @AfterExperiment
     protected void tearDown() {
         mWriteParcel.recycle();
         mWriteParcel = null;
@@ -118,5 +119,4 @@
             mLongParcel.readLongArray(mLongArray);
         }
     }
-
 }
diff --git a/core/tests/benchmarks/src/android/os/ParcelBenchmark.java b/core/tests/benchmarks/src/android/os/ParcelBenchmark.java
index 6a7b7c89..4bd2d00 100644
--- a/core/tests/benchmarks/src/android/os/ParcelBenchmark.java
+++ b/core/tests/benchmarks/src/android/os/ParcelBenchmark.java
@@ -16,18 +16,19 @@
 
 package android.os;
 
-import com.google.caliper.SimpleBenchmark;
+import com.google.caliper.AfterExperiment;
+import com.google.caliper.BeforeExperiment;
 
-public class ParcelBenchmark extends SimpleBenchmark {
+public class ParcelBenchmark {
 
     private Parcel mParcel;
 
-    @Override
+    @BeforeExperiment
     protected void setUp() {
         mParcel = Parcel.obtain();
     }
 
-    @Override
+    @AfterExperiment
     protected void tearDown() {
         mParcel.recycle();
         mParcel = null;
diff --git a/core/tests/benchmarks/src/android/os/StrictModeBenchmark.java b/core/tests/benchmarks/src/android/os/StrictModeBenchmark.java
index 41af3820..a110906 100644
--- a/core/tests/benchmarks/src/android/os/StrictModeBenchmark.java
+++ b/core/tests/benchmarks/src/android/os/StrictModeBenchmark.java
@@ -18,9 +18,7 @@
 
 import android.os.StrictMode.ThreadPolicy;
 
-import com.google.caliper.SimpleBenchmark;
-
-public class StrictModeBenchmark extends SimpleBenchmark {
+public class StrictModeBenchmark {
 
     private ThreadPolicy mOff = new ThreadPolicy.Builder().build();
     private ThreadPolicy mOn = new ThreadPolicy.Builder().detectAll().build();
diff --git a/core/tests/benchmarks/src/android/util/FloatMathBenchmark.java b/core/tests/benchmarks/src/android/util/FloatMathBenchmark.java
index 2858128..028dd1d 100644
--- a/core/tests/benchmarks/src/android/util/FloatMathBenchmark.java
+++ b/core/tests/benchmarks/src/android/util/FloatMathBenchmark.java
@@ -15,13 +15,9 @@
  */
 package android.util;
 
-import com.google.caliper.Param;
-import com.google.caliper.Runner;
-import com.google.caliper.SimpleBenchmark;
-
 import android.util.FloatMath;
 
-public class FloatMathBenchmark extends SimpleBenchmark {
+public class FloatMathBenchmark {
 
     public float timeFloatMathCeil(int reps) {
         // Keep an answer so we don't optimize the method call away.
@@ -112,5 +108,4 @@
         }
         return f;
     }
-
 }
diff --git a/core/tests/benchmarks/src/com/android/internal/net/NetworkStatsFactoryBenchmark.java b/core/tests/benchmarks/src/com/android/internal/net/NetworkStatsFactoryBenchmark.java
index 2174be5..e62fbd6 100644
--- a/core/tests/benchmarks/src/com/android/internal/net/NetworkStatsFactoryBenchmark.java
+++ b/core/tests/benchmarks/src/com/android/internal/net/NetworkStatsFactoryBenchmark.java
@@ -18,29 +18,31 @@
 
 import android.net.NetworkStats;
 import android.os.SystemClock;
-
-import com.google.caliper.SimpleBenchmark;
-
+import com.google.caliper.AfterExperiment;
+import com.google.caliper.BeforeExperiment;
 import java.io.File;
 
-public class NetworkStatsFactoryBenchmark extends SimpleBenchmark {
+public class NetworkStatsFactoryBenchmark {
     private File mStats;
 
     // TODO: consider staging stats file with different number of rows
 
-    @Override
+    @BeforeExperiment
     protected void setUp() {
         mStats = new File("/proc/net/xt_qtaguid/stats");
     }
 
-    @Override
+    @AfterExperiment
     protected void tearDown() {
         mStats = null;
     }
 
     public void timeReadNetworkStatsDetailJava(int reps) throws Exception {
         for (int i = 0; i < reps; i++) {
-            NetworkStatsFactory.javaReadNetworkStatsDetail(mStats, NetworkStats.UID_ALL);
+            NetworkStatsFactory.javaReadNetworkStatsDetail(mStats, NetworkStats.UID_ALL,
+                    // Looks like this was broken by change d0c5b9abed60b7bc056d026bf0f2b2235410fb70
+                    // Fixed compilation problem but needs addressing properly.
+                    new String[0], 999);
         }
     }
 
@@ -48,7 +50,10 @@
         for (int i = 0; i < reps; i++) {
             final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
             NetworkStatsFactory.nativeReadNetworkStatsDetail(
-                    stats, mStats.getAbsolutePath(), NetworkStats.UID_ALL);
+                    stats, mStats.getAbsolutePath(), NetworkStats.UID_ALL,
+                    // Looks like this was broken by change d0c5b9abed60b7bc056d026bf0f2b2235410fb70
+                    // Fixed compilation problem but needs addressing properly.
+                    new String[0], 999);
         }
     }
 }
diff --git a/core/tests/benchmarks/src/com/android/internal/util/IndentingPrintWriterBenchmark.java b/core/tests/benchmarks/src/com/android/internal/util/IndentingPrintWriterBenchmark.java
index 34c73e8..1112d5c 100644
--- a/core/tests/benchmarks/src/com/android/internal/util/IndentingPrintWriterBenchmark.java
+++ b/core/tests/benchmarks/src/com/android/internal/util/IndentingPrintWriterBenchmark.java
@@ -17,15 +17,15 @@
 package com.android.internal.util;
 
 import com.google.android.collect.Lists;
-import com.google.caliper.SimpleBenchmark;
-
+import com.google.caliper.AfterExperiment;
+import com.google.caliper.BeforeExperiment;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 
-public class IndentingPrintWriterBenchmark extends SimpleBenchmark {
+public class IndentingPrintWriterBenchmark {
 
     private PrintWriter mDirect;
     private IndentingPrintWriter mIndenting;
@@ -33,7 +33,7 @@
     private Node mSimple;
     private Node mComplex;
 
-    @Override
+    @BeforeExperiment
     protected void setUp() throws IOException {
         final FileOutputStream os = new FileOutputStream(new File("/dev/null"));
         mDirect = new PrintWriter(os);
@@ -49,7 +49,7 @@
                 manyChildren);
     }
 
-    @Override
+    @AfterExperiment
     protected void tearDown() {
         mIndenting.close();
         mIndenting = null;
diff --git a/keystore/java/android/security/IKeyChainService.aidl b/keystore/java/android/security/IKeyChainService.aidl
index 20c94c5..cfcb4e0 100644
--- a/keystore/java/android/security/IKeyChainService.aidl
+++ b/keystore/java/android/security/IKeyChainService.aidl
@@ -33,6 +33,7 @@
 
     // APIs used by DevicePolicyManager
     boolean installKeyPair(in byte[] privateKey, in byte[] userCert, String alias);
+    boolean removeKeyPair(String alias);
 
     // APIs used by Settings
     boolean deleteCaCertificate(String alias);
diff --git a/libs/hwui/Android.mk b/libs/hwui/Android.mk
index d98497b..0d1ee46 100644
--- a/libs/hwui/Android.mk
+++ b/libs/hwui/Android.mk
@@ -90,6 +90,9 @@
     protos/hwui.proto
 
 hwui_test_common_src_files := \
+    $(call all-cpp-files-under, tests/common/scenes) \
+    tests/common/TestContext.cpp \
+    tests/common/TestScene.cpp \
     tests/common/TestUtils.cpp
 
 hwui_cflags := \
@@ -259,12 +262,9 @@
 
 LOCAL_SRC_FILES += \
     $(hwui_test_common_src_files) \
-    tests/macrobench/TestContext.cpp \
     tests/macrobench/TestSceneRunner.cpp \
     tests/macrobench/main.cpp
 
-LOCAL_SRC_FILES += $(call all-cpp-files-under, tests/common/scenes)
-
 include $(BUILD_EXECUTABLE)
 
 # ------------------------
diff --git a/libs/hwui/tests/macrobench/TestContext.cpp b/libs/hwui/tests/common/TestContext.cpp
similarity index 98%
rename from libs/hwui/tests/macrobench/TestContext.cpp
rename to libs/hwui/tests/common/TestContext.cpp
index ba763a8..146e735 100644
--- a/libs/hwui/tests/macrobench/TestContext.cpp
+++ b/libs/hwui/tests/common/TestContext.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "TestContext.h"
+#include "tests/common/TestContext.h"
 
 namespace android {
 namespace uirenderer {
diff --git a/libs/hwui/tests/macrobench/TestContext.h b/libs/hwui/tests/common/TestContext.h
similarity index 100%
rename from libs/hwui/tests/macrobench/TestContext.h
rename to libs/hwui/tests/common/TestContext.h
diff --git a/libs/hwui/tests/common/TestScene.cpp b/libs/hwui/tests/common/TestScene.cpp
new file mode 100644
index 0000000..02bcd47
--- /dev/null
+++ b/libs/hwui/tests/common/TestScene.cpp
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "tests/common/TestScene.h"
+
+namespace android {
+namespace uirenderer {
+namespace test {
+
+// Not a static global because we need to force the map to be constructed
+// before we try to add things to it.
+std::unordered_map<std::string, TestScene::Info>& TestScene::testMap() {
+    static std::unordered_map<std::string, TestScene::Info> testMap;
+    return testMap;
+}
+
+void TestScene::registerScene(const TestScene::Info& info) {
+    testMap()[info.name] = info;
+}
+
+} /* namespace test */
+} /* namespace uirenderer */
+} /* namespace android */
diff --git a/libs/hwui/tests/common/TestScene.h b/libs/hwui/tests/common/TestScene.h
index b5d8954..df8d194 100644
--- a/libs/hwui/tests/common/TestScene.h
+++ b/libs/hwui/tests/common/TestScene.h
@@ -16,6 +16,9 @@
 #ifndef TESTS_TESTSCENE_H
 #define TESTS_TESTSCENE_H
 
+#include <string>
+#include <unordered_map>
+
 namespace android {
 namespace uirenderer {
 class RenderNode;
@@ -32,9 +35,40 @@
 
 class TestScene {
 public:
+    struct Options {
+        int count = 0;
+    };
+
+    template <class T>
+    static test::TestScene* simpleCreateScene(const TestScene::Options&) {
+        return new T();
+    }
+
+    typedef test::TestScene* (*CreateScene)(const TestScene::Options&);
+
+    struct Info {
+        std::string name;
+        std::string description;
+        CreateScene createScene;
+    };
+
+    class Registrar {
+    public:
+        Registrar(const TestScene::Info& info) {
+            TestScene::registerScene(info);
+        }
+    private:
+        Registrar() = delete;
+        Registrar(const Registrar&) = delete;
+        Registrar& operator=(const Registrar&) = delete;
+    };
+
     virtual ~TestScene() {}
     virtual void createContent(int width, int height, TestCanvas& renderer) = 0;
     virtual void doFrame(int frameNr) = 0;
+
+    static std::unordered_map<std::string, Info>& testMap();
+    static void registerScene(const Info& info);
 };
 
 } // namespace test
diff --git a/libs/hwui/tests/common/scenes/HwLayerAnimation.cpp b/libs/hwui/tests/common/scenes/HwLayerAnimation.cpp
index e316eca..c212df4 100644
--- a/libs/hwui/tests/common/scenes/HwLayerAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/HwLayerAnimation.cpp
@@ -18,11 +18,11 @@
 
 class HwLayerAnimation;
 
-static Benchmark _HwLayer(BenchmarkInfo{
+static TestScene::Registrar _HwLayer(TestScene::Info{
     "hwlayer",
     "A nested pair of nodes with LAYER_TYPE_HARDWARE set on each. "
     "Tests the hardware layer codepath.",
-    simpleCreateScene<HwLayerAnimation>
+    TestScene::simpleCreateScene<HwLayerAnimation>
 });
 
 class HwLayerAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/ListViewAnimation.cpp b/libs/hwui/tests/common/scenes/ListViewAnimation.cpp
index 6c64a32..43e247e 100644
--- a/libs/hwui/tests/common/scenes/ListViewAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/ListViewAnimation.cpp
@@ -21,11 +21,11 @@
 
 class ListViewAnimation;
 
-static Benchmark _ListView(BenchmarkInfo{
+static TestScene::Registrar _ListView(TestScene::Info{
     "listview",
     "A mock ListView of scrolling content. Doesn't re-bind/re-record views as they are recycled, so"
     "won't upload much content (either glyphs, or bitmaps).",
-    simpleCreateScene<ListViewAnimation>
+    TestScene::simpleCreateScene<ListViewAnimation>
 });
 
 class ListViewAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/OvalAnimation.cpp b/libs/hwui/tests/common/scenes/OvalAnimation.cpp
index 936aba1..082c628 100644
--- a/libs/hwui/tests/common/scenes/OvalAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/OvalAnimation.cpp
@@ -18,10 +18,10 @@
 
 class OvalAnimation;
 
-static Benchmark _Oval(BenchmarkInfo{
+static TestScene::Registrar _Oval(TestScene::Info{
     "oval",
     "Draws 1 oval.",
-    simpleCreateScene<OvalAnimation>
+    TestScene::simpleCreateScene<OvalAnimation>
 });
 
 class OvalAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/PartialDamageAnimation.cpp b/libs/hwui/tests/common/scenes/PartialDamageAnimation.cpp
index c31ddd1..84265a4 100644
--- a/libs/hwui/tests/common/scenes/PartialDamageAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/PartialDamageAnimation.cpp
@@ -18,12 +18,12 @@
 
 class PartialDamageAnimation;
 
-static Benchmark _PartialDamage(BenchmarkInfo{
+static TestScene::Registrar _PartialDamage(TestScene::Info{
     "partialdamage",
     "Tests the partial invalidation path. Draws a grid of rects and animates 1 "
     "of them, should be low CPU & GPU load if EGL_EXT_buffer_age or "
     "EGL_KHR_partial_update is supported by the device & are enabled in hwui.",
-    simpleCreateScene<PartialDamageAnimation>
+    TestScene::simpleCreateScene<PartialDamageAnimation>
 });
 
 class PartialDamageAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/RecentsAnimation.cpp b/libs/hwui/tests/common/scenes/RecentsAnimation.cpp
index 5d4ef96..6509edd 100644
--- a/libs/hwui/tests/common/scenes/RecentsAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/RecentsAnimation.cpp
@@ -19,11 +19,11 @@
 
 class RecentsAnimation;
 
-static Benchmark _Recents(BenchmarkInfo{
+static TestScene::Registrar _Recents(TestScene::Info{
     "recents",
     "A recents-like scrolling list of textures. "
     "Consists of updating a texture every frame",
-    simpleCreateScene<RecentsAnimation>
+    TestScene::simpleCreateScene<RecentsAnimation>
 });
 
 class RecentsAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/RectGridAnimation.cpp b/libs/hwui/tests/common/scenes/RectGridAnimation.cpp
index a1f04d6..a9293ab 100644
--- a/libs/hwui/tests/common/scenes/RectGridAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/RectGridAnimation.cpp
@@ -19,11 +19,11 @@
 
 class RectGridAnimation;
 
-static Benchmark _RectGrid(BenchmarkInfo{
+static TestScene::Registrar _RectGrid(TestScene::Info{
     "rectgrid",
     "A dense grid of 1x1 rects that should visually look like a single rect. "
     "Low CPU/GPU load.",
-    simpleCreateScene<RectGridAnimation>
+    TestScene::simpleCreateScene<RectGridAnimation>
 });
 
 class RectGridAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/SaveLayerAnimation.cpp b/libs/hwui/tests/common/scenes/SaveLayerAnimation.cpp
index c73e97b..78fcd8b 100644
--- a/libs/hwui/tests/common/scenes/SaveLayerAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/SaveLayerAnimation.cpp
@@ -18,11 +18,11 @@
 
 class SaveLayerAnimation;
 
-static Benchmark _SaveLayer(BenchmarkInfo{
+static TestScene::Registrar _SaveLayer(TestScene::Info{
     "savelayer",
     "A nested pair of clipped saveLayer operations. "
     "Tests the clipped saveLayer codepath. Draws content into offscreen buffers and back again.",
-    simpleCreateScene<SaveLayerAnimation>
+    TestScene::simpleCreateScene<SaveLayerAnimation>
 });
 
 class SaveLayerAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/ShadowGrid2Animation.cpp b/libs/hwui/tests/common/scenes/ShadowGrid2Animation.cpp
index 26c86aa..d3249b8 100644
--- a/libs/hwui/tests/common/scenes/ShadowGrid2Animation.cpp
+++ b/libs/hwui/tests/common/scenes/ShadowGrid2Animation.cpp
@@ -18,11 +18,11 @@
 
 class ShadowGrid2Animation;
 
-static Benchmark _ShadowGrid2(BenchmarkInfo{
+static TestScene::Registrar _ShadowGrid2(TestScene::Info{
     "shadowgrid2",
     "A dense grid of rounded rects that cast a shadow. This is a higher CPU load "
     "variant of shadowgrid. Very high CPU load, high GPU load.",
-    simpleCreateScene<ShadowGrid2Animation>
+    TestScene::simpleCreateScene<ShadowGrid2Animation>
 });
 
 class ShadowGrid2Animation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/ShadowGridAnimation.cpp b/libs/hwui/tests/common/scenes/ShadowGridAnimation.cpp
index ee3c590..5ffedf0 100644
--- a/libs/hwui/tests/common/scenes/ShadowGridAnimation.cpp
+++ b/libs/hwui/tests/common/scenes/ShadowGridAnimation.cpp
@@ -18,11 +18,11 @@
 
 class ShadowGridAnimation;
 
-static Benchmark _ShadowGrid(BenchmarkInfo{
+static TestScene::Registrar _ShadowGrid(TestScene::Info{
     "shadowgrid",
     "A grid of rounded rects that cast a shadow. Simplified scenario of an "
     "Android TV-style launcher interface. High CPU/GPU load.",
-    simpleCreateScene<ShadowGridAnimation>
+    TestScene::simpleCreateScene<ShadowGridAnimation>
 });
 
 class ShadowGridAnimation : public TestScene {
diff --git a/libs/hwui/tests/common/scenes/TestSceneBase.h b/libs/hwui/tests/common/scenes/TestSceneBase.h
index 8a24149..ac78124 100644
--- a/libs/hwui/tests/common/scenes/TestSceneBase.h
+++ b/libs/hwui/tests/common/scenes/TestSceneBase.h
@@ -19,8 +19,7 @@
 #include "DisplayListCanvas.h"
 #include "RecordingCanvas.h"
 #include "RenderNode.h"
-#include "tests/macrobench/Benchmark.h"
-#include "tests/macrobench/TestContext.h"
+#include "tests/common/TestContext.h"
 #include "tests/common/TestScene.h"
 #include "tests/common/TestUtils.h"
 
diff --git a/libs/hwui/tests/macrobench/Benchmark.h b/libs/hwui/tests/macrobench/Benchmark.h
deleted file mode 100644
index aad8eb3..0000000
--- a/libs/hwui/tests/macrobench/Benchmark.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef TESTS_BENCHMARK_H
-#define TESTS_BENCHMARK_H
-
-#include "tests/common/TestScene.h"
-
-#include <string>
-#include <vector>
-
-namespace android {
-namespace uirenderer {
-
-struct BenchmarkOptions {
-    int count;
-};
-
-typedef test::TestScene* (*CreateScene)(const BenchmarkOptions&);
-
-template <class T>
-test::TestScene* simpleCreateScene(const BenchmarkOptions&) {
-    return new T();
-}
-
-struct BenchmarkInfo {
-    std::string name;
-    std::string description;
-    CreateScene createScene;
-};
-
-class Benchmark {
-public:
-    Benchmark(const BenchmarkInfo& info) {
-        registerBenchmark(info);
-    }
-
-private:
-    Benchmark() = delete;
-    Benchmark(const Benchmark&) = delete;
-    Benchmark& operator=(const Benchmark&) = delete;
-
-    static void registerBenchmark(const BenchmarkInfo& info);
-};
-
-} /* namespace uirenderer */
-} /* namespace android */
-
-#endif /* TESTS_BENCHMARK_H */
diff --git a/libs/hwui/tests/macrobench/TestSceneRunner.cpp b/libs/hwui/tests/macrobench/TestSceneRunner.cpp
index 1e1c6a1..8261220 100644
--- a/libs/hwui/tests/macrobench/TestSceneRunner.cpp
+++ b/libs/hwui/tests/macrobench/TestSceneRunner.cpp
@@ -15,9 +15,9 @@
  */
 
 #include "AnimationContext.h"
-#include "Benchmark.h"
 #include "RenderNode.h"
-#include "TestContext.h"
+#include "tests/common/TestContext.h"
+#include "tests/common/TestScene.h"
 #include "tests/common/scenes/TestSceneBase.h"
 #include "renderthread/RenderProxy.h"
 #include "renderthread/RenderTask.h"
@@ -38,7 +38,7 @@
     }
 };
 
-void run(const BenchmarkInfo& info, const BenchmarkOptions& opts) {
+void run(const TestScene::Info& info, const TestScene::Options& opts) {
     // Switch to the real display
     gDisplay = getBuiltInDisplay();
 
diff --git a/libs/hwui/tests/macrobench/main.cpp b/libs/hwui/tests/macrobench/main.cpp
index 48566e8..619713c 100644
--- a/libs/hwui/tests/macrobench/main.cpp
+++ b/libs/hwui/tests/macrobench/main.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "Benchmark.h"
+#include "tests/common/TestScene.h"
 
 #include "protos/hwui.pb.h"
 
@@ -27,23 +27,13 @@
 
 using namespace android;
 using namespace android::uirenderer;
-
-// Not a static global because we need to force the map to be constructed
-// before we try to add things to it.
-std::unordered_map<std::string, BenchmarkInfo>& testMap() {
-    static std::unordered_map<std::string, BenchmarkInfo> testMap;
-    return testMap;
-}
-
-void Benchmark::registerBenchmark(const BenchmarkInfo& info) {
-    testMap()[info.name] = info;
-}
+using namespace android::uirenderer::test;
 
 static int gFrameCount = 150;
 static int gRepeatCount = 1;
-static std::vector<BenchmarkInfo> gRunTests;
+static std::vector<TestScene::Info> gRunTests;
 
-void run(const BenchmarkInfo& info, const BenchmarkOptions& opts);
+void run(const TestScene::Info& info, const TestScene::Options& opts);
 
 static void printHelp() {
     printf("\
@@ -59,7 +49,7 @@
 
 static void listTests() {
     printf("Tests: \n");
-    for (auto&& test : testMap()) {
+    for (auto&& test : TestScene::testMap()) {
         auto&& info = test.second;
         const char* col1 = info.name.c_str();
         int dlen = info.description.length();
@@ -168,8 +158,8 @@
     if (optind < argc) {
         do {
             const char* test = argv[optind++];
-            auto pos = testMap().find(test);
-            if (pos == testMap().end()) {
+            auto pos = TestScene::testMap().find(test);
+            if (pos == TestScene::testMap().end()) {
                 fprintf(stderr, "Unknown test '%s'\n", test);
                 exit(EXIT_FAILURE);
             } else {
@@ -177,14 +167,14 @@
             }
         } while (optind < argc);
     } else {
-        gRunTests.push_back(testMap()["shadowgrid"]);
+        gRunTests.push_back(TestScene::testMap()["shadowgrid"]);
     }
 }
 
 int main(int argc, char* argv[]) {
     parseOptions(argc, argv);
 
-    BenchmarkOptions opts;
+    TestScene::Options opts;
     opts.count = gFrameCount;
     for (int i = 0; i < gRepeatCount; i++) {
         for (auto&& test : gRunTests) {
diff --git a/libs/hwui/tests/microbench/OpReordererBench.cpp b/libs/hwui/tests/microbench/OpReordererBench.cpp
index ac2b15c..6bfe5a9 100644
--- a/libs/hwui/tests/microbench/OpReordererBench.cpp
+++ b/libs/hwui/tests/microbench/OpReordererBench.cpp
@@ -23,6 +23,8 @@
 #include "OpReorderer.h"
 #include "RecordedOp.h"
 #include "RecordingCanvas.h"
+#include "tests/common/TestContext.h"
+#include "tests/common/TestScene.h"
 #include "tests/common/TestUtils.h"
 #include "Vector.h"
 #include "tests/microbench/MicroBench.h"
@@ -31,6 +33,8 @@
 
 using namespace android;
 using namespace android::uirenderer;
+using namespace android::uirenderer::renderthread;
+using namespace android::uirenderer::test;
 
 const LayerUpdateQueue sEmptyLayerUpdateQueue;
 const Vector3 sLightCenter = {100, 100, 100};
@@ -71,7 +75,7 @@
 
 BENCHMARK_NO_ARG(BM_OpReorderer_deferAndRender);
 void BM_OpReorderer_deferAndRender::Run(int iters) {
-    TestUtils::runOnRenderThread([this, iters](renderthread::RenderThread& thread) {
+    TestUtils::runOnRenderThread([this, iters](RenderThread& thread) {
         auto nodes = createTestNodeList();
         BakedOpRenderer::LightInfo lightInfo = {50.0f, 128, 128 };
 
@@ -90,3 +94,67 @@
         StopBenchmarkTiming();
     });
 }
+
+static std::vector<sp<RenderNode>> getSyncedSceneNodes(const char* sceneName) {
+    gDisplay = getBuiltInDisplay(); // switch to real display if present
+
+    TestContext testContext;
+    TestScene::Options opts;
+    std::unique_ptr<TestScene> scene(TestScene::testMap()[sceneName].createScene(opts));
+
+    sp<RenderNode> rootNode = TestUtils::createNode(0, 0, gDisplay.w, gDisplay.h,
+                [&scene](RenderProperties& props, TestCanvas& canvas) {
+            scene->createContent(gDisplay.w, gDisplay.h, canvas);
+    });
+
+    TestUtils::syncHierarchyPropertiesAndDisplayList(rootNode);
+    std::vector<sp<RenderNode>> nodes;
+    nodes.emplace_back(rootNode);
+    return nodes;
+}
+
+static void benchDeferScene(testing::Benchmark& benchmark, int iters, const char* sceneName) {
+    auto nodes = getSyncedSceneNodes(sceneName);
+    benchmark.StartBenchmarkTiming();
+    for (int i = 0; i < iters; i++) {
+        OpReorderer reorderer(sEmptyLayerUpdateQueue,
+                SkRect::MakeWH(gDisplay.w, gDisplay.h), gDisplay.w, gDisplay.h,
+                nodes, sLightCenter);
+        MicroBench::DoNotOptimize(&reorderer);
+    }
+    benchmark.StopBenchmarkTiming();
+}
+
+static void benchDeferAndRenderScene(testing::Benchmark& benchmark,
+        int iters, const char* sceneName) {
+    TestUtils::runOnRenderThread([&benchmark, iters, sceneName](RenderThread& thread) {
+        auto nodes = getSyncedSceneNodes(sceneName);
+        BakedOpRenderer::LightInfo lightInfo = {50.0f, 128, 128 }; // TODO!
+
+        RenderState& renderState = thread.renderState();
+        Caches& caches = Caches::getInstance();
+
+        benchmark.StartBenchmarkTiming();
+        for (int i = 0; i < iters; i++) {
+            OpReorderer reorderer(sEmptyLayerUpdateQueue,
+                    SkRect::MakeWH(gDisplay.w, gDisplay.h), gDisplay.w, gDisplay.h,
+                    nodes, sLightCenter);
+
+            BakedOpRenderer renderer(caches, renderState, true, lightInfo);
+            reorderer.replayBakedOps<BakedOpDispatcher>(renderer);
+            MicroBench::DoNotOptimize(&renderer);
+        }
+        benchmark.StopBenchmarkTiming();
+    });
+}
+
+BENCHMARK_NO_ARG(BM_OpReorderer_listview_defer);
+void BM_OpReorderer_listview_defer::Run(int iters) {
+    benchDeferScene(*this, iters, "listview");
+}
+
+BENCHMARK_NO_ARG(BM_OpReorderer_listview_deferAndRender);
+void BM_OpReorderer_listview_deferAndRender::Run(int iters) {
+    benchDeferAndRenderScene(*this, iters, "listview");
+}
+
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 2f79adf..2e65656 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -180,13 +180,6 @@
             </intent-filter>
         </receiver>
 
-        <receiver android:name=".qs.tiles.HotspotTile$APChangedReceiver"
-                androidprv:systemUserOnly="true">
-            <intent-filter>
-                <action android:name="android.net.wifi.WIFI_AP_STATE_CHANGED" />
-            </intent-filter>
-        </receiver>
-
         <activity android:name=".tuner.TunerActivity"
                   android:enabled="false"
                   android:icon="@drawable/tuner"
diff --git a/packages/SystemUI/res/drawable/docked_divider_handle.xml b/packages/SystemUI/res/drawable/docked_divider_handle.xml
index ea32548..84c0343 100644
--- a/packages/SystemUI/res/drawable/docked_divider_handle.xml
+++ b/packages/SystemUI/res/drawable/docked_divider_handle.xml
@@ -17,6 +17,6 @@
         android:shape="rectangle">
     <size android:height="@dimen/docked_divider_handle_height"
         android:width="@dimen/docked_divider_handle_width" />
-    <corners radius="1dp" />
+    <corners android:radius="1dp" />
     <solid android:color="@color/docked_divider_handle" />
 </shape>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/quick_header_bg.xml b/packages/SystemUI/res/drawable/quick_header_bg.xml
new file mode 100644
index 0000000..d45d673
--- /dev/null
+++ b/packages/SystemUI/res/drawable/quick_header_bg.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2015 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+
+<ripple xmlns:android="http://schemas.android.com/apk/res/android"
+    android:color="?android:attr/colorControlHighlight" >
+    <item android:drawable="@color/system_primary_color"/>
+</ripple>
diff --git a/packages/SystemUI/res/layout/docked_stack_divider.xml b/packages/SystemUI/res/layout/docked_stack_divider.xml
index 5f42856..22ed216 100644
--- a/packages/SystemUI/res/layout/docked_stack_divider.xml
+++ b/packages/SystemUI/res/layout/docked_stack_divider.xml
@@ -27,8 +27,6 @@
     <ImageButton
         style="@style/DockedDividerHandle"
         android:id="@+id/docked_divider_handle"
-        android:layout_height="48dp"
-        android:layout_width="48dp"
         android:background="@null"
         android:src="@drawable/docked_divider_handle"/>
 
diff --git a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
index cc35c51c..8124eb7 100644
--- a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
+++ b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
@@ -25,9 +25,10 @@
     android:layout_gravity="@integer/notification_panel_layout_gravity"
     android:paddingStart="@dimen/notification_side_padding"
     android:paddingEnd="@dimen/notification_side_padding"
+    android:clipChildren="false"
+    android:clipToPadding="false"
     android:baselineAligned="false"
-    android:elevation="4dp"
-    android:background="@drawable/notification_header_bg"
+    android:background="@drawable/quick_header_bg"
     android:clickable="true"
     android:focusable="true"
     >
@@ -35,9 +36,11 @@
     <com.android.systemui.qs.QuickQSPanel
         android:id="@+id/quick_qs_panel"
         android:background="#0000"
-        android:layout_width="144dp"
+        android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_alignParentEnd="true"
+        android:clipChildren="false"
+        android:clipToPadding="false"
         android:layout_marginEnd="12dp" />
 
     <LinearLayout
@@ -49,7 +52,7 @@
         android:clipToPadding="false"
         android:orientation="horizontal"
         android:layout_alignParentEnd="true"
-        android:layout_marginEnd="10dp">
+        android:layout_marginEnd="12dp">
 
         <com.android.systemui.statusbar.AlphaOptimizedFrameLayout
             android:id="@+id/settings_button_container"
diff --git a/packages/SystemUI/res/values-land/styles.xml b/packages/SystemUI/res/values-land/styles.xml
index dd396d9..96d8fb8 100644
--- a/packages/SystemUI/res/values-land/styles.xml
+++ b/packages/SystemUI/res/values-land/styles.xml
@@ -27,6 +27,8 @@
 
     <style name="DockedDividerHandle">
         <item name="android:layout_gravity">center_vertical</item>
+        <item name="android:layout_width">48dp</item>
+        <item name="android:layout_height">64dp</item>
     </style>
 
 </resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 086e9f4..25ff6b1 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -173,7 +173,7 @@
     <dimen name="borderless_button_radius">2dp</dimen>
 
     <!-- How far the expanded QS panel peeks from the header in collapsed state. -->
-    <dimen name="qs_peek_height">8dp</dimen>
+    <dimen name="qs_peek_height">0dp</dimen>
 
     <!-- Zen mode panel: condition item button padding -->
     <dimen name="zen_mode_condition_detail_button_padding">8dp</dimen>
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 2fd0fe5..47ad6dc 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -311,6 +311,8 @@
 
     <style name="DockedDividerHandle">
         <item name="android:layout_gravity">center_horizontal</item>
+        <item name="android:layout_width">64dp</item>
+        <item name="android:layout_height">48dp</item>
     </style>
 
 </resources>
diff --git a/packages/SystemUI/src/com/android/systemui/QSQuickTileView.java b/packages/SystemUI/src/com/android/systemui/QSQuickTileView.java
deleted file mode 100644
index 3362650..0000000
--- a/packages/SystemUI/src/com/android/systemui/QSQuickTileView.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui;
-
-import android.content.Context;
-import android.view.View;
-import android.widget.ImageView;
-import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.QSTileBaseView;
-
-public class QSQuickTileView extends QSTileBaseView {
-
-    private final int mPadding;
-    private final ImageView mIcon;
-
-    public QSQuickTileView(Context context) {
-        super(context);
-        mPadding = context.getResources().getDimensionPixelSize(R.dimen.qs_quick_tile_padding);
-        mIcon = createIcon();
-        addView(mIcon);
-    }
-
-    protected ImageView createIcon() {
-        final ImageView icon = new ImageView(mContext);
-        icon.setId(android.R.id.icon);
-        icon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
-        return icon;
-    }
-
-    @Override
-    public void init(OnClickListener click, OnClickListener clickSecondary,
-                     OnLongClickListener longClick) {
-        setClickable(true);
-        setOnClickListener(click);
-    }
-
-    @Override
-    protected void handleStateChanged(QSTile.State state) {
-        mIcon.setImageDrawable(state.icon.getDrawable(getContext()));
-        setContentDescription(state.contentDescription);
-    }
-
-    @Override
-    public boolean setType(int type) {
-        return false;
-    }
-
-    @Override
-    public View updateAccessibilityOrder(View previousView) {
-        return this;
-    }
-
-    @Override
-    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
-        mIcon.measure(exactly(getMeasuredWidth() - 2 * mPadding),
-                exactly(getMeasuredHeight() - 2 * mPadding));
-    }
-
-    @Override
-    protected void onLayout(boolean changed, int l, int t, int r, int b) {
-        layout(mIcon, mPadding, mPadding);
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
index 0e4a4e5..ca4a03a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
@@ -73,11 +73,6 @@
     }
 
     @Override
-    public void setTileVisibility(TileRecord tile, int visibility) {
-        tile.tileView.setVisibility(visibility);
-    }
-
-    @Override
     public void addTile(TileRecord tile) {
         mTiles.add(tile);
         distributeTiles();
@@ -101,10 +96,6 @@
         final int NT = mTiles.size();
         for (int i = 0; i < NT; i++) {
             TileRecord tile = mTiles.get(i);
-            if (tile.tile.getTileType() == QSTileView.QS_TYPE_QUICK) {
-                // Don't show any quick tiles for now.
-                continue;
-            }
             if (mPages.get(index).isFull()) {
                 if (++index == mPages.size()) {
                     if (DEBUG) Log.d(TAG, "Adding page for " + tile.tile.getClass().getSimpleName());
@@ -178,7 +169,6 @@
 
         public TilePage(Context context, AttributeSet attrs) {
             super(context, attrs);
-            mAllowDual = false;
             updateResources();
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSIconView.java b/packages/SystemUI/src/com/android/systemui/qs/QSIconView.java
new file mode 100644
index 0000000..b56ad76
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSIconView.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.drawable.Animatable;
+import android.graphics.drawable.Drawable;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import com.android.systemui.R;
+
+import java.util.Objects;
+
+public class QSIconView extends ViewGroup {
+
+    private final View mIcon;
+    private final int mIconSizePx;
+    private final int mTilePaddingBelowIconPx;
+
+    public QSIconView(Context context) {
+        super(context);
+
+        final Resources res = context.getResources();
+        mIconSizePx = res.getDimensionPixelSize(R.dimen.qs_tile_icon_size);
+        mTilePaddingBelowIconPx =  res.getDimensionPixelSize(R.dimen.qs_tile_padding_below_icon);
+
+        mIcon = createIcon();
+        addView(mIcon);
+    }
+
+    @Override
+    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+        final int w = MeasureSpec.getSize(widthMeasureSpec);
+        final int iconSpec = exactly(mIconSizePx);
+        mIcon.measure(MeasureSpec.makeMeasureSpec(w, getIconMeasureMode()), iconSpec);
+        setMeasuredDimension(w, mIcon.getMeasuredHeight() + mTilePaddingBelowIconPx);
+    }
+
+    @Override
+    protected void onLayout(boolean changed, int l, int t, int r, int b) {
+        final int w = getMeasuredWidth();
+        final int h = getMeasuredHeight();
+        int top = 0;
+        final int iconLeft = (w - mIcon.getMeasuredWidth()) / 2;
+        layout(mIcon, iconLeft, top);
+    }
+
+    public void setIcon(QSTile.State state) {
+        setIcon((ImageView) mIcon, state);
+    }
+
+    protected void setIcon(ImageView iv, QSTile.State state) {
+        if (!Objects.equals(state.icon, iv.getTag(R.id.qs_icon_tag))) {
+            Drawable d = state.icon != null ? state.icon.getDrawable(mContext) : null;
+            if (d != null && state.autoMirrorDrawable) {
+                d.setAutoMirrored(true);
+            }
+            iv.setImageDrawable(d);
+            iv.setTag(R.id.qs_icon_tag, state.icon);
+            if (d instanceof Animatable) {
+                Animatable a = (Animatable) d;
+                if (state.icon instanceof QSTile.AnimationIcon && !iv.isShown()) {
+                    a.stop(); // skip directly to end state
+                }
+            }
+        }
+
+    }
+
+    protected int getIconMeasureMode() {
+        return MeasureSpec.EXACTLY;
+    }
+
+    protected View createIcon() {
+        final ImageView icon = new ImageView(mContext);
+        icon.setId(android.R.id.icon);
+        icon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
+        return icon;
+    }
+
+    protected static int exactly(int size) {
+        return MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
+    }
+
+    protected static void layout(View child, int left, int top) {
+        child.layout(left, top, left + child.getMeasuredWidth(), top + child.getMeasuredHeight());
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
index bb2b8fc..5d3fbe2 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
@@ -298,19 +298,10 @@
         showDetail(show, r);
     }
 
-    private void showDetail(boolean show, Record r) {
+    protected void showDetail(boolean show, Record r) {
         mHandler.obtainMessage(H.SHOW_DETAIL, show ? 1 : 0, 0, r).sendToTarget();
     }
 
-    private void setTileVisibility(TileRecord record, int visibility) {
-        mHandler.obtainMessage(H.SET_TILE_VISIBILITY, visibility, 0, record).sendToTarget();
-    }
-
-    private void handleSetTileVisibility(TileRecord tile, int visibility) {
-        if (visibility == tile.tileView.getVisibility()) return;
-        mTileLayout.setTileVisibility(tile, visibility);
-    }
-
     public void setTiles(Collection<QSTile<?>> tiles) {
         for (TileRecord record : mRecords) {
             mTileLayout.removeTile(record);
@@ -325,16 +316,17 @@
     }
 
     private void drawTile(TileRecord r, QSTile.State state) {
-        final int visibility = state.visible ? VISIBLE : GONE;
-        setTileVisibility(r, visibility);
         r.tileView.onStateChanged(state);
     }
 
+    protected QSTileBaseView createTileView(QSTile<?> tile) {
+        return new QSTileView(mContext, tile.createTileView(mContext));
+    }
+
     protected void addTile(final QSTile<?> tile) {
         final TileRecord r = new TileRecord();
         r.tile = tile;
-        r.tileView = tile.createTileView(mContext);
-        r.tileView.setVisibility(View.GONE);
+        r.tileView = createTileView(tile);
         final QSTile.Callback callback = new QSTile.Callback() {
             @Override
             public void onStateChanged(QSTile.State state) {
@@ -369,13 +361,7 @@
         final View.OnClickListener click = new View.OnClickListener() {
             @Override
             public void onClick(View v) {
-                r.tile.click();
-            }
-        };
-        final View.OnClickListener clickSecondary = new View.OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                r.tile.secondaryClick();
+                onTileClick(r.tile);
             }
         };
         final View.OnLongClickListener longClick = new View.OnLongClickListener() {
@@ -396,7 +382,7 @@
                 return true;
             }
         };
-        r.tileView.init(click, clickSecondary, longClick);
+        r.tileView.init(click, longClick);
         r.tile.setListening(mListening);
         callback.onStateChanged(r.tile.getState());
         r.tile.refreshState();
@@ -407,6 +393,10 @@
         }
     }
 
+    protected void onTileClick(QSTile<?> tile) {
+        tile.click();
+    }
+
     public boolean isShowingDetail() {
         return mDetailRecord != null
                 || (mCustomizePanel != null && mCustomizePanel.isCustomizing());
@@ -429,7 +419,7 @@
         return mQsContainer.getMeasuredHeight();
     }
 
-    private void handleShowDetail(Record r, boolean show) {
+    protected void handleShowDetail(Record r, boolean show) {
         if (r instanceof TileRecord) {
             handleShowDetailTile((TileRecord) r, show);
         } else {
@@ -515,9 +505,7 @@
     private void logTiles() {
         for (int i = 0; i < mRecords.size(); i++) {
             TileRecord tileRecord = mRecords.get(i);
-            if (tileRecord.tile.getState().visible) {
-                MetricsLogger.visible(mContext, tileRecord.tile.getMetricsCategory());
-            }
+            MetricsLogger.visible(mContext, tileRecord.tile.getMetricsCategory());
         }
     }
 
@@ -554,13 +542,11 @@
         public void handleMessage(Message msg) {
             if (msg.what == SHOW_DETAIL) {
                 handleShowDetail((Record)msg.obj, msg.arg1 != 0);
-            } else if (msg.what == SET_TILE_VISIBILITY) {
-                handleSetTileVisibility((TileRecord) msg.obj, msg.arg1);
             }
         }
     }
 
-    private static class Record {
+    protected static class Record {
         View detailView;
         DetailAdapter detailAdapter;
         int x;
@@ -619,7 +605,6 @@
     public interface QSTileLayout {
         void addTile(TileRecord tile);
         void removeTile(TileRecord tile);
-        void setTileVisibility(TileRecord tile, int visibility);
         int getOffsetTop(TileRecord tile);
         void updateResources();
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTile.java b/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
index 7f45545..39f0c55 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
@@ -86,20 +86,12 @@
         mTileSpec = tileSpec;
     }
 
-    public int getTileType() {
-        return QSTileView.QS_TYPE_NORMAL;
-    }
-
-    public final boolean supportsDualTargets() {
-        return getTileType() == QSTileView.QS_TYPE_DUAL;
-    }
-
     public Host getHost() {
         return mHost;
     }
 
-    public QSTileBaseView createTileView(Context context) {
-        return new QSTileView(context);
+    public QSIconView createTileView(Context context) {
+        return new QSIconView(context);
     }
 
     public DetailAdapter getDetailAdapter() {
@@ -181,7 +173,8 @@
     }
 
     protected void handleSecondaryClick() {
-        // optional
+        // Default to normal click.
+        handleClick();
     }
 
     protected void handleLongClick() {
@@ -327,8 +320,10 @@
     public interface Host {
         void startActivityDismissingKeyguard(Intent intent);
         void startActivityDismissingKeyguard(PendingIntent intent);
+        void startRunnableDismissingKeyguard(Runnable runnable);
         void warn(String message, Throwable t);
         void collapsePanels();
+        void openPanels();
         Looper getLooper();
         Context getContext();
         Collection<QSTile<?>> getTiles();
@@ -345,6 +340,7 @@
         UserSwitcherController getUserSwitcherController();
         UserInfoController getUserInfoController();
         BatteryController getBatteryController();
+        void removeTile(String tileSpec);
 
         public interface Callback {
             void onTilesChanged();
@@ -451,7 +447,6 @@
     }
 
     public static class State {
-        public boolean visible;
         public Icon icon;
         public CharSequence label;
         public CharSequence contentDescription;
@@ -461,14 +456,12 @@
         public boolean copyTo(State other) {
             if (other == null) throw new IllegalArgumentException();
             if (!other.getClass().equals(getClass())) throw new IllegalArgumentException();
-            final boolean changed = other.visible != visible
-                    || !Objects.equals(other.icon, icon)
+            final boolean changed = !Objects.equals(other.icon, icon)
                     || !Objects.equals(other.label, label)
                     || !Objects.equals(other.contentDescription, contentDescription)
                     || !Objects.equals(other.autoMirrorDrawable, autoMirrorDrawable)
                     || !Objects.equals(other.dualLabelContentDescription,
                     dualLabelContentDescription);
-            other.visible = visible;
             other.icon = icon;
             other.label = label;
             other.contentDescription = contentDescription;
@@ -484,7 +477,6 @@
 
         protected StringBuilder toStringBuilder() {
             final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append('[');
-            sb.append("visible=").append(visible);
             sb.append(",icon=").append(icon);
             sb.append(",label=").append(label);
             sb.append(",contentDescription=").append(contentDescription);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java b/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java
index 72fc88d..68461f5 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTileBaseView.java
@@ -1,57 +1,112 @@
 /*
  * Copyright (C) 2015 The Android Open Source Project
  *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
-
 package com.android.systemui.qs;
 
 import android.content.Context;
+import android.content.res.TypedArray;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.RippleDrawable;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
-import android.util.AttributeSet;
 import android.view.View;
-import android.view.ViewGroup;
+import android.widget.LinearLayout;
+import com.android.systemui.R;
 
-public abstract class QSTileBaseView extends ViewGroup {
-
-    public static final int QS_TYPE_NORMAL = 0;
-    public static final int QS_TYPE_DUAL   = 1;
-    public static final int QS_TYPE_QUICK  = 2;
+public class QSTileBaseView extends LinearLayout {
 
     private final H mHandler = new H();
+    private QSIconView mIcon;
+    private RippleDrawable mRipple;
+    private Drawable mTileBackground;
 
-    public QSTileBaseView(Context context) {
+    public QSTileBaseView(Context context, QSIconView icon) {
         super(context);
+        mIcon = icon;
+        addView(mIcon);
+
+        mTileBackground = newTileBackground();
+        if (mTileBackground instanceof RippleDrawable) {
+            setRipple((RippleDrawable) mTileBackground);
+        }
+        setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
+        setBackground(mTileBackground);
+
+        // Default to Quick Tile padding, and QSTileView will specify its own padding.
+        int padding = context.getResources().getDimensionPixelSize(R.dimen.qs_quick_tile_padding);
+        setPadding(padding, padding, padding, padding);
     }
 
-    public QSTileBaseView(Context context, AttributeSet attrs) {
-        super(context, attrs);
+    private Drawable newTileBackground() {
+        final int[] attrs = new int[] { android.R.attr.selectableItemBackgroundBorderless };
+        final TypedArray ta = mContext.obtainStyledAttributes(attrs);
+        final Drawable d = ta.getDrawable(0);
+        ta.recycle();
+        return d;
     }
 
+    private void setRipple(RippleDrawable tileBackground) {
+        mRipple = tileBackground;
+        if (getWidth() != 0) {
+            updateRippleSize(getWidth(), getHeight());
+        }
+    }
+
+    private void updateRippleSize(int width, int height) {
+        // center the touch feedback on the center of the icon, and dial it down a bit
+        final int cx = width / 2;
+        final int cy = height / 2;
+        final int rad = (int)(mIcon.getHeight() * .85f);
+        mRipple.setHotspotBounds(cx - rad, cy - rad, cx + rad, cy + rad);
+    }
+
+    public void init(OnClickListener click, OnLongClickListener longClick) {
+        setClickable(true);
+        setOnClickListener(click);
+    }
+
+    @Override
+    protected void onLayout(boolean changed, int l, int t, int r, int b) {
+        super.onLayout(changed, l, t, r, b);
+        final int w = getMeasuredWidth();
+        final int h = getMeasuredHeight();
+
+        if (mRipple != null) {
+            updateRippleSize(w, h);
+        }
+    }
+
+    /**
+     * Update the accessibility order for this view.
+     *
+     * @param previousView the view which should be before this one
+     * @return the last view in this view which is accessible
+     */
+    public View updateAccessibilityOrder(View previousView) {
+        setAccessibilityTraversalAfter(previousView.getId());
+        return this;
+    }
 
     public void onStateChanged(QSTile.State state) {
         mHandler.obtainMessage(H.STATE_CHANGED, state).sendToTarget();
     }
 
-    public abstract void init(OnClickListener click, OnClickListener clickSecondary,
-                              OnLongClickListener longClick);
-    public abstract View updateAccessibilityOrder(View previousView);
-    public abstract boolean setType(int type);
-
-    protected abstract void handleStateChanged(QSTile.State state);
-
-    protected static int exactly(int size) {
-        return MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
-    }
-
-    protected static void layout(View child, int left, int top) {
-        child.layout(left, top, left + child.getMeasuredWidth(), top + child.getMeasuredHeight());
+    protected void handleStateChanged(QSTile.State state) {
+        mIcon.setIcon(state);
+        setContentDescription(state.contentDescription);
     }
 
     private class H extends Handler {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTileView.java b/packages/SystemUI/src/com/android/systemui/qs/QSTileView.java
index 4cc2b8d..41ac4d9 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTileView.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTileView.java
@@ -17,26 +17,16 @@
 package com.android.systemui.qs;
 
 import android.content.Context;
-import android.content.res.ColorStateList;
 import android.content.res.Configuration;
 import android.content.res.Resources;
-import android.content.res.TypedArray;
 import android.graphics.Typeface;
-import android.graphics.drawable.Animatable;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.RippleDrawable;
 import android.util.MathUtils;
 import android.util.TypedValue;
 import android.view.Gravity;
 import android.view.View;
-import android.widget.ImageView;
-import android.widget.ImageView.ScaleType;
 import android.widget.TextView;
 import com.android.systemui.FontSizeUtils;
 import com.android.systemui.R;
-import com.android.systemui.qs.QSTile.AnimationIcon;
-
-import java.util.Objects;
 
 /** View that represents a standard quick settings tile. **/
 public class QSTileView extends QSTileBaseView {
@@ -44,59 +34,25 @@
             Typeface.NORMAL);
 
     protected final Context mContext;
-    private final View mIcon;
-    private final View mDivider;
-    private final int mIconSizePx;
     private final int mTileSpacingPx;
     private int mTilePaddingTopPx;
-    private final int mTilePaddingBelowIconPx;
-    private final int mDualTileVerticalPaddingPx;
-    private final View mTopBackgroundView;
 
     private TextView mLabel;
-    private QSDualTileLabel mDualLabel;
-    private int mType;
-    private OnClickListener mClickPrimary;
-    private OnClickListener mClickSecondary;
-    private OnLongClickListener mLongClick;
-    private Drawable mTileBackground;
-    private RippleDrawable mRipple;
 
-    private View mCircle;
-
-    public QSTileView(Context context) {
-        super(context);
+    public QSTileView(Context context, QSIconView icon) {
+        super(context, icon);
 
         mContext = context;
         final Resources res = context.getResources();
-        mIconSizePx = res.getDimensionPixelSize(R.dimen.qs_tile_icon_size);
         mTileSpacingPx = res.getDimensionPixelSize(R.dimen.qs_tile_spacing);
-        mTilePaddingBelowIconPx =  res.getDimensionPixelSize(R.dimen.qs_tile_padding_below_icon);
-        mDualTileVerticalPaddingPx =
-                res.getDimensionPixelSize(R.dimen.qs_dual_tile_padding_vertical);
-        mTileBackground = newTileBackground();
-        recreateLabel();
         setClipChildren(false);
 
-        mTopBackgroundView = new View(context);
-        mTopBackgroundView.setId(View.generateViewId());
-        addView(mTopBackgroundView);
-
-        mIcon = createIcon();
-        addView(mIcon);
-
-        mCircle = createCircleIcon();
-        addView(mCircle);
-
-        mDivider = new View(mContext);
-        mDivider.setBackgroundColor(context.getColor(R.color.qs_tile_divider));
-        final int dh = res.getDimensionPixelSize(R.dimen.qs_tile_divider_height);
-        mDivider.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, dh));
-        addView(mDivider);
-
         setClickable(true);
         updateTopPadding();
         setId(View.generateViewId());
+        createLabel();
+        setOrientation(VERTICAL);
+        setGravity(Gravity.CENTER);
     }
 
     private void updateTopPadding() {
@@ -106,6 +62,8 @@
         float largeFactor = (MathUtils.constrain(getResources().getConfiguration().fontScale,
                 1.0f, FontSizeUtils.LARGE_TEXT_SCALE) - 1f) / (FontSizeUtils.LARGE_TEXT_SCALE - 1f);
         mTilePaddingTopPx = Math.round((1 - largeFactor) * padding + largeFactor * largePadding);
+        setPadding(mTileSpacingPx, mTilePaddingTopPx + mTileSpacingPx, mTileSpacingPx,
+                mTileSpacingPx);
         requestLayout();
     }
 
@@ -114,260 +72,29 @@
         super.onConfigurationChanged(newConfig);
         updateTopPadding();
         FontSizeUtils.updateFontSize(mLabel, R.dimen.qs_tile_text_size);
-        if (mDualLabel != null) {
-            mDualLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX,
-                    getResources().getDimensionPixelSize(R.dimen.qs_tile_text_size));
-        }
     }
 
-    private void recreateLabel() {
-        CharSequence labelText = null;
-        CharSequence labelDescription = null;
-        if (mLabel != null) {
-            labelText = mLabel.getText();
-            removeView(mLabel);
-            mLabel = null;
-        }
-        if (mDualLabel != null) {
-            labelText = mDualLabel.getText();
-            labelDescription = mLabel != null ? mLabel.getContentDescription() : null;
-            removeView(mDualLabel);
-            mDualLabel = null;
-        }
+    private void createLabel() {
         final Resources res = mContext.getResources();
-        if (mType == QS_TYPE_DUAL) {
-            mDualLabel = new QSDualTileLabel(mContext);
-            mDualLabel.setId(View.generateViewId());
-            mDualLabel.setBackgroundResource(R.drawable.btn_borderless_rect);
-            mDualLabel.setFirstLineCaret(mContext.getDrawable(R.drawable.qs_dual_tile_caret));
-            mDualLabel.setTextColor(mContext.getColor(R.color.qs_tile_text));
-            mDualLabel.setPadding(0, mDualTileVerticalPaddingPx, 0, mDualTileVerticalPaddingPx);
-            mDualLabel.setTypeface(CONDENSED);
-            mDualLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX,
-                    res.getDimensionPixelSize(R.dimen.qs_tile_text_size));
-            mDualLabel.setClickable(true);
-            mDualLabel.setOnClickListener(mClickSecondary);
-            mDualLabel.setFocusable(true);
-            if (labelText != null) {
-                mDualLabel.setText(labelText);
-            }
-            if (labelDescription != null) {
-                mDualLabel.setContentDescription(labelDescription);
-            }
-            addView(mDualLabel);
-            mDualLabel.setAccessibilityTraversalAfter(mTopBackgroundView.getId());
-        } else if (mType == QS_TYPE_NORMAL) {
-            mLabel = new TextView(mContext);
-            mLabel.setTextColor(mContext.getColor(R.color.qs_tile_text));
-            mLabel.setGravity(Gravity.CENTER_HORIZONTAL);
-            mLabel.setMinLines(2);
-            mLabel.setPadding(0, 0, 0, 0);
-            mLabel.setTypeface(CONDENSED);
-            mLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX,
-                    res.getDimensionPixelSize(R.dimen.qs_tile_text_size));
-            mLabel.setClickable(false);
-            if (labelText != null) {
-                mLabel.setText(labelText);
-            }
-            addView(mLabel);
-        }
+        mLabel = new TextView(mContext);
+        mLabel.setTextColor(mContext.getColor(R.color.qs_tile_text));
+        mLabel.setGravity(Gravity.CENTER_HORIZONTAL);
+        mLabel.setMinLines(2);
+        mLabel.setPadding(0, 0, 0, 0);
+        mLabel.setTypeface(CONDENSED);
+        mLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX,
+                res.getDimensionPixelSize(R.dimen.qs_tile_text_size));
+        mLabel.setClickable(false);
+        addView(mLabel);
     }
 
-    public boolean setType(int type) {
-        final boolean changed = mType != type;
-        mType = type;
-        if (changed) {
-            recreateLabel();
-        }
-        if (mTileBackground instanceof RippleDrawable) {
-            setRipple((RippleDrawable) mTileBackground);
-        }
-        if (mType == QS_TYPE_DUAL) {
-            mTopBackgroundView.setOnClickListener(mClickPrimary);
-            setOnClickListener(null);
-            setClickable(false);
-            setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
-            mTopBackgroundView.setBackground(mTileBackground);
-        } else {
-            mTopBackgroundView.setOnClickListener(null);
-            mTopBackgroundView.setClickable(false);
-            setOnClickListener(mClickPrimary);
-            setOnLongClickListener(mLongClick);
-            setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
-            setBackground(mTileBackground);
-        }
-        mTopBackgroundView.setFocusable(mType == QS_TYPE_DUAL);
-        setFocusable(mType != QS_TYPE_DUAL);
-        mDivider.setVisibility(mType == QS_TYPE_DUAL ? VISIBLE : GONE);
-        mCircle.setVisibility(mType == QS_TYPE_QUICK ? VISIBLE : GONE);
-        postInvalidate();
-        return changed;
-    }
-
-    private void setRipple(RippleDrawable tileBackground) {
-        mRipple = tileBackground;
-        if (getWidth() != 0) {
-            updateRippleSize(getWidth(), getHeight());
-        }
-    }
-
-    public void init(OnClickListener clickPrimary, OnClickListener clickSecondary,
-            OnLongClickListener longClick) {
-        mClickPrimary = clickPrimary;
-        mClickSecondary = clickSecondary;
-        mLongClick = longClick;
-    }
-
-    protected View createIcon() {
-        final ImageView icon = new ImageView(mContext);
-        icon.setId(android.R.id.icon);
-        icon.setScaleType(ScaleType.CENTER_INSIDE);
-        return icon;
-    }
-
-    protected View createCircleIcon() {
-        final ImageView icon = new ImageView(mContext);
-        icon.setImageResource(R.drawable.ic_qs_circle);
-        // TODO: Not this.
-        icon.setPadding(20, 20, 20, 20);
-        return icon;
-    }
-
-    protected View createCircle() {
-        final ImageView icon = new ImageView(mContext);
-        icon.setId(android.R.id.icon);
-        icon.setScaleType(ScaleType.CENTER_INSIDE);
-        return icon;
-    }
-
-    private Drawable newTileBackground() {
-        final int[] attrs = new int[] { android.R.attr.selectableItemBackgroundBorderless };
-        final TypedArray ta = mContext.obtainStyledAttributes(attrs);
-        final Drawable d = ta.getDrawable(0);
-        ta.recycle();
-        return d;
-    }
-
-    private View labelView() {
-        return mType == QS_TYPE_DUAL ? mDualLabel : mLabel;
-    }
-
-    @Override
-    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-        final int w = MeasureSpec.getSize(widthMeasureSpec);
-        final int h = MeasureSpec.getSize(heightMeasureSpec);
-        final int iconSpec = exactly(mIconSizePx);
-        mIcon.measure(MeasureSpec.makeMeasureSpec(w, getIconMeasureMode()), iconSpec);
-        switch (mType) {
-            case QS_TYPE_QUICK:
-                mCircle.measure(
-                        MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY),
-                        MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY));
-                break;
-            case QS_TYPE_DUAL:
-                mDivider.measure(widthMeasureSpec, exactly(mDivider.getLayoutParams().height));
-            default:
-                labelView().measure(widthMeasureSpec,
-                        MeasureSpec.makeMeasureSpec(h, MeasureSpec.AT_MOST));
-                break;
-        }
-        int heightSpec = exactly(
-                mIconSizePx + mTilePaddingBelowIconPx + mTilePaddingTopPx);
-        mTopBackgroundView.measure(widthMeasureSpec, heightSpec);
-        setMeasuredDimension(w, h);
-    }
-
-    protected int getIconMeasureMode() {
-        return MeasureSpec.EXACTLY;
-    }
-
-    @Override
-    protected void onLayout(boolean changed, int l, int t, int r, int b) {
-        final int w = getMeasuredWidth();
-        final int h = getMeasuredHeight();
-
-        layout(mTopBackgroundView, 0, mTileSpacingPx);
-
-        int top = 0;
-        top += mTileSpacingPx;
-        top += mTilePaddingTopPx;
-        final int iconLeft = (w - mIcon.getMeasuredWidth()) / 2;
-        if (mType == QS_TYPE_QUICK) {
-            top = (h - mIcon.getMeasuredHeight()) / 2;
-            layout(mCircle, 0, 0);
-        }
-        layout(mIcon, iconLeft, top);
-        if (mRipple != null) {
-            updateRippleSize(w, h);
-
-        }
-        top = mIcon.getBottom();
-        top += mTilePaddingBelowIconPx;
-        if (mType == QS_TYPE_DUAL) {
-            layout(mDivider, 0, top);
-            top = mDivider.getBottom();
-        }
-        if (mType != QS_TYPE_QUICK) {
-            layout(labelView(), 0, top);
-        }
-    }
-
-    private void updateRippleSize(int width, int height) {
-        // center the touch feedback on the center of the icon, and dial it down a bit
-        final int cx = width / 2;
-        final int cy = mType == QS_TYPE_DUAL ? mIcon.getTop() + mIcon.getHeight() / 2 : height / 2;
-        final int rad = (int)(mIcon.getHeight() * 1.25f);
-        mRipple.setHotspotBounds(cx - rad, cy - rad, cx + rad, cy + rad);
+    public void init(OnClickListener clickPrimary, OnLongClickListener longClick) {
+        setOnClickListener(clickPrimary);
+        setOnLongClickListener(longClick);
     }
 
     protected void handleStateChanged(QSTile.State state) {
-        if (mIcon instanceof ImageView) {
-            setIcon((ImageView) mIcon, state);
-        }
-        if (mType == QS_TYPE_DUAL) {
-            mDualLabel.setText(state.label);
-            mDualLabel.setContentDescription(state.dualLabelContentDescription);
-            mTopBackgroundView.setContentDescription(state.contentDescription);
-        } else if (mType == QS_TYPE_NORMAL) {
-            mLabel.setText(state.label);
-            setContentDescription(state.contentDescription);
-        }
-    }
-
-    protected void setIcon(ImageView iv, QSTile.State state) {
-        if (!Objects.equals(state.icon, iv.getTag(R.id.qs_icon_tag))) {
-            Drawable d = state.icon != null ? state.icon.getDrawable(mContext) : null;
-            if (d != null && state.autoMirrorDrawable) {
-                d.setAutoMirrored(true);
-            }
-            iv.setImageDrawable(d);
-            iv.setTag(R.id.qs_icon_tag, state.icon);
-            if (d instanceof Animatable) {
-                Animatable a = (Animatable) d;
-                if (state.icon instanceof AnimationIcon && !iv.isShown()) {
-                    a.stop(); // skip directly to end state
-                }
-            }
-        }
-    }
-
-    /**
-     * Update the accessibility order for this view.
-     *
-     * @param previousView the view which should be before this one
-     * @return the last view in this view which is accessible
-     */
-    public View updateAccessibilityOrder(View previousView) {
-        View firstView;
-        View lastView;
-        if (mType == QS_TYPE_DUAL) {
-            lastView = mDualLabel;
-            firstView = mTopBackgroundView;
-        } else {
-            firstView = this;
-            lastView = this;
-        }
-        firstView.setAccessibilityTraversalAfter(previousView.getId());
-        return lastView;
+        super.handleStateChanged(state);
+        mLabel.setText(state.label);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
index 6a053be..fe8ce9b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
@@ -19,7 +19,6 @@
 import android.content.Context;
 import android.content.res.ColorStateList;
 import android.util.AttributeSet;
-import android.util.Log;
 import android.view.Gravity;
 import android.view.View;
 import android.widget.ImageView;
@@ -30,10 +29,14 @@
 import java.util.Collection;
 
 /**
- * Version of QSPanel that only shows 4 Quick Tiles in the QS Header.
+ * Version of QSPanel that only shows N Quick Tiles in the QS Header.
  */
 public class QuickQSPanel extends QSPanel {
 
+    private int mMaxTiles;
+    private QSPanel mFullPanel;
+    private View mHeader;
+
     public QuickQSPanel(Context context, AttributeSet attrs) {
         super(context, attrs);
         if (mTileLayout != null) {
@@ -46,6 +49,36 @@
         mQsContainer.addView((View) mTileLayout, 1 /* Between brightness and footer */);
     }
 
+    public void setQSPanelAndHeader(QSPanel fullPanel, View header) {
+        mFullPanel = fullPanel;
+        mHeader = header;
+    }
+
+    @Override
+    protected void handleShowDetail(QSPanel.Record r, boolean show) {
+        if (show) {
+            mHeader.performClick();
+            mFullPanel.showDetail(show, r);
+        } else {
+            // Not sure how we would end up here...
+            super.handleShowDetail(r, show);
+        }
+    }
+
+    @Override
+    protected QSTileBaseView createTileView(QSTile<?> tile) {
+        return new QSTileBaseView(mContext, tile.createTileView(mContext));
+    }
+
+    public void setMaxTiles(int maxTiles) {
+        mMaxTiles = maxTiles;
+    }
+
+    @Override
+    protected void onTileClick(QSTile<?> tile) {
+        tile.secondaryClick();
+    }
+
     @Override
     public void onTuningChanged(String key, String newValue) {
         // No tunings for you.
@@ -59,11 +92,8 @@
     public void setTiles(Collection<QSTile<?>> tiles) {
         ArrayList<QSTile<?>> quickTiles = new ArrayList<>();
         for (QSTile<?> tile : tiles) {
-            if (tile.getTileType() == QSTileView.QS_TYPE_QUICK) {
-                Log.d("QSPanel", "Adding " + tile.getTileSpec());
-                quickTiles.add(tile);
-            }
-            if (quickTiles.size() == 2) {
+            quickTiles.add(tile);
+            if (quickTiles.size() == mMaxTiles) {
                 break;
             }
         }
@@ -74,6 +104,8 @@
 
         public HeaderTileLayout(Context context) {
             super(context);
+            setClipChildren(false);
+            setClipToPadding(false);
             setGravity(Gravity.CENTER_VERTICAL);
             setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
 
@@ -92,17 +124,13 @@
         @Override
         public void addTile(TileRecord tile) {
             tile.tileView.setLayoutParams(generateLayoutParams());
-            // These shouldn't be normal tiles, but they will be for now so that the circles don't
-            // show up.
-            tile.tileView.setType(QSTileView.QS_TYPE_NORMAL);
             addView(tile.tileView, getChildCount() - 1 /* Leave icon at end */);
         }
 
         private LayoutParams generateLayoutParams() {
             int size =
                     mContext.getResources().getDimensionPixelSize(R.dimen.qs_quick_tile_size);
-            LayoutParams lp = new LayoutParams(0, size);
-            lp.weight = 1;
+            LayoutParams lp = new LayoutParams(size, size);
             return lp;
         }
 
@@ -112,11 +140,6 @@
         }
 
         @Override
-        public void setTileVisibility(TileRecord tile, int visibility) {
-            tile.tileView.setVisibility(visibility);
-        }
-
-        @Override
         public int getOffsetTop(TileRecord tile) {
             return 0;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/SignalTileView.java b/packages/SystemUI/src/com/android/systemui/qs/SignalTileView.java
index a2e1296..b2bfa06 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/SignalTileView.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/SignalTileView.java
@@ -27,7 +27,7 @@
 import com.android.systemui.qs.QSTile.SignalState;
 
 /** View that represents a custom quick settings tile for displaying signal info (wifi/cell). **/
-public final class SignalTileView extends QSTileView {
+public final class SignalTileView extends QSIconView {
     private static final long DEFAULT_DURATION = new ValueAnimator().getDuration();
     private static final long SHORT_DURATION = DEFAULT_DURATION / 3;
 
@@ -106,8 +106,7 @@
     }
 
     @Override
-    protected void handleStateChanged(QSTile.State state) {
-        super.handleStateChanged(state);
+    public void setIcon(QSTile.State state) {
         final SignalState s = (SignalState) state;
         setIcon(mSignal, s);
         if (s.overlayIconId > 0) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/TileLayout.java b/packages/SystemUI/src/com/android/systemui/qs/TileLayout.java
index 1336eec..ff11177 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/TileLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/TileLayout.java
@@ -18,14 +18,9 @@
 
     private static final String TAG = "TileLayout";
 
-    private int mDualTileUnderlap;
     protected int mColumns;
     private int mCellWidth;
     private int mCellHeight;
-    private int mLargeCellWidth;
-    private int mLargeCellHeight;
-
-    protected boolean mAllowDual = true;
 
     protected final ArrayList<TileRecord> mRecords = new ArrayList<>();
 
@@ -59,21 +54,11 @@
         super.removeAllViews();
     }
 
-    @Override
-    public void setTileVisibility(TileRecord tile, int visibility) {
-        tile.tileView.setVisibility(visibility);
-    }
-
     public void updateResources() {
         final Resources res = mContext.getResources();
         final int columns = Math.max(1, res.getInteger(R.integer.quick_settings_num_columns));
         mCellHeight = getCellHeight();
         mCellWidth = (int) (mCellHeight * TILE_ASPECT);
-        mLargeCellHeight = mAllowDual ? res.getDimensionPixelSize(R.dimen.qs_dual_tile_height)
-                : mCellHeight;
-        mLargeCellWidth = mAllowDual ? (int) (mLargeCellHeight * TILE_ASPECT) : mCellWidth;
-        mDualTileUnderlap = mAllowDual
-                ? res.getDimensionPixelSize(R.dimen.qs_dual_tile_padding_vertical) : 0;
         if (mColumns != columns) {
             mColumns = columns;
             postInvalidate();
@@ -90,16 +75,13 @@
         int r = -1;
         int c = -1;
         int rows = 0;
-        boolean rowIsDual = false;
         for (TileRecord record : mRecords) {
             if (record.tileView.getVisibility() == GONE) continue;
             // wrap to next column if we've reached the max # of columns
             // also don't allow dual + single tiles on the same row
-            if (r == -1 || c == (mColumns - 1)
-                    || rowIsDual != (mAllowDual && record.tile.supportsDualTargets())) {
+            if (r == -1 || c == (mColumns - 1)) {
                 r++;
                 c = 0;
-                rowIsDual = mAllowDual && record.tile.supportsDualTargets();
             } else {
                 c++;
             }
@@ -110,13 +92,9 @@
 
         View previousView = this;
         for (TileRecord record : mRecords) {
-            if (record.tileView.setType(mAllowDual ? record.tile.getTileType()
-                    : QSTileView.QS_TYPE_NORMAL)) {
-                record.tileView.handleStateChanged(record.tile.getState());
-            }
             if (record.tileView.getVisibility() == GONE) continue;
-            final int cw = record.row == 0 ? mLargeCellWidth : mCellWidth;
-            final int ch = record.row == 0 ? mLargeCellHeight : mCellHeight;
+            final int cw = mCellWidth;
+            final int ch = mCellHeight;
             record.tileView.measure(exactly(cw), exactly(ch));
             previousView = record.tileView.updateAccessibilityOrder(previousView);
         }
@@ -135,7 +113,7 @@
         for (TileRecord record : mRecords) {
             if (record.tileView.getVisibility() == GONE) continue;
             final int cols = getColumnCount(record.row);
-            final int cw = record.row == 0 ? mLargeCellWidth : mCellWidth;
+            final int cw = mCellWidth;
             final int extra = (w - cw * cols) / (cols + 1);
             int left = record.col * cw + (record.col + 1) * extra;
             final int top = getRowTop(record.row);
@@ -153,7 +131,7 @@
 
     private int getRowTop(int row) {
         if (row <= 0) return 0;
-        return mLargeCellHeight - mDualTileUnderlap + (row - 1) * mCellHeight;
+        return row * mCellHeight;
     }
 
     private int getColumnCount(int row) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/UsageTracker.java b/packages/SystemUI/src/com/android/systemui/qs/UsageTracker.java
deleted file mode 100644
index e64f6a0..0000000
--- a/packages/SystemUI/src/com/android/systemui/qs/UsageTracker.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.qs;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-
-import com.android.systemui.Prefs;
-import com.android.systemui.R;
-import com.android.systemui.statusbar.phone.SystemUIDialog;
-import com.android.systemui.statusbar.policy.Listenable;
-
-public class UsageTracker implements Listenable {
-    private static final long MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
-
-    private final Context mContext;
-    private final long mTimeToShowTile;
-    @Prefs.Key private final String mPrefKey;
-    private final String mResetAction;
-
-    private boolean mRegistered;
-
-    public UsageTracker(Context context, @Prefs.Key String prefKey, Class<?> tile,
-            int timeoutResource) {
-        mContext = context;
-        mPrefKey = prefKey;
-        mTimeToShowTile = MILLIS_PER_DAY * mContext.getResources().getInteger(timeoutResource);
-        mResetAction = "com.android.systemui.qs." + tile.getSimpleName() + ".usage_reset";
-    }
-
-    @Override
-    public void setListening(boolean listen) {
-        if (listen && !mRegistered) {
-             mContext.registerReceiver(mReceiver, new IntentFilter(mResetAction));
-             mRegistered = true;
-        } else if (!listen && mRegistered) {
-            mContext.unregisterReceiver(mReceiver);
-            mRegistered = false;
-        }
-    }
-
-    public boolean isRecentlyUsed() {
-        long lastUsed = Prefs.getLong(mContext, mPrefKey, 0L /* defaultValue */);
-        return (System.currentTimeMillis() - lastUsed) < mTimeToShowTile;
-    }
-
-    public void trackUsage() {
-        Prefs.putLong(mContext, mPrefKey, System.currentTimeMillis());
-    }
-
-    public void reset() {
-        Prefs.remove(mContext, mPrefKey);
-    }
-
-    public void showResetConfirmation(String title, final Runnable onConfirmed) {
-        final SystemUIDialog d = new SystemUIDialog(mContext);
-        d.setTitle(title);
-        d.setMessage(mContext.getString(R.string.quick_settings_reset_confirmation_message));
-        d.setNegativeButton(android.R.string.cancel, null);
-        d.setPositiveButton(R.string.quick_settings_reset_confirmation_button,
-                new DialogInterface.OnClickListener() {
-            @Override
-            public void onClick(DialogInterface dialog, int which) {
-                reset();
-                if (onConfirmed != null) {
-                    onConfirmed.run();
-                }
-            }
-        });
-        d.setCanceledOnTouchOutside(true);
-        d.show();
-    }
-
-    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            if (mResetAction.equals(intent.getAction())) {
-                reset();
-            }
-        }
-    };
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/BlankCustomTile.java b/packages/SystemUI/src/com/android/systemui/qs/customize/BlankCustomTile.java
index a4ff685..95ff611 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/BlankCustomTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/BlankCustomTile.java
@@ -72,12 +72,10 @@
         try {
             PackageManager pm = mContext.getPackageManager();
             ServiceInfo info = pm.getServiceInfo(mComponent, 0);
-            state.visible = true;
             state.icon = new DrawableIcon(info.loadIcon(pm));
             state.label = info.loadLabel(pm).toString();
             state.contentDescription = state.label;
         } catch (Exception e) {
-            state.visible = false;
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/CustomQSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/customize/CustomQSPanel.java
index 422ae4d..8dda9ba 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/CustomQSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/CustomQSPanel.java
@@ -176,13 +176,16 @@
             if (mTiles.get(i).startsWith(CustomTile.PREFIX)) {
                 mCurrentTiles.add(BlankCustomTile.create(mHost, mTiles.get(i)));
             } else {
-                mCurrentTiles.add(mHost.createTile(mTiles.get(i)));
+                QSTile<?> tile = mHost.createTile(mTiles.get(i));
+                if (tile != null) {
+                    mCurrentTiles.add(tile);
+                }
             }
             mCurrentTiles.get(mCurrentTiles.size() - 1).setTileSpec(mTiles.get(i));
         }
         super.setTiles(mCurrentTiles);
     }
-    
+
     public void addTile(String spec) {
         mTiles.add(spec);
         setTilesInternal();
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/NonPagedTileLayout.java b/packages/SystemUI/src/com/android/systemui/qs/customize/NonPagedTileLayout.java
index d0d5b54..3acbed8 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/NonPagedTileLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/NonPagedTileLayout.java
@@ -25,14 +25,12 @@
 import android.view.View;
 import android.view.View.OnTouchListener;
 import android.widget.LinearLayout;
-
 import com.android.systemui.R;
 import com.android.systemui.qs.PagedTileLayout;
 import com.android.systemui.qs.PagedTileLayout.TilePage;
 import com.android.systemui.qs.QSPanel.QSTileLayout;
 import com.android.systemui.qs.QSPanel.TileRecord;
 import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.QSTileView;
 import com.android.systemui.qs.QuickTileLayout;
 
 import java.util.ArrayList;
@@ -75,13 +73,12 @@
     public void addTile(TileRecord record) {
         mTiles.add(record);
         distributeTiles();
-        if (record.tile.getTileType() == QSTileView.QS_TYPE_QUICK
-                || record.tileView.getTag() == record.tile) {
+        if (record.tileView.getTag() == record.tile) {
             return;
         }
         record.tileView.setTag(record.tile);
         record.tileView.setVisibility(View.VISIBLE);
-        record.tileView.init(null, null, null);
+        record.tileView.init(null, null);
         record.tileView.setOnTouchListener(this);
         if (mCurrentClip != null && mCurrentClip.getItemAt(0)
                 .getText().toString().equals(record.tile.getTileSpec())) {
@@ -107,10 +104,6 @@
         final int NT = mTiles.size();
         for (int i = 0; i < NT; i++) {
             TileRecord tile = mTiles.get(i);
-            if (tile.tile.getTileType() == QSTileView.QS_TYPE_QUICK) {
-                // Ignore quick tiles for now.
-                continue;
-            }
             mPages.get(index).addTile(tile);
             // Keep everything in one layout for now.
             if (false && mPages.get(index).isFull()) {
@@ -125,12 +118,6 @@
     }
 
     @Override
-    public void setTileVisibility(TileRecord tile, int visibility) {
-        // All tiles visible here, so that they can be re-arranged.
-        tile.tileView.setVisibility(View.VISIBLE);
-    }
-
-    @Override
     public int getOffsetTop(TileRecord tile) {
         // No touch feedback, so this isn't required.
         return 0;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
index 144b202..6706c7a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
@@ -88,6 +88,9 @@
                 }
                 Log.d(TAG, "Trying " + spec);
                 final QSTile<?> tile = host.createTile(spec);
+                if (tile == null) {
+                    continue;
+                }
                 // Bad, bad, very bad.
                 tile.setListening(true);
                 tile.clearState();
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/AirplaneModeTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/AirplaneModeTile.java
index 49f8d1c..fc802dd 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/AirplaneModeTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/AirplaneModeTile.java
@@ -73,7 +73,6 @@
         final int value = arg instanceof Integer ? (Integer)arg : mSetting.getValue();
         final boolean airplaneMode = value != 0;
         state.value = airplaneMode;
-        state.visible = true;
         state.label = mContext.getString(R.string.airplane_mode);
         if (airplaneMode) {
             state.icon = mEnable;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/BatteryTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/BatteryTile.java
index 8f9655d..84eac65 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/BatteryTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/BatteryTile.java
@@ -73,7 +73,6 @@
         int level = (arg != null) ? (Integer) arg : mLevel;
         String percentage = NumberFormat.getPercentInstance().format((double) level / 100.0);
 
-        state.visible = true;
         state.icon = new Icon() {
             @Override
             public Drawable getDrawable(Context context) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/BluetoothTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/BluetoothTile.java
index 7f07ddc..cfc09a0 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/BluetoothTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/BluetoothTile.java
@@ -24,18 +24,15 @@
 import android.text.TextUtils;
 import android.view.View;
 import android.view.ViewGroup;
-
 import com.android.internal.logging.MetricsLogger;
 import com.android.settingslib.bluetooth.CachedBluetoothDevice;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSDetailItems;
 import com.android.systemui.qs.QSDetailItems.Item;
 import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.QSTileView;
 import com.android.systemui.statusbar.policy.BluetoothController;
 
 import java.util.Collection;
-import java.util.Set;
 
 /** Quick settings tile: Bluetooth **/
 public class BluetoothTile extends QSTile<QSTile.BooleanState>  {
@@ -44,21 +41,13 @@
     private final BluetoothController mController;
     private final BluetoothDetailAdapter mDetailAdapter;
 
-    private final boolean mAlwaysDetail;
-
-    public BluetoothTile(Host host, boolean alwaysDetail) {
+    public BluetoothTile(Host host) {
         super(host);
-        mAlwaysDetail = alwaysDetail;
         mController = host.getBluetoothController();
         mDetailAdapter = new BluetoothDetailAdapter();
     }
 
     @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_DUAL;
-    }
-
-    @Override
     public DetailAdapter getDetailAdapter() {
         return mDetailAdapter;
     }
@@ -78,18 +67,15 @@
     }
 
     @Override
-    protected void handleClick() {
-        if (mAlwaysDetail) {
-            handleSecondaryClick();
-            return;
-        }
+    protected void handleSecondaryClick() {
+        // Secondary clicks are header clicks, just toggle.
         final boolean isEnabled = (Boolean)mState.value;
         MetricsLogger.action(mContext, getMetricsCategory(), !isEnabled);
         mController.setBluetoothEnabled(!isEnabled);
     }
 
     @Override
-    protected void handleSecondaryClick() {
+    protected void handleClick() {
         if (!mState.value) {
             mState.value = true;
             mController.setBluetoothEnabled(true);
@@ -99,11 +85,9 @@
 
     @Override
     protected void handleUpdateState(BooleanState state, Object arg) {
-        final boolean supported = mController.isBluetoothSupported();
         final boolean enabled = mController.isBluetoothEnabled();
         final boolean connected = mController.isBluetoothConnected();
         final boolean connecting = mController.isBluetoothConnecting();
-        state.visible = supported;
         state.value = enabled;
         state.autoMirrorDrawable = false;
         if (enabled) {
@@ -155,6 +139,10 @@
         }
     }
 
+    public static boolean isSupported(Host host) {
+        return host.getBluetoothController().isBluetoothSupported();
+    }
+
     private final BluetoothController.Callback mCallback = new BluetoothController.Callback() {
         @Override
         public void onBluetoothStateChange(boolean enabled) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
index 48b74a4..a8e139c 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
@@ -23,12 +23,10 @@
 import android.view.View;
 import android.view.View.OnAttachStateChangeListener;
 import android.view.ViewGroup;
-
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSDetailItems;
 import com.android.systemui.qs.QSDetailItems.Item;
-import com.android.systemui.qs.QSPanel;
 import com.android.systemui.qs.QSTile;
 import com.android.systemui.statusbar.policy.CastController;
 import com.android.systemui.statusbar.policy.CastController.CastDevice;
@@ -87,14 +85,23 @@
 
     @Override
     protected void handleClick() {
+        if (mKeyguard.isSecure() && !mKeyguard.canSkipBouncer()) {
+            mHost.startRunnableDismissingKeyguard(new Runnable() {
+                @Override
+                public void run() {
+                    MetricsLogger.action(mContext, getMetricsCategory());
+                    showDetail(true);
+                    mHost.openPanels();
+                }
+            });
+            return;
+        }
         MetricsLogger.action(mContext, getMetricsCategory());
         showDetail(true);
     }
 
     @Override
     protected void handleUpdateState(BooleanState state, Object arg) {
-        state.visible = !mKeyguard.isSecure() || !mKeyguard.isShowing()
-                || mKeyguard.canSkipBouncer() || QSPanel.isTheNewQS(mContext);
         state.label = mContext.getString(R.string.quick_settings_cast_title);
         state.value = false;
         state.autoMirrorDrawable = false;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
index a0bbbe3..5fb76c8 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
@@ -26,8 +26,8 @@
 import com.android.internal.logging.MetricsLogger;
 import com.android.settingslib.net.MobileDataController;
 import com.android.systemui.R;
+import com.android.systemui.qs.QSIconView;
 import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.QSTileBaseView;
 import com.android.systemui.qs.SignalTileView;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.statusbar.policy.NetworkController.IconState;
@@ -71,7 +71,7 @@
     }
 
     @Override
-    public QSTileBaseView createTileView(Context context) {
+    public QSIconView createTileView(Context context) {
         return new SignalTileView(context);
     }
 
@@ -87,8 +87,6 @@
 
     @Override
     protected void handleUpdateState(SignalState state, Object arg) {
-        state.visible = mController.hasMobileDataFeature();
-        if (!state.visible) return;
         CallbackInfo cb = (CallbackInfo) arg;
         if (cb == null) {
             cb = mSignalCallback.mInfo;
@@ -138,6 +136,10 @@
         return string;
     }
 
+    public static boolean isSupported(Host host) {
+        return host.getNetworkController().hasMobileDataFeature();
+    }
+
     private static final class CallbackInfo {
         boolean enabled;
         boolean wifiEnabled;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/ColorInversionTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/ColorInversionTile.java
index 2f9a496..f73ee35 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/ColorInversionTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/ColorInversionTile.java
@@ -17,14 +17,10 @@
 package com.android.systemui.qs.tiles;
 
 import android.provider.Settings.Secure;
-
 import com.android.internal.logging.MetricsLogger;
-import com.android.systemui.Prefs;
 import com.android.systemui.R;
-import com.android.systemui.qs.QSPanel;
 import com.android.systemui.qs.QSTile;
 import com.android.systemui.qs.SecureSetting;
-import com.android.systemui.qs.UsageTracker;
 
 /** Quick settings tile: Invert colors **/
 public class ColorInversionTile extends QSTile<QSTile.BooleanState> {
@@ -34,7 +30,6 @@
     private final AnimationIcon mDisable
             = new AnimationIcon(R.drawable.ic_invert_colors_disable_animation);
     private final SecureSetting mSetting;
-    private final UsageTracker mUsageTracker;
 
     private boolean mListening;
 
@@ -45,28 +40,14 @@
                 Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED) {
             @Override
             protected void handleValueChanged(int value, boolean observedChange) {
-                if (value != 0 || observedChange) {
-                    mUsageTracker.trackUsage();
-                }
-                if (mListening) {
-                    handleRefreshState(value);
-                }
+                handleRefreshState(value);
             }
         };
-        mUsageTracker = new UsageTracker(host.getContext(),
-                Prefs.Key.COLOR_INVERSION_TILE_LAST_USED, ColorInversionTile.class,
-                R.integer.days_to_show_color_inversion_tile);
-        if (mSetting.getValue() != 0 && !mUsageTracker.isRecentlyUsed()) {
-            mUsageTracker.trackUsage();
-        }
-        mUsageTracker.setListening(true);
-        mSetting.setListening(true);
     }
 
     @Override
     protected void handleDestroy() {
         super.handleDestroy();
-        mUsageTracker.setListening(false);
         mSetting.setListening(false);
     }
 
@@ -77,7 +58,7 @@
 
     @Override
     public void setListening(boolean listening) {
-        mListening = listening;
+        mSetting.setListening(listening);
     }
 
     @Override
@@ -95,23 +76,9 @@
     }
 
     @Override
-    protected void handleLongClick() {
-        if (mState.value) return;  // don't allow usage reset if inversion is active
-        final String title = mContext.getString(R.string.quick_settings_reset_confirmation_title,
-                mState.label);
-        mUsageTracker.showResetConfirmation(title, new Runnable() {
-            @Override
-            public void run() {
-                refreshState();
-            }
-        });
-    }
-
-    @Override
     protected void handleUpdateState(BooleanState state, Object arg) {
         final int value = arg instanceof Integer ? (Integer) arg : mSetting.getValue();
         final boolean enabled = value != 0;
-        state.visible = enabled || mUsageTracker.isRecentlyUsed() || QSPanel.isTheNewQS(mContext);
         state.value = enabled;
         state.label = mContext.getString(R.string.quick_settings_inversion_label);
         state.icon = enabled ? mEnable : mDisable;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CustomTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CustomTile.java
index 04006eb..bb74f34 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CustomTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CustomTile.java
@@ -104,9 +104,15 @@
                         mServiceConnection, Service.BIND_AUTO_CREATE,
                         new UserHandle(ActivityManager.getCurrentUser()));
                 mBound = true;
+            } else {
+                if (mService != null) {
+                    mService.onStartListening();
+                } else {
+                    Log.d(TAG, "Can't start service listening");
+                }
             }
         } else {
-            if (mService!= null) {
+            if (mService != null) {
                 mService.onStopListening();
             }
             if (mIsTokenGranted && !mIsShowingDialog) {
@@ -168,7 +174,6 @@
 
     @Override
     protected void handleUpdateState(State state, Object arg) {
-        state.visible = true;
         Drawable drawable = mTile.getIcon().loadDrawable(mContext);
         drawable.setTint(mContext.getColor(android.R.color.white));
         state.icon = new DrawableIcon(drawable);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/DndTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/DndTile.java
index 781ab1c..d96f735 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/DndTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/DndTile.java
@@ -29,7 +29,6 @@
 import android.view.View.OnAttachStateChangeListener;
 import android.view.ViewGroup;
 import android.widget.Toast;
-
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
@@ -126,7 +125,6 @@
         final boolean newValue = zen != Global.ZEN_MODE_OFF;
         final boolean valueChanged = state.value != newValue;
         state.value = newValue;
-        state.visible = isVisible(mContext);
         switch (zen) {
             case Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS:
                 state.icon = ResourceIcon.get(R.drawable.ic_qs_dnd_on);
@@ -215,6 +213,10 @@
         }
     };
 
+    public static boolean isSupported(Host host) {
+        return isVisible(host.getContext());
+    }
+
     private final class DndDetailAdapter implements DetailAdapter, OnAttachStateChangeListener {
 
         @Override
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java
index 21cbef2..12c1298 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java
@@ -17,7 +17,6 @@
 package com.android.systemui.qs.tiles;
 
 import android.app.ActivityManager;
-
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSTile;
@@ -71,7 +70,8 @@
 
     @Override
     protected void handleUpdateState(BooleanState state, Object arg) {
-        state.visible = mFlashlightController.isAvailable();
+        // TODO: Flashlight available handling...
+//        state.visible = mFlashlightController.isAvailable();
         state.label = mHost.getContext().getString(R.string.quick_settings_flashlight_label);
         if (arg instanceof UserBoolean) {
             boolean value = ((UserBoolean) arg).value;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
index 79084ae..250d567 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
@@ -16,16 +16,9 @@
 
 package com.android.systemui.qs.tiles;
 
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
 import com.android.internal.logging.MetricsLogger;
-import com.android.systemui.Prefs;
 import com.android.systemui.R;
-import com.android.systemui.qs.QSPanel;
 import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.UsageTracker;
 import com.android.systemui.statusbar.policy.HotspotController;
 
 /** Quick settings tile: Hotspot **/
@@ -36,19 +29,15 @@
             new AnimationIcon(R.drawable.ic_hotspot_disable_animation);
     private final HotspotController mController;
     private final Callback mCallback = new Callback();
-    private final UsageTracker mUsageTracker;
 
     public HotspotTile(Host host) {
         super(host);
         mController = host.getHotspotController();
-        mUsageTracker = newUsageTracker(host.getContext());
-        mUsageTracker.setListening(true);
     }
 
     @Override
     protected void handleDestroy() {
         super.handleDestroy();
-        mUsageTracker.setListening(false);
     }
 
     @Override
@@ -75,22 +64,7 @@
     }
 
     @Override
-    protected void handleLongClick() {
-        if (mState.value) return;  // don't allow usage reset if hotspot is active
-        final String title = mContext.getString(R.string.quick_settings_reset_confirmation_title,
-                mState.label);
-        mUsageTracker.showResetConfirmation(title, new Runnable() {
-            @Override
-            public void run() {
-                refreshState();
-            }
-        });
-    }
-
-    @Override
     protected void handleUpdateState(BooleanState state, Object arg) {
-        state.visible = (mController.isHotspotSupported() && mUsageTracker.isRecentlyUsed())
-                || QSPanel.isTheNewQS(mContext);
         state.label = mContext.getString(R.string.quick_settings_hotspot_label);
 
         if (arg instanceof Boolean) {
@@ -98,7 +72,7 @@
         } else {
             state.value = mController.isHotspotEnabled();
         }
-        state.icon = state.visible && state.value ? mEnable : mDisable;
+        state.icon = state.value ? mEnable : mDisable;
     }
 
     @Override
@@ -115,31 +89,10 @@
         }
     }
 
-    private static UsageTracker newUsageTracker(Context context) {
-        return new UsageTracker(context, Prefs.Key.HOTSPOT_TILE_LAST_USED, HotspotTile.class,
-                R.integer.days_to_show_hotspot_tile);
-    }
-
     private final class Callback implements HotspotController.Callback {
         @Override
         public void onHotspotChanged(boolean enabled) {
             refreshState(enabled);
         }
     };
-
-    /**
-     * This will catch broadcasts for changes in hotspot state so we can show
-     * the hotspot tile for a number of days after use.
-     */
-    public static class APChangedReceiver extends BroadcastReceiver {
-        private UsageTracker mUsageTracker;
-
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            if (mUsageTracker == null) {
-                mUsageTracker = newUsageTracker(context);
-            }
-            mUsageTracker.trackUsage();
-        }
-    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java
index c7f2284..0883445 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java
@@ -124,7 +124,6 @@
         }
         // Save the last one in case we need it later.
         mLastIntent = intent;
-        state.visible = intent.getBooleanExtra("visible", true);
         state.contentDescription = intent.getStringExtra("contentDescription");
         state.label = intent.getStringExtra("label");
         state.icon = null;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java
index 0e2672c..08540f6 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java
@@ -18,7 +18,6 @@
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
-import com.android.systemui.qs.QSPanel;
 import com.android.systemui.qs.QSTile;
 import com.android.systemui.statusbar.policy.KeyguardMonitor;
 import com.android.systemui.statusbar.policy.LocationController;
@@ -60,6 +59,20 @@
 
     @Override
     protected void handleClick() {
+        if (mKeyguard.isSecure() && mKeyguard.isShowing()) {
+            mHost.startRunnableDismissingKeyguard(new Runnable() {
+                @Override
+                public void run() {
+                    final boolean wasEnabled = (Boolean) mState.value;
+                    mHost.openPanels();
+                    MetricsLogger.action(mContext, getMetricsCategory(), !wasEnabled);
+                    mController.setLocationEnabled(!wasEnabled);
+                    mEnable.setAllowAnimation(true);
+                    mDisable.setAllowAnimation(true);
+                }
+            });
+            return;
+        }
         final boolean wasEnabled = (Boolean) mState.value;
         MetricsLogger.action(mContext, getMetricsCategory(), !wasEnabled);
         mController.setLocationEnabled(!wasEnabled);
@@ -74,7 +87,6 @@
         // Work around for bug 15916487: don't show location tile on top of lock screen. After the
         // bug is fixed, this should be reverted to only hiding it on secure lock screens:
         // state.visible = !(mKeyguard.isSecure() && mKeyguard.isShowing());
-        state.visible = !mKeyguard.isShowing() || QSPanel.isTheNewQS(mContext);
         state.value = locationEnabled;
         if (locationEnabled) {
             state.icon = mEnable;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QAirplaneTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QAirplaneTile.java
deleted file mode 100644
index b77191e..0000000
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QAirplaneTile.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.qs.tiles;
-
-import android.content.Context;
-import com.android.systemui.QSQuickTileView;
-import com.android.systemui.qs.QSTileBaseView;
-import com.android.systemui.qs.QSTileView;
-
-/** Quick settings tile: Airplane mode **/
-public class QAirplaneTile extends AirplaneModeTile {
-
-    public QAirplaneTile(Host host) {
-        super(host);
-    }
-
-    @Override
-    public QSTileBaseView createTileView(Context context) {
-        return new QSQuickTileView(context);
-    }
-
-    @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_QUICK;
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QBluetoothTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QBluetoothTile.java
deleted file mode 100644
index 4fe7e45..0000000
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QBluetoothTile.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.qs.tiles;
-
-import android.content.Context;
-import com.android.systemui.QSQuickTileView;
-import com.android.systemui.qs.QSTileBaseView;
-import com.android.systemui.qs.QSTileView;
-
-/** Quick settings tile: Bluetooth **/
-public class QBluetoothTile extends BluetoothTile  {
-
-    public QBluetoothTile(Host host) {
-        super(host, false);
-    }
-
-    @Override
-    public QSTileBaseView createTileView(Context context) {
-        return new QSQuickTileView(context);
-    }
-
-    @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_QUICK;
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QFlashlightTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QFlashlightTile.java
deleted file mode 100644
index e115755e..0000000
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QFlashlightTile.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.qs.tiles;
-
-import android.content.Context;
-import com.android.systemui.QSQuickTileView;
-import com.android.systemui.qs.QSTileBaseView;
-import com.android.systemui.qs.QSTileView;
-
-/** Quick settings tile: Flashlight **/
-public class QFlashlightTile extends FlashlightTile {
-
-    public QFlashlightTile(Host host) {
-        super(host);
-    }
-
-    @Override
-    public QSTileBaseView createTileView(Context context) {
-        return new QSQuickTileView(context);
-    }
-
-    @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_QUICK;
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QLockTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QLockTile.java
deleted file mode 100644
index 8b3013a..0000000
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QLockTile.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.systemui.qs.tiles;
-
-import android.content.Context;
-import com.android.internal.logging.MetricsLogger;
-import com.android.systemui.QSQuickTileView;
-import com.android.systemui.R;
-import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.QSTileBaseView;
-import com.android.systemui.qs.QSTileView;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
-
-public class QLockTile extends QSTile<QSTile.State> implements KeyguardMonitor.Callback {
-
-    private final KeyguardMonitor mKeyguard;
-
-    public QLockTile(Host host) {
-        super(host);
-        mKeyguard = host.getKeyguardMonitor();
-    }
-
-    @Override
-    public QSTileBaseView createTileView(Context context) {
-        return new QSQuickTileView(context);
-    }
-
-    @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_QUICK;
-    }
-
-    @Override
-    protected State newTileState() {
-        return new State();
-    }
-
-    @Override
-    public void setListening(boolean listening) {
-        if (listening) {
-            mKeyguard.addCallback(this);
-        } else {
-            mKeyguard.removeCallback(this);
-        }
-    }
-
-    @Override
-    public int getMetricsCategory() {
-        return MetricsLogger.QS_LOCK_TILE;
-    }
-
-    @Override
-    public void onKeyguardChanged() {
-        refreshState();
-    }
-
-    @Override
-    protected void handleClick() {
-        if (mKeyguard.isShowing()) {
-            mKeyguard.unlock();
-        } else {
-            mKeyguard.lock();
-        }
-    }
-
-    @Override
-    protected void handleUpdateState(State state, Object arg) {
-        // TOD: Content description.
-        state.visible = true;
-        if (mKeyguard.isShowing()) {
-            state.icon = ResourceIcon.get(R.drawable.ic_qs_lock);
-        } else {
-            state.icon = ResourceIcon.get(R.drawable.ic_qs_lock_open);
-        }
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QRotationLockTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QRotationLockTile.java
deleted file mode 100644
index 5f5cab5..0000000
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QRotationLockTile.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.qs.tiles;
-
-import android.content.Context;
-import com.android.systemui.QSQuickTileView;
-import com.android.systemui.qs.QSTileBaseView;
-import com.android.systemui.qs.QSTileView;
-
-/** Quick settings tile: Rotation **/
-public class QRotationLockTile extends RotationLockTile {
-
-    public QRotationLockTile(Host host) {
-        super(host);
-    }
-
-    @Override
-    public QSTileBaseView createTileView(Context context) {
-        return new QSQuickTileView(context);
-    }
-
-    @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_QUICK;
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QWifiTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QWifiTile.java
deleted file mode 100644
index f0fe87d..0000000
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QWifiTile.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.qs.tiles;
-
-import android.content.Context;
-import com.android.systemui.QSQuickTileView;
-import com.android.systemui.qs.QSTileBaseView;
-import com.android.systemui.qs.QSTileView;
-import com.android.systemui.statusbar.policy.WifiIcons;
-
-/** Quick settings tile: Wifi **/
-public class QWifiTile extends WifiTile {
-
-    public QWifiTile(Host host) {
-        super(host, false);
-    }
-
-    @Override
-    public QSTileBaseView createTileView(Context context) {
-        return new QSQuickTileView(context);
-    }
-
-    @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_QUICK;
-    }
-
-    @Override
-    protected void handleUpdateState(SignalState state, Object arg) {
-        super.handleUpdateState(state, arg);
-
-        CallbackInfo cb = (CallbackInfo) arg;
-        if (cb == null) {
-            cb = mSignalCallback.mInfo;
-        }
-        boolean wifiConnected = cb.enabled && (cb.wifiSignalIconId > 0) && (cb.enabledDesc != null);
-
-        if (state.enabled && wifiConnected) {
-            // Only show full signal here.
-            state.icon = ResourceIcon.get(WifiIcons.QS_WIFI_SIGNAL_STRENGTH[1][4]);
-        }
-        // No activity in the quick toggle.
-        state.activityIn = false;
-        state.activityOut = false;
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java
index 1a26a4d..d85cf60 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java
@@ -72,7 +72,8 @@
         final boolean rotationLocked = arg != null ? ((UserBoolean) arg).value
                 : mController.isRotationLocked();
         final boolean userInitiated = arg != null ? ((UserBoolean) arg).userInitiated : false;
-        state.visible = mController.isRotationLockAffordanceVisible();
+        // TODO: Handle accessibility rotation lock and whatnot.
+//        state.visible = mController.isRotationLockAffordanceVisible();
         if (state.value == rotationLocked && state.contentDescription != null) {
             // No change and initialized, no need to update all the values.
             return;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/UserTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/UserTile.java
index 3c5ab8d..d29cae4 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/UserTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/UserTile.java
@@ -67,17 +67,19 @@
     @Override
     protected void handleUpdateState(State state, Object arg) {
         final Pair<String, Drawable> p = arg != null ? (Pair<String, Drawable>) arg : mLastUpdate;
-        state.visible = p != null;
-        if (!state.visible) return;
-        state.label = p.first;
-        // TODO: Better content description.
-        state.contentDescription = p.first;
-        state.icon = new Icon() {
-            @Override
-            public Drawable getDrawable(Context context) {
-                return p.second;
-            }
-        };
+        if (p != null) {
+            state.label = p.first;
+            // TODO: Better content description.
+            state.contentDescription = p.first;
+            state.icon = new Icon() {
+                @Override
+                public Drawable getDrawable(Context context) {
+                    return p.second;
+                }
+            };
+        } else {
+            // TODO: Default state.
+        }
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
index 7f4442a..48b4096 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
@@ -18,20 +18,19 @@
 
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.provider.Settings;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
-
 import com.android.internal.logging.MetricsLogger;
 import com.android.settingslib.wifi.AccessPoint;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSDetailItems;
 import com.android.systemui.qs.QSDetailItems.Item;
+import com.android.systemui.qs.QSIconView;
 import com.android.systemui.qs.QSTile;
-import com.android.systemui.qs.QSTileBaseView;
-import com.android.systemui.qs.QSTileView;
 import com.android.systemui.qs.SignalTileView;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.statusbar.policy.NetworkController.AccessPointController;
@@ -51,22 +50,14 @@
 
     protected final WifiSignalCallback mSignalCallback = new WifiSignalCallback();
 
-    private final boolean mAlwaysDetail;
-
-    public WifiTile(Host host, boolean alwaysDetail) {
+    public WifiTile(Host host) {
         super(host);
-        mAlwaysDetail = alwaysDetail;
         mController = host.getNetworkController();
         mWifiController = mController.getAccessPointController();
         mDetailAdapter = new WifiDetailAdapter();
     }
 
     @Override
-    public int getTileType() {
-        return QSTileView.QS_TYPE_DUAL;
-    }
-
-    @Override
     protected SignalState newTileState() {
         return new SignalState();
     }
@@ -95,23 +86,20 @@
     }
 
     @Override
-    public QSTileBaseView createTileView(Context context) {
+    public QSIconView createTileView(Context context) {
         return new SignalTileView(context);
     }
 
     @Override
-    protected void handleClick() {
-        if (mAlwaysDetail) {
-            handleSecondaryClick();
-            return;
-        }
+    protected void handleSecondaryClick() {
+        // Secondary clicks are header clicks, just toggle.
         mState.copyTo(mStateBeforeClick);
         MetricsLogger.action(mContext, getMetricsCategory(), !mState.enabled);
         mController.setWifiEnabled(!mState.enabled);
     }
 
     @Override
-    protected void handleSecondaryClick() {
+    protected void handleClick() {
         if (!mWifiController.canConfigWifi()) {
             mHost.startActivityDismissingKeyguard(new Intent(Settings.ACTION_WIFI_SETTINGS));
             return;
@@ -125,7 +113,6 @@
 
     @Override
     protected void handleUpdateState(SignalState state, Object arg) {
-        state.visible = true;
         if (DEBUG) Log.d(TAG, "handleUpdateState arg=" + arg);
         CallbackInfo cb = (CallbackInfo) arg;
         if (cb == null) {
@@ -201,6 +188,10 @@
         return string;
     }
 
+    public static boolean isSupported(Host host) {
+        return host.getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI);
+    }
+
     protected static final class CallbackInfo {
         boolean enabled;
         boolean connected;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
index 7605f3b8..07915f8 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
@@ -22,14 +22,8 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.UserInfo;
-import android.os.IUserManager;
-import android.os.RemoteException;
-import android.os.ServiceManager;
 import android.os.UserHandle;
 import android.os.UserManager;
-import android.util.ArraySet;
-import android.util.Log;
-
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSTile;
@@ -110,8 +104,7 @@
     @Override
     protected void handleUpdateState(BooleanState state, Object arg) {
         if (!hasActiveProfile()) {
-            state.visible = false;
-            state.value = false;
+            mHost.removeTile(getTileSpec());
             return;
         }
 
@@ -124,7 +117,6 @@
             userInitialized = false;
         }
 
-        state.visible = true;
         final AnimationIcon icon;
         state.label = mContext.getString(R.string.quick_settings_work_mode_label);
         if (state.value) {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
index a0a1bac..7ae686e 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
@@ -411,6 +411,8 @@
             RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
             if (launchState.launchedViaDragGesture) {
                 setTranslationY(getMeasuredHeight());
+            } else {
+                setTranslationY(0f);
             }
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index e51cf7ac..6dde157 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -2233,6 +2233,10 @@
         mHandler.post(mAnimateCollapsePanels);
     }
 
+    public void postAnimateOpenPanels() {
+        mHandler.sendEmptyMessage(MSG_OPEN_SETTINGS_PANEL);
+    }
+
     public void animateCollapsePanels(int flags) {
         animateCollapsePanels(flags, false /* force */, false /* delayed */,
                 1.0f /* speedUpFactor */);
@@ -3282,6 +3286,16 @@
         return !isDeviceProvisioned() || (mDisabled1 & StatusBarManager.DISABLE_SEARCH) != 0;
     }
 
+    public void postQSRunnableDismissingKeyguard(final Runnable runnable) {
+        mHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                mLeaveOpenOnKeyguardHide = true;
+                executeRunnableDismissingKeyguard(runnable, null, false, true);
+            }
+        });
+    }
+
     public void postStartActivityDismissingKeyguard(final PendingIntent intent) {
         mHandler.post(new Runnable() {
             @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java
index 327b81e..c740b08 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java
@@ -16,6 +16,7 @@
 
 package com.android.systemui.statusbar.phone;
 
+import android.app.ActivityManager;
 import android.app.PendingIntent;
 import android.content.ComponentName;
 import android.content.Context;
@@ -27,10 +28,11 @@
 import android.os.Looper;
 import android.os.Process;
 import android.os.RemoteException;
+import android.provider.Settings;
 import android.service.quicksettings.IQSService;
 import android.service.quicksettings.Tile;
+import android.text.TextUtils;
 import android.util.Log;
-
 import com.android.systemui.R;
 import com.android.systemui.qs.QSTile;
 import com.android.systemui.qs.tiles.AirplaneModeTile;
@@ -45,12 +47,6 @@
 import com.android.systemui.qs.tiles.HotspotTile;
 import com.android.systemui.qs.tiles.IntentTile;
 import com.android.systemui.qs.tiles.LocationTile;
-import com.android.systemui.qs.tiles.QAirplaneTile;
-import com.android.systemui.qs.tiles.QBluetoothTile;
-import com.android.systemui.qs.tiles.QFlashlightTile;
-import com.android.systemui.qs.tiles.QLockTile;
-import com.android.systemui.qs.tiles.QRotationLockTile;
-import com.android.systemui.qs.tiles.QWifiTile;
 import com.android.systemui.qs.tiles.RotationLockTile;
 import com.android.systemui.qs.tiles.UserTile;
 import com.android.systemui.qs.tiles.WifiTile;
@@ -166,6 +162,11 @@
     }
 
     @Override
+    public void startRunnableDismissingKeyguard(Runnable runnable) {
+        mStatusBar.postQSRunnableDismissingKeyguard(runnable);
+    }
+
+    @Override
     public void warn(String message, Throwable t) {
         // already logged
     }
@@ -176,6 +177,11 @@
     }
 
     @Override
+    public void openPanels() {
+        mStatusBar.postAnimateOpenPanels();
+    }
+
+    @Override
     public Looper getLooper() {
         return mLooper;
     }
@@ -273,8 +279,10 @@
                 if (DEBUG) Log.d(TAG, "Creating tile: " + tileSpec);
                 try {
                     QSTile<?> tile = createTile(tileSpec);
-                    tile.setTileSpec(tileSpec);
-                    newTiles.put(tileSpec, tile);
+                    if (tile != null) {
+                        tile.setTileSpec(tileSpec);
+                        newTiles.put(tileSpec, tile);
+                    }
                 } catch (Throwable t) {
                     Log.w(TAG, "Error creating tile for spec: " + tileSpec, t);
                 }
@@ -290,6 +298,14 @@
     }
 
     @Override
+    public void removeTile(String tileSpec) {
+        ArrayList<String> specs = new ArrayList<>(mTileSpecs);
+        specs.remove(tileSpec);
+        Settings.Secure.putStringForUser(mContext.getContentResolver(), TILES_SETTING,
+                TextUtils.join(",", specs), ActivityManager.getCurrentUser());
+    }
+
+    @Override
     public void updateQsTile(Tile tile) throws RemoteException {
         verifyCaller(tile.getComponentName().getPackageName());
         CustomTile customTile = getTileForComponent(tile.getComponentName());
@@ -334,13 +350,17 @@
     }
 
     public QSTile<?> createTile(String tileSpec) {
-        if (tileSpec.equals("wifi")) return new WifiTile(this, false);
-        else if (tileSpec.equals("bt")) return new BluetoothTile(this, false);
+        if (tileSpec.equals("wifi")) return WifiTile.isSupported(this)
+                ? new WifiTile(this) : null;
+        else if (tileSpec.equals("bt")) return BluetoothTile.isSupported(this)
+                ? new BluetoothTile(this) : null;
+        else if (tileSpec.equals("cell")) return CellularTile.isSupported(this)
+                ? new CellularTile(this) : null;
+        else if (tileSpec.equals("dnd")) return DndTile.isSupported(this)
+                ? new DndTile(this) : null;
         else if (tileSpec.equals("inversion")) return new ColorInversionTile(this);
-        else if (tileSpec.equals("cell")) return new CellularTile(this);
         else if (tileSpec.equals("airplane")) return new AirplaneModeTile(this);
         else if (tileSpec.equals("work")) return new WorkModeTile(this);
-        else if (tileSpec.equals("dnd")) return new DndTile(this);
         else if (tileSpec.equals("rotation")) return new RotationLockTile(this);
         else if (tileSpec.equals("flashlight")) return new FlashlightTile(this);
         else if (tileSpec.equals("location")) return new LocationTile(this);
@@ -348,16 +368,6 @@
         else if (tileSpec.equals("hotspot")) return new HotspotTile(this);
         else if (tileSpec.equals("user")) return new UserTile(this);
         else if (tileSpec.equals("battery")) return new BatteryTile(this);
-        // Detail only versions of wifi and bluetooth.
-        else if (tileSpec.equals("dwifi")) return new WifiTile(this, true);
-        else if (tileSpec.equals("dbt")) return new BluetoothTile(this, true);
-        // Quick tiles, no text.
-        else if (tileSpec.equals("qwifi")) return new QWifiTile(this);
-        else if (tileSpec.equals("qbt")) return new QBluetoothTile(this);
-        else if (tileSpec.equals("qairplane")) return new QAirplaneTile(this);
-        else if (tileSpec.equals("qrotation")) return new QRotationLockTile(this);
-        else if (tileSpec.equals("qflashlight")) return new QFlashlightTile(this);
-        else if (tileSpec.equals("qlock")) return new QLockTile(this);
         // Intent tiles.
         else if (tileSpec.startsWith(IntentTile.PREFIX)) return IntentTile.create(this,tileSpec);
         else if (tileSpec.startsWith(CustomTile.PREFIX)) return CustomTile.create(this,tileSpec);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
index cc9f5c7..26ff97a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
@@ -30,10 +30,10 @@
 import android.widget.Switch;
 import android.widget.TextView;
 import android.widget.Toast;
-
 import com.android.systemui.R;
 import com.android.systemui.qs.QSPanel;
 import com.android.systemui.qs.QSTile;
+import com.android.systemui.qs.QuickQSPanel;
 import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.NextAlarmController;
 import com.android.systemui.statusbar.policy.UserInfoController;
@@ -63,7 +63,7 @@
     private boolean mListening;
     private AlarmManager.AlarmClockInfo mNextAlarm;
 
-    private QSPanel mHeaderQsPanel;
+    private QuickQSPanel mHeaderQsPanel;
 
     public QuickStatusBarHeader(Context context, AttributeSet attrs) {
         super(context, attrs);
@@ -75,7 +75,7 @@
 
         mExpandedGroup = (ViewGroup) findViewById(R.id.expanded_group);
 
-        mHeaderQsPanel = (QSPanel) findViewById(R.id.quick_qs_panel);
+        mHeaderQsPanel = (QuickQSPanel) findViewById(R.id.quick_qs_panel);
 
         mSettingsButton = (SettingsButton) findViewById(R.id.settings_button);
         mSettingsContainer = findViewById(R.id.settings_button_container);
@@ -133,9 +133,10 @@
 
     @Override
     public void setExpansion(float headerExpansionFraction) {
-        float offset = getHeight() * headerExpansionFraction;
-        mExpandedGroup.setTranslationY(offset - getHeight());
-        mHeaderQsPanel.setTranslationY(offset);
+        mExpandedGroup.setAlpha(headerExpansionFraction);
+        mExpandedGroup.setVisibility(headerExpansionFraction > 0 ? View.VISIBLE : View.INVISIBLE);
+        mHeaderQsPanel.setAlpha(1 - headerExpansionFraction);
+        mHeaderQsPanel.setVisibility(headerExpansionFraction < 1 ? View.VISIBLE : View.INVISIBLE);
     }
 
     public void setListening(boolean listening) {
@@ -190,7 +191,9 @@
                 host.getUserSwitcherController(), host.getUserInfoController(),
                 host.getKeyguardMonitor(), host.getSecurityController(),
                 host.getBatteryController());
+        mHeaderQsPanel.setQSPanelAndHeader(mQsPanel, this);
         mHeaderQsPanel.setHost(myHost);
+        mHeaderQsPanel.setMaxTiles(3);
         mHeaderQsPanel.setTiles(myHost.getTiles());
         myHost.addCallback(new QSTile.Host.Callback() {
             @Override
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/QSPagingSwitch.java b/packages/SystemUI/src/com/android/systemui/tuner/QSPagingSwitch.java
index 04a51f0..d19a825 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/QSPagingSwitch.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/QSPagingSwitch.java
@@ -9,8 +9,8 @@
 public class QSPagingSwitch extends TunerSwitch {
 
     public static final String QS_PAGE_TILES =
-            "dwifi,dbt,dnd,cell,battery,user,rotation,flashlight,location,"
-             + "hotspot,qwifi,qbt,qlock,qflashlight,qairplane,inversion,cast";
+            "dnd,cell,battery,user,rotation,flashlight,location,"
+             + "hotspot,inversion,cast";
 
     public QSPagingSwitch(Context context, AttributeSet attrs) {
         super(context, attrs);
diff --git a/services/core/java/com/android/server/MountService.java b/services/core/java/com/android/server/MountService.java
index 807c0d6..184f890 100644
--- a/services/core/java/com/android/server/MountService.java
+++ b/services/core/java/com/android/server/MountService.java
@@ -57,6 +57,7 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.ParcelFileDescriptor;
+import android.os.PowerManager;
 import android.os.Process;
 import android.os.RemoteCallbackList;
 import android.os.RemoteException;
@@ -175,8 +176,8 @@
         }
 
         @Override
-        public void onStartUser(int userHandle) {
-            mMountService.onStartUser(userHandle);
+        public void onUnlockUser(int userHandle) {
+            mMountService.onUnlockUser(userHandle);
         }
 
         @Override
@@ -286,10 +287,12 @@
      */
     private final Object mLock = new Object();
 
+    /** Set of users that we know are unlocked. */
     @GuardedBy("mLock")
-    private int[] mStartedUsers = EmptyArray.INT;
+    private int[] mLocalUnlockedUsers = EmptyArray.INT;
+    /** Set of users that system knows are unlocked. */
     @GuardedBy("mLock")
-    private int[] mUnlockedUsers = EmptyArray.INT;
+    private int[] mSystemUnlockedUsers = EmptyArray.INT;
 
     /** Map from disk ID to disk */
     @GuardedBy("mLock")
@@ -834,12 +837,21 @@
     private void initIfReadyAndConnected() {
         Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
                 + ", mDaemonConnected=" + mDaemonConnected);
-        if (mSystemReady && mDaemonConnected && StorageManager.isFileBasedEncryptionEnabled()) {
-            final List<UserInfo> users = mContext.getSystemService(UserManager.class)
-                    .getUsers();
+        if (mSystemReady && mDaemonConnected
+                && !StorageManager.isNativeFileBasedEncryptionEnabled()) {
+            // When booting a device without native support, make sure that our
+            // user directories are locked or unlocked based on the current
+            // emulation status.
+            final boolean initLocked = StorageManager.isEmulatedFileBasedEncryptionEnabled();
+            final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
             for (UserInfo user : users) {
                 try {
-                    mCryptConnector.execute("cryptfs", "lock_user_key", user.id);
+                    if (initLocked) {
+                        mCryptConnector.execute("cryptfs", "lock_user_key", user.id);
+                    } else {
+                        mCryptConnector.execute("cryptfs", "unlock_user_key", user.id,
+                                user.serialNumber, "!");
+                    }
                 } catch (NativeDaemonConnectorException e) {
                     Slog.w(TAG, "Failed to init vold", e);
                 }
@@ -854,9 +866,9 @@
             final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
             killMediaProvider(users);
 
-            final int[] startedUsers;
+            final int[] systemUnlockedUsers;
             synchronized (mLock) {
-                startedUsers = mStartedUsers;
+                systemUnlockedUsers = mSystemUnlockedUsers;
 
                 mDisks.clear();
                 mVolumes.clear();
@@ -871,7 +883,7 @@
                 for (UserInfo user : users) {
                     mConnector.execute("volume", "user_added", user.id, user.serialNumber);
                 }
-                for (int userId : startedUsers) {
+                for (int userId : systemUnlockedUsers) {
                     mConnector.execute("volume", "user_started", userId);
                 }
             } catch (NativeDaemonConnectorException e) {
@@ -880,8 +892,8 @@
         }
     }
 
-    private void onStartUser(int userId) {
-        Slog.d(TAG, "onStartUser " + userId);
+    private void onUnlockUser(int userId) {
+        Slog.d(TAG, "onUnlockUser " + userId);
 
         // We purposefully block here to make sure that user-specific
         // staging area is ready so it's ready for zygote-forked apps to
@@ -904,7 +916,7 @@
                     mCallbacks.notifyStorageStateChanged(userVol.getPath(), envState, envState);
                 }
             }
-            mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userId);
+            mSystemUnlockedUsers = ArrayUtils.appendInt(mSystemUnlockedUsers, userId);
         }
     }
 
@@ -917,7 +929,7 @@
         }
 
         synchronized (mVolumes) {
-            mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userId);
+            mSystemUnlockedUsers = ArrayUtils.removeInt(mSystemUnlockedUsers, userId);
         }
     }
 
@@ -1337,7 +1349,7 @@
             // Kick state changed event towards all started users. Any users
             // started after this point will trigger additional
             // user-specific broadcasts.
-            for (int userId : mStartedUsers) {
+            for (int userId : mSystemUnlockedUsers) {
                 if (vol.isVisibleForRead(userId)) {
                     final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
                     mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
@@ -1926,8 +1938,16 @@
         waitForReady();
 
         if ((mask & StorageManager.DEBUG_EMULATE_FBE) != 0) {
+            if (StorageManager.isNativeFileBasedEncryptionEnabled()) {
+                throw new IllegalStateException(
+                        "Emulation not available on device with native FBE");
+            }
+
             final boolean emulateFbe = (flags & StorageManager.DEBUG_EMULATE_FBE) != 0;
             SystemProperties.set(StorageManager.PROP_EMULATE_FBE, Boolean.toString(emulateFbe));
+
+            // Perform hard reboot to kick policy into place
+            mContext.getSystemService(PowerManager.class).reboot(null);
         }
 
         if ((mask & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0) {
@@ -2696,12 +2716,13 @@
     }
 
     @Override
-    public void createUserKey(int userId, int serialNumber) {
+    public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
         enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
         waitForReady();
 
         try {
-            mCryptConnector.execute("cryptfs", "create_user_key", userId, serialNumber);
+            mCryptConnector.execute("cryptfs", "create_user_key", userId, serialNumber,
+                ephemeral ? 1 : 0);
         } catch (NativeDaemonConnectorException e) {
             throw e.rethrowAsParcelableException();
         }
@@ -2745,7 +2766,7 @@
         }
 
         synchronized (mLock) {
-            mUnlockedUsers = ArrayUtils.appendInt(mUnlockedUsers, userId);
+            mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
         }
     }
 
@@ -2761,7 +2782,7 @@
         }
 
         synchronized (mLock) {
-            mUnlockedUsers = ArrayUtils.removeInt(mUnlockedUsers, userId);
+            mLocalUnlockedUsers = ArrayUtils.removeInt(mLocalUnlockedUsers, userId);
         }
     }
 
@@ -2769,7 +2790,7 @@
     public boolean isUserKeyUnlocked(int userId) {
         if (StorageManager.isFileBasedEncryptionEnabled()) {
             synchronized (mLock) {
-                return ArrayUtils.contains(mUnlockedUsers, userId);
+                return ArrayUtils.contains(mLocalUnlockedUsers, userId);
             }
         } else {
             return true;
@@ -2777,13 +2798,14 @@
     }
 
     @Override
-    public void prepareUserStorage(String volumeUuid, int userId, int serialNumber) {
+    public void prepareUserStorage(
+            String volumeUuid, int userId, int serialNumber, boolean ephemeral) {
         enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
         waitForReady();
 
         try {
             mCryptConnector.execute("cryptfs", "prepare_user_storage", escapeNull(volumeUuid),
-                    userId, serialNumber);
+                    userId, serialNumber, ephemeral ? 1 : 0);
         } catch (NativeDaemonConnectorException e) {
             throw e.rethrowAsParcelableException();
         }
@@ -2836,21 +2858,25 @@
 
     @Override
     public StorageVolume[] getVolumeList(int uid, String packageName, int flags) {
+        final int userId = UserHandle.getUserId(uid);
         final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
 
-        final ArrayList<StorageVolume> res = new ArrayList<>();
+        boolean reportUnmounted = false;
         boolean foundPrimary = false;
 
-        final int userId = UserHandle.getUserId(uid);
-        final boolean reportUnmounted;
         final long identity = Binder.clearCallingIdentity();
         try {
-            reportUnmounted = !mMountServiceInternal.hasExternalStorage(
-                    uid, packageName);
+            if (!mMountServiceInternal.hasExternalStorage(uid, packageName)) {
+                reportUnmounted = true;
+            }
+            if (!isUserKeyUnlocked(userId)) {
+                reportUnmounted = true;
+            }
         } finally {
             Binder.restoreCallingIdentity(identity);
         }
 
+        final ArrayList<StorageVolume> res = new ArrayList<>();
         synchronized (mLock) {
             for (int i = 0; i < mVolumes.size(); i++) {
                 final VolumeInfo vol = mVolumes.valueAt(i);
@@ -3530,8 +3556,8 @@
             pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
             pw.println("Force adoptable: " + mForceAdoptable);
             pw.println();
-            pw.println("Started users: " + Arrays.toString(mStartedUsers));
-            pw.println("Unlocked users: " + Arrays.toString(mUnlockedUsers));
+            pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
+            pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
         }
 
         synchronized (mObbMounts) {
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index d6106d7..f22062c 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -17000,6 +17000,15 @@
             }
         }
 
+        final String action = intent.getAction();
+        final boolean isProtectedBroadcast;
+        try {
+            isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
+        } catch (RemoteException e) {
+            Slog.w(TAG, "Remote exception", e);
+            return ActivityManager.BROADCAST_SUCCESS;
+        }
+
         /*
          * Prevent non-system code (defined here to be non-persistent
          * processes) from sending protected broadcasts.
@@ -17009,49 +17018,54 @@
             || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID
             || callingAppId == Process.NFC_UID || callingUid == 0) {
             // Always okay.
+
+            // Yell if the system is trying to send a non-protected broadcast.
+            // The vast majority of broadcasts sent from system callers should
+            // be protected to avoid security holes, so exceptions here should
+            // be incredibly rare.
+            if (!isProtectedBroadcast
+                    && !Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
+                // TODO: eventually switch over to hard throw
+                Log.wtf(TAG, "Sending non-protected broadcast " + action
+                        + " from system", new Throwable());
+            }
+
         } else if (callerApp == null || !callerApp.persistent) {
-            try {
-                if (AppGlobals.getPackageManager().isProtectedBroadcast(
-                        intent.getAction())) {
+            if (isProtectedBroadcast) {
+                String msg = "Permission Denial: not allowed to send broadcast "
+                        + action + " from pid="
+                        + callingPid + ", uid=" + callingUid;
+                Slog.w(TAG, msg);
+                throw new SecurityException(msg);
+            } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)) {
+                // Special case for compatibility: we don't want apps to send this,
+                // but historically it has not been protected and apps may be using it
+                // to poke their own app widget.  So, instead of making it protected,
+                // just limit it to the caller.
+                if (callerApp == null) {
                     String msg = "Permission Denial: not allowed to send broadcast "
-                            + intent.getAction() + " from pid="
-                            + callingPid + ", uid=" + callingUid;
+                            + action + " from unknown caller.";
                     Slog.w(TAG, msg);
                     throw new SecurityException(msg);
-                } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) {
-                    // Special case for compatibility: we don't want apps to send this,
-                    // but historically it has not been protected and apps may be using it
-                    // to poke their own app widget.  So, instead of making it protected,
-                    // just limit it to the caller.
-                    if (callerApp == null) {
+                } else if (intent.getComponent() != null) {
+                    // They are good enough to send to an explicit component...  verify
+                    // it is being sent to the calling app.
+                    if (!intent.getComponent().getPackageName().equals(
+                            callerApp.info.packageName)) {
                         String msg = "Permission Denial: not allowed to send broadcast "
-                                + intent.getAction() + " from unknown caller.";
+                                + action + " to "
+                                + intent.getComponent().getPackageName() + " from "
+                                + callerApp.info.packageName;
                         Slog.w(TAG, msg);
                         throw new SecurityException(msg);
-                    } else if (intent.getComponent() != null) {
-                        // They are good enough to send to an explicit component...  verify
-                        // it is being sent to the calling app.
-                        if (!intent.getComponent().getPackageName().equals(
-                                callerApp.info.packageName)) {
-                            String msg = "Permission Denial: not allowed to send broadcast "
-                                    + intent.getAction() + " to "
-                                    + intent.getComponent().getPackageName() + " from "
-                                    + callerApp.info.packageName;
-                            Slog.w(TAG, msg);
-                            throw new SecurityException(msg);
-                        }
-                    } else {
-                        // Limit broadcast to their own package.
-                        intent.setPackage(callerApp.info.packageName);
                     }
+                } else {
+                    // Limit broadcast to their own package.
+                    intent.setPackage(callerApp.info.packageName);
                 }
-            } catch (RemoteException e) {
-                Slog.w(TAG, "Remote exception", e);
-                return ActivityManager.BROADCAST_SUCCESS;
             }
         }
 
-        final String action = intent.getAction();
         if (action != null) {
             switch (action) {
                 case Intent.ACTION_UID_REMOVED:
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 4f04519..ab8e5a7 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -34,7 +34,6 @@
 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
-import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
 import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
@@ -94,8 +93,6 @@
 import android.app.IActivityManager;
 import android.app.admin.IDevicePolicyManager;
 import android.app.backup.IBackupManager;
-import android.app.usage.UsageStats;
-import android.app.usage.UsageStatsManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -4093,8 +4090,15 @@
     @Override
     public boolean isProtectedBroadcast(String actionName) {
         synchronized (mPackages) {
-            return mProtectedBroadcasts.contains(actionName);
+            if (mProtectedBroadcasts.contains(actionName)) {
+                return true;
+            } else if (actionName != null
+                    && actionName.startsWith("android.net.netmon.lingerExpired")) {
+                // TODO: remove this terrible hack
+                return true;
+            }
         }
+        return false;
     }
 
     @Override
@@ -16446,7 +16450,7 @@
             if (userDir.exists()) continue;
 
             try {
-                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
+                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
                 UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
             } catch (IOException e) {
                 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
@@ -16835,13 +16839,11 @@
             mPendingBroadcasts.remove(userHandle);
         }
         synchronized (mInstallLock) {
-            if (mInstaller != null) {
-                final StorageManager storage = mContext.getSystemService(StorageManager.class);
-                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
-                    final String volumeUuid = vol.getFsUuid();
-                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
-                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
-                }
+            final StorageManager storage = mContext.getSystemService(StorageManager.class);
+            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
+                final String volumeUuid = vol.getFsUuid();
+                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
+                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
             }
             synchronized (mPackages) {
                 removeUnusedPackagesLILPw(userManager, userHandle);
@@ -16903,17 +16905,13 @@
 
     /** Called by UserManagerService */
     void createNewUser(int userHandle) {
-        if (mInstaller != null) {
-            synchronized (mInstallLock) {
-                synchronized (mPackages) {
-                    mInstaller.createUserConfig(userHandle);
-                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
-                }
-            }
-            synchronized (mPackages) {
-                applyFactoryDefaultBrowserLPw(userHandle);
-                primeDomainVerificationsLPw(userHandle);
-            }
+        synchronized (mInstallLock) {
+            mInstaller.createUserConfig(userHandle);
+            mSettings.createNewUserLI(this, mInstaller, userHandle);
+        }
+        synchronized (mPackages) {
+            applyFactoryDefaultBrowserLPw(userHandle);
+            primeDomainVerificationsLPw(userHandle);
         }
     }
 
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index 99aa30b..22f8e96 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -3644,21 +3644,47 @@
         }
     }
 
-    void createNewUserLILPw(PackageManagerService service, Installer installer, int userHandle) {
-        for (PackageSetting ps : mPackages.values()) {
-            if (ps.pkg == null || ps.pkg.applicationInfo == null) {
+    void createNewUserLI(@NonNull PackageManagerService service, @NonNull Installer installer,
+            int userHandle) {
+        String[] volumeUuids;
+        String[] names;
+        int[] uids;
+        String[] seinfos;
+        int packagesCount;
+        synchronized (mPackages) {
+            Collection<PackageSetting> packages = mPackages.values();
+            packagesCount = packages.size();
+            volumeUuids = new String[packagesCount];
+            names = new String[packagesCount];
+            uids = new int[packagesCount];
+            seinfos = new String[packagesCount];
+            Iterator<PackageSetting> packagesIterator = packages.iterator();
+            for (int i = 0; i < packagesCount; i++) {
+                PackageSetting ps = packagesIterator.next();
+                if (ps.pkg == null || ps.pkg.applicationInfo == null) {
+                    continue;
+                }
+                // Only system apps are initially installed.
+                ps.setInstalled(ps.isSystem(), userHandle);
+                // Need to create a data directory for all apps under this user. Accumulate all
+                // required args and call the installer after mPackages lock has been released
+                volumeUuids[i] = ps.volumeUuid;
+                names[i] = ps.name;
+                uids[i] = UserHandle.getUid(userHandle, ps.appId);
+                seinfos[i] = ps.pkg.applicationInfo.seinfo;
+            }
+        }
+        for (int i = 0; i < packagesCount; i++) {
+            if (names[i] == null) {
                 continue;
             }
-            // Only system apps are initially installed.
-            ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle);
-            // Need to create a data directory for all apps under this user.
-            installer.createUserData(ps.volumeUuid, ps.name,
-                    UserHandle.getUid(userHandle, ps.appId), userHandle,
-                    ps.pkg.applicationInfo.seinfo);
+            installer.createUserData(volumeUuids[i], names[i], uids[i], userHandle, seinfos[i]);
         }
-        applyDefaultPreferredAppsLPw(service, userHandle);
-        writePackageRestrictionsLPr(userHandle);
-        writePackageListLPr(userHandle);
+        synchronized (mPackages) {
+            applyDefaultPreferredAppsLPw(service, userHandle);
+            writePackageRestrictionsLPr(userHandle);
+            writePackageListLPr(userHandle);
+        }
     }
 
     void removeUserLPw(int userId) {
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index 5910c10..4497e4d 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -306,13 +306,13 @@
     }
 
     void systemReady() {
-        // Prune out any partially created/partially removed users.
+        // Prune out any partially created, partially removed and ephemeral users.
         ArrayList<UserInfo> partials = new ArrayList<>();
         synchronized (mUsersLock) {
             final int userSize = mUsers.size();
             for (int i = 0; i < userSize; i++) {
                 UserInfo ui = mUsers.valueAt(i);
-                if ((ui.partial || ui.guestToRemove) && i != 0) {
+                if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
                     partials.add(ui);
                 }
             }
@@ -845,6 +845,15 @@
     }
 
     @Override
+    public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
+        checkManageUsersPermission("hasBaseUserRestriction");
+        synchronized (mRestrictionsLock) {
+            Bundle bundle = mBaseUserRestrictions.get(userId);
+            return (bundle != null && bundle.getBoolean(restrictionKey, false));
+        }
+    }
+
+    @Override
     public void setUserRestriction(String key, boolean value, int userId) {
         checkManageUsersPermission("setUserRestriction");
         synchronized (mRestrictionsLock) {
@@ -1666,6 +1675,10 @@
                         }
                     }
                 }
+
+                if (parent != null && parent.isEphemeral()) {
+                    flags |= UserInfo.FLAG_EPHEMERAL;
+                }
                 userId = getNextAvailableId();
                 userInfo = new UserInfo(userId, name, null, flags);
                 userInfo.serialNumber = mNextSerialNumber++;
@@ -1694,12 +1707,13 @@
                 }
             }
             final StorageManager storage = mContext.getSystemService(StorageManager.class);
-            storage.createUserKey(userId, userInfo.serialNumber);
+            storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
                 final String volumeUuid = vol.getFsUuid();
                 try {
                     final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
-                    storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
+                    storage.prepareUserStorage(
+                            volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
                     enforceSerialNumber(userDir, userInfo.serialNumber);
                 } catch (IOException e) {
                     Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index fe427d3..b9a9d6e 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -396,6 +396,7 @@
     boolean mDeskDockEnablesAccelerometer;
     int mLidKeyboardAccessibility;
     int mLidNavigationAccessibility;
+    boolean mLidControlsScreenLock;
     boolean mLidControlsSleep;
     int mShortPressOnPowerBehavior;
     int mLongPressOnPowerBehavior;
@@ -1440,6 +1441,8 @@
                 com.android.internal.R.integer.config_lidKeyboardAccessibility);
         mLidNavigationAccessibility = mContext.getResources().getInteger(
                 com.android.internal.R.integer.config_lidNavigationAccessibility);
+        mLidControlsScreenLock = mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_lidControlsScreenLock);
         mLidControlsSleep = mContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_lidControlsSleep);
         mTranslucentDecorEnabled = mContext.getResources().getBoolean(
@@ -6378,6 +6381,8 @@
             mPowerManager.goToSleep(SystemClock.uptimeMillis(),
                     PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
                     PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
+        } else if (mLidState == LID_CLOSED && mLidControlsScreenLock) {
+            mWindowManagerFuncs.lockDeviceNow();
         }
 
         synchronized (mLock) {
@@ -6970,6 +6975,7 @@
         pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
                 pw.print(mLidKeyboardAccessibility);
                 pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
+                pw.print(" mLidControlsScreenLock="); pw.println(mLidControlsScreenLock);
                 pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
         pw.print(prefix);
                 pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index a4b4276..e6b649e7 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -16,6 +16,9 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.animation.ObjectAnimator;
 import android.animation.ValueAnimator;
 import android.app.Service;
@@ -219,7 +222,7 @@
      */
     private static final class DisplayMagnifier {
 
-        private static final String LOG_TAG = "DisplayMagnifier";
+        private static final String LOG_TAG = TAG_WITH_CLASS_NAME ? "DisplayMagnifier" : TAG_WM;
 
         private static final boolean DEBUG_WINDOW_TRANSITIONS = false;
         private static final boolean DEBUG_ROTATION = false;
@@ -925,7 +928,8 @@
      * user can see on the screen.
      */
     private static final class WindowsForAccessibilityObserver {
-        private static final String LOG_TAG = "WindowsForAccessibilityObserver";
+        private static final String LOG_TAG = TAG_WITH_CLASS_NAME ?
+                "WindowsForAccessibilityObserver" : TAG_WM;
 
         private static final boolean DEBUG = false;
 
diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java
index d394125..a7a4ed1 100644
--- a/services/core/java/com/android/server/wm/AppTransition.java
+++ b/services/core/java/com/android/server/wm/AppTransition.java
@@ -39,6 +39,8 @@
 import static com.android.internal.R.styleable.WindowAnimation_wallpaperIntraOpenExitAnimation;
 import static com.android.internal.R.styleable.WindowAnimation_wallpaperOpenEnterAnimation;
 import static com.android.internal.R.styleable.WindowAnimation_wallpaperOpenExitAnimation;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.annotation.Nullable;
 import android.content.Context;
@@ -46,7 +48,6 @@
 import android.graphics.Bitmap;
 import android.graphics.Rect;
 import android.os.Debug;
-import android.os.Handler;
 import android.os.IBinder;
 import android.os.IRemoteCallback;
 import android.os.RemoteException;
@@ -73,6 +74,7 @@
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
@@ -82,10 +84,10 @@
 // mOpeningApps and mClosingApps are the lists of tokens that will be
 // made visible or hidden at the next transition.
 public class AppTransition implements Dump {
-    private static final String TAG = "AppTransition";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "AppTransition" : TAG_WM;
     private static final boolean DEBUG_APP_TRANSITIONS =
-            WindowManagerService.DEBUG_APP_TRANSITIONS;
-    private static final boolean DEBUG_ANIM = WindowManagerService.DEBUG_ANIM;
+            WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
+    private static final boolean DEBUG_ANIM = WindowManagerDebugConfig.DEBUG_ANIM;
     private static final int CLIP_REVEAL_TRANSLATION_Y_DP = 8;
 
     /** Not set up for a transition. */
@@ -308,6 +310,16 @@
         return mNextAppTransitionScaleUp;
     }
 
+    boolean isNextAppTransitionThumbnailUp() {
+        return mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_SCALE_UP ||
+                mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_ASPECT_SCALE_UP;
+    }
+
+    boolean isNextAppTransitionThumbnailDown() {
+        return mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_SCALE_DOWN ||
+                mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_ASPECT_SCALE_DOWN;
+    }
+
     /**
      * @return true if and only if we are currently fetching app transition specs from the future
      *         passed into {@link #overridePendingAppTransitionMultiThumbFuture}
diff --git a/services/core/java/com/android/server/wm/AppWindowAnimator.java b/services/core/java/com/android/server/wm/AppWindowAnimator.java
index 4861acc..ab47f07 100644
--- a/services/core/java/com/android/server/wm/AppWindowAnimator.java
+++ b/services/core/java/com/android/server/wm/AppWindowAnimator.java
@@ -16,9 +16,12 @@
 
 package com.android.server.wm;
 
-import static com.android.server.wm.WindowManagerService.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerService.DEBUG_LAYERS;
-import static com.android.server.wm.WindowManagerService.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYERS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.TYPE_LAYER_OFFSET;
 
 import android.graphics.Matrix;
@@ -35,7 +38,7 @@
 import java.util.ArrayList;
 
 public class AppWindowAnimator {
-    static final String TAG = "AppWindowAnimator";
+    static final String TAG = TAG_WITH_CLASS_NAME ? "AppWindowAnimator" : TAG_WM;
 
     private static final int PROLONG_ANIMATION_DISABLED = 0;
     static final int PROLONG_ANIMATION_AT_END = 1;
@@ -410,8 +413,7 @@
         final int NW = mAllAppWinAnimators.size();
         for (int i=0; i<NW; i++) {
             WindowStateAnimator winAnimator = mAllAppWinAnimators.get(i);
-            if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(TAG,
-                    "performing show on: " + winAnimator);
+            if (DEBUG_VISIBILITY) Slog.v(TAG, "performing show on: " + winAnimator);
             winAnimator.performShowLocked();
             isAnimating |= winAnimator.isAnimating();
         }
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index 23ad1a81b..fd5c704 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -17,9 +17,12 @@
 package com.android.server.wm;
 
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
-import static com.android.server.wm.WindowManagerService.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerService.DEBUG_APP_TRANSITIONS;
-import static com.android.server.wm.WindowManagerService.TAG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_MOVEMENT;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import com.android.server.input.InputApplicationHandle;
 import com.android.server.wm.WindowManagerService.H;
@@ -44,6 +47,8 @@
  * really activity) that is displaying windows.
  */
 class AppWindowToken extends WindowToken {
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "AppWindowToken" : TAG_WM;
+
     // Non-null only for application tokens.
     final IApplicationToken appToken;
 
@@ -152,7 +157,7 @@
                 continue;
             }
             try {
-                if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(WindowManagerService.TAG,
+                if (DEBUG_VISIBILITY) Slog.v(TAG,
                         "Setting visibility of " + win + ": " + (!clientHidden));
                 win.mClient.dispatchAppVisibility(!clientHidden);
             } catch (RemoteException e) {
@@ -170,7 +175,7 @@
         int numDrawn = 0;
         boolean nowGone = true;
 
-        if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(WindowManagerService.TAG,
+        if (DEBUG_VISIBILITY) Slog.v(TAG,
                 "Update reported visibility: " + this);
         final int N = allAppWindows.size();
         for (int i=0; i<N; i++) {
@@ -181,12 +186,12 @@
                     || win.mDestroying) {
                 continue;
             }
-            if (WindowManagerService.DEBUG_VISIBILITY) {
-                Slog.v(WindowManagerService.TAG, "Win " + win + ": isDrawn="
+            if (DEBUG_VISIBILITY) {
+                Slog.v(TAG, "Win " + win + ": isDrawn="
                         + win.isDrawnLw()
                         + ", isAnimating=" + win.mWinAnimator.isAnimating());
                 if (!win.isDrawnLw()) {
-                    Slog.v(WindowManagerService.TAG, "Not displayed: s=" +
+                    Slog.v(TAG, "Not displayed: s=" +
                             win.mWinAnimator.mSurfaceController
                             + " pv=" + win.mPolicyVisibility
                             + " mDrawState=" + win.mWinAnimator.mDrawState
@@ -220,7 +225,7 @@
                 nowVisible = reportedVisible;
             }
         }
-        if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(WindowManagerService.TAG, "VIS " + this + ": interesting="
+        if (DEBUG_VISIBILITY) Slog.v(TAG, "VIS " + this + ": interesting="
                 + numInteresting + " visible=" + numVisible);
         if (nowDrawn != reportedDrawn) {
             if (nowDrawn) {
@@ -231,8 +236,8 @@
             reportedDrawn = nowDrawn;
         }
         if (nowVisible != reportedVisible) {
-            if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(
-                    WindowManagerService.TAG, "Visibility changed in " + this
+            if (DEBUG_VISIBILITY) Slog.v(
+                    TAG, "Visibility changed in " + this
                     + ": vis=" + nowVisible);
             reportedVisible = nowVisible;
             Message m = service.mH.obtainMessage(
@@ -295,7 +300,7 @@
         final Task task = mTask;
         if (task != null) {
             if (!task.removeAppToken(this)) {
-                Slog.e(WindowManagerService.TAG, "removeAppFromTaskLocked: token=" + this
+                Slog.e(TAG, "removeAppFromTaskLocked: token=" + this
                         + " not found.");
             }
             task.mStack.mExitingAppTokens.remove(this);
@@ -330,7 +335,7 @@
             return;
         }
 
-        if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
+        if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG_WM,
                 "Restoring saved surfaces: " + this + ", allDrawn=" + allDrawn);
 
         mAnimatingWithSavedSurface = true;
@@ -357,8 +362,8 @@
                 // and never beyond allAppWindows bounds.
                 winNdx = Math.min(winNdx - 1, allAppWindows.size() - 1)) {
             WindowState win = allAppWindows.get(winNdx);
-            if (WindowManagerService.DEBUG_WINDOW_MOVEMENT) {
-                Slog.w(WindowManagerService.TAG, "removeAllWindows: removing win=" + win);
+            if (DEBUG_WINDOW_MOVEMENT) {
+                Slog.w(TAG, "removeAllWindows: removing win=" + win);
             }
 
             service.removeWindowLocked(win);
@@ -377,8 +382,8 @@
                 winNdx = Math.min(winNdx - 1, allAppWindows.size() - 1)) {
             WindowState win = allAppWindows.get(winNdx);
             if (win.mAppDied) {
-                if (WindowManagerService.DEBUG_WINDOW_MOVEMENT) {
-                    Slog.w(WindowManagerService.TAG, "removeAllDeadWindows: " + win);
+                if (DEBUG_WINDOW_MOVEMENT) {
+                    Slog.w(TAG, "removeAllDeadWindows: " + win);
                 }
                 // Set mDestroying, we don't want any animation or delayed removal here.
                 win.mDestroying = true;
diff --git a/services/core/java/com/android/server/wm/BlackFrame.java b/services/core/java/com/android/server/wm/BlackFrame.java
index 7b08354..5c29a0a 100644
--- a/services/core/java/com/android/server/wm/BlackFrame.java
+++ b/services/core/java/com/android/server/wm/BlackFrame.java
@@ -16,6 +16,13 @@
 
 package com.android.server.wm;
 
+import static android.graphics.PixelFormat.OPAQUE;
+import static android.view.SurfaceControl.FX_SURFACE_DIM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import java.io.PrintWriter;
 
 import android.graphics.Matrix;
@@ -44,21 +51,20 @@
             int w = r-l;
             int h = b-t;
 
-            if (WindowManagerService.DEBUG_SURFACE_TRACE) {
+            if (DEBUG_SURFACE_TRACE) {
                 surface = new WindowSurfaceController.SurfaceTrace(session, "BlackSurface("
                         + l + ", " + t + ")",
-                        w, h, PixelFormat.OPAQUE, SurfaceControl.FX_SURFACE_DIM | SurfaceControl.HIDDEN);
+                        w, h, OPAQUE, FX_SURFACE_DIM | SurfaceControl.HIDDEN);
             } else {
                 surface = new SurfaceControl(session, "BlackSurface",
-                        w, h, PixelFormat.OPAQUE, SurfaceControl.FX_SURFACE_DIM | SurfaceControl.HIDDEN);
+                        w, h, OPAQUE, FX_SURFACE_DIM | SurfaceControl.HIDDEN);
             }
 
             surface.setAlpha(1);
             surface.setLayerStack(layerStack);
             surface.setLayer(layer);
             surface.show();
-            if (WindowManagerService.SHOW_TRANSACTIONS ||
-                    WindowManagerService.SHOW_SURFACE_ALLOC) Slog.i(WindowManagerService.TAG,
+            if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) Slog.i(TAG_WM,
                             "  BLACK " + surface + ": CREATE layer=" + layer);
         }
 
@@ -76,7 +82,7 @@
                     mTmpFloats[Matrix.MSCALE_X], mTmpFloats[Matrix.MSKEW_Y],
                     mTmpFloats[Matrix.MSKEW_X], mTmpFloats[Matrix.MSCALE_Y]);
             if (false) {
-                Slog.i(WindowManagerService.TAG, "Black Surface @ (" + left + "," + top + "): ("
+                Slog.i(TAG_WM, "Black Surface @ (" + left + "," + top + "): ("
                         + mTmpFloats[Matrix.MTRANS_X] + ","
                         + mTmpFloats[Matrix.MTRANS_Y] + ") matrix=["
                         + mTmpFloats[Matrix.MSCALE_X] + ","
@@ -149,10 +155,8 @@
         if (mBlackSurfaces != null) {
             for (int i=0; i<mBlackSurfaces.length; i++) {
                 if (mBlackSurfaces[i] != null) {
-                    if (WindowManagerService.SHOW_TRANSACTIONS ||
-                            WindowManagerService.SHOW_SURFACE_ALLOC) Slog.i(
-                                    WindowManagerService.TAG,
-                                    "  BLACK " + mBlackSurfaces[i].surface + ": DESTROY");
+                    if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) Slog.i(TAG_WM,
+                            "  BLACK " + mBlackSurfaces[i].surface + ": DESTROY");
                     mBlackSurfaces[i].surface.destroy();
                     mBlackSurfaces[i] = null;
                 }
diff --git a/services/core/java/com/android/server/wm/CircularDisplayMask.java b/services/core/java/com/android/server/wm/CircularDisplayMask.java
index 33cec64..ae41541 100644
--- a/services/core/java/com/android/server/wm/CircularDisplayMask.java
+++ b/services/core/java/com/android/server/wm/CircularDisplayMask.java
@@ -17,6 +17,9 @@
 package com.android.server.wm;
 
 
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.graphics.Canvas;
 import android.graphics.Color;
@@ -26,15 +29,15 @@
 import android.graphics.PorterDuff;
 import android.graphics.PorterDuffXfermode;
 import android.graphics.Rect;
+import android.util.Slog;
 import android.view.Display;
 import android.view.Surface;
 import android.view.Surface.OutOfResourcesException;
 import android.view.SurfaceControl;
 import android.view.SurfaceSession;
-import android.util.Slog;
 
 class CircularDisplayMask {
-    private static final String TAG = "CircularDisplayMask";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "CircularDisplayMask" : TAG_WM;
 
     // size of the chin
     private int mScreenOffset = 0;
@@ -64,7 +67,7 @@
 
         SurfaceControl ctrl = null;
         try {
-            if (WindowManagerService.DEBUG_SURFACE_TRACE) {
+            if (DEBUG_SURFACE_TRACE) {
                 ctrl = new WindowSurfaceController.SurfaceTrace(session, "CircularDisplayMask",
                         mScreenSize.x, mScreenSize.y, PixelFormat.TRANSLUCENT,
                         SurfaceControl.HIDDEN);
diff --git a/services/core/java/com/android/server/wm/DimLayer.java b/services/core/java/com/android/server/wm/DimLayer.java
index 4b3620f..6657a7b 100644
--- a/services/core/java/com/android/server/wm/DimLayer.java
+++ b/services/core/java/com/android/server/wm/DimLayer.java
@@ -16,6 +16,12 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.graphics.PixelFormat;
 import android.graphics.Rect;
 import android.os.SystemClock;
@@ -26,7 +32,7 @@
 import java.io.PrintWriter;
 
 public class DimLayer {
-    private static final String TAG = "DimLayer";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "DimLayer" : TAG_WM;
     private static final boolean DEBUG = false;
 
     public static final float RESIZING_HINT_ALPHA = 0.5f;
@@ -81,7 +87,7 @@
         if (DEBUG) Slog.v(TAG, "Ctor: displayId=" + displayId);
         SurfaceControl.openTransaction();
         try {
-            if (WindowManagerService.DEBUG_SURFACE_TRACE) {
+            if (DEBUG_SURFACE_TRACE) {
                 mDimSurface = new WindowSurfaceController.SurfaceTrace(service.mFxSession,
                     "DimSurface",
                     16, 16, PixelFormat.OPAQUE,
@@ -91,12 +97,11 @@
                     16, 16, PixelFormat.OPAQUE,
                     SurfaceControl.FX_SURFACE_DIM | SurfaceControl.HIDDEN);
             }
-            if (WindowManagerService.SHOW_TRANSACTIONS ||
-                    WindowManagerService.SHOW_SURFACE_ALLOC) Slog.i(TAG,
-                            "  DIM " + mDimSurface + ": CREATE");
+            if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) Slog.i(TAG,
+                    "  DIM " + mDimSurface + ": CREATE");
             mDimSurface.setLayerStack(displayId);
         } catch (Exception e) {
-            Slog.e(WindowManagerService.TAG, "Exception creating Dim surface", e);
+            Slog.e(TAG_WM, "Exception creating Dim surface", e);
         } finally {
             SurfaceControl.closeTransaction();
         }
diff --git a/services/core/java/com/android/server/wm/DimLayerController.java b/services/core/java/com/android/server/wm/DimLayerController.java
index bd30bd5..6d1cec4 100644
--- a/services/core/java/com/android/server/wm/DimLayerController.java
+++ b/services/core/java/com/android/server/wm/DimLayerController.java
@@ -1,6 +1,8 @@
 package com.android.server.wm;
 
-import static com.android.server.wm.WindowManagerService.DEBUG_DIM_LAYER;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DIM_LAYER;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.LAYER_OFFSET_DIM;
 
 import android.graphics.Rect;
@@ -16,7 +18,7 @@
  * as well as other use cases (such as dimming above a dead window).
  */
 class DimLayerController {
-    private static final String TAG = "DimLayerController";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "DimLayerController" : TAG_WM;
 
     /** Amount of time in milliseconds to animate the dim surface from one value to another,
      * when no window animation is driving it. */
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 898a9a4..9b64481 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -19,8 +19,8 @@
 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
 import static android.app.ActivityManager.StackId.HOME_STACK_ID;
 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
-import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
-import static com.android.server.wm.WindowManagerService.TAG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowState.RESIZE_HANDLE_WIDTH_IN_DP;
 
 import android.app.ActivityManager.StackId;
@@ -180,7 +180,7 @@
 
     TaskStack getHomeStack() {
         if (mHomeStack == null && mDisplayId == Display.DEFAULT_DISPLAY) {
-            Slog.e(TAG, "getHomeStack: Returning null from this=" + this);
+            Slog.e(TAG_WM, "getHomeStack: Returning null from this=" + this);
         }
         return mHomeStack;
     }
@@ -239,12 +239,12 @@
     void moveStack(TaskStack stack, boolean toTop) {
         if (StackId.isAlwaysOnTop(stack.mStackId) && !toTop) {
             // This stack is always-on-top silly...
-            Slog.w(TAG, "Ignoring move of always-on-top stack=" + stack + " to bottom");
+            Slog.w(TAG_WM, "Ignoring move of always-on-top stack=" + stack + " to bottom");
             return;
         }
 
         if (!mStacks.remove(stack)) {
-            Slog.wtf(TAG, "moving stack that was not added: " + stack, new Throwable());
+            Slog.wtf(TAG_WM, "moving stack that was not added: " + stack, new Throwable());
         }
 
         int addIndex = toTop ? mStacks.size() : 0;
@@ -422,7 +422,7 @@
         for (int i = 0; i < windows.size(); i++) {
             final WindowState win = windows.get(i);
             if (win.isHiddenFromUserLocked()) {
-                if (DEBUG_VISIBILITY) Slog.w(TAG, "user changing, hiding " + win
+                if (DEBUG_VISIBILITY) Slog.w(TAG_WM, "user changing, hiding " + win
                         + ", attrs=" + win.mAttrs.type + ", belonging to " + win.mOwnerUid);
                 win.hideLw(false);
             }
diff --git a/services/core/java/com/android/server/wm/DisplaySettings.java b/services/core/java/com/android/server/wm/DisplaySettings.java
index 80526f2..7f79686 100644
--- a/services/core/java/com/android/server/wm/DisplaySettings.java
+++ b/services/core/java/com/android/server/wm/DisplaySettings.java
@@ -16,16 +16,17 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.graphics.Rect;
 import android.os.Environment;
 import android.util.AtomicFile;
 import android.util.Slog;
 import android.util.Xml;
+
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.XmlUtils;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlSerializer;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -35,11 +36,15 @@
 import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
 /**
  * Current persistent settings about a display
  */
 public class DisplaySettings {
-    private static final String TAG = WindowManagerService.TAG;
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "DisplaySettings" : TAG_WM;
 
     private final AtomicFile mFile;
     private final HashMap<String, Entry> mEntries = new HashMap<String, Entry>();
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index 32c9b2a..8f3d3e3 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -27,13 +27,15 @@
 import static android.view.WindowManager.DOCKED_LEFT;
 import static android.view.WindowManager.DOCKED_RIGHT;
 import static android.view.WindowManager.DOCKED_TOP;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 /**
  * Keeps information about the docked stack divider.
  */
 public class DockedStackDividerController {
 
-    private static final String TAG = "DockedStackDividerController";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "DockedStackDividerController" : TAG_WM;
 
     private final DisplayContent mDisplayContent;
     private final int mDividerWindowWidth;
diff --git a/services/core/java/com/android/server/wm/DragState.java b/services/core/java/com/android/server/wm/DragState.java
index 0ef0e58..da894818 100644
--- a/services/core/java/com/android/server/wm/DragState.java
+++ b/services/core/java/com/android/server/wm/DragState.java
@@ -16,22 +16,15 @@
 
 package com.android.server.wm;
 
-import android.graphics.Matrix;
-import android.view.animation.AlphaAnimation;
-import android.view.animation.Animation;
-import android.view.animation.AnimationSet;
-import android.view.animation.DecelerateInterpolator;
-import android.view.animation.Interpolator;
-import android.view.animation.ScaleAnimation;
-import android.view.animation.Transformation;
-import android.view.animation.TranslateAnimation;
-import com.android.server.input.InputApplicationHandle;
-import com.android.server.input.InputWindowHandle;
-import com.android.server.wm.WindowManagerService.DragInputEventReceiver;
-import com.android.server.wm.WindowManagerService.H;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.content.ClipData;
 import android.content.ClipDescription;
+import android.graphics.Matrix;
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.graphics.Region;
@@ -47,6 +40,19 @@
 import android.view.SurfaceControl;
 import android.view.View;
 import android.view.WindowManager;
+import android.view.animation.AlphaAnimation;
+import android.view.animation.Animation;
+import android.view.animation.AnimationSet;
+import android.view.animation.DecelerateInterpolator;
+import android.view.animation.Interpolator;
+import android.view.animation.ScaleAnimation;
+import android.view.animation.Transformation;
+import android.view.animation.TranslateAnimation;
+
+import com.android.server.input.InputApplicationHandle;
+import com.android.server.input.InputWindowHandle;
+import com.android.server.wm.WindowManagerService.DragInputEventReceiver;
+import com.android.server.wm.WindowManagerService.H;
 
 import java.util.ArrayList;
 
@@ -114,9 +120,9 @@
      */
     void register(Display display) {
         mDisplay = display;
-        if (WindowManagerService.DEBUG_DRAG) Slog.d(WindowManagerService.TAG, "registering drag input channel");
+        if (DEBUG_DRAG) Slog.d(TAG_WM, "registering drag input channel");
         if (mClientChannel != null) {
-            Slog.e(WindowManagerService.TAG, "Duplicate register of drag input channel");
+            Slog.e(TAG_WM, "Duplicate register of drag input channel");
         } else {
             InputChannel[] channels = InputChannel.openInputChannelPair("drag");
             mServerChannel = channels[0];
@@ -161,17 +167,17 @@
             mDragWindowHandle.frameBottom = p.y;
 
             // Pause rotations before a drag.
-            if (WindowManagerService.DEBUG_ORIENTATION) {
-                Slog.d(WindowManagerService.TAG, "Pausing rotation during drag");
+            if (DEBUG_ORIENTATION) {
+                Slog.d(TAG_WM, "Pausing rotation during drag");
             }
             mService.pauseRotationLocked();
         }
     }
 
     void unregister() {
-        if (WindowManagerService.DEBUG_DRAG) Slog.d(WindowManagerService.TAG, "unregistering drag input channel");
+        if (DEBUG_DRAG) Slog.d(TAG_WM, "unregistering drag input channel");
         if (mClientChannel == null) {
-            Slog.e(WindowManagerService.TAG, "Unregister of nonexistent drag input channel");
+            Slog.e(TAG_WM, "Unregister of nonexistent drag input channel");
         } else {
             mService.mInputManager.unregisterInputChannel(mServerChannel);
             mInputEventReceiver.dispose();
@@ -185,8 +191,8 @@
             mDragApplicationHandle = null;
 
             // Resume rotations after a drag.
-            if (WindowManagerService.DEBUG_ORIENTATION) {
-                Slog.d(WindowManagerService.TAG, "Resuming rotation after drag");
+            if (DEBUG_ORIENTATION) {
+                Slog.d(TAG_WM, "Resuming rotation after drag");
             }
             mService.resumeRotationLocked();
         }
@@ -210,8 +216,8 @@
         mNotifiedWindows.clear();
         mDragInProgress = true;
 
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")");
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")");
         }
 
         final WindowList windows = mService.getWindowListLocked(mDisplay);
@@ -238,8 +244,8 @@
         if ((mFlags & View.DRAG_FLAG_GLOBAL) == 0) {
             final IBinder winBinder = newWin.mClient.asBinder();
             if (winBinder != mLocalWin) {
-                if (WindowManagerService.DEBUG_DRAG) {
-                    Slog.d(WindowManagerService.TAG, "Not dispatching local DRAG_STARTED to " + newWin);
+                if (DEBUG_DRAG) {
+                    Slog.d(TAG_WM, "Not dispatching local DRAG_STARTED to " + newWin);
                 }
                 return;
             }
@@ -253,7 +259,7 @@
                 // track each window that we've notified that the drag is starting
                 mNotifiedWindows.add(newWin);
             } catch (RemoteException e) {
-                Slog.w(WindowManagerService.TAG, "Unable to drag-start window " + newWin);
+                Slog.w(TAG_WM, "Unable to drag-start window " + newWin);
             } finally {
                 // if the callee was local, the dispatch has already recycled the event
                 if (Process.myPid() != newWin.mSession.mPid) {
@@ -275,8 +281,8 @@
                     return;
                 }
             }
-            if (WindowManagerService.DEBUG_DRAG) {
-                Slog.d(WindowManagerService.TAG, "need to send DRAG_STARTED to new window " + newWin);
+            if (DEBUG_DRAG) {
+                Slog.d(TAG_WM, "need to send DRAG_STARTED to new window " + newWin);
             }
             sendDragStartedLw(newWin, mCurrentX, mCurrentY, mDataDescription);
         }
@@ -285,8 +291,8 @@
     private void broadcastDragEndedLw() {
         final int myPid = Process.myPid();
 
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "broadcasting DRAG_ENDED");
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "broadcasting DRAG_ENDED");
         }
         for (WindowState ws : mNotifiedWindows) {
             float x = 0;
@@ -301,7 +307,7 @@
             try {
                 ws.mClient.dispatchDragEvent(evt);
             } catch (RemoteException e) {
-                Slog.w(WindowManagerService.TAG, "Unable to drag-end window " + ws);
+                Slog.w(TAG_WM, "Unable to drag-end window " + ws);
             }
             // if the current window is in the same process,
             // the dispatch has already recycled the event
@@ -356,24 +362,24 @@
         final int myPid = Process.myPid();
 
         // Move the surface to the given touch
-        if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS) Slog.i(
-                WindowManagerService.TAG, ">>> OPEN TRANSACTION notifyMoveLw");
+        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(
+                TAG_WM, ">>> OPEN TRANSACTION notifyMoveLw");
         SurfaceControl.openTransaction();
         try {
             mSurfaceControl.setPosition(x - mThumbOffsetX, y - mThumbOffsetY);
-            if (WindowManagerService.SHOW_TRANSACTIONS) Slog.i(WindowManagerService.TAG, "  DRAG "
+            if (SHOW_TRANSACTIONS) Slog.i(TAG_WM, "  DRAG "
                     + mSurfaceControl + ": pos=(" +
                     (int)(x - mThumbOffsetX) + "," + (int)(y - mThumbOffsetY) + ")");
         } finally {
             SurfaceControl.closeTransaction();
-            if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS) Slog.i(
-                    WindowManagerService.TAG, "<<< CLOSE TRANSACTION notifyMoveLw");
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(
+                    TAG_WM, "<<< CLOSE TRANSACTION notifyMoveLw");
         }
 
         // Tell the affected window
         WindowState touchedWin = getTouchedWinAtPointLw(x, y);
         if (touchedWin == null) {
-            if (WindowManagerService.DEBUG_DRAG) Slog.d(WindowManagerService.TAG, "No touched win at x=" + x + " y=" + y);
+            if (DEBUG_DRAG) Slog.d(TAG_WM, "No touched win at x=" + x + " y=" + y);
             return;
         }
         if ((mFlags & View.DRAG_FLAG_GLOBAL) == 0) {
@@ -387,8 +393,8 @@
         try {
             // have we dragged over a new window?
             if ((touchedWin != mTargetWindow) && (mTargetWindow != null)) {
-                if (WindowManagerService.DEBUG_DRAG) {
-                    Slog.d(WindowManagerService.TAG, "sending DRAG_EXITED to " + mTargetWindow);
+                if (DEBUG_DRAG) {
+                    Slog.d(TAG_WM, "sending DRAG_EXITED to " + mTargetWindow);
                 }
                 // force DRAG_EXITED_EVENT if appropriate
                 DragEvent evt = obtainDragEvent(mTargetWindow, DragEvent.ACTION_DRAG_EXITED,
@@ -399,8 +405,8 @@
                 }
             }
             if (touchedWin != null) {
-                if (false && WindowManagerService.DEBUG_DRAG) {
-                    Slog.d(WindowManagerService.TAG, "sending DRAG_LOCATION to " + touchedWin);
+                if (false && DEBUG_DRAG) {
+                    Slog.d(TAG_WM, "sending DRAG_LOCATION to " + touchedWin);
                 }
                 DragEvent evt = obtainDragEvent(touchedWin, DragEvent.ACTION_DRAG_LOCATION,
                         x, y, null, null, null, null, false);
@@ -410,7 +416,7 @@
                 }
             }
         } catch (RemoteException e) {
-            Slog.w(WindowManagerService.TAG, "can't send drag notification to windows");
+            Slog.w(TAG_WM, "can't send drag notification to windows");
         }
         mTargetWindow = touchedWin;
     }
@@ -437,8 +443,8 @@
             return true;
         }
 
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "sending DROP to " + touchedWin);
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "sending DROP to " + touchedWin);
         }
         final int myPid = Process.myPid();
         final IBinder token = touchedWin.mClient.asBinder();
@@ -452,7 +458,7 @@
             Message msg = mService.mH.obtainMessage(H.DRAG_END_TIMEOUT, token);
             mService.mH.sendMessageDelayed(msg, 5000);
         } catch (RemoteException e) {
-            Slog.w(WindowManagerService.TAG, "can't send drop notification to win " + touchedWin);
+            Slog.w(TAG_WM, "can't send drop notification to win " + touchedWin);
             return true;
         } finally {
             if (myPid != touchedWin.mSession.mPid) {
@@ -566,4 +572,4 @@
         set.start();  // Will start on the first call to getTransformation.
         return set;
     }
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java b/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java
index 0a372d8..3186d3d 100644
--- a/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java
+++ b/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java
@@ -17,6 +17,10 @@
 package com.android.server.wm;
 
 
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.content.Context;
 import android.graphics.Canvas;
 import android.graphics.Color;
@@ -32,7 +36,7 @@
 import android.view.SurfaceSession;
 
 class EmulatorDisplayOverlay {
-    private static final String TAG = "EmulatorDisplayOverlay";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "EmulatorDisplayOverlay" : TAG_WM;
 
     // Display dimensions
     private Point mScreenSize;
@@ -53,7 +57,7 @@
 
         SurfaceControl ctrl = null;
         try {
-            if (WindowManagerService.DEBUG_SURFACE_TRACE) {
+            if (DEBUG_SURFACE_TRACE) {
                 ctrl = new WindowSurfaceController.SurfaceTrace(session, "EmulatorDisplayOverlay",
                         mScreenSize.x, mScreenSize.y, PixelFormat.TRANSLUCENT,
                         SurfaceControl.HIDDEN);
diff --git a/services/core/java/com/android/server/wm/InputMonitor.java b/services/core/java/com/android/server/wm/InputMonitor.java
index 5511136..e42658e 100644
--- a/services/core/java/com/android/server/wm/InputMonitor.java
+++ b/services/core/java/com/android/server/wm/InputMonitor.java
@@ -16,9 +16,11 @@
 
 package com.android.server.wm;
 
-import static android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER;
-import static com.android.server.wm.WindowManagerService.DEBUG_FOCUS_LIGHT;
-import static com.android.server.wm.WindowManagerService.DEBUG_INPUT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_INPUT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_POSITIONING;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.app.ActivityManagerNative;
 import android.graphics.Rect;
@@ -79,7 +81,7 @@
         synchronized (mService.mWindowMap) {
             WindowState windowState = (WindowState) inputWindowHandle.windowState;
             if (windowState != null) {
-                Slog.i(WindowManagerService.TAG, "WINDOW DIED " + windowState);
+                Slog.i(TAG_WM, "WINDOW DIED " + windowState);
                 mService.removeWindowLocked(windowState);
             }
         }
@@ -108,7 +110,7 @@
             }
 
             if (windowState != null) {
-                Slog.i(WindowManagerService.TAG, "Input event dispatching timed out "
+                Slog.i(TAG_WM, "Input event dispatching timed out "
                         + "sending to " + windowState.mAttrs.getTitle()
                         + ".  Reason: " + reason);
                 // Figure out whether this window is layered above system windows.
@@ -118,11 +120,11 @@
                         WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                 aboveSystem = windowState.mBaseLayer > systemAlertLayer;
             } else if (appWindowToken != null) {
-                Slog.i(WindowManagerService.TAG, "Input event dispatching timed out "
+                Slog.i(TAG_WM, "Input event dispatching timed out "
                         + "sending to application " + appWindowToken.stringName
                         + ".  Reason: " + reason);
             } else {
-                Slog.i(WindowManagerService.TAG, "Input event dispatching timed out "
+                Slog.i(TAG_WM, "Input event dispatching timed out "
                         + ".  Reason: " + reason);
             }
 
@@ -212,7 +214,7 @@
         }
 
         if (DEBUG_INPUT) {
-            Slog.d(WindowManagerService.TAG, "addInputWindowHandle: "
+            Slog.d(TAG_WM, "addInputWindowHandle: "
                     + child + ", " + inputWindowHandle);
         }
         addInputWindowHandleLw(inputWindowHandle);
@@ -235,7 +237,7 @@
         }
         mUpdateInputWindowsNeeded = false;
 
-        if (false) Slog.d(WindowManagerService.TAG, ">>>>>> ENTERED updateInputWindowsLw");
+        if (false) Slog.d(TAG_WM, ">>>>>> ENTERED updateInputWindowsLw");
 
         // Populate the input window list with information about all of the windows that
         // could potentially receive input.
@@ -247,28 +249,28 @@
         // If there's a drag in flight, provide a pseudowindow to catch drag input
         final boolean inDrag = (mService.mDragState != null);
         if (inDrag) {
-            if (WindowManagerService.DEBUG_DRAG) {
-                Log.d(WindowManagerService.TAG, "Inserting drag window");
+            if (DEBUG_DRAG) {
+                Log.d(TAG_WM, "Inserting drag window");
             }
             final InputWindowHandle dragWindowHandle = mService.mDragState.mDragWindowHandle;
             if (dragWindowHandle != null) {
                 addInputWindowHandleLw(dragWindowHandle);
             } else {
-                Slog.w(WindowManagerService.TAG, "Drag is in progress but there is no "
+                Slog.w(TAG_WM, "Drag is in progress but there is no "
                         + "drag window handle.");
             }
         }
 
         final boolean inPositioning = (mService.mTaskPositioner != null);
         if (inPositioning) {
-            if (WindowManagerService.DEBUG_TASK_POSITIONING) {
-                Log.d(WindowManagerService.TAG, "Inserting window handle for repositioning");
+            if (DEBUG_TASK_POSITIONING) {
+                Log.d(TAG_WM, "Inserting window handle for repositioning");
             }
             final InputWindowHandle dragWindowHandle = mService.mTaskPositioner.mDragWindowHandle;
             if (dragWindowHandle != null) {
                 addInputWindowHandleLw(dragWindowHandle);
             } else {
-                Slog.e(WindowManagerService.TAG,
+                Slog.e(TAG_WM,
                         "Repositioning is in progress but there is no drag window handle.");
             }
         }
@@ -328,7 +330,7 @@
         // Clear the list in preparation for the next round.
         clearInputWindowHandlesLw();
 
-        if (false) Slog.d(WindowManagerService.TAG, "<<<<<<< EXITED updateInputWindowsLw");
+        if (false) Slog.d(TAG_WM, "<<<<<<< EXITED updateInputWindowsLw");
     }
 
     /* Notifies that the input device configuration has changed. */
@@ -416,7 +418,7 @@
      */
     public void setInputFocusLw(WindowState newWindow, boolean updateInputWindows) {
         if (DEBUG_FOCUS_LIGHT || DEBUG_INPUT) {
-            Slog.d(WindowManagerService.TAG, "Input focus has changed to " + newWindow);
+            Slog.d(TAG_WM, "Input focus has changed to " + newWindow);
         }
 
         if (newWindow != mInputFocus) {
@@ -452,7 +454,7 @@
     public void pauseDispatchingLw(WindowToken window) {
         if (! window.paused) {
             if (DEBUG_INPUT) {
-                Slog.v(WindowManagerService.TAG, "Pausing WindowToken " + window);
+                Slog.v(TAG_WM, "Pausing WindowToken " + window);
             }
 
             window.paused = true;
@@ -463,7 +465,7 @@
     public void resumeDispatchingLw(WindowToken window) {
         if (window.paused) {
             if (DEBUG_INPUT) {
-                Slog.v(WindowManagerService.TAG, "Resuming WindowToken " + window);
+                Slog.v(TAG_WM, "Resuming WindowToken " + window);
             }
 
             window.paused = false;
@@ -474,7 +476,7 @@
     public void freezeInputDispatchingLw() {
         if (! mInputDispatchFrozen) {
             if (DEBUG_INPUT) {
-                Slog.v(WindowManagerService.TAG, "Freezing input dispatching");
+                Slog.v(TAG_WM, "Freezing input dispatching");
             }
 
             mInputDispatchFrozen = true;
@@ -485,7 +487,7 @@
     public void thawInputDispatchingLw() {
         if (mInputDispatchFrozen) {
             if (DEBUG_INPUT) {
-                Slog.v(WindowManagerService.TAG, "Thawing input dispatching");
+                Slog.v(TAG_WM, "Thawing input dispatching");
             }
 
             mInputDispatchFrozen = false;
@@ -496,7 +498,7 @@
     public void setEventDispatchingLw(boolean enabled) {
         if (mInputDispatchEnabled != enabled) {
             if (DEBUG_INPUT) {
-                Slog.v(WindowManagerService.TAG, "Setting event dispatching to " + enabled);
+                Slog.v(TAG_WM, "Setting event dispatching to " + enabled);
             }
 
             mInputDispatchEnabled = enabled;
diff --git a/services/core/java/com/android/server/wm/KeyguardDisableHandler.java b/services/core/java/com/android/server/wm/KeyguardDisableHandler.java
index 37d811f..377071d 100644
--- a/services/core/java/com/android/server/wm/KeyguardDisableHandler.java
+++ b/services/core/java/com/android/server/wm/KeyguardDisableHandler.java
@@ -16,6 +16,9 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.app.ActivityManagerNative;
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
@@ -29,7 +32,7 @@
 import android.view.WindowManagerPolicy;
 
 public class KeyguardDisableHandler extends Handler {
-    private static final String TAG = "KeyguardDisableHandler";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "KeyguardDisableHandler" : TAG_WM;
 
     private static final int ALLOW_DISABLE_YES = 1;
     private static final int ALLOW_DISABLE_NO = 0;
diff --git a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
index 3158c47..c118a21 100644
--- a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
+++ b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
@@ -16,11 +16,16 @@
 
 package com.android.server.wm;
 
-import java.io.PrintWriter;
-
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.TYPE_LAYER_MULTIPLIER;
-import static com.android.server.wm.WindowSurfaceController.SurfaceTrace;
 import static com.android.server.wm.WindowStateAnimator.WINDOW_FREEZE_LAYER;
+import static com.android.server.wm.WindowSurfaceController.SurfaceTrace;
+
 import android.content.Context;
 import android.graphics.Matrix;
 import android.graphics.PixelFormat;
@@ -28,16 +33,18 @@
 import android.util.Slog;
 import android.view.Display;
 import android.view.DisplayInfo;
-import android.view.Surface.OutOfResourcesException;
 import android.view.Surface;
+import android.view.Surface.OutOfResourcesException;
 import android.view.SurfaceControl;
 import android.view.SurfaceSession;
 import android.view.animation.Animation;
 import android.view.animation.AnimationUtils;
 import android.view.animation.Transformation;
 
+import java.io.PrintWriter;
+
 class ScreenRotationAnimation {
-    static final String TAG = "ScreenRotationAnimation";
+    static final String TAG = TAG_WITH_CLASS_NAME ? "ScreenRotationAnimation" : TAG_WM;
     static final boolean DEBUG_STATE = false;
     static final boolean DEBUG_TRANSFORMS = false;
     static final boolean TWO_PHASE_ANIMATION = false;
@@ -244,7 +251,7 @@
         mOriginalHeight = originalHeight;
 
         if (!inTransaction) {
-            if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS) Slog.i(WindowManagerService.TAG,
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                     ">>> OPEN TRANSACTION ScreenRotationAnimation");
             SurfaceControl.openTransaction();
         }
@@ -256,7 +263,7 @@
                     flags |= SurfaceControl.SECURE;
                 }
 
-                if (WindowManagerService.DEBUG_SURFACE_TRACE) {
+                if (DEBUG_SURFACE_TRACE) {
                     mSurfaceControl = new SurfaceTrace(session, "ScreenshotSurface",
                             mWidth, mHeight,
                             PixelFormat.OPAQUE, flags);
@@ -282,15 +289,14 @@
                 Slog.w(TAG, "Unable to allocate freeze surface", e);
             }
 
-            if (WindowManagerService.SHOW_TRANSACTIONS ||
-                    WindowManagerService.SHOW_SURFACE_ALLOC) Slog.i(WindowManagerService.TAG,
-                            "  FREEZE " + mSurfaceControl + ": CREATE");
+            if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) Slog.i(TAG_WM,
+                    "  FREEZE " + mSurfaceControl + ": CREATE");
 
             setRotationInTransaction(originalRotation);
         } finally {
             if (!inTransaction) {
                 SurfaceControl.closeTransaction();
-                if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS) Slog.i(WindowManagerService.TAG,
+                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                         "<<< CLOSE TRANSACTION ScreenRotationAnimation");
             }
         }
@@ -537,8 +543,8 @@
 
         final int layerStack = mDisplayContent.getDisplay().getLayerStack();
         if (USE_CUSTOM_BLACK_FRAME && mCustomBlackFrame == null) {
-            if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
-                    WindowManagerService.TAG,
+            if (SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
+                    TAG_WM,
                     ">>> OPEN TRANSACTION ScreenRotationAnimation.startAnimation");
             SurfaceControl.openTransaction();
 
@@ -561,15 +567,15 @@
                 Slog.w(TAG, "Unable to allocate black surface", e);
             } finally {
                 SurfaceControl.closeTransaction();
-                if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
-                        WindowManagerService.TAG,
+                if (SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
+                        TAG_WM,
                         "<<< CLOSE TRANSACTION ScreenRotationAnimation.startAnimation");
             }
         }
 
         if (!customAnim && mExitingBlackFrame == null) {
-            if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
-                    WindowManagerService.TAG,
+            if (SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
+                    TAG_WM,
                     ">>> OPEN TRANSACTION ScreenRotationAnimation.startAnimation");
             SurfaceControl.openTransaction();
             try {
@@ -601,15 +607,15 @@
                 Slog.w(TAG, "Unable to allocate black surface", e);
             } finally {
                 SurfaceControl.closeTransaction();
-                if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
-                        WindowManagerService.TAG,
+                if (SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
+                        TAG_WM,
                         "<<< CLOSE TRANSACTION ScreenRotationAnimation.startAnimation");
             }
         }
 
         if (customAnim && mEnteringBlackFrame == null) {
-            if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
-                    WindowManagerService.TAG,
+            if (SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
+                    TAG_WM,
                     ">>> OPEN TRANSACTION ScreenRotationAnimation.startAnimation");
             SurfaceControl.openTransaction();
 
@@ -623,8 +629,8 @@
                 Slog.w(TAG, "Unable to allocate black surface", e);
             } finally {
                 SurfaceControl.closeTransaction();
-                if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
-                        WindowManagerService.TAG,
+                if (SHOW_LIGHT_TRANSACTIONS || DEBUG_STATE) Slog.i(
+                        TAG_WM,
                         "<<< CLOSE TRANSACTION ScreenRotationAnimation.startAnimation");
             }
         }
@@ -657,8 +663,8 @@
     public void kill() {
         if (DEBUG_STATE) Slog.v(TAG, "Kill!");
         if (mSurfaceControl != null) {
-            if (WindowManagerService.SHOW_TRANSACTIONS ||
-                    WindowManagerService.SHOW_SURFACE_ALLOC) Slog.i(WindowManagerService.TAG,
+            if (SHOW_TRANSACTIONS ||
+                    SHOW_SURFACE_ALLOC) Slog.i(TAG_WM,
                             "  FREEZE " + mSurfaceControl + ": DESTROY");
             mSurfaceControl.destroy();
             mSurfaceControl = null;
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index 6e2e830..1b6957d 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -16,12 +16,11 @@
 
 package com.android.server.wm;
 
-import android.view.IWindowId;
-import android.view.IWindowSessionCallback;
-import com.android.internal.view.IInputContext;
-import com.android.internal.view.IInputMethodClient;
-import com.android.internal.view.IInputMethodManager;
-import com.android.server.wm.WindowManagerService.H;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_POSITIONING;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.content.ClipData;
 import android.content.Context;
@@ -39,13 +38,20 @@
 import android.util.Slog;
 import android.view.Display;
 import android.view.IWindow;
+import android.view.IWindowId;
 import android.view.IWindowSession;
+import android.view.IWindowSessionCallback;
 import android.view.InputChannel;
 import android.view.Surface;
 import android.view.SurfaceControl;
 import android.view.SurfaceSession;
 import android.view.WindowManager;
 
+import com.android.internal.view.IInputContext;
+import com.android.internal.view.IInputMethodClient;
+import com.android.internal.view.IInputMethodManager;
+import com.android.server.wm.WindowManagerService.H;
+
 import java.io.PrintWriter;
 
 /**
@@ -131,7 +137,7 @@
         } catch (RuntimeException e) {
             // Log all 'real' exceptions thrown to the caller
             if (!(e instanceof SecurityException)) {
-                Slog.wtf(WindowManagerService.TAG, "Window Session Crash", e);
+                Slog.wtf(TAG_WM, "Window Session Crash", e);
             }
             throw e;
         }
@@ -200,13 +206,13 @@
             Rect outVisibleInsets, Rect outStableInsets, Rect outsets, Configuration
                     outConfig,
             Surface outSurface) {
-        if (false) Slog.d(WindowManagerService.TAG, ">>>>>> ENTERED relayout from "
+        if (false) Slog.d(TAG_WM, ">>>>>> ENTERED relayout from "
                 + Binder.getCallingPid());
         int res = mService.relayoutWindow(this, window, seq, attrs,
                 requestedWidth, requestedHeight, viewFlags, flags,
                 outFrame, outOverscanInsets, outContentInsets, outVisibleInsets,
                 outStableInsets, outsets, outConfig, outSurface);
-        if (false) Slog.d(WindowManagerService.TAG, "<<<<<< EXITING relayout to "
+        if (false) Slog.d(TAG_WM, "<<<<<< EXITING relayout to "
                 + Binder.getCallingPid());
         return res;
     }
@@ -235,7 +241,7 @@
 
     public void finishDrawing(IWindow window) {
         if (WindowManagerService.localLOGV) Slog.v(
-            WindowManagerService.TAG, "IWindow finishDrawing called for " + window);
+            TAG_WM, "IWindow finishDrawing called for " + window);
         mService.finishDrawingWindow(this, window);
     }
 
@@ -275,24 +281,24 @@
     public boolean performDrag(IWindow window, IBinder dragToken,
             float touchX, float touchY, float thumbCenterX, float thumbCenterY,
             ClipData data) {
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "perform drag: win=" + window + " data=" + data);
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "perform drag: win=" + window + " data=" + data);
         }
 
         synchronized (mService.mWindowMap) {
             if (mService.mDragState == null) {
-                Slog.w(WindowManagerService.TAG, "No drag prepared");
+                Slog.w(TAG_WM, "No drag prepared");
                 throw new IllegalStateException("performDrag() without prepareDrag()");
             }
 
             if (dragToken != mService.mDragState.mToken) {
-                Slog.w(WindowManagerService.TAG, "Performing mismatched drag");
+                Slog.w(TAG_WM, "Performing mismatched drag");
                 throw new IllegalStateException("performDrag() does not match prepareDrag()");
             }
 
             WindowState callingWin = mService.windowForClientLocked(null, window, false);
             if (callingWin == null) {
-                Slog.w(WindowManagerService.TAG, "Bad requesting window " + window);
+                Slog.w(TAG_WM, "Bad requesting window " + window);
                 return false;  // !!! TODO: throw here?
             }
 
@@ -317,7 +323,7 @@
             mService.mInputMonitor.updateInputWindowsLw(true /*force*/);
             if (!mService.mInputManager.transferTouchFocus(callingWin.mInputChannel,
                     mService.mDragState.mServerChannel)) {
-                Slog.e(WindowManagerService.TAG, "Unable to transfer touch focus");
+                Slog.e(TAG_WM, "Unable to transfer touch focus");
                 mService.mDragState.unregister();
                 mService.mDragState = null;
                 mService.mInputMonitor.updateInputWindowsLw(true /*force*/);
@@ -333,8 +339,8 @@
 
             // Make the surface visible at the proper location
             final SurfaceControl surfaceControl = mService.mDragState.mSurfaceControl;
-            if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS) Slog.i(
-                    WindowManagerService.TAG, ">>> OPEN TRANSACTION performDrag");
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(
+                    TAG_WM, ">>> OPEN TRANSACTION performDrag");
             SurfaceControl.openTransaction();
             try {
                 surfaceControl.setPosition(touchX - thumbCenterX,
@@ -344,8 +350,8 @@
                 surfaceControl.show();
             } finally {
                 SurfaceControl.closeTransaction();
-                if (WindowManagerService.SHOW_LIGHT_TRANSACTIONS) Slog.i(
-                        WindowManagerService.TAG, "<<< CLOSE TRANSACTION performDrag");
+                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(
+                        TAG_WM, "<<< CLOSE TRANSACTION performDrag");
             }
         }
 
@@ -353,16 +359,16 @@
     }
 
     public boolean startMovingTask(IWindow window, float startX, float startY) {
-        if (WindowManagerService.DEBUG_TASK_POSITIONING) Slog.d(
-                WindowManagerService.TAG, "startMovingTask: {" + startX + "," + startY + "}");
+        if (DEBUG_TASK_POSITIONING) Slog.d(
+                TAG_WM, "startMovingTask: {" + startX + "," + startY + "}");
 
         return mService.startMovingTask(window, startX, startY);
     }
 
     public void reportDropResult(IWindow window, boolean consumed) {
         IBinder token = window.asBinder();
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "Drop result=" + consumed + " reported by " + token);
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "Drop result=" + consumed + " reported by " + token);
         }
 
         synchronized (mService.mWindowMap) {
@@ -371,13 +377,13 @@
                 if (mService.mDragState == null) {
                     // Most likely the drop recipient ANRed and we ended the drag
                     // out from under it.  Log the issue and move on.
-                    Slog.w(WindowManagerService.TAG, "Drop result given but no drag in progress");
+                    Slog.w(TAG_WM, "Drop result given but no drag in progress");
                     return;
                 }
 
                 if (mService.mDragState.mToken != token) {
                     // We're in a drag, but the wrong window has responded.
-                    Slog.w(WindowManagerService.TAG, "Invalid drop-result claim by " + window);
+                    Slog.w(TAG_WM, "Invalid drop-result claim by " + window);
                     throw new IllegalStateException("reportDropResult() by non-recipient");
                 }
 
@@ -387,7 +393,7 @@
                 mService.mH.removeMessages(H.DRAG_END_TIMEOUT, window.asBinder());
                 WindowState callingWin = mService.windowForClientLocked(null, window, false);
                 if (callingWin == null) {
-                    Slog.w(WindowManagerService.TAG, "Bad result-reporting window " + window);
+                    Slog.w(TAG_WM, "Bad result-reporting window " + window);
                     return;  // !!! TODO: throw here?
                 }
 
@@ -400,20 +406,20 @@
     }
 
     public void cancelDragAndDrop(IBinder dragToken) {
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "cancelDragAndDrop");
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "cancelDragAndDrop");
         }
 
         synchronized (mService.mWindowMap) {
             long ident = Binder.clearCallingIdentity();
             try {
                 if (mService.mDragState == null) {
-                    Slog.w(WindowManagerService.TAG, "cancelDragAndDrop() without prepareDrag()");
+                    Slog.w(TAG_WM, "cancelDragAndDrop() without prepareDrag()");
                     throw new IllegalStateException("cancelDragAndDrop() without prepareDrag()");
                 }
 
                 if (mService.mDragState.mToken != dragToken) {
-                    Slog.w(WindowManagerService.TAG,
+                    Slog.w(TAG_WM,
                             "cancelDragAndDrop() does not match prepareDrag()");
                     throw new IllegalStateException(
                             "cancelDragAndDrop() does not match prepareDrag()");
@@ -428,14 +434,14 @@
     }
 
     public void dragRecipientEntered(IWindow window) {
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "Drag into new candidate view @ " + window.asBinder());
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "Drag into new candidate view @ " + window.asBinder());
         }
     }
 
     public void dragRecipientExited(IWindow window) {
-        if (WindowManagerService.DEBUG_DRAG) {
-            Slog.d(WindowManagerService.TAG, "Drag from old candidate view @ " + window.asBinder());
+        if (DEBUG_DRAG) {
+            Slog.d(TAG_WM, "Drag from old candidate view @ " + window.asBinder());
         }
     }
 
@@ -518,10 +524,10 @@
     void windowAddedLocked() {
         if (mSurfaceSession == null) {
             if (WindowManagerService.localLOGV) Slog.v(
-                WindowManagerService.TAG, "First window added to " + this + ", creating SurfaceSession");
+                TAG_WM, "First window added to " + this + ", creating SurfaceSession");
             mSurfaceSession = new SurfaceSession();
-            if (WindowManagerService.SHOW_TRANSACTIONS) Slog.i(
-                    WindowManagerService.TAG, "  NEW SURFACE SESSION " + mSurfaceSession);
+            if (SHOW_TRANSACTIONS) Slog.i(
+                    TAG_WM, "  NEW SURFACE SESSION " + mSurfaceSession);
             mService.mSessions.add(this);
             if (mLastReportedAnimatorScale != mService.getCurrentAnimatorScale()) {
                 mService.dispatchNewAnimatorScaleLocked(this);
@@ -540,14 +546,14 @@
             mService.mSessions.remove(this);
             if (mSurfaceSession != null) {
                 if (WindowManagerService.localLOGV) Slog.v(
-                    WindowManagerService.TAG, "Last window removed from " + this
+                    TAG_WM, "Last window removed from " + this
                     + ", destroying " + mSurfaceSession);
-                if (WindowManagerService.SHOW_TRANSACTIONS) Slog.i(
-                        WindowManagerService.TAG, "  KILL SURFACE SESSION " + mSurfaceSession);
+                if (SHOW_TRANSACTIONS) Slog.i(
+                        TAG_WM, "  KILL SURFACE SESSION " + mSurfaceSession);
                 try {
                     mSurfaceSession.kill();
                 } catch (Exception e) {
-                    Slog.w(WindowManagerService.TAG, "Exception thrown when killing surface session "
+                    Slog.w(TAG_WM, "Exception thrown when killing surface session "
                         + mSurfaceSession + " in session " + this
                         + ": " + e.toString());
                 }
diff --git a/services/core/java/com/android/server/wm/StrictModeFlash.java b/services/core/java/com/android/server/wm/StrictModeFlash.java
index fb5876b..d1547eb 100644
--- a/services/core/java/com/android/server/wm/StrictModeFlash.java
+++ b/services/core/java/com/android/server/wm/StrictModeFlash.java
@@ -17,6 +17,9 @@
 package com.android.server.wm;
 
 
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.PixelFormat;
@@ -29,7 +32,7 @@
 import android.view.SurfaceSession;
 
 class StrictModeFlash {
-    private static final String TAG = "StrictModeFlash";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "StrictModeFlash" : TAG_WM;
 
     private final SurfaceControl mSurfaceControl;
     private final Surface mSurface = new Surface();
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index e4f6c56..72a8343 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -19,12 +19,11 @@
 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
 import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
 import static android.app.ActivityManager.StackId.HOME_STACK_ID;
-import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
 import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
 import static android.app.ActivityManager.RESIZE_MODE_SYSTEM_SCREEN_ROTATION;
-import static com.android.server.wm.WindowManagerService.TAG;
-import static com.android.server.wm.WindowManagerService.DEBUG_RESIZE;
-import static com.android.server.wm.WindowManagerService.DEBUG_STACK;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RESIZE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK;
 import static com.android.server.wm.WindowManagerService.H.RESIZE_TASK;
 import static com.android.server.wm.WindowManagerService.H.SHOW_NON_RESIZEABLE_DOCK_TOAST;
 import static android.view.WindowManager.DOCKED_INVALID;
@@ -156,11 +155,11 @@
 
     void removeLocked() {
         if (!mAppTokens.isEmpty() && mStack.isAnimating()) {
-            if (DEBUG_STACK) Slog.i(TAG, "removeTask: deferring removing taskId=" + mTaskId);
+            if (DEBUG_STACK) Slog.i(TAG_WM, "removeTask: deferring removing taskId=" + mTaskId);
             mDeferRemoval = true;
             return;
         }
-        if (DEBUG_STACK) Slog.i(TAG, "removeTask: removing taskId=" + mTaskId);
+        if (DEBUG_STACK) Slog.i(TAG_WM, "removeTask: removing taskId=" + mTaskId);
         EventLog.writeEvent(EventLogTags.WM_TASK_REMOVED, mTaskId, "removeTask");
         mDeferRemoval = false;
         DisplayContent content = getDisplayContent();
@@ -175,7 +174,7 @@
         if (stack == mStack) {
             return;
         }
-        if (DEBUG_STACK) Slog.i(TAG, "moveTaskToStack: removing taskId=" + mTaskId
+        if (DEBUG_STACK) Slog.i(TAG_WM, "moveTaskToStack: removing taskId=" + mTaskId
                 + " from stack=" + mStack);
         EventLog.writeEvent(EventLogTags.WM_TASK_REMOVED, mTaskId, "moveTask");
         if (mStack != null) {
@@ -186,7 +185,7 @@
 
     void positionTaskInStack(TaskStack stack, int position, Rect bounds, Configuration config) {
         if (mStack != null && stack != mStack) {
-            if (DEBUG_STACK) Slog.i(TAG, "positionTaskInStack: removing taskId=" + mTaskId
+            if (DEBUG_STACK) Slog.i(TAG_WM, "positionTaskInStack: removing taskId=" + mTaskId
                     + " from stack=" + mStack);
             EventLog.writeEvent(EventLogTags.WM_TASK_REMOVED, mTaskId, "moveTask");
             mStack.removeTask(this);
@@ -464,7 +463,7 @@
             for (int winNdx = windows.size() - 1; winNdx >= 0; --winNdx) {
                 final WindowState win = windows.get(winNdx);
                 if (!resizingWindows.contains(win)) {
-                    if (DEBUG_RESIZE) Slog.d(TAG, "setBounds: Resizing " + win);
+                    if (DEBUG_RESIZE) Slog.d(TAG_WM, "setBounds: Resizing " + win);
                     resizingWindows.add(win);
                 }
             }
diff --git a/services/core/java/com/android/server/wm/TaskPositioner.java b/services/core/java/com/android/server/wm/TaskPositioner.java
index 32c3205..725bbbc 100644
--- a/services/core/java/com/android/server/wm/TaskPositioner.java
+++ b/services/core/java/com/android/server/wm/TaskPositioner.java
@@ -18,15 +18,18 @@
 
 import static android.app.ActivityManager.DOCKED_STACK_CREATE_MODE_BOTTOM_OR_RIGHT;
 import static android.app.ActivityManager.DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT;
-import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
 import static android.app.ActivityManager.RESIZE_MODE_USER;
 import static android.app.ActivityManager.RESIZE_MODE_USER_FORCED;
+import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
 import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
 import static com.android.server.wm.DimLayer.RESIZING_HINT_ALPHA;
 import static com.android.server.wm.DimLayer.RESIZING_HINT_DURATION_MS;
-import static com.android.server.wm.WindowManagerService.DEBUG_TASK_POSITIONING;
-import static com.android.server.wm.WindowManagerService.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_POSITIONING;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.dipToPixel;
 import static com.android.server.wm.WindowState.MINIMUM_VISIBLE_HEIGHT_IN_DP;
 import static com.android.server.wm.WindowState.MINIMUM_VISIBLE_WIDTH_IN_DP;
@@ -40,13 +43,13 @@
 import android.os.Trace;
 import android.util.DisplayMetrics;
 import android.util.Slog;
+import android.view.BatchedInputEventReceiver;
 import android.view.Choreographer;
 import android.view.Display;
 import android.view.DisplayInfo;
 import android.view.InputChannel;
 import android.view.InputDevice;
 import android.view.InputEvent;
-import android.view.BatchedInputEventReceiver;
 import android.view.MotionEvent;
 import android.view.SurfaceControl;
 import android.view.WindowManager;
@@ -59,7 +62,7 @@
 import java.lang.annotation.RetentionPolicy;
 
 class TaskPositioner implements DimLayer.DimLayerUser {
-    private static final String TAG = "TaskPositioner";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "TaskPositioner" : TAG_WM;
 
     // The margin the pointer position has to be within the side of the screen to be
     // considered at the side of the screen.
@@ -277,7 +280,7 @@
         mDragWindowHandle.frameBottom = p.y;
 
         // Pause rotations before a drag.
-        if (WindowManagerService.DEBUG_ORIENTATION) {
+        if (DEBUG_ORIENTATION) {
             Slog.d(TAG, "Pausing rotation during re-position");
         }
         mService.pauseRotationLocked();
@@ -321,7 +324,7 @@
         mDragEnded = true;
 
         // Resume rotations after a drag.
-        if (WindowManagerService.DEBUG_ORIENTATION) {
+        if (DEBUG_ORIENTATION) {
             Slog.d(TAG, "Resuming rotation after re-position");
         }
         mService.resumeRotationLocked();
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index 996fadf..49d9efe 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -39,9 +39,9 @@
 import static android.view.WindowManager.DOCKED_LEFT;
 import static android.view.WindowManager.DOCKED_RIGHT;
 import static android.view.WindowManager.DOCKED_TOP;
-import static com.android.server.wm.WindowManagerService.DEBUG_TASK_MOVEMENT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_MOVEMENT;
 import static com.android.server.wm.WindowManagerService.H.RESIZE_STACK;
-import static com.android.server.wm.WindowManagerService.TAG;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 public class TaskStack implements DimLayer.DimLayerUser {
 
@@ -138,7 +138,7 @@
                     task.setBounds(bounds, config);
                 }
             } else {
-                Slog.wtf(TAG, "No config for task: " + task + ", is there a mismatch with AM?");
+                Slog.wtf(TAG_WM, "No config for task: " + task + ", is there a mismatch with AM?");
             }
         }
         return true;
@@ -285,7 +285,7 @@
         // Reset position based on minimum/maximum possible positions.
         position = Math.min(Math.max(position, minPosition), maxPosition);
 
-        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG,
+        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG_WM,
                 "positionTask: task=" + task + " position=" + position);
         mTasks.add(position, task);
 
@@ -338,14 +338,14 @@
     }
 
     void moveTaskToTop(Task task) {
-        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG, "moveTaskToTop: task=" + task + " Callers="
+        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG_WM, "moveTaskToTop: task=" + task + " Callers="
                 + Debug.getCallers(6));
         mTasks.remove(task);
         addTask(task, true);
     }
 
     void moveTaskToBottom(Task task) {
-        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG, "moveTaskToBottom: task=" + task);
+        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG_WM, "moveTaskToBottom: task=" + task);
         mTasks.remove(task);
         addTask(task, false);
     }
@@ -356,7 +356,7 @@
      * @param task The Task to delete.
      */
     void removeTask(Task task) {
-        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG, "removeTask: task=" + task);
+        if (DEBUG_TASK_MOVEMENT) Slog.d(TAG_WM, "removeTask: task=" + task);
         mTasks.remove(task);
         if (mDisplayContent != null) {
             if (mTasks.isEmpty()) {
@@ -433,7 +433,7 @@
         final int dockedSide = dockedStack.getDockSide();
         if (dockedSide == DOCKED_INVALID) {
             // Not sure how you got here...Only thing we can do is return current bounds.
-            Slog.e(TAG, "Failed to get valid docked side for docked stack=" + dockedStack);
+            Slog.e(TAG_WM, "Failed to get valid docked side for docked stack=" + dockedStack);
             outBounds.set(mBounds);
             return;
         }
diff --git a/services/core/java/com/android/server/wm/ViewServer.java b/services/core/java/com/android/server/wm/ViewServer.java
index 741cee3..ecf5652 100644
--- a/services/core/java/com/android/server/wm/ViewServer.java
+++ b/services/core/java/com/android/server/wm/ViewServer.java
@@ -17,6 +17,9 @@
 package com.android.server.wm;
 
 
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.util.Slog;
 
 import java.net.ServerSocket;
@@ -47,7 +50,7 @@
     private static final int VIEW_SERVER_MAX_CONNECTIONS = 10;
 
     // Debug facility
-    private static final String LOG_TAG = "ViewServer";
+    private static final String LOG_TAG = TAG_WITH_CLASS_NAME ? "ViewServer" : TAG_WM;
 
     private static final String VALUE_PROTOCOL_VERSION = "4";
     private static final String VALUE_SERVER_VERSION = "4";
@@ -150,7 +153,7 @@
      *
      * @see #start()
      * @see #stop()
-     * @see WindowManagerService#isViewServerRunning()  
+     * @see WindowManagerService#isViewServerRunning()
      */
     boolean isRunning() {
         return mThread != null && mThread.isAlive();
diff --git a/services/core/java/com/android/server/wm/WallpaperController.java b/services/core/java/com/android/server/wm/WallpaperController.java
index 8b984f0..3db9ae0 100644
--- a/services/core/java/com/android/server/wm/WallpaperController.java
+++ b/services/core/java/com/android/server/wm/WallpaperController.java
@@ -22,13 +22,15 @@
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
 import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM;
 import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
-import static com.android.server.wm.WindowManagerService.DEBUG_ADD_REMOVE;
-import static com.android.server.wm.WindowManagerService.DEBUG_APP_TRANSITIONS;
-import static com.android.server.wm.WindowManagerService.DEBUG_LAYERS;
-import static com.android.server.wm.WindowManagerService.DEBUG_WINDOW_MOVEMENT;
-import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
-import static com.android.server.wm.WindowManagerService.DEBUG_WALLPAPER;
-import static com.android.server.wm.WindowManagerService.DEBUG_WALLPAPER_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYERS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_MOVEMENT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.H.WALLPAPER_DRAW_PENDING_TIMEOUT;
 import static com.android.server.wm.WindowManagerService.TYPE_LAYER_MULTIPLIER;
 import static com.android.server.wm.WindowManagerService.TYPE_LAYER_OFFSET;
@@ -51,7 +53,7 @@
  * NOTE: All methods in this class must be called with the window manager service lock held.
  */
 class WallpaperController {
-    private static final String TAG = com.android.server.wm.WindowManagerService.TAG;
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "WallpaperController" : TAG_WM;
     final private WindowManagerService mService;
 
     private final ArrayList<WindowToken> mWallpaperTokens = new ArrayList<>();
diff --git a/services/core/java/com/android/server/wm/Watermark.java b/services/core/java/com/android/server/wm/Watermark.java
index e226e3d..171e575 100644
--- a/services/core/java/com/android/server/wm/Watermark.java
+++ b/services/core/java/com/android/server/wm/Watermark.java
@@ -16,6 +16,8 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.graphics.Canvas;
 import android.graphics.Paint;
 import android.graphics.PixelFormat;
@@ -53,9 +55,9 @@
 
     Watermark(Display display, DisplayMetrics dm, SurfaceSession session, String[] tokens) {
         if (false) {
-            Log.i(WindowManagerService.TAG, "*********************** WATERMARK");
+            Log.i(TAG_WM, "*********************** WATERMARK");
             for (int i=0; i<tokens.length; i++) {
-                Log.i(WindowManagerService.TAG, "  TOKEN #" + i + ": " + tokens[i]);
+                Log.i(TAG_WM, "  TOKEN #" + i + ": " + tokens[i]);
             }
         }
 
@@ -78,7 +80,7 @@
         }
         mText = builder.toString();
         if (false) {
-            Log.i(WindowManagerService.TAG, "Final text: " + mText);
+            Log.i(TAG_WM, "Final text: " + mText);
         }
 
         int fontSize = WindowManagerService.getPropertyInt(tokens, 1,
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index f20c4e5..a6523a4 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -21,15 +21,17 @@
 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_SYSTEM_ERROR;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
-import static com.android.server.wm.WindowManagerService.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerService.DEBUG_FOCUS_LIGHT;
-import static com.android.server.wm.WindowManagerService.DEBUG_KEYGUARD;
-import static com.android.server.wm.WindowManagerService.DEBUG_LAYOUT_REPEATS;
-import static com.android.server.wm.WindowManagerService.DEBUG_ORIENTATION;
-import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
-import static com.android.server.wm.WindowManagerService.DEBUG_WALLPAPER;
-import static com.android.server.wm.WindowManagerService.DEBUG_WINDOW_TRACE;
-import static com.android.server.wm.WindowManagerService.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_KEYGUARD;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowSurfacePlacer.SET_FORCE_HIDING_CHANGED;
 import static com.android.server.wm.WindowSurfacePlacer.SET_ORIENTATION_CHANGE_COMPLETE;
 import static com.android.server.wm.WindowSurfacePlacer.SET_UPDATE_ROTATION;
@@ -56,7 +58,7 @@
  * on behalf of WindowManagerService.
  */
 public class WindowAnimator {
-    private static final String TAG = "WindowAnimator";
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "WindowAnimator" : TAG_WM;
 
     /** How long to give statusbar to clear the private keyguard flag when animating out */
     private static final long KEYGUARD_ANIM_TIMEOUT_MS = 1000;
diff --git a/services/core/java/com/android/server/wm/WindowManagerDebugConfig.java b/services/core/java/com/android/server/wm/WindowManagerDebugConfig.java
new file mode 100644
index 0000000..a49bb31
--- /dev/null
+++ b/services/core/java/com/android/server/wm/WindowManagerDebugConfig.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package com.android.server.wm;
+
+/**
+ * Common class for the various debug {@link android.util.Log} output configuration in the window
+ * manager package.
+ */
+public class WindowManagerDebugConfig {
+    // All output logs in the window manager package use the {@link #TAG_WM} string for tagging
+    // their log output. This makes it easy to identify the origin of the log message when sifting
+    // through a large amount of log output from multiple sources. However, it also makes trying
+    // to figure-out the origin of a log message while debugging the window manager a little
+    // painful. By setting this constant to true, log messages from the window manager package
+    // will be tagged with their class names instead fot the generic tag.
+    static final boolean TAG_WITH_CLASS_NAME = false;
+
+    // Default log tag for the window manager package.
+    static final String TAG_WM = "WindowManager";
+
+    static final boolean DEBUG_RESIZE = false;
+    static final boolean DEBUG = false;
+    static final boolean DEBUG_ADD_REMOVE = false;
+    static final boolean DEBUG_FOCUS = false;
+    static final boolean DEBUG_FOCUS_LIGHT = DEBUG_FOCUS || false;
+    static final boolean DEBUG_ANIM = false;
+    static final boolean DEBUG_KEYGUARD = false;
+    static final boolean DEBUG_LAYOUT = false;
+    static final boolean DEBUG_LAYERS = false;
+    static final boolean DEBUG_INPUT = false;
+    static final boolean DEBUG_INPUT_METHOD = false;
+    static final boolean DEBUG_VISIBILITY = false;
+    static final boolean DEBUG_WINDOW_MOVEMENT = false;
+    static final boolean DEBUG_TOKEN_MOVEMENT = false;
+    static final boolean DEBUG_ORIENTATION = false;
+    static final boolean DEBUG_APP_ORIENTATION = false;
+    static final boolean DEBUG_CONFIGURATION = false;
+    static final boolean DEBUG_APP_TRANSITIONS = false;
+    static final boolean DEBUG_STARTING_WINDOW = false;
+    static final boolean DEBUG_WALLPAPER = false;
+    static final boolean DEBUG_WALLPAPER_LIGHT = false || DEBUG_WALLPAPER;
+    static final boolean DEBUG_DRAG = false;
+    static final boolean DEBUG_SCREEN_ON = false;
+    static final boolean DEBUG_SCREENSHOT = false;
+    static final boolean DEBUG_BOOT = false;
+    static final boolean DEBUG_LAYOUT_REPEATS = true;
+    static final boolean DEBUG_SURFACE_TRACE = false;
+    static final boolean DEBUG_WINDOW_TRACE = false;
+    static final boolean DEBUG_TASK_MOVEMENT = false;
+    static final boolean DEBUG_TASK_POSITIONING = false;
+    static final boolean DEBUG_STACK = false;
+    static final boolean DEBUG_DISPLAY = false;
+    static final boolean DEBUG_POWER = false;
+    static final boolean DEBUG_DIM_LAYER = false;
+    static final boolean SHOW_SURFACE_ALLOC = false;
+    static final boolean SHOW_TRANSACTIONS = false;
+    static final boolean SHOW_VERBOSE_TRANSACTIONS = false && SHOW_TRANSACTIONS;
+    static final boolean SHOW_LIGHT_TRANSACTIONS = false || SHOW_TRANSACTIONS;
+    static final boolean HIDE_STACK_CRAWLS = true;
+    static final boolean DEBUG_WINDOW_CROP = false;
+}
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 5237a13..dbbbb58 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -20,8 +20,8 @@
 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
 import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
 import static android.app.StatusBarManager.DISABLE_MASK;
-import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_BEHIND;
+import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
 import static android.view.WindowManager.DOCKED_INVALID;
 import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
 import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
@@ -50,15 +50,47 @@
 import static android.view.WindowManagerGlobal.RELAYOUT_DEFER_SURFACE_DESTROY;
 import static android.view.WindowManagerGlobal.RELAYOUT_RES_SURFACE_CHANGED;
 import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
-
 import static com.android.server.wm.AppWindowAnimator.PROLONG_ANIMATION_AT_END;
 import static com.android.server.wm.AppWindowAnimator.PROLONG_ANIMATION_AT_START;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_BOOT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DISPLAY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_INPUT_METHOD;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_KEYGUARD;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYERS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RESIZE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREENSHOT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREEN_ON;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_POSITIONING;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TOKEN_MOVEMENT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_MOVEMENT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.HIDE_STACK_CRAWLS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_VERBOSE_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.Manifest;
 import android.animation.ValueAnimator;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.app.ActivityManager;
 import android.app.ActivityManager.StackId;
 import android.app.ActivityManagerNative;
 import android.app.AppOpsManager;
@@ -122,8 +154,8 @@
 import android.view.DisplayInfo;
 import android.view.DropPermissionHolder;
 import android.view.Gravity;
-import android.view.IApplicationToken;
 import android.view.IAppTransitionAnimationSpecsFuture;
+import android.view.IApplicationToken;
 import android.view.IDockDividerVisibilityListener;
 import android.view.IInputFilter;
 import android.view.IOnKeyguardExitResult;
@@ -155,8 +187,8 @@
 import android.view.animation.Animation;
 import android.widget.Toast;
 
-import com.android.internal.app.IAssistScreenshotReceiver;
 import com.android.internal.R;
+import com.android.internal.app.IAssistScreenshotReceiver;
 import com.android.internal.util.FastPrintWriter;
 import com.android.internal.view.IInputContext;
 import com.android.internal.view.IInputMethodClient;
@@ -196,46 +228,6 @@
 /** {@hide} */
 public class WindowManagerService extends IWindowManager.Stub
         implements Watchdog.Monitor, WindowManagerPolicy.WindowManagerFuncs {
-    static final String TAG = "WindowManager";
-    static final boolean DEBUG = false;
-    static final boolean DEBUG_ADD_REMOVE = false;
-    static final boolean DEBUG_FOCUS = false;
-    static final boolean DEBUG_FOCUS_LIGHT = DEBUG_FOCUS || false;
-    static final boolean DEBUG_ANIM = false;
-    static final boolean DEBUG_KEYGUARD = false;
-    static final boolean DEBUG_LAYOUT = false;
-    static final boolean DEBUG_RESIZE = false;
-    static final boolean DEBUG_LAYERS = false;
-    static final boolean DEBUG_INPUT = false;
-    static final boolean DEBUG_INPUT_METHOD = false;
-    static final boolean DEBUG_VISIBILITY = false;
-    static final boolean DEBUG_WINDOW_MOVEMENT = false;
-    static final boolean DEBUG_TOKEN_MOVEMENT = false;
-    static final boolean DEBUG_ORIENTATION = false;
-    static final boolean DEBUG_APP_ORIENTATION = false;
-    static final boolean DEBUG_CONFIGURATION = false;
-    static final boolean DEBUG_APP_TRANSITIONS = false;
-    static final boolean DEBUG_STARTING_WINDOW = false;
-    static final boolean DEBUG_WALLPAPER = false;
-    static final boolean DEBUG_WALLPAPER_LIGHT = false || DEBUG_WALLPAPER;
-    static final boolean DEBUG_DRAG = false;
-    static final boolean DEBUG_SCREEN_ON = false;
-    static final boolean DEBUG_SCREENSHOT = false;
-    static final boolean DEBUG_BOOT = false;
-    static final boolean DEBUG_LAYOUT_REPEATS = true;
-    static final boolean DEBUG_SURFACE_TRACE = false;
-    static final boolean DEBUG_WINDOW_TRACE = false;
-    static final boolean DEBUG_TASK_MOVEMENT = false;
-    static final boolean DEBUG_TASK_POSITIONING = false;
-    static final boolean DEBUG_STACK = false;
-    static final boolean DEBUG_DISPLAY = false;
-    static final boolean DEBUG_POWER = false;
-    static final boolean DEBUG_DIM_LAYER = false;
-    static final boolean SHOW_SURFACE_ALLOC = false;
-    static final boolean SHOW_TRANSACTIONS = false;
-    static final boolean SHOW_LIGHT_TRANSACTIONS = false || SHOW_TRANSACTIONS;
-    static final boolean SHOW_VERBOSE_TRANSACTIONS = false && SHOW_TRANSACTIONS;
-    static final boolean HIDE_STACK_CRAWLS = true;
     static final int LAYOUT_REPEAT_THRESHOLD = 4;
 
     static final boolean PROFILE_ORIENTATION = false;
@@ -706,13 +698,13 @@
                     switch (motionEvent.getAction()) {
                     case MotionEvent.ACTION_DOWN: {
                         if (DEBUG_DRAG) {
-                            Slog.w(TAG, "Unexpected ACTION_DOWN in drag layer");
+                            Slog.w(TAG_WM, "Unexpected ACTION_DOWN in drag layer");
                         }
                     } break;
 
                     case MotionEvent.ACTION_MOVE: {
                         if (mStylusButtonDownAtStart && !isStylusButtonDown) {
-                            if (DEBUG_DRAG) Slog.d(TAG, "Button no longer pressed; dropping at "
+                            if (DEBUG_DRAG) Slog.d(TAG_WM, "Button no longer pressed; dropping at "
                                     + newX + "," + newY);
                             synchronized (mWindowMap) {
                                 endDrag = completeDropLw(newX, newY);
@@ -726,7 +718,7 @@
                     } break;
 
                     case MotionEvent.ACTION_UP: {
-                        if (DEBUG_DRAG) Slog.d(TAG, "Got UP on move channel; dropping at "
+                        if (DEBUG_DRAG) Slog.d(TAG_WM, "Got UP on move channel; dropping at "
                                 + newX + "," + newY);
                         synchronized (mWindowMap) {
                             endDrag = completeDropLw(newX, newY);
@@ -734,13 +726,13 @@
                     } break;
 
                     case MotionEvent.ACTION_CANCEL: {
-                        if (DEBUG_DRAG) Slog.d(TAG, "Drag cancelled!");
+                        if (DEBUG_DRAG) Slog.d(TAG_WM, "Drag cancelled!");
                         endDrag = true;
                     } break;
                     }
 
                     if (endDrag) {
-                        if (DEBUG_DRAG) Slog.d(TAG, "Drag ended; tearing down state");
+                        if (DEBUG_DRAG) Slog.d(TAG_WM, "Drag ended; tearing down state");
                         // tell all the windows that the drag has ended
                         synchronized (mWindowMap) {
                             mDragState.endDragLw();
@@ -752,7 +744,7 @@
                     handled = true;
                 }
             } catch (Exception e) {
-                Slog.e(TAG, "Exception caught by drag handleMotion", e);
+                Slog.e(TAG_WM, "Exception caught by drag handleMotion", e);
             } finally {
                 finishInputEvent(event, handled);
             }
@@ -889,7 +881,7 @@
 
         LocalServices.addService(WindowManagerPolicy.class, mPolicy);
 
-        mPointerEventDispatcher = new PointerEventDispatcher(mInputManager.monitorInput(TAG));
+        mPointerEventDispatcher = new PointerEventDispatcher(mInputManager.monitorInput(TAG_WM));
 
         mFxSession = new SurfaceSession();
         mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
@@ -950,7 +942,7 @@
         updateShowImeWithHardKeyboard();
 
         mHoldingScreenWakeLock = mPowerManager.newWakeLock(
-                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
+                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG_WM);
         mHoldingScreenWakeLock.setReferenceCounted(false);
 
         mAnimator = new WindowAnimator(this);
@@ -988,7 +980,7 @@
             // The window manager only throws security exceptions, so let's
             // log all others.
             if (!(e instanceof SecurityException)) {
-                Slog.wtf(TAG, "Window Manager Crash", e);
+                Slog.wtf(TAG_WM, "Window Manager Crash", e);
             }
             throw e;
         }
@@ -998,7 +990,7 @@
         final WindowList windows = pos.getWindowList();
         final int i = windows.indexOf(pos);
         if (DEBUG_FOCUS || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(
-            TAG, "Adding window " + window + " at "
+            TAG_WM, "Adding window " + window + " at "
             + (i+1) + " of " + windows.size() + " (after " + pos + ")");
         windows.add(i+1, window);
         mWindowsChanged = true;
@@ -1008,10 +1000,10 @@
         final WindowList windows = pos.getWindowList();
         int i = windows.indexOf(pos);
         if (DEBUG_FOCUS || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(
-            TAG, "Adding window " + window + " at "
+            TAG_WM, "Adding window " + window + " at "
             + i + " of " + windows.size() + " (before " + pos + ")");
         if (i < 0) {
-            Slog.w(TAG, "placeWindowBefore: Unable to find " + pos + " in " + windows);
+            Slog.w(TAG_WM, "placeWindowBefore: Unable to find " + pos + " in " + windows);
             i = 0;
         }
         windows.add(i, window);
@@ -1087,7 +1079,7 @@
         }
 
         // No windows from this token on this display
-        if (localLOGV) Slog.v(TAG, "Figuring out where to add app window " + client.asBinder()
+        if (localLOGV) Slog.v(TAG_WM, "Figuring out where to add app window " + client.asBinder()
                 + " (token=" + token + ")");
         // Figure out where the window should go, based on the
         // order of applications.
@@ -1195,7 +1187,7 @@
                 break;
             }
         }
-        if (DEBUG_FOCUS_LIGHT || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG,
+        if (DEBUG_FOCUS_LIGHT || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
                 "Based on layer: Adding window " + win + " at " + (i + 1) + " of "
                         + windows.size());
         windows.add(i + 1, win);
@@ -1227,7 +1219,7 @@
                 //apptoken note that the window could be a floating window
                 //that was created later or a window at the top of the list of
                 //windows associated with this token.
-                if (DEBUG_FOCUS_LIGHT || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG,
+                if (DEBUG_FOCUS_LIGHT || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
                         "not Base app: Adding window " + win + " at " + (newIdx + 1) + " of "
                                 + windows.size());
                 windows.add(newIdx + 1, win);
@@ -1265,7 +1257,7 @@
             }
         }
         i++;
-        if (DEBUG_FOCUS_LIGHT || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG,
+        if (DEBUG_FOCUS_LIGHT || DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
                 "Free window: Adding window " + win + " at " + i + " of " + windows.size());
         windows.add(i, win);
         mWindowsChanged = true;
@@ -1300,7 +1292,7 @@
                 // in the same sublayer.
                 if (wSublayer >= sublayer) {
                     if (addToToken) {
-                        if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + win + " to " + token);
+                        if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Adding " + win + " to " + token);
                         token.windows.add(i, win);
                     }
                     placeWindowBefore(wSublayer >= 0 ? attached : w, win);
@@ -1311,7 +1303,7 @@
                 // in the same sublayer.
                 if (wSublayer > sublayer) {
                     if (addToToken) {
-                        if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + win + " to " + token);
+                        if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Adding " + win + " to " + token);
                         token.windows.add(i, win);
                     }
                     placeWindowBefore(w, win);
@@ -1321,7 +1313,7 @@
         }
         if (i >= NA) {
             if (addToToken) {
-                if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + win + " to " + token);
+                if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Adding " + win + " to " + token);
                 token.windows.add(win);
             }
             if (sublayer < 0) {
@@ -1336,7 +1328,7 @@
     }
 
     private void addWindowToListInOrderLocked(final WindowState win, boolean addToToken) {
-        if (DEBUG_FOCUS_LIGHT) Slog.d(TAG, "addWindowToListInOrderLocked: win=" + win +
+        if (DEBUG_FOCUS_LIGHT) Slog.d(TAG_WM, "addWindowToListInOrderLocked: win=" + win +
                 " Callers=" + Debug.getCallers(4));
         if (win.mAttachedWindow == null) {
             final WindowToken token = win.mToken;
@@ -1347,7 +1339,7 @@
                 addFreeWindowToListLocked(win);
             }
             if (addToToken) {
-                if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + win + " to " + token);
+                if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Adding " + win + " to " + token);
                 token.windows.add(tokenWindowsPos, win);
             }
         } else {
@@ -1375,9 +1367,9 @@
         if (fl == 0 || fl == (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM)
                 || type == TYPE_APPLICATION_STARTING || type == TYPE_DOCK_DIVIDER) {
             if (DEBUG_INPUT_METHOD) {
-                Slog.i(TAG, "isVisibleOrAdding " + w + ": " + w.isVisibleOrAdding());
+                Slog.i(TAG_WM, "isVisibleOrAdding " + w + ": " + w.isVisibleOrAdding());
                 if (!w.isVisibleOrAdding()) {
-                    Slog.i(TAG, "  mSurfaceController=" + w.mWinAnimator.mSurfaceController
+                    Slog.i(TAG_WM, "  mSurfaceController=" + w.mWinAnimator.mSurfaceController
                             + " relayoutCalled=" + w.mRelayoutCalled
                             + " viewVis=" + w.mViewVisibility
                             + " policyVis=" + w.mPolicyVisibility
@@ -1385,7 +1377,7 @@
                             + " attachHid=" + w.mAttachedHidden
                             + " exiting=" + w.mExiting + " destroying=" + w.mDestroying);
                     if (w.mAppToken != null) {
-                        Slog.i(TAG, "  mAppToken.hiddenRequested=" + w.mAppToken.hiddenRequested);
+                        Slog.i(TAG_WM, "  mAppToken.hiddenRequested=" + w.mAppToken.hiddenRequested);
                     }
                 }
             }
@@ -1409,11 +1401,11 @@
         for (i = windows.size() - 1; i >= 0; --i) {
             WindowState win = windows.get(i);
 
-            if (DEBUG_INPUT_METHOD && willMove) Slog.i(TAG, "Checking window @" + i
+            if (DEBUG_INPUT_METHOD && willMove) Slog.i(TAG_WM, "Checking window @" + i
                     + " " + win + " fl=0x" + Integer.toHexString(win.mAttrs.flags));
             if (canBeImeTarget(win)) {
                 w = win;
-                //Slog.i(TAG, "Putting input method here!");
+                //Slog.i(TAG_WM, "Putting input method here!");
 
                 // Yet more tricksyness!  If this window is a "starting"
                 // window, we do actually want to be on top of it, but
@@ -1435,7 +1427,7 @@
 
         // Now w is either mWindows[0] or an IME (or null if mWindows is empty).
 
-        if (DEBUG_INPUT_METHOD && willMove) Slog.v(TAG, "Proposed new IME target: " + w);
+        if (DEBUG_INPUT_METHOD && willMove) Slog.v(TAG_WM, "Proposed new IME target: " + w);
 
         // Now, a special case -- if the last target's window is in the
         // process of exiting, and is above the new target, keep on the
@@ -1448,11 +1440,11 @@
                 && curTarget.isDisplayedLw()
                 && curTarget.isClosing()
                 && (w == null || curTarget.mWinAnimator.mAnimLayer > w.mWinAnimator.mAnimLayer)) {
-            if (DEBUG_INPUT_METHOD) Slog.v(TAG, "Current target higher, not changing");
+            if (DEBUG_INPUT_METHOD) Slog.v(TAG_WM, "Current target higher, not changing");
             return windows.indexOf(curTarget) + 1;
         }
 
-        if (DEBUG_INPUT_METHOD) Slog.v(TAG, "Desired input method target="
+        if (DEBUG_INPUT_METHOD) Slog.v(TAG_WM, "Desired input method target="
                 + w + " willMove=" + willMove);
 
         if (willMove && w != null) {
@@ -1485,7 +1477,7 @@
                 }
 
                 if (highestTarget != null) {
-                    if (DEBUG_INPUT_METHOD) Slog.v(TAG, mAppTransition + " " + highestTarget
+                    if (DEBUG_INPUT_METHOD) Slog.v(TAG_WM, mAppTransition + " " + highestTarget
                             + " animating=" + highestTarget.mWinAnimator.isAnimating()
                             + " layer=" + highestTarget.mWinAnimator.mAnimLayer
                             + " new layer=" + w.mWinAnimator.mAnimLayer);
@@ -1510,10 +1502,10 @@
             }
         }
 
-        //Slog.i(TAG, "Placing input method @" + (i+1));
+        //Slog.i(TAG_WM, "Placing input method @" + (i+1));
         if (w != null) {
             if (willMove) {
-                if (DEBUG_INPUT_METHOD) Slog.w(TAG, "Moving IM target from " + curTarget + " to "
+                if (DEBUG_INPUT_METHOD) Slog.w(TAG_WM, "Moving IM target from " + curTarget + " to "
                         + w + (HIDE_STACK_CRAWLS ? "" : " Callers=" + Debug.getCallers(4)));
                 mInputMethodTarget = w;
                 mInputMethodTargetWaitingAnim = false;
@@ -1526,7 +1518,7 @@
             return i+1;
         }
         if (willMove) {
-            if (DEBUG_INPUT_METHOD) Slog.w(TAG, "Moving IM target from " + curTarget + " to null."
+            if (DEBUG_INPUT_METHOD) Slog.w(TAG_WM, "Moving IM target from " + curTarget + " to null."
                     + (HIDE_STACK_CRAWLS ? "" : " Callers=" + Debug.getCallers(4)));
             mInputMethodTarget = null;
             setInputMethodAnimLayerAdjustment(0);
@@ -1539,7 +1531,7 @@
         if (pos >= 0) {
             win.mTargetAppToken = mInputMethodTarget.mAppToken;
             if (DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(
-                    TAG, "Adding input method window " + win + " at " + pos);
+                    TAG_WM, "Adding input method window " + win + " at " + pos);
             // TODO(multidisplay): IMEs are only supported on the default display.
             getDefaultWindowListLocked().add(pos, win);
             mWindowsChanged = true;
@@ -1552,19 +1544,19 @@
     }
 
     void setInputMethodAnimLayerAdjustment(int adj) {
-        if (DEBUG_LAYERS) Slog.v(TAG, "Setting im layer adj to " + adj);
+        if (DEBUG_LAYERS) Slog.v(TAG_WM, "Setting im layer adj to " + adj);
         mInputMethodAnimLayerAdjustment = adj;
         WindowState imw = mInputMethodWindow;
         if (imw != null) {
             imw.mWinAnimator.mAnimLayer = imw.mLayer + adj;
-            if (DEBUG_LAYERS) Slog.v(TAG, "IM win " + imw
+            if (DEBUG_LAYERS) Slog.v(TAG_WM, "IM win " + imw
                     + " anim layer: " + imw.mWinAnimator.mAnimLayer);
             int wi = imw.mChildWindows.size();
             while (wi > 0) {
                 wi--;
                 WindowState cw = imw.mChildWindows.get(wi);
                 cw.mWinAnimator.mAnimLayer = cw.mLayer + adj;
-                if (DEBUG_LAYERS) Slog.v(TAG, "IM win " + cw
+                if (DEBUG_LAYERS) Slog.v(TAG_WM, "IM win " + cw
                         + " anim layer: " + cw.mWinAnimator.mAnimLayer);
             }
         }
@@ -1573,7 +1565,7 @@
             di --;
             imw = mInputMethodDialogs.get(di);
             imw.mWinAnimator.mAnimLayer = imw.mLayer + adj;
-            if (DEBUG_LAYERS) Slog.v(TAG, "IM win " + imw
+            if (DEBUG_LAYERS) Slog.v(TAG_WM, "IM win " + imw
                     + " anim layer: " + imw.mWinAnimator.mAnimLayer);
         }
     }
@@ -1583,7 +1575,7 @@
         int wpos = windows.indexOf(win);
         if (wpos >= 0) {
             if (wpos < interestingPos) interestingPos--;
-            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Temp removing at " + wpos + ": " + win);
+            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Temp removing at " + wpos + ": " + win);
             windows.remove(wpos);
             mWindowsChanged = true;
             int NC = win.mChildWindows.size();
@@ -1593,7 +1585,7 @@
                 int cpos = windows.indexOf(cw);
                 if (cpos >= 0) {
                     if (cpos < interestingPos) interestingPos--;
-                    if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Temp removing child at "
+                    if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Temp removing child at "
                             + cpos + ": " + cw);
                     windows.remove(cpos);
                 }
@@ -1610,7 +1602,7 @@
         WindowList windows = win.getWindowList();
         int wpos = windows.indexOf(win);
         if (wpos >= 0) {
-            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "ReAdd removing from " + wpos + ": " + win);
+            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "ReAdd removing from " + wpos + ": " + win);
             windows.remove(wpos);
             mWindowsChanged = true;
             reAddWindowLocked(wpos, win);
@@ -1621,7 +1613,7 @@
         int N = windows.size();
         while (N > 0) {
             N--;
-            Slog.v(TAG, prefix + "#" + N + ": " + windows.get(N));
+            Slog.v(TAG_WM, prefix + "#" + N + ": " + windows.get(N));
         }
     }
 
@@ -1631,12 +1623,12 @@
         // TODO(multidisplay): IMEs are only supported on the default display.
         WindowList windows = getDefaultWindowListLocked();
         final int N = dialogs.size();
-        if (DEBUG_INPUT_METHOD) Slog.v(TAG, "Removing " + N + " dialogs w/pos=" + pos);
+        if (DEBUG_INPUT_METHOD) Slog.v(TAG_WM, "Removing " + N + " dialogs w/pos=" + pos);
         for (int i=0; i<N; i++) {
             pos = tmpRemoveWindowLocked(pos, dialogs.get(i));
         }
         if (DEBUG_INPUT_METHOD) {
-            Slog.v(TAG, "Window list w/pos=" + pos);
+            Slog.v(TAG_WM, "Window list w/pos=" + pos);
             logWindowList(windows, "  ");
         }
 
@@ -1653,14 +1645,14 @@
                     break;
                 }
             }
-            if (DEBUG_INPUT_METHOD) Slog.v(TAG, "Adding " + N + " dialogs at pos=" + pos);
+            if (DEBUG_INPUT_METHOD) Slog.v(TAG_WM, "Adding " + N + " dialogs at pos=" + pos);
             for (int i=0; i<N; i++) {
                 WindowState win = dialogs.get(i);
                 win.mTargetAppToken = targetAppToken;
                 pos = reAddWindowLocked(pos, win);
             }
             if (DEBUG_INPUT_METHOD) {
-                Slog.v(TAG, "Final window list:");
+                Slog.v(TAG_WM, "Final window list:");
                 logWindowList(windows, "  ");
             }
             return;
@@ -1670,7 +1662,7 @@
             win.mTargetAppToken = null;
             reAddWindowToListInOrderLocked(win);
             if (DEBUG_INPUT_METHOD) {
-                Slog.v(TAG, "No IM target, final list:");
+                Slog.v(TAG_WM, "No IM target, final list:");
                 logWindowList(windows, "  ");
             }
         }
@@ -1736,18 +1728,18 @@
 
             if (imWin != null) {
                 if (DEBUG_INPUT_METHOD) {
-                    Slog.v(TAG, "Moving IM from " + imPos);
+                    Slog.v(TAG_WM, "Moving IM from " + imPos);
                     logWindowList(windows, "  ");
                 }
                 imPos = tmpRemoveWindowLocked(imPos, imWin);
                 if (DEBUG_INPUT_METHOD) {
-                    Slog.v(TAG, "List after removing with new pos " + imPos + ":");
+                    Slog.v(TAG_WM, "List after removing with new pos " + imPos + ":");
                     logWindowList(windows, "  ");
                 }
                 imWin.mTargetAppToken = mInputMethodTarget.mAppToken;
                 reAddWindowLocked(imPos, imWin);
                 if (DEBUG_INPUT_METHOD) {
-                    Slog.v(TAG, "List after moving IM to " + imPos + ":");
+                    Slog.v(TAG_WM, "List after moving IM to " + imPos + ":");
                     logWindowList(windows, "  ");
                 }
                 if (DN > 0) moveInputMethodDialogsLocked(imPos+1);
@@ -1760,12 +1752,12 @@
             // because they aren't currently associated with a focus window.
 
             if (imWin != null) {
-                if (DEBUG_INPUT_METHOD) Slog.v(TAG, "Moving IM from " + imPos);
+                if (DEBUG_INPUT_METHOD) Slog.v(TAG_WM, "Moving IM from " + imPos);
                 tmpRemoveWindowLocked(0, imWin);
                 imWin.mTargetAppToken = null;
                 reAddWindowToListInOrderLocked(imWin);
                 if (DEBUG_INPUT_METHOD) {
-                    Slog.v(TAG, "List with no IM target:");
+                    Slog.v(TAG_WM, "List with no IM target:");
                     logWindowList(windows, "  ");
                 }
                 if (DN > 0) moveInputMethodDialogsLocked(-1);
@@ -1804,38 +1796,38 @@
 
             final DisplayContent displayContent = getDisplayContentLocked(displayId);
             if (displayContent == null) {
-                Slog.w(TAG, "Attempted to add window to a display that does not exist: "
+                Slog.w(TAG_WM, "Attempted to add window to a display that does not exist: "
                         + displayId + ".  Aborting.");
                 return WindowManagerGlobal.ADD_INVALID_DISPLAY;
             }
             if (!displayContent.hasAccess(session.mUid)) {
-                Slog.w(TAG, "Attempted to add window to a display for which the application "
+                Slog.w(TAG_WM, "Attempted to add window to a display for which the application "
                         + "does not have access: " + displayId + ".  Aborting.");
                 return WindowManagerGlobal.ADD_INVALID_DISPLAY;
             }
 
             if (mWindowMap.containsKey(client.asBinder())) {
-                Slog.w(TAG, "Window " + client + " is already added");
+                Slog.w(TAG_WM, "Window " + client + " is already added");
                 return WindowManagerGlobal.ADD_DUPLICATE_ADD;
             }
 
             if (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW) {
                 attachedWindow = windowForClientLocked(null, attrs.token, false);
                 if (attachedWindow == null) {
-                    Slog.w(TAG, "Attempted to add window with token that is not a window: "
+                    Slog.w(TAG_WM, "Attempted to add window with token that is not a window: "
                           + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN;
                 }
                 if (attachedWindow.mAttrs.type >= FIRST_SUB_WINDOW
                         && attachedWindow.mAttrs.type <= LAST_SUB_WINDOW) {
-                    Slog.w(TAG, "Attempted to add window with token that is a sub-window: "
+                    Slog.w(TAG_WM, "Attempted to add window with token that is a sub-window: "
                             + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN;
                 }
             }
 
             if (type == TYPE_PRIVATE_PRESENTATION && !displayContent.isPrivate()) {
-                Slog.w(TAG, "Attempted to add private presentation window to a non-private display.  Aborting.");
+                Slog.w(TAG_WM, "Attempted to add private presentation window to a non-private display.  Aborting.");
                 return WindowManagerGlobal.ADD_PERMISSION_DENIED;
             }
 
@@ -1844,37 +1836,37 @@
             AppWindowToken atoken = null;
             if (token == null) {
                 if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
-                    Slog.w(TAG, "Attempted to add application window with unknown token "
+                    Slog.w(TAG_WM, "Attempted to add application window with unknown token "
                           + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (type == TYPE_INPUT_METHOD) {
-                    Slog.w(TAG, "Attempted to add input method window with unknown token "
+                    Slog.w(TAG_WM, "Attempted to add input method window with unknown token "
                           + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (type == TYPE_VOICE_INTERACTION) {
-                    Slog.w(TAG, "Attempted to add voice interaction window with unknown token "
+                    Slog.w(TAG_WM, "Attempted to add voice interaction window with unknown token "
                           + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (type == TYPE_WALLPAPER) {
-                    Slog.w(TAG, "Attempted to add wallpaper window with unknown token "
+                    Slog.w(TAG_WM, "Attempted to add wallpaper window with unknown token "
                           + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (type == TYPE_DREAM) {
-                    Slog.w(TAG, "Attempted to add Dream window with unknown token "
+                    Slog.w(TAG_WM, "Attempted to add Dream window with unknown token "
                           + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (type == TYPE_QS_DIALOG) {
-                    Slog.w(TAG, "Attempted to add QS dialog window with unknown token "
+                    Slog.w(TAG_WM, "Attempted to add QS dialog window with unknown token "
                           + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (type == TYPE_ACCESSIBILITY_OVERLAY) {
-                    Slog.w(TAG, "Attempted to add Accessibility overlay window with unknown token "
+                    Slog.w(TAG_WM, "Attempted to add Accessibility overlay window with unknown token "
                             + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
@@ -1883,52 +1875,52 @@
             } else if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
                 atoken = token.appWindowToken;
                 if (atoken == null) {
-                    Slog.w(TAG, "Attempted to add window with non-application token "
+                    Slog.w(TAG_WM, "Attempted to add window with non-application token "
                           + token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_NOT_APP_TOKEN;
                 } else if (atoken.removed) {
-                    Slog.w(TAG, "Attempted to add window with exiting application token "
+                    Slog.w(TAG_WM, "Attempted to add window with exiting application token "
                           + token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_APP_EXITING;
                 }
                 if (type == TYPE_APPLICATION_STARTING && atoken.firstWindowDrawn) {
                     // No need for this guy!
                     if (DEBUG_STARTING_WINDOW || localLOGV) Slog.v(
-                            TAG, "**** NO NEED TO START: " + attrs.getTitle());
+                            TAG_WM, "**** NO NEED TO START: " + attrs.getTitle());
                     return WindowManagerGlobal.ADD_STARTING_NOT_NEEDED;
                 }
             } else if (type == TYPE_INPUT_METHOD) {
                 if (token.windowType != TYPE_INPUT_METHOD) {
-                    Slog.w(TAG, "Attempted to add input method window with bad token "
+                    Slog.w(TAG_WM, "Attempted to add input method window with bad token "
                             + attrs.token + ".  Aborting.");
                       return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (type == TYPE_VOICE_INTERACTION) {
                 if (token.windowType != TYPE_VOICE_INTERACTION) {
-                    Slog.w(TAG, "Attempted to add voice interaction window with bad token "
+                    Slog.w(TAG_WM, "Attempted to add voice interaction window with bad token "
                             + attrs.token + ".  Aborting.");
                       return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (type == TYPE_WALLPAPER) {
                 if (token.windowType != TYPE_WALLPAPER) {
-                    Slog.w(TAG, "Attempted to add wallpaper window with bad token "
+                    Slog.w(TAG_WM, "Attempted to add wallpaper window with bad token "
                             + attrs.token + ".  Aborting.");
                       return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (type == TYPE_DREAM) {
                 if (token.windowType != TYPE_DREAM) {
-                    Slog.w(TAG, "Attempted to add Dream window with bad token "
+                    Slog.w(TAG_WM, "Attempted to add Dream window with bad token "
                             + attrs.token + ".  Aborting.");
                       return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (type == TYPE_ACCESSIBILITY_OVERLAY) {
                 if (token.windowType != TYPE_ACCESSIBILITY_OVERLAY) {
-                    Slog.w(TAG, "Attempted to add Accessibility overlay window with bad token "
+                    Slog.w(TAG_WM, "Attempted to add Accessibility overlay window with bad token "
                             + attrs.token + ".  Aborting.");
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (token.appWindowToken != null) {
-                Slog.w(TAG, "Non-null appWindowToken for system window of type=" + type);
+                Slog.w(TAG_WM, "Non-null appWindowToken for system window of type=" + type);
                 // It is not valid to use an app token with other system types; we will
                 // instead make a new token for it (as if null had been passed in for the token).
                 attrs.token = null;
@@ -1941,18 +1933,18 @@
             if (win.mDeathRecipient == null) {
                 // Client has apparently died, so there is no reason to
                 // continue.
-                Slog.w(TAG, "Adding window client " + client.asBinder()
+                Slog.w(TAG_WM, "Adding window client " + client.asBinder()
                         + " that is dead, aborting.");
                 return WindowManagerGlobal.ADD_APP_EXITING;
             }
 
             if (win.getDisplayContent() == null) {
-                Slog.w(TAG, "Adding window to Display that has been removed.");
+                Slog.w(TAG_WM, "Adding window to Display that has been removed.");
                 return WindowManagerGlobal.ADD_INVALID_DISPLAY;
             }
 
             if (atoken != null && atoken.appDied) {
-                Slog.d(TAG, "App is now revived: " + atoken);
+                Slog.d(TAG_WM, "App is now revived: " + atoken);
                 atoken.appDied = false;
             }
 
@@ -1992,7 +1984,7 @@
 
             if (type == TYPE_APPLICATION_STARTING && token.appWindowToken != null) {
                 token.appWindowToken.startingWindow = win;
-                if (DEBUG_STARTING_WINDOW) Slog.v (TAG, "addWindow: " + token.appWindowToken
+                if (DEBUG_STARTING_WINDOW) Slog.v (TAG_WM, "addWindow: " + token.appWindowToken
                         + " startingWindow=" + win);
             }
 
@@ -2073,7 +2065,7 @@
             }
             mInputMonitor.updateInputWindowsLw(false /*force*/);
 
-            if (localLOGV || DEBUG_ADD_REMOVE) Slog.v(TAG, "addWindow: New client "
+            if (localLOGV || DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "addWindow: New client "
                     + client.asBinder() + ": window=" + win + " Callers=" + Debug.getCallers(5));
 
             if (win.isVisibleOrAdding() && updateOrientationFromAppTokensLocked(false)) {
@@ -2178,11 +2170,11 @@
     void removeWindowLocked(WindowState win) {
         final boolean startingWindow = win.mAttrs.type == TYPE_APPLICATION_STARTING;
         if (startingWindow) {
-            if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "Starting window removed " + win);
+            if (DEBUG_STARTING_WINDOW) Slog.d(TAG_WM, "Starting window removed " + win);
         }
 
         if (localLOGV || DEBUG_FOCUS || DEBUG_FOCUS_LIGHT && win==mCurrentFocus) Slog.v(
-                TAG, "Remove " + win + " client="
+                TAG_WM, "Remove " + win + " client="
                 + Integer.toHexString(System.identityHashCode(win.mClient.asBinder()))
                 + ", surfaceController=" + win.mWinAnimator.mSurfaceController + " Callers="
                 + Debug.getCallers(4));
@@ -2192,7 +2184,7 @@
         win.disposeInputChannel();
 
         if (DEBUG_APP_TRANSITIONS) Slog.v(
-                TAG, "Remove " + win + ": mSurfaceController=" + win.mWinAnimator.mSurfaceController
+                TAG_WM, "Remove " + win + ": mSurfaceController=" + win.mWinAnimator.mSurfaceController
                 + " mExiting=" + win.mExiting
                 + " isAnimating=" + win.mWinAnimator.isAnimating()
                 + " app-animation="
@@ -2213,7 +2205,7 @@
             if (appToken != null && appToken.mWillReplaceWindow) {
                 // This window is going to be replaced. We need to keep it around until the new one
                 // gets added, then we will get rid of this one.
-                if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Preserving " + win + " until the new one is "
+                if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Preserving " + win + " until the new one is "
                         + "added");
                 win.mExiting = true;
                 appToken.mReplacingRemoveRequested = true;
@@ -2225,7 +2217,7 @@
             wasVisible = win.isWinVisibleLw();
 
             if (wasVisible && appToken != null && appToken.appDied) {
-                if (DEBUG_ADD_REMOVE) Slog.v(TAG,
+                if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
                         "Not removing " + win + " because app died while it's visible");
 
                 win.mAppDied = true;
@@ -2300,7 +2292,7 @@
 
         for (int i=win.mChildWindows.size()-1; i>=0; i--) {
             WindowState cwin = win.mChildWindows.get(i);
-            Slog.w(TAG, "Force-removing child win " + cwin + " from container "
+            Slog.w(TAG_WM, "Force-removing child win " + cwin + " from container "
                     + win);
             removeWindowInnerLocked(cwin);
         }
@@ -2314,13 +2306,13 @@
         if (false) {
             RuntimeException e = new RuntimeException("here");
             e.fillInStackTrace();
-            Slog.w(TAG, "Removing window " + win, e);
+            Slog.w(TAG_WM, "Removing window " + win, e);
         }
 
         mPolicy.removeWindowLw(win);
         win.removeLocked();
 
-        if (DEBUG_ADD_REMOVE) Slog.v(TAG, "removeWindowInnerLocked: " + win);
+        if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "removeWindowInnerLocked: " + win);
         mWindowMap.remove(win.mClient.asBinder());
         if (win.mAppOp != AppOpsManager.OP_NONE) {
             mAppOps.finishOp(win.mAppOp, win.getOwningUid(), win.getOwningPackage());
@@ -2329,7 +2321,7 @@
         mPendingRemove.remove(win);
         mResizingWindows.remove(win);
         mWindowsChanged = true;
-        if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Final remove of window: " + win);
+        if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Final remove of window: " + win);
 
         if (mInputMethodWindow == win) {
             mInputMethodWindow = null;
@@ -2339,13 +2331,13 @@
 
         final WindowToken token = win.mToken;
         final AppWindowToken atoken = win.mAppToken;
-        if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + win + " from " + token);
+        if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Removing " + win + " from " + token);
         token.windows.remove(win);
         if (atoken != null) {
             atoken.allAppWindows.remove(win);
         }
         if (localLOGV) Slog.v(
-                TAG, "**** Removing window " + win + ": count="
+                TAG_WM, "**** Removing window " + win + ": count="
                 + token.windows.size());
         if (token.windows.size() == 0) {
             if (!token.explicit) {
@@ -2357,13 +2349,13 @@
 
         if (atoken != null) {
             if (atoken.startingWindow == win) {
-                if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Notify removed startingWindow " + win);
+                if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Notify removed startingWindow " + win);
                 scheduleRemoveStartingWindowLocked(atoken);
             } else
             if (atoken.allAppWindows.size() == 0 && atoken.startingData != null) {
                 // If this is the last window and we had requested a starting
                 // transition window, well there is no point now.
-                if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Nulling last startingWindow");
+                if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Nulling last startingWindow");
                 atoken.startingData = null;
             } else if (atoken.allAppWindows.size() == 1 && atoken.startingView != null) {
                 // If this is the last window except for a starting transition
@@ -2419,18 +2411,18 @@
     static void logSurface(WindowState w, String msg, RuntimeException where) {
         String str = "  SURFACE " + msg + ": " + w;
         if (where != null) {
-            Slog.i(TAG, str, where);
+            Slog.i(TAG_WM, str, where);
         } else {
-            Slog.i(TAG, str);
+            Slog.i(TAG_WM, str);
         }
     }
 
     static void logSurface(SurfaceControl s, String title, String msg, RuntimeException where) {
         String str = "  SURFACE " + s + ": " + msg + " / " + title;
         if (where != null) {
-            Slog.i(TAG, str, where);
+            Slog.i(TAG_WM, str, where);
         } else {
-            Slog.i(TAG, str);
+            Slog.i(TAG_WM, str);
         }
     }
 
@@ -2543,7 +2535,7 @@
                 win.setWindowScale(win.mRequestedWidth, win.mRequestedHeight);
 
                 if (SHOW_TRANSACTIONS) {
-                    Slog.i(TAG, ">>> OPEN TRANSACTION repositionChild");
+                    Slog.i(TAG_WM, ">>> OPEN TRANSACTION repositionChild");
                 }
 
                 SurfaceControl.openTransaction();
@@ -2561,7 +2553,7 @@
 
                 SurfaceControl.closeTransaction();
                 if (SHOW_TRANSACTIONS) {
-                    Slog.i(TAG, "<<< CLOSE TRANSACTION repositionChild");
+                    Slog.i(TAG_WM, "<<< CLOSE TRANSACTION repositionChild");
                 }
 
                 outFrame = win.mCompatFrame;
@@ -2633,7 +2625,7 @@
                 }
             }
 
-            if (DEBUG_LAYOUT) Slog.v(TAG, "Relayout " + win + ": viewVisibility=" + viewVisibility
+            if (DEBUG_LAYOUT) Slog.v(TAG_WM, "Relayout " + win + ": viewVisibility=" + viewVisibility
                     + " req=" + requestedWidth + "x" + requestedHeight + " " + win.mAttrs);
             winAnimator.mSurfaceDestroyDeferred = (flags & RELAYOUT_DEFER_SURFACE_DESTROY) != 0;
             win.mEnforceSizeCompat =
@@ -2662,7 +2654,7 @@
             if (DEBUG_SCREEN_ON) {
                 RuntimeException stack = new RuntimeException();
                 stack.fillInStackTrace();
-                Slog.i(TAG, "Relayout " + win + ": oldVis=" + oldVisibility
+                Slog.i(TAG_WM, "Relayout " + win + ": oldVis=" + oldVisibility
                         + " newVis=" + viewVisibility, stack);
             }
             if (viewVisibility == View.VISIBLE &&
@@ -2674,7 +2666,7 @@
                 } catch (Exception e) {
                     mInputMonitor.updateInputWindowsLw(true /*force*/);
 
-                    Slog.w(TAG, "Exception thrown when creating surface for client "
+                    Slog.w(TAG_WM, "Exception thrown when creating surface for client "
                              + client + " (" + win.mAttrs.getTitle() + ")",
                              e);
                     Binder.restoreCallingIdentity(origId);
@@ -2693,7 +2685,7 @@
                 winAnimator.mEnteringAnimation = false;
                 if (winAnimator.mSurfaceController != null &&
                         winAnimator.mSurfaceController.hasSurface()) {
-                    if (DEBUG_VISIBILITY) Slog.i(TAG, "Relayout invis " + win
+                    if (DEBUG_VISIBILITY) Slog.i(TAG_WM, "Relayout invis " + win
                             + ": mExiting=" + win.mExiting);
                     // If we are using a saved surface to do enter animation, just let the
                     // animation run and don't destroy the surface. This could happen when
@@ -2713,7 +2705,7 @@
                 }
 
                 outSurface.release();
-                if (DEBUG_VISIBILITY) Slog.i(TAG, "Releasing surface in: " + win);
+                if (DEBUG_VISIBILITY) Slog.i(TAG_WM, "Releasing surface in: " + win);
             }
 
             if (focusMayChange) {
@@ -2765,7 +2757,7 @@
             outStableInsets.set(win.mStableInsets);
             outOutsets.set(win.mOutsets);
             if (localLOGV) Slog.v(
-                TAG, "Relayout given client " + client.asBinder()
+                TAG_WM, "Relayout given client " + client.asBinder()
                 + ", requestedWidth=" + requestedWidth
                 + ", requestedHeight=" + requestedHeight
                 + ", viewVisibility=" + viewVisibility
@@ -2773,14 +2765,14 @@
                 + ", surface=" + outSurface);
 
             if (localLOGV || DEBUG_FOCUS) Slog.v(
-                TAG, "Relayout of " + win + ": focusMayChange=" + focusMayChange);
+                TAG_WM, "Relayout of " + win + ": focusMayChange=" + focusMayChange);
 
             result |= mInTouchMode ? WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE : 0;
 
             mInputMonitor.updateInputWindowsLw(true /*force*/);
 
             if (DEBUG_LAYOUT) {
-                Slog.v(TAG, "Relayout complete " + win + ": outFrame=" + outFrame.toShortString());
+                Slog.v(TAG_WM, "Relayout complete " + win + ": outFrame=" + outFrame.toShortString());
             }
         }
 
@@ -2834,7 +2826,7 @@
         WindowSurfaceController surfaceController = winAnimator.createSurfaceLocked();
         if (surfaceController != null) {
             surfaceController.getSurface(outSurface);
-            if (SHOW_TRANSACTIONS) Slog.i(TAG, "  OUT SURFACE " + outSurface + ": copied");
+            if (SHOW_TRANSACTIONS) Slog.i(TAG_WM, "  OUT SURFACE " + outSurface + ": copied");
         } else {
             // For some reason there isn't a surface.  Clear the
             // caller's object so they see the same state.
@@ -2930,7 +2922,7 @@
         try {
             synchronized (mWindowMap) {
                 WindowState win = windowForClientLocked(session, client, false);
-                if (DEBUG_ADD_REMOVE) Slog.d(TAG, "finishDrawingWindow: " + win + " mDrawState="
+                if (DEBUG_ADD_REMOVE) Slog.d(TAG_WM, "finishDrawingWindow: " + win + " mDrawState="
                         + (win != null ? win.mWinAnimator.drawStateToString() : "null"));
                 if (win != null && win.mWinAnimator.finishDrawingLocked()) {
                     if ((win.mAttrs.flags & FLAG_SHOW_WALLPAPER) != 0) {
@@ -2956,7 +2948,7 @@
             DisplayInfo displayInfo = getDefaultDisplayInfoLocked();
             final int width = displayInfo.appWidth;
             final int height = displayInfo.appHeight;
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
+            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG_WM,
                     "applyAnimation: atoken=" + atoken);
 
             // Determine the visible rect to calculate the thumbnail clip
@@ -2992,7 +2984,7 @@
                 // screen gets the enter animation. Both appear in the mOpeningApps set.
                 enter = false;
             }
-            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG, "Loading animation for app transition."
+            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG_WM, "Loading animation for app transition."
                     + " transit=" + AppTransition.appTransitionToString(transit) + " enter=" + enter
                     + " frame=" + frame + " insets=" + insets + " surfaceInsets=" + surfaceInsets);
             Animation a = mAppTransition.loadAnimation(lp, transit, enter,
@@ -3005,7 +2997,7 @@
                         e = new RuntimeException();
                         e.fillInStackTrace();
                     }
-                    Slog.v(TAG, "Loaded animation " + a + " for " + atoken, e);
+                    Slog.v(TAG_WM, "Loaded animation " + a + " for " + atoken, e);
                 }
                 final int containingWidth = frame.width();
                 final int containingHeight = frame.height();
@@ -3027,7 +3019,7 @@
         synchronized (mWindowMap) {
             int t = tasks.size() - 1;
             if (t < 0) {
-                Slog.w(TAG, "validateAppTokens: empty task list");
+                Slog.w(TAG_WM, "validateAppTokens: empty task list");
                 return;
             }
 
@@ -3036,7 +3028,7 @@
             Task targetTask = mTaskIdToTask.get(taskId);
             DisplayContent displayContent = targetTask.getDisplayContent();
             if (displayContent == null) {
-                Slog.w(TAG, "validateAppTokens: no Display for taskId=" + taskId);
+                Slog.w(TAG_WM, "validateAppTokens: no Display for taskId=" + taskId);
                 return;
             }
 
@@ -3050,7 +3042,7 @@
                 DisplayContent lastDisplayContent = displayContent;
                 displayContent = mTaskIdToTask.get(taskId).getDisplayContent();
                 if (displayContent != lastDisplayContent) {
-                    Slog.w(TAG, "validateAppTokens: displayContent changed in TaskGroup list!");
+                    Slog.w(TAG_WM, "validateAppTokens: displayContent changed in TaskGroup list!");
                     return;
                 }
 
@@ -3076,9 +3068,9 @@
             }
 
             if (taskNdx >= 0 || t >= 0) {
-                Slog.w(TAG, "validateAppTokens: Mismatch! ActivityManager=" + tasks);
-                Slog.w(TAG, "validateAppTokens: Mismatch! WindowManager=" + localTasks);
-                Slog.w(TAG, "validateAppTokens: Mismatch! Callers=" + Debug.getCallers(4));
+                Slog.w(TAG_WM, "validateAppTokens: Mismatch! ActivityManager=" + tasks);
+                Slog.w(TAG_WM, "validateAppTokens: Mismatch! WindowManager=" + localTasks);
+                Slog.w(TAG_WM, "validateAppTokens: Mismatch! Callers=" + Debug.getCallers(4));
             }
         }
     }
@@ -3101,7 +3093,7 @@
                 + Binder.getCallingPid()
                 + ", uid=" + Binder.getCallingUid()
                 + " requires " + permission;
-        Slog.w(TAG, msg);
+        Slog.w(TAG_WM, msg);
         return false;
     }
 
@@ -3127,7 +3119,7 @@
         synchronized(mWindowMap) {
             WindowToken wtoken = mTokenMap.get(token);
             if (wtoken != null) {
-                Slog.w(TAG, "Attempted to add existing input method token: " + token);
+                Slog.w(TAG_WM, "Attempted to add existing input method token: " + token);
                 return;
             }
             wtoken = new WindowToken(this, token, type, true);
@@ -3197,7 +3189,7 @@
 
                 mInputMonitor.updateInputWindowsLw(true /*force*/);
             } else {
-                Slog.w(TAG, "Attempted to remove non-existing token: " + token);
+                Slog.w(TAG_WM, "Attempted to remove non-existing token: " + token);
             }
         }
         Binder.restoreCallingIdentity(origId);
@@ -3205,7 +3197,7 @@
 
     private Task createTaskLocked(int taskId, int stackId, int userId, AppWindowToken atoken,
             Rect bounds, Configuration config) {
-        if (DEBUG_STACK) Slog.i(TAG, "createTaskLocked: taskId=" + taskId + " stackId=" + stackId
+        if (DEBUG_STACK) Slog.i(TAG_WM, "createTaskLocked: taskId=" + taskId + " stackId=" + stackId
                 + " atoken=" + atoken + " bounds=" + bounds);
         final TaskStack stack = mStackIdToStack.get(stackId);
         if (stack == null) {
@@ -3238,14 +3230,14 @@
         try {
             inputDispatchingTimeoutNanos = token.getKeyDispatchingTimeout() * 1000000L;
         } catch (RemoteException ex) {
-            Slog.w(TAG, "Could not get dispatching timeout.", ex);
+            Slog.w(TAG_WM, "Could not get dispatching timeout.", ex);
             inputDispatchingTimeoutNanos = DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
         }
 
         synchronized(mWindowMap) {
             AppWindowToken atoken = findAppWindowToken(token.asBinder());
             if (atoken != null) {
-                Slog.w(TAG, "Attempted to add existing app token: " + token);
+                Slog.w(TAG_WM, "Attempted to add existing app token: " + token);
                 return;
             }
             atoken = new AppWindowToken(this, token, voiceInteraction);
@@ -3257,7 +3249,7 @@
                     (ActivityInfo.CONFIG_SCREEN_SIZE | ActivityInfo.CONFIG_ORIENTATION)) != 0;
             atoken.mLaunchTaskBehind = launchTaskBehind;
             atoken.mCropWindowsToStack = cropWindowsToStack;
-            if (DEBUG_TOKEN_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG, "addAppToken: " + atoken
+            if (DEBUG_TOKEN_MOVEMENT || DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "addAppToken: " + atoken
                     + " to stack=" + stackId + " task=" + taskId + " at " + addPos);
 
             Task task = mTaskIdToTask.get(taskId);
@@ -3285,7 +3277,7 @@
         synchronized(mWindowMap) {
             final AppWindowToken atoken = findAppWindowToken(token);
             if (atoken == null) {
-                Slog.w(TAG, "Attempted to set task id of non-existing app token: " + token);
+                Slog.w(TAG_WM, "Attempted to set task id of non-existing app token: " + token);
                 return;
             }
             final Task oldTask = atoken.mTask;
@@ -3303,7 +3295,7 @@
     public int getOrientationLocked() {
         if (mDisplayFrozen) {
             if (mLastWindowForcedOrientation != SCREEN_ORIENTATION_UNSPECIFIED) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG,
+                if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                         "Display is frozen, return " + mLastWindowForcedOrientation);
                 // If the display is frozen, some activities may be in the middle
                 // of restarting, and thus have removed their old window.  If the
@@ -3330,7 +3322,7 @@
                     continue;
                 }
 
-                if (DEBUG_ORIENTATION) Slog.v(TAG, win + " forcing orientation to " + req);
+                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, win + " forcing orientation to " + req);
                 if (mPolicy.isKeyguardHostWindow(win.mAttrs)) {
                     mLastKeyguardForcedOrientation = req;
                 }
@@ -3350,11 +3342,11 @@
                     if (req == SCREEN_ORIENTATION_BEHIND) {
                         req = mLastKeyguardForcedOrientation;
                     }
-                    if (DEBUG_ORIENTATION) Slog.v(TAG, "Done at " + appShowWhenLocked
+                    if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Done at " + appShowWhenLocked
                             + " -- show when locked, return " + req);
                     return req;
                 }
-                if (DEBUG_ORIENTATION) Slog.v(TAG,
+                if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                         "No one is requesting an orientation when the screen is locked");
                 return mLastKeyguardForcedOrientation;
             }
@@ -3384,12 +3376,12 @@
             for (int tokenNdx = firstToken; tokenNdx >= 0; --tokenNdx) {
                 final AppWindowToken atoken = tokens.get(tokenNdx);
 
-                if (DEBUG_APP_ORIENTATION) Slog.v(TAG, "Checking app orientation: " + atoken);
+                if (DEBUG_APP_ORIENTATION) Slog.v(TAG_WM, "Checking app orientation: " + atoken);
 
                 // if we're about to tear down this window and not seek for
                 // the behind activity, don't use it for orientation
                 if (!findingBehind && !atoken.hidden && atoken.hiddenRequested) {
-                    if (DEBUG_ORIENTATION) Slog.v(TAG,
+                    if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                             "Skipping " + atoken + " -- going to hide");
                     continue;
                 }
@@ -3399,7 +3391,7 @@
                     // explicitly say to use the orientation behind it, and the last app was
                     // full screen, then we'll stick with the user's orientation.
                     if (lastOrientation != SCREEN_ORIENTATION_BEHIND && lastFullscreen) {
-                        if (DEBUG_ORIENTATION) Slog.v(TAG, "Done at " + atoken
+                        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Done at " + atoken
                                 + " -- end of group, return " + lastOrientation);
                         return lastOrientation;
                     }
@@ -3407,7 +3399,7 @@
 
                 // We ignore any hidden applications on the top.
                 if (atoken.hiddenRequested) {
-                    if (DEBUG_ORIENTATION) Slog.v(TAG,
+                    if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                             "Skipping " + atoken + " -- hidden on top");
                     continue;
                 }
@@ -3423,20 +3415,20 @@
                 // orientation it has and ignores whatever is under it.
                 lastFullscreen = atoken.appFullscreen;
                 if (lastFullscreen && or != SCREEN_ORIENTATION_BEHIND) {
-                    if (DEBUG_ORIENTATION) Slog.v(TAG,
+                    if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                             "Done at " + atoken + " -- full screen, return " + or);
                     return or;
                 }
                 // If this application has requested an explicit orientation, then use it.
                 if (or != SCREEN_ORIENTATION_UNSPECIFIED && or != SCREEN_ORIENTATION_BEHIND) {
-                    if (DEBUG_ORIENTATION) Slog.v(TAG,
+                    if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                             "Done at " + atoken + " -- explicitly set, return " + or);
                     return or;
                 }
                 findingBehind |= (or == SCREEN_ORIENTATION_BEHIND);
             }
         }
-        if (DEBUG_ORIENTATION) Slog.v(TAG,
+        if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                 "No app is requesting an orientation, return " + mForcedAppOrientation);
         // The next app has not been requested to be visible, so we keep the current orientation
         // to prevent freezing/unfreezing the display too early.
@@ -3567,7 +3559,7 @@
         synchronized(mWindowMap) {
             AppWindowToken atoken = findAppWindowToken(token.asBinder());
             if (atoken == null) {
-                Slog.w(TAG, "Attempted to set orientation of non-existing app token: " + token);
+                Slog.w(TAG_WM, "Attempted to set orientation of non-existing app token: " + token);
                 return;
             }
 
@@ -3607,14 +3599,14 @@
         synchronized(mWindowMap) {
             final AppWindowToken newFocus;
             if (token == null) {
-                if (DEBUG_FOCUS_LIGHT) Slog.v(TAG, "Clearing focused app, was " + mFocusedApp);
+                if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "Clearing focused app, was " + mFocusedApp);
                 newFocus = null;
             } else {
                 newFocus = findAppWindowToken(token);
                 if (newFocus == null) {
-                    Slog.w(TAG, "Attempted to set focus to non-existing app token: " + token);
+                    Slog.w(TAG_WM, "Attempted to set focus to non-existing app token: " + token);
                 }
-                if (DEBUG_FOCUS_LIGHT) Slog.v(TAG, "Set focused app to: " + newFocus
+                if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "Set focused app to: " + newFocus
                         + " old focus=" + mFocusedApp + " moveFocusNow=" + moveFocusNow);
             }
 
@@ -3774,7 +3766,7 @@
         }
 
         synchronized(mWindowMap) {
-            if (DEBUG_APP_TRANSITIONS) Slog.w(TAG, "Execute app transition: " + mAppTransition
+            if (DEBUG_APP_TRANSITIONS) Slog.w(TAG_WM, "Execute app transition: " + mAppTransition
                     + " Callers=" + Debug.getCallers(5));
             if (mAppTransition.isTransitionSet()) {
                 mAppTransition.setReady();
@@ -3800,12 +3792,12 @@
 
         synchronized(mWindowMap) {
             if (DEBUG_STARTING_WINDOW) Slog.v(
-                    TAG, "setAppStartingWindow: token=" + token + " pkg=" + pkg
+                    TAG_WM, "setAppStartingWindow: token=" + token + " pkg=" + pkg
                     + " transferFrom=" + transferFrom);
 
             AppWindowToken wtoken = findAppWindowToken(token);
             if (wtoken == null) {
-                Slog.w(TAG, "Attempted to set icon of non-existing app token: " + token);
+                Slog.w(TAG_WM, "Attempted to set icon of non-existing app token: " + token);
                 return;
             }
 
@@ -3834,7 +3826,7 @@
             // show a starting window -- the current effect (a full-screen
             // opaque starting window that fades away to the real contents
             // when it is ready) does not work for this.
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Checking theme of starting window: 0x"
+            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Checking theme of starting window: 0x"
                     + Integer.toHexString(theme));
             if (theme != 0) {
                 AttributeCache.Entry ent = AttributeCache.instance().get(pkg, theme,
@@ -3852,7 +3844,7 @@
                         com.android.internal.R.styleable.Window_windowShowWallpaper, false);
                 final boolean windowDisableStarting = ent.array.getBoolean(
                         com.android.internal.R.styleable.Window_windowDisablePreview, false);
-                if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Translucent=" + windowIsTranslucent
+                if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Translucent=" + windowIsTranslucent
                         + " Floating=" + windowIsFloating
                         + " ShowWallpaper=" + windowShowWallpaper);
                 if (windowIsTranslucent) {
@@ -3875,14 +3867,14 @@
                 }
             }
 
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Creating StartingData");
+            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Creating StartingData");
             wtoken.startingData = new StartingData(pkg, theme, compatInfo, nonLocalizedLabel,
                     labelRes, icon, logo, windowFlags);
             Message m = mH.obtainMessage(H.ADD_STARTING, wtoken);
             // Note: we really want to do sendMessageAtFrontOfQueue() because we
             // want to process the message ASAP, before any other queued
             // messages.
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Enqueueing ADD_STARTING");
+            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Enqueueing ADD_STARTING");
             mH.sendMessageAtFrontOfQueue(m);
         }
     }
@@ -3901,7 +3893,7 @@
             // letting windows get shown immediately without any more transitions.
             mSkipAppTransitionAnimation = true;
 
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG,
+            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM,
                     "Moving existing starting " + startingWindow + " from " + ttoken
                             + " to " + wtoken);
             final long origId = Binder.clearCallingIdentity();
@@ -3922,11 +3914,11 @@
             startingWindow.mAppToken = wtoken;
 
             if (DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE || DEBUG_STARTING_WINDOW) {
-                Slog.v(TAG, "Removing starting window: " + startingWindow);
+                Slog.v(TAG_WM, "Removing starting window: " + startingWindow);
             }
             startingWindow.getWindowList().remove(startingWindow);
             mWindowsChanged = true;
-            if (DEBUG_ADD_REMOVE) Slog.v(TAG,
+            if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
                     "Removing starting " + startingWindow + " from " + ttoken);
             ttoken.windows.remove(startingWindow);
             ttoken.allAppWindows.remove(startingWindow);
@@ -3964,7 +3956,7 @@
         } else if (ttoken.startingData != null) {
             // The previous app was getting ready to show a
             // starting window, but hasn't yet done so.  Steal it!
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Moving pending starting from " + ttoken
+            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Moving pending starting from " + ttoken
                     + " to " + wtoken);
             wtoken.startingData = ttoken.startingData;
             ttoken.startingData = null;
@@ -4047,7 +4039,7 @@
                 (visible && wtoken.mWillReplaceWindow)) {
             boolean changed = false;
             if (DEBUG_APP_TRANSITIONS) Slog.v(
-                TAG, "Changing app " + wtoken + " hidden=" + wtoken.hidden
+                TAG_WM, "Changing app " + wtoken + " hidden=" + wtoken.hidden
                 + " performLayout=" + performLayout);
 
             boolean runningAppAnimation = false;
@@ -4075,7 +4067,7 @@
                     continue;
                 }
 
-                //Slog.i(TAG, "Window " + win + ": vis=" + win.isVisible());
+                //Slog.i(TAG_WM, "Window " + win + ": vis=" + win.isVisible());
                 //win.dump("  ");
                 if (visible) {
                     if (!win.isVisibleNow()) {
@@ -4121,7 +4113,7 @@
                  }
             }
 
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "setTokenVisibilityLocked: " + wtoken
+            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "setTokenVisibilityLocked: " + wtoken
                       + ": hidden=" + wtoken.hidden + " hiddenRequested="
                       + wtoken.hiddenRequested);
 
@@ -4170,11 +4162,11 @@
         synchronized(mWindowMap) {
             wtoken = findAppWindowToken(token);
             if (wtoken == null) {
-                Slog.w(TAG, "Attempted to set visibility of non-existing app token: " + token);
+                Slog.w(TAG_WM, "Attempted to set visibility of non-existing app token: " + token);
                 return;
             }
 
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ORIENTATION) Slog.v(TAG, "setAppVisibility(" +
+            if (DEBUG_APP_TRANSITIONS || DEBUG_ORIENTATION) Slog.v(TAG_WM, "setAppVisibility(" +
                     token + ", visible=" + visible + "): " + mAppTransition +
                     " hidden=" + wtoken.hidden + " hiddenRequested=" +
                     wtoken.hiddenRequested + " Callers=" + Debug.getCallers(6));
@@ -4202,7 +4194,7 @@
                 if (!wtoken.mAppAnimator.usingTransferredAnimation &&
                         (!wtoken.startingDisplayed || mSkipAppTransitionAnimation)) {
                     if (DEBUG_APP_TRANSITIONS) Slog.v(
-                            TAG, "Setting dummy animation on: " + wtoken);
+                            TAG_WM, "Setting dummy animation on: " + wtoken);
                     wtoken.mAppAnimator.setDummyAnimation();
                 }
                 wtoken.inPendingTransaction = true;
@@ -4241,7 +4233,7 @@
                     if (win != null) {
                         final AppWindowToken focusedToken = win.mAppToken;
                         if (focusedToken != null) {
-                            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG, "TRANSIT_TASK_OPEN_BEHIND, " +
+                            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG_WM, "TRANSIT_TASK_OPEN_BEHIND, " +
                                     " adding " + focusedToken + " to mOpeningApps");
                             // Force animation to be loaded.
                             focusedToken.hidden = true;
@@ -4264,7 +4256,7 @@
     void unsetAppFreezingScreenLocked(AppWindowToken wtoken,
             boolean unfreezeSurfaceNow, boolean force) {
         if (wtoken.mAppAnimator.freezingScreen) {
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Clear freezing of " + wtoken
+            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Clear freezing of " + wtoken
                     + " force=" + force);
             final int N = wtoken.allAppWindows.size();
             boolean unfrozeWindows = false;
@@ -4274,7 +4266,7 @@
                     w.mAppFreezing = false;
                     if (w.mHasSurface && !w.mOrientationChanging
                             && mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_TIMEOUT) {
-                        if (DEBUG_ORIENTATION) Slog.v(TAG, "set mOrientationChanging of " + w);
+                        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "set mOrientationChanging of " + w);
                         w.mOrientationChanging = true;
                         mWindowPlacerLocked.mOrientationChangeComplete = false;
                     }
@@ -4284,7 +4276,7 @@
                 }
             }
             if (force || unfrozeWindows) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG, "No longer freezing: " + wtoken);
+                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "No longer freezing: " + wtoken);
                 wtoken.mAppAnimator.freezingScreen = false;
                 wtoken.mAppAnimator.lastFreezeDuration = (int)(SystemClock.elapsedRealtime()
                         - mDisplayFreezeTime);
@@ -4307,7 +4299,7 @@
                 e = new RuntimeException();
                 e.fillInStackTrace();
             }
-            Slog.i(TAG, "Set freezing of " + wtoken.appToken
+            Slog.i(TAG_WM, "Set freezing of " + wtoken.appToken
                     + ": hidden=" + wtoken.hidden + " freezing="
                     + wtoken.mAppAnimator.freezingScreen, e);
         }
@@ -4339,13 +4331,13 @@
 
         synchronized(mWindowMap) {
             if (configChanges == 0 && okToDisplay()) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG, "Skipping set freeze of " + token);
+                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Skipping set freeze of " + token);
                 return;
             }
 
             AppWindowToken wtoken = findAppWindowToken(token);
             if (wtoken == null || wtoken.appToken == null) {
-                Slog.w(TAG, "Attempted to freeze screen with non-existing app token: " + wtoken);
+                Slog.w(TAG_WM, "Attempted to freeze screen with non-existing app token: " + wtoken);
                 return;
             }
             final long origId = Binder.clearCallingIdentity();
@@ -4367,7 +4359,7 @@
                 return;
             }
             final long origId = Binder.clearCallingIdentity();
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Clear freezing of " + token
+            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Clear freezing of " + token
                     + ": hidden=" + wtoken.hidden + " freezing=" + wtoken.mAppAnimator.freezingScreen);
             unsetAppFreezingScreenLocked(wtoken, true, force);
             Binder.restoreCallingIdentity(origId);
@@ -4389,7 +4381,7 @@
         synchronized(mWindowMap) {
             WindowToken basewtoken = mTokenMap.remove(token);
             if (basewtoken != null && (wtoken=basewtoken.appWindowToken) != null) {
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Removing app token: " + wtoken);
+                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "Removing app token: " + wtoken);
                 delayed = setTokenVisibilityLocked(wtoken, null, false,
                         AppTransition.TRANSIT_UNSET, true, wtoken.voiceInteraction);
                 wtoken.inPendingTransaction = false;
@@ -4402,15 +4394,15 @@
                     delayed = true;
                 }
                 if (DEBUG_APP_TRANSITIONS) Slog.v(
-                        TAG, "Removing app " + wtoken + " delayed=" + delayed
+                        TAG_WM, "Removing app " + wtoken + " delayed=" + delayed
                         + " animation=" + wtoken.mAppAnimator.animation
                         + " animating=" + wtoken.mAppAnimator.animating);
-                if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG, "removeAppToken: "
+                if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG_WM, "removeAppToken: "
                         + wtoken + " delayed=" + delayed + " Callers=" + Debug.getCallers(4));
                 final TaskStack stack = wtoken.mTask.mStack;
                 if (delayed && !wtoken.allAppWindows.isEmpty()) {
                     // set the token aside because it has an active animation to be finished
-                    if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG,
+                    if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG_WM,
                             "removeAppToken make exiting: " + wtoken);
                     stack.mExitingAppTokens.add(wtoken);
                     wtoken.mIsExiting = true;
@@ -4429,13 +4421,13 @@
                 }
                 unsetAppFreezingScreenLocked(wtoken, true, true);
                 if (mFocusedApp == wtoken) {
-                    if (DEBUG_FOCUS_LIGHT) Slog.v(TAG, "Removing focused app token:" + wtoken);
+                    if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "Removing focused app token:" + wtoken);
                     mFocusedApp = null;
                     updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, true /*updateInputWindows*/);
                     mInputMonitor.setFocusedAppLw(null);
                 }
             } else {
-                Slog.w(TAG, "Attempted to remove non-existing app token: " + token);
+                Slog.w(TAG_WM, "Attempted to remove non-existing app token: " + token);
             }
 
             if (!delayed && wtoken != null) {
@@ -4455,7 +4447,7 @@
             return;
         }
         if (wtoken != null && wtoken.startingWindow != null) {
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, Debug.getCallers(1) +
+            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, Debug.getCallers(1) +
                     ": Schedule remove starting " + wtoken + (wtoken != null ?
                     " startingWindow=" + wtoken.startingWindow : ""));
             Message m = mH.obtainMessage(H.REMOVE_STARTING, wtoken);
@@ -4467,16 +4459,16 @@
         final int numStacks = mStackIdToStack.size();
         for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
             final TaskStack stack = mStackIdToStack.valueAt(stackNdx);
-            Slog.v(TAG, "  Stack #" + stack.mStackId + " tasks from bottom to top:");
+            Slog.v(TAG_WM, "  Stack #" + stack.mStackId + " tasks from bottom to top:");
             final ArrayList<Task> tasks = stack.getTasks();
             final int numTasks = tasks.size();
             for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
                 final Task task = tasks.get(taskNdx);
-                Slog.v(TAG, "    Task #" + task.mTaskId + " activities from bottom to top:");
+                Slog.v(TAG_WM, "    Task #" + task.mTaskId + " activities from bottom to top:");
                 AppTokenList tokens = task.mAppTokens;
                 final int numTokens = tokens.size();
                 for (int tokenNdx = 0; tokenNdx < numTokens; ++tokenNdx) {
-                    Slog.v(TAG, "      activity #" + tokenNdx + ": " + tokens.get(tokenNdx).token);
+                    Slog.v(TAG_WM, "      activity #" + tokenNdx + ": " + tokens.get(tokenNdx).token);
                 }
             }
         }
@@ -4486,10 +4478,10 @@
         final int numDisplays = mDisplayContents.size();
         for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
             final DisplayContent displayContent = mDisplayContents.valueAt(displayNdx);
-            Slog.v(TAG, " Display #" + displayContent.getDisplayId());
+            Slog.v(TAG_WM, " Display #" + displayContent.getDisplayId());
             final WindowList windows = displayContent.getWindowList();
             for (int winNdx = windows.size() - 1; winNdx >= 0; --winNdx) {
-                Slog.v(TAG, "  #" + winNdx + ": " + windows.get(winNdx));
+                Slog.v(TAG_WM, "  #" + winNdx + ": " + windows.get(winNdx));
             }
         }
     }
@@ -4502,21 +4494,21 @@
         for (int j=0; j<NCW; j++) {
             WindowState cwin = win.mChildWindows.get(j);
             if (!winAdded && cwin.mSubLayer >= 0) {
-                if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Re-adding child window at "
+                if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Re-adding child window at "
                         + index + ": " + cwin);
                 win.mRebuilding = false;
                 windows.add(index, win);
                 index++;
                 winAdded = true;
             }
-            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Re-adding window at "
+            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Re-adding window at "
                     + index + ": " + cwin);
             cwin.mRebuilding = false;
             windows.add(index, cwin);
             index++;
         }
         if (!winAdded) {
-            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Re-adding window at "
+            if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Re-adding window at "
                     + index + ": " + win);
             win.mRebuilding = false;
             windows.add(index, win);
@@ -4623,7 +4615,7 @@
             synchronized(mWindowMap) {
                 Task task = mTaskIdToTask.get(taskId);
                 if (task == null) {
-                    Slog.e(TAG, "moveTaskToBottom: taskId=" + taskId
+                    Slog.e(TAG_WM, "moveTaskToBottom: taskId=" + taskId
                             + " not found in mTaskIdToTask");
                     return;
                 }
@@ -4667,7 +4659,7 @@
                 if (displayContent != null) {
                     TaskStack stack = mStackIdToStack.get(stackId);
                     if (stack == null) {
-                        if (DEBUG_STACK) Slog.d(TAG, "attachStack: stackId=" + stackId);
+                        if (DEBUG_STACK) Slog.d(TAG_WM, "attachStack: stackId=" + stackId);
                         stack = new TaskStack(this, stackId);
                         mStackIdToStack.put(stackId, stack);
                     }
@@ -4723,7 +4715,7 @@
         synchronized (mWindowMap) {
             Task task = mTaskIdToTask.get(taskId);
             if (task == null) {
-                if (DEBUG_STACK) Slog.i(TAG, "removeTask: could not find taskId=" + taskId);
+                if (DEBUG_STACK) Slog.i(TAG_WM, "removeTask: could not find taskId=" + taskId);
                 return;
             }
             task.removeLocked();
@@ -4752,11 +4744,11 @@
 
     public void addTask(int taskId, int stackId, boolean toTop) {
         synchronized (mWindowMap) {
-            if (DEBUG_STACK) Slog.i(TAG, "addTask: adding taskId=" + taskId
+            if (DEBUG_STACK) Slog.i(TAG_WM, "addTask: adding taskId=" + taskId
                     + " to " + (toTop ? "top" : "bottom"));
             Task task = mTaskIdToTask.get(taskId);
             if (task == null) {
-                if (DEBUG_STACK) Slog.i(TAG, "addTask: could not find taskId=" + taskId);
+                if (DEBUG_STACK) Slog.i(TAG_WM, "addTask: could not find taskId=" + taskId);
                 return;
             }
             TaskStack stack = mStackIdToStack.get(stackId);
@@ -4769,16 +4761,16 @@
 
     public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
         synchronized (mWindowMap) {
-            if (DEBUG_STACK) Slog.i(TAG, "moveTaskToStack: moving taskId=" + taskId
+            if (DEBUG_STACK) Slog.i(TAG_WM, "moveTaskToStack: moving taskId=" + taskId
                     + " to stackId=" + stackId + " at " + (toTop ? "top" : "bottom"));
             Task task = mTaskIdToTask.get(taskId);
             if (task == null) {
-                if (DEBUG_STACK) Slog.i(TAG, "moveTaskToStack: could not find taskId=" + taskId);
+                if (DEBUG_STACK) Slog.i(TAG_WM, "moveTaskToStack: could not find taskId=" + taskId);
                 return;
             }
             TaskStack stack = mStackIdToStack.get(stackId);
             if (stack == null) {
-                if (DEBUG_STACK) Slog.i(TAG, "moveTaskToStack: could not find stackId=" + stackId);
+                if (DEBUG_STACK) Slog.i(TAG_WM, "moveTaskToStack: could not find stackId=" + stackId);
                 return;
             }
             task.moveTaskToStack(stack, toTop);
@@ -4803,7 +4795,7 @@
         synchronized (mWindowMap) {
             Task task = mTaskIdToTask.get(taskId);
             if (task == null) {
-                if (DEBUG_STACK) Slog.i(TAG, "scheduleShowToast: could not find taskId=" + taskId);
+                if (DEBUG_STACK) Slog.i(TAG_WM, "scheduleShowToast: could not find taskId=" + taskId);
                 return;
             }
             task.setShowNonResizeableDockToast();
@@ -4849,17 +4841,17 @@
     public void positionTaskInStack(int taskId, int stackId, int position, Rect bounds,
             Configuration config) {
         synchronized (mWindowMap) {
-            if (DEBUG_STACK) Slog.i(TAG, "positionTaskInStack: positioning taskId=" + taskId
+            if (DEBUG_STACK) Slog.i(TAG_WM, "positionTaskInStack: positioning taskId=" + taskId
                     + " in stackId=" + stackId + " at " + position);
             Task task = mTaskIdToTask.get(taskId);
             if (task == null) {
-                if (DEBUG_STACK) Slog.i(TAG,
+                if (DEBUG_STACK) Slog.i(TAG_WM,
                         "positionTaskInStack: could not find taskId=" + taskId);
                 return;
             }
             TaskStack stack = mStackIdToStack.get(stackId);
             if (stack == null) {
-                if (DEBUG_STACK) Slog.i(TAG,
+                if (DEBUG_STACK) Slog.i(TAG_WM,
                         "positionTaskInStack: could not find stackId=" + stackId);
                 return;
             }
@@ -5000,7 +4992,7 @@
         // If this isn't coming from the system then don't allow disabling the lockscreen
         // to bypass security.
         if (Binder.getCallingUid() != Process.SYSTEM_UID && isKeyguardSecure()) {
-            Log.d(TAG, "current mode is SecurityMode, ignore hide keyguard");
+            Log.d(TAG_WM, "current mode is SecurityMode, ignore hide keyguard");
             return;
         }
 
@@ -5091,7 +5083,7 @@
                 != PackageManager.PERMISSION_GRANTED) {
             throw new SecurityException("Requires DISABLE_KEYGUARD permission");
         }
-        if (DEBUG_KEYGUARD) Slog.d(TAG, "keyguardGoingAway: disableWinAnim="
+        if (DEBUG_KEYGUARD) Slog.d(TAG_WM, "keyguardGoingAway: disableWinAnim="
                 + disableWindowAnimations + " kgToNotifShade=" + keyguardGoingToNotificationShade);
         synchronized (mWindowMap) {
             mAnimator.mKeyguardGoingAway = true;
@@ -5102,14 +5094,14 @@
     }
 
     public void keyguardWaitingForActivityDrawn() {
-        if (DEBUG_KEYGUARD) Slog.d(TAG, "keyguardWaitingForActivityDrawn");
+        if (DEBUG_KEYGUARD) Slog.d(TAG_WM, "keyguardWaitingForActivityDrawn");
         synchronized (mWindowMap) {
             mKeyguardWaitingForActivityDrawn = true;
         }
     }
 
     public void notifyActivityDrawnForKeyguard() {
-        if (DEBUG_KEYGUARD) Slog.d(TAG, "notifyActivityDrawnForKeyguard: waiting="
+        if (DEBUG_KEYGUARD) Slog.d(TAG_WM, "notifyActivityDrawnForKeyguard: waiting="
                 + mKeyguardWaitingForActivityDrawn + " Callers=" + Debug.getCallers(5));
         synchronized (mWindowMap) {
             if (mKeyguardWaitingForActivityDrawn) {
@@ -5260,6 +5252,12 @@
 
     // Called by window manager policy. Not exposed externally.
     @Override
+    public void lockDeviceNow() {
+        lockNow(null);
+    }
+
+    // Called by window manager policy. Not exposed externally.
+    @Override
     public int getCameraLensCoverState() {
         int sw = mInputManager.getSwitchState(-1, InputDevice.SOURCE_ANY,
                 InputManagerService.SW_CAMERA_LENS_COVER);
@@ -5331,7 +5329,7 @@
             if (DEBUG_BOOT) {
                 RuntimeException here = new RuntimeException("here");
                 here.fillInStackTrace();
-                Slog.i(TAG, "enableScreenAfterBoot: mDisplayEnabled=" + mDisplayEnabled
+                Slog.i(TAG_WM, "enableScreenAfterBoot: mDisplayEnabled=" + mDisplayEnabled
                         + " mForceDisplayEnabled=" + mForceDisplayEnabled
                         + " mShowingBootMessages=" + mShowingBootMessages
                         + " mSystemBooted=" + mSystemBooted, here);
@@ -5362,7 +5360,7 @@
         if (DEBUG_BOOT) {
             RuntimeException here = new RuntimeException("here");
             here.fillInStackTrace();
-            Slog.i(TAG, "enableScreenIfNeededLocked: mDisplayEnabled=" + mDisplayEnabled
+            Slog.i(TAG_WM, "enableScreenIfNeededLocked: mDisplayEnabled=" + mDisplayEnabled
                     + " mForceDisplayEnabled=" + mForceDisplayEnabled
                     + " mShowingBootMessages=" + mShowingBootMessages
                     + " mSystemBooted=" + mSystemBooted, here);
@@ -5381,7 +5379,7 @@
             if (mDisplayEnabled) {
                 return;
             }
-            Slog.w(TAG, "***** BOOT TIMEOUT: forcing display enabled");
+            Slog.w(TAG_WM, "***** BOOT TIMEOUT: forcing display enabled");
             mForceDisplayEnabled = true;
         }
         performEnableScreen();
@@ -5420,7 +5418,7 @@
         }
 
         if (DEBUG_SCREEN_ON || DEBUG_BOOT) {
-            Slog.i(TAG, "******** booted=" + mSystemBooted + " msg=" + mShowingBootMessages
+            Slog.i(TAG_WM, "******** booted=" + mSystemBooted + " msg=" + mShowingBootMessages
                     + " haveBoot=" + haveBootMsg + " haveApp=" + haveApp
                     + " haveWall=" + haveWallpaper + " wallEnabled=" + wallpaperEnabled
                     + " haveKeyguard=" + haveKeyguard);
@@ -5445,7 +5443,7 @@
 
     public void performEnableScreen() {
         synchronized(mWindowMap) {
-            if (DEBUG_BOOT) Slog.i(TAG, "performEnableScreen: mDisplayEnabled=" + mDisplayEnabled
+            if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: mDisplayEnabled=" + mDisplayEnabled
                     + " mForceDisplayEnabled=" + mForceDisplayEnabled
                     + " mShowingBootMessages=" + mShowingBootMessages
                     + " mSystemBooted=" + mSystemBooted
@@ -5469,7 +5467,7 @@
                 try {
                     IBinder surfaceFlinger = ServiceManager.getService("SurfaceFlinger");
                     if (surfaceFlinger != null) {
-                        //Slog.i(TAG, "******* TELLING SURFACE FLINGER WE ARE BOOTED!");
+                        //Slog.i(TAG_WM, "******* TELLING SURFACE FLINGER WE ARE BOOTED!");
                         Parcel data = Parcel.obtain();
                         data.writeInterfaceToken("android.ui.ISurfaceComposer");
                         surfaceFlinger.transact(IBinder.FIRST_CALL_TRANSACTION, // BOOT_FINISHED
@@ -5477,20 +5475,20 @@
                         data.recycle();
                     }
                 } catch (RemoteException ex) {
-                    Slog.e(TAG, "Boot completed: SurfaceFlinger is dead!");
+                    Slog.e(TAG_WM, "Boot completed: SurfaceFlinger is dead!");
                 }
                 mBootAnimationStopped = true;
             }
 
             if (!mForceDisplayEnabled && !checkBootAnimationCompleteLocked()) {
-                if (DEBUG_BOOT) Slog.i(TAG, "performEnableScreen: Waiting for anim complete");
+                if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: Waiting for anim complete");
                 return;
             }
 
             EventLog.writeEvent(EventLogTags.WM_BOOT_ANIMATION_DONE, SystemClock.uptimeMillis());
             Trace.asyncTraceEnd(Trace.TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0);
             mDisplayEnabled = true;
-            if (DEBUG_SCREEN_ON || DEBUG_BOOT) Slog.i(TAG, "******************** ENABLING SCREEN!");
+            if (DEBUG_SCREEN_ON || DEBUG_BOOT) Slog.i(TAG_WM, "******************** ENABLING SCREEN!");
 
             // Enable input dispatch.
             mInputMonitor.setEventDispatchingLw(mEventDispatchingEnabled);
@@ -5512,10 +5510,10 @@
             mH.removeMessages(H.CHECK_IF_BOOT_ANIMATION_FINISHED);
             mH.sendEmptyMessageDelayed(H.CHECK_IF_BOOT_ANIMATION_FINISHED,
                     BOOT_ANIMATION_POLL_INTERVAL);
-            if (DEBUG_BOOT) Slog.i(TAG, "checkBootAnimationComplete: Waiting for anim complete");
+            if (DEBUG_BOOT) Slog.i(TAG_WM, "checkBootAnimationComplete: Waiting for anim complete");
             return false;
         }
-        if (DEBUG_BOOT) Slog.i(TAG, "checkBootAnimationComplete: Animation complete!");
+        if (DEBUG_BOOT) Slog.i(TAG_WM, "checkBootAnimationComplete: Animation complete!");
         return true;
     }
 
@@ -5525,7 +5523,7 @@
             if (DEBUG_BOOT) {
                 RuntimeException here = new RuntimeException("here");
                 here.fillInStackTrace();
-                Slog.i(TAG, "showBootMessage: msg=" + msg + " always=" + always
+                Slog.i(TAG_WM, "showBootMessage: msg=" + msg + " always=" + always
                         + " mAllowBootMessages=" + mAllowBootMessages
                         + " mShowingBootMessages=" + mShowingBootMessages
                         + " mSystemBooted=" + mSystemBooted, here);
@@ -5554,7 +5552,7 @@
         if (DEBUG_BOOT) {
             RuntimeException here = new RuntimeException("here");
             here.fillInStackTrace();
-            Slog.i(TAG, "hideBootMessagesLocked: mDisplayEnabled=" + mDisplayEnabled
+            Slog.i(TAG_WM, "hideBootMessagesLocked: mDisplayEnabled=" + mDisplayEnabled
                     + " mForceDisplayEnabled=" + mForceDisplayEnabled
                     + " mShowingBootMessages=" + mShowingBootMessages
                     + " mSystemBooted=" + mSystemBooted, here);
@@ -5605,7 +5603,7 @@
     public void showCircularMask(boolean visible) {
         synchronized(mWindowMap) {
 
-            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                     ">>> OPEN TRANSACTION showCircularMask(visible=" + visible + ")");
             SurfaceControl.openTransaction();
             try {
@@ -5631,7 +5629,7 @@
                 }
             } finally {
                 SurfaceControl.closeTransaction();
-                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
+                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                         "<<< CLOSE TRANSACTION showCircularMask(visible=" + visible + ")");
             }
         }
@@ -5640,7 +5638,7 @@
     public void showEmulatorDisplayOverlay() {
         synchronized(mWindowMap) {
 
-            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                     ">>> OPEN TRANSACTION showEmulatorDisplayOverlay");
             SurfaceControl.openTransaction();
             try {
@@ -5656,7 +5654,7 @@
                 mEmulatorDisplayOverlay.setVisibility(true);
             } finally {
                 SurfaceControl.closeTransaction();
-                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
+                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                         "<<< CLOSE TRANSACTION showEmulatorDisplayOverlay");
             }
         }
@@ -5695,7 +5693,7 @@
                 }
             }
 
-            if (SHOW_VERBOSE_TRANSACTIONS) Slog.i(TAG,
+            if (SHOW_VERBOSE_TRANSACTIONS) Slog.i(TAG_WM,
                     ">>> OPEN TRANSACTION showStrictModeViolation");
             SurfaceControl.openTransaction();
             try {
@@ -5707,7 +5705,7 @@
                 mStrictModeFlash.setVisibility(on);
             } finally {
                 SurfaceControl.closeTransaction();
-                if (SHOW_VERBOSE_TRANSACTIONS) Slog.i(TAG,
+                if (SHOW_VERBOSE_TRANSACTIONS) Slog.i(TAG_WM,
                         "<<< CLOSE TRANSACTION showStrictModeViolation");
             }
         }
@@ -5794,7 +5792,7 @@
         synchronized(mWindowMap) {
             displayContent = getDisplayContentLocked(displayId);
             if (displayContent == null) {
-                if (DEBUG_SCREENSHOT) Slog.i(TAG, "Screenshot of " + appToken
+                if (DEBUG_SCREENSHOT) Slog.i(TAG_WM, "Screenshot of " + appToken
                         + ": returning null. No Display for displayId=" + displayId);
                 return null;
             }
@@ -5803,7 +5801,7 @@
         int dw = displayInfo.logicalWidth;
         int dh = displayInfo.logicalHeight;
         if (dw == 0 || dh == 0) {
-            if (DEBUG_SCREENSHOT) Slog.i(TAG, "Screenshot of " + appToken
+            if (DEBUG_SCREENSHOT) Slog.i(TAG_WM, "Screenshot of " + appToken
                     + ": returning null. logical widthxheight=" + dw + "x" + dh);
             return null;
         }
@@ -5925,21 +5923,21 @@
 
                 if (appToken != null && appWin == null) {
                     // Can't find a window to snapshot.
-                    if (DEBUG_SCREENSHOT) Slog.i(TAG,
+                    if (DEBUG_SCREENSHOT) Slog.i(TAG_WM,
                             "Screenshot: Couldn't find a surface matching " + appToken);
                     return null;
                 }
 
                 if (!screenshotReady) {
                     if (retryCount > MAX_SCREENSHOT_RETRIES) {
-                        Slog.i(TAG, "Screenshot max retries " + retryCount + " of " + appToken +
+                        Slog.i(TAG_WM, "Screenshot max retries " + retryCount + " of " + appToken +
                                 " appWin=" + (appWin == null ? "null" : (appWin + " drawState=" +
                                 appWin.mWinAnimator.mDrawState)));
                         return null;
                     }
 
                     // Delay and hope that window gets drawn.
-                    if (DEBUG_SCREENSHOT) Slog.i(TAG, "Screenshot: No image ready for " + appToken
+                    if (DEBUG_SCREENSHOT) Slog.i(TAG_WM, "Screenshot: No image ready for " + appToken
                             + ", " + appWin + " drawState=" + appWin.mWinAnimator.mDrawState);
                     continue;
                 }
@@ -5950,7 +5948,7 @@
                 // taken.
 
                 if (maxLayer == 0) {
-                    if (DEBUG_SCREENSHOT) Slog.i(TAG, "Screenshot of " + appToken
+                    if (DEBUG_SCREENSHOT) Slog.i(TAG_WM, "Screenshot of " + appToken
                             + ": returning null maxLayer=" + maxLayer);
                     return null;
                 }
@@ -5998,11 +5996,11 @@
                 convertCropForSurfaceFlinger(crop, rot, dw, dh);
 
                 if (DEBUG_SCREENSHOT) {
-                    Slog.i(TAG, "Screenshot: " + dw + "x" + dh + " from " + minLayer + " to "
+                    Slog.i(TAG_WM, "Screenshot: " + dw + "x" + dh + " from " + minLayer + " to "
                             + maxLayer + " appToken=" + appToken);
                     for (int i = 0; i < windows.size(); i++) {
                         WindowState win = windows.get(i);
-                        Slog.i(TAG, win + ": " + win.mLayer
+                        Slog.i(TAG_WM, win + ": " + win.mLayer
                                 + " animLayer=" + win.mWinAnimator.mAnimLayer
                                 + " surfaceLayer=" + win.mWinAnimator.mSurfaceController.getLayer());
                     }
@@ -6012,13 +6010,13 @@
                         mAnimator.getScreenRotationAnimationLocked(Display.DEFAULT_DISPLAY);
                 final boolean inRotation = screenRotationAnimation != null &&
                         screenRotationAnimation.isAnimating();
-                if (DEBUG_SCREENSHOT && inRotation) Slog.v(TAG,
+                if (DEBUG_SCREENSHOT && inRotation) Slog.v(TAG_WM,
                         "Taking screenshot while rotating");
 
                 bm = SurfaceControl.screenshot(crop, width, height, minLayer, maxLayer,
                         inRotation, rot);
                 if (bm == null) {
-                    Slog.w(TAG, "Screenshot failure taking screenshot for (" + dw + "x" + dh
+                    Slog.w(TAG_WM, "Screenshot failure taking screenshot for (" + dw + "x" + dh
                             + ") to layer " + maxLayer);
                     return null;
                 }
@@ -6040,7 +6038,7 @@
                 }
             }
             if (allBlack) {
-                Slog.i(TAG, "Screenshot " + appWin + " was monochrome(" +
+                Slog.i(TAG_WM, "Screenshot " + appWin + " was monochrome(" +
                         Integer.toHexString(firstColor) + ")! mSurfaceLayer=" +
                         (appWin != null ?
                                 appWin.mWinAnimator.mSurfaceController.getLayer() : "null") +
@@ -6072,7 +6070,7 @@
                     + "rotation constant.");
         }
 
-        if (DEBUG_ORIENTATION) Slog.v(TAG, "freezeRotation: mRotation=" + mRotation);
+        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "freezeRotation: mRotation=" + mRotation);
 
         long origId = Binder.clearCallingIdentity();
         try {
@@ -6096,7 +6094,7 @@
             throw new SecurityException("Requires SET_ORIENTATION permission");
         }
 
-        if (DEBUG_ORIENTATION) Slog.v(TAG, "thawRotation: mRotation=" + mRotation);
+        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "thawRotation: mRotation=" + mRotation);
 
         long origId = Binder.clearCallingIdentity();
         try {
@@ -6150,7 +6148,7 @@
     }
 
     public void updateRotationUnchecked(boolean alwaysSendConfiguration, boolean forceRelayout) {
-        if(DEBUG_ORIENTATION) Slog.v(TAG, "updateRotationUnchecked("
+        if(DEBUG_ORIENTATION) Slog.v(TAG_WM, "updateRotationUnchecked("
                    + "alwaysSendConfiguration=" + alwaysSendConfiguration + ")");
 
         long origId = Binder.clearCallingIdentity();
@@ -6181,7 +6179,7 @@
         if (mDeferredRotationPauseCount > 0) {
             // Rotation updates have been paused temporarily.  Defer the update until
             // updates have been resumed.
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Deferring rotation, rotation is paused.");
+            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Deferring rotation, rotation is paused.");
             return false;
         }
 
@@ -6191,13 +6189,13 @@
             // Rotation updates cannot be performed while the previous rotation change
             // animation is still in progress.  Skip this update.  We will try updating
             // again after the animation is finished and the display is unfrozen.
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Deferring rotation, animation in progress.");
+            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Deferring rotation, animation in progress.");
             return false;
         }
 
         if (!mDisplayEnabled) {
             // No point choosing a rotation if the display is not enabled.
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Deferring rotation, display is not enabled.");
+            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Deferring rotation, display is not enabled.");
             return false;
         }
 
@@ -6211,7 +6209,7 @@
                 mForcedAppOrientation, rotation);
 
         if (DEBUG_ORIENTATION) {
-            Slog.v(TAG, "Application requested orientation "
+            Slog.v(TAG_WM, "Application requested orientation "
                     + mForcedAppOrientation + ", got rotation " + rotation
                     + " which has " + (altOrientation ? "incompatible" : "compatible")
                     + " metrics");
@@ -6223,7 +6221,7 @@
         }
 
         if (DEBUG_ORIENTATION) {
-            Slog.v(TAG,
+            Slog.v(TAG_WM,
                 "Rotation changed to " + rotation + (altOrientation ? " (alt)" : "")
                 + " from " + mRotation + (mAltOrientation ? " (alt)" : "")
                 + ", forceApp=" + mForcedAppOrientation);
@@ -6260,7 +6258,7 @@
         final DisplayInfo displayInfo = displayContent.getDisplayInfo();
         if (!inTransaction) {
             if (SHOW_TRANSACTIONS) {
-                Slog.i(TAG, ">>> OPEN TRANSACTION setRotationUnchecked");
+                Slog.i(TAG_WM, ">>> OPEN TRANSACTION setRotationUnchecked");
             }
             SurfaceControl.openTransaction();
         }
@@ -6282,7 +6280,7 @@
             if (!inTransaction) {
                 SurfaceControl.closeTransaction();
                 if (SHOW_LIGHT_TRANSACTIONS) {
-                    Slog.i(TAG, "<<< CLOSE TRANSACTION setRotationUnchecked");
+                    Slog.i(TAG_WM, "<<< CLOSE TRANSACTION setRotationUnchecked");
                 }
             }
         }
@@ -6295,7 +6293,7 @@
                 w.mAppToken.destroySavedSurfaces();
             }
             if (w.mHasSurface) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG, "Set mOrientationChanging of " + w);
+                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Set mOrientationChanging of " + w);
                 w.mOrientationChanging = true;
                 mWindowPlacerLocked.mOrientationChangeComplete = false;
             }
@@ -6465,7 +6463,7 @@
                 try {
                     return mViewServer.start();
                 } catch (IOException e) {
-                    Slog.w(TAG, "View server did not start");
+                    Slog.w(TAG_WM, "View server did not start");
                 }
             }
             return false;
@@ -6475,7 +6473,7 @@
             mViewServer = new ViewServer(this, port);
             return mViewServer.start();
         } catch (IOException e) {
-            Slog.w(TAG, "View server did not start");
+            Slog.w(TAG_WM, "View server did not start");
         }
         return false;
     }
@@ -6709,7 +6707,7 @@
             }
 
         } catch (Exception e) {
-            Slog.w(TAG, "Could not send command " + command + " with parameters " + parameters, e);
+            Slog.w(TAG_WM, "Could not send command " + command + " with parameters " + parameters, e);
             success = false;
         } finally {
             if (data != null) {
@@ -6980,7 +6978,7 @@
 
         displayContent.mBaseDisplayRect.set(0, 0, dw, dh);
         if (false) {
-            Slog.i(TAG, "Set app display size: " + appWidth + " x " + appHeight);
+            Slog.i(TAG_WM, "Set app display size: " + appWidth + " x " + appHeight);
         }
 
         mCompatibleScreenScale = CompatibilityInfo.computeCompatibleScaling(mDisplayMetrics,
@@ -7123,7 +7121,7 @@
     }
 
     private void startScrollingTask(DisplayContent displayContent, int startX, int startY) {
-        if (DEBUG_TASK_POSITIONING) Slog.d(TAG,
+        if (DEBUG_TASK_POSITIONING) Slog.d(TAG_WM,
                 "startScrollingTask: " + "{" + startX + ", " + startY + "}");
 
         Task task = null;
@@ -7158,22 +7156,22 @@
 
     private boolean startPositioningLocked(
             WindowState win, boolean resize, float startX, float startY) {
-        if (DEBUG_TASK_POSITIONING) Slog.d(TAG, "startPositioningLocked: "
+        if (DEBUG_TASK_POSITIONING) Slog.d(TAG_WM, "startPositioningLocked: "
             + "win=" + win + ", resize=" + resize + ", {" + startX + ", " + startY + "}");
 
         if (win == null || win.getAppToken() == null) {
-            Slog.w(TAG, "startPositioningLocked: Bad window " + win);
+            Slog.w(TAG_WM, "startPositioningLocked: Bad window " + win);
             return false;
         }
         if (win.mInputChannel == null) {
-            Slog.wtf(TAG, "startPositioningLocked: " + win + " has no input channel, "
+            Slog.wtf(TAG_WM, "startPositioningLocked: " + win + " has no input channel, "
                     + " probably being removed");
             return false;
         }
 
         final DisplayContent displayContent = win.getDisplayContent();
         if (displayContent == null) {
-            Slog.w(TAG, "startPositioningLocked: Invalid display content " + win);
+            Slog.w(TAG_WM, "startPositioningLocked: Invalid display content " + win);
             return false;
         }
 
@@ -7183,7 +7181,7 @@
         mInputMonitor.updateInputWindowsLw(true /*force*/);
         if (!mInputManager.transferTouchFocus(
                 win.mInputChannel, mTaskPositioner.mServerChannel)) {
-            Slog.e(TAG, "startPositioningLocked: Unable to transfer touch focus");
+            Slog.e(TAG_WM, "startPositioningLocked: Unable to transfer touch focus");
             mTaskPositioner.unregister();
             mTaskPositioner = null;
             mInputMonitor.updateInputWindowsLw(true /*force*/);
@@ -7196,7 +7194,7 @@
 
     private void finishPositioning() {
         if (DEBUG_TASK_POSITIONING) {
-            Slog.d(TAG, "finishPositioning");
+            Slog.d(TAG_WM, "finishPositioning");
         }
         synchronized (mWindowMap) {
             if (mTaskPositioner != null) {
@@ -7214,7 +7212,7 @@
     IBinder prepareDragSurface(IWindow window, SurfaceSession session,
             int flags, int width, int height, Surface outSurface) {
         if (DEBUG_DRAG) {
-            Slog.d(TAG, "prepare drag surface: w=" + width + " h=" + height
+            Slog.d(TAG_WM, "prepare drag surface: w=" + width + " h=" + height
                     + " flags=" + Integer.toHexString(flags) + " win=" + window
                     + " asbinder=" + window.asBinder());
         }
@@ -7241,7 +7239,7 @@
                         }
                         surface.setAlpha(alpha);
 
-                        if (SHOW_TRANSACTIONS) Slog.i(TAG, "  DRAG "
+                        if (SHOW_TRANSACTIONS) Slog.i(TAG_WM, "  DRAG "
                                 + surface + ": CREATE");
                         outSurface.copyFrom(surface);
                         final IBinder winBinder = window.asBinder();
@@ -7257,10 +7255,10 @@
                         Message msg = mH.obtainMessage(H.DRAG_START_TIMEOUT, winBinder);
                         mH.sendMessageDelayed(msg, 5000);
                     } else {
-                        Slog.w(TAG, "Drag already in progress");
+                        Slog.w(TAG_WM, "Drag already in progress");
                     }
                 } catch (OutOfResourcesException e) {
-                    Slog.e(TAG, "Can't allocate drag surface w=" + width + " h=" + height, e);
+                    Slog.e(TAG_WM, "Can't allocate drag surface w=" + width + " h=" + height, e);
                     if (mDragState != null) {
                         mDragState.reset();
                         mDragState = null;
@@ -7339,7 +7337,7 @@
     public boolean detectSafeMode() {
         if (!mInputMonitor.waitForInputDevicesReady(
                 INPUT_DEVICES_READY_FOR_SAFE_MODE_DETECTION_TIMEOUT_MILLIS)) {
-            Slog.w(TAG, "Devices still not ready after waiting "
+            Slog.w(TAG_WM, "Devices still not ready after waiting "
                    + INPUT_DEVICES_READY_FOR_SAFE_MODE_DETECTION_TIMEOUT_MILLIS
                    + " milliseconds before attempting to detect safe mode.");
         }
@@ -7363,10 +7361,10 @@
         } catch (IllegalArgumentException e) {
         }
         if (mSafeMode) {
-            Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
+            Log.i(TAG_WM, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
                     + " dpad=" + dpadState + " trackball=" + trackballState + ")");
         } else {
-            Log.i(TAG, "SAFE MODE not enabled");
+            Log.i(TAG_WM, "SAFE MODE not enabled");
         }
         mPolicy.setSafeMode(mSafeMode);
         return mSafeMode;
@@ -7487,7 +7485,7 @@
         @Override
         public void handleMessage(Message msg) {
             if (DEBUG_WINDOW_TRACE) {
-                Slog.v(TAG, "handleMessage: entry what=" + msg.what);
+                Slog.v(TAG_WM, "handleMessage: entry what=" + msg.what);
             }
             switch (msg.what) {
                 case REPORT_FOCUS_CHANGE: {
@@ -7510,11 +7508,11 @@
                             return;
                         }
                         mLastFocus = newFocus;
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG, "Focus moving from " + lastFocus +
+                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Focus moving from " + lastFocus +
                                 " to " + newFocus);
                         if (newFocus != null && lastFocus != null
                                 && !newFocus.isDisplayedLw()) {
-                            //Slog.i(TAG, "Delaying loss of focus...");
+                            //Slog.i(TAG_WM, "Delaying loss of focus...");
                             mLosingFocus.add(lastFocus);
                             lastFocus = null;
                         }
@@ -7529,13 +7527,13 @@
                     //System.out.println("Changing focus from " + lastFocus
                     //                   + " to " + newFocus);
                     if (newFocus != null) {
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG, "Gaining focus: " + newFocus);
+                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Gaining focus: " + newFocus);
                         newFocus.reportFocusChangedSerialized(true, mInTouchMode);
                         notifyFocusChanged();
                     }
 
                     if (lastFocus != null) {
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG, "Losing focus: " + lastFocus);
+                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Losing focus: " + lastFocus);
                         lastFocus.reportFocusChangedSerialized(false, mInTouchMode);
                     }
                 } break;
@@ -7550,7 +7548,7 @@
 
                     final int N = losers.size();
                     for (int i=0; i<N; i++) {
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG, "Losing delayed focus: " +
+                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Losing delayed focus: " +
                                 losers.get(i));
                         losers.get(i).reportFocusChangedSerialized(false, mInTouchMode);
                     }
@@ -7571,7 +7569,7 @@
                         return;
                     }
 
-                    if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Add starting "
+                    if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Add starting "
                             + wtoken + ": pkg=" + sd.pkg);
 
                     View view = null;
@@ -7580,7 +7578,7 @@
                             wtoken.token, sd.pkg, sd.theme, sd.compatInfo,
                             sd.nonLocalizedLabel, sd.labelRes, sd.icon, sd.logo, sd.windowFlags);
                     } catch (Exception e) {
-                        Slog.w(TAG, "Exception when adding starting window", e);
+                        Slog.w(TAG_WM, "Exception when adding starting window", e);
                     }
 
                     if (view != null) {
@@ -7591,7 +7589,7 @@
                                 // If the window was successfully added, then
                                 // we need to remove it.
                                 if (wtoken.startingWindow != null) {
-                                    if (DEBUG_STARTING_WINDOW) Slog.v(TAG,
+                                    if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM,
                                             "Aborted starting " + wtoken
                                             + ": removed=" + wtoken.removed
                                             + " startingData=" + wtoken.startingData);
@@ -7602,7 +7600,7 @@
                             } else {
                                 wtoken.startingView = view;
                             }
-                            if (DEBUG_STARTING_WINDOW && !abort) Slog.v(TAG,
+                            if (DEBUG_STARTING_WINDOW && !abort) Slog.v(TAG_WM,
                                     "Added starting " + wtoken
                                     + ": startingWindow="
                                     + wtoken.startingWindow + " startingView="
@@ -7613,7 +7611,7 @@
                             try {
                                 mPolicy.removeStartingWindow(wtoken.token, view);
                             } catch (Exception e) {
-                                Slog.w(TAG, "Exception when removing starting window", e);
+                                Slog.w(TAG_WM, "Exception when removing starting window", e);
                             }
                         }
                     }
@@ -7624,7 +7622,7 @@
                     IBinder token = null;
                     View view = null;
                     synchronized (mWindowMap) {
-                        if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Remove starting "
+                        if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Remove starting "
                                 + wtoken + ": startingWindow="
                                 + wtoken.startingWindow + " startingView="
                                 + wtoken.startingView);
@@ -7641,7 +7639,7 @@
                         try {
                             mPolicy.removeStartingWindow(token, view);
                         } catch (Exception e) {
-                            Slog.w(TAG, "Exception when removing starting window", e);
+                            Slog.w(TAG_WM, "Exception when removing starting window", e);
                         }
                     }
                 } break;
@@ -7657,7 +7655,7 @@
                             }
                             AppWindowToken wtoken = mFinishedStarting.remove(N-1);
 
-                            if (DEBUG_STARTING_WINDOW) Slog.v(TAG,
+                            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM,
                                     "Finished starting " + wtoken
                                     + ": startingWindow=" + wtoken.startingWindow
                                     + " startingView=" + wtoken.startingView);
@@ -7677,7 +7675,7 @@
                         try {
                             mPolicy.removeStartingWindow(token, view);
                         } catch (Exception e) {
-                            Slog.w(TAG, "Exception when removing starting window", e);
+                            Slog.w(TAG_WM, "Exception when removing starting window", e);
                         }
                     }
                 } break;
@@ -7687,7 +7685,7 @@
 
                     try {
                         if (DEBUG_VISIBILITY) Slog.v(
-                                TAG, "Reporting drawn in " + wtoken);
+                                TAG_WM, "Reporting drawn in " + wtoken);
                         wtoken.appToken.windowsDrawn();
                     } catch (RemoteException ex) {
                     }
@@ -7701,7 +7699,7 @@
 
                     try {
                         if (DEBUG_VISIBILITY) Slog.v(
-                                TAG, "Reporting visible in " + wtoken
+                                TAG_WM, "Reporting visible in " + wtoken
                                 + " visible=" + nowVisible
                                 + " gone=" + nowGone);
                         if (nowVisible) {
@@ -7716,7 +7714,7 @@
                 case WINDOW_FREEZE_TIMEOUT: {
                     // TODO(multidisplay): Can non-default displays rotate?
                     synchronized (mWindowMap) {
-                        Slog.w(TAG, "Window freeze timeout expired.");
+                        Slog.w(TAG_WM, "Window freeze timeout expired.");
                         mWindowsFreezingScreen = WINDOWS_FREEZING_SCREENS_TIMEOUT;
                         final WindowList windows = getDefaultWindowListLocked();
                         int i = windows.size();
@@ -7727,7 +7725,7 @@
                                 w.mOrientationChanging = false;
                                 w.mLastFreezeDuration = (int)(SystemClock.elapsedRealtime()
                                         - mDisplayFreezeTime);
-                                Slog.w(TAG, "Force clearing orientation change: " + w);
+                                Slog.w(TAG_WM, "Force clearing orientation change: " + w);
                             }
                         }
                         mWindowPlacerLocked.performSurfacePlacement();
@@ -7739,7 +7737,7 @@
                     synchronized (mWindowMap) {
                         if (mAppTransition.isTransitionSet() || !mOpeningApps.isEmpty()
                                     || !mClosingApps.isEmpty()) {
-                            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "*** APP TRANSITION TIMEOUT."
+                            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "*** APP TRANSITION TIMEOUT."
                                     + " isTransitionSet()=" + mAppTransition.isTransitionSet()
                                     + " mOpeningApps.size()=" + mOpeningApps.size()
                                     + " mClosingApps.size()=" + mClosingApps.size());
@@ -7788,7 +7786,7 @@
 
                 case APP_FREEZE_TIMEOUT: {
                     synchronized (mWindowMap) {
-                        Slog.w(TAG, "App freeze timeout expired.");
+                        Slog.w(TAG_WM, "App freeze timeout expired.");
                         mWindowsFreezingScreen = WINDOWS_FREEZING_SCREENS_TIMEOUT;
                         final int numStacks = mStackIdToStack.size();
                         for (int stackNdx = 0; stackNdx < numStacks; ++stackNdx) {
@@ -7799,7 +7797,7 @@
                                 for (int tokenNdx = tokens.size() - 1; tokenNdx >= 0; --tokenNdx) {
                                     AppWindowToken tok = tokens.get(tokenNdx);
                                     if (tok.mAppAnimator.freezingScreen) {
-                                        Slog.w(TAG, "Force clearing freeze: " + tok);
+                                        Slog.w(TAG_WM, "Force clearing freeze: " + tok);
                                         unsetAppFreezingScreenLocked(tok, true, true);
                                     }
                                 }
@@ -7839,7 +7837,7 @@
                 case DRAG_START_TIMEOUT: {
                     IBinder win = (IBinder)msg.obj;
                     if (DEBUG_DRAG) {
-                        Slog.w(TAG, "Timeout starting drag by win " + win);
+                        Slog.w(TAG_WM, "Timeout starting drag by win " + win);
                     }
                     synchronized (mWindowMap) {
                         // !!! TODO: ANR the app that has failed to start the drag in time
@@ -7856,7 +7854,7 @@
                 case DRAG_END_TIMEOUT: {
                     IBinder win = (IBinder)msg.obj;
                     if (DEBUG_DRAG) {
-                        Slog.w(TAG, "Timeout ending drag to win " + win);
+                        Slog.w(TAG_WM, "Timeout ending drag to win " + win);
                     }
                     synchronized (mWindowMap) {
                         // !!! TODO: ANR the drag-receiving app
@@ -7881,7 +7879,7 @@
                 case WAITING_FOR_DRAWN_TIMEOUT: {
                     Runnable callback = null;
                     synchronized (mWindowMap) {
-                        Slog.w(TAG, "Timeout waiting for drawn: undrawn=" + mWaitingForDrawn);
+                        Slog.w(TAG_WM, "Timeout waiting for drawn: undrawn=" + mWaitingForDrawn);
                         mWaitingForDrawn.clear();
                         callback = mWaitingForDrawnCallback;
                         mWaitingForDrawnCallback = null;
@@ -8006,7 +8004,7 @@
                 case CHECK_IF_BOOT_ANIMATION_FINISHED: {
                     final boolean bootAnimationComplete;
                     synchronized (mWindowMap) {
-                        if (DEBUG_BOOT) Slog.i(TAG, "CHECK_IF_BOOT_ANIMATION_FINISHED:");
+                        if (DEBUG_BOOT) Slog.i(TAG_WM, "CHECK_IF_BOOT_ANIMATION_FINISHED:");
                         bootAnimationComplete = checkBootAnimationCompleteLocked();
                     }
                     if (bootAnimationComplete) {
@@ -8063,7 +8061,7 @@
                 break;
             }
             if (DEBUG_WINDOW_TRACE) {
-                Slog.v(TAG, "handleMessage: exit");
+                Slog.v(TAG_WM, "handleMessage: exit");
             }
         }
     }
@@ -8098,9 +8096,9 @@
                 // TODO(multidisplay): IMEs are only supported on the default display.
                 WindowState imFocus = getDefaultWindowListLocked().get(idx-1);
                 if (DEBUG_INPUT_METHOD) {
-                    Slog.i(TAG, "Desired input method target: " + imFocus);
-                    Slog.i(TAG, "Current focus: " + mCurrentFocus);
-                    Slog.i(TAG, "Last focus: " + mLastFocus);
+                    Slog.i(TAG_WM, "Desired input method target: " + imFocus);
+                    Slog.i(TAG_WM, "Current focus: " + mCurrentFocus);
+                    Slog.i(TAG_WM, "Last focus: " + mLastFocus);
                 }
                 if (imFocus != null) {
                     // This may be a starting window, in which case we still want
@@ -8112,18 +8110,18 @@
                         for (int i=0; i<imFocus.mAppToken.windows.size(); i++) {
                             WindowState w = imFocus.mAppToken.windows.get(i);
                             if (w != imFocus) {
-                                Log.i(TAG, "Switching to real app window: " + w);
+                                Log.i(TAG_WM, "Switching to real app window: " + w);
                                 imFocus = w;
                                 break;
                             }
                         }
                     }
                     if (DEBUG_INPUT_METHOD) {
-                        Slog.i(TAG, "IM target client: " + imFocus.mSession.mClient);
+                        Slog.i(TAG_WM, "IM target client: " + imFocus.mSession.mClient);
                         if (imFocus.mSession.mClient != null) {
-                            Slog.i(TAG, "IM target client binder: "
+                            Slog.i(TAG_WM, "IM target client binder: "
                                     + imFocus.mSession.mClient.asBinder());
-                            Slog.i(TAG, "Requesting client binder: " + client.asBinder());
+                            Slog.i(TAG_WM, "Requesting client binder: " + client.asBinder());
                         }
                     }
                     if (imFocus.mSession.mClient != null &&
@@ -8236,7 +8234,7 @@
     }
 
     private void setForcedDisplayScalingModeLocked(DisplayContent displayContent, int mode) {
-        Slog.i(TAG, "Using display scaling mode: " + (mode == 0 ? "auto" : "off"));
+        Slog.i(TAG_WM, "Using display scaling mode: " + (mode == 0 ? "auto" : "off"));
         displayContent.mDisplayScalingDisabled = (mode != 0);
         reconfigureDisplayLocked(displayContent);
     }
@@ -8257,7 +8255,7 @@
                     height = Integer.parseInt(sizeStr.substring(pos+1));
                     if (displayContent.mBaseDisplayWidth != width
                             || displayContent.mBaseDisplayHeight != height) {
-                        Slog.i(TAG, "FORCED DISPLAY SIZE: " + width + "x" + height);
+                        Slog.i(TAG_WM, "FORCED DISPLAY SIZE: " + width + "x" + height);
                         displayContent.mBaseDisplayWidth = width;
                         displayContent.mBaseDisplayHeight = height;
                     }
@@ -8277,7 +8275,7 @@
             try {
                 density = Integer.parseInt(densityStr);
                 if (displayContent.mBaseDisplayDensity != density) {
-                    Slog.i(TAG, "FORCED DISPLAY DENSITY: " + density);
+                    Slog.i(TAG_WM, "FORCED DISPLAY DENSITY: " + density);
                     displayContent.mBaseDisplayDensity = density;
                 }
             } catch (NumberFormatException ex) {
@@ -8288,14 +8286,14 @@
         int mode = Settings.Global.getInt(mContext.getContentResolver(),
                 Settings.Global.DISPLAY_SCALING_FORCE, 0);
         if (mode != 0) {
-            Slog.i(TAG, "FORCED DISPLAY SCALING DISABLED");
+            Slog.i(TAG_WM, "FORCED DISPLAY SCALING DISABLED");
             displayContent.mDisplayScalingDisabled = true;
         }
     }
 
     // displayContent must not be null
     private void setForcedDisplaySizeLocked(DisplayContent displayContent, int width, int height) {
-        Slog.i(TAG, "Using new display size: " + width + "x" + height);
+        Slog.i(TAG_WM, "Using new display size: " + width + "x" + height);
         displayContent.mBaseDisplayWidth = width;
         displayContent.mBaseDisplayHeight = height;
         reconfigureDisplayLocked(displayContent);
@@ -8378,7 +8376,7 @@
 
     // displayContent must not be null
     private void setForcedDisplayDensityLocked(DisplayContent displayContent, int density) {
-        Slog.i(TAG, "Using new display density: " + density);
+        Slog.i(TAG_WM, "Using new display density: " + density);
         displayContent.mBaseDisplayDensity = density;
         reconfigureDisplayLocked(displayContent);
     }
@@ -8495,14 +8493,14 @@
             boolean throwOnError) {
         WindowState win = mWindowMap.get(client);
         if (localLOGV) Slog.v(
-            TAG, "Looking up client " + client + ": " + win);
+            TAG_WM, "Looking up client " + client + ": " + win);
         if (win == null) {
             RuntimeException ex = new IllegalArgumentException(
                     "Requested window " + client + " does not exist");
             if (throwOnError) {
                 throw ex;
             }
-            Slog.w(TAG, "Failed looking up window", ex);
+            Slog.w(TAG_WM, "Failed looking up window", ex);
             return null;
         }
         if (session != null && win.mSession != session) {
@@ -8512,7 +8510,7 @@
             if (throwOnError) {
                 throw ex;
             }
-            Slog.w(TAG, "Failed looking up window", ex);
+            Slog.w(TAG_WM, "Failed looking up window", ex);
             return null;
         }
 
@@ -8543,7 +8541,7 @@
                 win.mRebuilding = true;
                 mRebuildTmp[numRemoved] = win;
                 mWindowsChanged = true;
-                if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG, "Rebuild removing window: " + win);
+                if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Rebuild removing window: " + win);
                 NW--;
                 numRemoved++;
                 continue;
@@ -8594,7 +8592,7 @@
         i -= lastBelow;
         if (i != numRemoved) {
             displayContent.layoutNeeded = true;
-            Slog.w(TAG, "On display=" + displayContent.getDisplayId() + " Rebuild removed " +
+            Slog.w(TAG_WM, "On display=" + displayContent.getDisplayId() + " Rebuild removed " +
                     numRemoved + " windows but added " + i,
                     new RuntimeException("here").fillInStackTrace());
             for (i=0; i<numRemoved; i++) {
@@ -8604,14 +8602,14 @@
                     PrintWriter pw = new FastPrintWriter(sw, false, 1024);
                     ws.dump(pw, "", true);
                     pw.flush();
-                    Slog.w(TAG, "This window was lost: " + ws);
-                    Slog.w(TAG, sw.toString());
+                    Slog.w(TAG_WM, "This window was lost: " + ws);
+                    Slog.w(TAG_WM, sw.toString());
                     ws.mWinAnimator.destroySurfaceLocked();
                 }
             }
-            Slog.w(TAG, "Current app token list:");
+            Slog.w(TAG_WM, "Current app token list:");
             dumpAppTokensLocked();
-            Slog.w(TAG, "Final window list:");
+            Slog.w(TAG_WM, "Final window list:");
             dumpWindowsLocked();
         }
         Arrays.fill(mRebuildTmp, null);
@@ -8623,7 +8621,7 @@
         int curLayer = 0;
         int i;
 
-        if (DEBUG_LAYERS) Slog.v(TAG, "Assigning layers based on windows=" + windows,
+        if (DEBUG_LAYERS) Slog.v(TAG_WM, "Assigning layers based on windows=" + windows,
                 new RuntimeException("here").fillInStackTrace());
 
         boolean anyLayerChanged = false;
@@ -8672,7 +8670,7 @@
                 // Force an animation pass just to update the mDimLayer layer.
                 scheduleAnimationLocked();
             }
-            if (DEBUG_LAYERS) Slog.v(TAG, "Assign layer " + w + ": "
+            if (DEBUG_LAYERS) Slog.v(TAG_WM, "Assign layer " + w + ": "
                     + "mBase=" + w.mBaseLayer
                     + " mLayer=" + w.mLayer
                     + (wtoken == null ?
@@ -8701,8 +8699,8 @@
         }
         if (!force) {
             final TaskStack stack = w.getStack();
-            if (stack != null && StackId.isAlwaysOnTop(stack.mStackId)) {
-                // If the window's stack is always on top, we want to make it above other windows
+            if (stack != null && (StackId.shouldIncreaseApplicationWindowLayer(stack.mStackId))) {
+                // For pinned and docked stack window, we want to make them above other windows
                 // also when these windows are animating.
                 force = true;
             }
@@ -8718,7 +8716,7 @@
         // it frozen/off until this window draws at its new
         // orientation.
         if (!okToDisplay() && mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_TIMEOUT) {
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Changing surface while display frozen: " + w);
+            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Changing surface while display frozen: " + w);
             w.mOrientationChanging = true;
             w.mLastFreezeDuration = 0;
             mWindowPlacerLocked.mOrientationChangeComplete = false;
@@ -8763,7 +8761,7 @@
         rebuildAppWindowListLocked();
 
         changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_LAYOUT;
-        if (DEBUG_WALLPAPER_LIGHT) Slog.v(TAG,
+        if (DEBUG_WALLPAPER_LIGHT) Slog.v(TAG_WM,
                 "Wallpaper layer changed: assigning layers + relayout");
         moveInputMethodWindowsIfNeededLocked(true);
         mWindowPlacerLocked.mWallpaperMayChange = true;
@@ -8781,11 +8779,11 @@
             w.setInsetsChanged();
             boolean configChanged = w.isConfigChanged();
             if (DEBUG_CONFIGURATION && configChanged) {
-                Slog.v(TAG, "Win " + w + " config changed: "
+                Slog.v(TAG_WM, "Win " + w + " config changed: "
                         + mCurConfiguration);
             }
             final boolean dragResizingChanged = w.isDragResizeChanged();
-            if (localLOGV) Slog.v(TAG, "Resizing " + w
+            if (localLOGV) Slog.v(TAG_WM, "Resizing " + w
                     + ": configChanged=" + configChanged
                     + " dragResizingChanged=" + dragResizingChanged
                     + " last=" + w.mLastFrame + " frame=" + w.mFrame);
@@ -8797,7 +8795,7 @@
                     || configChanged
                     || dragResizingChanged) {
                 if (DEBUG_RESIZE || DEBUG_ORIENTATION) {
-                    Slog.v(TAG, "Resize reasons for w=" + w + ": "
+                    Slog.v(TAG_WM, "Resize reasons for w=" + w + ": "
                             + " contentInsetsChanged=" + w.mContentInsetsChanged
                             + " " + w.mContentInsets.toShortString()
                             + " visibleInsetsChanged=" + w.mVisibleInsetsChanged
@@ -8831,7 +8829,7 @@
                 // application when it has finished drawing.
                 if (w.mOrientationChanging || dragResizingChanged) {
                     if (DEBUG_SURFACE_TRACE || DEBUG_ANIM || DEBUG_ORIENTATION || DEBUG_RESIZE) {
-                        Slog.v(TAG, "Orientation or resize start waiting for draw"
+                        Slog.v(TAG_WM, "Orientation or resize start waiting for draw"
                                 + ", mDrawState=DRAW_PENDING in " + w
                                 + ", surfaceController " + winAnimator.mSurfaceController);
                     }
@@ -8842,13 +8840,13 @@
                     }
                 }
                 if (!mResizingWindows.contains(w)) {
-                    if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG,
+                    if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG_WM,
                             "Resizing window " + w);
                     mResizingWindows.add(w);
                 }
             } else if (w.mOrientationChanging) {
                 if (w.isDrawnLw()) {
-                    if (DEBUG_ORIENTATION) Slog.v(TAG,
+                    if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
                             "Orientation not waiting for draw in "
                             + w + ", surfaceController " + winAnimator.mSurfaceController);
                     w.mOrientationChanging = false;
@@ -8865,22 +8863,22 @@
         }
         for (int j = mWaitingForDrawn.size() - 1; j >= 0; j--) {
             WindowState win = mWaitingForDrawn.get(j);
-            if (DEBUG_SCREEN_ON) Slog.i(TAG, "Waiting for drawn " + win +
+            if (DEBUG_SCREEN_ON) Slog.i(TAG_WM, "Waiting for drawn " + win +
                     ": removed=" + win.mRemoved + " visible=" + win.isVisibleLw() +
                     " mHasSurface=" + win.mHasSurface +
                     " drawState=" + win.mWinAnimator.mDrawState);
             if (win.mRemoved || !win.mHasSurface || !win.mPolicyVisibility) {
                 // Window has been removed or hidden; no draw will now happen, so stop waiting.
-                if (DEBUG_SCREEN_ON) Slog.w(TAG, "Aborted waiting for drawn: " + win);
+                if (DEBUG_SCREEN_ON) Slog.w(TAG_WM, "Aborted waiting for drawn: " + win);
                 mWaitingForDrawn.remove(win);
             } else if (win.hasDrawnLw()) {
                 // Window is now drawn (and shown).
-                if (DEBUG_SCREEN_ON) Slog.d(TAG, "Window drawn win=" + win);
+                if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "Window drawn win=" + win);
                 mWaitingForDrawn.remove(win);
             }
         }
         if (mWaitingForDrawn.isEmpty()) {
-            if (DEBUG_SCREEN_ON) Slog.d(TAG, "All windows drawn!");
+            if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "All windows drawn!");
             mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT);
             mH.sendEmptyMessage(H.ALL_WINDOWS_DRAWN);
         }
@@ -8960,7 +8958,7 @@
             // window list to make sure we haven't left any dangling surfaces
             // around.
 
-            Slog.i(TAG, "Out of memory for surface!  Looking for leaks...");
+            Slog.i(TAG_WM, "Out of memory for surface!  Looking for leaks...");
             final int numDisplays = mDisplayContents.size();
             for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
                 final WindowList windows = mDisplayContents.valueAt(displayNdx).getWindowList();
@@ -8970,7 +8968,7 @@
                     WindowStateAnimator wsa = ws.mWinAnimator;
                     if (wsa.mSurfaceController != null) {
                         if (!mSessions.contains(wsa.mSession)) {
-                            Slog.w(TAG, "LEAKED SURFACE (session doesn't exist): "
+                            Slog.w(TAG_WM, "LEAKED SURFACE (session doesn't exist): "
                                     + ws + " surface=" + wsa.mSurfaceController
                                     + " token=" + ws.mToken
                                     + " pid=" + ws.mSession.mPid
@@ -8980,7 +8978,7 @@
                             mForceRemoves.add(ws);
                             leakedSurface = true;
                         } else if (ws.mAppToken != null && ws.mAppToken.clientHidden) {
-                            Slog.w(TAG, "LEAKED SURFACE (app token hidden): "
+                            Slog.w(TAG_WM, "LEAKED SURFACE (app token hidden): "
                                     + ws + " surface=" + wsa.mSurfaceController
                                     + " token=" + ws.mAppToken
                                     + " saved=" + ws.mAppToken.hasSavedSurface());
@@ -8994,7 +8992,7 @@
             }
 
             if (!leakedSurface) {
-                Slog.w(TAG, "No leaked surfaces; killing applicatons!");
+                Slog.w(TAG_WM, "No leaked surfaces; killing applicatons!");
                 SparseIntArray pidCandidates = new SparseIntArray();
                 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
                     final WindowList windows = mDisplayContents.valueAt(displayNdx).getWindowList();
@@ -9027,7 +9025,7 @@
             if (leakedSurface || killedApps) {
                 // We managed to reclaim some memory, so get rid of the trouble
                 // surface and ask the app to request another one.
-                Slog.w(TAG, "Looks like we have reclaimed some memory, clearing surface for retry.");
+                Slog.w(TAG_WM, "Looks like we have reclaimed some memory, clearing surface for retry.");
                 if (surfaceController != null) {
                     if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) logSurface(winAnimator.mWin,
                             "RECOVER DESTROY", null);
@@ -9066,7 +9064,7 @@
                 newFocus = computeFocusedWindowLocked();
             }
 
-            if (DEBUG_FOCUS_LIGHT || localLOGV) Slog.v(TAG, "Changing focus from " +
+            if (DEBUG_FOCUS_LIGHT || localLOGV) Slog.v(TAG_WM, "Changing focus from " +
                     mCurrentFocus + " to " + newFocus + " Callers=" + Debug.getCallers(4));
             final WindowState oldFocus = mCurrentFocus;
             mCurrentFocus = newFocus;
@@ -9126,7 +9124,7 @@
             final WindowState win = windows.get(i);
 
             if (localLOGV || DEBUG_FOCUS) Slog.v(
-                TAG, "Looking for focus: " + i
+                TAG_WM, "Looking for focus: " + i
                 + " = " + win
                 + ", flags=" + win.mAttrs.flags
                 + ", canReceive=" + win.canReceiveKeys());
@@ -9139,7 +9137,7 @@
 
             // If this window's application has been removed, just skip it.
             if (wtoken != null && (wtoken.removed || wtoken.sendingToBottom)) {
-                if (DEBUG_FOCUS) Slog.v(TAG, "Skipping " + wtoken + " because "
+                if (DEBUG_FOCUS) Slog.v(TAG_WM, "Skipping " + wtoken + " because "
                         + (wtoken.removed ? "removed" : "sendingToBottom"));
                 continue;
             }
@@ -9160,7 +9158,7 @@
                         if (mFocusedApp == token && token.stackCanReceiveKeys()) {
                             // Whoops, we are below the focused app whose stack can receive keys...
                             // No focus for you!!!
-                            if (localLOGV || DEBUG_FOCUS_LIGHT) Slog.v(TAG,
+                            if (localLOGV || DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM,
                                     "findFocusedWindow: Reached focused app=" + mFocusedApp);
                             return null;
                         }
@@ -9172,12 +9170,12 @@
                 }
             }
 
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG, "findFocusedWindow: Found new focus @ " + i +
+            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "findFocusedWindow: Found new focus @ " + i +
                         " = " + win);
             return win;
         }
 
-        if (DEBUG_FOCUS_LIGHT) Slog.v(TAG, "findFocusedWindow: No focusable windows.");
+        if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "findFocusedWindow: No focusable windows.");
         return null;
     }
 
@@ -9253,7 +9251,7 @@
         if (mWaitingForConfig || mAppsFreezingScreen > 0
                 || mWindowsFreezingScreen == WINDOWS_FREEZING_SCREENS_ACTIVE
                 || mClientFreezingScreen || !mOpeningApps.isEmpty()) {
-            if (DEBUG_ORIENTATION) Slog.d(TAG,
+            if (DEBUG_ORIENTATION) Slog.d(TAG_WM,
                 "stopFreezingDisplayLocked: Returning mWaitingForConfig=" + mWaitingForConfig
                 + ", mAppsFreezingScreen=" + mAppsFreezingScreen
                 + ", mWindowsFreezingScreen=" + mWindowsFreezingScreen
@@ -9271,7 +9269,7 @@
             sb.append(" due to ");
             sb.append(mLastFinishedFreezeSource);
         }
-        Slog.i(TAG, sb.toString());
+        Slog.i(TAG_WM, sb.toString());
         mH.removeMessages(H.APP_FREEZE_TIMEOUT);
         mH.removeMessages(H.CLIENT_FREEZE_TIMEOUT);
         if (PROFILE_ORIENTATION) {
@@ -9286,7 +9284,7 @@
                 mAnimator.getScreenRotationAnimationLocked(displayId);
         if (CUSTOM_SCREEN_ROTATION && screenRotationAnimation != null
                 && screenRotationAnimation.hasScreenshot()) {
-            if (DEBUG_ORIENTATION) Slog.i(TAG, "**** Dismissing screen rotation animation");
+            if (DEBUG_ORIENTATION) Slog.i(TAG_WM, "**** Dismissing screen rotation animation");
             // TODO(multidisplay): rotation on main screen only.
             DisplayInfo displayInfo = displayContent.getDisplayInfo();
             // Get rotation animation again, with new top window
@@ -9332,7 +9330,7 @@
         mScreenFrozenLock.release();
 
         if (updateRotation) {
-            if (DEBUG_ORIENTATION) Slog.d(TAG, "Performing post-rotate rotation");
+            if (DEBUG_ORIENTATION) Slog.d(TAG_WM, "Performing post-rotate rotation");
             configChanged |= updateRotationUncheckedLocked(false);
         }
 
@@ -10071,7 +10069,7 @@
     private DisplayContent newDisplayContentLocked(final Display display) {
         DisplayContent displayContent = new DisplayContent(display, this);
         final int displayId = display.getDisplayId();
-        if (DEBUG_DISPLAY) Slog.v(TAG, "Adding display=" + display);
+        if (DEBUG_DISPLAY) Slog.v(TAG_WM, "Adding display=" + display);
         mDisplayContents.put(displayId, displayContent);
 
         DisplayInfo displayInfo = displayContent.getDisplayInfo();
@@ -10175,7 +10173,7 @@
                 displayContent.mDeferredRemoval = true;
                 return;
             }
-            if (DEBUG_DISPLAY) Slog.v(TAG, "Removing display=" + displayContent);
+            if (DEBUG_DISPLAY) Slog.v(TAG_WM, "Removing display=" + displayContent);
             mDisplayContents.delete(displayId);
             displayContent.close();
             if (displayId == Display.DEFAULT_DISPLAY) {
@@ -10212,10 +10210,10 @@
         synchronized (mWindowMap) {
             AppWindowToken appWindowToken = findAppWindowToken(token);
             if (appWindowToken == null || !appWindowToken.isVisible()) {
-                Slog.w(TAG, "Attempted to set replacing window on non-existing app token " + token);
+                Slog.w(TAG_WM, "Attempted to set replacing window on non-existing app token " + token);
                 return;
             }
-            if (DEBUG_ADD_REMOVE) Slog.d(TAG, "Marking app token " + appWindowToken
+            if (DEBUG_ADD_REMOVE) Slog.d(TAG_WM, "Marking app token " + appWindowToken
                     + " as replacing window.");
             appWindowToken.mWillReplaceWindow = true;
             appWindowToken.mHasReplacedWindow = false;
@@ -10225,7 +10223,7 @@
                 // Set-up dummy animation so we can start treating windows associated with this
                 // token like they are in transition before the new app window is ready for us to
                 // run the real transition animation.
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                         "setReplacingWindow() Setting dummy animation on: " + appWindowToken);
                 appWindowToken.mAppAnimator.setDummyAnimation();
             }
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index c9ded3a..0fc7142 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -83,16 +83,18 @@
 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
 import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
-import static com.android.server.wm.WindowManagerService.DEBUG_ADD_REMOVE;
-import static com.android.server.wm.WindowManagerService.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerService.DEBUG_APP_TRANSITIONS;
-import static com.android.server.wm.WindowManagerService.DEBUG_CONFIGURATION;
-import static com.android.server.wm.WindowManagerService.DEBUG_FOCUS_LIGHT;
-import static com.android.server.wm.WindowManagerService.DEBUG_LAYOUT;
-import static com.android.server.wm.WindowManagerService.DEBUG_ORIENTATION;
-import static com.android.server.wm.WindowManagerService.DEBUG_POWER;
-import static com.android.server.wm.WindowManagerService.DEBUG_RESIZE;
-import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_POWER;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RESIZE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 class WindowList extends ArrayList<WindowState> {
 }
@@ -101,7 +103,7 @@
  * A window in the window manager.
  */
 final class WindowState implements WindowManagerPolicy.WindowState {
-    static final String TAG = "WindowState";
+    static final String TAG = TAG_WITH_CLASS_NAME ? "WindowState" : TAG_WM;
 
     // The minimal size of a window within the usable area of the freeform stack.
     // TODO(multi-window): fix the min sizes when we have mininum width/height support,
@@ -257,13 +259,6 @@
      */
     int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
 
-    /**
-     * This is rectangle of the window's surface that is not covered by
-     * system decorations.
-     */
-    final Rect mSystemDecorRect = new Rect();
-    final Rect mLastSystemDecorRect = new Rect();
-
     // Current transformation being applied.
     float mGlobalScale=1;
     float mInvGlobalScale=1;
@@ -479,8 +474,7 @@
                     + WindowManagerService.TYPE_LAYER_OFFSET;
             mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
             mAttachedWindow = attachedWindow;
-            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to "
-                    + mAttachedWindow);
+            if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to " + mAttachedWindow);
 
             final WindowList childWindows = mAttachedWindow.mChildWindows;
             final int numChildWindows = childWindows.size();
@@ -626,7 +620,7 @@
         final int ph = mContainingFrame.height();
 
         if (!mParentFrame.equals(pf)) {
-            //Slog.i(TAG, "Window " + this + " content frame from " + mParentFrame
+            //Slog.i(TAG_WM, "Window " + this + " content frame from " + mParentFrame
             //        + " to " + pf);
             mParentFrame.set(pf);
             mContentChanged = true;
@@ -1242,7 +1236,7 @@
         disposeInputChannel();
 
         if (mAttachedWindow != null) {
-            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + this + " from " + mAttachedWindow);
+            if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + this + " from " + mAttachedWindow);
             mAttachedWindow.mChildWindows.remove(this);
         }
         mWinAnimator.destroyDeferredSurfaceLocked();
@@ -1700,9 +1694,7 @@
     }
 
     public void destroySavedSurface() {
-        if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                "Destroying saved surface: " + this);
-
+        if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG, "Destroying saved surface: " + this);
         if (mSurfaceSaved) {
             mWinAnimator.destroySurfaceLocked();
         }
@@ -2086,13 +2078,6 @@
             pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
                     pw.print(" last="); mLastFrame.printShortString(pw);
                     pw.println();
-            pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
-                    pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
-                    if (mWinAnimator.mHasClipRect) {
-                        pw.print(" mLastClipRect=");
-                        mWinAnimator.mLastClipRect.printShortString(pw);
-                    }
-                    pw.println();
         }
         if (mEnforceSizeCompat) {
             pw.print(prefix); pw.print("mCompatFrame="); mCompatFrame.printShortString(pw);
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 1790fb3..7cd67d0 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -20,15 +20,21 @@
 import static android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
 import static android.view.WindowManager.LayoutParams.FLAG_SCALED;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
-import static com.android.server.wm.WindowManagerService.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerService.DEBUG_LAYERS;
-import static com.android.server.wm.WindowManagerService.DEBUG_ORIENTATION;
-import static com.android.server.wm.WindowManagerService.DEBUG_STARTING_WINDOW;
-import static com.android.server.wm.WindowManagerService.DEBUG_SURFACE_TRACE;
-import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
-import static com.android.server.wm.WindowManagerService.SHOW_LIGHT_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerService.SHOW_SURFACE_ALLOC;
-import static com.android.server.wm.WindowManagerService.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYERS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_CROP;
+import static com.android.server.wm.WindowManagerDebugConfig.HIDE_STACK_CRAWLS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.TYPE_LAYER_MULTIPLIER;
 import static com.android.server.wm.WindowManagerService.localLOGV;
 import static com.android.server.wm.WindowState.DRAG_RESIZE_MODE_FREEFORM;
@@ -64,7 +70,7 @@
  * Keep track of animations and surface operations for a single WindowState.
  **/
 class WindowStateAnimator {
-    static final String TAG = "WindowStateAnimator";
+    static final String TAG = TAG_WITH_CLASS_NAME ? "WindowStateAnimator" : TAG_WM;
     static final int WINDOW_FREEZE_LAYER = TYPE_LAYER_MULTIPLIER * 200;
 
     // Unchanging local convenience fields.
@@ -123,6 +129,13 @@
     Rect mLastClipRect = new Rect();
     Rect mTmpStackBounds = new Rect();
 
+    /**
+     * This is rectangle of the window's surface that is not covered by
+     * system decorations.
+     */
+    private final Rect mSystemDecorRect = new Rect();
+    private final Rect mLastSystemDecorRect = new Rect();
+
     // Used to save animation distances between the time they are calculated and when they are used.
     private int mAnimDx;
     private int mAnimDy;
@@ -402,7 +415,7 @@
         finishExit();
         final int displayId = mWin.getDisplayId();
         mAnimator.setPendingLayoutChanges(displayId, WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM);
-        if (WindowManagerService.DEBUG_LAYOUT_REPEATS)
+        if (DEBUG_LAYOUT_REPEATS)
             mService.mWindowPlacerLocked.debugLayoutRepeats(
                     "WindowStateAnimator", mAnimator.getPendingLayoutChanges(displayId));
 
@@ -414,7 +427,7 @@
     }
 
     void finishExit() {
-        if (WindowManagerService.DEBUG_ANIM) Slog.v(
+        if (DEBUG_ANIM) Slog.v(
                 TAG, "finishExit in " + this
                 + ": exiting=" + mWin.mExiting
                 + " remove=" + mWin.mRemoveOnExit
@@ -594,7 +607,7 @@
             }
 
             // We may abort, so initialize to defaults.
-            w.mLastSystemDecorRect.set(0, 0, 0, 0);
+            mLastSystemDecorRect.set(0, 0, 0, 0);
             mHasClipRect = false;
             mClipRect.set(0, 0, 0, 0);
             mLastClipRect.set(0, 0, 0, 0);
@@ -660,7 +673,7 @@
 
             // Start a new transaction and apply position & offset.
             final int layerStack = w.getDisplayContent().getDisplay().getLayerStack();
-            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
+            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
                     "POS " + mTmpSize.left + ", " + mTmpSize.top, null);
             mSurfaceController.setPositionAndLayer(mTmpSize.left, mTmpSize.top, layerStack,
                     mAnimLayer);
@@ -750,7 +763,7 @@
             try {
                 if (DEBUG_VISIBILITY) {
                     RuntimeException e = null;
-                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
+                    if (!HIDE_STACK_CRAWLS) {
                         e = new RuntimeException();
                         e.fillInStackTrace();
                     }
@@ -762,7 +775,7 @@
                         if (mPendingDestroySurface != null) {
                             if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
                                 RuntimeException e = null;
-                                if (!WindowManagerService.HIDE_STACK_CRAWLS) {
+                                if (!HIDE_STACK_CRAWLS) {
                                     e = new RuntimeException();
                                     e.fillInStackTrace();
                                 }
@@ -775,7 +788,7 @@
                 } else {
                     if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
                         RuntimeException e = null;
-                        if (!WindowManagerService.HIDE_STACK_CRAWLS) {
+                        if (!HIDE_STACK_CRAWLS) {
                             e = new RuntimeException();
                             e.fillInStackTrace();
                         }
@@ -811,7 +824,7 @@
             if (mPendingDestroySurface != null) {
                 if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
                     RuntimeException e = null;
-                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
+                    if (!HIDE_STACK_CRAWLS) {
                         e = new RuntimeException();
                         e.fillInStackTrace();
                     }
@@ -850,7 +863,7 @@
                     wallpaperAnimator.mAnimation != null &&
                     !wallpaperAnimator.mAnimation.getDetachWallpaper()) {
                 attachedTransformation = wallpaperAnimator.mTransformation;
-                if (WindowManagerService.DEBUG_WALLPAPER && attachedTransformation != null) {
+                if (DEBUG_WALLPAPER && attachedTransformation != null) {
                     Slog.v(TAG, "WP target attached xform: " + attachedTransformation);
                 }
             }
@@ -860,7 +873,7 @@
                     && wpAppAnimator.animation != null
                     && !wpAppAnimator.animation.getDetachWallpaper()) {
                 appTransformation = wpAppAnimator.transformation;
-                if (WindowManagerService.DEBUG_WALLPAPER && appTransformation != null) {
+                if (DEBUG_WALLPAPER && appTransformation != null) {
                     Slog.v(TAG, "WP target app xform: " + appTransformation);
                 }
             }
@@ -931,7 +944,7 @@
             // (a 2x2 matrix + an offset)
             // Here we must not transform the position of the surface
             // since it is already included in the transformation.
-            //Slog.i(TAG, "Transform: " + matrix);
+            //Slog.i(TAG_WM, "Transform: " + matrix);
 
             mHaveMatrix = true;
             tmpMatrix.getValues(tmpFloats);
@@ -953,7 +966,7 @@
                     || (!PixelFormat.formatHasAlpha(mWin.mAttrs.format)
                     || (mWin.isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy)
                             && x == frame.left && y == frame.top))) {
-                //Slog.i(TAG, "Applying alpha transform");
+                //Slog.i(TAG_WM, "Applying alpha transform");
                 if (selfTransformation) {
                     mShownAlpha *= mTransformation.getAlpha();
                 }
@@ -971,7 +984,7 @@
                     mShownAlpha *= screenRotationAnimation.getEnterTransformation().getAlpha();
                 }
             } else {
-                //Slog.i(TAG, "Not applying alpha transform");
+                //Slog.i(TAG_WM, "Not applying alpha transform");
             }
 
             if ((DEBUG_SURFACE_TRACE || WindowManagerService.localLOGV)
@@ -1043,8 +1056,9 @@
         }
     }
 
-    private void applyDecorRect(final Rect decorRect) {
+    private void calculateSystemDecorRect() {
         final WindowState w = mWin;
+        final Rect decorRect = w.mDecorFrame;
         final int width = w.mFrame.width();
         final int height = w.mFrame.height();
 
@@ -1053,11 +1067,17 @@
         final int top = w.mYOffset + w.mFrame.top;
 
         // Initialize the decor rect to the entire frame.
-        w.mSystemDecorRect.set(0, 0, width, height);
+        mSystemDecorRect.set(0, 0, width, height);
 
-        // Intersect with the decor rect, offsetted by window position.
-        w.mSystemDecorRect.intersect(decorRect.left - left, decorRect.top - top,
-                decorRect.right - left, decorRect.bottom - top);
+        // If a freeform window is animating from a position where it would be cutoff, it would be
+        // cutoff during the animation. We don't want that, so for the duration of the animation
+        // we ignore the decor cropping and depend on layering to position windows correctly.
+        final boolean cropToDecor = !(w.inFreeformWorkspace() && w.isAnimatingLw());
+        if (cropToDecor) {
+            // Intersect with the decor rect, offsetted by window position.
+            mSystemDecorRect.intersect(decorRect.left - left, decorRect.top - top,
+                    decorRect.right - left, decorRect.bottom - top);
+        }
 
         // If size compatibility is being applied to the window, the
         // surface is scaled relative to the screen.  Also apply this
@@ -1067,10 +1087,10 @@
         // much and hide part of the window that should be seen.
         if (w.mEnforceSizeCompat && w.mInvGlobalScale != 1.0f) {
             final float scale = w.mInvGlobalScale;
-            w.mSystemDecorRect.left = (int) (w.mSystemDecorRect.left * scale - 0.5f);
-            w.mSystemDecorRect.top = (int) (w.mSystemDecorRect.top * scale - 0.5f);
-            w.mSystemDecorRect.right = (int) ((w.mSystemDecorRect.right+1) * scale - 0.5f);
-            w.mSystemDecorRect.bottom = (int) ((w.mSystemDecorRect.bottom+1) * scale - 0.5f);
+            mSystemDecorRect.left = (int) (mSystemDecorRect.left * scale - 0.5f);
+            mSystemDecorRect.top = (int) (mSystemDecorRect.top * scale - 0.5f);
+            mSystemDecorRect.right = (int) ((mSystemDecorRect.right+1) * scale - 0.5f);
+            mSystemDecorRect.bottom = (int) ((mSystemDecorRect.bottom+1) * scale - 0.5f);
         }
     }
 
@@ -1081,30 +1101,34 @@
             return;
         }
         final DisplayInfo displayInfo = displayContent.getDisplayInfo();
+        if (DEBUG_WINDOW_CROP) Slog.d(TAG, "Updating crop for window: " + w + ", " + "mLastCrop=" +
+                mLastClipRect);
 
         // Need to recompute a new system decor rect each time.
         if (!w.isDefaultDisplay()) {
             // On a different display there is no system decor.  Crop the window
             // by the screen boundaries.
-            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
-            w.mSystemDecorRect.intersect(-w.mCompatFrame.left, -w.mCompatFrame.top,
+            mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
+            mSystemDecorRect.intersect(-w.mCompatFrame.left, -w.mCompatFrame.top,
                     displayInfo.logicalWidth - w.mCompatFrame.left,
                     displayInfo.logicalHeight - w.mCompatFrame.top);
         } else if (w.mLayer >= mService.mSystemDecorLayer) {
             // Above the decor layer is easy, just use the entire window.
-            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
+            mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
         } else if (w.mDecorFrame.isEmpty()) {
             // Windows without policy decor aren't cropped.
-            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
+            mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
         } else if (w.mAttrs.type == LayoutParams.TYPE_WALLPAPER && mAnimator.isAnimating()) {
             // If we're animating, the wallpaper crop should only be updated at the end of the
             // animation.
-            mTmpClipRect.set(w.mSystemDecorRect);
-            applyDecorRect(w.mDecorFrame);
-            w.mSystemDecorRect.union(mTmpClipRect);
+            mTmpClipRect.set(mSystemDecorRect);
+            calculateSystemDecorRect();
+            mSystemDecorRect.union(mTmpClipRect);
         } else {
             // Crop to the system decor specified by policy.
-            applyDecorRect(w.mDecorFrame);
+            calculateSystemDecorRect();
+            if (DEBUG_WINDOW_CROP) Slog.d(TAG, "Applying decor to crop for " + w + ", mDecorFrame="
+                    + w.mDecorFrame + ", mSystemDecorRect=" + mSystemDecorRect);
         }
 
         final boolean fullscreen = w.isFrameFullscreen(displayInfo);
@@ -1118,7 +1142,9 @@
         } else {
             // We use the clip rect as provided by the tranformation for non-fullscreen windows to
             // avoid premature clipping with the system decor rect.
-            clipRect.set((mHasClipRect && !fullscreen) ? mClipRect : w.mSystemDecorRect);
+            clipRect.set((mHasClipRect && !fullscreen) ? mClipRect : mSystemDecorRect);
+            if (DEBUG_WINDOW_CROP) Slog.d(TAG, "Initial clip rect: " + clipRect + ", mHasClipRect="
+                    + mHasClipRect + ", fullscreen=" + fullscreen);
         }
         // Expand the clip rect for surface insets.
         final WindowManager.LayoutParams attrs = w.mAttrs;
@@ -1138,6 +1164,7 @@
         clipRect.offset(attrs.surfaceInsets.left, attrs.surfaceInsets.top);
 
         adjustCropToStackBounds(w, clipRect, isFreeformResizing);
+        if (DEBUG_WINDOW_CROP) Slog.d(TAG, "Clip rect after stack adjustment=" + mClipRect);
 
         w.transformFromScreenToSurfaceSpace(clipRect);
 
@@ -1155,13 +1182,14 @@
         }
 
         // We don't apply the stack bounds crop if:
-        // 1. The window is currently animating docked mode, otherwise the animating window will be
-        // suddenly cut off.
+        // 1. The window is currently animating docked mode or in freeform mode, otherwise the
+        // animating window will be suddenly (docked) or for whole animation (freeform) cut off.
         // 2. The window that is being replaced during animation, because it was living in a
         // different stack. If we suddenly crop it to the new stack bounds, it might get cut off.
         // We don't want it to happen, so we let it ignore the stack bounds until it gets removed.
         // The window that will replace it will abide them.
-        if (isAnimating() && (appToken.mWillReplaceWindow || w.inDockedWorkspace())) {
+        if (isAnimating() && (appToken.mWillReplaceWindow || w.inDockedWorkspace()
+                || w.inFreeformWorkspace())) {
             return;
         }
 
@@ -1263,7 +1291,7 @@
             mLastDtDy = mDtDy;
             w.mLastHScale = w.mHScale;
             w.mLastVScale = w.mVScale;
-            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
+            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
                     "controller=" + mSurfaceController +
                     "alpha=" + mShownAlpha + " layer=" + mAnimLayer
                     + " matrix=[" + mDsDx + "*" + w.mHScale
@@ -1461,10 +1489,8 @@
                 mWin.mAppToken.removeAllDeadWindows();
 
                 if (mWin.mAppToken.startingData != null) {
-                    if (WindowManagerService.DEBUG_STARTING_WINDOW ||
-                            WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
-                            "Finish starting " + mWin.mToken
-                            + ": first real window is shown, no animation");
+                    if (DEBUG_STARTING_WINDOW || DEBUG_ANIM) Slog.v(TAG, "Finish starting "
+                            + mWin.mToken + ": first real window is shown, no animation");
                     // If this initial window is animating, stop it -- we
                     // will do an animation to reveal it from behind the
                     // starting window, so there is no need for it to also
@@ -1575,16 +1601,16 @@
                     a = mService.mAppTransition.loadAnimationAttr(mWin.mAttrs, attr);
                 }
             }
-            if (WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
+            if (DEBUG_ANIM) Slog.v(TAG,
                     "applyAnimation: win=" + this
                     + " anim=" + anim + " attr=0x" + Integer.toHexString(attr)
                     + " a=" + a
                     + " transit=" + transit
                     + " isEntrance=" + isEntrance + " Callers " + Debug.getCallers(3));
             if (a != null) {
-                if (WindowManagerService.DEBUG_ANIM) {
+                if (DEBUG_ANIM) {
                     RuntimeException e = null;
-                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
+                    if (!HIDE_STACK_CRAWLS) {
                         e = new RuntimeException();
                         e.fillInStackTrace();
                     }
@@ -1643,6 +1669,12 @@
         if (dumpAll) {
             pw.print(prefix); pw.print("mDrawState="); pw.print(drawStateToString());
             pw.print(prefix); pw.print(" mLastHidden="); pw.println(mLastHidden);
+            pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
+            pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
+            if (mHasClipRect) {
+                pw.print(" mLastClipRect="); mLastClipRect.printShortString(pw);
+            }
+            pw.println();
         }
 
         if (mPendingDestroySurface != null) {
diff --git a/services/core/java/com/android/server/wm/WindowSurfaceController.java b/services/core/java/com/android/server/wm/WindowSurfaceController.java
index f8b8d6c..bd2912d 100644
--- a/services/core/java/com/android/server/wm/WindowSurfaceController.java
+++ b/services/core/java/com/android/server/wm/WindowSurfaceController.java
@@ -16,12 +16,14 @@
 
 package com.android.server.wm;
 
-import static com.android.server.wm.WindowManagerService.SHOW_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerService.SHOW_LIGHT_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerService.SHOW_SURFACE_ALLOC;
-import static com.android.server.wm.WindowManagerService.DEBUG_SURFACE_TRACE;
-import static com.android.server.wm.WindowManagerService.HIDE_STACK_CRAWLS;
-import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SURFACE_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.HIDE_STACK_CRAWLS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.graphics.Point;
 import android.graphics.PointF;
@@ -41,7 +43,7 @@
 import java.util.ArrayList;
 
 class WindowSurfaceController {
-    static final String TAG = "WindowSurfaceController";
+    static final String TAG = TAG_WITH_CLASS_NAME ? "WindowSurfaceController" : TAG_WM;
 
     final WindowStateAnimator mAnimator;
 
@@ -392,7 +394,7 @@
     }
 
     static class SurfaceTrace extends SurfaceControl {
-        private final static String SURFACE_TAG = "SurfaceTrace";
+        private final static String SURFACE_TAG = TAG_WITH_CLASS_NAME ? "SurfaceTrace" : TAG_WM;
         private final static boolean LOG_SURFACE_TRACE = DEBUG_SURFACE_TRACE;
         final static ArrayList<SurfaceTrace> sSurfaces = new ArrayList<SurfaceTrace>();
 
diff --git a/services/core/java/com/android/server/wm/WindowSurfacePlacer.java b/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
index 3ae3be5..50bdf25 100644
--- a/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
+++ b/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
@@ -15,24 +15,24 @@
 import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_CONFIG;
 import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT;
 import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
-import static com.android.server.wm.WindowManagerService.DEBUG;
-import static com.android.server.wm.WindowManagerService.DEBUG_ADD_REMOVE;
-import static com.android.server.wm.WindowManagerService.DEBUG_APP_TRANSITIONS;
-import static com.android.server.wm.WindowManagerService.DEBUG_LAYOUT;
-import static com.android.server.wm.WindowManagerService.DEBUG_LAYOUT_REPEATS;
-import static com.android.server.wm.WindowManagerService.DEBUG_ORIENTATION;
-import static com.android.server.wm.WindowManagerService.DEBUG_POWER;
-import static com.android.server.wm.WindowManagerService.DEBUG_STARTING_WINDOW;
-import static com.android.server.wm.WindowManagerService.DEBUG_TOKEN_MOVEMENT;
-import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
-import static com.android.server.wm.WindowManagerService.DEBUG_WALLPAPER_LIGHT;
-import static com.android.server.wm.WindowManagerService.DEBUG_WINDOW_TRACE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_POWER;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TOKEN_MOVEMENT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE;
 import static com.android.server.wm.WindowManagerService.H.*;
 import static com.android.server.wm.WindowManagerService.LAYOUT_REPEAT_THRESHOLD;
 import static com.android.server.wm.WindowManagerService.MAX_ANIMATION_DURATION;
-import static com.android.server.wm.WindowManagerService.SHOW_LIGHT_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerService.SHOW_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerService.TAG;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_PLACING_SURFACES;
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_WILL_PLACE_SURFACES;
 import static com.android.server.wm.WindowManagerService.WINDOWS_FREEZING_SCREENS_NONE;
@@ -54,7 +54,7 @@
 import android.view.Surface;
 import android.view.SurfaceControl;
 import android.view.View;
-import android.view.WindowManager;
+import android.view.WindowManager.LayoutParams;
 import android.view.animation.Animation;
 
 import java.io.PrintWriter;
@@ -112,6 +112,12 @@
     private boolean mTraversalScheduled;
     private int mDeferDepth = 0;
 
+    private static final class LayerAndToken {
+        public int layer;
+        public AppWindowToken token;
+    }
+    private final LayerAndToken mTmpLayerAndToken = new LayerAndToken();
+
     public WindowSurfacePlacer(WindowManagerService service) {
         mService = service;
         mWallpaperControllerLocked = mService.mWallpaperControllerLocked;
@@ -153,7 +159,7 @@
             if (DEBUG) {
                 throw new RuntimeException("Recursive call!");
             }
-            Slog.w(TAG, "performLayoutAndPlaceSurfacesLocked called while in layout. Callers="
+            Slog.w(TAG_WM, "performLayoutAndPlaceSurfacesLocked called while in layout. Callers="
                     + Debug.getCallers(3));
             return;
         }
@@ -179,10 +185,10 @@
             // Wait a little bit for things to settle down, and off we go.
             while (!mService.mForceRemoves.isEmpty()) {
                 WindowState ws = mService.mForceRemoves.remove(0);
-                Slog.i(TAG, "Force removing: " + ws);
+                Slog.i(TAG_WM, "Force removing: " + ws);
                 mService.removeWindowInnerLocked(ws);
             }
-            Slog.w(TAG,
+            Slog.w(TAG_WM,
                     "Due to memory failure, waiting a bit for next layout");
             Object tmp = new Object();
             synchronized (tmp) {
@@ -202,7 +208,7 @@
                 if (++mLayoutRepeatCount < 6) {
                     requestTraversal();
                 } else {
-                    Slog.e(TAG, "Performed 6 layouts in a row. Skipping");
+                    Slog.e(TAG_WM, "Performed 6 layouts in a row. Skipping");
                     mLayoutRepeatCount = 0;
                 }
             } else {
@@ -215,7 +221,7 @@
             }
         } catch (RuntimeException e) {
             mInLayout = false;
-            Slog.wtf(TAG, "Unhandled exception while laying out windows", e);
+            Slog.wtf(TAG_WM, "Unhandled exception while laying out windows", e);
         }
 
         Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
@@ -223,7 +229,7 @@
 
     void debugLayoutRepeats(final String msg, int pendingLayoutChanges) {
         if (mLayoutRepeatCount >= LAYOUT_REPEAT_THRESHOLD) {
-            Slog.v(TAG, "Layouts looping: " + msg +
+            Slog.v(TAG_WM, "Layouts looping: " + msg +
                     ", mPendingLayoutChanges = 0x" + Integer.toHexString(pendingLayoutChanges));
         }
     }
@@ -231,7 +237,7 @@
     // "Something has changed!  Let's make it correct now."
     private void performSurfacePlacementInner(boolean recoveringMemory) {
         if (DEBUG_WINDOW_TRACE) {
-            Slog.v(TAG,
+            Slog.v(TAG_WM,
                     "performSurfacePlacementInner: entry. Called by "
                     + Debug.getCallers(3));
         }
@@ -276,16 +282,16 @@
         final int defaultDw = defaultInfo.logicalWidth;
         final int defaultDh = defaultInfo.logicalHeight;
 
-        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
+        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                 ">>> OPEN TRANSACTION performLayoutAndPlaceSurfaces");
         SurfaceControl.openTransaction();
         try {
             applySurfaceChangesTransaction(recoveringMemory, numDisplays, defaultDw, defaultDh);
         } catch (RuntimeException e) {
-            Slog.wtf(TAG, "Unhandled exception in Window Manager", e);
+            Slog.wtf(TAG_WM, "Unhandled exception in Window Manager", e);
         } finally {
             SurfaceControl.closeTransaction();
-            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                     "<<< CLOSE TRANSACTION performLayoutAndPlaceSurfaces");
         }
 
@@ -332,7 +338,7 @@
 
         if (mWallpaperMayChange) {
             if (DEBUG_WALLPAPER_LIGHT)
-                Slog.v(TAG, "Wallpaper may change!  Adjusting");
+                Slog.v(TAG_WM, "Wallpaper may change!  Adjusting");
             defaultDisplay.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
             if (DEBUG_LAYOUT_REPEATS) debugLayoutRepeats("WallpaperMayChange",
                     defaultDisplay.pendingLayoutChanges);
@@ -368,7 +374,7 @@
         }
 
         if (DEBUG_ORIENTATION && mService.mDisplayFrozen)
-            Slog.v(TAG,
+            Slog.v(TAG_WM,
                 "With display frozen, orientationChangeComplete="
                 + mOrientationChangeComplete);
         if (mOrientationChangeComplete) {
@@ -429,7 +435,7 @@
                     token.mAppAnimator.clearAnimation();
                     token.mAppAnimator.animating = false;
                     if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT)
-                        Slog.v(TAG,
+                        Slog.v(TAG_WM,
                                 "performLayout: App token exiting now removed" + token);
                     token.removeAppFromTaskLocked();
                 }
@@ -475,7 +481,7 @@
                     || Settings.Global.getInt(mService.mContext.getContentResolver(),
                         Settings.Global.THEATER_MODE_ON, 0) == 0) {
                 if (DEBUG_VISIBILITY || DEBUG_POWER) {
-                    Slog.v(TAG, "Turning screen on after layout!");
+                    Slog.v(TAG_WM, "Turning screen on after layout!");
                 }
                 mService.mPowerManager.wakeUp(SystemClock.uptimeMillis(),
                         "android.server.wm:TURN_ON");
@@ -484,7 +490,7 @@
         }
 
         if (mUpdateRotation) {
-            if (DEBUG_ORIENTATION) Slog.d(TAG,
+            if (DEBUG_ORIENTATION) Slog.d(TAG_WM,
                     "Performing post-rotate rotation");
             if (mService.updateRotationUncheckedLocked(false)) {
                 mService.mH.sendEmptyMessage(SEND_NEW_CONFIGURATION);
@@ -538,7 +544,7 @@
 
         mService.scheduleAnimationLocked();
 
-        if (DEBUG_WINDOW_TRACE) Slog.e(TAG,
+        if (DEBUG_WINDOW_TRACE) Slog.e(TAG_WM,
                 "performSurfacePlacementInner exit: animating=" + mService.mAnimator.isAnimating());
     }
 
@@ -582,7 +588,7 @@
             do {
                 repeats++;
                 if (repeats > 6) {
-                    Slog.w(TAG, "Animation repeat aborted after too many iterations");
+                    Slog.w(TAG_WM, "Animation repeat aborted after too many iterations");
                     displayContent.layoutNeeded = false;
                     break;
                 }
@@ -598,7 +604,7 @@
 
                 if (isDefaultDisplay
                         && (displayContent.pendingLayoutChanges & FINISH_LAYOUT_REDO_CONFIG) != 0) {
-                    if (DEBUG_LAYOUT) Slog.v(TAG, "Computing new config from layout");
+                    if (DEBUG_LAYOUT) Slog.v(TAG_WM, "Computing new config from layout");
                     if (mService.updateOrientationFromAppTokensLocked(true)) {
                         displayContent.layoutNeeded = true;
                         mService.mH.sendEmptyMessage(SEND_NEW_CONFIGURATION);
@@ -614,7 +620,7 @@
                     performLayoutLockedInner(displayContent, repeats == 1,
                             false /* updateInputWindows */);
                 } else {
-                    Slog.w(TAG, "Layout repeat skipped after too many iterations");
+                    Slog.w(TAG_WM, "Layout repeat skipped after too many iterations");
                 }
 
                 // FIRST AND ONE HALF LOOP: Make WindowManagerPolicy think
@@ -700,7 +706,7 @@
                     }
                 }
 
-                //Slog.i(TAG, "Window " + this + " clearing mContentChanged - done placing");
+                //Slog.i(TAG_WM, "Window " + this + " clearing mContentChanged - done placing");
                 w.mContentChanged = false;
 
                 // Moved from updateWindowsAndWallpaperLocked().
@@ -722,7 +728,7 @@
                         }
                         if ((w.mAttrs.flags & FLAG_SHOW_WALLPAPER) != 0) {
                             if (DEBUG_WALLPAPER_LIGHT)
-                                Slog.v(TAG, "First draw done in potential wallpaper target " + w);
+                                Slog.v(TAG_WM, "First draw done in potential wallpaper target " + w);
                             mWallpaperMayChange = true;
                             displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
                             if (DEBUG_LAYOUT_REPEATS) {
@@ -743,7 +749,7 @@
 
                 final AppWindowToken atoken = w.mAppToken;
                 if (DEBUG_STARTING_WINDOW && atoken != null && w == atoken.startingWindow) {
-                    Slog.d(TAG, "updateWindows: starting " + w
+                    Slog.d(TAG_WM, "updateWindows: starting " + w
                             + " isOnScreen=" + w.isOnScreen() + " allDrawn=" + atoken.allDrawn
                             + " freezingScreen=" + atoken.mAppAnimator.freezingScreen);
                 }
@@ -757,11 +763,11 @@
                             || winAnimator.mAttrType == TYPE_BASE_APPLICATION)
                             && !w.mExiting && !w.mDestroying) {
                         if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
-                            Slog.v(TAG, "Eval win " + w + ": isDrawn="
+                            Slog.v(TAG_WM, "Eval win " + w + ": isDrawn="
                                     + w.isDrawnLw()
                                     + ", isAnimating=" + winAnimator.isAnimating());
                             if (!w.isDrawnLw()) {
-                                Slog.v(TAG, "Not displayed: s="
+                                Slog.v(TAG_WM, "Not displayed: s="
                                         + winAnimator.mSurfaceController
                                         + " pv=" + w.mPolicyVisibility
                                         + " mDrawState=" + winAnimator.drawStateToString()
@@ -776,7 +782,7 @@
                                 if (w.isDrawnLw()) {
                                     atoken.numDrawnWindows++;
                                     if (DEBUG_VISIBILITY || DEBUG_ORIENTATION)
-                                        Slog.v(TAG, "tokenMayBeDrawn: " + atoken
+                                        Slog.v(TAG_WM, "tokenMayBeDrawn: " + atoken
                                                 + " freezingScreen="
                                                 + atoken.mAppAnimator.freezingScreen
                                                 + " mAppFreezing=" + w.mAppFreezing);
@@ -844,8 +850,8 @@
         int i;
 
         if (DEBUG_LAYOUT) {
-            Slog.v(TAG, "-------------------------------------");
-            Slog.v(TAG, "performLayout: needed="
+            Slog.v(TAG_WM, "-------------------------------------");
+            Slog.v(TAG_WM, "performLayout: needed="
                     + displayContent.layoutNeeded + " dw=" + dw + " dh=" + dh);
         }
 
@@ -878,18 +884,18 @@
                     || win.isGoneForLayoutLw();
 
             if (DEBUG_LAYOUT && !win.mLayoutAttached) {
-                Slog.v(TAG, "1ST PASS " + win
+                Slog.v(TAG_WM, "1ST PASS " + win
                         + ": gone=" + gone + " mHaveFrame=" + win.mHaveFrame
                         + " mLayoutAttached=" + win.mLayoutAttached
                         + " screen changed=" + win.isConfigChanged());
                 final AppWindowToken atoken = win.mAppToken;
-                if (gone) Slog.v(TAG, "  GONE: mViewVisibility="
+                if (gone) Slog.v(TAG_WM, "  GONE: mViewVisibility="
                         + win.mViewVisibility + " mRelayoutCalled="
                         + win.mRelayoutCalled + " hidden="
                         + win.mRootToken.hidden + " hiddenRequested="
                         + (atoken != null && atoken.hiddenRequested)
                         + " mAttachedHidden=" + win.mAttachedHidden);
-                else Slog.v(TAG, "  VIS: mViewVisibility="
+                else Slog.v(TAG_WM, "  VIS: mViewVisibility="
                         + win.mViewVisibility + " mRelayoutCalled="
                         + win.mRelayoutCalled + " hidden="
                         + win.mRootToken.hidden + " hiddenRequested="
@@ -909,7 +915,7 @@
                             win.mAppToken.layoutConfigChanges)))) {
                 if (!win.mLayoutAttached) {
                     if (initial) {
-                        //Slog.i(TAG, "Window " + this + " clearing mContentChanged - initial");
+                        //Slog.i(TAG_WM, "Window " + this + " clearing mContentChanged - initial");
                         win.mContentChanged = false;
                     }
                     if (win.mAttrs.type == TYPE_DREAM) {
@@ -929,7 +935,7 @@
                         displayContent.mDimLayerController.updateDimLayer(task);
                     }
 
-                    if (DEBUG_LAYOUT) Slog.v(TAG,
+                    if (DEBUG_LAYOUT) Slog.v(TAG_WM,
                             "  LAYOUT: mFrame="
                             + win.mFrame + " mContainingFrame="
                             + win.mContainingFrame + " mDisplayFrame="
@@ -950,7 +956,7 @@
             final WindowState win = windows.get(i);
 
             if (win.mLayoutAttached) {
-                if (DEBUG_LAYOUT) Slog.v(TAG,
+                if (DEBUG_LAYOUT) Slog.v(TAG_WM,
                         "2ND PASS " + win + " mHaveFrame=" + win.mHaveFrame + " mViewVisibility="
                         + win.mViewVisibility + " mRelayoutCalled=" + win.mRelayoutCalled);
                 // If this view is GONE, then skip it -- keep the current
@@ -964,14 +970,14 @@
                 if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
                         || !win.mHaveFrame || win.mLayoutNeeded) {
                     if (initial) {
-                        //Slog.i(TAG, "Window " + this + " clearing mContentChanged - initial");
+                        //Slog.i(TAG_WM, "Window " + this + " clearing mContentChanged - initial");
                         win.mContentChanged = false;
                     }
                     win.mLayoutNeeded = false;
                     win.prelayout();
                     mService.mPolicy.layoutWindowLw(win, win.mAttachedWindow);
                     win.mLayoutSeq = seq;
-                    if (DEBUG_LAYOUT) Slog.v(TAG,
+                    if (DEBUG_LAYOUT) Slog.v(TAG_WM,
                             "  LAYOUT: mFrame=" + win.mFrame + " mContainingFrame="
                             + win.mContainingFrame + " mDisplayFrame=" + win.mDisplayFrame);
                 }
@@ -1002,7 +1008,7 @@
         if (!transitionGoodToGo(appsCount)) {
             return 0;
         }
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "**** GOOD TO GO");
+        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "**** GOOD TO GO");
         int transit = mService.mAppTransition.getAppTransition();
         if (mService.mSkipAppTransitionAnimation) {
             transit = AppTransition.TRANSIT_UNSET;
@@ -1018,7 +1024,7 @@
 
         // The top-most window will supply the layout params,
         // and we will determine it below.
-        WindowManager.LayoutParams animLp = null;
+        LayoutParams animLp = null;
         int bestAnimLayer = -1;
         boolean fullscreenAnim = false;
         boolean voiceInteraction = false;
@@ -1094,21 +1100,127 @@
         // example, when this transition is being done behind
         // the lock screen.
         if (!mService.mPolicy.allowAppAnimationsLw()) {
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                     "Animations disallowed by keyguard or dream.");
             animLp = null;
         }
 
         processApplicationsAnimatingInPlace(transit);
 
-        AppWindowToken topClosingApp = null;
-        int topClosingLayer = 0;
+        handleClosingApps(transit, animLp, voiceInteraction, mTmpLayerAndToken);
+        final AppWindowToken topClosingApp = mTmpLayerAndToken.token;
+        final int topClosingLayer = mTmpLayerAndToken.layer;
+
+        final AppWindowToken topOpeningApp = handleOpeningApps(transit,
+                animLp, voiceInteraction, topClosingLayer);
+
+        final AppWindowAnimator openingAppAnimator = (topOpeningApp == null) ?  null :
+                topOpeningApp.mAppAnimator;
+        final AppWindowAnimator closingAppAnimator = (topClosingApp == null) ? null :
+                topClosingApp.mAppAnimator;
+
+        mService.mAppTransition.goodToGo(openingAppAnimator, closingAppAnimator);
+        mService.mAppTransition.postAnimationCallback();
+        mService.mAppTransition.clear();
+
+        mService.mOpeningApps.clear();
+        mService.mClosingApps.clear();
+
+        // This has changed the visibility of windows, so perform
+        // a new layout to get them all up-to-date.
+        mService.getDefaultDisplayContentLocked().layoutNeeded = true;
+
+        // TODO(multidisplay): IMEs are only supported on the default display.
+        if (windows == mService.getDefaultWindowListLocked()
+                && !mService.moveInputMethodWindowsIfNeededLocked(true)) {
+            mService.assignLayersLocked(windows);
+        }
+        mService.updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES,
+                true /*updateInputWindows*/);
+        mService.mFocusMayChange = false;
+        mService.notifyActivityDrawnForKeyguard();
+        return FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG;
+    }
+
+    private AppWindowToken handleOpeningApps(int transit, LayoutParams animLp,
+            boolean voiceInteraction, int topClosingLayer) {
+        AppWindowToken topOpeningApp = null;
+        final int appsCount = mService.mOpeningApps.size();
+        for (int i = 0; i < appsCount; i++) {
+            AppWindowToken wtoken = mService.mOpeningApps.valueAt(i);
+            final AppWindowAnimator appAnimator = wtoken.mAppAnimator;
+            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "Now opening app" + wtoken);
+
+            if (!appAnimator.usingTransferredAnimation) {
+                appAnimator.clearThumbnail();
+                appAnimator.animation = null;
+            }
+            wtoken.inPendingTransaction = false;
+            if (!mService.setTokenVisibilityLocked(
+                    wtoken, animLp, true, transit, false, voiceInteraction)){
+                // This token isn't going to be animating. Add it to the list of tokens to
+                // be notified of app transition complete since the notification will not be
+                // sent be the app window animator.
+                mService.mNoAnimationNotifyOnTransitionFinished.add(wtoken.token);
+            }
+            wtoken.updateReportedVisibilityLocked();
+            wtoken.waitingToShow = false;
+
+            appAnimator.mAllAppWinAnimators.clear();
+            final int windowsCount = wtoken.allAppWindows.size();
+            for (int j = 0; j < windowsCount; j++) {
+                appAnimator.mAllAppWinAnimators.add(wtoken.allAppWindows.get(j).mWinAnimator);
+            }
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
+                    ">>> OPEN TRANSACTION handleAppTransitionReadyLocked()");
+            SurfaceControl.openTransaction();
+            try {
+                mService.mAnimator.orAnimating(appAnimator.showAllWindowsLocked());
+            } finally {
+                SurfaceControl.closeTransaction();
+                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
+                        "<<< CLOSE TRANSACTION handleAppTransitionReadyLocked()");
+            }
+            mService.mAnimator.mAppWindowAnimating |= appAnimator.isAnimating();
+
+            int topOpeningLayer = 0;
+            if (animLp != null) {
+                int layer = -1;
+                for (int j = 0; j < wtoken.windows.size(); j++) {
+                    final WindowState win = wtoken.windows.get(j);
+                    // Clearing the mExiting flag before entering animation. It will be set to true
+                    // if app window is removed, or window relayout to invisible. We don't want to
+                    // clear it out for windows that get replaced, because the animation depends on
+                    // the flag to remove the replaced window.
+                    if (win.mAppToken == null || !win.mAppToken.mWillReplaceWindow) {
+                        win.mExiting = false;
+                    }
+                    if (win.mWinAnimator.mAnimLayer > layer) {
+                        layer = win.mWinAnimator.mAnimLayer;
+                    }
+                }
+                if (topOpeningApp == null || layer > topOpeningLayer) {
+                    topOpeningApp = wtoken;
+                    topOpeningLayer = layer;
+                }
+            }
+            if (mService.mAppTransition.isNextAppTransitionThumbnailUp()) {
+                createThumbnailAppAnimator(transit, wtoken, topOpeningLayer, topClosingLayer);
+            }
+
+            wtoken.restoreSavedSurfaces();
+        }
+        return topOpeningApp;
+    }
+
+    private void handleClosingApps(int transit, LayoutParams animLp, boolean voiceInteraction,
+            LayerAndToken layerAndToken) {
+        final int appsCount;
         appsCount = mService.mClosingApps.size();
-        for (i = 0; i < appsCount; i++) {
+        for (int i = 0; i < appsCount; i++) {
             AppWindowToken wtoken = mService.mClosingApps.valueAt(i);
             final AppWindowAnimator appAnimator = wtoken.mAppAnimator;
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
-                    "Now closing app " + wtoken);
+            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "Now closing app " + wtoken);
             appAnimator.clearThumbnail();
             appAnimator.animation = null;
             wtoken.inPendingTransaction = false;
@@ -1135,116 +1247,26 @@
                         layer = win.mWinAnimator.mAnimLayer;
                     }
                 }
-                if (topClosingApp == null || layer > topClosingLayer) {
-                    topClosingApp = wtoken;
-                    topClosingLayer = layer;
+                if (layerAndToken.token == null || layer > layerAndToken.layer) {
+                    layerAndToken.token = wtoken;
+                    layerAndToken.layer = layer;
                 }
             }
+            if (mService.mAppTransition.isNextAppTransitionThumbnailDown()) {
+                createThumbnailAppAnimator(transit, wtoken, 0, layerAndToken.layer);
+            }
         }
-
-        AppWindowToken topOpeningApp = null;
-        appsCount = mService.mOpeningApps.size();
-        for (i = 0; i < appsCount; i++) {
-            AppWindowToken wtoken = mService.mOpeningApps.valueAt(i);
-            final AppWindowAnimator appAnimator = wtoken.mAppAnimator;
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
-                    "Now opening app" + wtoken);
-
-            if (!appAnimator.usingTransferredAnimation) {
-                appAnimator.clearThumbnail();
-                appAnimator.animation = null;
-            }
-            wtoken.inPendingTransaction = false;
-            if (!mService.setTokenVisibilityLocked(
-                    wtoken, animLp, true, transit, false, voiceInteraction)){
-                // This token isn't going to be animating. Add it to the list of tokens to
-                // be notified of app transition complete since the notification will not be
-                // sent be the app window animator.
-                mService.mNoAnimationNotifyOnTransitionFinished.add(wtoken.token);
-            }
-            wtoken.updateReportedVisibilityLocked();
-            wtoken.waitingToShow = false;
-
-            appAnimator.mAllAppWinAnimators.clear();
-            final int windowsCount = wtoken.allAppWindows.size();
-            for (int j = 0; j < windowsCount; j++) {
-                appAnimator.mAllAppWinAnimators.add(wtoken.allAppWindows.get(j).mWinAnimator);
-            }
-            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
-                    ">>> OPEN TRANSACTION handleAppTransitionReadyLocked()");
-            SurfaceControl.openTransaction();
-            try {
-                mService.mAnimator.orAnimating(appAnimator.showAllWindowsLocked());
-            } finally {
-                SurfaceControl.closeTransaction();
-                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
-                        "<<< CLOSE TRANSACTION handleAppTransitionReadyLocked()");
-            }
-            mService.mAnimator.mAppWindowAnimating |= appAnimator.isAnimating();
-
-            int topOpeningLayer = 0;
-            if (animLp != null) {
-                int layer = -1;
-                for (int j = 0; j < wtoken.windows.size(); j++) {
-                    final WindowState win = wtoken.windows.get(j);
-                    // Clearing the mExiting flag before entering animation. It will be set to true
-                    // if app window is removed, or window relayout to invisible. We don't want to
-                    // clear it out for windows that get replaced, because the animation depends on
-                    // the flag to remove the replaced window.
-                    if (win.mAppToken == null || !win.mAppToken.mWillReplaceWindow) {
-                        win.mExiting = false;
-                    }
-                    if (win.mWinAnimator.mAnimLayer > layer) {
-                        layer = win.mWinAnimator.mAnimLayer;
-                    }
-                }
-                if (topOpeningApp == null || layer > topOpeningLayer) {
-                    topOpeningApp = wtoken;
-                    topOpeningLayer = layer;
-                }
-            }
-            createThumbnailAppAnimator(transit, wtoken, topOpeningLayer, topClosingLayer);
-
-            wtoken.restoreSavedSurfaces();
-        }
-
-        AppWindowAnimator openingAppAnimator = (topOpeningApp == null) ?  null :
-                topOpeningApp.mAppAnimator;
-        AppWindowAnimator closingAppAnimator = (topClosingApp == null) ? null :
-                topClosingApp.mAppAnimator;
-
-        mService.mAppTransition.goodToGo(openingAppAnimator, closingAppAnimator);
-        mService.mAppTransition.postAnimationCallback();
-        mService.mAppTransition.clear();
-
-        mService.mOpeningApps.clear();
-        mService.mClosingApps.clear();
-
-        // This has changed the visibility of windows, so perform
-        // a new layout to get them all up-to-date.
-        mService.getDefaultDisplayContentLocked().layoutNeeded = true;
-
-        // TODO(multidisplay): IMEs are only supported on the default display.
-        if (windows == mService.getDefaultWindowListLocked()
-                && !mService.moveInputMethodWindowsIfNeededLocked(true)) {
-            mService.assignLayersLocked(windows);
-        }
-        mService.updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES,
-                true /*updateInputWindows*/);
-        mService.mFocusMayChange = false;
-        mService.notifyActivityDrawnForKeyguard();
-        return FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG;
     }
 
     private boolean transitionGoodToGo(int appsCount) {
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                 "Checking " + appsCount + " opening apps (frozen="
                         + mService.mDisplayFrozen + " timeout="
                         + mService.mAppTransition.isTimeout() + ")...");
         if (!mService.mAppTransition.isTimeout()) {
             for (int i = 0; i < appsCount; i++) {
                 AppWindowToken wtoken = mService.mOpeningApps.valueAt(i);
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                         "Check opening app=" + wtoken + ": allDrawn="
                         + wtoken.allDrawn + " startingDisplayed="
                         + wtoken.startingDisplayed + " startingMoved="
@@ -1260,7 +1282,7 @@
 
             // We also need to wait for the specs to be fetched, if needed.
             if (mService.mAppTransition.isFetchingAppTransitionsSpecs()) {
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "isFetchingAppTransitionSpecs=true");
+                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "isFetchingAppTransitionSpecs=true");
                 return false;
             }
 
@@ -1281,7 +1303,7 @@
                         ? null : wallpaperTarget;
         final ArraySet<AppWindowToken> openingApps = mService.mOpeningApps;
         final ArraySet<AppWindowToken> closingApps = mService.mClosingApps;
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                 "New wallpaper target=" + wallpaperTarget
                         + ", oldWallpaper=" + oldWallpaper
                         + ", lower target=" + lowerWallpaperTarget
@@ -1291,7 +1313,7 @@
         mService.mAnimateWallpaperWithTarget = false;
         if (closingAppHasWallpaper && openingAppHasWallpaper) {
             if (DEBUG_APP_TRANSITIONS)
-                Slog.v(TAG, "Wallpaper animation!");
+                Slog.v(TAG_WM, "Wallpaper animation!");
             switch (transit) {
                 case AppTransition.TRANSIT_ACTIVITY_OPEN:
                 case AppTransition.TRANSIT_TASK_OPEN:
@@ -1304,14 +1326,14 @@
                     transit = AppTransition.TRANSIT_WALLPAPER_INTRA_CLOSE;
                     break;
             }
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                     "New transit: " + AppTransition.appTransitionToString(transit));
         } else if (oldWallpaper != null && !mService.mOpeningApps.isEmpty()
                 && !openingApps.contains(oldWallpaper.mAppToken)
                 && closingApps.contains(oldWallpaper.mAppToken)) {
             // We are transitioning from an activity with a wallpaper to one without.
             transit = AppTransition.TRANSIT_WALLPAPER_CLOSE;
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                     "New transit away from wallpaper: "
                     + AppTransition.appTransitionToString(transit));
         } else if (wallpaperTarget != null && wallpaperTarget.isVisibleLw() &&
@@ -1319,7 +1341,7 @@
             // We are transitioning from an activity without
             // a wallpaper to now showing the wallpaper
             transit = AppTransition.TRANSIT_WALLPAPER_OPEN;
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
+            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
                     "New transit into wallpaper: "
                     + AppTransition.appTransitionToString(transit));
         } else {
@@ -1333,7 +1355,7 @@
      * @param dispInfo info of the display that the window's obscuring state is checked against.
      */
     private void handleNotObscuredLocked(final WindowState w, final DisplayInfo dispInfo) {
-        final WindowManager.LayoutParams attrs = w.mAttrs;
+        final LayoutParams attrs = w.mAttrs;
         final int attrFlags = attrs.flags;
         final boolean canBeSeen = w.isDisplayedLw();
 
@@ -1414,7 +1436,7 @@
                         int numInteresting = wtoken.numInterestingWindows;
                         if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
                             if (DEBUG_VISIBILITY)
-                                Slog.v(TAG, "allDrawn: " + wtoken
+                                Slog.v(TAG_WM, "allDrawn: " + wtoken
                                     + " interesting=" + numInteresting
                                     + " drawn=" + wtoken.numDrawnWindows);
                             wtoken.allDrawn = true;
@@ -1443,7 +1465,7 @@
                 final AppWindowToken wtoken = win.mAppToken;
                 final AppWindowAnimator appAnimator = wtoken.mAppAnimator;
                 if (DEBUG_APP_TRANSITIONS)
-                    Slog.v(TAG, "Now animating app in place " + wtoken);
+                    Slog.v(TAG_WM, "Now animating app in place " + wtoken);
                 appAnimator.clearThumbnail();
                 appAnimator.animation = null;
                 mService.updateTokenInPlaceLocked(wtoken, transit);
@@ -1469,7 +1491,7 @@
         final int taskId = appToken.mTask.mTaskId;
         Bitmap thumbnailHeader = mService.mAppTransition.getAppTransitionThumbnailHeader(taskId);
         if (thumbnailHeader == null || thumbnailHeader.getConfig() == Bitmap.Config.ALPHA_8) {
-            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG, "No thumbnail header bitmap for: " + taskId);
+            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG_WM, "No thumbnail header bitmap for: " + taskId);
             return;
         }
         // This thumbnail animation is very special, we need to have
@@ -1487,7 +1509,7 @@
                     PixelFormat.TRANSLUCENT, SurfaceControl.HIDDEN);
             surfaceControl.setLayerStack(display.getLayerStack());
             if (SHOW_TRANSACTIONS) {
-                Slog.i(TAG, "  THUMBNAIL " + surfaceControl + ": CREATE");
+                Slog.i(TAG_WM, "  THUMBNAIL " + surfaceControl + ": CREATE");
             }
 
             // Draw the thumbnail onto the surface
@@ -1530,7 +1552,7 @@
             openingAppAnimator.thumbnailX = mTmpStartRect.left;
             openingAppAnimator.thumbnailY = mTmpStartRect.top;
         } catch (Surface.OutOfResourcesException e) {
-            Slog.e(TAG, "Can't allocate thumbnail/Canvas surface w="
+            Slog.e(TAG_WM, "Can't allocate thumbnail/Canvas surface w="
                     + dirty.width() + " h=" + dirty.height(), e);
             openingAppAnimator.clearThumbnail();
         }
diff --git a/services/core/java/com/android/server/wm/WindowToken.java b/services/core/java/com/android/server/wm/WindowToken.java
index 4ac9135..7894ccf 100644
--- a/services/core/java/com/android/server/wm/WindowToken.java
+++ b/services/core/java/com/android/server/wm/WindowToken.java
@@ -16,6 +16,9 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_MOVEMENT;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.os.IBinder;
 import android.util.Slog;
 
@@ -77,8 +80,7 @@
     void removeAllWindows() {
         for (int winNdx = windows.size() - 1; winNdx >= 0; --winNdx) {
             WindowState win = windows.get(winNdx);
-            if (WindowManagerService.DEBUG_WINDOW_MOVEMENT) Slog.w(WindowManagerService.TAG,
-                    "removeAllWindows: removing win=" + win);
+            if (DEBUG_WINDOW_MOVEMENT) Slog.w(TAG_WM, "removeAllWindows: removing win=" + win);
             win.mService.removeWindowLocked(win);
         }
         windows.clear();
@@ -106,4 +108,4 @@
         }
         return stringName;
     }
-}
\ No newline at end of file
+}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index eed5419..5cf8ac0e 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -3541,6 +3541,18 @@
         }
     }
 
+    private void enforceCanManageInstalledKeys(ComponentName who) {
+        if (who == null) {
+            if (!isCallerDelegatedCertInstaller()) {
+                throw new SecurityException("who == null, but caller is not cert installer");
+            }
+        } else {
+            synchronized (this) {
+                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
+            }
+        }
+    }
+
     private boolean isCallerDelegatedCertInstaller() {
         final int callingUid = mInjector.binderGetCallingUid();
         final int userHandle = UserHandle.getUserId(callingUid);
@@ -3630,27 +3642,20 @@
 
     @Override
     public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
-        if (who == null) {
-            if (!isCallerDelegatedCertInstaller()) {
-                throw new SecurityException("who == null, but caller is not cert installer");
-            }
-        } else {
-            synchronized (this) {
-                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
-            }
-        }
+        enforceCanManageInstalledKeys(who);
+
         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
         final long id = mInjector.binderClearCallingIdentity();
         try {
-          final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
-          try {
-              IKeyChainService keyChain = keyChainConnection.getService();
-              return keyChain.installKeyPair(privKey, cert, alias);
-          } catch (RemoteException e) {
-              Log.e(LOG_TAG, "Installing certificate", e);
-          } finally {
-              keyChainConnection.close();
-          }
+            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
+            try {
+                IKeyChainService keyChain = keyChainConnection.getService();
+                return keyChain.installKeyPair(privKey, cert, alias);
+            } catch (RemoteException e) {
+                Log.e(LOG_TAG, "Installing certificate", e);
+            } finally {
+                keyChainConnection.close();
+            }
         } catch (InterruptedException e) {
             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
             Thread.currentThread().interrupt();
@@ -3661,6 +3666,31 @@
     }
 
     @Override
+    public boolean removeKeyPair(ComponentName who, String alias) {
+        enforceCanManageInstalledKeys(who);
+
+        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
+        final long id = Binder.clearCallingIdentity();
+        try {
+            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
+            try {
+                IKeyChainService keyChain = keyChainConnection.getService();
+                return keyChain.removeKeyPair(alias);
+            } catch (RemoteException e) {
+                Log.e(LOG_TAG, "Removing keypair", e);
+            } finally {
+                keyChainConnection.close();
+            }
+        } catch (InterruptedException e) {
+            Log.w(LOG_TAG, "Interrupted while removing keypair", e);
+            Thread.currentThread().interrupt();
+        } finally {
+            Binder.restoreCallingIdentity(id);
+        }
+        return false;
+    }
+
+    @Override
     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
             final IBinder response) {
         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index c7f3d0a..12b36b2 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -673,12 +673,15 @@
     @Nullable
     public PersistableBundle getConfigForSubId(int subId) {
         try {
-            return getICarrierConfigLoader().getConfigForSubId(subId);
+            ICarrierConfigLoader loader = getICarrierConfigLoader();
+            if (loader == null) {
+                Rlog.w(TAG, "Error getting config for subId " + subId
+                        + " ICarrierConfigLoader is null");
+                return null;
+            }
+            return loader.getConfigForSubId(subId);
         } catch (RemoteException ex) {
-            Rlog.e(TAG, "Error getting config for subId " + Integer.toString(subId) + ": "
-                    + ex.toString());
-        } catch (NullPointerException ex) {
-            Rlog.e(TAG, "Error getting config for subId " + Integer.toString(subId) + ": "
+            Rlog.e(TAG, "Error getting config for subId " + subId + ": "
                     + ex.toString());
         }
         return null;
@@ -714,11 +717,15 @@
      */
     public void notifyConfigChangedForSubId(int subId) {
         try {
-            getICarrierConfigLoader().notifyConfigChangedForSubId(subId);
+            ICarrierConfigLoader loader = getICarrierConfigLoader();
+            if (loader == null) {
+                Rlog.w(TAG, "Error reloading config for subId=" + subId
+                        + " ICarrierConfigLoader is null");
+                return;
+            }
+            loader.notifyConfigChangedForSubId(subId);
         } catch (RemoteException ex) {
             Rlog.e(TAG, "Error reloading config for subId=" + subId + ": " + ex.toString());
-        } catch (NullPointerException ex) {
-            Rlog.e(TAG, "Error reloading config for subId=" + subId + ": " + ex.toString());
         }
     }
 
@@ -734,11 +741,15 @@
     @SystemApi
     public void updateConfigForPhoneId(int phoneId, String simState) {
         try {
-            getICarrierConfigLoader().updateConfigForPhoneId(phoneId, simState);
+            ICarrierConfigLoader loader = getICarrierConfigLoader();
+            if (loader == null) {
+                Rlog.w(TAG, "Error updating config for phoneId=" + phoneId
+                        + " ICarrierConfigLoader is null");
+                return;
+            }
+            loader.updateConfigForPhoneId(phoneId, simState);
         } catch (RemoteException ex) {
             Rlog.e(TAG, "Error updating config for phoneId=" + phoneId + ": " + ex.toString());
-        } catch (NullPointerException ex) {
-            Rlog.e(TAG, "Error updating config for phoneId=" + phoneId + ": " + ex.toString());
         }
     }
 
@@ -754,6 +765,7 @@
     }
 
     /** @hide */
+    @Nullable
     private ICarrierConfigLoader getICarrierConfigLoader() {
         return ICarrierConfigLoader.Stub
                 .asInterface(ServiceManager.getService(Context.CARRIER_CONFIG_SERVICE));
diff --git a/test-runner/src/android/test/mock/MockContext.java b/test-runner/src/android/test/mock/MockContext.java
index c967c2b..225edf8 100644
--- a/test-runner/src/android/test/mock/MockContext.java
+++ b/test-runner/src/android/test/mock/MockContext.java
@@ -130,12 +130,6 @@
         throw new UnsupportedOperationException();
     }
 
-    /** @hide */
-    @Override
-    public File getSharedPrefsFile(String name) {
-        throw new UnsupportedOperationException();
-    }
-
     @Override
     public String getPackageCodePath() {
         throw new UnsupportedOperationException();
@@ -172,6 +166,11 @@
     }
 
     @Override
+    public File getSharedPreferencesPath(String name) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
     public String[] fileList() {
         throw new UnsupportedOperationException();
     }
diff --git a/tools/aapt/Bundle.h b/tools/aapt/Bundle.h
index c29bb48..c449550 100644
--- a/tools/aapt/Bundle.h
+++ b/tools/aapt/Bundle.h
@@ -127,6 +127,12 @@
     const android::String8& getPlatformBuildVersionName() { return mPlatformVersionName; }
     void setPlatformBuildVersionName(const android::String8& name) { mPlatformVersionName = name; }
 
+    const android::String8& getPrivateSymbolsPackage() const { return mPrivateSymbolsPackage; }
+
+    void setPrivateSymbolsPackage(const android::String8& package) {
+        mPrivateSymbolsPackage = package;
+    }
+
     bool getUTF16StringsOption() {
         return mWantUTF16 || !isMinSdkAtLeast(SDK_FROYO);
     }
@@ -333,6 +339,7 @@
     bool        mBuildAppAsSharedLibrary;
     android::String8 mPlatformVersionCode;
     android::String8 mPlatformVersionName;
+    android::String8 mPrivateSymbolsPackage;
 
     /* file specification */
     int         mArgc;
diff --git a/tools/aapt/Main.cpp b/tools/aapt/Main.cpp
index 6411286..c424cc5 100644
--- a/tools/aapt/Main.cpp
+++ b/tools/aapt/Main.cpp
@@ -220,7 +220,9 @@
         "       Prevents symbols from being generated for strings that do not have a default\n"
         "       localization\n"
         "   --no-version-vectors\n"
-        "       Do not automatically generate versioned copies of vector XML resources.\n",
+        "       Do not automatically generate versioned copies of vector XML resources.\n"
+        "   --private-symbols\n"
+        "       Java package name to use when generating R.java for private resources.\n",
         gDefaultIgnoreAssets);
 }
 
@@ -689,6 +691,16 @@
                     bundle.setPseudolocalize(PSEUDO_ACCENTED | PSEUDO_BIDI);
                 } else if (strcmp(cp, "-no-version-vectors") == 0) {
                     bundle.setNoVersionVectors(true);
+                } else if (strcmp(cp, "-private-symbols") == 0) {
+                    argc--;
+                    argv++;
+                    if (!argc) {
+                        fprintf(stderr, "ERROR: No argument supplied for "
+                                "'--private-symbols' option\n");
+                        wantUsage = true;
+                        goto bail;
+                    }
+                    bundle.setPrivateSymbolsPackage(String8(argv[0]));
                 } else {
                     fprintf(stderr, "ERROR: Unknown option '-%s'\n", cp);
                     wantUsage = true;
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index fb0fe38..576f076 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -1161,6 +1161,12 @@
         printf("Creating resources for package %s\n", assets->getPackage().string());
     }
 
+    // Set the private symbols package if it was declared.
+    // This can also be declared in XML as <private-symbols name="package" />
+    if (bundle->getPrivateSymbolsPackage().size() != 0) {
+        assets->setSymbolsPrivatePackage(bundle->getPrivateSymbolsPackage());
+    }
+
     ResourceTable::PackageType packageType = ResourceTable::App;
     if (bundle->getBuildSharedLibrary()) {
         packageType = ResourceTable::SharedLibrary;
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 0e470d9..e87c7d40 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -1141,7 +1141,15 @@
                 }
                 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
                 if (!localHasErrors) {
-                    assets->setSymbolsPrivatePackage(String8(pkg));
+                    SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
+                            "<private-symbols> is deprecated. Use the command line flag "
+                            "--private-symbols instead.\n");
+                    if (assets->havePrivateSymbols()) {
+                        SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
+                                "private symbol package already specified. Ignoring...\n");
+                    } else {
+                        assets->setSymbolsPrivatePackage(String8(pkg));
+                    }
                 }
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
index ff15f3b..9214759 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
@@ -1365,6 +1365,12 @@
     }
 
     @Override
+    public File getSharedPreferencesPath(String name) {
+        // pass
+        return null;
+    }
+
+    @Override
     public File getFilesDir() {
         // pass
         return null;
@@ -1424,12 +1430,6 @@
     }
 
     @Override
-    public File getSharedPrefsFile(String name) {
-        // pass
-        return null;
-    }
-
-    @Override
     public SharedPreferences getSharedPreferences(String arg0, int arg1) {
         if (mSharedPreferences == null) {
             mSharedPreferences = new BridgeSharedPreferences();