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