Revert "VR: Ensure we remove black overlay if VR is exited while entering."

This reverts commit 9f8158c12189567f8b9f4bcb44dd3cfc68ecd470.

Reason for revert: Culprit of failed VR tests https://ci.chromium.org/p/chromium/builders/luci.chromium.ci/Nougat%20Phone%20Tester/6884

Original change's description:
> VR: Ensure we remove black overlay if VR is exited while entering.
> 
> This fixes a failure mode where we shutdownVR after handling the VR NFC
> broadcast, and fail to properly cancel VR entry.
> 
> Also does some other random cleanup of comments/visibility.
> 
> Bug: 862829
> Change-Id: Ic382692d7255aa5893391a602a6c949b4b4d498b
> Reviewed-on: https://chromium-review.googlesource.com/1138726
> Reviewed-by: Tibor Goldschwendt <tiborg@chromium.org>
> Commit-Queue: Michael Thiessen <mthiesse@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#575388}

TBR=mthiesse@chromium.org,tiborg@chromium.org

Change-Id: Ibe67ee8c09dc44ac34d40c3eaf890884b400fc24
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 862829
Reviewed-on: https://chromium-review.googlesource.com/1140813
Reviewed-by: Brian Sheedy <bsheedy@chromium.org>
Commit-Queue: Brian Sheedy <bsheedy@chromium.org>
Cr-Commit-Position: refs/heads/master@{#575725}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrAlertDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrAlertDialog.java
index 41f83c3..0d1b7ab 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrAlertDialog.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrAlertDialog.java
@@ -16,15 +16,19 @@
  * This class implements a VrAlertDialog which is similar to Android AlertDialog in VR.
  */
 public class VrAlertDialog extends AlertDialog {
+    private VrDialogManager mVrDialogManager;
     private ModalDialogManager mModalDialogManager;
     private ModalDialogView mModalDialogView;
+    private boolean mIsShowing;
     private CharSequence mMessage;
     private DialogButton mButtonPositive;
     private DialogButton mButtonNegative;
     protected View mView;
 
-    public VrAlertDialog(Context context, ModalDialogManager modalDialogManager) {
+    public VrAlertDialog(Context context, VrDialogManager vrDialogManager,
+            ModalDialogManager modalDialogManager) {
         super(context);
+        mVrDialogManager = vrDialogManager;
         mModalDialogManager = modalDialogManager;
     }
 
@@ -56,6 +60,7 @@
     public void show() {
         mModalDialogView = createView();
         mModalDialogManager.showDialog(mModalDialogView, ModalDialogManager.APP_MODAL);
+        mIsShowing = true;
     }
 
     /**
@@ -98,6 +103,7 @@
      */
     @Override
     public void dismiss() {
+        mIsShowing = false;
         mModalDialogManager.cancelDialog(mModalDialogView);
     }
 
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrFirstRunActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrFirstRunActivity.java
index 40fd1b2..b98b591 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrFirstRunActivity.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrFirstRunActivity.java
@@ -24,6 +24,8 @@
 
     private static final BooleanHistogramSample sFreNotCompleteBrowserHistogram =
             new BooleanHistogramSample("VRFreNotComplete.Browser");
+    private static final BooleanHistogramSample sFreNotCompleteAutopresentHistogram =
+            new BooleanHistogramSample("VRFreNotComplete.WebVRAutopresent");
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java
index 2beeed4..b20389a 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java
@@ -42,7 +42,6 @@
 import org.chromium.base.Log;
 import org.chromium.base.PackageUtils;
 import org.chromium.base.ThreadUtils;
-import org.chromium.base.VisibleForTesting;
 import org.chromium.base.annotations.CalledByNative;
 import org.chromium.base.annotations.JNINamespace;
 import org.chromium.base.library_loader.LibraryLoader;
@@ -207,7 +206,6 @@
 
     private static final List<VrModeObserver> sVrModeObservers = new ArrayList<>();
 
-    @VisibleForTesting
     protected boolean mTestWorkaroundDontCancelVrEntryOnResume;
 
     private long mNativeVrShellDelegate;
@@ -908,7 +906,7 @@
     }
 
     /**
-     *  @return Whether or not VR is enabled in this build.
+     *  @return Whether or not VR is supported on this platform.
      */
     /* package */ static boolean isVrEnabled() {
         return getVrClassesWrapper() != null;
@@ -1044,8 +1042,8 @@
         // If an activity isn't resumed at the point, it must have been paused.
         mPaused = ApplicationStatus.getStateForActivity(activity) != ActivityState.RESUMED;
         mVisible = activity.hasWindowFocus();
-        mNativeVrShellDelegate = nativeInit();
         updateVrSupportLevel(null);
+        mNativeVrShellDelegate = nativeInit();
         mFeedbackFrequency = VrFeedbackStatus.getFeedbackFrequency();
         ensureLifecycleObserverInitialized();
         if (!mPaused) onResume();
@@ -1161,7 +1159,6 @@
                 buttonText, null, true);
     }
 
-    @VisibleForTesting
     protected boolean isVrBrowsingEnabled() {
         return isVrBrowsingEnabled(mActivity, getVrSupportLevel());
     }
@@ -1218,11 +1215,16 @@
     }
 
     private void enterVr(final boolean tentativeWebVrMode) {
-        // We should only enter VR when we're the resumed Activity or our changes to things like
-        // system UI flags might get lost.
+        // We can't enter VR before the application resumes, or we encounter bizarre crashes
+        // related to gpu surfaces.
+        // TODO(mthiesse): Is the above comment still accurate? It may have been tied to our HTML
+        // UI which is gone.
         assert !mPaused;
-        assert mNativeVrShellDelegate != 0;
         if (mInVr) return;
+        if (mNativeVrShellDelegate == 0) {
+            cancelPendingVrEntry();
+            return;
+        }
         mInVr = true;
         setVrModeEnabled(mActivity, true);
 
@@ -1242,11 +1244,11 @@
         mExitedDueToUnsupportedMode = false;
 
         addVrViews();
+        boolean webVrMode = mRequestedWebVr || tentativeWebVrMode;
         // Make sure that assets component is registered when creating native VR shell.
         if (!sRegisteredVrAssetsComponent) {
             registerVrAssetsComponentIfDaydreamUser(isDaydreamCurrentViewer());
         }
-        boolean webVrMode = mRequestedWebVr || tentativeWebVrMode;
         mVrShell.initializeNative(webVrMode, getVrClassesWrapper().bootsToVr());
         mVrShell.setWebVrModeEnabled(webVrMode);
 
@@ -1288,9 +1290,6 @@
         // Nothing to do if we were launched by an internal intent.
         if (mInternalIntentUsedToStartVr) {
             mInternalIntentUsedToStartVr = false;
-            // This is extremely unlikely in practice. Some code must have called shutdownVR() while
-            // we were entering VR through NFC insertion.
-            if (!mDonSucceeded) cancelPendingVrEntry();
             return;
         }
 
@@ -1545,7 +1544,6 @@
         return true;
     }
 
-    @VisibleForTesting
     protected void onResume() {
         if (DEBUG_LOGS) Log.i(TAG, "onResume");
         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) return;
@@ -1666,7 +1664,7 @@
         if (mInVr) mVrShell.pause();
     }
 
-    private void onPause() {
+    protected void onPause() {
         if (DEBUG_LOGS) Log.i(TAG, "onPause");
         mPaused = true;
         if (mCancellingEntryAnimation) return;
@@ -1757,9 +1755,13 @@
 
         mShowingDaydreamDoff = false;
 
-        if (mShowingDoffForGvrUpdate) mShowVrServicesUpdatePrompt = success;
+        if (mShowingDoffForGvrUpdate) {
+            mShowVrServicesUpdatePrompt = success;
+        }
 
-        if (success) shutdownVr(true /* disableVrMode */, true /* stayingInChrome */);
+        if (success) {
+            shutdownVr(true /* disableVrMode */, true /* stayingInChrome */);
+        }
 
         callOnExitVrRequestListener(success);
         mShowingDoffForGvrUpdate = false;
@@ -1776,7 +1778,8 @@
     @CalledByNative
     private void setListeningForWebVrActivate(boolean listening) {
         if (DEBUG_LOGS) Log.i(TAG, "WebVR page listening for vrdisplayactivate: " + listening);
-        // Non-Daydream devices do not have the concept of activation.
+        // Non-Daydream devices may not have the concept of display activate. So disable
+        // mListeningForWebVrActivate for them.
         if (getVrSupportLevel() != VrSupportLevel.VR_DAYDREAM) return;
         if (mListeningForWebVrActivate == listening) return;
         mListeningForWebVrActivate = listening;
@@ -1821,7 +1824,7 @@
     /**
      * Exits VR Shell, performing all necessary cleanup.
      */
-    private void shutdownVr(boolean disableVrMode, boolean stayingInChrome) {
+    protected void shutdownVr(boolean disableVrMode, boolean stayingInChrome) {
         if (DEBUG_LOGS) Log.i(TAG, "shuttdown VR");
         cancelPendingVrEntry();
 
@@ -1938,13 +1941,11 @@
                 GVR_KEYBOARD_UPDATE_RESULT);
     }
 
-    @VisibleForTesting
     protected boolean canLaunch2DIntentsInternal() {
         return getVrClassesWrapper().supports2dInVr()
                 && !sVrModeEnabledActivitys.contains(sInstance.mActivity);
     }
 
-    @VisibleForTesting
     protected boolean createVrShell() {
         assert mVrShell == null;
         if (getVrClassesWrapper() == null) return false;
@@ -1971,7 +1972,6 @@
         mActivity.onEnterVr();
     }
 
-    @VisibleForTesting
     protected boolean isBlackOverlayVisible() {
         View overlay = mActivity.getWindow().findViewById(R.id.vr_overlay_view);
         return overlay != null;
@@ -1997,7 +1997,6 @@
     /**
      * @param api The VrDaydreamApi object this delegate will use instead of the default one
      */
-    @VisibleForTesting
     protected void overrideDaydreamApi(VrDaydreamApi api) {
         sVrDaydreamApi = api;
     }
@@ -2005,7 +2004,6 @@
     /**
      * @return The VrShell for the VrShellDelegate instance
      */
-    @VisibleForTesting
     protected VrShell getVrShell() {
         return mVrShell;
     }
@@ -2013,7 +2011,6 @@
     /**
      * @param versionChecker The VrCoreVersionChecker object this delegate will use
      */
-    @VisibleForTesting
     protected void overrideVrCoreVersionChecker(VrCoreVersionChecker versionChecker) {
         sVrCoreVersionChecker = versionChecker;
         updateVrSupportLevel(null);
@@ -2022,30 +2019,24 @@
     /**
      * @param frequency Sets how often to show the feedback prompt.
      */
-    @VisibleForTesting
     protected void setFeedbackFrequency(int frequency) {
         mFeedbackFrequency = frequency;
     }
 
-    @VisibleForTesting
     protected boolean isListeningForWebVrActivate() {
         return mListeningForWebVrActivate;
     }
 
-    @VisibleForTesting
     protected boolean isVrEntryComplete() {
         return mInVr && !mProbablyInDon;
     }
 
-    @VisibleForTesting
     protected boolean isShowingDoff() {
         return mShowingDaydreamDoff;
     }
 
-    @VisibleForTesting
     protected void onBroadcastReceived() {}
 
-    @VisibleForTesting
     protected void setExpectingIntent(boolean expectingIntent) {}
 
     /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrToast.java b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrToast.java
index 4ec17fa93..ec9edf9 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrToast.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrToast.java
@@ -12,6 +12,7 @@
 /**
  * This class implements a Toast which is similar to Android Toast in VR.
  */
+
 public class VrToast extends android.widget.Toast {
     private VrToastManager mVrToastManager;
 
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrUiWidgetFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrUiWidgetFactory.java
index 5b56053..8e66e5e 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrUiWidgetFactory.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrUiWidgetFactory.java
@@ -36,7 +36,7 @@
 
     @Override
     public AlertDialog createAlertDialog(Context context) {
-        return new VrAlertDialog(context, mModalDialogManager);
+        return new VrAlertDialog(context, mVrShell, mModalDialogManager);
     }
 
     @Override
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/TestVrShellDelegate.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/TestVrShellDelegate.java
index a79186f..a196f91 100644
--- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/TestVrShellDelegate.java
+++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/TestVrShellDelegate.java
@@ -48,6 +48,11 @@
         return TestVrShellDelegate.getInstance().getVrShell();
     }
 
+    @Override
+    public void shutdownVr(boolean disableVrMode, boolean stayingInChrome) {
+        super.shutdownVr(disableVrMode, stayingInChrome);
+    }
+
     public void overrideDaydreamApiForTesting(VrDaydreamApi api) {
         super.overrideDaydreamApi(api);
     }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/TransitionUtils.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/TransitionUtils.java
index 2e1323a..1b7f6cec 100644
--- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/TransitionUtils.java
+++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/util/TransitionUtils.java
@@ -69,7 +69,8 @@
         ThreadUtils.runOnUiThreadBlocking(new Runnable() {
             @Override
             public void run() {
-                VrShellDelegate.forceExitVrImmediately();
+                VrShellDelegateUtils.getDelegateInstance().shutdownVr(
+                        true /* disableVrMode */, true /* stayingInChrome */);
             }
         });
     }