Merge "Fix SocialWidgetConfigureActivity contact-picker double-launch." into jb-dev
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 33da473..996bc78 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -121,7 +121,7 @@
             android:launchMode="singleTask"
             android:clearTaskOnLaunch="true"
             android:icon="@mipmap/ic_launcher_phone"
-            android:screenOrientation="nosensor"
+            android:screenOrientation="portrait"
             android:enabled="@*android:bool/config_voice_capable"
             android:taskAffinity="android.task.contacts.phone"
             android:windowSoftInputMode="stateAlwaysHidden|adjustNothing">
diff --git a/src/com/android/contacts/dialog/ClearFrequentsDialog.java b/src/com/android/contacts/dialog/ClearFrequentsDialog.java
index ecb1a27..4aeaf1c 100644
--- a/src/com/android/contacts/dialog/ClearFrequentsDialog.java
+++ b/src/com/android/contacts/dialog/ClearFrequentsDialog.java
@@ -45,6 +45,9 @@
         final OnClickListener okListener = new OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
+                final IndeterminateProgressDialog progressDialog = IndeterminateProgressDialog.show(
+                        getFragmentManager(), getString(R.string.clearFrequentsProgress_title),
+                        null, 500);
                 final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                     @Override
                     protected Void doInBackground(Void... params) {
@@ -52,8 +55,13 @@
                                 null, null);
                         return null;
                     }
+
+                    @Override
+                    protected void onPostExecute(Void result) {
+                        progressDialog.dismiss();
+                    }
                 };
-                task.execute();
+                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
             }
         };
         return new AlertDialog.Builder(getActivity())
diff --git a/src/com/android/contacts/dialog/IndeterminateProgressDialog.java b/src/com/android/contacts/dialog/IndeterminateProgressDialog.java
new file mode 100644
index 0000000..21cd4bb
--- /dev/null
+++ b/src/com/android/contacts/dialog/IndeterminateProgressDialog.java
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2012 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.contacts.dialog;
+
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.app.FragmentManager;
+import android.app.ProgressDialog;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.os.Handler;
+
+/**
+ * Indeterminate progress dialog wrapped up in a DialogFragment to work even when the device
+ * orientation is changed. Currently, only supports adding a title and/or message to the progress
+ * dialog.  There is an additional parameter of the minimum amount of time to display the progress
+ * dialog even after a call to dismiss the dialog {@link #dismiss()} or
+ * {@link #dismissAllowingStateLoss()}.
+ * <p>
+ * To create and show the progress dialog, use
+ * {@link #show(FragmentManager, CharSequence, CharSequence, long)} and retain the reference to the
+ * IndeterminateProgressDialog instance.
+ * <p>
+ * To dismiss the dialog, use {@link #dismiss()} or {@link #dismissAllowingStateLoss()} on the
+ * instance.  The instance returned by
+ * {@link #show(FragmentManager, CharSequence, CharSequence, long)} is guaranteed to be valid
+ * after a device orientation change because the {@link #setRetainInstance(boolean)} is called
+ * internally with true.
+ */
+public class IndeterminateProgressDialog extends DialogFragment {
+    private static final String TAG = IndeterminateProgressDialog.class.getSimpleName();
+
+    private CharSequence mTitle;
+    private CharSequence mMessage;
+    private long mMinDisplayTime;
+    private long mShowTime = 0;
+    private boolean mActivityReady = false;
+    private Dialog mOldDialog;
+    private final Handler mHandler = new Handler();
+    private boolean mCalledSuperDismiss = false;
+    private boolean mAllowStateLoss;
+    private final Runnable mDismisser = new Runnable() {
+        @Override
+        public void run() {
+            superDismiss();
+        }
+    };
+
+    /**
+     * Creates and shows an indeterminate progress dialog.  Once the progress dialog is shown, it
+     * will be shown for at least the minDisplayTime (in milliseconds), so that the progress dialog
+     * does not flash in and out to quickly.
+     */
+    public static IndeterminateProgressDialog show(FragmentManager fragmentManager,
+            CharSequence title, CharSequence message, long minDisplayTime) {
+        IndeterminateProgressDialog dialogFragment = new IndeterminateProgressDialog();
+        dialogFragment.mTitle = title;
+        dialogFragment.mMessage = message;
+        dialogFragment.mMinDisplayTime = minDisplayTime;
+        dialogFragment.show(fragmentManager, TAG);
+        dialogFragment.mShowTime = System.currentTimeMillis();
+        dialogFragment.setCancelable(false);
+
+        return dialogFragment;
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setRetainInstance(true);
+    }
+
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+        // Create the progress dialog and set its properties
+        final ProgressDialog dialog = new ProgressDialog(getActivity());
+        dialog.setIndeterminate(true);
+        dialog.setIndeterminateDrawable(null);
+        dialog.setTitle(mTitle);
+        dialog.setMessage(mMessage);
+
+        return dialog;
+    }
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        mActivityReady = true;
+
+        // Check if superDismiss() had been called before.  This can happen if in a long
+        // running operation, the user hits the home button and closes this fragment's activity.
+        // Upon returning, we want to dismiss this progress dialog fragment.
+        if (mCalledSuperDismiss) {
+            superDismiss();
+        }
+    }
+
+    @Override
+    public void onStop() {
+        super.onStop();
+        mActivityReady = false;
+    }
+
+    /**
+     * There is a race condition that is not handled properly by the DialogFragment class.
+     * If we don't check that this onDismiss callback isn't for the old progress dialog from before
+     * the device orientation change, then this will cause the newly created dialog after the
+     * orientation change to be dismissed immediately.
+     */
+    @Override
+    public void onDismiss(DialogInterface dialog) {
+        if (mOldDialog != null && mOldDialog == dialog) {
+            // This is the callback from the old progress dialog that was already dismissed before
+            // the device orientation change, so just ignore it.
+            return;
+        }
+        super.onDismiss(dialog);
+    }
+
+    /**
+     * Save the old dialog that is about to get destroyed in case this is due to a change
+     * in device orientation.  This will allow us to intercept the callback to
+     * {@link #onDismiss(DialogInterface)} in case the callback happens after a new progress dialog
+     * instance was created.
+     */
+    @Override
+    public void onDestroyView() {
+        mOldDialog = getDialog();
+        super.onDestroyView();
+    }
+
+    /**
+     * This tells the progress dialog to dismiss itself after guaranteeing to be shown for the
+     * specified time in {@link #show(FragmentManager, CharSequence, CharSequence, long)}.
+     */
+    @Override
+    public void dismiss() {
+        mAllowStateLoss = false;
+        dismissWhenReady();
+    }
+
+    /**
+     * This tells the progress dialog to dismiss itself (with state loss) after guaranteeing to be
+     * shown for the specified time in
+     * {@link #show(FragmentManager, CharSequence, CharSequence, long)}.
+     */
+    @Override
+    public void dismissAllowingStateLoss() {
+        mAllowStateLoss = true;
+        dismissWhenReady();
+    }
+
+    /**
+     * Tells the progress dialog to dismiss itself after guaranteeing that the dialog had been
+     * showing for at least the minimum display time as set in
+     * {@link #show(FragmentManager, CharSequence, CharSequence, long)}.
+     */
+    private void dismissWhenReady() {
+        // Compute how long the dialog has been showing
+        final long shownTime = System.currentTimeMillis() - mShowTime;
+        if (shownTime >= mMinDisplayTime) {
+            // dismiss immediately
+            mHandler.post(mDismisser);
+        } else {
+            // Need to wait some more, so compute the amount of time to sleep.
+            final long sleepTime = mMinDisplayTime - shownTime;
+            mHandler.postDelayed(mDismisser, sleepTime);
+        }
+    }
+
+    /**
+     * Actually dismiss the dialog fragment.
+     */
+    private void superDismiss() {
+        mCalledSuperDismiss = true;
+        if (mActivityReady) {
+            // The fragment is either in onStart or past it, but has not gotten to onStop yet.
+            // It is safe to dismiss this dialog fragment.
+            if (mAllowStateLoss) {
+                super.dismissAllowingStateLoss();
+            } else {
+                super.dismiss();
+            }
+        }
+        // If mActivityReady is false, then this dialog fragment has already passed the onStop
+        // state. This can happen if the user hit the 'home' button before this dialog fragment was
+        // dismissed or if there is a configuration change.
+        // In the event that this dialog fragment is re-attached and reaches onStart (e.g.,
+        // because the user returns to this fragment's activity or the device configuration change
+        // has re-attached this dialog fragment), because the mCalledSuperDismiss flag was set to
+        // true, this dialog fragment will be dismissed within onStart.  So, there's nothing else
+        // that needs to be done.
+    }
+}
diff --git a/src/com/android/contacts/quickcontact/FloatingChildLayout.java b/src/com/android/contacts/quickcontact/FloatingChildLayout.java
index 6302c5d..dca738c 100644
--- a/src/com/android/contacts/quickcontact/FloatingChildLayout.java
+++ b/src/com/android/contacts/quickcontact/FloatingChildLayout.java
@@ -23,15 +23,13 @@
 import android.content.Context;
 import android.content.res.Resources;
 import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
 import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.Drawable;
 import android.graphics.drawable.TransitionDrawable;
-import android.os.Handler;
 import android.util.AttributeSet;
 import android.util.Log;
 import android.view.MotionEvent;
 import android.view.View;
-import android.view.ViewPropertyAnimator;
 import android.view.animation.AnimationUtils;
 import android.widget.FrameLayout;
 import android.widget.PopupWindow;
@@ -53,11 +51,30 @@
     private static final String TAG = "FloatingChildLayout";
     private int mFixedTopPosition;
     private View mChild;
-    private boolean mIsShowingChild;
     private Rect mTargetScreen = new Rect();
     private final int mAnimationDuration;
     private final TransitionDrawable mBackground;
 
+    /** The phase of the background dim. This is one of the values of {@link BackgroundPhase}  */
+    private int mBackgroundPhase = BackgroundPhase.BEFORE;
+
+    private interface BackgroundPhase {
+        public static final int BEFORE = 0;
+        public static final int APPEARING_OR_VISIBLE = 1;
+        public static final int DISAPPEARING_OR_GONE = 3;
+    }
+
+    /** The phase of the contents window. This is one of the values of {@link ForegroundPhase}  */
+    private int mForegroundPhase = ForegroundPhase.BEFORE;
+
+    private interface ForegroundPhase {
+        public static final int BEFORE = 0;
+        public static final int APPEARING = 1;
+        public static final int IDLE = 2;
+        public static final int DISAPPEARING = 3;
+        public static final int AFTER = 4;
+    }
+
     // Black, 50% alpha as per the system default.
     private static final int DIM_BACKGROUND_COLOR = 0x7F000000;
 
@@ -83,8 +100,6 @@
         mChild.setScaleX(0.5f);
         mChild.setScaleY(0.5f);
         mChild.setAlpha(0.0f);
-
-        mIsShowingChild = false;
     }
 
     public View getChild() {
@@ -163,43 +178,51 @@
         child.layout(left, top, left + child.getMeasuredWidth(), top + child.getMeasuredHeight());
     }
 
-    /** Begin animating {@link #getChild()} visible. */
-    public void showChild(final Runnable onAnimationEndRunnable) {
-        if (mIsShowingChild) return;
-        mIsShowingChild = true;
-
-        // TODO: understand this.
-        // For some reason this needs wait a tick in order to avoid jank.
-        // Maybe because we set up a hardware layer in animateScale()?
-        // Probably not, since it should also be required in hideChild().
-        new Handler().post(new Runnable() {
-            @Override public void run() {
-                animateBackground(false);
-            }
-        });
-
-        animateScale(false, onAnimationEndRunnable);
-    }
-
-    /** Begin animating {@link #getChild()} invisible. */
-    public void hideChild(final Runnable onAnimationEndRunnable) {
-        if (!mIsShowingChild) return;
-        mIsShowingChild = false;
-
-        animateBackground(true);
-        animateScale(true, onAnimationEndRunnable);
-    }
-
-    private void animateBackground(boolean isExitAnimation) {
-        if (isExitAnimation) {
-            mBackground.reverseTransition(mAnimationDuration);
-        } else {
+    public void fadeInBackground() {
+        if (mBackgroundPhase == BackgroundPhase.BEFORE) {
+            mBackgroundPhase = BackgroundPhase.APPEARING_OR_VISIBLE;
             mBackground.startTransition(mAnimationDuration);
         }
     }
 
+    public void fadeOutBackground() {
+        if (mBackgroundPhase == BackgroundPhase.APPEARING_OR_VISIBLE) {
+            mBackgroundPhase = BackgroundPhase.DISAPPEARING_OR_GONE;
+            mBackground.reverseTransition(mAnimationDuration);
+        }
+    }
+
+    public boolean isContentFullyVisible() {
+        return mForegroundPhase == ForegroundPhase.IDLE;
+    }
+
+    /** Begin animating {@link #getChild()} visible. */
+    public void showContent(final Runnable onAnimationEndRunnable) {
+        if (mForegroundPhase == ForegroundPhase.BEFORE) {
+            mForegroundPhase = ForegroundPhase.APPEARING;
+            animateScale(false, onAnimationEndRunnable);
+        }
+    }
+
+    /**
+     * Begin animating {@link #getChild()} invisible. Returns false if animation is not valid in
+     * this state
+     */
+    public boolean hideContent(final Runnable onAnimationEndRunnable) {
+        if (mForegroundPhase == ForegroundPhase.APPEARING ||
+                mForegroundPhase == ForegroundPhase.IDLE) {
+            mForegroundPhase = ForegroundPhase.DISAPPEARING;
+            animateScale(true, onAnimationEndRunnable);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
     /** Creates the open/close animation */
-    private void animateScale(boolean isExitAnimation, final Runnable onAnimationEndRunnable) {
+    private void animateScale(
+            final boolean isExitAnimation,
+            final Runnable onAnimationEndRunnable) {
         mChild.setPivotX(mTargetScreen.centerX() - mChild.getLeft());
         mChild.setPivotY(mTargetScreen.centerY() - mChild.getTop());
 
@@ -208,7 +231,7 @@
                 : android.R.interpolator.decelerate_quint;
         final float scaleTarget = isExitAnimation ? 0.5f : 1.0f;
 
-        ViewPropertyAnimator animator = mChild.animate().withLayer()
+        mChild.animate().withLayer()
                 .setDuration(mAnimationDuration)
                 .setInterpolator(AnimationUtils.loadInterpolator(getContext(), scaleInterpolator))
                 .scaleX(scaleTarget)
@@ -217,7 +240,17 @@
                 .setListener(new AnimatorListenerAdapter() {
                     @Override
                     public void onAnimationEnd(Animator animation) {
-                        if (onAnimationEndRunnable != null) onAnimationEndRunnable.run();
+                        if (isExitAnimation) {
+                            if (mForegroundPhase == ForegroundPhase.DISAPPEARING) {
+                                mForegroundPhase = ForegroundPhase.AFTER;
+                                if (onAnimationEndRunnable != null) onAnimationEndRunnable.run();
+                            }
+                        } else {
+                            if (mForegroundPhase == ForegroundPhase.APPEARING) {
+                                mForegroundPhase = ForegroundPhase.IDLE;
+                                if (onAnimationEndRunnable != null) onAnimationEndRunnable.run();
+                            }
+                        }
                     }
                 });
     }
diff --git a/src/com/android/contacts/quickcontact/QuickContactActivity.java b/src/com/android/contacts/quickcontact/QuickContactActivity.java
index b656969..5fe34e0 100644
--- a/src/com/android/contacts/quickcontact/QuickContactActivity.java
+++ b/src/com/android/contacts/quickcontact/QuickContactActivity.java
@@ -98,9 +98,6 @@
     private String[] mExcludeMimes;
     private List<String> mSortedActionMimeTypes = Lists.newArrayList();
 
-    private boolean mHasFinishedAnimatingIn = false;
-    private boolean mHasStartedAnimatingOut = false;
-
     private FloatingChildLayout mFloatingLayout;
 
     private View mPhotoContainer;
@@ -154,6 +151,8 @@
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
 
+        if (TRACE_LAUNCH) android.os.Debug.startMethodTracing(TRACE_TAG);
+
         // Show QuickContact in front of soft input
         getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
@@ -172,7 +171,8 @@
         mFloatingLayout.setOnOutsideTouchListener(new View.OnTouchListener() {
             @Override
             public boolean onTouch(View v, MotionEvent event) {
-                return handleOutsideTouch();
+                handleOutsideTouch();
+                return true;
             }
         });
 
@@ -183,7 +183,7 @@
                 mContactLoader.cacheResult();
                 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                 startActivity(intent);
-                hide(false);
+                close(false);
             }
         };
         mOpenDetailsButton.setOnClickListener(openDetailsClickHandler);
@@ -191,15 +191,6 @@
         mListPager.setAdapter(new ViewPagerAdapter(getFragmentManager()));
         mListPager.setOnPageChangeListener(new PageChangeListener());
 
-        show();
-    }
-
-    private void show() {
-
-        if (TRACE_LAUNCH) {
-            android.os.Debug.startMethodTracing(TRACE_TAG);
-        }
-
         final Intent intent = getIntent();
 
         Uri lookupUri = intent.getData();
@@ -226,23 +217,23 @@
 
         mContactLoader = (ContactLoader) getLoaderManager().initLoader(
                 LOADER_ID, null, mLoaderCallbacks);
+
+        mFloatingLayout.fadeInBackground();
     }
 
-    private boolean handleOutsideTouch() {
-        if (!mHasFinishedAnimatingIn) return false;
-        if (mHasStartedAnimatingOut) return false;
-
-        mHasStartedAnimatingOut = true;
-        hide(true);
-        return true;
+    private void handleOutsideTouch() {
+        if (mFloatingLayout.isContentFullyVisible()) {
+            close(true);
+        }
     }
 
-    private void hide(boolean withAnimation) {
+    private void close(boolean withAnimation) {
         // cancel any pending queries
         getLoaderManager().destroyLoader(LOADER_ID);
 
         if (withAnimation) {
-            mFloatingLayout.hideChild(new Runnable() {
+            mFloatingLayout.fadeOutBackground();
+            final boolean animated = mFloatingLayout.hideContent(new Runnable() {
                 @Override
                 public void run() {
                     // Wait until the final animation frame has been drawn, otherwise
@@ -266,15 +257,19 @@
                     });
                 }
             });
+            if (!animated) {
+                // If we were in the wrong state, simply quit (this can happen for example
+                // if the user pushes BACK before anything has loaded)
+                finish();
+            }
         } else {
-            mFloatingLayout.hideChild(null);
             finish();
         }
     }
 
     @Override
     public void onBackPressed() {
-        hide(true);
+        close(true);
     }
 
     /** Assign this string to the view if it is not empty. */
@@ -480,7 +475,7 @@
         @Override
         public void onLoadFinished(Loader<ContactLoader.Result> loader, ContactLoader.Result data) {
             if (isFinishing()) {
-                hide(false);
+                close(false);
                 return;
             }
             if (data.isError()) {
@@ -492,25 +487,22 @@
                 Log.i(TAG, "No contact found: " + ((ContactLoader)loader).getLookupUri());
                 Toast.makeText(QuickContactActivity.this, R.string.invalidContactMessage,
                         Toast.LENGTH_LONG).show();
-                hide(false);
+                close(false);
                 return;
             }
 
             bindData(data);
 
-            if (TRACE_LAUNCH) {
-                android.os.Debug.stopMethodTracing();
-            }
+            if (TRACE_LAUNCH) android.os.Debug.stopMethodTracing();
 
             // Data bound and ready, pull curtain to show. Put this on the Handler to ensure
             // that the layout passes are completed
             SchedulingUtils.doAfterLayout(mFloatingLayout, new Runnable() {
                 @Override
                 public void run() {
-                    mFloatingLayout.showChild(new Runnable() {
+                    mFloatingLayout.showContent(new Runnable() {
                         @Override
                         public void run() {
-                            mHasFinishedAnimatingIn = true;
                             mContactLoader.upgradeToFullContact();
                         }
                     });
@@ -599,7 +591,7 @@
                                 Toast.LENGTH_SHORT).show();
                     }
 
-                    hide(false);
+                    close(false);
                 }
             };
             // Defer the action to make the window properly repaint