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