TabBar.java revision 7e5b8b5ab04edd6cfe3acc4dadca42b11ba484c3
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
19import com.android.browser.BrowserWebView.ScrollListener;
20
21import android.animation.Animator;
22import android.animation.Animator.AnimatorListener;
23import android.animation.AnimatorSet;
24import android.animation.ObjectAnimator;
25import android.app.Activity;
26import android.content.Context;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.graphics.Bitmap;
30import android.graphics.BitmapShader;
31import android.graphics.Canvas;
32import android.graphics.Matrix;
33import android.graphics.Paint;
34import android.graphics.Path;
35import android.graphics.Shader;
36import android.graphics.drawable.BitmapDrawable;
37import android.graphics.drawable.Drawable;
38import android.graphics.drawable.LayerDrawable;
39import android.graphics.drawable.PaintDrawable;
40import android.view.ContextMenu;
41import android.view.Gravity;
42import android.view.LayoutInflater;
43import android.view.MenuInflater;
44import android.view.View;
45import android.view.View.OnClickListener;
46import android.webkit.WebView;
47import android.widget.ImageButton;
48import android.widget.ImageView;
49import android.widget.LinearLayout;
50import android.widget.TextView;
51
52import java.util.HashMap;
53import java.util.List;
54import java.util.Map;
55
56/**
57 * tabbed title bar for xlarge screen browser
58 */
59public class TabBar extends LinearLayout
60        implements ScrollListener, OnClickListener {
61
62    private static final int PROGRESS_MAX = 100;
63
64    private Activity mActivity;
65    private UiController mUiController;
66    private TabControl mTabControl;
67    private XLargeUi mUi;
68
69    private int mTabWidthSelected;
70    private int mTabWidthUnselected;
71
72    private TabScrollView mTabs;
73
74    private ImageButton mNewTab;
75    private int mButtonWidth;
76
77    private Map<Tab, TabView> mTabMap;
78
79    private Drawable mGenericFavicon;
80
81    private int mCurrentTextureWidth = 0;
82    private int mCurrentTextureHeight = 0;
83
84    private Drawable mActiveDrawable;
85    private Drawable mInactiveDrawable;
86
87    private final Paint mActiveShaderPaint = new Paint();
88    private final Paint mInactiveShaderPaint = new Paint();
89    private final Paint mFocusPaint = new Paint();
90    private final Matrix mActiveMatrix = new Matrix();
91    private final Matrix mInactiveMatrix = new Matrix();
92
93    private BitmapShader mActiveShader;
94    private BitmapShader mInactiveShader;
95
96    private int mTabOverlap;
97    private int mAddTabOverlap;
98    private int mTabSliceWidth;
99    private boolean mUseQuickControls;
100
101    public TabBar(Activity activity, UiController controller, XLargeUi ui) {
102        super(activity);
103        mActivity = activity;
104        mUiController = controller;
105        mTabControl = mUiController.getTabControl();
106        mUi = ui;
107        Resources res = activity.getResources();
108        mTabWidthSelected = (int) res.getDimension(R.dimen.tab_width_selected);
109        mTabWidthUnselected = (int) res.getDimension(R.dimen.tab_width_unselected);
110        mActiveDrawable = res.getDrawable(R.drawable.bg_urlbar);
111        mInactiveDrawable = res.getDrawable(R.drawable.browsertab_inactive);
112
113        mTabMap = new HashMap<Tab, TabView>();
114        LayoutInflater factory = LayoutInflater.from(activity);
115        factory.inflate(R.layout.tab_bar, this);
116        setPadding(0, (int) res.getDimension(R.dimen.tab_padding_top), 0, 0);
117        mTabs = (TabScrollView) findViewById(R.id.tabs);
118        mNewTab = (ImageButton) findViewById(R.id.newtab);
119        mNewTab.setOnClickListener(this);
120        mGenericFavicon = res.getDrawable(R.drawable.app_web_browser_sm);
121
122        updateTabs(mUiController.getTabs());
123        mButtonWidth = -1;
124        // tab dimensions
125        mTabOverlap = (int) res.getDimension(R.dimen.tab_overlap);
126        mAddTabOverlap = (int) res.getDimension(R.dimen.tab_addoverlap);
127        mTabSliceWidth = (int) res.getDimension(R.dimen.tab_slice);
128
129        mActiveShaderPaint.setStyle(Paint.Style.FILL);
130        mActiveShaderPaint.setAntiAlias(true);
131
132        mInactiveShaderPaint.setStyle(Paint.Style.FILL);
133        mInactiveShaderPaint.setAntiAlias(true);
134
135        mFocusPaint.setStyle(Paint.Style.STROKE);
136        mFocusPaint.setStrokeWidth(res.getDimension(R.dimen.tab_focus_stroke));
137        mFocusPaint.setAntiAlias(true);
138        mFocusPaint.setColor(res.getColor(R.color.tabFocusHighlight));
139    }
140
141    @Override
142    public void onConfigurationChanged(Configuration config) {
143        super.onConfigurationChanged(config);
144        Resources res = mActivity.getResources();
145        mTabWidthSelected = (int) res.getDimension(R.dimen.tab_width_selected);
146        mTabWidthUnselected = (int) res.getDimension(R.dimen.tab_width_unselected);
147        // force update of tab bar
148        mTabs.updateLayout();
149    }
150
151    void setUseQuickControls(boolean useQuickControls) {
152        mUseQuickControls = useQuickControls;
153        mNewTab.setVisibility(mUseQuickControls ? View.GONE
154                : View.VISIBLE);
155    }
156
157    int getTabCount() {
158        return mTabMap.size();
159    }
160
161    void updateTabs(List<Tab> tabs) {
162        mTabs.clearTabs();
163        mTabMap.clear();
164        for (Tab tab : tabs) {
165            TabView tv = buildTabView(tab);
166            mTabs.addTab(tv);
167        }
168        mTabs.setSelectedTab(mTabControl.getCurrentPosition());
169    }
170
171    @Override
172    protected void onMeasure(int hspec, int vspec) {
173        super.onMeasure(hspec, vspec);
174        int w = getMeasuredWidth();
175        // adjust for new tab overlap
176        if (!mUseQuickControls) {
177            w -= mAddTabOverlap;
178        }
179        setMeasuredDimension(w, getMeasuredHeight());
180    }
181
182    @Override
183    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
184        // use paddingLeft and paddingTop
185        int pl = getPaddingLeft();
186        int pt = getPaddingTop();
187        int sw = mTabs.getMeasuredWidth();
188        int w = right - left - pl;
189        if (mUseQuickControls) {
190            mButtonWidth = 0;
191        } else {
192            mButtonWidth = mNewTab.getMeasuredWidth() - mAddTabOverlap;
193            if (w-sw < mButtonWidth) {
194                sw = w - mButtonWidth;
195            }
196        }
197        mTabs.layout(pl, pt, pl + sw, bottom - top);
198        // adjust for overlap
199        if (!mUseQuickControls) {
200            mNewTab.layout(pl + sw - mAddTabOverlap, pt,
201                    pl + sw + mButtonWidth - mAddTabOverlap, bottom - top);
202        }
203    }
204
205    public void onClick(View view) {
206        if (mNewTab == view) {
207            mUiController.openTabToHomePage();
208        } else if (mTabs.getSelectedTab() == view) {
209            if (mUseQuickControls) {
210                if (mUi.isTitleBarShowing() && !isLoading()) {
211                    mUi.stopEditingUrl();
212                    mUi.hideTitleBar();
213                } else {
214                    mUi.stopWebViewScrolling();
215                    mUi.editUrl(false);
216                }
217            } else if (mUi.isTitleBarShowing() && !isLoading()) {
218                mUi.stopEditingUrl();
219                mUi.hideTitleBar();
220            } else {
221                showUrlBar();
222            }
223        } else if (view instanceof TabView) {
224            final Tab tab = ((TabView) view).mTab;
225            int ix = mTabs.getChildIndex(view);
226            if (ix >= 0) {
227                mTabs.setSelectedTab(ix);
228                mUiController.switchToTab(tab);
229            }
230        }
231    }
232
233    private void showUrlBar() {
234        mUi.stopWebViewScrolling();
235        mUi.showTitleBar();
236    }
237
238    void showTitleBarIndicator(boolean show) {
239        Tab tab = mTabControl.getCurrentTab();
240        if (tab != null && !tab.isSnapshot()) {
241            TabView tv = mTabMap.get(tab);
242            if (tv != null) {
243                tv.showIndicator(show);
244            }
245        }
246    }
247
248    boolean showsTitleBarIndicator() {
249        Tab tab = mTabControl.getCurrentTab();
250        if (tab != null) {
251            TabView tv = mTabMap.get(tab);
252            if (tv != null) {
253                return tv.showsIndicator();
254            }
255        }
256        return false;
257    }
258
259    // callback after fake titlebar is shown
260    void onShowTitleBar() {
261        showTitleBarIndicator(false);
262    }
263
264    // callback after fake titlebar is hidden
265    void onHideTitleBar() {
266        Tab tab = mTabControl.getCurrentTab();
267        WebView w = tab.getWebView();
268        if (w != null) {
269            showTitleBarIndicator(w.getVisibleTitleHeight() == 0);
270        }
271    }
272
273    // webview scroll listener
274
275    @Override
276    public void onScroll(int visibleTitleHeight, boolean userInitiated) {
277        if (mUseQuickControls) return;
278        // isLoading is using the current tab, which initially might not be set yet
279        if (mTabControl.getCurrentTab() != null) {
280            if (visibleTitleHeight == 0 && !mUi.isTitleBarShowing()) {
281                if (!showsTitleBarIndicator()) {
282                    showTitleBarIndicator(true);
283                }
284            } else {
285                if (showsTitleBarIndicator()) {
286                    showTitleBarIndicator(false);
287                }
288            }
289        }
290    }
291
292    @Override
293    public void createContextMenu(ContextMenu menu) {
294        MenuInflater inflater = mActivity.getMenuInflater();
295        inflater.inflate(R.menu.title_context, menu);
296        mActivity.onCreateContextMenu(menu, this, null);
297    }
298
299    private TabView buildTabView(Tab tab) {
300        TabView tabview = new TabView(mActivity, tab);
301        mTabMap.put(tab, tabview);
302        tabview.setOnClickListener(this);
303        return tabview;
304    }
305
306    private static Bitmap getDrawableAsBitmap(Drawable drawable, int width, int height) {
307        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
308        Canvas c = new Canvas(b);
309        drawable.setBounds(0, 0, width, height);
310        drawable.draw(c);
311        return b;
312    }
313
314    /**
315     * View used in the tab bar
316     */
317    class TabView extends LinearLayout implements OnClickListener {
318
319        Tab mTab;
320        View mTabContent;
321        TextView mTitle;
322        View mIndicator;
323        View mIncognito;
324        View mSnapshot;
325        ImageView mIconView;
326        ImageView mLock;
327        ImageView mClose;
328        boolean mSelected;
329        boolean mInLoad;
330        Path mPath;
331        Path mFocusPath;
332        int[] mWindowPos;
333
334        /**
335         * @param context
336         */
337        public TabView(Context context, Tab tab) {
338            super(context);
339            setWillNotDraw(false);
340            mPath = new Path();
341            mFocusPath = new Path();
342            mWindowPos = new int[2];
343            mTab = tab;
344            setGravity(Gravity.CENTER_VERTICAL);
345            setOrientation(LinearLayout.HORIZONTAL);
346            setPadding(mTabOverlap, 0, mTabSliceWidth, 0);
347            LayoutInflater inflater = LayoutInflater.from(getContext());
348            mTabContent = inflater.inflate(R.layout.tab_title, this, true);
349            mTitle = (TextView) mTabContent.findViewById(R.id.title);
350            mIconView = (ImageView) mTabContent.findViewById(R.id.favicon);
351            mLock = (ImageView) mTabContent.findViewById(R.id.lock);
352            mClose = (ImageView) mTabContent.findViewById(R.id.close);
353            mClose.setOnClickListener(this);
354            mIncognito = mTabContent.findViewById(R.id.incognito);
355            mSnapshot = mTabContent.findViewById(R.id.snapshot);
356            mIndicator = mTabContent.findViewById(R.id.chevron);
357            mSelected = false;
358            mInLoad = false;
359            // update the status
360            updateFromTab();
361        }
362
363        void showIndicator(boolean show) {
364            if (mSelected) {
365                mIndicator.setVisibility(show ? View.VISIBLE : View.GONE);
366                LayoutParams lp = (LinearLayout.LayoutParams) getLayoutParams();
367                if (show) {
368                    lp.width = mTabWidthSelected + mIndicator.getWidth();
369                } else {
370                    lp.width = mTabWidthSelected;
371                }
372                lp.height =  LayoutParams.MATCH_PARENT;
373                setLayoutParams(lp);
374            } else {
375                mIndicator.setVisibility(View.GONE);
376            }
377        }
378
379        boolean showsIndicator() {
380            return (mIndicator.getVisibility() == View.VISIBLE);
381        }
382
383        @Override
384        public void onClick(View v) {
385            if (v == mClose) {
386                closeTab();
387            }
388        }
389
390        private void updateFromTab() {
391            String displayTitle = mTab.getTitle();
392            if (displayTitle == null) {
393                displayTitle = mTab.getUrl();
394            }
395            setDisplayTitle(displayTitle);
396            setProgress(mTab.getLoadProgress());
397            if (mTab.getFavicon() != null) {
398                setFavicon(renderFavicon(mTab.getFavicon()));
399            }
400            updateTabIcons();
401        }
402
403        private void updateTabIcons() {
404            mIncognito.setVisibility(
405                    mTab.isPrivateBrowsingEnabled() ?
406                    View.VISIBLE : View.GONE);
407            mSnapshot.setVisibility(mTab.isSnapshot()
408                    ? View.VISIBLE : View.GONE);
409        }
410
411        @Override
412        public void setActivated(boolean selected) {
413            mSelected = selected;
414            mClose.setVisibility(mSelected ? View.VISIBLE : View.GONE);
415            mIndicator.setVisibility(View.GONE);
416            mTitle.setTextAppearance(mActivity, mSelected ?
417                    R.style.TabTitleSelected : R.style.TabTitleUnselected);
418            setHorizontalFadingEdgeEnabled(!mSelected);
419            super.setActivated(selected);
420            updateLayoutParams();
421            setFocusable(!selected);
422            postInvalidate();
423        }
424
425        public void updateLayoutParams() {
426            LayoutParams lp = (LinearLayout.LayoutParams) getLayoutParams();
427            lp.width = mSelected ? mTabWidthSelected : mTabWidthUnselected;
428            lp.height =  LayoutParams.MATCH_PARENT;
429            setLayoutParams(lp);
430        }
431
432        void setDisplayTitle(String title) {
433            mTitle.setText(title);
434        }
435
436        void setFavicon(Drawable d) {
437            mIconView.setImageDrawable(d);
438        }
439
440        void setLock(Drawable d) {
441            if (null == d) {
442                mLock.setVisibility(View.GONE);
443            } else {
444                mLock.setImageDrawable(d);
445                mLock.setVisibility(View.VISIBLE);
446            }
447        }
448
449        void setProgress(int newProgress) {
450            if (newProgress >= PROGRESS_MAX) {
451                mInLoad = false;
452            } else {
453                if (!mInLoad && getWindowToken() != null) {
454                    mInLoad = true;
455                }
456            }
457        }
458
459        private void closeTab() {
460            if (mTab == mTabControl.getCurrentTab()) {
461                mUiController.closeCurrentTab();
462            } else {
463                mUiController.closeTab(mTab);
464            }
465        }
466
467        @Override
468        protected void onLayout(boolean changed, int l, int t, int r, int b) {
469            super.onLayout(changed, l, t, r, b);
470            setTabPath(mPath, 0, 0, r - l, b - t);
471            setFocusPath(mFocusPath, 0, 0, r - l, b - t);
472        }
473
474        @Override
475        protected void dispatchDraw(Canvas canvas) {
476            if (mCurrentTextureWidth != mUi.getContentWidth() ||
477                    mCurrentTextureHeight != getHeight()) {
478                mCurrentTextureWidth = mUi.getContentWidth();
479                mCurrentTextureHeight = getHeight();
480
481                if (mCurrentTextureWidth > 0 && mCurrentTextureHeight > 0) {
482                    Bitmap activeTexture = getDrawableAsBitmap(mActiveDrawable,
483                            mCurrentTextureWidth, mCurrentTextureHeight);
484                    Bitmap inactiveTexture = getDrawableAsBitmap(mInactiveDrawable,
485                            mCurrentTextureWidth, mCurrentTextureHeight);
486
487                    mActiveShader = new BitmapShader(activeTexture,
488                            Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
489                    mActiveShaderPaint.setShader(mActiveShader);
490
491                    mInactiveShader = new BitmapShader(inactiveTexture,
492                            Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
493                    mInactiveShaderPaint.setShader(mInactiveShader);
494                }
495            }
496            // add some monkey protection
497            if ((mActiveShader != null) && (mInactiveShader != null)) {
498                int state = canvas.save();
499                getLocationInWindow(mWindowPos);
500                Paint paint = mSelected ? mActiveShaderPaint : mInactiveShaderPaint;
501                drawClipped(canvas, paint, mPath, mWindowPos[0]);
502                canvas.restoreToCount(state);
503            }
504            super.dispatchDraw(canvas);
505        }
506
507        private void drawClipped(Canvas canvas, Paint paint, Path clipPath, int left) {
508            // TODO: We should change the matrix/shader only when needed
509            final Matrix matrix = mSelected ? mActiveMatrix : mInactiveMatrix;
510            matrix.setTranslate(-left, 0.0f);
511            (mSelected ? mActiveShader : mInactiveShader).setLocalMatrix(matrix);
512            canvas.drawPath(clipPath, paint);
513            if (isFocused()) {
514                canvas.drawPath(mFocusPath, mFocusPaint);
515            }
516        }
517
518        private void setTabPath(Path path, int l, int t, int r, int b) {
519            path.reset();
520            path.moveTo(l, b);
521            path.lineTo(l, t);
522            path.lineTo(r - mTabSliceWidth, t);
523            path.lineTo(r, b);
524            path.close();
525        }
526
527        private void setFocusPath(Path path, int l, int t, int r, int b) {
528            path.reset();
529            path.moveTo(l, b);
530            path.lineTo(l, t);
531            path.lineTo(r - mTabSliceWidth, t);
532            path.lineTo(r, b);
533        }
534
535    }
536
537    static Drawable createFaviconBackground(Context context) {
538        PaintDrawable faviconBackground = new PaintDrawable();
539        Resources res = context.getResources();
540        faviconBackground.getPaint().setColor(context.getResources()
541                .getColor(R.color.tabFaviconBackground));
542        faviconBackground.setCornerRadius(
543                res.getDimension(R.dimen.tab_favicon_corner_radius));
544        return faviconBackground;
545    }
546
547    private Drawable renderFavicon(Bitmap icon) {
548        Drawable[] array = new Drawable[2];
549        array[0] = createFaviconBackground(getContext());
550        if (icon == null) {
551            array[1] = mGenericFavicon;
552        } else {
553            array[1] = new BitmapDrawable(icon);
554        }
555        LayerDrawable d = new LayerDrawable(array);
556        d.setLayerInset(1, 2, 2, 2, 2);
557        return d;
558    }
559
560    private void animateTabOut(final Tab tab, final TabView tv) {
561        ObjectAnimator scalex = ObjectAnimator.ofFloat(tv, "scaleX", 1.0f, 0.0f);
562        ObjectAnimator scaley = ObjectAnimator.ofFloat(tv, "scaleY", 1.0f, 0.0f);
563        ObjectAnimator alpha = ObjectAnimator.ofFloat(tv, "alpha", 1.0f, 0.0f);
564        AnimatorSet animator = new AnimatorSet();
565        animator.playTogether(scalex, scaley, alpha);
566        animator.setDuration(150);
567        animator.addListener(new AnimatorListener() {
568
569            @Override
570            public void onAnimationCancel(Animator animation) {
571            }
572
573            @Override
574            public void onAnimationEnd(Animator animation) {
575                mTabs.removeTab(tv);
576                mTabMap.remove(tab);
577                mUi.onRemoveTabCompleted(tab);
578            }
579
580            @Override
581            public void onAnimationRepeat(Animator animation) {
582            }
583
584            @Override
585            public void onAnimationStart(Animator animation) {
586            }
587
588        });
589        animator.start();
590    }
591
592    private void animateTabIn(final Tab tab, final TabView tv) {
593        ObjectAnimator scalex = ObjectAnimator.ofFloat(tv, "scaleX", 0.0f, 1.0f);
594        scalex.setDuration(150);
595        scalex.addListener(new AnimatorListener() {
596
597            @Override
598            public void onAnimationCancel(Animator animation) {
599            }
600
601            @Override
602            public void onAnimationEnd(Animator animation) {
603                mUi.onAddTabCompleted(tab);
604            }
605
606            @Override
607            public void onAnimationRepeat(Animator animation) {
608            }
609
610            @Override
611            public void onAnimationStart(Animator animation) {
612                mTabs.addTab(tv);
613            }
614
615        });
616        scalex.start();
617    }
618
619    // TabChangeListener implementation
620
621    public void onSetActiveTab(Tab tab) {
622        mTabs.setSelectedTab(mTabControl.getTabPosition(tab));
623        TabView tv = mTabMap.get(tab);
624        if (tv != null) {
625            tv.setProgress(tv.mTab.getLoadProgress());
626            // update the scroll state
627            WebView webview = tab.getWebView();
628            if (webview != null) {
629                int h = webview.getVisibleTitleHeight();
630                onScroll(h, true);
631            }
632        }
633    }
634
635    public void onFavicon(Tab tab, Bitmap favicon) {
636        TabView tv = mTabMap.get(tab);
637        if (tv != null) {
638            tv.setFavicon(renderFavicon(favicon));
639        }
640    }
641
642    public void onNewTab(Tab tab) {
643        TabView tv = buildTabView(tab);
644        animateTabIn(tab, tv);
645    }
646
647    public void onProgress(Tab tab, int progress) {
648        TabView tv = mTabMap.get(tab);
649        if (tv != null) {
650            tv.setProgress(progress);
651        }
652    }
653
654    public void onRemoveTab(Tab tab) {
655        TabView tv = mTabMap.get(tab);
656        if (tv != null) {
657            animateTabOut(tab, tv);
658        } else {
659            mTabMap.remove(tab);
660        }
661    }
662
663    public void onUrlAndTitle(Tab tab, String url, String title) {
664        TabView tv = mTabMap.get(tab);
665        if (tv != null) {
666            if (title != null) {
667                tv.setDisplayTitle(title);
668            } else if (url != null) {
669                tv.setDisplayTitle(UrlUtils.stripUrl(url));
670            }
671            tv.updateTabIcons();
672        }
673    }
674
675    private boolean isLoading() {
676        TabView tv = mTabMap.get(mTabControl.getCurrentTab());
677        if (tv != null) {
678            return tv.mInLoad;
679        } else {
680            return false;
681        }
682    }
683
684}
685