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