PIP: Use StatusBarService to handle PIP key

Bug: 26591829
Change-Id: I7051fab966e2fc0887b2a21ddbf11aff7e16804b
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 06da4955..ea1ccaf 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -2567,16 +2567,6 @@
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     public static final String ACTION_MEDIA_BUTTON = "android.intent.action.MEDIA_BUTTON";
 
-   /**
-     * Broadcast Action:  The "Picture-in-picture (PIP) Button" was pressed.
-     * Includes a single extra field, {@link #EXTRA_KEY_EVENT}, containing the key event that
-     * caused the broadcast.
-     * @hide
-     */
-    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
-    public static final String ACTION_PICTURE_IN_PICTURE_BUTTON =
-            "android.intent.action.PICTURE_IN_PICTURE_BUTTON";
-
     /**
      * Broadcast Action:  The "Camera Button" was pressed.  Includes a single
      * extra field, {@link #EXTRA_KEY_EVENT}, containing the key event that
diff --git a/core/java/com/android/internal/statusbar/IStatusBar.aidl b/core/java/com/android/internal/statusbar/IStatusBar.aidl
index 632285c..3854923 100644
--- a/core/java/com/android/internal/statusbar/IStatusBar.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBar.aidl
@@ -78,5 +78,14 @@
      * @param source the identifier for the gesture, see {@link StatusBarManager}
      */
     void onCameraLaunchGestureDetected(int source);
-}
 
+    /**
+     * Request picture-in-picture.
+     *
+     * <p>
+     * This is called when an user presses picture-in-picture key or equivalent.
+     * TV device may start picture-in-picture from foreground activity if there's none.
+     * Picture-in-picture overlay menu will be shown instead otherwise.
+     */
+    void requestTvPictureInPicture();
+}
diff --git a/core/java/com/android/internal/statusbar/IStatusBarService.aidl b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
index 32de45c..a6fd9f9 100644
--- a/core/java/com/android/internal/statusbar/IStatusBarService.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
@@ -93,4 +93,14 @@
     void appTransitionStarting(long statusBarAnimationsStartTime, long statusBarAnimationsDuration);
 
     void startAssist(in Bundle args);
+
+    /**
+     * Request picture-in-picture.
+     *
+     * <p>
+     * This is called when an user presses picture-in-picture key or equivalent.
+     * TV device may start picture-in-picture from foreground activity if there's none.
+     * Picture-in-picture overlay menu will be shown instead otherwise.
+     */
+    void requestTvPictureInPicture();
 }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 56c3fc8..dd7f1f7 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -226,8 +226,6 @@
     <protected-broadcast android:name="android.intent.action.MEDIA_UNMOUNTABLE" />
     <protected-broadcast android:name="android.intent.action.MEDIA_EJECT" />
 
-    <protected-broadcast android:name="android.intent.action.PICTURE_IN_PICTURE_BUTTON" />
-
     <protected-broadcast android:name="android.net.conn.CAPTIVE_PORTAL" />
     <protected-broadcast android:name="android.net.conn.CONNECTIVITY_CHANGE" />
     <!-- @deprecated.  Only {@link android.net.ConnectivityManager.CONNECTIVITY_ACTION} is sent. -->
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
index cc26223..05a40b3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
@@ -39,31 +39,32 @@
     private static final int OP_SET_ICON    = 1;
     private static final int OP_REMOVE_ICON = 2;
 
-    private static final int MSG_ICON                       = 1 << MSG_SHIFT;
-    private static final int MSG_DISABLE                    = 2 << MSG_SHIFT;
-    private static final int MSG_EXPAND_NOTIFICATIONS       = 3 << MSG_SHIFT;
-    private static final int MSG_COLLAPSE_PANELS            = 4 << MSG_SHIFT;
-    private static final int MSG_EXPAND_SETTINGS            = 5 << MSG_SHIFT;
-    private static final int MSG_SET_SYSTEMUI_VISIBILITY    = 6 << MSG_SHIFT;
-    private static final int MSG_TOP_APP_WINDOW_CHANGED     = 7 << MSG_SHIFT;
-    private static final int MSG_SHOW_IME_BUTTON            = 8 << MSG_SHIFT;
-    private static final int MSG_TOGGLE_RECENT_APPS         = 9 << MSG_SHIFT;
-    private static final int MSG_PRELOAD_RECENT_APPS        = 10 << MSG_SHIFT;
-    private static final int MSG_CANCEL_PRELOAD_RECENT_APPS = 11 << MSG_SHIFT;
-    private static final int MSG_SET_WINDOW_STATE           = 12 << MSG_SHIFT;
-    private static final int MSG_SHOW_RECENT_APPS           = 13 << MSG_SHIFT;
-    private static final int MSG_HIDE_RECENT_APPS           = 14 << MSG_SHIFT;
-    private static final int MSG_BUZZ_BEEP_BLINKED          = 15 << MSG_SHIFT;
-    private static final int MSG_NOTIFICATION_LIGHT_OFF     = 16 << MSG_SHIFT;
-    private static final int MSG_NOTIFICATION_LIGHT_PULSE   = 17 << MSG_SHIFT;
-    private static final int MSG_SHOW_SCREEN_PIN_REQUEST    = 18 << MSG_SHIFT;
-    private static final int MSG_APP_TRANSITION_PENDING     = 19 << MSG_SHIFT;
-    private static final int MSG_APP_TRANSITION_CANCELLED   = 20 << MSG_SHIFT;
-    private static final int MSG_APP_TRANSITION_STARTING    = 21 << MSG_SHIFT;
-    private static final int MSG_ASSIST_DISCLOSURE          = 22 << MSG_SHIFT;
-    private static final int MSG_START_ASSIST               = 23 << MSG_SHIFT;
-    private static final int MSG_CAMERA_LAUNCH_GESTURE      = 24 << MSG_SHIFT;
-    private static final int MSG_TOGGLE_KEYBOARD_SHORTCUTS  = 25 << MSG_SHIFT;
+    private static final int MSG_ICON                          = 1 << MSG_SHIFT;
+    private static final int MSG_DISABLE                       = 2 << MSG_SHIFT;
+    private static final int MSG_EXPAND_NOTIFICATIONS          = 3 << MSG_SHIFT;
+    private static final int MSG_COLLAPSE_PANELS               = 4 << MSG_SHIFT;
+    private static final int MSG_EXPAND_SETTINGS               = 5 << MSG_SHIFT;
+    private static final int MSG_SET_SYSTEMUI_VISIBILITY       = 6 << MSG_SHIFT;
+    private static final int MSG_TOP_APP_WINDOW_CHANGED        = 7 << MSG_SHIFT;
+    private static final int MSG_SHOW_IME_BUTTON               = 8 << MSG_SHIFT;
+    private static final int MSG_TOGGLE_RECENT_APPS            = 9 << MSG_SHIFT;
+    private static final int MSG_PRELOAD_RECENT_APPS           = 10 << MSG_SHIFT;
+    private static final int MSG_CANCEL_PRELOAD_RECENT_APPS    = 11 << MSG_SHIFT;
+    private static final int MSG_SET_WINDOW_STATE              = 12 << MSG_SHIFT;
+    private static final int MSG_SHOW_RECENT_APPS              = 13 << MSG_SHIFT;
+    private static final int MSG_HIDE_RECENT_APPS              = 14 << MSG_SHIFT;
+    private static final int MSG_BUZZ_BEEP_BLINKED             = 15 << MSG_SHIFT;
+    private static final int MSG_NOTIFICATION_LIGHT_OFF        = 16 << MSG_SHIFT;
+    private static final int MSG_NOTIFICATION_LIGHT_PULSE      = 17 << MSG_SHIFT;
+    private static final int MSG_SHOW_SCREEN_PIN_REQUEST       = 18 << MSG_SHIFT;
+    private static final int MSG_APP_TRANSITION_PENDING        = 19 << MSG_SHIFT;
+    private static final int MSG_APP_TRANSITION_CANCELLED      = 20 << MSG_SHIFT;
+    private static final int MSG_APP_TRANSITION_STARTING       = 21 << MSG_SHIFT;
+    private static final int MSG_ASSIST_DISCLOSURE             = 22 << MSG_SHIFT;
+    private static final int MSG_START_ASSIST                  = 23 << MSG_SHIFT;
+    private static final int MSG_CAMERA_LAUNCH_GESTURE         = 24 << MSG_SHIFT;
+    private static final int MSG_TOGGLE_KEYBOARD_SHORTCUTS     = 25 << MSG_SHIFT;
+    private static final int MSG_REQUEST_TV_PICTURE_IN_PICTURE = 26 << MSG_SHIFT;
 
     public static final int FLAG_EXCLUDE_NONE = 0;
     public static final int FLAG_EXCLUDE_SEARCH_PANEL = 1 << 0;
@@ -109,6 +110,7 @@
         public void showAssistDisclosure();
         public void startAssist(Bundle args);
         public void onCameraLaunchGestureDetected(int source);
+        public void requestTvPictureInPicture();
     }
 
     public CommandQueue(Callbacks callbacks) {
@@ -230,6 +232,14 @@
         }
     }
 
+    @Override
+    public void requestTvPictureInPicture() {
+        synchronized (mLock) {
+            mHandler.removeMessages(MSG_REQUEST_TV_PICTURE_IN_PICTURE);
+            mHandler.obtainMessage(MSG_REQUEST_TV_PICTURE_IN_PICTURE).sendToTarget();
+        }
+    }
+
     public void setWindowState(int window, int state) {
         synchronized (mLock) {
             // don't coalesce these
@@ -398,6 +408,9 @@
                 case MSG_CAMERA_LAUNCH_GESTURE:
                     mCallbacks.onCameraLaunchGestureDetected(msg.arg1);
                     break;
+                case MSG_REQUEST_TV_PICTURE_IN_PICTURE:
+                    mCallbacks.requestTvPictureInPicture();
+                    break;
             }
         }
     }
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 6fa1f5df..c65110e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -4241,6 +4241,11 @@
         }
     }
 
+    @Override
+    public void requestTvPictureInPicture() {
+        // no-op.
+    }
+
     public void notifyFpAuthModeChanged() {
         updateDozing();
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
index 0406ae3..f322348 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
@@ -25,6 +25,7 @@
 import com.android.systemui.statusbar.ActivatableNotificationView;
 import com.android.systemui.statusbar.BaseStatusBar;
 import com.android.systemui.statusbar.NotificationData;
+import com.android.systemui.tv.pip.PipManager;
 
 /*
  * Status bar implementation for "large screen" products that mostly present no on-screen nav
@@ -170,6 +171,11 @@
     }
 
     @Override
+    public void requestTvPictureInPicture() {
+        PipManager.getInstance().requestTvPictureInPicture();
+    }
+
+    @Override
     protected void updateHeadsUp(String key, NotificationData.Entry entry, boolean shouldPeek,
             boolean alertAgain) {
     }
diff --git a/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java b/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
index e947ed5..bbc60b1 100644
--- a/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/tv/pip/PipManager.java
@@ -105,14 +105,7 @@
         @Override
         public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
-            if (Intent.ACTION_PICTURE_IN_PICTURE_BUTTON.equals(action)) {
-                if (DEBUG) Log.d(TAG, "PIP button pressed");
-                if (!hasPipTasks()) {
-                    startPip();
-                } else if (mState == STATE_PIP_OVERLAY) {
-                    showPipMenu();
-                }
-            } else if (Intent.ACTION_MEDIA_RESOURCE_GRANTED.equals(action)) {
+            if (Intent.ACTION_MEDIA_RESOURCE_GRANTED.equals(action)) {
                 String[] packageNames = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
                 int resourceType = intent.getIntExtra(Intent.EXTRA_MEDIA_RESOURCE_TYPE,
                         INVALID_RESOURCE_TYPE);
@@ -151,18 +144,29 @@
             Log.e(TAG, "registerTaskStackListener failed", e);
         }
         IntentFilter intentFilter = new IntentFilter();
-        intentFilter.addAction(Intent.ACTION_PICTURE_IN_PICTURE_BUTTON);
         intentFilter.addAction(Intent.ACTION_MEDIA_RESOURCE_GRANTED);
         mContext.registerReceiver(mBroadcastReceiver, intentFilter);
     }
 
+    /**
+     * Request PIP.
+     * It could either start PIP if there's none, and show PIP menu otherwise.
+     */
+    public void requestTvPictureInPicture() {
+        if (DEBUG) Log.d(TAG, "requestTvPictureInPicture()");
+        if (!hasPipTasks()) {
+            startPip();
+        } else if (mState == STATE_PIP_OVERLAY) {
+            showPipMenu();
+        }
+    }
+
     private void startPip() {
         try {
             mActivityManager.moveTopActivityToPinnedStack(FULLSCREEN_WORKSPACE_STACK_ID, mPipBound);
         } catch (RemoteException|IllegalArgumentException e) {
             Log.e(TAG, "moveTopActivityToPinnedStack failed", e);
         }
-
     }
 
     /**
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 0b1354a..43b82e9 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -658,6 +658,7 @@
     private static final int MSG_POWER_LONG_PRESS = 14;
     private static final int MSG_UPDATE_DREAMING_SLEEP_TOKEN = 15;
     private static final int MSG_REQUEST_TRANSIENT_BARS = 16;
+    private static final int MSG_REQUEST_TV_PICTURE_IN_PICTURE = 17;
 
     private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0;
     private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1;
@@ -719,6 +720,9 @@
                         requestTransientBars(targetBar);
                     }
                     break;
+                case MSG_REQUEST_TV_PICTURE_IN_PICTURE:
+                    requestTvPictureInPictureInternal();
+                    break;
             }
         }
     }
@@ -1337,7 +1341,7 @@
                 launchAssistAction(null, deviceId);
                 break;
             case LONG_PRESS_HOME_PICTURE_IN_PICTURE:
-                handlePipKey(event);
+                requestTvPictureInPicture(event);
                 break;
             default:
                 Log.w(TAG, "Not defined home long press behavior: " + mLongPressOnHomeBehavior);
@@ -1352,11 +1356,25 @@
         }
     }
 
-    private void handlePipKey(KeyEvent event) {
-        if (DEBUG_INPUT) Log.d(TAG, "handlePipKey event=" + event);
-        Intent intent = new Intent(Intent.ACTION_PICTURE_IN_PICTURE_BUTTON);
-        intent.putExtra(Intent.EXTRA_KEY_EVENT, event);
-        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
+    private void requestTvPictureInPicture(KeyEvent event) {
+        if (DEBUG_INPUT) Log.d(TAG, "requestTvPictureInPicture event=" + event);
+        mHandler.removeMessages(MSG_REQUEST_TV_PICTURE_IN_PICTURE);
+        Message msg = mHandler.obtainMessage(MSG_REQUEST_TV_PICTURE_IN_PICTURE);
+        msg.setAsynchronous(true);
+        msg.sendToTarget();
+    }
+
+    private void requestTvPictureInPictureInternal() {
+        try {
+            IStatusBarService statusbar = getStatusBarService();
+            if (statusbar != null) {
+                statusbar.requestTvPictureInPicture();
+            }
+        } catch (RemoteException|IllegalArgumentException e) {
+            Slog.e(TAG, "Cannot handle picture-in-picture key", e);
+            // re-acquire status bar service next time it is needed.
+            mStatusBarService = null;
+        }
     }
 
     private final Runnable mHomeDoubleTapTimeoutRunnable = new Runnable() {
@@ -1648,14 +1666,16 @@
      * eg. Disable long press on home goes to recents on sw600dp.
      */
     private void readConfigurationDependentBehaviors() {
-        mLongPressOnHomeBehavior = mContext.getResources().getInteger(
+        final Resources res = mContext.getResources();
+
+        mLongPressOnHomeBehavior = res.getInteger(
                 com.android.internal.R.integer.config_longPressOnHomeBehavior);
         if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING ||
                 mLongPressOnHomeBehavior > LAST_LONG_PRESS_HOME_BEHAVIOR) {
             mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
         }
 
-        mDoubleTapOnHomeBehavior = mContext.getResources().getInteger(
+        mDoubleTapOnHomeBehavior = res.getInteger(
                 com.android.internal.R.integer.config_doubleTapOnHomeBehavior);
         if (mDoubleTapOnHomeBehavior < DOUBLE_TAP_HOME_NOTHING ||
                 mDoubleTapOnHomeBehavior > DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
@@ -5337,7 +5357,7 @@
             case KeyEvent.KEYCODE_WINDOW: {
                 if (mShortPressWindowBehavior == SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE) {
                     if (!down) {
-                        handlePipKey(event);
+                        requestTvPictureInPicture(event);
                     }
                     result &= ~ACTION_PASS_TO_USER;
                 }
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index 2a1f46e..9e2ba95 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -491,6 +491,15 @@
     }
 
     @Override
+    public void requestTvPictureInPicture() {
+        if (mBar != null) {
+            try {
+                mBar.requestTvPictureInPicture();
+            } catch (RemoteException ex) {}
+        }
+    }
+
+    @Override
     public void setCurrentUser(int newUserId) {
         if (SPEW) Slog.d(TAG, "Setting current user to user " + newUserId);
         mCurrentUserId = newUserId;