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