PhoneWindow.java revision d76b67c340d1564abf8d14d976fdaf83bf2b3320
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                AudioManager audioManager = (AudioManager) getContext().getSystemService(
1321                        Context.AUDIO_SERVICE);
1322                if (audioManager != null) {
1323                    /*
1324                     * Play a sound. This is done on key up since we don't want the
1325                     * sound to play when a user holds down volume down to mute.
1326                     */
1327                    audioManager.adjustSuggestedStreamVolume(
1328                            AudioManager.ADJUST_SAME,
1329                            mVolumeControlStreamType,
1330                            AudioManager.FLAG_PLAY_SOUND);
1331                    mVolumeKeyUpTime = SystemClock.uptimeMillis();
1332                }
1333                return true;
1334            }
1335
1336            case KeyEvent.KEYCODE_MENU: {
1337                onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId,
1338                        event);
1339                return true;
1340            }
1341
1342            case KeyEvent.KEYCODE_BACK: {
1343                if (featureId < 0) break;
1344                if (event.isTracking() && !event.isCanceled()) {
1345                    if (featureId == FEATURE_OPTIONS_PANEL) {
1346                        PanelFeatureState st = getPanelState(featureId, false);
1347                        if (st != null && st.isInExpandedMode) {
1348                            // If the user is in an expanded menu and hits back, it
1349                            // should go back to the icon menu
1350                            reopenMenu(true);
1351                            return true;
1352                        }
1353                    }
1354                    closePanel(featureId);
1355                    return true;
1356                }
1357                break;
1358            }
1359
1360            case KeyEvent.KEYCODE_HEADSETHOOK:
1361            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
1362            case KeyEvent.KEYCODE_MEDIA_STOP:
1363            case KeyEvent.KEYCODE_MEDIA_NEXT:
1364            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
1365            case KeyEvent.KEYCODE_MEDIA_REWIND:
1366            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
1367                Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
1368                intent.putExtra(Intent.EXTRA_KEY_EVENT, event);
1369                getContext().sendOrderedBroadcast(intent, null);
1370                return true;
1371            }
1372
1373            case KeyEvent.KEYCODE_CAMERA: {
1374                if (getKeyguardManager().inKeyguardRestrictedInputMode()) {
1375                    break;
1376                }
1377                if (event.isTracking() && !event.isCanceled()) {
1378                    // Add short press behavior here if desired
1379                }
1380                return true;
1381            }
1382
1383            case KeyEvent.KEYCODE_CALL: {
1384                if (getKeyguardManager().inKeyguardRestrictedInputMode()) {
1385                    break;
1386                }
1387                if (event.isTracking() && !event.isCanceled()) {
1388                    startCallActivity();
1389                }
1390                return true;
1391            }
1392
1393            case KeyEvent.KEYCODE_SEARCH: {
1394                /*
1395                 * Do this in onKeyUp since the Search key is also used for
1396                 * chording quick launch shortcuts.
1397                 */
1398                if (getKeyguardManager().inKeyguardRestrictedInputMode()) {
1399                    break;
1400                }
1401                if (event.isTracking() && !event.isCanceled()) {
1402                    launchDefaultSearch();
1403                }
1404                return true;
1405            }
1406        }
1407
1408        return false;
1409    }
1410
1411    private void startCallActivity() {
1412        sendCloseSystemWindows();
1413        Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);
1414        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1415        getContext().startActivity(intent);
1416    }
1417
1418    @Override
1419    protected void onActive() {
1420    }
1421
1422    @Override
1423    public final View getDecorView() {
1424        if (mDecor == null) {
1425            installDecor();
1426        }
1427        return mDecor;
1428    }
1429
1430    @Override
1431    public final View peekDecorView() {
1432        return mDecor;
1433    }
1434
1435    static private final String FOCUSED_ID_TAG = "android:focusedViewId";
1436    static private final String VIEWS_TAG = "android:views";
1437    static private final String PANELS_TAG = "android:Panels";
1438
1439    /** {@inheritDoc} */
1440    @Override
1441    public Bundle saveHierarchyState() {
1442        Bundle outState = new Bundle();
1443        if (mContentParent == null) {
1444            return outState;
1445        }
1446
1447        SparseArray<Parcelable> states = new SparseArray<Parcelable>();
1448        mContentParent.saveHierarchyState(states);
1449        outState.putSparseParcelableArray(VIEWS_TAG, states);
1450
1451        // save the focused view id
1452        View focusedView = mContentParent.findFocus();
1453        if (focusedView != null) {
1454            if (focusedView.getId() != View.NO_ID) {
1455                outState.putInt(FOCUSED_ID_TAG, focusedView.getId());
1456            } else {
1457                if (Config.LOGD) {
1458                    Log.d(TAG, "couldn't save which view has focus because the focused view "
1459                            + focusedView + " has no id.");
1460                }
1461            }
1462        }
1463
1464        // save the panels
1465        SparseArray<Parcelable> panelStates = new SparseArray<Parcelable>();
1466        savePanelState(panelStates);
1467        if (panelStates.size() > 0) {
1468            outState.putSparseParcelableArray(PANELS_TAG, panelStates);
1469        }
1470
1471        return outState;
1472    }
1473
1474    /** {@inheritDoc} */
1475    @Override
1476    public void restoreHierarchyState(Bundle savedInstanceState) {
1477        if (mContentParent == null) {
1478            return;
1479        }
1480
1481        SparseArray<Parcelable> savedStates
1482                = savedInstanceState.getSparseParcelableArray(VIEWS_TAG);
1483        if (savedStates != null) {
1484            mContentParent.restoreHierarchyState(savedStates);
1485        }
1486
1487        // restore the focused view
1488        int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID);
1489        if (focusedViewId != View.NO_ID) {
1490            View needsFocus = mContentParent.findViewById(focusedViewId);
1491            if (needsFocus != null) {
1492                needsFocus.requestFocus();
1493            } else {
1494                Log.w(TAG,
1495                        "Previously focused view reported id " + focusedViewId
1496                                + " during save, but can't be found during restore.");
1497            }
1498        }
1499
1500        // restore the panels
1501        SparseArray<Parcelable> panelStates = savedInstanceState.getSparseParcelableArray(PANELS_TAG);
1502        if (panelStates != null) {
1503            restorePanelState(panelStates);
1504        }
1505    }
1506
1507    /**
1508     * Invoked when the panels should freeze their state.
1509     *
1510     * @param icicles Save state into this. This is usually indexed by the
1511     *            featureId. This will be given to {@link #restorePanelState} in the
1512     *            future.
1513     */
1514    private void savePanelState(SparseArray<Parcelable> icicles) {
1515        PanelFeatureState[] panels = mPanels;
1516        if (panels == null) {
1517            return;
1518        }
1519
1520        for (int curFeatureId = panels.length - 1; curFeatureId >= 0; curFeatureId--) {
1521            if (panels[curFeatureId] != null) {
1522                icicles.put(curFeatureId, panels[curFeatureId].onSaveInstanceState());
1523            }
1524        }
1525    }
1526
1527    /**
1528     * Invoked when the panels should thaw their state from a previously frozen state.
1529     *
1530     * @param icicles The state saved by {@link #savePanelState} that needs to be thawed.
1531     */
1532    private void restorePanelState(SparseArray<Parcelable> icicles) {
1533        PanelFeatureState st;
1534        for (int curFeatureId = icicles.size() - 1; curFeatureId >= 0; curFeatureId--) {
1535            st = getPanelState(curFeatureId, false /* required */);
1536            if (st == null) {
1537                // The panel must not have been required, and is currently not around, skip it
1538                continue;
1539            }
1540
1541            st.onRestoreInstanceState(icicles.get(curFeatureId));
1542        }
1543
1544        /*
1545         * Implementation note: call openPanelsAfterRestore later to actually open the
1546         * restored panels.
1547         */
1548    }
1549
1550    /**
1551     * Opens the panels that have had their state restored. This should be
1552     * called sometime after {@link #restorePanelState} when it is safe to add
1553     * to the window manager.
1554     */
1555    private void openPanelsAfterRestore() {
1556        PanelFeatureState[] panels = mPanels;
1557
1558        if (panels == null) {
1559            return;
1560        }
1561
1562        PanelFeatureState st;
1563        for (int i = panels.length - 1; i >= 0; i--) {
1564            st = panels[i];
1565            // We restore the panel if it was last open; we skip it if it
1566            // now is open, to avoid a race condition if the user immediately
1567            // opens it when we are resuming.
1568            if ((st != null) && !st.isOpen && st.wasLastOpen) {
1569                st.isInExpandedMode = st.wasLastExpanded;
1570                openPanel(st, null);
1571            }
1572        }
1573    }
1574
1575    private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
1576        /* package */int mDefaultOpacity = PixelFormat.OPAQUE;
1577
1578        /** The feature ID of the panel, or -1 if this is the application's DecorView */
1579        private final int mFeatureId;
1580
1581        private final Rect mDrawingBounds = new Rect();
1582
1583        private final Rect mBackgroundPadding = new Rect();
1584
1585        private final Rect mFramePadding = new Rect();
1586
1587        private final Rect mFrameOffsets = new Rect();
1588
1589        private boolean mChanging;
1590
1591        private Drawable mMenuBackground;
1592        private boolean mWatchingForMenu;
1593        private int mDownY;
1594
1595        public DecorView(Context context, int featureId) {
1596            super(context);
1597            mFeatureId = featureId;
1598        }
1599
1600        @Override
1601        public boolean dispatchKeyEvent(KeyEvent event) {
1602            final int keyCode = event.getKeyCode();
1603            final boolean isDown = event.getAction() == KeyEvent.ACTION_DOWN;
1604
1605            /*
1606             * If the user hits another key within the play sound delay, then
1607             * cancel the sound
1608             */
1609            if (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_UP
1610                    && mVolumeKeyUpTime + VolumePanel.PLAY_SOUND_DELAY
1611                            > SystemClock.uptimeMillis()) {
1612                /*
1613                 * The user has hit another key during the delay (e.g., 300ms)
1614                 * since the last volume key up, so cancel any sounds.
1615                 */
1616                AudioManager audioManager = (AudioManager) getContext().getSystemService(
1617                        Context.AUDIO_SERVICE);
1618                if (audioManager != null) {
1619                    audioManager.adjustSuggestedStreamVolume(AudioManager.ADJUST_SAME,
1620                            mVolumeControlStreamType, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
1621                }
1622            }
1623
1624            if (isDown && (event.getRepeatCount() == 0)) {
1625                // First handle chording of panel key: if a panel key is held
1626                // but not released, try to execute a shortcut in it.
1627                if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) {
1628                    // Perform the shortcut (mPreparedPanel can be null since
1629                    // global shortcuts (such as search) don't rely on a
1630                    // prepared panel or menu).
1631                    boolean handled = performPanelShortcut(mPreparedPanel, keyCode, event,
1632                            Menu.FLAG_PERFORM_NO_CLOSE);
1633
1634                    if (!handled) {
1635                        /*
1636                         * If not handled, then pass it to the view hierarchy
1637                         * and anyone else that may be interested.
1638                         */
1639                        handled = dispatchKeyShortcutEvent(event);
1640
1641                        if (handled && mPreparedPanel != null) {
1642                            mPreparedPanel.isHandled = true;
1643                        }
1644                    }
1645
1646                    if (handled) {
1647                        return true;
1648                    }
1649                }
1650
1651                // If a panel is open, perform a shortcut on it without the
1652                // chorded panel key
1653                if ((mPreparedPanel != null) && mPreparedPanel.isOpen) {
1654                    if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) {
1655                        return true;
1656                    }
1657                }
1658            }
1659
1660            final Callback cb = getCallback();
1661            final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event)
1662                    : super.dispatchKeyEvent(event);
1663            if (handled) {
1664                return true;
1665            }
1666            return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event)
1667                    : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event);
1668        }
1669
1670        @Override
1671        public boolean dispatchTouchEvent(MotionEvent ev) {
1672            final Callback cb = getCallback();
1673            return cb != null && mFeatureId < 0 ? cb.dispatchTouchEvent(ev) : super
1674                    .dispatchTouchEvent(ev);
1675        }
1676
1677        @Override
1678        public boolean dispatchTrackballEvent(MotionEvent ev) {
1679            final Callback cb = getCallback();
1680            return cb != null && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev) : super
1681                    .dispatchTrackballEvent(ev);
1682        }
1683
1684        public boolean superDispatchKeyEvent(KeyEvent event) {
1685            return super.dispatchKeyEvent(event);
1686        }
1687
1688        public boolean superDispatchTouchEvent(MotionEvent event) {
1689            return super.dispatchTouchEvent(event);
1690        }
1691
1692        public boolean superDispatchTrackballEvent(MotionEvent event) {
1693            return super.dispatchTrackballEvent(event);
1694        }
1695
1696        @Override
1697        public boolean onTouchEvent(MotionEvent event) {
1698            return onInterceptTouchEvent(event);
1699        }
1700
1701        private boolean isOutOfBounds(int x, int y) {
1702            return x < -5 || y < -5 || x > (getWidth() + 5)
1703                    || y > (getHeight() + 5);
1704        }
1705
1706        @Override
1707        public boolean onInterceptTouchEvent(MotionEvent event) {
1708            int action = event.getAction();
1709            if (mFeatureId >= 0) {
1710                if (action == MotionEvent.ACTION_DOWN) {
1711                    int x = (int)event.getX();
1712                    int y = (int)event.getY();
1713                    if (isOutOfBounds(x, y)) {
1714                        closePanel(mFeatureId);
1715                        return true;
1716                    }
1717                }
1718            }
1719
1720            if (!SWEEP_OPEN_MENU) {
1721                return false;
1722            }
1723
1724            if (mFeatureId >= 0) {
1725                if (action == MotionEvent.ACTION_DOWN) {
1726                    Log.i(TAG, "Watchiing!");
1727                    mWatchingForMenu = true;
1728                    mDownY = (int) event.getY();
1729                    return false;
1730                }
1731
1732                if (!mWatchingForMenu) {
1733                    return false;
1734                }
1735
1736                int y = (int)event.getY();
1737                if (action == MotionEvent.ACTION_MOVE) {
1738                    if (y > (mDownY+30)) {
1739                        Log.i(TAG, "Closing!");
1740                        closePanel(mFeatureId);
1741                        mWatchingForMenu = false;
1742                        return true;
1743                    }
1744                } else if (action == MotionEvent.ACTION_UP) {
1745                    mWatchingForMenu = false;
1746                }
1747
1748                return false;
1749            }
1750
1751            //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY()
1752            //        + " (in " + getHeight() + ")");
1753
1754            if (action == MotionEvent.ACTION_DOWN) {
1755                int y = (int)event.getY();
1756                if (y >= (getHeight()-5) && !hasChildren()) {
1757                    Log.i(TAG, "Watchiing!");
1758                    mWatchingForMenu = true;
1759                }
1760                return false;
1761            }
1762
1763            if (!mWatchingForMenu) {
1764                return false;
1765            }
1766
1767            int y = (int)event.getY();
1768            if (action == MotionEvent.ACTION_MOVE) {
1769                if (y < (getHeight()-30)) {
1770                    Log.i(TAG, "Opening!");
1771                    openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent(
1772                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU));
1773                    mWatchingForMenu = false;
1774                    return true;
1775                }
1776            } else if (action == MotionEvent.ACTION_UP) {
1777                mWatchingForMenu = false;
1778            }
1779
1780            return false;
1781        }
1782
1783        @Override
1784        public void sendAccessibilityEvent(int eventType) {
1785            if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
1786                return;
1787            }
1788
1789            // if we are showing a feature that should be announced and one child
1790            // make this child the event source since this is the feature itself
1791            // otherwise the callback will take over and announce its client
1792            if ((mFeatureId == FEATURE_OPTIONS_PANEL ||
1793                    mFeatureId == FEATURE_CONTEXT_MENU ||
1794                    mFeatureId == FEATURE_PROGRESS ||
1795                    mFeatureId == FEATURE_INDETERMINATE_PROGRESS)
1796                    && getChildCount() == 1) {
1797                getChildAt(0).sendAccessibilityEvent(eventType);
1798            } else {
1799                super.sendAccessibilityEvent(eventType);
1800            }
1801        }
1802
1803        @Override
1804        public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1805            final Callback cb = getCallback();
1806            if (cb != null) {
1807                if (cb.dispatchPopulateAccessibilityEvent(event)) {
1808                    return true;
1809                }
1810            }
1811            return super.dispatchPopulateAccessibilityEvent(event);
1812        }
1813
1814        @Override
1815        protected boolean setFrame(int l, int t, int r, int b) {
1816            boolean changed = super.setFrame(l, t, r, b);
1817            if (changed) {
1818                final Rect drawingBounds = mDrawingBounds;
1819                getDrawingRect(drawingBounds);
1820
1821                Drawable fg = getForeground();
1822                if (fg != null) {
1823                    final Rect frameOffsets = mFrameOffsets;
1824                    drawingBounds.left += frameOffsets.left;
1825                    drawingBounds.top += frameOffsets.top;
1826                    drawingBounds.right -= frameOffsets.right;
1827                    drawingBounds.bottom -= frameOffsets.bottom;
1828                    fg.setBounds(drawingBounds);
1829                    final Rect framePadding = mFramePadding;
1830                    drawingBounds.left += framePadding.left - frameOffsets.left;
1831                    drawingBounds.top += framePadding.top - frameOffsets.top;
1832                    drawingBounds.right -= framePadding.right - frameOffsets.right;
1833                    drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom;
1834                }
1835
1836                Drawable bg = getBackground();
1837                if (bg != null) {
1838                    bg.setBounds(drawingBounds);
1839                }
1840
1841                if (SWEEP_OPEN_MENU) {
1842                    if (mMenuBackground == null && mFeatureId < 0
1843                            && getAttributes().height
1844                            == WindowManager.LayoutParams.MATCH_PARENT) {
1845                        mMenuBackground = getContext().getResources().getDrawable(
1846                                com.android.internal.R.drawable.menu_background);
1847                    }
1848                    if (mMenuBackground != null) {
1849                        mMenuBackground.setBounds(drawingBounds.left,
1850                                drawingBounds.bottom-6, drawingBounds.right,
1851                                drawingBounds.bottom+20);
1852                    }
1853                }
1854            }
1855            return changed;
1856        }
1857
1858        @Override
1859        public void draw(Canvas canvas) {
1860            super.draw(canvas);
1861
1862            if (mMenuBackground != null) {
1863                mMenuBackground.draw(canvas);
1864            }
1865        }
1866
1867
1868        @Override
1869        public boolean showContextMenuForChild(View originalView) {
1870            // Reuse the context menu builder
1871            if (mContextMenu == null) {
1872                mContextMenu = new ContextMenuBuilder(getContext());
1873                mContextMenu.setCallback(mContextMenuCallback);
1874            } else {
1875                mContextMenu.clearAll();
1876            }
1877
1878            mContextMenuHelper = mContextMenu.show(originalView, originalView.getWindowToken());
1879            return mContextMenuHelper != null;
1880        }
1881
1882        public void startChanging() {
1883            mChanging = true;
1884        }
1885
1886        public void finishChanging() {
1887            mChanging = false;
1888            drawableChanged();
1889        }
1890
1891        public void setWindowBackground(Drawable drawable) {
1892            if (getBackground() != drawable) {
1893                setBackgroundDrawable(drawable);
1894                if (drawable != null) {
1895                    drawable.getPadding(mBackgroundPadding);
1896                } else {
1897                    mBackgroundPadding.setEmpty();
1898                }
1899                drawableChanged();
1900            }
1901        }
1902
1903        public void setWindowFrame(Drawable drawable) {
1904            if (getForeground() != drawable) {
1905                setForeground(drawable);
1906                if (drawable != null) {
1907                    drawable.getPadding(mFramePadding);
1908                } else {
1909                    mFramePadding.setEmpty();
1910                }
1911                drawableChanged();
1912            }
1913        }
1914
1915        @Override
1916        protected boolean fitSystemWindows(Rect insets) {
1917            mFrameOffsets.set(insets);
1918            if (getForeground() != null) {
1919                drawableChanged();
1920            }
1921            return super.fitSystemWindows(insets);
1922        }
1923
1924        private void drawableChanged() {
1925            if (mChanging) {
1926                return;
1927            }
1928
1929            setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top
1930                    + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right,
1931                    mFramePadding.bottom + mBackgroundPadding.bottom);
1932            requestLayout();
1933            invalidate();
1934
1935            int opacity = PixelFormat.OPAQUE;
1936
1937            // Note: if there is no background, we will assume opaque. The
1938            // common case seems to be that an application sets there to be
1939            // no background so it can draw everything itself. For that,
1940            // we would like to assume OPAQUE and let the app force it to
1941            // the slower TRANSLUCENT mode if that is really what it wants.
1942            Drawable bg = getBackground();
1943            Drawable fg = getForeground();
1944            if (bg != null) {
1945                if (fg == null) {
1946                    opacity = bg.getOpacity();
1947                } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0
1948                        && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) {
1949                    // If the frame padding is zero, then we can be opaque
1950                    // if either the frame -or- the background is opaque.
1951                    int fop = fg.getOpacity();
1952                    int bop = bg.getOpacity();
1953                    if (Config.LOGV)
1954                        Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop);
1955                    if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) {
1956                        opacity = PixelFormat.OPAQUE;
1957                    } else if (fop == PixelFormat.UNKNOWN) {
1958                        opacity = bop;
1959                    } else if (bop == PixelFormat.UNKNOWN) {
1960                        opacity = fop;
1961                    } else {
1962                        opacity = Drawable.resolveOpacity(fop, bop);
1963                    }
1964                } else {
1965                    // For now we have to assume translucent if there is a
1966                    // frame with padding... there is no way to tell if the
1967                    // frame and background together will draw all pixels.
1968                    if (Config.LOGV)
1969                        Log.v(TAG, "Padding: " + mFramePadding);
1970                    opacity = PixelFormat.TRANSLUCENT;
1971                }
1972            }
1973
1974            if (Config.LOGV)
1975                Log.v(TAG, "Background: " + bg + ", Frame: " + fg);
1976            if (Config.LOGV)
1977                Log.v(TAG, "Selected default opacity: " + opacity);
1978
1979            mDefaultOpacity = opacity;
1980            if (mFeatureId < 0) {
1981                setDefaultWindowFormat(opacity);
1982            }
1983        }
1984
1985        @Override
1986        public void onWindowFocusChanged(boolean hasWindowFocus) {
1987            super.onWindowFocusChanged(hasWindowFocus);
1988
1989            mPanelMayLongPress = false;
1990
1991            // If the user is chording a menu shortcut, release the chord since
1992            // this window lost focus
1993            if (!hasWindowFocus && mPanelChordingKey != 0) {
1994                closePanel(FEATURE_OPTIONS_PANEL);
1995            }
1996
1997            final Callback cb = getCallback();
1998            if (cb != null && mFeatureId < 0) {
1999                cb.onWindowFocusChanged(hasWindowFocus);
2000            }
2001        }
2002
2003        @Override
2004        protected void onAttachedToWindow() {
2005            super.onAttachedToWindow();
2006
2007            final Callback cb = getCallback();
2008            if (cb != null && mFeatureId < 0) {
2009                cb.onAttachedToWindow();
2010            }
2011
2012            if (mFeatureId == -1) {
2013                /*
2014                 * The main window has been attached, try to restore any panels
2015                 * that may have been open before. This is called in cases where
2016                 * an activity is being killed for configuration change and the
2017                 * menu was open. When the activity is recreated, the menu
2018                 * should be shown again.
2019                 */
2020                openPanelsAfterRestore();
2021            }
2022        }
2023
2024        @Override
2025        protected void onDetachedFromWindow() {
2026            super.onDetachedFromWindow();
2027
2028            final Callback cb = getCallback();
2029            if (cb != null && mFeatureId < 0) {
2030                cb.onDetachedFromWindow();
2031            }
2032        }
2033
2034        @Override
2035        public void onCloseSystemDialogs(String reason) {
2036            if (mFeatureId >= 0) {
2037                closeAllPanels();
2038            }
2039        }
2040
2041        public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() {
2042            return mFeatureId < 0 ? mTakeSurfaceCallback : null;
2043        }
2044
2045        public InputQueue.Callback willYouTakeTheInputQueue() {
2046            return mFeatureId < 0 ? mTakeInputQueueCallback : null;
2047        }
2048
2049        public void setSurfaceType(int type) {
2050            PhoneWindow.this.setType(type);
2051        }
2052
2053        public void setSurfaceFormat(int format) {
2054            PhoneWindow.this.setFormat(format);
2055        }
2056
2057        public void setSurfaceKeepScreenOn(boolean keepOn) {
2058            if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2059            else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2060        }
2061    }
2062
2063    protected DecorView generateDecor() {
2064        return new DecorView(getContext(), -1);
2065    }
2066
2067    protected void setFeatureFromAttrs(int featureId, TypedArray attrs,
2068            int drawableAttr, int alphaAttr) {
2069        Drawable d = attrs.getDrawable(drawableAttr);
2070        if (d != null) {
2071            requestFeature(featureId);
2072            setFeatureDefaultDrawable(featureId, d);
2073        }
2074        if ((getFeatures() & (1 << featureId)) != 0) {
2075            int alpha = attrs.getInt(alphaAttr, -1);
2076            if (alpha >= 0) {
2077                setFeatureDrawableAlpha(featureId, alpha);
2078            }
2079        }
2080    }
2081
2082    protected ViewGroup generateLayout(DecorView decor) {
2083        // Apply data from current theme.
2084
2085        TypedArray a = getWindowStyle();
2086
2087        if (false) {
2088            System.out.println("From style:");
2089            String s = "Attrs:";
2090            for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) {
2091                s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "="
2092                        + a.getString(i);
2093            }
2094            System.out.println(s);
2095        }
2096
2097        mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
2098        int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
2099                & (~getForcedWindowFlags());
2100        if (mIsFloating) {
2101            setLayout(WRAP_CONTENT, WRAP_CONTENT);
2102            setFlags(0, flagsToUpdate);
2103        } else {
2104            setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
2105        }
2106
2107        if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
2108            requestFeature(FEATURE_NO_TITLE);
2109        }
2110
2111        if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
2112            setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags()));
2113        }
2114
2115        if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) {
2116            setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
2117        }
2118
2119        WindowManager.LayoutParams params = getAttributes();
2120
2121        if (!hasSoftInputMode()) {
2122            params.softInputMode = a.getInt(
2123                    com.android.internal.R.styleable.Window_windowSoftInputMode,
2124                    params.softInputMode);
2125        }
2126
2127        if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled,
2128                mIsFloating)) {
2129            /* All dialogs should have the window dimmed */
2130            if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
2131                params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
2132            }
2133            params.dimAmount = a.getFloat(
2134                    android.R.styleable.Window_backgroundDimAmount, 0.5f);
2135        }
2136
2137        if (params.windowAnimations == 0) {
2138            params.windowAnimations = a.getResourceId(
2139                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2140        }
2141
2142        // The rest are only done if this window is not embedded; otherwise,
2143        // the values are inherited from our container.
2144        if (getContainer() == null) {
2145            if (mBackgroundDrawable == null) {
2146                if (mBackgroundResource == 0) {
2147                    mBackgroundResource = a.getResourceId(
2148                            com.android.internal.R.styleable.Window_windowBackground, 0);
2149                }
2150                if (mFrameResource == 0) {
2151                    mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0);
2152                }
2153                if (false) {
2154                    System.out.println("Background: "
2155                            + Integer.toHexString(mBackgroundResource) + " Frame: "
2156                            + Integer.toHexString(mFrameResource));
2157                }
2158            }
2159            mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000);
2160        }
2161
2162        // Inflate the window decor.
2163
2164        int layoutResource;
2165        int features = getLocalFeatures();
2166        // System.out.println("Features: 0x" + Integer.toHexString(features));
2167        if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
2168            if (mIsFloating) {
2169                layoutResource = com.android.internal.R.layout.dialog_title_icons;
2170            } else {
2171                layoutResource = com.android.internal.R.layout.screen_title_icons;
2172            }
2173            // System.out.println("Title Icons!");
2174        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0) {
2175            // Special case for a window with only a progress bar (and title).
2176            // XXX Need to have a no-title version of embedded windows.
2177            layoutResource = com.android.internal.R.layout.screen_progress;
2178            // System.out.println("Progress!");
2179        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
2180            // Special case for a window with a custom title.
2181            // If the window is floating, we need a dialog layout
2182            if (mIsFloating) {
2183                layoutResource = com.android.internal.R.layout.dialog_custom_title;
2184            } else {
2185                layoutResource = com.android.internal.R.layout.screen_custom_title;
2186            }
2187        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
2188            // If no other features and not embedded, only need a title.
2189            // If the window is floating, we need a dialog layout
2190            if (mIsFloating) {
2191                layoutResource = com.android.internal.R.layout.dialog_title;
2192            } else {
2193                layoutResource = com.android.internal.R.layout.screen_title;
2194            }
2195            // System.out.println("Title!");
2196        } else {
2197            // Embedded, so no decoration is needed.
2198            layoutResource = com.android.internal.R.layout.screen_simple;
2199            // System.out.println("Simple!");
2200        }
2201
2202        mDecor.startChanging();
2203
2204        View in = mLayoutInflater.inflate(layoutResource, null);
2205        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
2206
2207        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
2208        if (contentParent == null) {
2209            throw new RuntimeException("Window couldn't find content container view");
2210        }
2211
2212        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2213            ProgressBar progress = getCircularProgressBar(false);
2214            if (progress != null) {
2215                progress.setIndeterminate(true);
2216            }
2217        }
2218
2219        // Remaining setup -- of background and title -- that only applies
2220        // to top-level windows.
2221        if (getContainer() == null) {
2222            Drawable drawable = mBackgroundDrawable;
2223            if (mBackgroundResource != 0) {
2224                drawable = getContext().getResources().getDrawable(mBackgroundResource);
2225            }
2226            mDecor.setWindowBackground(drawable);
2227            drawable = null;
2228            if (mFrameResource != 0) {
2229                drawable = getContext().getResources().getDrawable(mFrameResource);
2230            }
2231            mDecor.setWindowFrame(drawable);
2232
2233            // System.out.println("Text=" + Integer.toHexString(mTextColor) +
2234            // " Sel=" + Integer.toHexString(mTextSelectedColor) +
2235            // " Title=" + Integer.toHexString(mTitleColor));
2236
2237            if (mTitleColor == 0) {
2238                mTitleColor = mTextColor;
2239            }
2240
2241            if (mTitle != null) {
2242                setTitle(mTitle);
2243            }
2244            setTitleColor(mTitleColor);
2245        }
2246
2247        mDecor.finishChanging();
2248
2249        return contentParent;
2250    }
2251
2252    private void installDecor() {
2253        if (mDecor == null) {
2254            mDecor = generateDecor();
2255            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
2256            mDecor.setIsRootNamespace(true);
2257        }
2258        if (mContentParent == null) {
2259            mContentParent = generateLayout(mDecor);
2260
2261            mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
2262            if (mTitleView != null) {
2263                if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
2264                    View titleContainer = findViewById(com.android.internal.R.id.title_container);
2265                    if (titleContainer != null) {
2266                        titleContainer.setVisibility(View.GONE);
2267                    } else {
2268                        mTitleView.setVisibility(View.GONE);
2269                    }
2270                    if (mContentParent instanceof FrameLayout) {
2271                        ((FrameLayout)mContentParent).setForeground(null);
2272                    }
2273                } else {
2274                    mTitleView.setText(mTitle);
2275                }
2276            }
2277        }
2278    }
2279
2280    private Drawable loadImageURI(Uri uri) {
2281        try {
2282            return Drawable.createFromStream(
2283                    getContext().getContentResolver().openInputStream(uri), null);
2284        } catch (Exception e) {
2285            Log.w(TAG, "Unable to open content: " + uri);
2286        }
2287        return null;
2288    }
2289
2290    private DrawableFeatureState getDrawableState(int featureId, boolean required) {
2291        if ((getFeatures() & (1 << featureId)) == 0) {
2292            if (!required) {
2293                return null;
2294            }
2295            throw new RuntimeException("The feature has not been requested");
2296        }
2297
2298        DrawableFeatureState[] ar;
2299        if ((ar = mDrawables) == null || ar.length <= featureId) {
2300            DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1];
2301            if (ar != null) {
2302                System.arraycopy(ar, 0, nar, 0, ar.length);
2303            }
2304            mDrawables = ar = nar;
2305        }
2306
2307        DrawableFeatureState st = ar[featureId];
2308        if (st == null) {
2309            ar[featureId] = st = new DrawableFeatureState(featureId);
2310        }
2311        return st;
2312    }
2313
2314    /**
2315     * Gets a panel's state based on its feature ID.
2316     *
2317     * @param featureId The feature ID of the panel.
2318     * @param required Whether the panel is required (if it is required and it
2319     *            isn't in our features, this throws an exception).
2320     * @return The panel state.
2321     */
2322    private PanelFeatureState getPanelState(int featureId, boolean required) {
2323        return getPanelState(featureId, required, null);
2324    }
2325
2326    /**
2327     * Gets a panel's state based on its feature ID.
2328     *
2329     * @param featureId The feature ID of the panel.
2330     * @param required Whether the panel is required (if it is required and it
2331     *            isn't in our features, this throws an exception).
2332     * @param convertPanelState Optional: If the panel state does not exist, use
2333     *            this as the panel state.
2334     * @return The panel state.
2335     */
2336    private PanelFeatureState getPanelState(int featureId, boolean required,
2337            PanelFeatureState convertPanelState) {
2338        if ((getFeatures() & (1 << featureId)) == 0) {
2339            if (!required) {
2340                return null;
2341            }
2342            throw new RuntimeException("The feature has not been requested");
2343        }
2344
2345        PanelFeatureState[] ar;
2346        if ((ar = mPanels) == null || ar.length <= featureId) {
2347            PanelFeatureState[] nar = new PanelFeatureState[featureId + 1];
2348            if (ar != null) {
2349                System.arraycopy(ar, 0, nar, 0, ar.length);
2350            }
2351            mPanels = ar = nar;
2352        }
2353
2354        PanelFeatureState st = ar[featureId];
2355        if (st == null) {
2356            ar[featureId] = st = (convertPanelState != null)
2357                    ? convertPanelState
2358                    : new PanelFeatureState(featureId);
2359        }
2360        return st;
2361    }
2362
2363    @Override
2364    public final void setChildDrawable(int featureId, Drawable drawable) {
2365        DrawableFeatureState st = getDrawableState(featureId, true);
2366        st.child = drawable;
2367        updateDrawable(featureId, st, false);
2368    }
2369
2370    @Override
2371    public final void setChildInt(int featureId, int value) {
2372        updateInt(featureId, value, false);
2373    }
2374
2375    @Override
2376    public boolean isShortcutKey(int keyCode, KeyEvent event) {
2377        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
2378        return st.menu != null && st.menu.isShortcutKey(keyCode, event);
2379    }
2380
2381    private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) {
2382        // Do nothing if the decor is not yet installed... an update will
2383        // need to be forced when we eventually become active.
2384        if (mContentParent == null) {
2385            return;
2386        }
2387
2388        final int featureMask = 1 << featureId;
2389
2390        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2391            return;
2392        }
2393
2394        Drawable drawable = null;
2395        if (st != null) {
2396            drawable = st.child;
2397            if (drawable == null)
2398                drawable = st.local;
2399            if (drawable == null)
2400                drawable = st.def;
2401        }
2402        if ((getLocalFeatures() & featureMask) == 0) {
2403            if (getContainer() != null) {
2404                if (isActive() || fromResume) {
2405                    getContainer().setChildDrawable(featureId, drawable);
2406                }
2407            }
2408        } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) {
2409            // System.out.println("Drawable changed: old=" + st.cur
2410            // + ", new=" + drawable);
2411            st.cur = drawable;
2412            st.curAlpha = st.alpha;
2413            onDrawableChanged(featureId, drawable, st.alpha);
2414        }
2415    }
2416
2417    private void updateInt(int featureId, int value, boolean fromResume) {
2418
2419        // Do nothing if the decor is not yet installed... an update will
2420        // need to be forced when we eventually become active.
2421        if (mContentParent == null) {
2422            return;
2423        }
2424
2425        final int featureMask = 1 << featureId;
2426
2427        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2428            return;
2429        }
2430
2431        if ((getLocalFeatures() & featureMask) == 0) {
2432            if (getContainer() != null) {
2433                getContainer().setChildInt(featureId, value);
2434            }
2435        } else {
2436            onIntChanged(featureId, value);
2437        }
2438    }
2439
2440    private ImageView getLeftIconView() {
2441        if (mLeftIconView != null) {
2442            return mLeftIconView;
2443        }
2444        if (mContentParent == null) {
2445            installDecor();
2446        }
2447        return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon));
2448    }
2449
2450    private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) {
2451        if (mCircularProgressBar != null) {
2452            return mCircularProgressBar;
2453        }
2454        if (mContentParent == null && shouldInstallDecor) {
2455            installDecor();
2456        }
2457        mCircularProgressBar = (ProgressBar)findViewById(com.android.internal.R.id.progress_circular);
2458        mCircularProgressBar.setVisibility(View.INVISIBLE);
2459        return mCircularProgressBar;
2460    }
2461
2462    private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) {
2463        if (mHorizontalProgressBar != null) {
2464            return mHorizontalProgressBar;
2465        }
2466        if (mContentParent == null && shouldInstallDecor) {
2467            installDecor();
2468        }
2469        mHorizontalProgressBar = (ProgressBar)findViewById(com.android.internal.R.id.progress_horizontal);
2470        mHorizontalProgressBar.setVisibility(View.INVISIBLE);
2471        return mHorizontalProgressBar;
2472    }
2473
2474    private ImageView getRightIconView() {
2475        if (mRightIconView != null) {
2476            return mRightIconView;
2477        }
2478        if (mContentParent == null) {
2479            installDecor();
2480        }
2481        return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon));
2482    }
2483
2484    /**
2485     * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)}
2486     * callback. This method will grab whatever extra state is needed for the
2487     * callback that isn't given in the parameters. If the panel is not open,
2488     * this will not perform the callback.
2489     *
2490     * @param featureId Feature ID of the panel that was closed. Must be given.
2491     * @param panel Panel that was closed. Optional but useful if there is no
2492     *            menu given.
2493     * @param menu The menu that was closed. Optional, but give if you have.
2494     */
2495    private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) {
2496        final Callback cb = getCallback();
2497        if (cb == null)
2498            return;
2499
2500        // Try to get a menu
2501        if (menu == null) {
2502            // Need a panel to grab the menu, so try to get that
2503            if (panel == null) {
2504                if ((featureId >= 0) && (featureId < mPanels.length)) {
2505                    panel = mPanels[featureId];
2506                }
2507            }
2508
2509            if (panel != null) {
2510                // menu still may be null, which is okay--we tried our best
2511                menu = panel.menu;
2512            }
2513        }
2514
2515        // If the panel is not open, do not callback
2516        if ((panel != null) && (!panel.isOpen))
2517            return;
2518
2519        cb.onPanelClosed(featureId, menu);
2520    }
2521
2522    /**
2523     * Helper method for adding launch-search to most applications. Opens the
2524     * search window using default settings.
2525     *
2526     * @return true if search window opened
2527     */
2528    private boolean launchDefaultSearch() {
2529        final Callback cb = getCallback();
2530        if (cb == null) {
2531            return false;
2532        } else {
2533            sendCloseSystemWindows("search");
2534            return cb.onSearchRequested();
2535        }
2536    }
2537
2538    @Override
2539    public void setVolumeControlStream(int streamType) {
2540        mVolumeControlStreamType = streamType;
2541    }
2542
2543    @Override
2544    public int getVolumeControlStream() {
2545        return mVolumeControlStreamType;
2546    }
2547
2548    private static final class DrawableFeatureState {
2549        DrawableFeatureState(int _featureId) {
2550            featureId = _featureId;
2551        }
2552
2553        final int featureId;
2554
2555        int resid;
2556
2557        Uri uri;
2558
2559        Drawable local;
2560
2561        Drawable child;
2562
2563        Drawable def;
2564
2565        Drawable cur;
2566
2567        int alpha = 255;
2568
2569        int curAlpha = 255;
2570    }
2571
2572    private static final class PanelFeatureState {
2573
2574        /** Feature ID for this panel. */
2575        int featureId;
2576
2577        // Information pulled from the style for this panel.
2578
2579        int background;
2580
2581        /** The background when the panel spans the entire available width. */
2582        int fullBackground;
2583
2584        int gravity;
2585
2586        int x;
2587
2588        int y;
2589
2590        int windowAnimations;
2591
2592        /** Dynamic state of the panel. */
2593        DecorView decorView;
2594
2595        /** The panel that was returned by onCreatePanelView(). */
2596        View createdPanelView;
2597
2598        /** The panel that we are actually showing. */
2599        View shownPanelView;
2600
2601        /** Use {@link #setMenu} to set this. */
2602        Menu menu;
2603
2604        /**
2605         * Whether the panel has been prepared (see
2606         * {@link PhoneWindow#preparePanel}).
2607         */
2608        boolean isPrepared;
2609
2610        /**
2611         * Whether an item's action has been performed. This happens in obvious
2612         * scenarios (user clicks on menu item), but can also happen with
2613         * chording menu+(shortcut key).
2614         */
2615        boolean isHandled;
2616
2617        boolean isOpen;
2618
2619        /**
2620         * True if the menu is in expanded mode, false if the menu is in icon
2621         * mode
2622         */
2623        boolean isInExpandedMode;
2624
2625        public boolean qwertyMode;
2626
2627        boolean refreshDecorView;
2628
2629        boolean wasLastOpen;
2630
2631        boolean wasLastExpanded;
2632
2633        /**
2634         * Contains the state of the menu when told to freeze.
2635         */
2636        Bundle frozenMenuState;
2637
2638        PanelFeatureState(int featureId) {
2639            this.featureId = featureId;
2640
2641            refreshDecorView = false;
2642        }
2643
2644        void setStyle(Context context) {
2645            TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
2646            background = a.getResourceId(
2647                    com.android.internal.R.styleable.Theme_panelBackground, 0);
2648            fullBackground = a.getResourceId(
2649                    com.android.internal.R.styleable.Theme_panelFullBackground, 0);
2650            windowAnimations = a.getResourceId(
2651                    com.android.internal.R.styleable.Theme_windowAnimationStyle, 0);
2652            a.recycle();
2653        }
2654
2655        void setMenu(Menu menu) {
2656            this.menu = menu;
2657
2658            if (frozenMenuState != null) {
2659                ((MenuBuilder) menu).restoreHierarchyState(frozenMenuState);
2660                frozenMenuState = null;
2661            }
2662        }
2663
2664        Parcelable onSaveInstanceState() {
2665            SavedState savedState = new SavedState();
2666            savedState.featureId = featureId;
2667            savedState.isOpen = isOpen;
2668            savedState.isInExpandedMode = isInExpandedMode;
2669
2670            if (menu != null) {
2671                savedState.menuState = new Bundle();
2672                ((MenuBuilder) menu).saveHierarchyState(savedState.menuState);
2673            }
2674
2675            return savedState;
2676        }
2677
2678        void onRestoreInstanceState(Parcelable state) {
2679            SavedState savedState = (SavedState) state;
2680            featureId = savedState.featureId;
2681            wasLastOpen = savedState.isOpen;
2682            wasLastExpanded = savedState.isInExpandedMode;
2683            frozenMenuState = savedState.menuState;
2684
2685            /*
2686             * A LocalActivityManager keeps the same instance of this class around.
2687             * The first time the menu is being shown after restoring, the
2688             * Activity.onCreateOptionsMenu should be called. But, if it is the
2689             * same instance then menu != null and we won't call that method.
2690             * So, clear this.  Also clear any cached views.
2691             */
2692            menu = null;
2693            createdPanelView = null;
2694            shownPanelView = null;
2695            decorView = null;
2696        }
2697
2698        private static class SavedState implements Parcelable {
2699            int featureId;
2700            boolean isOpen;
2701            boolean isInExpandedMode;
2702            Bundle menuState;
2703
2704            public int describeContents() {
2705                return 0;
2706            }
2707
2708            public void writeToParcel(Parcel dest, int flags) {
2709                dest.writeInt(featureId);
2710                dest.writeInt(isOpen ? 1 : 0);
2711                dest.writeInt(isInExpandedMode ? 1 : 0);
2712
2713                if (isOpen) {
2714                    dest.writeBundle(menuState);
2715                }
2716            }
2717
2718            private static SavedState readFromParcel(Parcel source) {
2719                SavedState savedState = new SavedState();
2720                savedState.featureId = source.readInt();
2721                savedState.isOpen = source.readInt() == 1;
2722                savedState.isInExpandedMode = source.readInt() == 1;
2723
2724                if (savedState.isOpen) {
2725                    savedState.menuState = source.readBundle();
2726                }
2727
2728                return savedState;
2729            }
2730
2731            public static final Parcelable.Creator<SavedState> CREATOR
2732                    = new Parcelable.Creator<SavedState>() {
2733                public SavedState createFromParcel(Parcel in) {
2734                    return readFromParcel(in);
2735                }
2736
2737                public SavedState[] newArray(int size) {
2738                    return new SavedState[size];
2739                }
2740            };
2741        }
2742
2743    }
2744
2745    /**
2746     * Simple implementation of MenuBuilder.Callback that:
2747     * <li> Opens a submenu when selected.
2748     * <li> Calls back to the callback's onMenuItemSelected when an item is
2749     * selected.
2750     */
2751    private final class ContextMenuCallback implements MenuBuilder.Callback {
2752        private int mFeatureId;
2753        private MenuDialogHelper mSubMenuHelper;
2754
2755        public ContextMenuCallback(int featureId) {
2756            mFeatureId = featureId;
2757        }
2758
2759        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
2760            if (allMenusAreClosing) {
2761                Callback callback = getCallback();
2762                if (callback != null) callback.onPanelClosed(mFeatureId, menu);
2763
2764                if (menu == mContextMenu) {
2765                    dismissContextMenu();
2766                }
2767
2768                // Dismiss the submenu, if it is showing
2769                if (mSubMenuHelper != null) {
2770                    mSubMenuHelper.dismiss();
2771                    mSubMenuHelper = null;
2772                }
2773            }
2774        }
2775
2776        public void onCloseSubMenu(SubMenuBuilder menu) {
2777            Callback callback = getCallback();
2778            if (callback != null) callback.onPanelClosed(mFeatureId, menu.getRootMenu());
2779        }
2780
2781        public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
2782            Callback callback = getCallback();
2783            return (callback != null) && callback.onMenuItemSelected(mFeatureId, item);
2784        }
2785
2786        public void onMenuModeChange(MenuBuilder menu) {
2787        }
2788
2789        public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
2790            // Set a simple callback for the submenu
2791            subMenu.setCallback(this);
2792
2793            // The window manager will give us a valid window token
2794            mSubMenuHelper = new MenuDialogHelper(subMenu);
2795            mSubMenuHelper.show(null);
2796
2797            return true;
2798        }
2799    }
2800
2801    void sendCloseSystemWindows() {
2802        PhoneWindowManager.sendCloseSystemWindows(getContext(), null);
2803    }
2804
2805    void sendCloseSystemWindows(String reason) {
2806        PhoneWindowManager.sendCloseSystemWindows(getContext(), reason);
2807    }
2808}
2809