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