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