PhoneWindow.java revision 31bb97d240915d6ead410ab0befd3da115a92282
1/*
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16package com.android.internal.policy.impl;
17
18import static android.view.View.MeasureSpec.AT_MOST;
19import static android.view.View.MeasureSpec.EXACTLY;
20import static android.view.View.MeasureSpec.getMode;
21import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
22import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
23import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
24import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
25import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
26import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
27import static android.view.WindowManager.LayoutParams.FLAG_SPLIT_TOUCH;
28
29import com.android.internal.view.RootViewSurfaceTaker;
30import com.android.internal.view.StandaloneActionMode;
31import com.android.internal.view.menu.ContextMenuBuilder;
32import com.android.internal.view.menu.IconMenuPresenter;
33import com.android.internal.view.menu.ListMenuPresenter;
34import com.android.internal.view.menu.MenuBuilder;
35import com.android.internal.view.menu.MenuDialogHelper;
36import com.android.internal.view.menu.MenuPresenter;
37import com.android.internal.view.menu.MenuView;
38import com.android.internal.view.menu.SubMenuBuilder;
39import com.android.internal.widget.ActionBarContainer;
40import com.android.internal.widget.ActionBarContextView;
41import com.android.internal.widget.ActionBarView;
42
43import android.app.KeyguardManager;
44import android.content.Context;
45import android.content.res.Configuration;
46import android.content.res.TypedArray;
47import android.graphics.Canvas;
48import android.graphics.PixelFormat;
49import android.graphics.Rect;
50import android.graphics.drawable.Drawable;
51import android.media.AudioManager;
52import android.net.Uri;
53import android.os.Bundle;
54import android.os.Parcel;
55import android.os.Parcelable;
56import android.util.AndroidRuntimeException;
57import android.util.DisplayMetrics;
58import android.util.EventLog;
59import android.util.Log;
60import android.util.SparseArray;
61import android.util.TypedValue;
62import android.view.ActionMode;
63import android.view.Gravity;
64import android.view.InputQueue;
65import android.view.KeyCharacterMap;
66import android.view.KeyEvent;
67import android.view.LayoutInflater;
68import android.view.Menu;
69import android.view.MenuItem;
70import android.view.MotionEvent;
71import android.view.SurfaceHolder;
72import android.view.View;
73import android.view.ViewGroup;
74import android.view.ViewManager;
75import android.view.ViewStub;
76import android.view.Window;
77import android.view.WindowManager;
78import android.view.accessibility.AccessibilityEvent;
79import android.view.accessibility.AccessibilityManager;
80import android.view.animation.Animation;
81import android.view.animation.AnimationUtils;
82import android.widget.FrameLayout;
83import android.widget.ImageView;
84import android.widget.PopupWindow;
85import android.widget.ProgressBar;
86import android.widget.TextView;
87
88/**
89 * Android-specific Window.
90 * <p>
91 * todo: need to pull the generic functionality out into a base class
92 * in android.widget.
93 */
94public class PhoneWindow extends Window implements MenuBuilder.Callback {
95
96    private final static String TAG = "PhoneWindow";
97
98    private final static boolean SWEEP_OPEN_MENU = false;
99
100    /**
101     * Simple callback used by the context menu and its submenus. The options
102     * menu submenus do not use this (their behavior is more complex).
103     */
104    final DialogMenuCallback mContextMenuCallback = new DialogMenuCallback(FEATURE_CONTEXT_MENU);
105
106    final TypedValue mMinWidthMajor = new TypedValue();
107    final TypedValue mMinWidthMinor = new TypedValue();
108
109    // This is the top-level view of the window, containing the window decor.
110    private DecorView mDecor;
111
112    // This is the view in which the window contents are placed. It is either
113    // mDecor itself, or a child of mDecor where the contents go.
114    private ViewGroup mContentParent;
115
116    SurfaceHolder.Callback2 mTakeSurfaceCallback;
117
118    InputQueue.Callback mTakeInputQueueCallback;
119
120    private boolean mIsFloating;
121
122    private LayoutInflater mLayoutInflater;
123
124    private TextView mTitleView;
125
126    private ActionBarView mActionBar;
127    private ActionMenuPresenterCallback mActionMenuPresenterCallback;
128    private PanelMenuPresenterCallback mPanelMenuPresenterCallback;
129
130    private DrawableFeatureState[] mDrawables;
131
132    private PanelFeatureState[] mPanels;
133
134    /**
135     * The panel that is prepared or opened (the most recent one if there are
136     * multiple panels). Shortcuts will go to this panel. It gets set in
137     * {@link #preparePanel} and cleared in {@link #closePanel}.
138     */
139    private PanelFeatureState mPreparedPanel;
140
141    /**
142     * The keycode that is currently held down (as a modifier) for chording. If
143     * this is 0, there is no key held down.
144     */
145    private int mPanelChordingKey;
146
147    private ImageView mLeftIconView;
148
149    private ImageView mRightIconView;
150
151    private ProgressBar mCircularProgressBar;
152
153    private ProgressBar mHorizontalProgressBar;
154
155    private int mBackgroundResource = 0;
156
157    private Drawable mBackgroundDrawable;
158
159    private int mFrameResource = 0;
160
161    private int mTextColor = 0;
162
163    private CharSequence mTitle = null;
164
165    private int mTitleColor = 0;
166
167    private boolean mAlwaysReadCloseOnTouchAttr = false;
168
169    private ContextMenuBuilder mContextMenu;
170    private MenuDialogHelper mContextMenuHelper;
171    private boolean mClosingActionMenu;
172
173    private int mVolumeControlStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE;
174
175    private AudioManager mAudioManager;
176    private KeyguardManager mKeyguardManager;
177
178    public PhoneWindow(Context context) {
179        super(context);
180        mLayoutInflater = LayoutInflater.from(context);
181    }
182
183    @Override
184    public final void setContainer(Window container) {
185        super.setContainer(container);
186    }
187
188    @Override
189    public boolean requestFeature(int featureId) {
190        if (mContentParent != null) {
191            throw new AndroidRuntimeException("requestFeature() must be called before adding content");
192        }
193        final int features = getFeatures();
194        if ((features != DEFAULT_FEATURES) && (featureId == FEATURE_CUSTOM_TITLE)) {
195
196            /* Another feature is enabled and the user is trying to enable the custom title feature */
197            throw new AndroidRuntimeException("You cannot combine custom titles with other title features");
198        }
199        if (((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) &&
200                (featureId != FEATURE_CUSTOM_TITLE) && (featureId != FEATURE_ACTION_MODE_OVERLAY)) {
201
202            /* Custom title feature is enabled and the user is trying to enable another feature */
203            throw new AndroidRuntimeException("You cannot combine custom titles with other title features");
204        }
205        if ((features & (1 << FEATURE_NO_TITLE)) != 0 && featureId == FEATURE_ACTION_BAR) {
206            return false; // Ignore. No title dominates.
207        }
208        if ((features & (1 << FEATURE_ACTION_BAR)) != 0 && featureId == FEATURE_NO_TITLE) {
209            // Remove the action bar feature if we have no title. No title dominates.
210            removeFeature(FEATURE_ACTION_BAR);
211        }
212        return super.requestFeature(featureId);
213    }
214
215    @Override
216    public void setContentView(int layoutResID) {
217        if (mContentParent == null) {
218            installDecor();
219        } else {
220            mContentParent.removeAllViews();
221        }
222        mLayoutInflater.inflate(layoutResID, mContentParent);
223        final Callback cb = getCallback();
224        if (cb != null && !isDestroyed()) {
225            cb.onContentChanged();
226        }
227    }
228
229    @Override
230    public void setContentView(View view) {
231        setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
232    }
233
234    @Override
235    public void setContentView(View view, ViewGroup.LayoutParams params) {
236        if (mContentParent == null) {
237            installDecor();
238        } else {
239            mContentParent.removeAllViews();
240        }
241        mContentParent.addView(view, params);
242        final Callback cb = getCallback();
243        if (cb != null && !isDestroyed()) {
244            cb.onContentChanged();
245        }
246    }
247
248    @Override
249    public void addContentView(View view, ViewGroup.LayoutParams params) {
250        if (mContentParent == null) {
251            installDecor();
252        }
253        mContentParent.addView(view, params);
254        final Callback cb = getCallback();
255        if (cb != null && !isDestroyed()) {
256            cb.onContentChanged();
257        }
258    }
259
260    @Override
261    public View getCurrentFocus() {
262        return mDecor != null ? mDecor.findFocus() : null;
263    }
264
265    @Override
266    public void takeSurface(SurfaceHolder.Callback2 callback) {
267        mTakeSurfaceCallback = callback;
268    }
269
270    public void takeInputQueue(InputQueue.Callback callback) {
271        mTakeInputQueueCallback = callback;
272    }
273
274    @Override
275    public boolean isFloating() {
276        return mIsFloating;
277    }
278
279    /**
280     * Return a LayoutInflater instance that can be used to inflate XML view layout
281     * resources for use in this Window.
282     *
283     * @return LayoutInflater The shared LayoutInflater.
284     */
285    @Override
286    public LayoutInflater getLayoutInflater() {
287        return mLayoutInflater;
288    }
289
290    @Override
291    public void setTitle(CharSequence title) {
292        if (mTitleView != null) {
293            mTitleView.setText(title);
294        } else if (mActionBar != null) {
295            mActionBar.setWindowTitle(title);
296        }
297        mTitle = title;
298    }
299
300    @Override
301    public void setTitleColor(int textColor) {
302        if (mTitleView != null) {
303            mTitleView.setTextColor(textColor);
304        }
305        mTitleColor = textColor;
306    }
307
308    /**
309     * Prepares the panel to either be opened or chorded. This creates the Menu
310     * instance for the panel and populates it via the Activity callbacks.
311     *
312     * @param st The panel state to prepare.
313     * @param event The event that triggered the preparing of the panel.
314     * @return Whether the panel was prepared. If the panel should not be shown,
315     *         returns false.
316     */
317    public final boolean preparePanel(PanelFeatureState st, KeyEvent event) {
318        if (isDestroyed()) {
319            return false;
320        }
321
322        // Already prepared (isPrepared will be reset to false later)
323        if (st.isPrepared)
324            return true;
325
326        if ((mPreparedPanel != null) && (mPreparedPanel != st)) {
327            // Another Panel is prepared and possibly open, so close it
328            closePanel(mPreparedPanel, false);
329        }
330
331        final Callback cb = getCallback();
332
333        if (cb != null) {
334            st.createdPanelView = cb.onCreatePanelView(st.featureId);
335        }
336
337        if (st.createdPanelView == null) {
338            // Init the panel state's menu--return false if init failed
339            if (st.menu == null || st.refreshMenuContent) {
340                if (st.menu == null) {
341                    if (!initializePanelMenu(st) || (st.menu == null)) {
342                        return false;
343                    }
344                }
345
346                // Call callback, and return if it doesn't want to display menu.
347
348                // Creating the panel menu will involve a lot of manipulation;
349                // don't dispatch change events to presenters until we're done.
350                st.menu.stopDispatchingItemsChanged();
351                if ((cb == null) || !cb.onCreatePanelMenu(st.featureId, st.menu)) {
352                    // Ditch the menu created above
353                    st.menu = null;
354
355                    return false;
356                }
357
358                st.refreshMenuContent = false;
359
360                if (mActionBar != null) {
361                    if (mActionMenuPresenterCallback == null) {
362                        mActionMenuPresenterCallback = new ActionMenuPresenterCallback();
363                    }
364                    mActionBar.setMenu(st.menu, mActionMenuPresenterCallback);
365                }
366            }
367
368            // Callback and return if the callback does not want to show the menu
369
370            // Preparing the panel menu can involve a lot of manipulation;
371            // don't dispatch change events to presenters until we're done.
372            st.menu.stopDispatchingItemsChanged();
373            if (!cb.onPreparePanel(st.featureId, st.createdPanelView, st.menu)) {
374                st.menu.startDispatchingItemsChanged();
375                return false;
376            }
377            st.menu.startDispatchingItemsChanged();
378
379            // Set the proper keymap
380            KeyCharacterMap kmap = KeyCharacterMap.load(
381                    event != null ? event.getDeviceId() : KeyCharacterMap.VIRTUAL_KEYBOARD);
382            st.qwertyMode = kmap.getKeyboardType() != KeyCharacterMap.NUMERIC;
383            st.menu.setQwertyMode(st.qwertyMode);
384        }
385
386        // Set other state
387        st.isPrepared = true;
388        st.isHandled = false;
389        mPreparedPanel = st;
390
391        return true;
392    }
393
394    @Override
395    public void onConfigurationChanged(Configuration newConfig) {
396        // Action bars handle their own menu state
397        if (mActionBar == null) {
398            PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
399            if ((st != null) && (st.menu != null)) {
400                if (st.isOpen) {
401                    // Freeze state
402                    final Bundle state = new Bundle();
403                    if (st.iconMenuPresenter != null) {
404                        st.iconMenuPresenter.saveHierarchyState(state);
405                    }
406                    if (st.expandedMenuPresenter != null) {
407                        st.expandedMenuPresenter.saveHierarchyState(state);
408                    }
409
410                    // Remove the menu views since they need to be recreated
411                    // according to the new configuration
412                    clearMenuViews(st);
413
414                    // Re-open the same menu
415                    reopenMenu(false);
416
417                    // Restore state
418                    if (st.iconMenuPresenter != null) {
419                        st.iconMenuPresenter.restoreHierarchyState(state);
420                    }
421                    if (st.expandedMenuPresenter != null) {
422                        st.expandedMenuPresenter.restoreHierarchyState(state);
423                    }
424
425                } else {
426                    // Clear menu views so on next menu opening, it will use
427                    // the proper layout
428                    clearMenuViews(st);
429                }
430            }
431        }
432    }
433
434    private static void clearMenuViews(PanelFeatureState st) {
435        // This can be called on config changes, so we should make sure
436        // the views will be reconstructed based on the new orientation, etc.
437
438        // Allow the callback to create a new panel view
439        st.createdPanelView = null;
440
441        // Causes the decor view to be recreated
442        st.refreshDecorView = true;
443
444        st.clearMenuPresenters();
445    }
446
447    @Override
448    public final void openPanel(int featureId, KeyEvent event) {
449        if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
450                mActionBar.isOverflowReserved()) {
451            if (mActionBar.getVisibility() == View.VISIBLE) {
452                // Invalidate the options menu, we want a prepare event that the app can respond to.
453                invalidatePanelMenu(FEATURE_OPTIONS_PANEL);
454                mActionBar.showOverflowMenu();
455            }
456        } else {
457            openPanel(getPanelState(featureId, true), event);
458        }
459    }
460
461    private void openPanel(PanelFeatureState st, KeyEvent event) {
462        // System.out.println("Open panel: isOpen=" + st.isOpen);
463
464        // Already open, return
465        if (st.isOpen || isDestroyed()) {
466            return;
467        }
468
469        // Don't open an options panel for honeycomb apps on xlarge devices.
470        // (The app should be using an action bar for menu items.)
471        if (st.featureId == FEATURE_OPTIONS_PANEL) {
472            Context context = getContext();
473            Configuration config = context.getResources().getConfiguration();
474            boolean isXLarge = (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
475                    Configuration.SCREENLAYOUT_SIZE_XLARGE;
476            boolean isHoneycombApp = context.getApplicationInfo().targetSdkVersion >=
477                    android.os.Build.VERSION_CODES.HONEYCOMB;
478
479            if (isXLarge && isHoneycombApp) {
480                return;
481            }
482        }
483
484        Callback cb = getCallback();
485        if ((cb != null) && (!cb.onMenuOpened(st.featureId, st.menu))) {
486            // Callback doesn't want the menu to open, reset any state
487            closePanel(st, true);
488            return;
489        }
490
491        final WindowManager wm = getWindowManager();
492        if (wm == null) {
493            return;
494        }
495
496        // Prepare panel (should have been done before, but just in case)
497        if (!preparePanel(st, event)) {
498            return;
499        }
500
501        if (st.decorView == null || st.refreshDecorView) {
502            if (st.decorView == null) {
503                // Initialize the panel decor, this will populate st.decorView
504                if (!initializePanelDecor(st) || (st.decorView == null))
505                    return;
506            } else if (st.refreshDecorView && (st.decorView.getChildCount() > 0)) {
507                // Decor needs refreshing, so remove its views
508                st.decorView.removeAllViews();
509            }
510
511            // This will populate st.shownPanelView
512            if (!initializePanelContent(st) || !st.hasPanelItems()) {
513                return;
514            }
515
516            ViewGroup.LayoutParams lp = st.shownPanelView.getLayoutParams();
517            if (lp == null) {
518                lp = new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
519            }
520
521            int backgroundResId;
522            if (lp.width == ViewGroup.LayoutParams.MATCH_PARENT) {
523                // If the contents is fill parent for the width, set the
524                // corresponding background
525                backgroundResId = st.fullBackground;
526            } else {
527                // Otherwise, set the normal panel background
528                backgroundResId = st.background;
529            }
530            st.decorView.setWindowBackground(getContext().getResources().getDrawable(
531                    backgroundResId));
532
533
534            st.decorView.addView(st.shownPanelView, lp);
535
536            /*
537             * Give focus to the view, if it or one of its children does not
538             * already have it.
539             */
540            if (!st.shownPanelView.hasFocus()) {
541                st.shownPanelView.requestFocus();
542            }
543        }
544
545        st.isOpen = true;
546        st.isHandled = false;
547
548        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
549                WRAP_CONTENT, WRAP_CONTENT,
550                st.x, st.y, WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG,
551                WindowManager.LayoutParams.FLAG_DITHER
552                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
553                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
554                st.decorView.mDefaultOpacity);
555
556        lp.gravity = st.gravity;
557        lp.windowAnimations = st.windowAnimations;
558
559        wm.addView(st.decorView, lp);
560        // Log.v(TAG, "Adding main menu to window manager.");
561    }
562
563    @Override
564    public final void closePanel(int featureId) {
565        if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
566                mActionBar.isOverflowReserved()) {
567            mActionBar.hideOverflowMenu();
568        } else if (featureId == FEATURE_CONTEXT_MENU) {
569            closeContextMenu();
570        } else {
571            closePanel(getPanelState(featureId, true), true);
572        }
573    }
574
575    /**
576     * Closes the given panel.
577     *
578     * @param st The panel to be closed.
579     * @param doCallback Whether to notify the callback that the panel was
580     *            closed. If the panel is in the process of re-opening or
581     *            opening another panel (e.g., menu opening a sub menu), the
582     *            callback should not happen and this variable should be false.
583     *            In addition, this method internally will only perform the
584     *            callback if the panel is open.
585     */
586    public final void closePanel(PanelFeatureState st, boolean doCallback) {
587        // System.out.println("Close panel: isOpen=" + st.isOpen);
588        if (doCallback && st.featureId == FEATURE_OPTIONS_PANEL &&
589                mActionBar != null && mActionBar.isOverflowMenuShowing()) {
590            checkCloseActionMenu(st.menu);
591            return;
592        }
593
594        final ViewManager wm = getWindowManager();
595        if ((wm != null) && st.isOpen) {
596            if (st.decorView != null) {
597                wm.removeView(st.decorView);
598                // Log.v(TAG, "Removing main menu from window manager.");
599            }
600
601            if (doCallback) {
602                callOnPanelClosed(st.featureId, st, null);
603            }
604        }
605
606        st.isPrepared = false;
607        st.isHandled = false;
608        st.isOpen = false;
609
610        // This view is no longer shown, so null it out
611        st.shownPanelView = null;
612
613        if (st.isInExpandedMode) {
614            // Next time the menu opens, it should not be in expanded mode, so
615            // force a refresh of the decor
616            st.refreshDecorView = true;
617            st.isInExpandedMode = false;
618        }
619
620        if (mPreparedPanel == st) {
621            mPreparedPanel = null;
622            mPanelChordingKey = 0;
623        }
624    }
625
626    void checkCloseActionMenu(Menu menu) {
627        if (mClosingActionMenu) {
628            return;
629        }
630
631        mClosingActionMenu = true;
632        mActionBar.dismissPopupMenus();
633        Callback cb = getCallback();
634        if (cb != null && !isDestroyed()) {
635            cb.onPanelClosed(FEATURE_ACTION_BAR, menu);
636        }
637        mClosingActionMenu = false;
638    }
639
640    @Override
641    public final void togglePanel(int featureId, KeyEvent event) {
642        PanelFeatureState st = getPanelState(featureId, true);
643        if (st.isOpen) {
644            closePanel(st, true);
645        } else {
646            openPanel(st, event);
647        }
648    }
649
650    @Override
651    public void invalidatePanelMenu(int featureId) {
652        PanelFeatureState st = getPanelState(featureId, true);
653        if (st.menu != null) {
654            st.menu.clear();
655        }
656        st.refreshMenuContent = true;
657        st.refreshDecorView = true;
658
659        // Prepare the options panel if we have an action bar
660        if ((featureId == FEATURE_ACTION_BAR || featureId == FEATURE_OPTIONS_PANEL)
661                && mActionBar != null) {
662            st = getPanelState(Window.FEATURE_OPTIONS_PANEL, false);
663            if (st != null) {
664                st.isPrepared = false;
665                preparePanel(st, null);
666            }
667        }
668    }
669
670    /**
671     * Called when the panel key is pushed down.
672     * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}.
673     * @param event The key event.
674     * @return Whether the key was handled.
675     */
676    public final boolean onKeyDownPanel(int featureId, KeyEvent event) {
677        final int keyCode = event.getKeyCode();
678
679        if (event.getRepeatCount() == 0) {
680            // The panel key was pushed, so set the chording key
681            mPanelChordingKey = keyCode;
682
683            PanelFeatureState st = getPanelState(featureId, true);
684            if (!st.isOpen) {
685                return preparePanel(st, event);
686            }
687        }
688
689        return false;
690    }
691
692    /**
693     * Called when the panel key is released.
694     * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}.
695     * @param event The key event.
696     */
697    public final void onKeyUpPanel(int featureId, KeyEvent event) {
698        // The panel key was released, so clear the chording key
699        if (mPanelChordingKey != 0) {
700            mPanelChordingKey = 0;
701
702            if (event.isCanceled()) {
703                return;
704            }
705
706            boolean playSoundEffect = false;
707            final PanelFeatureState st = getPanelState(featureId, true);
708            if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
709                    mActionBar.isOverflowReserved()) {
710                if (mActionBar.getVisibility() == View.VISIBLE) {
711                    if (!mActionBar.isOverflowMenuShowing()) {
712                        final Callback cb = getCallback();
713                        if (cb != null && !isDestroyed() &&
714                                cb.onPreparePanel(featureId, st.createdPanelView, st.menu)) {
715                            playSoundEffect = mActionBar.showOverflowMenu();
716                        }
717                    } else {
718                        playSoundEffect = mActionBar.hideOverflowMenu();
719                    }
720                }
721            } else {
722                if (st.isOpen || st.isHandled) {
723
724                    // Play the sound effect if the user closed an open menu (and not if
725                    // they just released a menu shortcut)
726                    playSoundEffect = st.isOpen;
727
728                    // Close menu
729                    closePanel(st, true);
730
731                } else if (st.isPrepared) {
732
733                    // Write 'menu opened' to event log
734                    EventLog.writeEvent(50001, 0);
735
736                    // Show menu
737                    openPanel(st, event);
738
739                    playSoundEffect = true;
740                }
741            }
742
743            if (playSoundEffect) {
744                AudioManager audioManager = (AudioManager) getContext().getSystemService(
745                        Context.AUDIO_SERVICE);
746                if (audioManager != null) {
747                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
748                } else {
749                    Log.w(TAG, "Couldn't get audio manager");
750                }
751            }
752        }
753    }
754
755    @Override
756    public final void closeAllPanels() {
757        final ViewManager wm = getWindowManager();
758        if (wm == null) {
759            return;
760        }
761
762        final PanelFeatureState[] panels = mPanels;
763        final int N = panels != null ? panels.length : 0;
764        for (int i = 0; i < N; i++) {
765            final PanelFeatureState panel = panels[i];
766            if (panel != null) {
767                closePanel(panel, true);
768            }
769        }
770
771        closeContextMenu();
772    }
773
774    /**
775     * Closes the context menu. This notifies the menu logic of the close, along
776     * with dismissing it from the UI.
777     */
778    private synchronized void closeContextMenu() {
779        if (mContextMenu != null) {
780            mContextMenu.close();
781            dismissContextMenu();
782        }
783    }
784
785    /**
786     * Dismisses just the context menu UI. To close the context menu, use
787     * {@link #closeContextMenu()}.
788     */
789    private synchronized void dismissContextMenu() {
790        mContextMenu = null;
791
792        if (mContextMenuHelper != null) {
793            mContextMenuHelper.dismiss();
794            mContextMenuHelper = null;
795        }
796    }
797
798    @Override
799    public boolean performPanelShortcut(int featureId, int keyCode, KeyEvent event, int flags) {
800        return performPanelShortcut(getPanelState(featureId, true), keyCode, event, flags);
801    }
802
803    private boolean performPanelShortcut(PanelFeatureState st, int keyCode, KeyEvent event,
804            int flags) {
805        if (event.isSystem() || (st == null)) {
806            return false;
807        }
808
809        boolean handled = false;
810
811        // Only try to perform menu shortcuts if preparePanel returned true (possible false
812        // return value from application not wanting to show the menu).
813        if ((st.isPrepared || preparePanel(st, event)) && st.menu != null) {
814            // The menu is prepared now, perform the shortcut on it
815            handled = st.menu.performShortcut(keyCode, event, flags);
816        }
817
818        if (handled) {
819            // Mark as handled
820            st.isHandled = true;
821
822            if ((flags & Menu.FLAG_PERFORM_NO_CLOSE) == 0) {
823                closePanel(st, true);
824            }
825        }
826
827        return handled;
828    }
829
830    @Override
831    public boolean performPanelIdentifierAction(int featureId, int id, int flags) {
832
833        PanelFeatureState st = getPanelState(featureId, true);
834        if (!preparePanel(st, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU))) {
835            return false;
836        }
837        if (st.menu == null) {
838            return false;
839        }
840
841        boolean res = st.menu.performIdentifierAction(id, flags);
842
843        closePanel(st, true);
844
845        return res;
846    }
847
848    public PanelFeatureState findMenuPanel(Menu menu) {
849        final PanelFeatureState[] panels = mPanels;
850        final int N = panels != null ? panels.length : 0;
851        for (int i = 0; i < N; i++) {
852            final PanelFeatureState panel = panels[i];
853            if (panel != null && panel.menu == menu) {
854                return panel;
855            }
856        }
857        return null;
858    }
859
860    public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
861        final Callback cb = getCallback();
862        if (cb != null && !isDestroyed()) {
863            final PanelFeatureState panel = findMenuPanel(menu.getRootMenu());
864            if (panel != null) {
865                return cb.onMenuItemSelected(panel.featureId, item);
866            }
867        }
868        return false;
869    }
870
871    public void onMenuModeChange(MenuBuilder menu) {
872        reopenMenu(true);
873    }
874
875    private void reopenMenu(boolean toggleMenuMode) {
876        if (mActionBar != null && mActionBar.isOverflowReserved()) {
877            final Callback cb = getCallback();
878            if (!mActionBar.isOverflowMenuShowing() || !toggleMenuMode) {
879                if (cb != null && !isDestroyed() && mActionBar.getVisibility() == View.VISIBLE) {
880                    final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
881                    if (cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) {
882                        cb.onMenuOpened(FEATURE_ACTION_BAR, st.menu);
883                        mActionBar.showOverflowMenu();
884                    }
885                }
886            } else {
887                mActionBar.hideOverflowMenu();
888                if (cb != null && !isDestroyed()) {
889                    final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
890                    cb.onPanelClosed(FEATURE_ACTION_BAR, st.menu);
891                }
892            }
893            return;
894        }
895
896        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
897
898        // Save the future expanded mode state since closePanel will reset it
899        boolean newExpandedMode = toggleMenuMode ? !st.isInExpandedMode : st.isInExpandedMode;
900
901        st.refreshDecorView = true;
902        closePanel(st, false);
903
904        // Set the expanded mode state
905        st.isInExpandedMode = newExpandedMode;
906
907        openPanel(st, null);
908    }
909
910    /**
911     * Initializes the menu associated with the given panel feature state. You
912     * must at the very least set PanelFeatureState.menu to the Menu to be
913     * associated with the given panel state. The default implementation creates
914     * a new menu for the panel state.
915     *
916     * @param st The panel whose menu is being initialized.
917     * @return Whether the initialization was successful.
918     */
919    protected boolean initializePanelMenu(final PanelFeatureState st) {
920        final MenuBuilder menu = new MenuBuilder(getContext());
921
922        menu.setCallback(this);
923        st.setMenu(menu);
924
925        return true;
926    }
927
928    /**
929     * Perform initial setup of a panel. This should at the very least set the
930     * style information in the PanelFeatureState and must set
931     * PanelFeatureState.decor to the panel's window decor view.
932     *
933     * @param st The panel being initialized.
934     */
935    protected boolean initializePanelDecor(PanelFeatureState st) {
936        st.decorView = new DecorView(getContext(), st.featureId);
937        st.gravity = Gravity.CENTER | Gravity.BOTTOM;
938        st.setStyle(getContext());
939
940        return true;
941    }
942
943    /**
944     * Initializes the panel associated with the panel feature state. You must
945     * at the very least set PanelFeatureState.panel to the View implementing
946     * its contents. The default implementation gets the panel from the menu.
947     *
948     * @param st The panel state being initialized.
949     * @return Whether the initialization was successful.
950     */
951    protected boolean initializePanelContent(PanelFeatureState st) {
952        if (st.createdPanelView != null) {
953            st.shownPanelView = st.createdPanelView;
954            return true;
955        }
956
957        if (st.menu == null) {
958            return false;
959        }
960
961        if (mPanelMenuPresenterCallback == null) {
962            mPanelMenuPresenterCallback = new PanelMenuPresenterCallback();
963        }
964
965        MenuView menuView = st.isInExpandedMode
966                ? st.getExpandedMenuView(mPanelMenuPresenterCallback)
967                : st.getIconMenuView(mPanelMenuPresenterCallback);
968
969        st.shownPanelView = (View) menuView;
970
971        if (st.shownPanelView != null) {
972            // Use the menu View's default animations if it has any
973            final int defaultAnimations = menuView.getWindowAnimations();
974            if (defaultAnimations != 0) {
975                st.windowAnimations = defaultAnimations;
976            }
977            return true;
978        } else {
979            return false;
980        }
981    }
982
983    @Override
984    public boolean performContextMenuIdentifierAction(int id, int flags) {
985        return (mContextMenu != null) ? mContextMenu.performIdentifierAction(id, flags) : false;
986    }
987
988    @Override
989    public final void setBackgroundDrawable(Drawable drawable) {
990        if (drawable != mBackgroundDrawable || mBackgroundResource != 0) {
991            mBackgroundResource = 0;
992            mBackgroundDrawable = drawable;
993            if (mDecor != null) {
994                mDecor.setWindowBackground(drawable);
995            }
996        }
997    }
998
999    @Override
1000    public final void setFeatureDrawableResource(int featureId, int resId) {
1001        if (resId != 0) {
1002            DrawableFeatureState st = getDrawableState(featureId, true);
1003            if (st.resid != resId) {
1004                st.resid = resId;
1005                st.uri = null;
1006                st.local = getContext().getResources().getDrawable(resId);
1007                updateDrawable(featureId, st, false);
1008            }
1009        } else {
1010            setFeatureDrawable(featureId, null);
1011        }
1012    }
1013
1014    @Override
1015    public final void setFeatureDrawableUri(int featureId, Uri uri) {
1016        if (uri != null) {
1017            DrawableFeatureState st = getDrawableState(featureId, true);
1018            if (st.uri == null || !st.uri.equals(uri)) {
1019                st.resid = 0;
1020                st.uri = uri;
1021                st.local = loadImageURI(uri);
1022                updateDrawable(featureId, st, false);
1023            }
1024        } else {
1025            setFeatureDrawable(featureId, null);
1026        }
1027    }
1028
1029    @Override
1030    public final void setFeatureDrawable(int featureId, Drawable drawable) {
1031        DrawableFeatureState st = getDrawableState(featureId, true);
1032        st.resid = 0;
1033        st.uri = null;
1034        if (st.local != drawable) {
1035            st.local = drawable;
1036            updateDrawable(featureId, st, false);
1037        }
1038    }
1039
1040    @Override
1041    public void setFeatureDrawableAlpha(int featureId, int alpha) {
1042        DrawableFeatureState st = getDrawableState(featureId, true);
1043        if (st.alpha != alpha) {
1044            st.alpha = alpha;
1045            updateDrawable(featureId, st, false);
1046        }
1047    }
1048
1049    protected final void setFeatureDefaultDrawable(int featureId, Drawable drawable) {
1050        DrawableFeatureState st = getDrawableState(featureId, true);
1051        if (st.def != drawable) {
1052            st.def = drawable;
1053            updateDrawable(featureId, st, false);
1054        }
1055    }
1056
1057    @Override
1058    public final void setFeatureInt(int featureId, int value) {
1059        // XXX Should do more management (as with drawable features) to
1060        // deal with interactions between multiple window policies.
1061        updateInt(featureId, value, false);
1062    }
1063
1064    /**
1065     * Update the state of a drawable feature. This should be called, for every
1066     * drawable feature supported, as part of onActive(), to make sure that the
1067     * contents of a containing window is properly updated.
1068     *
1069     * @see #onActive
1070     * @param featureId The desired drawable feature to change.
1071     * @param fromActive Always true when called from onActive().
1072     */
1073    protected final void updateDrawable(int featureId, boolean fromActive) {
1074        final DrawableFeatureState st = getDrawableState(featureId, false);
1075        if (st != null) {
1076            updateDrawable(featureId, st, fromActive);
1077        }
1078    }
1079
1080    /**
1081     * Called when a Drawable feature changes, for the window to update its
1082     * graphics.
1083     *
1084     * @param featureId The feature being changed.
1085     * @param drawable The new Drawable to show, or null if none.
1086     * @param alpha The new alpha blending of the Drawable.
1087     */
1088    protected void onDrawableChanged(int featureId, Drawable drawable, int alpha) {
1089        ImageView view;
1090        if (featureId == FEATURE_LEFT_ICON) {
1091            view = getLeftIconView();
1092        } else if (featureId == FEATURE_RIGHT_ICON) {
1093            view = getRightIconView();
1094        } else {
1095            return;
1096        }
1097
1098        if (drawable != null) {
1099            drawable.setAlpha(alpha);
1100            view.setImageDrawable(drawable);
1101            view.setVisibility(View.VISIBLE);
1102        } else {
1103            view.setVisibility(View.GONE);
1104        }
1105    }
1106
1107    /**
1108     * Called when an int feature changes, for the window to update its
1109     * graphics.
1110     *
1111     * @param featureId The feature being changed.
1112     * @param value The new integer value.
1113     */
1114    protected void onIntChanged(int featureId, int value) {
1115        if (featureId == FEATURE_PROGRESS || featureId == FEATURE_INDETERMINATE_PROGRESS) {
1116            updateProgressBars(value);
1117        } else if (featureId == FEATURE_CUSTOM_TITLE) {
1118            FrameLayout titleContainer = (FrameLayout) findViewById(com.android.internal.R.id.title_container);
1119            if (titleContainer != null) {
1120                mLayoutInflater.inflate(value, titleContainer);
1121            }
1122        }
1123    }
1124
1125    /**
1126     * Updates the progress bars that are shown in the title bar.
1127     *
1128     * @param value Can be one of {@link Window#PROGRESS_VISIBILITY_ON},
1129     *            {@link Window#PROGRESS_VISIBILITY_OFF},
1130     *            {@link Window#PROGRESS_INDETERMINATE_ON},
1131     *            {@link Window#PROGRESS_INDETERMINATE_OFF}, or a value
1132     *            starting at {@link Window#PROGRESS_START} through
1133     *            {@link Window#PROGRESS_END} for setting the default
1134     *            progress (if {@link Window#PROGRESS_END} is given,
1135     *            the progress bar widgets in the title will be hidden after an
1136     *            animation), a value between
1137     *            {@link Window#PROGRESS_SECONDARY_START} -
1138     *            {@link Window#PROGRESS_SECONDARY_END} for the
1139     *            secondary progress (if
1140     *            {@link Window#PROGRESS_SECONDARY_END} is given, the
1141     *            progress bar widgets will still be shown with the secondary
1142     *            progress bar will be completely filled in.)
1143     */
1144    private void updateProgressBars(int value) {
1145        ProgressBar circularProgressBar = getCircularProgressBar(true);
1146        ProgressBar horizontalProgressBar = getHorizontalProgressBar(true);
1147
1148        final int features = getLocalFeatures();
1149        if (value == PROGRESS_VISIBILITY_ON) {
1150            if ((features & (1 << FEATURE_PROGRESS)) != 0) {
1151                int level = horizontalProgressBar.getProgress();
1152                int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ?
1153                        View.VISIBLE : View.INVISIBLE;
1154                horizontalProgressBar.setVisibility(visibility);
1155            }
1156            if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
1157                circularProgressBar.setVisibility(View.VISIBLE);
1158            }
1159        } else if (value == PROGRESS_VISIBILITY_OFF) {
1160            if ((features & (1 << FEATURE_PROGRESS)) != 0) {
1161                horizontalProgressBar.setVisibility(View.GONE);
1162            }
1163            if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
1164                circularProgressBar.setVisibility(View.GONE);
1165            }
1166        } else if (value == PROGRESS_INDETERMINATE_ON) {
1167            horizontalProgressBar.setIndeterminate(true);
1168        } else if (value == PROGRESS_INDETERMINATE_OFF) {
1169            horizontalProgressBar.setIndeterminate(false);
1170        } else if (PROGRESS_START <= value && value <= PROGRESS_END) {
1171            // We want to set the progress value before testing for visibility
1172            // so that when the progress bar becomes visible again, it has the
1173            // correct level.
1174            horizontalProgressBar.setProgress(value - PROGRESS_START);
1175
1176            if (value < PROGRESS_END) {
1177                showProgressBars(horizontalProgressBar, circularProgressBar);
1178            } else {
1179                hideProgressBars(horizontalProgressBar, circularProgressBar);
1180            }
1181        } else if (PROGRESS_SECONDARY_START <= value && value <= PROGRESS_SECONDARY_END) {
1182            horizontalProgressBar.setSecondaryProgress(value - PROGRESS_SECONDARY_START);
1183
1184            showProgressBars(horizontalProgressBar, circularProgressBar);
1185        }
1186
1187    }
1188
1189    private void showProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
1190        final int features = getLocalFeatures();
1191        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
1192                spinnyProgressBar.getVisibility() == View.INVISIBLE) {
1193            spinnyProgressBar.setVisibility(View.VISIBLE);
1194        }
1195        // Only show the progress bars if the primary progress is not complete
1196        if ((features & (1 << FEATURE_PROGRESS)) != 0 &&
1197                horizontalProgressBar.getProgress() < 10000) {
1198            horizontalProgressBar.setVisibility(View.VISIBLE);
1199        }
1200    }
1201
1202    private void hideProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
1203        final int features = getLocalFeatures();
1204        Animation anim = AnimationUtils.loadAnimation(getContext(), com.android.internal.R.anim.fade_out);
1205        anim.setDuration(1000);
1206        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
1207                spinnyProgressBar.getVisibility() == View.VISIBLE) {
1208            spinnyProgressBar.startAnimation(anim);
1209            spinnyProgressBar.setVisibility(View.INVISIBLE);
1210        }
1211        if ((features & (1 << FEATURE_PROGRESS)) != 0 &&
1212                horizontalProgressBar.getVisibility() == View.VISIBLE) {
1213            horizontalProgressBar.startAnimation(anim);
1214            horizontalProgressBar.setVisibility(View.INVISIBLE);
1215        }
1216    }
1217
1218    /**
1219     * Request that key events come to this activity. Use this if your activity
1220     * has no views with focus, but the activity still wants a chance to process
1221     * key events.
1222     */
1223    @Override
1224    public void takeKeyEvents(boolean get) {
1225        mDecor.setFocusable(get);
1226    }
1227
1228    @Override
1229    public boolean superDispatchKeyEvent(KeyEvent event) {
1230        return mDecor.superDispatchKeyEvent(event);
1231    }
1232
1233    @Override
1234    public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
1235        return mDecor.superDispatchKeyShortcutEvent(event);
1236    }
1237
1238    @Override
1239    public boolean superDispatchTouchEvent(MotionEvent event) {
1240        return mDecor.superDispatchTouchEvent(event);
1241    }
1242
1243    @Override
1244    public boolean superDispatchTrackballEvent(MotionEvent event) {
1245        return mDecor.superDispatchTrackballEvent(event);
1246    }
1247
1248    @Override
1249    public boolean superDispatchGenericMotionEvent(MotionEvent event) {
1250        return mDecor.superDispatchGenericMotionEvent(event);
1251    }
1252
1253    /**
1254     * A key was pressed down and not handled by anything else in the window.
1255     *
1256     * @see #onKeyUp
1257     * @see android.view.KeyEvent
1258     */
1259    protected boolean onKeyDown(int featureId, int keyCode, KeyEvent event) {
1260        /* ****************************************************************************
1261         * HOW TO DECIDE WHERE YOUR KEY HANDLING GOES.
1262         *
1263         * If your key handling must happen before the app gets a crack at the event,
1264         * it goes in PhoneWindowManager.
1265         *
1266         * If your key handling should happen in all windows, and does not depend on
1267         * the state of the current application, other than that the current
1268         * application can override the behavior by handling the event itself, it
1269         * should go in PhoneFallbackEventHandler.
1270         *
1271         * Only if your handling depends on the window, and the fact that it has
1272         * a DecorView, should it go here.
1273         * ****************************************************************************/
1274
1275        final KeyEvent.DispatcherState dispatcher =
1276                mDecor != null ? mDecor.getKeyDispatcherState() : null;
1277        //Log.i(TAG, "Key down: repeat=" + event.getRepeatCount()
1278        //        + " flags=0x" + Integer.toHexString(event.getFlags()));
1279
1280        switch (keyCode) {
1281            case KeyEvent.KEYCODE_VOLUME_UP:
1282            case KeyEvent.KEYCODE_VOLUME_DOWN:
1283            case KeyEvent.KEYCODE_VOLUME_MUTE: {
1284                // Similar code is in PhoneFallbackEventHandler in case the window
1285                // doesn't have one of these.  In this case, we execute it here and
1286                // eat the event instead, because we have mVolumeControlStreamType
1287                // and they don't.
1288                getAudioManager().handleKeyDown(keyCode, mVolumeControlStreamType);
1289                return true;
1290            }
1291
1292            case KeyEvent.KEYCODE_MENU: {
1293                onKeyDownPanel((featureId < 0) ? FEATURE_OPTIONS_PANEL : featureId, event);
1294                return true;
1295            }
1296
1297            case KeyEvent.KEYCODE_BACK: {
1298                if (event.getRepeatCount() > 0) break;
1299                if (featureId < 0) break;
1300                // Currently don't do anything with long press.
1301                dispatcher.startTracking(event, this);
1302                return true;
1303            }
1304
1305        }
1306
1307        return false;
1308    }
1309
1310    private KeyguardManager getKeyguardManager() {
1311        if (mKeyguardManager == null) {
1312            mKeyguardManager = (KeyguardManager) getContext().getSystemService(
1313                    Context.KEYGUARD_SERVICE);
1314        }
1315        return mKeyguardManager;
1316    }
1317
1318    AudioManager getAudioManager() {
1319        if (mAudioManager == null) {
1320            mAudioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
1321        }
1322        return mAudioManager;
1323    }
1324
1325    /**
1326     * A key was released and not handled by anything else in the window.
1327     *
1328     * @see #onKeyDown
1329     * @see android.view.KeyEvent
1330     */
1331    protected boolean onKeyUp(int featureId, int keyCode, KeyEvent event) {
1332        final KeyEvent.DispatcherState dispatcher =
1333                mDecor != null ? mDecor.getKeyDispatcherState() : null;
1334        if (dispatcher != null) {
1335            dispatcher.handleUpEvent(event);
1336        }
1337        //Log.i(TAG, "Key up: repeat=" + event.getRepeatCount()
1338        //        + " flags=0x" + Integer.toHexString(event.getFlags()));
1339
1340        switch (keyCode) {
1341            case KeyEvent.KEYCODE_VOLUME_UP:
1342            case KeyEvent.KEYCODE_VOLUME_DOWN:
1343            case KeyEvent.KEYCODE_VOLUME_MUTE: {
1344                // Similar code is in PhoneFallbackEventHandler in case the window
1345                // doesn't have one of these.  In this case, we execute it here and
1346                // eat the event instead, because we have mVolumeControlStreamType
1347                // and they don't.
1348                getAudioManager().handleKeyUp(keyCode, mVolumeControlStreamType);
1349                return true;
1350            }
1351
1352            case KeyEvent.KEYCODE_MENU: {
1353                onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId,
1354                        event);
1355                return true;
1356            }
1357
1358            case KeyEvent.KEYCODE_BACK: {
1359                if (featureId < 0) break;
1360                if (event.isTracking() && !event.isCanceled()) {
1361                    if (featureId == FEATURE_OPTIONS_PANEL) {
1362                        PanelFeatureState st = getPanelState(featureId, false);
1363                        if (st != null && st.isInExpandedMode) {
1364                            // If the user is in an expanded menu and hits back, it
1365                            // should go back to the icon menu
1366                            reopenMenu(true);
1367                            return true;
1368                        }
1369                    }
1370                    closePanel(featureId);
1371                    return true;
1372                }
1373                break;
1374            }
1375
1376            case KeyEvent.KEYCODE_SEARCH: {
1377                /*
1378                 * Do this in onKeyUp since the Search key is also used for
1379                 * chording quick launch shortcuts.
1380                 */
1381                if (getKeyguardManager().inKeyguardRestrictedInputMode()) {
1382                    break;
1383                }
1384                if (event.isTracking() && !event.isCanceled()) {
1385                    launchDefaultSearch();
1386                }
1387                return true;
1388            }
1389        }
1390
1391        return false;
1392    }
1393
1394    @Override
1395    protected void onActive() {
1396    }
1397
1398    @Override
1399    public final View getDecorView() {
1400        if (mDecor == null) {
1401            installDecor();
1402        }
1403        return mDecor;
1404    }
1405
1406    @Override
1407    public final View peekDecorView() {
1408        return mDecor;
1409    }
1410
1411    static private final String FOCUSED_ID_TAG = "android:focusedViewId";
1412    static private final String VIEWS_TAG = "android:views";
1413    static private final String PANELS_TAG = "android:Panels";
1414    static private final String ACTION_BAR_TAG = "android:ActionBar";
1415
1416    /** {@inheritDoc} */
1417    @Override
1418    public Bundle saveHierarchyState() {
1419        Bundle outState = new Bundle();
1420        if (mContentParent == null) {
1421            return outState;
1422        }
1423
1424        SparseArray<Parcelable> states = new SparseArray<Parcelable>();
1425        mContentParent.saveHierarchyState(states);
1426        outState.putSparseParcelableArray(VIEWS_TAG, states);
1427
1428        // save the focused view id
1429        View focusedView = mContentParent.findFocus();
1430        if (focusedView != null) {
1431            if (focusedView.getId() != View.NO_ID) {
1432                outState.putInt(FOCUSED_ID_TAG, focusedView.getId());
1433            } else {
1434                if (false) {
1435                    Log.d(TAG, "couldn't save which view has focus because the focused view "
1436                            + focusedView + " has no id.");
1437                }
1438            }
1439        }
1440
1441        // save the panels
1442        SparseArray<Parcelable> panelStates = new SparseArray<Parcelable>();
1443        savePanelState(panelStates);
1444        if (panelStates.size() > 0) {
1445            outState.putSparseParcelableArray(PANELS_TAG, panelStates);
1446        }
1447
1448        if (mActionBar != null) {
1449            outState.putBoolean(ACTION_BAR_TAG, mActionBar.isOverflowMenuShowing());
1450        }
1451
1452        return outState;
1453    }
1454
1455    /** {@inheritDoc} */
1456    @Override
1457    public void restoreHierarchyState(Bundle savedInstanceState) {
1458        if (mContentParent == null) {
1459            return;
1460        }
1461
1462        SparseArray<Parcelable> savedStates
1463                = savedInstanceState.getSparseParcelableArray(VIEWS_TAG);
1464        if (savedStates != null) {
1465            mContentParent.restoreHierarchyState(savedStates);
1466        }
1467
1468        // restore the focused view
1469        int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID);
1470        if (focusedViewId != View.NO_ID) {
1471            View needsFocus = mContentParent.findViewById(focusedViewId);
1472            if (needsFocus != null) {
1473                needsFocus.requestFocus();
1474            } else {
1475                Log.w(TAG,
1476                        "Previously focused view reported id " + focusedViewId
1477                                + " during save, but can't be found during restore.");
1478            }
1479        }
1480
1481        // restore the panels
1482        SparseArray<Parcelable> panelStates = savedInstanceState.getSparseParcelableArray(PANELS_TAG);
1483        if (panelStates != null) {
1484            restorePanelState(panelStates);
1485        }
1486
1487        if (mActionBar != null && savedInstanceState.getBoolean(ACTION_BAR_TAG)) {
1488            mActionBar.postShowOverflowMenu();
1489        }
1490    }
1491
1492    /**
1493     * Invoked when the panels should freeze their state.
1494     *
1495     * @param icicles Save state into this. This is usually indexed by the
1496     *            featureId. This will be given to {@link #restorePanelState} in the
1497     *            future.
1498     */
1499    private void savePanelState(SparseArray<Parcelable> icicles) {
1500        PanelFeatureState[] panels = mPanels;
1501        if (panels == null) {
1502            return;
1503        }
1504
1505        for (int curFeatureId = panels.length - 1; curFeatureId >= 0; curFeatureId--) {
1506            if (panels[curFeatureId] != null) {
1507                icicles.put(curFeatureId, panels[curFeatureId].onSaveInstanceState());
1508            }
1509        }
1510    }
1511
1512    /**
1513     * Invoked when the panels should thaw their state from a previously frozen state.
1514     *
1515     * @param icicles The state saved by {@link #savePanelState} that needs to be thawed.
1516     */
1517    private void restorePanelState(SparseArray<Parcelable> icicles) {
1518        PanelFeatureState st;
1519        for (int curFeatureId = icicles.size() - 1; curFeatureId >= 0; curFeatureId--) {
1520            st = getPanelState(curFeatureId, false /* required */);
1521            if (st == null) {
1522                // The panel must not have been required, and is currently not around, skip it
1523                continue;
1524            }
1525
1526            st.onRestoreInstanceState(icicles.get(curFeatureId));
1527            invalidatePanelMenu(curFeatureId);
1528        }
1529
1530        /*
1531         * Implementation note: call openPanelsAfterRestore later to actually open the
1532         * restored panels.
1533         */
1534    }
1535
1536    /**
1537     * Opens the panels that have had their state restored. This should be
1538     * called sometime after {@link #restorePanelState} when it is safe to add
1539     * to the window manager.
1540     */
1541    private void openPanelsAfterRestore() {
1542        PanelFeatureState[] panels = mPanels;
1543
1544        if (panels == null) {
1545            return;
1546        }
1547
1548        PanelFeatureState st;
1549        for (int i = panels.length - 1; i >= 0; i--) {
1550            st = panels[i];
1551            // We restore the panel if it was last open; we skip it if it
1552            // now is open, to avoid a race condition if the user immediately
1553            // opens it when we are resuming.
1554            if ((st != null) && !st.isOpen && st.wasLastOpen) {
1555                st.isInExpandedMode = st.wasLastExpanded;
1556                openPanel(st, null);
1557            }
1558        }
1559    }
1560
1561    private class PanelMenuPresenterCallback implements MenuPresenter.Callback {
1562        @Override
1563        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
1564            final Menu parentMenu = menu.getRootMenu();
1565            final boolean isSubMenu = parentMenu != menu;
1566            final PanelFeatureState panel = findMenuPanel(isSubMenu ? parentMenu : menu);
1567            if (panel != null) {
1568                if (isSubMenu) {
1569                    callOnPanelClosed(panel.featureId, panel, parentMenu);
1570                    closePanel(panel, true);
1571                } else {
1572                    // Close the panel and only do the callback if the menu is being
1573                    // closed completely, not if opening a sub menu
1574                    closePanel(panel, allMenusAreClosing);
1575                }
1576            }
1577        }
1578
1579        @Override
1580        public boolean onOpenSubMenu(MenuBuilder subMenu) {
1581            if (subMenu == null && hasFeature(FEATURE_ACTION_BAR)) {
1582                Callback cb = getCallback();
1583                if (cb != null && !isDestroyed()) {
1584                    cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
1585                }
1586            }
1587
1588            return true;
1589        }
1590    }
1591
1592    private final class ActionMenuPresenterCallback implements MenuPresenter.Callback {
1593        @Override
1594        public boolean onOpenSubMenu(MenuBuilder subMenu) {
1595            Callback cb = getCallback();
1596            if (cb != null) {
1597                cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
1598                return true;
1599            }
1600            return false;
1601        }
1602
1603        @Override
1604        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
1605            checkCloseActionMenu(menu);
1606        }
1607    }
1608
1609    private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
1610        /* package */int mDefaultOpacity = PixelFormat.OPAQUE;
1611
1612        /** The feature ID of the panel, or -1 if this is the application's DecorView */
1613        private final int mFeatureId;
1614
1615        private final Rect mDrawingBounds = new Rect();
1616
1617        private final Rect mBackgroundPadding = new Rect();
1618
1619        private final Rect mFramePadding = new Rect();
1620
1621        private final Rect mFrameOffsets = new Rect();
1622
1623        private boolean mChanging;
1624
1625        private Drawable mMenuBackground;
1626        private boolean mWatchingForMenu;
1627        private int mDownY;
1628
1629        private ActionMode mActionMode;
1630        private ActionBarContextView mActionModeView;
1631        private PopupWindow mActionModePopup;
1632        private Runnable mShowActionModePopup;
1633
1634        public DecorView(Context context, int featureId) {
1635            super(context);
1636            mFeatureId = featureId;
1637        }
1638
1639        @Override
1640        public boolean dispatchKeyEvent(KeyEvent event) {
1641            final int keyCode = event.getKeyCode();
1642            final int action = event.getAction();
1643            final boolean isDown = action == KeyEvent.ACTION_DOWN;
1644
1645            if (isDown && (event.getRepeatCount() == 0)) {
1646                // First handle chording of panel key: if a panel key is held
1647                // but not released, try to execute a shortcut in it.
1648                if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) {
1649                    boolean handled = dispatchKeyShortcutEvent(event);
1650                    if (handled) {
1651                        return true;
1652                    }
1653                }
1654
1655                // If a panel is open, perform a shortcut on it without the
1656                // chorded panel key
1657                if ((mPreparedPanel != null) && mPreparedPanel.isOpen) {
1658                    if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) {
1659                        return true;
1660                    }
1661                }
1662            }
1663
1664            // Back cancels action modes first.
1665            if (mActionMode != null && keyCode == KeyEvent.KEYCODE_BACK) {
1666                if (action == KeyEvent.ACTION_UP) {
1667                    mActionMode.finish();
1668                }
1669                return true;
1670            }
1671
1672            if (!isDestroyed()) {
1673                final Callback cb = getCallback();
1674                final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event)
1675                        : super.dispatchKeyEvent(event);
1676                if (handled) {
1677                    return true;
1678                }
1679            }
1680            return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event)
1681                    : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event);
1682        }
1683
1684        @Override
1685        public boolean dispatchKeyShortcutEvent(KeyEvent ev) {
1686            // Perform the shortcut (mPreparedPanel can be null since
1687            // global shortcuts (such as search) don't rely on a
1688            // prepared panel or menu).
1689            boolean handled = performPanelShortcut(mPreparedPanel, ev.getKeyCode(), ev,
1690                    Menu.FLAG_PERFORM_NO_CLOSE);
1691            if (handled) {
1692                if (mPreparedPanel != null) {
1693                    mPreparedPanel.isHandled = true;
1694                }
1695                return true;
1696            }
1697
1698            // Shortcut not handled by the panel.  Dispatch to the view hierarchy.
1699            final Callback cb = getCallback();
1700            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchKeyShortcutEvent(ev)
1701                    : super.dispatchKeyShortcutEvent(ev);
1702        }
1703
1704        @Override
1705        public boolean dispatchTouchEvent(MotionEvent ev) {
1706            final Callback cb = getCallback();
1707            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
1708                    : super.dispatchTouchEvent(ev);
1709        }
1710
1711        @Override
1712        public boolean dispatchTrackballEvent(MotionEvent ev) {
1713            final Callback cb = getCallback();
1714            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev)
1715                    : super.dispatchTrackballEvent(ev);
1716        }
1717
1718        @Override
1719        public boolean dispatchGenericMotionEvent(MotionEvent ev) {
1720            final Callback cb = getCallback();
1721            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchGenericMotionEvent(ev)
1722                    : super.dispatchGenericMotionEvent(ev);
1723        }
1724
1725        public boolean superDispatchKeyEvent(KeyEvent event) {
1726            return super.dispatchKeyEvent(event);
1727        }
1728
1729        public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
1730            return super.dispatchKeyShortcutEvent(event);
1731        }
1732
1733        public boolean superDispatchTouchEvent(MotionEvent event) {
1734            return super.dispatchTouchEvent(event);
1735        }
1736
1737        public boolean superDispatchTrackballEvent(MotionEvent event) {
1738            return super.dispatchTrackballEvent(event);
1739        }
1740
1741        public boolean superDispatchGenericMotionEvent(MotionEvent event) {
1742            return super.dispatchGenericMotionEvent(event);
1743        }
1744
1745        @Override
1746        public boolean onTouchEvent(MotionEvent event) {
1747            return onInterceptTouchEvent(event);
1748        }
1749
1750        private boolean isOutOfBounds(int x, int y) {
1751            return x < -5 || y < -5 || x > (getWidth() + 5)
1752                    || y > (getHeight() + 5);
1753        }
1754
1755        @Override
1756        public boolean onInterceptTouchEvent(MotionEvent event) {
1757            int action = event.getAction();
1758            if (mFeatureId >= 0) {
1759                if (action == MotionEvent.ACTION_DOWN) {
1760                    int x = (int)event.getX();
1761                    int y = (int)event.getY();
1762                    if (isOutOfBounds(x, y)) {
1763                        closePanel(mFeatureId);
1764                        return true;
1765                    }
1766                }
1767            }
1768
1769            if (!SWEEP_OPEN_MENU) {
1770                return false;
1771            }
1772
1773            if (mFeatureId >= 0) {
1774                if (action == MotionEvent.ACTION_DOWN) {
1775                    Log.i(TAG, "Watchiing!");
1776                    mWatchingForMenu = true;
1777                    mDownY = (int) event.getY();
1778                    return false;
1779                }
1780
1781                if (!mWatchingForMenu) {
1782                    return false;
1783                }
1784
1785                int y = (int)event.getY();
1786                if (action == MotionEvent.ACTION_MOVE) {
1787                    if (y > (mDownY+30)) {
1788                        Log.i(TAG, "Closing!");
1789                        closePanel(mFeatureId);
1790                        mWatchingForMenu = false;
1791                        return true;
1792                    }
1793                } else if (action == MotionEvent.ACTION_UP) {
1794                    mWatchingForMenu = false;
1795                }
1796
1797                return false;
1798            }
1799
1800            //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY()
1801            //        + " (in " + getHeight() + ")");
1802
1803            if (action == MotionEvent.ACTION_DOWN) {
1804                int y = (int)event.getY();
1805                if (y >= (getHeight()-5) && !hasChildren()) {
1806                    Log.i(TAG, "Watchiing!");
1807                    mWatchingForMenu = true;
1808                }
1809                return false;
1810            }
1811
1812            if (!mWatchingForMenu) {
1813                return false;
1814            }
1815
1816            int y = (int)event.getY();
1817            if (action == MotionEvent.ACTION_MOVE) {
1818                if (y < (getHeight()-30)) {
1819                    Log.i(TAG, "Opening!");
1820                    openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent(
1821                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU));
1822                    mWatchingForMenu = false;
1823                    return true;
1824                }
1825            } else if (action == MotionEvent.ACTION_UP) {
1826                mWatchingForMenu = false;
1827            }
1828
1829            return false;
1830        }
1831
1832        @Override
1833        public void sendAccessibilityEvent(int eventType) {
1834            if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
1835                return;
1836            }
1837
1838            // if we are showing a feature that should be announced and one child
1839            // make this child the event source since this is the feature itself
1840            // otherwise the callback will take over and announce its client
1841            if ((mFeatureId == FEATURE_OPTIONS_PANEL ||
1842                    mFeatureId == FEATURE_CONTEXT_MENU ||
1843                    mFeatureId == FEATURE_PROGRESS ||
1844                    mFeatureId == FEATURE_INDETERMINATE_PROGRESS)
1845                    && getChildCount() == 1) {
1846                getChildAt(0).sendAccessibilityEvent(eventType);
1847            } else {
1848                super.sendAccessibilityEvent(eventType);
1849            }
1850        }
1851
1852        @Override
1853        public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1854            final Callback cb = getCallback();
1855            if (cb != null && !isDestroyed()) {
1856                if (cb.dispatchPopulateAccessibilityEvent(event)) {
1857                    return true;
1858                }
1859            }
1860            return super.dispatchPopulateAccessibilityEvent(event);
1861        }
1862
1863        @Override
1864        protected boolean setFrame(int l, int t, int r, int b) {
1865            boolean changed = super.setFrame(l, t, r, b);
1866            if (changed) {
1867                final Rect drawingBounds = mDrawingBounds;
1868                getDrawingRect(drawingBounds);
1869
1870                Drawable fg = getForeground();
1871                if (fg != null) {
1872                    final Rect frameOffsets = mFrameOffsets;
1873                    drawingBounds.left += frameOffsets.left;
1874                    drawingBounds.top += frameOffsets.top;
1875                    drawingBounds.right -= frameOffsets.right;
1876                    drawingBounds.bottom -= frameOffsets.bottom;
1877                    fg.setBounds(drawingBounds);
1878                    final Rect framePadding = mFramePadding;
1879                    drawingBounds.left += framePadding.left - frameOffsets.left;
1880                    drawingBounds.top += framePadding.top - frameOffsets.top;
1881                    drawingBounds.right -= framePadding.right - frameOffsets.right;
1882                    drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom;
1883                }
1884
1885                Drawable bg = getBackground();
1886                if (bg != null) {
1887                    bg.setBounds(drawingBounds);
1888                }
1889
1890                if (SWEEP_OPEN_MENU) {
1891                    if (mMenuBackground == null && mFeatureId < 0
1892                            && getAttributes().height
1893                            == WindowManager.LayoutParams.MATCH_PARENT) {
1894                        mMenuBackground = getContext().getResources().getDrawable(
1895                                com.android.internal.R.drawable.menu_background);
1896                    }
1897                    if (mMenuBackground != null) {
1898                        mMenuBackground.setBounds(drawingBounds.left,
1899                                drawingBounds.bottom-6, drawingBounds.right,
1900                                drawingBounds.bottom+20);
1901                    }
1902                }
1903            }
1904            return changed;
1905        }
1906
1907        @Override
1908        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1909            final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
1910            final boolean isPortrait = metrics.widthPixels < metrics.heightPixels;
1911
1912            final int widthMode = getMode(widthMeasureSpec);
1913
1914            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1915
1916            int width = getMeasuredWidth();
1917            boolean measure = false;
1918
1919            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY);
1920
1921            final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor;
1922
1923            if (widthMode == AT_MOST && tv.type != TypedValue.TYPE_NULL) {
1924                final int min;
1925                if (tv.type == TypedValue.TYPE_DIMENSION) {
1926                    min = (int)tv.getDimension(metrics);
1927                } else if (tv.type == TypedValue.TYPE_FRACTION) {
1928                    min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels);
1929                } else {
1930                    min = 0;
1931                }
1932
1933                if (width < min) {
1934                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY);
1935                    measure = true;
1936                }
1937            }
1938
1939            // TODO: Support height?
1940
1941            if (measure) {
1942                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1943            }
1944        }
1945
1946        @Override
1947        public void draw(Canvas canvas) {
1948            super.draw(canvas);
1949
1950            if (mMenuBackground != null) {
1951                mMenuBackground.draw(canvas);
1952            }
1953        }
1954
1955
1956        @Override
1957        public boolean showContextMenuForChild(View originalView) {
1958            // Reuse the context menu builder
1959            if (mContextMenu == null) {
1960                mContextMenu = new ContextMenuBuilder(getContext());
1961                mContextMenu.setCallback(mContextMenuCallback);
1962            } else {
1963                mContextMenu.clearAll();
1964            }
1965
1966            final MenuDialogHelper helper = mContextMenu.show(originalView,
1967                    originalView.getWindowToken());
1968            if (helper != null) {
1969                helper.setPresenterCallback(mContextMenuCallback);
1970            }
1971            mContextMenuHelper = helper;
1972            return helper != null;
1973        }
1974
1975        @Override
1976        public ActionMode startActionModeForChild(View originalView,
1977                ActionMode.Callback callback) {
1978            // originalView can be used here to be sure that we don't obscure
1979            // relevant content with the context mode UI.
1980            return startActionMode(callback);
1981        }
1982
1983        @Override
1984        public ActionMode startActionMode(ActionMode.Callback callback) {
1985            if (mActionMode != null) {
1986                mActionMode.finish();
1987            }
1988
1989            final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback);
1990            ActionMode mode = null;
1991            if (getCallback() != null && !isDestroyed()) {
1992                try {
1993                    mode = getCallback().onWindowStartingActionMode(wrappedCallback);
1994                } catch (AbstractMethodError ame) {
1995                    // Older apps might not implement this callback method.
1996                }
1997            }
1998            if (mode != null) {
1999                mActionMode = mode;
2000            } else {
2001                if (mActionModeView == null) {
2002                    if (hasFeature(FEATURE_ACTION_MODE_OVERLAY)) {
2003                        mActionModeView = new ActionBarContextView(mContext);
2004                        mActionModePopup = new PopupWindow(mContext, null,
2005                                com.android.internal.R.attr.actionModePopupWindowStyle);
2006                        mActionModePopup.setLayoutInScreenEnabled(true);
2007                        mActionModePopup.setClippingEnabled(false);
2008                        mActionModePopup.setContentView(mActionModeView);
2009                        mActionModePopup.setWidth(MATCH_PARENT);
2010
2011                        TypedValue heightValue = new TypedValue();
2012                        mContext.getTheme().resolveAttribute(
2013                                com.android.internal.R.attr.actionBarSize, heightValue, false);
2014                        final int height = TypedValue.complexToDimensionPixelSize(heightValue.data,
2015                                mContext.getResources().getDisplayMetrics());
2016                        mActionModePopup.setHeight(height);
2017                        mShowActionModePopup = new Runnable() {
2018                            public void run() {
2019                                mActionModePopup.showAtLocation(PhoneWindow.DecorView.this,
2020                                        Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
2021                            }
2022                        };
2023                    } else {
2024                        ViewStub stub = (ViewStub) findViewById(
2025                                com.android.internal.R.id.action_mode_bar_stub);
2026                        if (stub != null) {
2027                            mActionModeView = (ActionBarContextView) stub.inflate();
2028                        }
2029                    }
2030                }
2031
2032                if (mActionModeView != null) {
2033                    mActionModeView.killMode();
2034                    mode = new StandaloneActionMode(getContext(), mActionModeView, wrappedCallback);
2035                    if (callback.onCreateActionMode(mode, mode.getMenu())) {
2036                        mode.invalidate();
2037                        mActionModeView.initForMode(mode);
2038                        mActionModeView.setVisibility(View.VISIBLE);
2039                        mActionMode = mode;
2040                        if (mActionModePopup != null) {
2041                            post(mShowActionModePopup);
2042                        }
2043                    } else {
2044                        mActionMode = null;
2045                    }
2046                }
2047            }
2048            if (mActionMode != null && getCallback() != null && !isDestroyed()) {
2049                try {
2050                    getCallback().onActionModeStarted(mActionMode);
2051                } catch (AbstractMethodError ame) {
2052                    // Older apps might not implement this callback method.
2053                }
2054            }
2055            return mActionMode;
2056        }
2057
2058        public void startChanging() {
2059            mChanging = true;
2060        }
2061
2062        public void finishChanging() {
2063            mChanging = false;
2064            drawableChanged();
2065        }
2066
2067        public void setWindowBackground(Drawable drawable) {
2068            if (getBackground() != drawable) {
2069                setBackgroundDrawable(drawable);
2070                if (drawable != null) {
2071                    drawable.getPadding(mBackgroundPadding);
2072                } else {
2073                    mBackgroundPadding.setEmpty();
2074                }
2075                drawableChanged();
2076            }
2077        }
2078
2079        @Override
2080        public void setBackgroundDrawable(Drawable d) {
2081            super.setBackgroundDrawable(d);
2082            if (getWindowToken() != null) {
2083                updateWindowResizeState();
2084            }
2085        }
2086
2087        public void setWindowFrame(Drawable drawable) {
2088            if (getForeground() != drawable) {
2089                setForeground(drawable);
2090                if (drawable != null) {
2091                    drawable.getPadding(mFramePadding);
2092                } else {
2093                    mFramePadding.setEmpty();
2094                }
2095                drawableChanged();
2096            }
2097        }
2098
2099        @Override
2100        protected boolean fitSystemWindows(Rect insets) {
2101            mFrameOffsets.set(insets);
2102            if (getForeground() != null) {
2103                drawableChanged();
2104            }
2105            return super.fitSystemWindows(insets);
2106        }
2107
2108        private void drawableChanged() {
2109            if (mChanging) {
2110                return;
2111            }
2112
2113            setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top
2114                    + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right,
2115                    mFramePadding.bottom + mBackgroundPadding.bottom);
2116            requestLayout();
2117            invalidate();
2118
2119            int opacity = PixelFormat.OPAQUE;
2120
2121            // Note: if there is no background, we will assume opaque. The
2122            // common case seems to be that an application sets there to be
2123            // no background so it can draw everything itself. For that,
2124            // we would like to assume OPAQUE and let the app force it to
2125            // the slower TRANSLUCENT mode if that is really what it wants.
2126            Drawable bg = getBackground();
2127            Drawable fg = getForeground();
2128            if (bg != null) {
2129                if (fg == null) {
2130                    opacity = bg.getOpacity();
2131                } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0
2132                        && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) {
2133                    // If the frame padding is zero, then we can be opaque
2134                    // if either the frame -or- the background is opaque.
2135                    int fop = fg.getOpacity();
2136                    int bop = bg.getOpacity();
2137                    if (false)
2138                        Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop);
2139                    if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) {
2140                        opacity = PixelFormat.OPAQUE;
2141                    } else if (fop == PixelFormat.UNKNOWN) {
2142                        opacity = bop;
2143                    } else if (bop == PixelFormat.UNKNOWN) {
2144                        opacity = fop;
2145                    } else {
2146                        opacity = Drawable.resolveOpacity(fop, bop);
2147                    }
2148                } else {
2149                    // For now we have to assume translucent if there is a
2150                    // frame with padding... there is no way to tell if the
2151                    // frame and background together will draw all pixels.
2152                    if (false)
2153                        Log.v(TAG, "Padding: " + mFramePadding);
2154                    opacity = PixelFormat.TRANSLUCENT;
2155                }
2156            }
2157
2158            if (false)
2159                Log.v(TAG, "Background: " + bg + ", Frame: " + fg);
2160            if (false)
2161                Log.v(TAG, "Selected default opacity: " + opacity);
2162
2163            mDefaultOpacity = opacity;
2164            if (mFeatureId < 0) {
2165                setDefaultWindowFormat(opacity);
2166            }
2167        }
2168
2169        @Override
2170        public void onWindowFocusChanged(boolean hasWindowFocus) {
2171            super.onWindowFocusChanged(hasWindowFocus);
2172
2173            // If the user is chording a menu shortcut, release the chord since
2174            // this window lost focus
2175            if (!hasWindowFocus && mPanelChordingKey != 0) {
2176                closePanel(FEATURE_OPTIONS_PANEL);
2177            }
2178
2179            final Callback cb = getCallback();
2180            if (cb != null && !isDestroyed() && mFeatureId < 0) {
2181                cb.onWindowFocusChanged(hasWindowFocus);
2182            }
2183        }
2184
2185        void updateWindowResizeState() {
2186            Drawable bg = getBackground();
2187            hackTurnOffWindowResizeAnim(bg == null || bg.getOpacity()
2188                    != PixelFormat.OPAQUE);
2189        }
2190
2191        @Override
2192        protected void onAttachedToWindow() {
2193            super.onAttachedToWindow();
2194
2195            updateWindowResizeState();
2196
2197            final Callback cb = getCallback();
2198            if (cb != null && !isDestroyed() && mFeatureId < 0) {
2199                cb.onAttachedToWindow();
2200            }
2201
2202            if (mFeatureId == -1) {
2203                /*
2204                 * The main window has been attached, try to restore any panels
2205                 * that may have been open before. This is called in cases where
2206                 * an activity is being killed for configuration change and the
2207                 * menu was open. When the activity is recreated, the menu
2208                 * should be shown again.
2209                 */
2210                openPanelsAfterRestore();
2211            }
2212        }
2213
2214        @Override
2215        protected void onDetachedFromWindow() {
2216            super.onDetachedFromWindow();
2217
2218            final Callback cb = getCallback();
2219            if (cb != null && mFeatureId < 0) {
2220                cb.onDetachedFromWindow();
2221            }
2222
2223            if (mActionBar != null) {
2224                mActionBar.dismissPopupMenus();
2225            }
2226
2227            if (mActionModePopup != null) {
2228                removeCallbacks(mShowActionModePopup);
2229                if (mActionModePopup.isShowing()) {
2230                    mActionModePopup.dismiss();
2231                }
2232                mActionModePopup = null;
2233            }
2234        }
2235
2236        @Override
2237        public void onCloseSystemDialogs(String reason) {
2238            if (mFeatureId >= 0) {
2239                closeAllPanels();
2240            }
2241        }
2242
2243        public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() {
2244            return mFeatureId < 0 ? mTakeSurfaceCallback : null;
2245        }
2246
2247        public InputQueue.Callback willYouTakeTheInputQueue() {
2248            return mFeatureId < 0 ? mTakeInputQueueCallback : null;
2249        }
2250
2251        public void setSurfaceType(int type) {
2252            PhoneWindow.this.setType(type);
2253        }
2254
2255        public void setSurfaceFormat(int format) {
2256            PhoneWindow.this.setFormat(format);
2257        }
2258
2259        public void setSurfaceKeepScreenOn(boolean keepOn) {
2260            if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2261            else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2262        }
2263
2264        /**
2265         * Clears out internal reference when the action mode is destroyed.
2266         */
2267        private class ActionModeCallbackWrapper implements ActionMode.Callback {
2268            private ActionMode.Callback mWrapped;
2269
2270            public ActionModeCallbackWrapper(ActionMode.Callback wrapped) {
2271                mWrapped = wrapped;
2272            }
2273
2274            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2275                return mWrapped.onCreateActionMode(mode, menu);
2276            }
2277
2278            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2279                return mWrapped.onPrepareActionMode(mode, menu);
2280            }
2281
2282            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2283                return mWrapped.onActionItemClicked(mode, item);
2284            }
2285
2286            public void onDestroyActionMode(ActionMode mode) {
2287                mWrapped.onDestroyActionMode(mode);
2288                if (mActionModePopup != null) {
2289                    removeCallbacks(mShowActionModePopup);
2290                    mActionModePopup.dismiss();
2291                } else if (mActionModeView != null) {
2292                    mActionModeView.setVisibility(GONE);
2293                }
2294                if (mActionModeView != null) {
2295                    mActionModeView.removeAllViews();
2296                }
2297                if (getCallback() != null && !isDestroyed()) {
2298                    try {
2299                        getCallback().onActionModeFinished(mActionMode);
2300                    } catch (AbstractMethodError ame) {
2301                        // Older apps might not implement this callback method.
2302                    }
2303                }
2304                mActionMode = null;
2305            }
2306        }
2307    }
2308
2309    protected DecorView generateDecor() {
2310        return new DecorView(getContext(), -1);
2311    }
2312
2313    protected void setFeatureFromAttrs(int featureId, TypedArray attrs,
2314            int drawableAttr, int alphaAttr) {
2315        Drawable d = attrs.getDrawable(drawableAttr);
2316        if (d != null) {
2317            requestFeature(featureId);
2318            setFeatureDefaultDrawable(featureId, d);
2319        }
2320        if ((getFeatures() & (1 << featureId)) != 0) {
2321            int alpha = attrs.getInt(alphaAttr, -1);
2322            if (alpha >= 0) {
2323                setFeatureDrawableAlpha(featureId, alpha);
2324            }
2325        }
2326    }
2327
2328    protected ViewGroup generateLayout(DecorView decor) {
2329        // Apply data from current theme.
2330
2331        TypedArray a = getWindowStyle();
2332
2333        if (false) {
2334            System.out.println("From style:");
2335            String s = "Attrs:";
2336            for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) {
2337                s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "="
2338                        + a.getString(i);
2339            }
2340            System.out.println(s);
2341        }
2342
2343        mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
2344        int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
2345                & (~getForcedWindowFlags());
2346        if (mIsFloating) {
2347            setLayout(WRAP_CONTENT, WRAP_CONTENT);
2348            setFlags(0, flagsToUpdate);
2349        } else {
2350            setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
2351        }
2352
2353        if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
2354            requestFeature(FEATURE_NO_TITLE);
2355        } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) {
2356            // Don't allow an action bar if there is no title.
2357            requestFeature(FEATURE_ACTION_BAR);
2358        }
2359
2360        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) {
2361            requestFeature(FEATURE_ACTION_BAR_OVERLAY);
2362        }
2363
2364        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) {
2365            requestFeature(FEATURE_ACTION_MODE_OVERLAY);
2366        }
2367
2368        if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
2369            setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags()));
2370        }
2371
2372        if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) {
2373            setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
2374        }
2375
2376        if (a.getBoolean(com.android.internal.R.styleable.Window_windowEnableSplitTouch,
2377                getContext().getApplicationInfo().targetSdkVersion
2378                        >= android.os.Build.VERSION_CODES.HONEYCOMB)) {
2379            setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags()));
2380        }
2381
2382        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMajor, mMinWidthMajor);
2383        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMinor, mMinWidthMinor);
2384
2385        if (getContext().getApplicationInfo().targetSdkVersion
2386                < android.os.Build.VERSION_CODES.HONEYCOMB) {
2387            addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY);
2388        }
2389
2390        if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion
2391                >= android.os.Build.VERSION_CODES.HONEYCOMB) {
2392            if (a.getBoolean(
2393                    com.android.internal.R.styleable.Window_windowCloseOnTouchOutside,
2394                    false)) {
2395                setCloseOnTouchOutsideIfNotSet(true);
2396            }
2397        }
2398
2399        WindowManager.LayoutParams params = getAttributes();
2400
2401        if (!hasSoftInputMode()) {
2402            params.softInputMode = a.getInt(
2403                    com.android.internal.R.styleable.Window_windowSoftInputMode,
2404                    params.softInputMode);
2405        }
2406
2407        if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled,
2408                mIsFloating)) {
2409            /* All dialogs should have the window dimmed */
2410            if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
2411                params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
2412            }
2413            params.dimAmount = a.getFloat(
2414                    android.R.styleable.Window_backgroundDimAmount, 0.5f);
2415        }
2416
2417        if (params.windowAnimations == 0) {
2418            params.windowAnimations = a.getResourceId(
2419                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2420        }
2421
2422        // The rest are only done if this window is not embedded; otherwise,
2423        // the values are inherited from our container.
2424        if (getContainer() == null) {
2425            if (mBackgroundDrawable == null) {
2426                if (mBackgroundResource == 0) {
2427                    mBackgroundResource = a.getResourceId(
2428                            com.android.internal.R.styleable.Window_windowBackground, 0);
2429                }
2430                if (mFrameResource == 0) {
2431                    mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0);
2432                }
2433                if (false) {
2434                    System.out.println("Background: "
2435                            + Integer.toHexString(mBackgroundResource) + " Frame: "
2436                            + Integer.toHexString(mFrameResource));
2437                }
2438            }
2439            mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000);
2440        }
2441
2442        // Inflate the window decor.
2443
2444        int layoutResource;
2445        int features = getLocalFeatures();
2446        // System.out.println("Features: 0x" + Integer.toHexString(features));
2447        if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
2448            if (mIsFloating) {
2449                TypedValue res = new TypedValue();
2450                getContext().getTheme().resolveAttribute(
2451                        com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true);
2452                layoutResource = res.resourceId;
2453            } else {
2454                layoutResource = com.android.internal.R.layout.screen_title_icons;
2455            }
2456            // XXX Remove this once action bar supports these features.
2457            removeFeature(FEATURE_ACTION_BAR);
2458            // System.out.println("Title Icons!");
2459        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
2460                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
2461            // Special case for a window with only a progress bar (and title).
2462            // XXX Need to have a no-title version of embedded windows.
2463            layoutResource = com.android.internal.R.layout.screen_progress;
2464            // System.out.println("Progress!");
2465        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
2466            // Special case for a window with a custom title.
2467            // If the window is floating, we need a dialog layout
2468            if (mIsFloating) {
2469                TypedValue res = new TypedValue();
2470                getContext().getTheme().resolveAttribute(
2471                        com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true);
2472                layoutResource = res.resourceId;
2473            } else {
2474                layoutResource = com.android.internal.R.layout.screen_custom_title;
2475            }
2476            // XXX Remove this once action bar supports these features.
2477            removeFeature(FEATURE_ACTION_BAR);
2478        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
2479            // If no other features and not embedded, only need a title.
2480            // If the window is floating, we need a dialog layout
2481            if (mIsFloating) {
2482                TypedValue res = new TypedValue();
2483                getContext().getTheme().resolveAttribute(
2484                        com.android.internal.R.attr.dialogTitleDecorLayout, res, true);
2485                layoutResource = res.resourceId;
2486            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
2487                if ((features & (1 << FEATURE_ACTION_BAR_OVERLAY)) != 0) {
2488                    layoutResource = com.android.internal.R.layout.screen_action_bar_overlay;
2489                } else {
2490                    layoutResource = com.android.internal.R.layout.screen_action_bar;
2491                }
2492            } else {
2493                layoutResource = com.android.internal.R.layout.screen_title;
2494            }
2495            // System.out.println("Title!");
2496        } else {
2497            // Embedded, so no decoration is needed.
2498            layoutResource = com.android.internal.R.layout.screen_simple;
2499            // System.out.println("Simple!");
2500        }
2501
2502        mDecor.startChanging();
2503
2504        View in = mLayoutInflater.inflate(layoutResource, null);
2505        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
2506
2507        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
2508        if (contentParent == null) {
2509            throw new RuntimeException("Window couldn't find content container view");
2510        }
2511
2512        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2513            ProgressBar progress = getCircularProgressBar(false);
2514            if (progress != null) {
2515                progress.setIndeterminate(true);
2516            }
2517        }
2518
2519        // Remaining setup -- of background and title -- that only applies
2520        // to top-level windows.
2521        if (getContainer() == null) {
2522            Drawable drawable = mBackgroundDrawable;
2523            if (mBackgroundResource != 0) {
2524                drawable = getContext().getResources().getDrawable(mBackgroundResource);
2525            }
2526            mDecor.setWindowBackground(drawable);
2527            drawable = null;
2528            if (mFrameResource != 0) {
2529                drawable = getContext().getResources().getDrawable(mFrameResource);
2530            }
2531            mDecor.setWindowFrame(drawable);
2532
2533            // System.out.println("Text=" + Integer.toHexString(mTextColor) +
2534            // " Sel=" + Integer.toHexString(mTextSelectedColor) +
2535            // " Title=" + Integer.toHexString(mTitleColor));
2536
2537            if (mTitleColor == 0) {
2538                mTitleColor = mTextColor;
2539            }
2540
2541            if (mTitle != null) {
2542                setTitle(mTitle);
2543            }
2544            setTitleColor(mTitleColor);
2545        }
2546
2547        mDecor.finishChanging();
2548
2549        return contentParent;
2550    }
2551
2552    /** @hide */
2553    public void alwaysReadCloseOnTouchAttr() {
2554        mAlwaysReadCloseOnTouchAttr = true;
2555    }
2556
2557    private void installDecor() {
2558        if (mDecor == null) {
2559            mDecor = generateDecor();
2560            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
2561            mDecor.setIsRootNamespace(true);
2562        }
2563        if (mContentParent == null) {
2564            mContentParent = generateLayout(mDecor);
2565
2566            mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
2567            if (mTitleView != null) {
2568                if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
2569                    View titleContainer = findViewById(com.android.internal.R.id.title_container);
2570                    if (titleContainer != null) {
2571                        titleContainer.setVisibility(View.GONE);
2572                    } else {
2573                        mTitleView.setVisibility(View.GONE);
2574                    }
2575                    if (mContentParent instanceof FrameLayout) {
2576                        ((FrameLayout)mContentParent).setForeground(null);
2577                    }
2578                } else {
2579                    mTitleView.setText(mTitle);
2580                }
2581            } else {
2582                mActionBar = (ActionBarView) findViewById(com.android.internal.R.id.action_bar);
2583                if (mActionBar != null) {
2584                    if (mActionBar.getTitle() == null) {
2585                        mActionBar.setWindowTitle(mTitle);
2586                    }
2587                    final int localFeatures = getLocalFeatures();
2588                    if ((localFeatures & (1 << FEATURE_PROGRESS)) != 0) {
2589                        mActionBar.initProgress();
2590                    }
2591                    if ((localFeatures & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2592                        mActionBar.initIndeterminateProgress();
2593                    }
2594
2595                    final boolean splitActionBar = getWindowStyle().getBoolean(
2596                            com.android.internal.R.styleable.Window_windowSplitActionBar, false);
2597                    if (splitActionBar) {
2598                        final ActionBarContainer splitView = (ActionBarContainer) findViewById(
2599                                com.android.internal.R.id.split_action_bar);
2600                        if (splitView != null) {
2601                            splitView.setVisibility(View.VISIBLE);
2602                            mActionBar.setSplitActionBar(splitActionBar);
2603                            mActionBar.setSplitView(splitView);
2604
2605                            final ActionBarContextView cab = (ActionBarContextView) findViewById(
2606                                    com.android.internal.R.id.action_context_bar);
2607                            cab.setSplitView(splitView);
2608                        } else {
2609                            Log.e(TAG, "Window style requested split action bar with " +
2610                                    "incompatible window decor! Ignoring request.");
2611                        }
2612                    }
2613
2614                    // Post the panel invalidate for later; avoid application onCreateOptionsMenu
2615                    // being called in the middle of onCreate or similar.
2616                    mDecor.post(new Runnable() {
2617                        public void run() {
2618                            if (!isDestroyed()) {
2619                                invalidatePanelMenu(FEATURE_ACTION_BAR);
2620                            }
2621                        }
2622                    });
2623                }
2624            }
2625        }
2626    }
2627
2628    private Drawable loadImageURI(Uri uri) {
2629        try {
2630            return Drawable.createFromStream(
2631                    getContext().getContentResolver().openInputStream(uri), null);
2632        } catch (Exception e) {
2633            Log.w(TAG, "Unable to open content: " + uri);
2634        }
2635        return null;
2636    }
2637
2638    private DrawableFeatureState getDrawableState(int featureId, boolean required) {
2639        if ((getFeatures() & (1 << featureId)) == 0) {
2640            if (!required) {
2641                return null;
2642            }
2643            throw new RuntimeException("The feature has not been requested");
2644        }
2645
2646        DrawableFeatureState[] ar;
2647        if ((ar = mDrawables) == null || ar.length <= featureId) {
2648            DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1];
2649            if (ar != null) {
2650                System.arraycopy(ar, 0, nar, 0, ar.length);
2651            }
2652            mDrawables = ar = nar;
2653        }
2654
2655        DrawableFeatureState st = ar[featureId];
2656        if (st == null) {
2657            ar[featureId] = st = new DrawableFeatureState(featureId);
2658        }
2659        return st;
2660    }
2661
2662    /**
2663     * Gets a panel's state based on its feature ID.
2664     *
2665     * @param featureId The feature ID of the panel.
2666     * @param required Whether the panel is required (if it is required and it
2667     *            isn't in our features, this throws an exception).
2668     * @return The panel state.
2669     */
2670    private PanelFeatureState getPanelState(int featureId, boolean required) {
2671        return getPanelState(featureId, required, null);
2672    }
2673
2674    /**
2675     * Gets a panel's state based on its feature ID.
2676     *
2677     * @param featureId The feature ID of the panel.
2678     * @param required Whether the panel is required (if it is required and it
2679     *            isn't in our features, this throws an exception).
2680     * @param convertPanelState Optional: If the panel state does not exist, use
2681     *            this as the panel state.
2682     * @return The panel state.
2683     */
2684    private PanelFeatureState getPanelState(int featureId, boolean required,
2685            PanelFeatureState convertPanelState) {
2686        if ((getFeatures() & (1 << featureId)) == 0) {
2687            if (!required) {
2688                return null;
2689            }
2690            throw new RuntimeException("The feature has not been requested");
2691        }
2692
2693        PanelFeatureState[] ar;
2694        if ((ar = mPanels) == null || ar.length <= featureId) {
2695            PanelFeatureState[] nar = new PanelFeatureState[featureId + 1];
2696            if (ar != null) {
2697                System.arraycopy(ar, 0, nar, 0, ar.length);
2698            }
2699            mPanels = ar = nar;
2700        }
2701
2702        PanelFeatureState st = ar[featureId];
2703        if (st == null) {
2704            ar[featureId] = st = (convertPanelState != null)
2705                    ? convertPanelState
2706                    : new PanelFeatureState(featureId);
2707        }
2708        return st;
2709    }
2710
2711    @Override
2712    public final void setChildDrawable(int featureId, Drawable drawable) {
2713        DrawableFeatureState st = getDrawableState(featureId, true);
2714        st.child = drawable;
2715        updateDrawable(featureId, st, false);
2716    }
2717
2718    @Override
2719    public final void setChildInt(int featureId, int value) {
2720        updateInt(featureId, value, false);
2721    }
2722
2723    @Override
2724    public boolean isShortcutKey(int keyCode, KeyEvent event) {
2725        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
2726        return st.menu != null && st.menu.isShortcutKey(keyCode, event);
2727    }
2728
2729    private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) {
2730        // Do nothing if the decor is not yet installed... an update will
2731        // need to be forced when we eventually become active.
2732        if (mContentParent == null) {
2733            return;
2734        }
2735
2736        final int featureMask = 1 << featureId;
2737
2738        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2739            return;
2740        }
2741
2742        Drawable drawable = null;
2743        if (st != null) {
2744            drawable = st.child;
2745            if (drawable == null)
2746                drawable = st.local;
2747            if (drawable == null)
2748                drawable = st.def;
2749        }
2750        if ((getLocalFeatures() & featureMask) == 0) {
2751            if (getContainer() != null) {
2752                if (isActive() || fromResume) {
2753                    getContainer().setChildDrawable(featureId, drawable);
2754                }
2755            }
2756        } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) {
2757            // System.out.println("Drawable changed: old=" + st.cur
2758            // + ", new=" + drawable);
2759            st.cur = drawable;
2760            st.curAlpha = st.alpha;
2761            onDrawableChanged(featureId, drawable, st.alpha);
2762        }
2763    }
2764
2765    private void updateInt(int featureId, int value, boolean fromResume) {
2766
2767        // Do nothing if the decor is not yet installed... an update will
2768        // need to be forced when we eventually become active.
2769        if (mContentParent == null) {
2770            return;
2771        }
2772
2773        final int featureMask = 1 << featureId;
2774
2775        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2776            return;
2777        }
2778
2779        if ((getLocalFeatures() & featureMask) == 0) {
2780            if (getContainer() != null) {
2781                getContainer().setChildInt(featureId, value);
2782            }
2783        } else {
2784            onIntChanged(featureId, value);
2785        }
2786    }
2787
2788    private ImageView getLeftIconView() {
2789        if (mLeftIconView != null) {
2790            return mLeftIconView;
2791        }
2792        if (mContentParent == null) {
2793            installDecor();
2794        }
2795        return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon));
2796    }
2797
2798    private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) {
2799        if (mCircularProgressBar != null) {
2800            return mCircularProgressBar;
2801        }
2802        if (mContentParent == null && shouldInstallDecor) {
2803            installDecor();
2804        }
2805        mCircularProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_circular);
2806        if (mCircularProgressBar != null) {
2807            mCircularProgressBar.setVisibility(View.INVISIBLE);
2808        }
2809        return mCircularProgressBar;
2810    }
2811
2812    private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) {
2813        if (mHorizontalProgressBar != null) {
2814            return mHorizontalProgressBar;
2815        }
2816        if (mContentParent == null && shouldInstallDecor) {
2817            installDecor();
2818        }
2819        mHorizontalProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_horizontal);
2820        if (mHorizontalProgressBar != null) {
2821            mHorizontalProgressBar.setVisibility(View.INVISIBLE);
2822        }
2823        return mHorizontalProgressBar;
2824    }
2825
2826    private ImageView getRightIconView() {
2827        if (mRightIconView != null) {
2828            return mRightIconView;
2829        }
2830        if (mContentParent == null) {
2831            installDecor();
2832        }
2833        return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon));
2834    }
2835
2836    /**
2837     * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)}
2838     * callback. This method will grab whatever extra state is needed for the
2839     * callback that isn't given in the parameters. If the panel is not open,
2840     * this will not perform the callback.
2841     *
2842     * @param featureId Feature ID of the panel that was closed. Must be given.
2843     * @param panel Panel that was closed. Optional but useful if there is no
2844     *            menu given.
2845     * @param menu The menu that was closed. Optional, but give if you have.
2846     */
2847    private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) {
2848        final Callback cb = getCallback();
2849        if (cb == null)
2850            return;
2851
2852        // Try to get a menu
2853        if (menu == null) {
2854            // Need a panel to grab the menu, so try to get that
2855            if (panel == null) {
2856                if ((featureId >= 0) && (featureId < mPanels.length)) {
2857                    panel = mPanels[featureId];
2858                }
2859            }
2860
2861            if (panel != null) {
2862                // menu still may be null, which is okay--we tried our best
2863                menu = panel.menu;
2864            }
2865        }
2866
2867        // If the panel is not open, do not callback
2868        if ((panel != null) && (!panel.isOpen))
2869            return;
2870
2871        if (!isDestroyed()) {
2872            cb.onPanelClosed(featureId, menu);
2873        }
2874    }
2875
2876    /**
2877     * Helper method for adding launch-search to most applications. Opens the
2878     * search window using default settings.
2879     *
2880     * @return true if search window opened
2881     */
2882    private boolean launchDefaultSearch() {
2883        final Callback cb = getCallback();
2884        if (cb == null || isDestroyed()) {
2885            return false;
2886        } else {
2887            sendCloseSystemWindows("search");
2888            return cb.onSearchRequested();
2889        }
2890    }
2891
2892    @Override
2893    public void setVolumeControlStream(int streamType) {
2894        mVolumeControlStreamType = streamType;
2895    }
2896
2897    @Override
2898    public int getVolumeControlStream() {
2899        return mVolumeControlStreamType;
2900    }
2901
2902    private static final class DrawableFeatureState {
2903        DrawableFeatureState(int _featureId) {
2904            featureId = _featureId;
2905        }
2906
2907        final int featureId;
2908
2909        int resid;
2910
2911        Uri uri;
2912
2913        Drawable local;
2914
2915        Drawable child;
2916
2917        Drawable def;
2918
2919        Drawable cur;
2920
2921        int alpha = 255;
2922
2923        int curAlpha = 255;
2924    }
2925
2926    private static final class PanelFeatureState {
2927
2928        /** Feature ID for this panel. */
2929        int featureId;
2930
2931        // Information pulled from the style for this panel.
2932
2933        int background;
2934
2935        /** The background when the panel spans the entire available width. */
2936        int fullBackground;
2937
2938        int gravity;
2939
2940        int x;
2941
2942        int y;
2943
2944        int windowAnimations;
2945
2946        /** Dynamic state of the panel. */
2947        DecorView decorView;
2948
2949        /** The panel that was returned by onCreatePanelView(). */
2950        View createdPanelView;
2951
2952        /** The panel that we are actually showing. */
2953        View shownPanelView;
2954
2955        /** Use {@link #setMenu} to set this. */
2956        MenuBuilder menu;
2957
2958        IconMenuPresenter iconMenuPresenter;
2959        ListMenuPresenter expandedMenuPresenter;
2960
2961        /**
2962         * Whether the panel has been prepared (see
2963         * {@link PhoneWindow#preparePanel}).
2964         */
2965        boolean isPrepared;
2966
2967        /**
2968         * Whether an item's action has been performed. This happens in obvious
2969         * scenarios (user clicks on menu item), but can also happen with
2970         * chording menu+(shortcut key).
2971         */
2972        boolean isHandled;
2973
2974        boolean isOpen;
2975
2976        /**
2977         * True if the menu is in expanded mode, false if the menu is in icon
2978         * mode
2979         */
2980        boolean isInExpandedMode;
2981
2982        public boolean qwertyMode;
2983
2984        boolean refreshDecorView;
2985
2986        boolean refreshMenuContent;
2987
2988        boolean wasLastOpen;
2989
2990        boolean wasLastExpanded;
2991
2992        /**
2993         * Contains the state of the menu when told to freeze.
2994         */
2995        Bundle frozenMenuState;
2996
2997        PanelFeatureState(int featureId) {
2998            this.featureId = featureId;
2999
3000            refreshDecorView = false;
3001        }
3002
3003        public boolean hasPanelItems() {
3004            if (shownPanelView == null) return false;
3005
3006            if (isInExpandedMode) {
3007                return expandedMenuPresenter.getAdapter().getCount() > 0;
3008            } else {
3009                return ((ViewGroup) shownPanelView).getChildCount() > 0;
3010            }
3011        }
3012
3013        /**
3014         * Unregister and free attached MenuPresenters. They will be recreated as needed.
3015         */
3016        public void clearMenuPresenters() {
3017            if (menu != null) {
3018                menu.removeMenuPresenter(iconMenuPresenter);
3019                menu.removeMenuPresenter(expandedMenuPresenter);
3020            }
3021            iconMenuPresenter = null;
3022            expandedMenuPresenter = null;
3023        }
3024
3025        void setStyle(Context context) {
3026            TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
3027            background = a.getResourceId(
3028                    com.android.internal.R.styleable.Theme_panelBackground, 0);
3029            fullBackground = a.getResourceId(
3030                    com.android.internal.R.styleable.Theme_panelFullBackground, 0);
3031            windowAnimations = a.getResourceId(
3032                    com.android.internal.R.styleable.Theme_windowAnimationStyle, 0);
3033            a.recycle();
3034        }
3035
3036        void setMenu(MenuBuilder menu) {
3037            this.menu = menu;
3038        }
3039
3040        MenuView getExpandedMenuView(MenuPresenter.Callback cb) {
3041            if (menu == null) return null;
3042
3043            getIconMenuView(cb); // Need this initialized to know where our offset goes
3044
3045            boolean init = false;
3046            if (expandedMenuPresenter == null) {
3047                expandedMenuPresenter = new ListMenuPresenter(
3048                        com.android.internal.R.layout.list_menu_item_layout,
3049                        com.android.internal.R.style.Theme_ExpandedMenu);
3050                expandedMenuPresenter.setCallback(cb);
3051                menu.addMenuPresenter(expandedMenuPresenter);
3052                init = true;
3053            }
3054
3055            expandedMenuPresenter.setItemIndexOffset(iconMenuPresenter.getNumActualItemsShown());
3056            MenuView result = expandedMenuPresenter.getMenuView(decorView);
3057
3058            if (init && frozenMenuState != null) {
3059                expandedMenuPresenter.restoreHierarchyState(frozenMenuState);
3060                // Once we initialize the expanded menu we're done with the frozen state
3061                // since we will have also restored any icon menu state.
3062                frozenMenuState = null;
3063            }
3064
3065            return result;
3066        }
3067
3068        MenuView getIconMenuView(MenuPresenter.Callback cb) {
3069            if (menu == null) return null;
3070
3071            boolean init = false;
3072            if (iconMenuPresenter == null) {
3073                iconMenuPresenter = new IconMenuPresenter();
3074                iconMenuPresenter.setCallback(cb);
3075                menu.addMenuPresenter(iconMenuPresenter);
3076                init = true;
3077            }
3078
3079            MenuView result = iconMenuPresenter.getMenuView(decorView);
3080
3081            if (init && frozenMenuState != null) {
3082                iconMenuPresenter.restoreHierarchyState(frozenMenuState);
3083            }
3084
3085            return result;
3086        }
3087
3088        Parcelable onSaveInstanceState() {
3089            SavedState savedState = new SavedState();
3090            savedState.featureId = featureId;
3091            savedState.isOpen = isOpen;
3092            savedState.isInExpandedMode = isInExpandedMode;
3093
3094            if (menu != null) {
3095                savedState.menuState = new Bundle();
3096                if (iconMenuPresenter != null) {
3097                    iconMenuPresenter.saveHierarchyState(savedState.menuState);
3098                }
3099                if (expandedMenuPresenter != null) {
3100                    expandedMenuPresenter.saveHierarchyState(savedState.menuState);
3101                }
3102            }
3103
3104            return savedState;
3105        }
3106
3107        void onRestoreInstanceState(Parcelable state) {
3108            SavedState savedState = (SavedState) state;
3109            featureId = savedState.featureId;
3110            wasLastOpen = savedState.isOpen;
3111            wasLastExpanded = savedState.isInExpandedMode;
3112            frozenMenuState = savedState.menuState;
3113
3114            /*
3115             * A LocalActivityManager keeps the same instance of this class around.
3116             * The first time the menu is being shown after restoring, the
3117             * Activity.onCreateOptionsMenu should be called. But, if it is the
3118             * same instance then menu != null and we won't call that method.
3119             * We clear any cached views here. The caller should invalidatePanelMenu.
3120             */
3121            createdPanelView = null;
3122            shownPanelView = null;
3123            decorView = null;
3124        }
3125
3126        private static class SavedState implements Parcelable {
3127            int featureId;
3128            boolean isOpen;
3129            boolean isInExpandedMode;
3130            Bundle menuState;
3131
3132            public int describeContents() {
3133                return 0;
3134            }
3135
3136            public void writeToParcel(Parcel dest, int flags) {
3137                dest.writeInt(featureId);
3138                dest.writeInt(isOpen ? 1 : 0);
3139                dest.writeInt(isInExpandedMode ? 1 : 0);
3140
3141                if (isOpen) {
3142                    dest.writeBundle(menuState);
3143                }
3144            }
3145
3146            private static SavedState readFromParcel(Parcel source) {
3147                SavedState savedState = new SavedState();
3148                savedState.featureId = source.readInt();
3149                savedState.isOpen = source.readInt() == 1;
3150                savedState.isInExpandedMode = source.readInt() == 1;
3151
3152                if (savedState.isOpen) {
3153                    savedState.menuState = source.readBundle();
3154                }
3155
3156                return savedState;
3157            }
3158
3159            public static final Parcelable.Creator<SavedState> CREATOR
3160                    = new Parcelable.Creator<SavedState>() {
3161                public SavedState createFromParcel(Parcel in) {
3162                    return readFromParcel(in);
3163                }
3164
3165                public SavedState[] newArray(int size) {
3166                    return new SavedState[size];
3167                }
3168            };
3169        }
3170
3171    }
3172
3173    /**
3174     * Simple implementation of MenuBuilder.Callback that:
3175     * <li> Opens a submenu when selected.
3176     * <li> Calls back to the callback's onMenuItemSelected when an item is
3177     * selected.
3178     */
3179    private final class DialogMenuCallback implements MenuBuilder.Callback, MenuPresenter.Callback {
3180        private int mFeatureId;
3181        private MenuDialogHelper mSubMenuHelper;
3182
3183        public DialogMenuCallback(int featureId) {
3184            mFeatureId = featureId;
3185        }
3186
3187        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
3188            if (menu.getRootMenu() != menu) {
3189                onCloseSubMenu(menu);
3190            }
3191
3192            if (allMenusAreClosing) {
3193                Callback callback = getCallback();
3194                if (callback != null && !isDestroyed()) {
3195                    callback.onPanelClosed(mFeatureId, menu);
3196                }
3197
3198                if (menu == mContextMenu) {
3199                    dismissContextMenu();
3200                }
3201
3202                // Dismiss the submenu, if it is showing
3203                if (mSubMenuHelper != null) {
3204                    mSubMenuHelper.dismiss();
3205                    mSubMenuHelper = null;
3206                }
3207            }
3208        }
3209
3210        public void onCloseSubMenu(MenuBuilder menu) {
3211            Callback callback = getCallback();
3212            if (callback != null && !isDestroyed()) {
3213                callback.onPanelClosed(mFeatureId, menu.getRootMenu());
3214            }
3215        }
3216
3217        public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
3218            Callback callback = getCallback();
3219            return (callback != null && !isDestroyed())
3220                    && callback.onMenuItemSelected(mFeatureId, item);
3221        }
3222
3223        public void onMenuModeChange(MenuBuilder menu) {
3224        }
3225
3226        public boolean onOpenSubMenu(MenuBuilder subMenu) {
3227            // Set a simple callback for the submenu
3228            subMenu.setCallback(this);
3229
3230            // The window manager will give us a valid window token
3231            mSubMenuHelper = new MenuDialogHelper(subMenu);
3232            mSubMenuHelper.show(null);
3233
3234            return true;
3235        }
3236    }
3237
3238    void sendCloseSystemWindows() {
3239        PhoneWindowManager.sendCloseSystemWindows(getContext(), null);
3240    }
3241
3242    void sendCloseSystemWindows(String reason) {
3243        PhoneWindowManager.sendCloseSystemWindows(getContext(), reason);
3244    }
3245}
3246