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