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