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