Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / android / java / src / org / chromium / chrome / browser / infobar / InfoBarContainer.java
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package org.chromium.chrome.browser.infobar;
6
7 import android.animation.ObjectAnimator;
8 import android.app.Activity;
9 import android.graphics.Canvas;
10 import android.view.Gravity;
11 import android.view.MotionEvent;
12 import android.view.View;
13 import android.view.ViewGroup;
14 import android.widget.FrameLayout;
15 import android.widget.LinearLayout;
16
17 import com.google.common.annotations.VisibleForTesting;
18
19 import org.chromium.base.ApiCompatibilityUtils;
20 import org.chromium.base.CalledByNative;
21 import org.chromium.content.browser.DeviceUtils;
22 import org.chromium.ui.UiUtils;
23
24 import java.util.ArrayDeque;
25 import java.util.ArrayList;
26 import java.util.Iterator;
27 import java.util.LinkedList;
28
29
30 /**
31  * A container for all the infobars of a specific tab.
32  * Note that infobars creation can be initiated from Java of from native code.
33  * When initiated from native code, special code is needed to keep the Java and native infobar in
34  * sync, see NativeInfoBar.
35  */
36 public class InfoBarContainer extends LinearLayout {
37     private static final String TAG = "InfoBarContainer";
38     private static final long REATTACH_FADE_IN_MS = 250;
39
40     public interface InfoBarAnimationListener {
41         /**
42          * Notifies the subscriber when an animation is completed.
43          */
44         void notifyAnimationFinished(int animationType);
45     }
46
47     private static class InfoBarTransitionInfo {
48         // InfoBar being animated.
49         public InfoBar target;
50
51         // View to replace the current View shown by the ContentWrapperView.
52         public View toShow;
53
54         // Which type of animation needs to be performed.
55         public int animationType;
56
57         public InfoBarTransitionInfo(InfoBar bar, View view, int type) {
58             assert type >= AnimationHelper.ANIMATION_TYPE_SHOW;
59             assert type < AnimationHelper.ANIMATION_TYPE_BOUNDARY;
60
61             target = bar;
62             toShow = view;
63             animationType = type;
64         }
65     }
66
67     private InfoBarAnimationListener mAnimationListener;
68
69     // Native InfoBarContainer pointer which will be set by nativeInit()
70     private long mNativeInfoBarContainer;
71
72     private final Activity mActivity;
73
74     private final AutoLoginDelegate mAutoLoginDelegate;
75
76     // Whether the infobar are shown on top (below the location bar) or at the bottom of the screen.
77     private final boolean mInfoBarsOnTop;
78
79     // The list of all infobars in this container, regardless of whether they've been shown yet.
80     private final ArrayList<InfoBar> mInfoBars = new ArrayList<InfoBar>();
81
82     // We only animate changing infobars one at a time.
83     private final ArrayDeque<InfoBarTransitionInfo> mInfoBarTransitions;
84
85     // Animation currently moving InfoBars around.
86     private AnimationHelper mAnimation;
87     private final FrameLayout mAnimationSizer;
88
89     // True when this container has been emptied and its native counterpart has been destroyed.
90     private boolean mDestroyed = false;
91
92     // The id of the tab associated with us. Set to TabBase.INVALID_TAB_ID if no tab is associated.
93     private int mTabId;
94
95     // Parent view that contains us.
96     private ViewGroup mParentView;
97
98     public InfoBarContainer(Activity activity, AutoLoginProcessor autoLoginProcessor,
99             int tabId, ViewGroup parentView, long nativeWebContents) {
100         super(activity);
101         setOrientation(LinearLayout.VERTICAL);
102         mAnimationListener = null;
103         mInfoBarTransitions = new ArrayDeque<InfoBarTransitionInfo>();
104
105         mAutoLoginDelegate = new AutoLoginDelegate(autoLoginProcessor, activity);
106         mActivity = activity;
107         mTabId = tabId;
108         mParentView = parentView;
109
110         mAnimationSizer = new FrameLayout(activity);
111         mAnimationSizer.setVisibility(INVISIBLE);
112
113         // The tablet has the infobars below the location bar. On the phone they are at the bottom.
114         mInfoBarsOnTop = DeviceUtils.isTablet(activity);
115         setGravity(determineGravity());
116
117         // Chromium's InfoBarContainer may add an InfoBar immediately during this initialization
118         // call, so make sure everything in the InfoBarContainer is completely ready beforehand.
119         mNativeInfoBarContainer = nativeInit(nativeWebContents, mAutoLoginDelegate);
120     }
121
122     public void setAnimationListener(InfoBarAnimationListener listener) {
123         mAnimationListener = listener;
124     }
125
126     @VisibleForTesting
127     public InfoBarAnimationListener getAnimationListener() {
128         return mAnimationListener;
129     }
130
131
132     public boolean areInfoBarsOnTop() {
133         return mInfoBarsOnTop;
134     }
135
136     @Override
137     public boolean onInterceptTouchEvent(MotionEvent ev) {
138         // Trap any attempts to fiddle with the Views while we're animating.
139         return mAnimation != null;
140     }
141
142     @Override
143     public boolean onTouchEvent(MotionEvent event) {
144         // Consume all motion events so they do not reach the ContentView.
145         return true;
146     }
147
148     private void addToParentView() {
149         if (mParentView != null && mParentView.indexOfChild(this) == -1) {
150             mParentView.addView(this, createLayoutParams());
151         }
152     }
153
154     private int determineGravity() {
155         return mInfoBarsOnTop ? Gravity.TOP : Gravity.BOTTOM;
156     }
157
158     private FrameLayout.LayoutParams createLayoutParams() {
159         return new FrameLayout.LayoutParams(
160                 LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, determineGravity());
161     }
162
163     public void removeFromParentView() {
164         if (getParent() != null) {
165             ((ViewGroup) getParent()).removeView(this);
166         }
167     }
168
169     /**
170      * Called when the parent {@link android.view.ViewGroup} has changed for
171      * this container.
172      */
173     public void onParentViewChanged(int tabId, ViewGroup parentView) {
174         mTabId = tabId;
175         mParentView = parentView;
176
177         removeFromParentView();
178         addToParentView();
179     }
180
181     @Override
182     protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
183         if (mAnimation == null || child != mAnimation.getTarget()) {
184             return super.drawChild(canvas, child, drawingTime);
185         }
186         // When infobars are on top, the new infobar Z-order is greater than the previous infobar,
187         // which means it shows on top during the animation. We cannot change the Z-order in the
188         // linear layout, it is driven by the insertion index.
189         // So we simply clip the children to their bounds to make sure the new infobar does not
190         // paint over.
191         boolean retVal;
192         canvas.save();
193         canvas.clipRect(mAnimation.getTarget().getClippingRect());
194         retVal = super.drawChild(canvas, child, drawingTime);
195         canvas.restore();
196         return retVal;
197     }
198
199     @Override
200     protected void onAttachedToWindow() {
201         super.onAttachedToWindow();
202         ObjectAnimator.ofFloat(this, "alpha", 0.f, 1.f).setDuration(REATTACH_FADE_IN_MS).start();
203         setVisibility(VISIBLE);
204     }
205
206     @Override
207     protected void onDetachedFromWindow() {
208         super.onDetachedFromWindow();
209         setVisibility(INVISIBLE);
210     }
211
212     public InfoBar findInfoBar(int nativeInfoBar) {
213         for (InfoBar infoBar : mInfoBars) {
214             if (infoBar.ownsNativeInfoBar(nativeInfoBar)) {
215                 return infoBar;
216             }
217         }
218         return null;
219     }
220
221     /**
222      * Adds an InfoBar to the view hierarchy.
223      * @param infoBar InfoBar to add to the View hierarchy.
224      */
225     @CalledByNative
226     public void addInfoBar(InfoBar infoBar) {
227         assert !mDestroyed;
228         if (infoBar == null) {
229             return;
230         }
231         if (mInfoBars.contains(infoBar)) {
232             assert false : "Trying to add an info bar that has already been added.";
233             return;
234         }
235
236         // We add the infobar immediately to mInfoBars but we wait for the animation to end to
237         // notify it's been added, as tests rely on this notification but expects the infobar view
238         // to be available when they get the notification.
239         mInfoBars.add(infoBar);
240         infoBar.setContext(mActivity);
241         infoBar.setInfoBarContainer(this);
242
243         enqueueInfoBarAnimation(infoBar, null, AnimationHelper.ANIMATION_TYPE_SHOW);
244     }
245
246     /**
247      * Returns the latest InfoBarTransitionInfo that deals with the given InfoBar.
248      * @param toFind InfoBar that we're looking for.
249      */
250     public InfoBarTransitionInfo findLastTransitionForInfoBar(InfoBar toFind) {
251         Iterator<InfoBarTransitionInfo> iterator = mInfoBarTransitions.descendingIterator();
252         while (iterator.hasNext()) {
253             InfoBarTransitionInfo info = iterator.next();
254             if (info.target == toFind) return info;
255         }
256         return null;
257     }
258
259     /**
260      * Animates swapping out the current View in the {@code infoBar} with {@code toShow} without
261      * destroying or dismissing the entire InfoBar.
262      * @param infoBar InfoBar that is having its content replaced.
263      * @param toShow View representing the InfoBar's new contents.
264      */
265     public void swapInfoBarViews(InfoBar infoBar, View toShow) {
266         assert !mDestroyed;
267
268         if (!mInfoBars.contains(infoBar)) {
269             assert false : "Trying to swap an InfoBar that is not in this container.";
270             return;
271         }
272
273         InfoBarTransitionInfo transition = findLastTransitionForInfoBar(infoBar);
274         if (transition != null && transition.toShow == toShow) {
275             assert false : "Tried to enqueue the same swap twice in a row.";
276             return;
277         }
278
279         enqueueInfoBarAnimation(infoBar, toShow, AnimationHelper.ANIMATION_TYPE_SWAP);
280     }
281
282     /**
283      * Removes an InfoBar from the view hierarchy.
284      * @param infoBar InfoBar to remove from the View hierarchy.
285      */
286     public void removeInfoBar(InfoBar infoBar) {
287         assert !mDestroyed;
288
289         if (!mInfoBars.remove(infoBar)) {
290             assert false : "Trying to remove an InfoBar that is not in this container.";
291             return;
292         }
293
294         // If an InfoBar is told to hide itself before it has a chance to be shown, don't bother
295         // with animating any of it.
296         boolean collapseAnimations = false;
297         ArrayDeque<InfoBarTransitionInfo> transitionCopy =
298                 new ArrayDeque<InfoBarTransitionInfo>(mInfoBarTransitions);
299         for (InfoBarTransitionInfo info : transitionCopy) {
300             if (info.target == infoBar) {
301                 if (info.animationType == AnimationHelper.ANIMATION_TYPE_SHOW) {
302                     // We can assert that two attempts to show the same InfoBar won't be in the
303                     // deque simultaneously because of the check in addInfoBar().
304                     assert !collapseAnimations;
305                     collapseAnimations = true;
306                 }
307                 if (collapseAnimations) {
308                     mInfoBarTransitions.remove(info);
309                 }
310             }
311         }
312
313         if (!collapseAnimations) {
314             enqueueInfoBarAnimation(infoBar, null, AnimationHelper.ANIMATION_TYPE_HIDE);
315         }
316     }
317
318     /**
319      * Enqueue a new animation to run and kicks off the animation sequence.
320      */
321     private void enqueueInfoBarAnimation(InfoBar infoBar, View toShow, int animationType) {
322         InfoBarTransitionInfo info = new InfoBarTransitionInfo(infoBar, toShow, animationType);
323         mInfoBarTransitions.add(info);
324         processPendingInfoBars();
325     }
326
327     @Override
328     protected void onLayout(boolean changed, int l, int t, int r, int b) {
329         // Hide the infobars when the keyboard is showing.
330         boolean isShowing = (getVisibility() == View.VISIBLE);
331         if (UiUtils.isKeyboardShowing(mActivity, this)) {
332             if (isShowing) {
333                 setVisibility(View.INVISIBLE);
334             }
335         } else {
336             if (!isShowing) {
337                 setVisibility(View.VISIBLE);
338             }
339         }
340         super.onLayout(changed, l, t, r, b);
341     }
342
343     /**
344      * @return True when this container has been emptied and its native counterpart has been
345      *         destroyed.
346      */
347     public boolean hasBeenDestroyed() {
348         return mDestroyed;
349     }
350
351     private void processPendingInfoBars() {
352         if (mAnimation != null || mInfoBarTransitions.isEmpty()) return;
353
354         // Start animating what has to be animated.
355         InfoBarTransitionInfo info = mInfoBarTransitions.remove();
356         View toShow = info.toShow;
357         ContentWrapperView targetView;
358
359         addToParentView();
360
361         if (info.animationType == AnimationHelper.ANIMATION_TYPE_SHOW) {
362             targetView = info.target.getContentWrapper(true);
363             assert mInfoBars.contains(info.target);
364             toShow = targetView.detachCurrentView();
365             addView(targetView, mInfoBarsOnTop ? getChildCount() : 0,
366                     new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
367         } else {
368             targetView = info.target.getContentWrapper(false);
369         }
370
371         // Kick off the animation.
372         mAnimation = new AnimationHelper(this, targetView, info.target, toShow, info.animationType);
373         mAnimation.start();
374     }
375
376     // Called by the tab when it has started loading a new page.
377     public void onPageStarted(String url) {
378         LinkedList<InfoBar> barsToRemove = new LinkedList<InfoBar>();
379
380         for (InfoBar infoBar : mInfoBars) {
381             if (infoBar.shouldExpire(url)) {
382                 barsToRemove.add(infoBar);
383             }
384         }
385
386         for (InfoBar infoBar : barsToRemove) {
387             infoBar.dismissJavaOnlyInfoBar();
388         }
389     }
390
391     /**
392      * Returns the id of the tab we are associated with.
393      */
394     public int getTabId() {
395         return mTabId;
396     }
397
398     public void destroy() {
399         mDestroyed = true;
400         removeAllViews();
401         if (mNativeInfoBarContainer != 0) {
402             nativeDestroy(mNativeInfoBarContainer);
403         }
404         mInfoBarTransitions.clear();
405     }
406
407     /**
408      * @return all of the InfoBars held in this container.
409      */
410     @VisibleForTesting
411     public ArrayList<InfoBar> getInfoBars() {
412         return mInfoBars;
413     }
414
415     /**
416      * Dismisses all {@link AutoLoginInfoBar}s in this {@link InfoBarContainer} that are for
417      * {@code accountName} and {@code authToken}.  This also resets all {@link InfoBar}s that are
418      * for a different request.
419      * @param accountName The name of the account request is being accessed for.
420      * @param authToken The authentication token access is being requested for.
421      * @param success Whether or not the authentication attempt was successful.
422      * @param result The resulting token for the auto login request (ignored if {@code success} is
423      *               {@code false}.
424      */
425     public void processAutoLogin(String accountName, String authToken, boolean success,
426             String result) {
427         mAutoLoginDelegate.dismissAutoLogins(accountName, authToken, success, result);
428     }
429
430     /**
431      * Dismiss all auto logins infobars without processing any result.
432      */
433     public void dismissAutoLoginInfoBars() {
434         mAutoLoginDelegate.dismissAutoLogins("", "", false, "");
435     }
436
437     public void prepareTransition(View toShow) {
438         if (toShow != null) {
439             // In order to animate the addition of the infobar, we need a layout first.
440             // Attach the child to invisible layout so that we can get measurements for it without
441             // moving everything in the real container.
442             ViewGroup parent = (ViewGroup) toShow.getParent();
443             if (parent != null) parent.removeView(toShow);
444
445             assert mAnimationSizer.getParent() == null;
446             mParentView.addView(mAnimationSizer, createLayoutParams());
447             mAnimationSizer.addView(toShow, 0,
448                     new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
449             mAnimationSizer.requestLayout();
450         }
451     }
452
453     public void startTransition() {
454         if (mInfoBarsOnTop) {
455             // We need to clip this view to its bounds while it is animated because the layout's
456             // z-ordering puts it on top of other infobars as it's being animated.
457             ApiCompatibilityUtils.postInvalidateOnAnimation(this);
458         }
459     }
460
461     /**
462      * Finishes off whatever animation is running.
463      */
464     public void finishTransition() {
465         assert mAnimation != null;
466
467         // If the InfoBar was hidden, get rid of its View entirely.
468         if (mAnimation.getAnimationType() == AnimationHelper.ANIMATION_TYPE_HIDE) {
469             removeView(mAnimation.getTarget());
470         }
471
472         // Reset all translations and put everything where they need to be.
473         for (int i = 0; i < getChildCount(); ++i) {
474             View view = getChildAt(i);
475             view.setTranslationY(0);
476         }
477         requestLayout();
478
479         // If there are no infobars shown, there is no need to keep the infobar container in the
480         // view hierarchy.
481         if (getChildCount() == 0) {
482             removeFromParentView();
483         }
484
485         if (mAnimationSizer.getParent() != null) {
486             ((ViewGroup) mAnimationSizer.getParent()).removeView(mAnimationSizer);
487         }
488
489         // Notify interested parties and move on to the next animation.
490         if (mAnimationListener != null) {
491             mAnimationListener.notifyAnimationFinished(mAnimation.getAnimationType());
492         }
493         mAnimation = null;
494         processPendingInfoBars();
495     }
496
497     /**
498      * Searches a given view's child views for an instance of {@link InfoBarContainer}.
499      *
500      * @param parentView View to be searched for
501      * @return {@link InfoBarContainer} instance if it's one of the child views;
502      *     otherwise {@code null}.
503      */
504     public static InfoBarContainer childViewOf(ViewGroup parentView) {
505         for (int i = 0; i < parentView.getChildCount(); i++) {
506             if (parentView.getChildAt(i) instanceof InfoBarContainer) {
507                 return (InfoBarContainer) parentView.getChildAt(i);
508             }
509         }
510         return null;
511     }
512
513     public long getNative() {
514         return mNativeInfoBarContainer;
515     }
516
517     private native long nativeInit(long webContentsPtr, AutoLoginDelegate autoLoginDelegate);
518
519     private native void nativeDestroy(long nativeInfoBarContainerAndroid);
520 }