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