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