PhoneWindow.java revision 1d07e16c9d9ecaaaf8994ad5691c4063ab31f265
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                dispatcher.startTracking(event, this);
1405                return true;
1406            }
1407
1408        }
1409
1410        return false;
1411    }
1412
1413    private KeyguardManager getKeyguardManager() {
1414        if (mKeyguardManager == null) {
1415            mKeyguardManager = (KeyguardManager) getContext().getSystemService(
1416                    Context.KEYGUARD_SERVICE);
1417        }
1418        return mKeyguardManager;
1419    }
1420
1421    AudioManager getAudioManager() {
1422        if (mAudioManager == null) {
1423            mAudioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
1424        }
1425        return mAudioManager;
1426    }
1427
1428    /**
1429     * A key was released and not handled by anything else in the window.
1430     *
1431     * @see #onKeyDown
1432     * @see android.view.KeyEvent
1433     */
1434    protected boolean onKeyUp(int featureId, int keyCode, KeyEvent event) {
1435        final KeyEvent.DispatcherState dispatcher =
1436                mDecor != null ? mDecor.getKeyDispatcherState() : null;
1437        if (dispatcher != null) {
1438            dispatcher.handleUpEvent(event);
1439        }
1440        //Log.i(TAG, "Key up: repeat=" + event.getRepeatCount()
1441        //        + " flags=0x" + Integer.toHexString(event.getFlags()));
1442
1443        switch (keyCode) {
1444            case KeyEvent.KEYCODE_VOLUME_UP:
1445            case KeyEvent.KEYCODE_VOLUME_DOWN:
1446            case KeyEvent.KEYCODE_VOLUME_MUTE: {
1447                // Similar code is in PhoneFallbackEventHandler in case the window
1448                // doesn't have one of these.  In this case, we execute it here and
1449                // eat the event instead, because we have mVolumeControlStreamType
1450                // and they don't.
1451                getAudioManager().handleKeyUp(keyCode, mVolumeControlStreamType);
1452                return true;
1453            }
1454
1455            case KeyEvent.KEYCODE_MENU: {
1456                onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId,
1457                        event);
1458                return true;
1459            }
1460
1461            case KeyEvent.KEYCODE_BACK: {
1462                if (featureId < 0) break;
1463                if (event.isTracking() && !event.isCanceled()) {
1464                    if (featureId == FEATURE_OPTIONS_PANEL) {
1465                        PanelFeatureState st = getPanelState(featureId, false);
1466                        if (st != null && st.isInExpandedMode) {
1467                            // If the user is in an expanded menu and hits back, it
1468                            // should go back to the icon menu
1469                            reopenMenu(true);
1470                            return true;
1471                        }
1472                    }
1473                    closePanel(featureId);
1474                    return true;
1475                }
1476                break;
1477            }
1478
1479            case KeyEvent.KEYCODE_SEARCH: {
1480                /*
1481                 * Do this in onKeyUp since the Search key is also used for
1482                 * chording quick launch shortcuts.
1483                 */
1484                if (getKeyguardManager().inKeyguardRestrictedInputMode()) {
1485                    break;
1486                }
1487                if (event.isTracking() && !event.isCanceled()) {
1488                    launchDefaultSearch();
1489                }
1490                return true;
1491            }
1492        }
1493
1494        return false;
1495    }
1496
1497    @Override
1498    protected void onActive() {
1499    }
1500
1501    @Override
1502    public final View getDecorView() {
1503        if (mDecor == null) {
1504            installDecor();
1505        }
1506        return mDecor;
1507    }
1508
1509    @Override
1510    public final View peekDecorView() {
1511        return mDecor;
1512    }
1513
1514    static private final String FOCUSED_ID_TAG = "android:focusedViewId";
1515    static private final String VIEWS_TAG = "android:views";
1516    static private final String PANELS_TAG = "android:Panels";
1517    static private final String ACTION_BAR_TAG = "android:ActionBar";
1518
1519    /** {@inheritDoc} */
1520    @Override
1521    public Bundle saveHierarchyState() {
1522        Bundle outState = new Bundle();
1523        if (mContentParent == null) {
1524            return outState;
1525        }
1526
1527        SparseArray<Parcelable> states = new SparseArray<Parcelable>();
1528        mContentParent.saveHierarchyState(states);
1529        outState.putSparseParcelableArray(VIEWS_TAG, states);
1530
1531        // save the focused view id
1532        View focusedView = mContentParent.findFocus();
1533        if (focusedView != null) {
1534            if (focusedView.getId() != View.NO_ID) {
1535                outState.putInt(FOCUSED_ID_TAG, focusedView.getId());
1536            } else {
1537                if (false) {
1538                    Log.d(TAG, "couldn't save which view has focus because the focused view "
1539                            + focusedView + " has no id.");
1540                }
1541            }
1542        }
1543
1544        // save the panels
1545        SparseArray<Parcelable> panelStates = new SparseArray<Parcelable>();
1546        savePanelState(panelStates);
1547        if (panelStates.size() > 0) {
1548            outState.putSparseParcelableArray(PANELS_TAG, panelStates);
1549        }
1550
1551        if (mActionBar != null) {
1552            SparseArray<Parcelable> actionBarStates = new SparseArray<Parcelable>();
1553            mActionBar.saveHierarchyState(actionBarStates);
1554            outState.putSparseParcelableArray(ACTION_BAR_TAG, actionBarStates);
1555        }
1556
1557        return outState;
1558    }
1559
1560    /** {@inheritDoc} */
1561    @Override
1562    public void restoreHierarchyState(Bundle savedInstanceState) {
1563        if (mContentParent == null) {
1564            return;
1565        }
1566
1567        SparseArray<Parcelable> savedStates
1568                = savedInstanceState.getSparseParcelableArray(VIEWS_TAG);
1569        if (savedStates != null) {
1570            mContentParent.restoreHierarchyState(savedStates);
1571        }
1572
1573        // restore the focused view
1574        int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID);
1575        if (focusedViewId != View.NO_ID) {
1576            View needsFocus = mContentParent.findViewById(focusedViewId);
1577            if (needsFocus != null) {
1578                needsFocus.requestFocus();
1579            } else {
1580                Log.w(TAG,
1581                        "Previously focused view reported id " + focusedViewId
1582                                + " during save, but can't be found during restore.");
1583            }
1584        }
1585
1586        // restore the panels
1587        SparseArray<Parcelable> panelStates = savedInstanceState.getSparseParcelableArray(PANELS_TAG);
1588        if (panelStates != null) {
1589            restorePanelState(panelStates);
1590        }
1591
1592        if (mActionBar != null) {
1593            SparseArray<Parcelable> actionBarStates =
1594                    savedInstanceState.getSparseParcelableArray(ACTION_BAR_TAG);
1595            mActionBar.restoreHierarchyState(actionBarStates);
1596        }
1597    }
1598
1599    /**
1600     * Invoked when the panels should freeze their state.
1601     *
1602     * @param icicles Save state into this. This is usually indexed by the
1603     *            featureId. This will be given to {@link #restorePanelState} in the
1604     *            future.
1605     */
1606    private void savePanelState(SparseArray<Parcelable> icicles) {
1607        PanelFeatureState[] panels = mPanels;
1608        if (panels == null) {
1609            return;
1610        }
1611
1612        for (int curFeatureId = panels.length - 1; curFeatureId >= 0; curFeatureId--) {
1613            if (panels[curFeatureId] != null) {
1614                icicles.put(curFeatureId, panels[curFeatureId].onSaveInstanceState());
1615            }
1616        }
1617    }
1618
1619    /**
1620     * Invoked when the panels should thaw their state from a previously frozen state.
1621     *
1622     * @param icicles The state saved by {@link #savePanelState} that needs to be thawed.
1623     */
1624    private void restorePanelState(SparseArray<Parcelable> icicles) {
1625        PanelFeatureState st;
1626        for (int curFeatureId = icicles.size() - 1; curFeatureId >= 0; curFeatureId--) {
1627            st = getPanelState(curFeatureId, false /* required */);
1628            if (st == null) {
1629                // The panel must not have been required, and is currently not around, skip it
1630                continue;
1631            }
1632
1633            st.onRestoreInstanceState(icicles.get(curFeatureId));
1634            invalidatePanelMenu(curFeatureId);
1635        }
1636
1637        /*
1638         * Implementation note: call openPanelsAfterRestore later to actually open the
1639         * restored panels.
1640         */
1641    }
1642
1643    /**
1644     * Opens the panels that have had their state restored. This should be
1645     * called sometime after {@link #restorePanelState} when it is safe to add
1646     * to the window manager.
1647     */
1648    private void openPanelsAfterRestore() {
1649        PanelFeatureState[] panels = mPanels;
1650
1651        if (panels == null) {
1652            return;
1653        }
1654
1655        PanelFeatureState st;
1656        for (int i = panels.length - 1; i >= 0; i--) {
1657            st = panels[i];
1658            // We restore the panel if it was last open; we skip it if it
1659            // now is open, to avoid a race condition if the user immediately
1660            // opens it when we are resuming.
1661            if (st != null) {
1662                st.applyFrozenState();
1663                if (!st.isOpen && st.wasLastOpen) {
1664                    st.isInExpandedMode = st.wasLastExpanded;
1665                    openPanel(st, null);
1666                }
1667            }
1668        }
1669    }
1670
1671    private class PanelMenuPresenterCallback implements MenuPresenter.Callback {
1672        @Override
1673        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
1674            final Menu parentMenu = menu.getRootMenu();
1675            final boolean isSubMenu = parentMenu != menu;
1676            final PanelFeatureState panel = findMenuPanel(isSubMenu ? parentMenu : menu);
1677            if (panel != null) {
1678                if (isSubMenu) {
1679                    callOnPanelClosed(panel.featureId, panel, parentMenu);
1680                    closePanel(panel, true);
1681                } else {
1682                    // Close the panel and only do the callback if the menu is being
1683                    // closed completely, not if opening a sub menu
1684                    closePanel(panel, allMenusAreClosing);
1685                }
1686            }
1687        }
1688
1689        @Override
1690        public boolean onOpenSubMenu(MenuBuilder subMenu) {
1691            if (subMenu == null && hasFeature(FEATURE_ACTION_BAR)) {
1692                Callback cb = getCallback();
1693                if (cb != null && !isDestroyed()) {
1694                    cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
1695                }
1696            }
1697
1698            return true;
1699        }
1700    }
1701
1702    private final class ActionMenuPresenterCallback implements MenuPresenter.Callback {
1703        @Override
1704        public boolean onOpenSubMenu(MenuBuilder subMenu) {
1705            Callback cb = getCallback();
1706            if (cb != null) {
1707                cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
1708                return true;
1709            }
1710            return false;
1711        }
1712
1713        @Override
1714        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
1715            checkCloseActionMenu(menu);
1716        }
1717    }
1718
1719    private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
1720        /* package */int mDefaultOpacity = PixelFormat.OPAQUE;
1721
1722        /** The feature ID of the panel, or -1 if this is the application's DecorView */
1723        private final int mFeatureId;
1724
1725        private final Rect mDrawingBounds = new Rect();
1726
1727        private final Rect mBackgroundPadding = new Rect();
1728
1729        private final Rect mFramePadding = new Rect();
1730
1731        private final Rect mFrameOffsets = new Rect();
1732
1733        private boolean mChanging;
1734
1735        private Drawable mMenuBackground;
1736        private boolean mWatchingForMenu;
1737        private int mDownY;
1738
1739        private ActionMode mActionMode;
1740        private ActionBarContextView mActionModeView;
1741        private PopupWindow mActionModePopup;
1742        private Runnable mShowActionModePopup;
1743
1744        public DecorView(Context context, int featureId) {
1745            super(context);
1746            mFeatureId = featureId;
1747        }
1748
1749        @Override
1750        public boolean dispatchKeyEvent(KeyEvent event) {
1751            final int keyCode = event.getKeyCode();
1752            final int action = event.getAction();
1753            final boolean isDown = action == KeyEvent.ACTION_DOWN;
1754
1755            if (isDown && (event.getRepeatCount() == 0)) {
1756                // First handle chording of panel key: if a panel key is held
1757                // but not released, try to execute a shortcut in it.
1758                if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) {
1759                    boolean handled = dispatchKeyShortcutEvent(event);
1760                    if (handled) {
1761                        return true;
1762                    }
1763                }
1764
1765                // If a panel is open, perform a shortcut on it without the
1766                // chorded panel key
1767                if ((mPreparedPanel != null) && mPreparedPanel.isOpen) {
1768                    if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) {
1769                        return true;
1770                    }
1771                }
1772            }
1773
1774            if (!isDestroyed()) {
1775                final Callback cb = getCallback();
1776                final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event)
1777                        : super.dispatchKeyEvent(event);
1778                if (handled) {
1779                    return true;
1780                }
1781            }
1782
1783            return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event)
1784                    : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event);
1785        }
1786
1787        @Override
1788        public boolean dispatchKeyShortcutEvent(KeyEvent ev) {
1789            // Perform the shortcut (mPreparedPanel can be null since
1790            // global shortcuts (such as search) don't rely on a
1791            // prepared panel or menu).
1792            boolean handled = performPanelShortcut(mPreparedPanel, ev.getKeyCode(), ev,
1793                    Menu.FLAG_PERFORM_NO_CLOSE);
1794            if (handled) {
1795                if (mPreparedPanel != null) {
1796                    mPreparedPanel.isHandled = true;
1797                }
1798                return true;
1799            }
1800
1801            // Shortcut not handled by the panel.  Dispatch to the view hierarchy.
1802            final Callback cb = getCallback();
1803            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchKeyShortcutEvent(ev)
1804                    : super.dispatchKeyShortcutEvent(ev);
1805        }
1806
1807        @Override
1808        public boolean dispatchTouchEvent(MotionEvent ev) {
1809            final Callback cb = getCallback();
1810            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
1811                    : super.dispatchTouchEvent(ev);
1812        }
1813
1814        @Override
1815        public boolean dispatchTrackballEvent(MotionEvent ev) {
1816            final Callback cb = getCallback();
1817            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev)
1818                    : super.dispatchTrackballEvent(ev);
1819        }
1820
1821        @Override
1822        public boolean dispatchGenericMotionEvent(MotionEvent ev) {
1823            final Callback cb = getCallback();
1824            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchGenericMotionEvent(ev)
1825                    : super.dispatchGenericMotionEvent(ev);
1826        }
1827
1828        public boolean superDispatchKeyEvent(KeyEvent event) {
1829            if (super.dispatchKeyEvent(event)) {
1830                return true;
1831            }
1832
1833            // Not handled by the view hierarchy, does the action bar want it
1834            // to cancel out of something special?
1835            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
1836                final int action = event.getAction();
1837                // Back cancels action modes first.
1838                if (mActionMode != null) {
1839                    if (action == KeyEvent.ACTION_UP) {
1840                        mActionMode.finish();
1841                    }
1842                    return true;
1843                }
1844
1845                // Next collapse any expanded action views.
1846                if (mActionBar != null && mActionBar.hasExpandedActionView()) {
1847                    if (action == KeyEvent.ACTION_UP) {
1848                        mActionBar.collapseActionView();
1849                    }
1850                    return true;
1851                }
1852            }
1853
1854            return false;
1855        }
1856
1857        public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
1858            return super.dispatchKeyShortcutEvent(event);
1859        }
1860
1861        public boolean superDispatchTouchEvent(MotionEvent event) {
1862            return super.dispatchTouchEvent(event);
1863        }
1864
1865        public boolean superDispatchTrackballEvent(MotionEvent event) {
1866            return super.dispatchTrackballEvent(event);
1867        }
1868
1869        public boolean superDispatchGenericMotionEvent(MotionEvent event) {
1870            return super.dispatchGenericMotionEvent(event);
1871        }
1872
1873        @Override
1874        public boolean onTouchEvent(MotionEvent event) {
1875            return onInterceptTouchEvent(event);
1876        }
1877
1878        private boolean isOutOfBounds(int x, int y) {
1879            return x < -5 || y < -5 || x > (getWidth() + 5)
1880                    || y > (getHeight() + 5);
1881        }
1882
1883        @Override
1884        public boolean onInterceptTouchEvent(MotionEvent event) {
1885            int action = event.getAction();
1886            if (mFeatureId >= 0) {
1887                if (action == MotionEvent.ACTION_DOWN) {
1888                    int x = (int)event.getX();
1889                    int y = (int)event.getY();
1890                    if (isOutOfBounds(x, y)) {
1891                        closePanel(mFeatureId);
1892                        return true;
1893                    }
1894                }
1895            }
1896
1897            if (!SWEEP_OPEN_MENU) {
1898                return false;
1899            }
1900
1901            if (mFeatureId >= 0) {
1902                if (action == MotionEvent.ACTION_DOWN) {
1903                    Log.i(TAG, "Watchiing!");
1904                    mWatchingForMenu = true;
1905                    mDownY = (int) event.getY();
1906                    return false;
1907                }
1908
1909                if (!mWatchingForMenu) {
1910                    return false;
1911                }
1912
1913                int y = (int)event.getY();
1914                if (action == MotionEvent.ACTION_MOVE) {
1915                    if (y > (mDownY+30)) {
1916                        Log.i(TAG, "Closing!");
1917                        closePanel(mFeatureId);
1918                        mWatchingForMenu = false;
1919                        return true;
1920                    }
1921                } else if (action == MotionEvent.ACTION_UP) {
1922                    mWatchingForMenu = false;
1923                }
1924
1925                return false;
1926            }
1927
1928            //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY()
1929            //        + " (in " + getHeight() + ")");
1930
1931            if (action == MotionEvent.ACTION_DOWN) {
1932                int y = (int)event.getY();
1933                if (y >= (getHeight()-5) && !hasChildren()) {
1934                    Log.i(TAG, "Watchiing!");
1935                    mWatchingForMenu = true;
1936                }
1937                return false;
1938            }
1939
1940            if (!mWatchingForMenu) {
1941                return false;
1942            }
1943
1944            int y = (int)event.getY();
1945            if (action == MotionEvent.ACTION_MOVE) {
1946                if (y < (getHeight()-30)) {
1947                    Log.i(TAG, "Opening!");
1948                    openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent(
1949                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU));
1950                    mWatchingForMenu = false;
1951                    return true;
1952                }
1953            } else if (action == MotionEvent.ACTION_UP) {
1954                mWatchingForMenu = false;
1955            }
1956
1957            return false;
1958        }
1959
1960        @Override
1961        public void sendAccessibilityEvent(int eventType) {
1962            if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
1963                return;
1964            }
1965
1966            // if we are showing a feature that should be announced and one child
1967            // make this child the event source since this is the feature itself
1968            // otherwise the callback will take over and announce its client
1969            if ((mFeatureId == FEATURE_OPTIONS_PANEL ||
1970                    mFeatureId == FEATURE_CONTEXT_MENU ||
1971                    mFeatureId == FEATURE_PROGRESS ||
1972                    mFeatureId == FEATURE_INDETERMINATE_PROGRESS)
1973                    && getChildCount() == 1) {
1974                getChildAt(0).sendAccessibilityEvent(eventType);
1975            } else {
1976                super.sendAccessibilityEvent(eventType);
1977            }
1978        }
1979
1980        @Override
1981        public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1982            final Callback cb = getCallback();
1983            if (cb != null && !isDestroyed()) {
1984                if (cb.dispatchPopulateAccessibilityEvent(event)) {
1985                    return true;
1986                }
1987            }
1988            return super.dispatchPopulateAccessibilityEvent(event);
1989        }
1990
1991        @Override
1992        protected boolean setFrame(int l, int t, int r, int b) {
1993            boolean changed = super.setFrame(l, t, r, b);
1994            if (changed) {
1995                final Rect drawingBounds = mDrawingBounds;
1996                getDrawingRect(drawingBounds);
1997
1998                Drawable fg = getForeground();
1999                if (fg != null) {
2000                    final Rect frameOffsets = mFrameOffsets;
2001                    drawingBounds.left += frameOffsets.left;
2002                    drawingBounds.top += frameOffsets.top;
2003                    drawingBounds.right -= frameOffsets.right;
2004                    drawingBounds.bottom -= frameOffsets.bottom;
2005                    fg.setBounds(drawingBounds);
2006                    final Rect framePadding = mFramePadding;
2007                    drawingBounds.left += framePadding.left - frameOffsets.left;
2008                    drawingBounds.top += framePadding.top - frameOffsets.top;
2009                    drawingBounds.right -= framePadding.right - frameOffsets.right;
2010                    drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom;
2011                }
2012
2013                Drawable bg = getBackground();
2014                if (bg != null) {
2015                    bg.setBounds(drawingBounds);
2016                }
2017
2018                if (SWEEP_OPEN_MENU) {
2019                    if (mMenuBackground == null && mFeatureId < 0
2020                            && getAttributes().height
2021                            == WindowManager.LayoutParams.MATCH_PARENT) {
2022                        mMenuBackground = getContext().getResources().getDrawable(
2023                                com.android.internal.R.drawable.menu_background);
2024                    }
2025                    if (mMenuBackground != null) {
2026                        mMenuBackground.setBounds(drawingBounds.left,
2027                                drawingBounds.bottom-6, drawingBounds.right,
2028                                drawingBounds.bottom+20);
2029                    }
2030                }
2031            }
2032            return changed;
2033        }
2034
2035        @Override
2036        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2037            final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
2038            final boolean isPortrait = metrics.widthPixels < metrics.heightPixels;
2039
2040            final int widthMode = getMode(widthMeasureSpec);
2041
2042            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
2043
2044            int width = getMeasuredWidth();
2045            boolean measure = false;
2046
2047            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY);
2048
2049            final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor;
2050
2051            if (widthMode == AT_MOST && tv.type != TypedValue.TYPE_NULL) {
2052                final int min;
2053                if (tv.type == TypedValue.TYPE_DIMENSION) {
2054                    min = (int)tv.getDimension(metrics);
2055                } else if (tv.type == TypedValue.TYPE_FRACTION) {
2056                    min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels);
2057                } else {
2058                    min = 0;
2059                }
2060
2061                if (width < min) {
2062                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY);
2063                    measure = true;
2064                }
2065            }
2066
2067            // TODO: Support height?
2068
2069            if (measure) {
2070                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
2071            }
2072        }
2073
2074        @Override
2075        public void draw(Canvas canvas) {
2076            super.draw(canvas);
2077
2078            if (mMenuBackground != null) {
2079                mMenuBackground.draw(canvas);
2080            }
2081        }
2082
2083
2084        @Override
2085        public boolean showContextMenuForChild(View originalView) {
2086            // Reuse the context menu builder
2087            if (mContextMenu == null) {
2088                mContextMenu = new ContextMenuBuilder(getContext());
2089                mContextMenu.setCallback(mContextMenuCallback);
2090            } else {
2091                mContextMenu.clearAll();
2092            }
2093
2094            final MenuDialogHelper helper = mContextMenu.show(originalView,
2095                    originalView.getWindowToken());
2096            if (helper != null) {
2097                helper.setPresenterCallback(mContextMenuCallback);
2098            }
2099            mContextMenuHelper = helper;
2100            return helper != null;
2101        }
2102
2103        @Override
2104        public ActionMode startActionModeForChild(View originalView,
2105                ActionMode.Callback callback) {
2106            // originalView can be used here to be sure that we don't obscure
2107            // relevant content with the context mode UI.
2108            return startActionMode(callback);
2109        }
2110
2111        @Override
2112        public ActionMode startActionMode(ActionMode.Callback callback) {
2113            if (mActionMode != null) {
2114                mActionMode.finish();
2115            }
2116
2117            final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback);
2118            ActionMode mode = null;
2119            if (getCallback() != null && !isDestroyed()) {
2120                try {
2121                    mode = getCallback().onWindowStartingActionMode(wrappedCallback);
2122                } catch (AbstractMethodError ame) {
2123                    // Older apps might not implement this callback method.
2124                }
2125            }
2126            if (mode != null) {
2127                mActionMode = mode;
2128            } else {
2129                if (mActionModeView == null) {
2130                    if (hasFeature(FEATURE_ACTION_MODE_OVERLAY)) {
2131                        mActionModeView = new ActionBarContextView(mContext);
2132                        mActionModePopup = new PopupWindow(mContext, null,
2133                                com.android.internal.R.attr.actionModePopupWindowStyle);
2134                        mActionModePopup.setLayoutInScreenEnabled(true);
2135                        mActionModePopup.setLayoutInsetDecor(true);
2136                        mActionModePopup.setClippingEnabled(false);
2137                        mActionModePopup.setContentView(mActionModeView);
2138                        mActionModePopup.setWidth(MATCH_PARENT);
2139
2140                        TypedValue heightValue = new TypedValue();
2141                        mContext.getTheme().resolveAttribute(
2142                                com.android.internal.R.attr.actionBarSize, heightValue, true);
2143                        final int height = TypedValue.complexToDimensionPixelSize(heightValue.data,
2144                                mContext.getResources().getDisplayMetrics());
2145                        mActionModePopup.setHeight(height);
2146                        mShowActionModePopup = new Runnable() {
2147                            public void run() {
2148                                mActionModePopup.showAtLocation(PhoneWindow.DecorView.this,
2149                                        Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
2150                            }
2151                        };
2152                    } else {
2153                        ViewStub stub = (ViewStub) findViewById(
2154                                com.android.internal.R.id.action_mode_bar_stub);
2155                        if (stub != null) {
2156                            mActionModeView = (ActionBarContextView) stub.inflate();
2157                        }
2158                    }
2159                }
2160
2161                if (mActionModeView != null) {
2162                    mActionModeView.killMode();
2163                    mode = new StandaloneActionMode(getContext(), mActionModeView, wrappedCallback);
2164                    if (callback.onCreateActionMode(mode, mode.getMenu())) {
2165                        mode.invalidate();
2166                        mActionModeView.initForMode(mode);
2167                        mActionModeView.setVisibility(View.VISIBLE);
2168                        mActionMode = mode;
2169                        if (mActionModePopup != null) {
2170                            post(mShowActionModePopup);
2171                        }
2172                    } else {
2173                        mActionMode = null;
2174                    }
2175                }
2176            }
2177            if (mActionMode != null && getCallback() != null && !isDestroyed()) {
2178                try {
2179                    getCallback().onActionModeStarted(mActionMode);
2180                } catch (AbstractMethodError ame) {
2181                    // Older apps might not implement this callback method.
2182                }
2183            }
2184            return mActionMode;
2185        }
2186
2187        public void startChanging() {
2188            mChanging = true;
2189        }
2190
2191        public void finishChanging() {
2192            mChanging = false;
2193            drawableChanged();
2194        }
2195
2196        public void setWindowBackground(Drawable drawable) {
2197            if (getBackground() != drawable) {
2198                setBackgroundDrawable(drawable);
2199                if (drawable != null) {
2200                    drawable.getPadding(mBackgroundPadding);
2201                } else {
2202                    mBackgroundPadding.setEmpty();
2203                }
2204                drawableChanged();
2205            }
2206        }
2207
2208        @Override
2209        public void setBackgroundDrawable(Drawable d) {
2210            super.setBackgroundDrawable(d);
2211            if (getWindowToken() != null) {
2212                updateWindowResizeState();
2213            }
2214        }
2215
2216        public void setWindowFrame(Drawable drawable) {
2217            if (getForeground() != drawable) {
2218                setForeground(drawable);
2219                if (drawable != null) {
2220                    drawable.getPadding(mFramePadding);
2221                } else {
2222                    mFramePadding.setEmpty();
2223                }
2224                drawableChanged();
2225            }
2226        }
2227
2228        @Override
2229        protected boolean fitSystemWindows(Rect insets) {
2230            mFrameOffsets.set(insets);
2231            if (getForeground() != null) {
2232                drawableChanged();
2233            }
2234            return super.fitSystemWindows(insets);
2235        }
2236
2237        private void drawableChanged() {
2238            if (mChanging) {
2239                return;
2240            }
2241
2242            setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top
2243                    + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right,
2244                    mFramePadding.bottom + mBackgroundPadding.bottom);
2245            requestLayout();
2246            invalidate();
2247
2248            int opacity = PixelFormat.OPAQUE;
2249
2250            // Note: if there is no background, we will assume opaque. The
2251            // common case seems to be that an application sets there to be
2252            // no background so it can draw everything itself. For that,
2253            // we would like to assume OPAQUE and let the app force it to
2254            // the slower TRANSLUCENT mode if that is really what it wants.
2255            Drawable bg = getBackground();
2256            Drawable fg = getForeground();
2257            if (bg != null) {
2258                if (fg == null) {
2259                    opacity = bg.getOpacity();
2260                } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0
2261                        && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) {
2262                    // If the frame padding is zero, then we can be opaque
2263                    // if either the frame -or- the background is opaque.
2264                    int fop = fg.getOpacity();
2265                    int bop = bg.getOpacity();
2266                    if (false)
2267                        Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop);
2268                    if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) {
2269                        opacity = PixelFormat.OPAQUE;
2270                    } else if (fop == PixelFormat.UNKNOWN) {
2271                        opacity = bop;
2272                    } else if (bop == PixelFormat.UNKNOWN) {
2273                        opacity = fop;
2274                    } else {
2275                        opacity = Drawable.resolveOpacity(fop, bop);
2276                    }
2277                } else {
2278                    // For now we have to assume translucent if there is a
2279                    // frame with padding... there is no way to tell if the
2280                    // frame and background together will draw all pixels.
2281                    if (false)
2282                        Log.v(TAG, "Padding: " + mFramePadding);
2283                    opacity = PixelFormat.TRANSLUCENT;
2284                }
2285            }
2286
2287            if (false)
2288                Log.v(TAG, "Background: " + bg + ", Frame: " + fg);
2289            if (false)
2290                Log.v(TAG, "Selected default opacity: " + opacity);
2291
2292            mDefaultOpacity = opacity;
2293            if (mFeatureId < 0) {
2294                setDefaultWindowFormat(opacity);
2295            }
2296        }
2297
2298        @Override
2299        public void onWindowFocusChanged(boolean hasWindowFocus) {
2300            super.onWindowFocusChanged(hasWindowFocus);
2301
2302            // If the user is chording a menu shortcut, release the chord since
2303            // this window lost focus
2304            if (!hasWindowFocus && mPanelChordingKey != 0) {
2305                closePanel(FEATURE_OPTIONS_PANEL);
2306            }
2307
2308            final Callback cb = getCallback();
2309            if (cb != null && !isDestroyed() && mFeatureId < 0) {
2310                cb.onWindowFocusChanged(hasWindowFocus);
2311            }
2312        }
2313
2314        void updateWindowResizeState() {
2315            Drawable bg = getBackground();
2316            hackTurnOffWindowResizeAnim(bg == null || bg.getOpacity()
2317                    != PixelFormat.OPAQUE);
2318        }
2319
2320        @Override
2321        protected void onAttachedToWindow() {
2322            super.onAttachedToWindow();
2323
2324            updateWindowResizeState();
2325
2326            final Callback cb = getCallback();
2327            if (cb != null && !isDestroyed() && mFeatureId < 0) {
2328                cb.onAttachedToWindow();
2329            }
2330
2331            if (mFeatureId == -1) {
2332                /*
2333                 * The main window has been attached, try to restore any panels
2334                 * that may have been open before. This is called in cases where
2335                 * an activity is being killed for configuration change and the
2336                 * menu was open. When the activity is recreated, the menu
2337                 * should be shown again.
2338                 */
2339                openPanelsAfterRestore();
2340            }
2341        }
2342
2343        @Override
2344        protected void onDetachedFromWindow() {
2345            super.onDetachedFromWindow();
2346
2347            final Callback cb = getCallback();
2348            if (cb != null && mFeatureId < 0) {
2349                cb.onDetachedFromWindow();
2350            }
2351
2352            if (mActionBar != null) {
2353                mActionBar.dismissPopupMenus();
2354            }
2355
2356            if (mActionModePopup != null) {
2357                removeCallbacks(mShowActionModePopup);
2358                if (mActionModePopup.isShowing()) {
2359                    mActionModePopup.dismiss();
2360                }
2361                mActionModePopup = null;
2362            }
2363
2364            PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
2365            if (st != null && st.menu != null && mFeatureId < 0) {
2366                st.menu.close();
2367            }
2368        }
2369
2370        @Override
2371        public void onCloseSystemDialogs(String reason) {
2372            if (mFeatureId >= 0) {
2373                closeAllPanels();
2374            }
2375        }
2376
2377        public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() {
2378            return mFeatureId < 0 ? mTakeSurfaceCallback : null;
2379        }
2380
2381        public InputQueue.Callback willYouTakeTheInputQueue() {
2382            return mFeatureId < 0 ? mTakeInputQueueCallback : null;
2383        }
2384
2385        public void setSurfaceType(int type) {
2386            PhoneWindow.this.setType(type);
2387        }
2388
2389        public void setSurfaceFormat(int format) {
2390            PhoneWindow.this.setFormat(format);
2391        }
2392
2393        public void setSurfaceKeepScreenOn(boolean keepOn) {
2394            if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2395            else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2396        }
2397
2398        /**
2399         * Clears out internal reference when the action mode is destroyed.
2400         */
2401        private class ActionModeCallbackWrapper implements ActionMode.Callback {
2402            private ActionMode.Callback mWrapped;
2403
2404            public ActionModeCallbackWrapper(ActionMode.Callback wrapped) {
2405                mWrapped = wrapped;
2406            }
2407
2408            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2409                return mWrapped.onCreateActionMode(mode, menu);
2410            }
2411
2412            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2413                return mWrapped.onPrepareActionMode(mode, menu);
2414            }
2415
2416            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2417                return mWrapped.onActionItemClicked(mode, item);
2418            }
2419
2420            public void onDestroyActionMode(ActionMode mode) {
2421                mWrapped.onDestroyActionMode(mode);
2422                if (mActionModePopup != null) {
2423                    removeCallbacks(mShowActionModePopup);
2424                    mActionModePopup.dismiss();
2425                } else if (mActionModeView != null) {
2426                    mActionModeView.setVisibility(GONE);
2427                }
2428                if (mActionModeView != null) {
2429                    mActionModeView.removeAllViews();
2430                }
2431                if (getCallback() != null && !isDestroyed()) {
2432                    try {
2433                        getCallback().onActionModeFinished(mActionMode);
2434                    } catch (AbstractMethodError ame) {
2435                        // Older apps might not implement this callback method.
2436                    }
2437                }
2438                mActionMode = null;
2439            }
2440        }
2441    }
2442
2443    protected DecorView generateDecor() {
2444        return new DecorView(getContext(), -1);
2445    }
2446
2447    protected void setFeatureFromAttrs(int featureId, TypedArray attrs,
2448            int drawableAttr, int alphaAttr) {
2449        Drawable d = attrs.getDrawable(drawableAttr);
2450        if (d != null) {
2451            requestFeature(featureId);
2452            setFeatureDefaultDrawable(featureId, d);
2453        }
2454        if ((getFeatures() & (1 << featureId)) != 0) {
2455            int alpha = attrs.getInt(alphaAttr, -1);
2456            if (alpha >= 0) {
2457                setFeatureDrawableAlpha(featureId, alpha);
2458            }
2459        }
2460    }
2461
2462    protected ViewGroup generateLayout(DecorView decor) {
2463        // Apply data from current theme.
2464
2465        TypedArray a = getWindowStyle();
2466
2467        if (false) {
2468            System.out.println("From style:");
2469            String s = "Attrs:";
2470            for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) {
2471                s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "="
2472                        + a.getString(i);
2473            }
2474            System.out.println(s);
2475        }
2476
2477        mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
2478        int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
2479                & (~getForcedWindowFlags());
2480        if (mIsFloating) {
2481            setLayout(WRAP_CONTENT, WRAP_CONTENT);
2482            setFlags(0, flagsToUpdate);
2483        } else {
2484            setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
2485        }
2486
2487        if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
2488            requestFeature(FEATURE_NO_TITLE);
2489        } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) {
2490            // Don't allow an action bar if there is no title.
2491            requestFeature(FEATURE_ACTION_BAR);
2492        }
2493
2494        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) {
2495            requestFeature(FEATURE_ACTION_BAR_OVERLAY);
2496        }
2497
2498        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) {
2499            requestFeature(FEATURE_ACTION_MODE_OVERLAY);
2500        }
2501
2502        if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
2503            setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags()));
2504        }
2505
2506        if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) {
2507            setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
2508        }
2509
2510        if (a.getBoolean(com.android.internal.R.styleable.Window_windowEnableSplitTouch,
2511                getContext().getApplicationInfo().targetSdkVersion
2512                        >= android.os.Build.VERSION_CODES.HONEYCOMB)) {
2513            setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags()));
2514        }
2515
2516        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMajor, mMinWidthMajor);
2517        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMinor, mMinWidthMinor);
2518
2519        final Context context = getContext();
2520        final int targetSdk = context.getApplicationInfo().targetSdkVersion;
2521        final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
2522        final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
2523        final boolean targetHcNeedsOptions = context.getResources().getBoolean(
2524                com.android.internal.R.bool.target_honeycomb_needs_options_menu);
2525        final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);
2526
2527        if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
2528            addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY);
2529        }
2530
2531        if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion
2532                >= android.os.Build.VERSION_CODES.HONEYCOMB) {
2533            if (a.getBoolean(
2534                    com.android.internal.R.styleable.Window_windowCloseOnTouchOutside,
2535                    false)) {
2536                setCloseOnTouchOutsideIfNotSet(true);
2537            }
2538        }
2539
2540        WindowManager.LayoutParams params = getAttributes();
2541
2542        if (!hasSoftInputMode()) {
2543            params.softInputMode = a.getInt(
2544                    com.android.internal.R.styleable.Window_windowSoftInputMode,
2545                    params.softInputMode);
2546        }
2547
2548        if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled,
2549                mIsFloating)) {
2550            /* All dialogs should have the window dimmed */
2551            if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
2552                params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
2553            }
2554            if (!haveDimAmount()) {
2555                params.dimAmount = a.getFloat(
2556                        android.R.styleable.Window_backgroundDimAmount, 0.5f);
2557            }
2558        }
2559
2560        if (params.windowAnimations == 0) {
2561            params.windowAnimations = a.getResourceId(
2562                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2563        }
2564
2565        // The rest are only done if this window is not embedded; otherwise,
2566        // the values are inherited from our container.
2567        if (getContainer() == null) {
2568            if (mBackgroundDrawable == null) {
2569                if (mBackgroundResource == 0) {
2570                    mBackgroundResource = a.getResourceId(
2571                            com.android.internal.R.styleable.Window_windowBackground, 0);
2572                }
2573                if (mFrameResource == 0) {
2574                    mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0);
2575                }
2576                if (false) {
2577                    System.out.println("Background: "
2578                            + Integer.toHexString(mBackgroundResource) + " Frame: "
2579                            + Integer.toHexString(mFrameResource));
2580                }
2581            }
2582            mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000);
2583        }
2584
2585        // Inflate the window decor.
2586
2587        int layoutResource;
2588        int features = getLocalFeatures();
2589        // System.out.println("Features: 0x" + Integer.toHexString(features));
2590        if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
2591            if (mIsFloating) {
2592                TypedValue res = new TypedValue();
2593                getContext().getTheme().resolveAttribute(
2594                        com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true);
2595                layoutResource = res.resourceId;
2596            } else {
2597                layoutResource = com.android.internal.R.layout.screen_title_icons;
2598            }
2599            // XXX Remove this once action bar supports these features.
2600            removeFeature(FEATURE_ACTION_BAR);
2601            // System.out.println("Title Icons!");
2602        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
2603                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
2604            // Special case for a window with only a progress bar (and title).
2605            // XXX Need to have a no-title version of embedded windows.
2606            layoutResource = com.android.internal.R.layout.screen_progress;
2607            // System.out.println("Progress!");
2608        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
2609            // Special case for a window with a custom title.
2610            // If the window is floating, we need a dialog layout
2611            if (mIsFloating) {
2612                TypedValue res = new TypedValue();
2613                getContext().getTheme().resolveAttribute(
2614                        com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true);
2615                layoutResource = res.resourceId;
2616            } else {
2617                layoutResource = com.android.internal.R.layout.screen_custom_title;
2618            }
2619            // XXX Remove this once action bar supports these features.
2620            removeFeature(FEATURE_ACTION_BAR);
2621        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
2622            // If no other features and not embedded, only need a title.
2623            // If the window is floating, we need a dialog layout
2624            if (mIsFloating) {
2625                TypedValue res = new TypedValue();
2626                getContext().getTheme().resolveAttribute(
2627                        com.android.internal.R.attr.dialogTitleDecorLayout, res, true);
2628                layoutResource = res.resourceId;
2629            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
2630                if ((features & (1 << FEATURE_ACTION_BAR_OVERLAY)) != 0) {
2631                    layoutResource = com.android.internal.R.layout.screen_action_bar_overlay;
2632                } else {
2633                    layoutResource = com.android.internal.R.layout.screen_action_bar;
2634                }
2635            } else {
2636                layoutResource = com.android.internal.R.layout.screen_title;
2637            }
2638            // System.out.println("Title!");
2639        } else {
2640            // Embedded, so no decoration is needed.
2641            layoutResource = com.android.internal.R.layout.screen_simple;
2642            // System.out.println("Simple!");
2643        }
2644
2645        mDecor.startChanging();
2646
2647        View in = mLayoutInflater.inflate(layoutResource, null);
2648        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
2649
2650        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
2651        if (contentParent == null) {
2652            throw new RuntimeException("Window couldn't find content container view");
2653        }
2654
2655        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2656            ProgressBar progress = getCircularProgressBar(false);
2657            if (progress != null) {
2658                progress.setIndeterminate(true);
2659            }
2660        }
2661
2662        // Remaining setup -- of background and title -- that only applies
2663        // to top-level windows.
2664        if (getContainer() == null) {
2665            Drawable drawable = mBackgroundDrawable;
2666            if (mBackgroundResource != 0) {
2667                drawable = getContext().getResources().getDrawable(mBackgroundResource);
2668            }
2669            mDecor.setWindowBackground(drawable);
2670            drawable = null;
2671            if (mFrameResource != 0) {
2672                drawable = getContext().getResources().getDrawable(mFrameResource);
2673            }
2674            mDecor.setWindowFrame(drawable);
2675
2676            // System.out.println("Text=" + Integer.toHexString(mTextColor) +
2677            // " Sel=" + Integer.toHexString(mTextSelectedColor) +
2678            // " Title=" + Integer.toHexString(mTitleColor));
2679
2680            if (mTitleColor == 0) {
2681                mTitleColor = mTextColor;
2682            }
2683
2684            if (mTitle != null) {
2685                setTitle(mTitle);
2686            }
2687            setTitleColor(mTitleColor);
2688        }
2689
2690        mDecor.finishChanging();
2691
2692        return contentParent;
2693    }
2694
2695    /** @hide */
2696    public void alwaysReadCloseOnTouchAttr() {
2697        mAlwaysReadCloseOnTouchAttr = true;
2698    }
2699
2700    private void installDecor() {
2701        if (mDecor == null) {
2702            mDecor = generateDecor();
2703            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
2704            mDecor.setIsRootNamespace(true);
2705        }
2706        if (mContentParent == null) {
2707            mContentParent = generateLayout(mDecor);
2708
2709            mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
2710            if (mTitleView != null) {
2711                if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
2712                    View titleContainer = findViewById(com.android.internal.R.id.title_container);
2713                    if (titleContainer != null) {
2714                        titleContainer.setVisibility(View.GONE);
2715                    } else {
2716                        mTitleView.setVisibility(View.GONE);
2717                    }
2718                    if (mContentParent instanceof FrameLayout) {
2719                        ((FrameLayout)mContentParent).setForeground(null);
2720                    }
2721                } else {
2722                    mTitleView.setText(mTitle);
2723                }
2724            } else {
2725                mActionBar = (ActionBarView) findViewById(com.android.internal.R.id.action_bar);
2726                if (mActionBar != null) {
2727                    if (mActionBar.getTitle() == null) {
2728                        mActionBar.setWindowTitle(mTitle);
2729                    }
2730                    final int localFeatures = getLocalFeatures();
2731                    if ((localFeatures & (1 << FEATURE_PROGRESS)) != 0) {
2732                        mActionBar.initProgress();
2733                    }
2734                    if ((localFeatures & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2735                        mActionBar.initIndeterminateProgress();
2736                    }
2737
2738                    boolean splitActionBar = false;
2739                    if ((mUiOptions & ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW) != 0) {
2740                        splitActionBar = getContext().getResources().getBoolean(
2741                                com.android.internal.R.bool.split_action_bar_is_narrow);
2742                    } else {
2743                        splitActionBar = getWindowStyle().getBoolean(
2744                                com.android.internal.R.styleable.Window_windowSplitActionBar, false);
2745                    }
2746                    if (splitActionBar) {
2747                        final ActionBarContainer splitView = (ActionBarContainer) findViewById(
2748                                com.android.internal.R.id.split_action_bar);
2749                        if (splitView != null) {
2750                            splitView.setVisibility(View.VISIBLE);
2751                            mActionBar.setSplitActionBar(splitActionBar);
2752                            mActionBar.setSplitView(splitView);
2753
2754                            final ActionBarContextView cab = (ActionBarContextView) findViewById(
2755                                    com.android.internal.R.id.action_context_bar);
2756                            cab.setSplitView(splitView);
2757                        } else {
2758                            Log.e(TAG, "Requested split action bar with " +
2759                                    "incompatible window decor! Ignoring request.");
2760                        }
2761                    }
2762
2763                    // Post the panel invalidate for later; avoid application onCreateOptionsMenu
2764                    // being called in the middle of onCreate or similar.
2765                    mDecor.post(new Runnable() {
2766                        public void run() {
2767                            // Invalidate if the panel menu hasn't been created before this.
2768                            PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
2769                            if (!isDestroyed() && (st == null || st.menu == null)) {
2770                                invalidatePanelMenu(FEATURE_ACTION_BAR);
2771                            }
2772                        }
2773                    });
2774                }
2775            }
2776        }
2777    }
2778
2779    private Drawable loadImageURI(Uri uri) {
2780        try {
2781            return Drawable.createFromStream(
2782                    getContext().getContentResolver().openInputStream(uri), null);
2783        } catch (Exception e) {
2784            Log.w(TAG, "Unable to open content: " + uri);
2785        }
2786        return null;
2787    }
2788
2789    private DrawableFeatureState getDrawableState(int featureId, boolean required) {
2790        if ((getFeatures() & (1 << featureId)) == 0) {
2791            if (!required) {
2792                return null;
2793            }
2794            throw new RuntimeException("The feature has not been requested");
2795        }
2796
2797        DrawableFeatureState[] ar;
2798        if ((ar = mDrawables) == null || ar.length <= featureId) {
2799            DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1];
2800            if (ar != null) {
2801                System.arraycopy(ar, 0, nar, 0, ar.length);
2802            }
2803            mDrawables = ar = nar;
2804        }
2805
2806        DrawableFeatureState st = ar[featureId];
2807        if (st == null) {
2808            ar[featureId] = st = new DrawableFeatureState(featureId);
2809        }
2810        return st;
2811    }
2812
2813    /**
2814     * Gets a panel's state based on its feature ID.
2815     *
2816     * @param featureId The feature ID of the panel.
2817     * @param required Whether the panel is required (if it is required and it
2818     *            isn't in our features, this throws an exception).
2819     * @return The panel state.
2820     */
2821    private PanelFeatureState getPanelState(int featureId, boolean required) {
2822        return getPanelState(featureId, required, null);
2823    }
2824
2825    /**
2826     * Gets a panel's state based on its feature ID.
2827     *
2828     * @param featureId The feature ID of the panel.
2829     * @param required Whether the panel is required (if it is required and it
2830     *            isn't in our features, this throws an exception).
2831     * @param convertPanelState Optional: If the panel state does not exist, use
2832     *            this as the panel state.
2833     * @return The panel state.
2834     */
2835    private PanelFeatureState getPanelState(int featureId, boolean required,
2836            PanelFeatureState convertPanelState) {
2837        if ((getFeatures() & (1 << featureId)) == 0) {
2838            if (!required) {
2839                return null;
2840            }
2841            throw new RuntimeException("The feature has not been requested");
2842        }
2843
2844        PanelFeatureState[] ar;
2845        if ((ar = mPanels) == null || ar.length <= featureId) {
2846            PanelFeatureState[] nar = new PanelFeatureState[featureId + 1];
2847            if (ar != null) {
2848                System.arraycopy(ar, 0, nar, 0, ar.length);
2849            }
2850            mPanels = ar = nar;
2851        }
2852
2853        PanelFeatureState st = ar[featureId];
2854        if (st == null) {
2855            ar[featureId] = st = (convertPanelState != null)
2856                    ? convertPanelState
2857                    : new PanelFeatureState(featureId);
2858        }
2859        return st;
2860    }
2861
2862    @Override
2863    public final void setChildDrawable(int featureId, Drawable drawable) {
2864        DrawableFeatureState st = getDrawableState(featureId, true);
2865        st.child = drawable;
2866        updateDrawable(featureId, st, false);
2867    }
2868
2869    @Override
2870    public final void setChildInt(int featureId, int value) {
2871        updateInt(featureId, value, false);
2872    }
2873
2874    @Override
2875    public boolean isShortcutKey(int keyCode, KeyEvent event) {
2876        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
2877        return st.menu != null && st.menu.isShortcutKey(keyCode, event);
2878    }
2879
2880    private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) {
2881        // Do nothing if the decor is not yet installed... an update will
2882        // need to be forced when we eventually become active.
2883        if (mContentParent == null) {
2884            return;
2885        }
2886
2887        final int featureMask = 1 << featureId;
2888
2889        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2890            return;
2891        }
2892
2893        Drawable drawable = null;
2894        if (st != null) {
2895            drawable = st.child;
2896            if (drawable == null)
2897                drawable = st.local;
2898            if (drawable == null)
2899                drawable = st.def;
2900        }
2901        if ((getLocalFeatures() & featureMask) == 0) {
2902            if (getContainer() != null) {
2903                if (isActive() || fromResume) {
2904                    getContainer().setChildDrawable(featureId, drawable);
2905                }
2906            }
2907        } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) {
2908            // System.out.println("Drawable changed: old=" + st.cur
2909            // + ", new=" + drawable);
2910            st.cur = drawable;
2911            st.curAlpha = st.alpha;
2912            onDrawableChanged(featureId, drawable, st.alpha);
2913        }
2914    }
2915
2916    private void updateInt(int featureId, int value, boolean fromResume) {
2917
2918        // Do nothing if the decor is not yet installed... an update will
2919        // need to be forced when we eventually become active.
2920        if (mContentParent == null) {
2921            return;
2922        }
2923
2924        final int featureMask = 1 << featureId;
2925
2926        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2927            return;
2928        }
2929
2930        if ((getLocalFeatures() & featureMask) == 0) {
2931            if (getContainer() != null) {
2932                getContainer().setChildInt(featureId, value);
2933            }
2934        } else {
2935            onIntChanged(featureId, value);
2936        }
2937    }
2938
2939    private ImageView getLeftIconView() {
2940        if (mLeftIconView != null) {
2941            return mLeftIconView;
2942        }
2943        if (mContentParent == null) {
2944            installDecor();
2945        }
2946        return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon));
2947    }
2948
2949    private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) {
2950        if (mCircularProgressBar != null) {
2951            return mCircularProgressBar;
2952        }
2953        if (mContentParent == null && shouldInstallDecor) {
2954            installDecor();
2955        }
2956        mCircularProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_circular);
2957        if (mCircularProgressBar != null) {
2958            mCircularProgressBar.setVisibility(View.INVISIBLE);
2959        }
2960        return mCircularProgressBar;
2961    }
2962
2963    private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) {
2964        if (mHorizontalProgressBar != null) {
2965            return mHorizontalProgressBar;
2966        }
2967        if (mContentParent == null && shouldInstallDecor) {
2968            installDecor();
2969        }
2970        mHorizontalProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_horizontal);
2971        if (mHorizontalProgressBar != null) {
2972            mHorizontalProgressBar.setVisibility(View.INVISIBLE);
2973        }
2974        return mHorizontalProgressBar;
2975    }
2976
2977    private ImageView getRightIconView() {
2978        if (mRightIconView != null) {
2979            return mRightIconView;
2980        }
2981        if (mContentParent == null) {
2982            installDecor();
2983        }
2984        return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon));
2985    }
2986
2987    /**
2988     * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)}
2989     * callback. This method will grab whatever extra state is needed for the
2990     * callback that isn't given in the parameters. If the panel is not open,
2991     * this will not perform the callback.
2992     *
2993     * @param featureId Feature ID of the panel that was closed. Must be given.
2994     * @param panel Panel that was closed. Optional but useful if there is no
2995     *            menu given.
2996     * @param menu The menu that was closed. Optional, but give if you have.
2997     */
2998    private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) {
2999        final Callback cb = getCallback();
3000        if (cb == null)
3001            return;
3002
3003        // Try to get a menu
3004        if (menu == null) {
3005            // Need a panel to grab the menu, so try to get that
3006            if (panel == null) {
3007                if ((featureId >= 0) && (featureId < mPanels.length)) {
3008                    panel = mPanels[featureId];
3009                }
3010            }
3011
3012            if (panel != null) {
3013                // menu still may be null, which is okay--we tried our best
3014                menu = panel.menu;
3015            }
3016        }
3017
3018        // If the panel is not open, do not callback
3019        if ((panel != null) && (!panel.isOpen))
3020            return;
3021
3022        if (!isDestroyed()) {
3023            cb.onPanelClosed(featureId, menu);
3024        }
3025    }
3026
3027    /**
3028     * Helper method for adding launch-search to most applications. Opens the
3029     * search window using default settings.
3030     *
3031     * @return true if search window opened
3032     */
3033    private boolean launchDefaultSearch() {
3034        final Callback cb = getCallback();
3035        if (cb == null || isDestroyed()) {
3036            return false;
3037        } else {
3038            sendCloseSystemWindows("search");
3039            return cb.onSearchRequested();
3040        }
3041    }
3042
3043    @Override
3044    public void setVolumeControlStream(int streamType) {
3045        mVolumeControlStreamType = streamType;
3046    }
3047
3048    @Override
3049    public int getVolumeControlStream() {
3050        return mVolumeControlStreamType;
3051    }
3052
3053    private static final class DrawableFeatureState {
3054        DrawableFeatureState(int _featureId) {
3055            featureId = _featureId;
3056        }
3057
3058        final int featureId;
3059
3060        int resid;
3061
3062        Uri uri;
3063
3064        Drawable local;
3065
3066        Drawable child;
3067
3068        Drawable def;
3069
3070        Drawable cur;
3071
3072        int alpha = 255;
3073
3074        int curAlpha = 255;
3075    }
3076
3077    private static final class PanelFeatureState {
3078
3079        /** Feature ID for this panel. */
3080        int featureId;
3081
3082        // Information pulled from the style for this panel.
3083
3084        int background;
3085
3086        /** The background when the panel spans the entire available width. */
3087        int fullBackground;
3088
3089        int gravity;
3090
3091        int x;
3092
3093        int y;
3094
3095        int windowAnimations;
3096
3097        /** Dynamic state of the panel. */
3098        DecorView decorView;
3099
3100        /** The panel that was returned by onCreatePanelView(). */
3101        View createdPanelView;
3102
3103        /** The panel that we are actually showing. */
3104        View shownPanelView;
3105
3106        /** Use {@link #setMenu} to set this. */
3107        MenuBuilder menu;
3108
3109        IconMenuPresenter iconMenuPresenter;
3110        ListMenuPresenter listMenuPresenter;
3111
3112        /** true if this menu will show in single-list compact mode */
3113        boolean isCompact;
3114
3115        /** Theme resource ID for list elements of the panel menu */
3116        int listPresenterTheme;
3117
3118        /**
3119         * Whether the panel has been prepared (see
3120         * {@link PhoneWindow#preparePanel}).
3121         */
3122        boolean isPrepared;
3123
3124        /**
3125         * Whether an item's action has been performed. This happens in obvious
3126         * scenarios (user clicks on menu item), but can also happen with
3127         * chording menu+(shortcut key).
3128         */
3129        boolean isHandled;
3130
3131        boolean isOpen;
3132
3133        /**
3134         * True if the menu is in expanded mode, false if the menu is in icon
3135         * mode
3136         */
3137        boolean isInExpandedMode;
3138
3139        public boolean qwertyMode;
3140
3141        boolean refreshDecorView;
3142
3143        boolean refreshMenuContent;
3144
3145        boolean wasLastOpen;
3146
3147        boolean wasLastExpanded;
3148
3149        /**
3150         * Contains the state of the menu when told to freeze.
3151         */
3152        Bundle frozenMenuState;
3153
3154        /**
3155         * Contains the state of associated action views when told to freeze.
3156         * These are saved across invalidations.
3157         */
3158        Bundle frozenActionViewState;
3159
3160        PanelFeatureState(int featureId) {
3161            this.featureId = featureId;
3162
3163            refreshDecorView = false;
3164        }
3165
3166        public boolean isInListMode() {
3167            return isInExpandedMode || isCompact;
3168        }
3169
3170        public boolean hasPanelItems() {
3171            if (shownPanelView == null) return false;
3172            if (createdPanelView != null) return true;
3173
3174            if (isCompact || isInExpandedMode) {
3175                return listMenuPresenter.getAdapter().getCount() > 0;
3176            } else {
3177                return ((ViewGroup) shownPanelView).getChildCount() > 0;
3178            }
3179        }
3180
3181        /**
3182         * Unregister and free attached MenuPresenters. They will be recreated as needed.
3183         */
3184        public void clearMenuPresenters() {
3185            if (menu != null) {
3186                menu.removeMenuPresenter(iconMenuPresenter);
3187                menu.removeMenuPresenter(listMenuPresenter);
3188            }
3189            iconMenuPresenter = null;
3190            listMenuPresenter = null;
3191        }
3192
3193        void setStyle(Context context) {
3194            TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
3195            background = a.getResourceId(
3196                    com.android.internal.R.styleable.Theme_panelBackground, 0);
3197            fullBackground = a.getResourceId(
3198                    com.android.internal.R.styleable.Theme_panelFullBackground, 0);
3199            windowAnimations = a.getResourceId(
3200                    com.android.internal.R.styleable.Theme_windowAnimationStyle, 0);
3201            isCompact = a.getBoolean(
3202                    com.android.internal.R.styleable.Theme_panelMenuIsCompact, false);
3203            listPresenterTheme = a.getResourceId(
3204                    com.android.internal.R.styleable.Theme_panelMenuListTheme,
3205                    com.android.internal.R.style.Theme_ExpandedMenu);
3206            a.recycle();
3207        }
3208
3209        void setMenu(MenuBuilder menu) {
3210            if (menu == this.menu) return;
3211
3212            if (this.menu != null) {
3213                this.menu.removeMenuPresenter(iconMenuPresenter);
3214                this.menu.removeMenuPresenter(listMenuPresenter);
3215            }
3216            this.menu = menu;
3217            if (menu != null) {
3218                if (iconMenuPresenter != null) menu.addMenuPresenter(iconMenuPresenter);
3219                if (listMenuPresenter != null) menu.addMenuPresenter(listMenuPresenter);
3220            }
3221        }
3222
3223        MenuView getListMenuView(MenuPresenter.Callback cb) {
3224            if (menu == null) return null;
3225
3226            if (!isCompact) {
3227                getIconMenuView(cb); // Need this initialized to know where our offset goes
3228            }
3229
3230            if (listMenuPresenter == null) {
3231                listMenuPresenter = new ListMenuPresenter(
3232                        com.android.internal.R.layout.list_menu_item_layout, listPresenterTheme);
3233                listMenuPresenter.setCallback(cb);
3234                listMenuPresenter.setId(com.android.internal.R.id.list_menu_presenter);
3235                menu.addMenuPresenter(listMenuPresenter);
3236            }
3237
3238            if (iconMenuPresenter != null) {
3239                listMenuPresenter.setItemIndexOffset(
3240                        iconMenuPresenter.getNumActualItemsShown());
3241            }
3242            MenuView result = listMenuPresenter.getMenuView(decorView);
3243
3244            return result;
3245        }
3246
3247        MenuView getIconMenuView(MenuPresenter.Callback cb) {
3248            if (menu == null) return null;
3249
3250            if (iconMenuPresenter == null) {
3251                iconMenuPresenter = new IconMenuPresenter();
3252                iconMenuPresenter.setCallback(cb);
3253                iconMenuPresenter.setId(com.android.internal.R.id.icon_menu_presenter);
3254                menu.addMenuPresenter(iconMenuPresenter);
3255            }
3256
3257            MenuView result = iconMenuPresenter.getMenuView(decorView);
3258
3259            return result;
3260        }
3261
3262        Parcelable onSaveInstanceState() {
3263            SavedState savedState = new SavedState();
3264            savedState.featureId = featureId;
3265            savedState.isOpen = isOpen;
3266            savedState.isInExpandedMode = isInExpandedMode;
3267
3268            if (menu != null) {
3269                savedState.menuState = new Bundle();
3270                menu.savePresenterStates(savedState.menuState);
3271            }
3272
3273            return savedState;
3274        }
3275
3276        void onRestoreInstanceState(Parcelable state) {
3277            SavedState savedState = (SavedState) state;
3278            featureId = savedState.featureId;
3279            wasLastOpen = savedState.isOpen;
3280            wasLastExpanded = savedState.isInExpandedMode;
3281            frozenMenuState = savedState.menuState;
3282
3283            /*
3284             * A LocalActivityManager keeps the same instance of this class around.
3285             * The first time the menu is being shown after restoring, the
3286             * Activity.onCreateOptionsMenu should be called. But, if it is the
3287             * same instance then menu != null and we won't call that method.
3288             * We clear any cached views here. The caller should invalidatePanelMenu.
3289             */
3290            createdPanelView = null;
3291            shownPanelView = null;
3292            decorView = null;
3293        }
3294
3295        void applyFrozenState() {
3296            if (menu != null && frozenMenuState != null) {
3297                menu.restorePresenterStates(frozenMenuState);
3298                frozenMenuState = null;
3299            }
3300        }
3301
3302        private static class SavedState implements Parcelable {
3303            int featureId;
3304            boolean isOpen;
3305            boolean isInExpandedMode;
3306            Bundle menuState;
3307
3308            public int describeContents() {
3309                return 0;
3310            }
3311
3312            public void writeToParcel(Parcel dest, int flags) {
3313                dest.writeInt(featureId);
3314                dest.writeInt(isOpen ? 1 : 0);
3315                dest.writeInt(isInExpandedMode ? 1 : 0);
3316
3317                if (isOpen) {
3318                    dest.writeBundle(menuState);
3319                }
3320            }
3321
3322            private static SavedState readFromParcel(Parcel source) {
3323                SavedState savedState = new SavedState();
3324                savedState.featureId = source.readInt();
3325                savedState.isOpen = source.readInt() == 1;
3326                savedState.isInExpandedMode = source.readInt() == 1;
3327
3328                if (savedState.isOpen) {
3329                    savedState.menuState = source.readBundle();
3330                }
3331
3332                return savedState;
3333            }
3334
3335            public static final Parcelable.Creator<SavedState> CREATOR
3336                    = new Parcelable.Creator<SavedState>() {
3337                public SavedState createFromParcel(Parcel in) {
3338                    return readFromParcel(in);
3339                }
3340
3341                public SavedState[] newArray(int size) {
3342                    return new SavedState[size];
3343                }
3344            };
3345        }
3346
3347    }
3348
3349    static class RotationWatcher extends IRotationWatcher.Stub {
3350        private Handler mHandler;
3351        private final Runnable mRotationChanged = new Runnable() {
3352            public void run() {
3353                dispatchRotationChanged();
3354            }
3355        };
3356        private final ArrayList<WeakReference<PhoneWindow>> mWindows =
3357                new ArrayList<WeakReference<PhoneWindow>>();
3358        private boolean mIsWatching;
3359
3360        @Override
3361        public void onRotationChanged(int rotation) throws RemoteException {
3362            mHandler.post(mRotationChanged);
3363        }
3364
3365        public void addWindow(PhoneWindow phoneWindow) {
3366            synchronized (mWindows) {
3367                if (!mIsWatching) {
3368                    try {
3369                        WindowManagerHolder.sWindowManager.watchRotation(this);
3370                        mHandler = new Handler();
3371                        mIsWatching = true;
3372                    } catch (RemoteException ex) {
3373                        Log.e(TAG, "Couldn't start watching for device rotation", ex);
3374                    }
3375                }
3376                mWindows.add(new WeakReference<PhoneWindow>(phoneWindow));
3377            }
3378        }
3379
3380        public void removeWindow(PhoneWindow phoneWindow) {
3381            synchronized (mWindows) {
3382                int i = 0;
3383                while (i < mWindows.size()) {
3384                    final WeakReference<PhoneWindow> ref = mWindows.get(i);
3385                    final PhoneWindow win = ref.get();
3386                    if (win == null || win == phoneWindow) {
3387                        mWindows.remove(i);
3388                    } else {
3389                        i++;
3390                    }
3391                }
3392            }
3393        }
3394
3395        void dispatchRotationChanged() {
3396            synchronized (mWindows) {
3397                int i = 0;
3398                while (i < mWindows.size()) {
3399                    final WeakReference<PhoneWindow> ref = mWindows.get(i);
3400                    final PhoneWindow win = ref.get();
3401                    if (win != null) {
3402                        win.onOptionsPanelRotationChanged();
3403                        i++;
3404                    } else {
3405                        mWindows.remove(i);
3406                    }
3407                }
3408            }
3409        }
3410    }
3411
3412    /**
3413     * Simple implementation of MenuBuilder.Callback that:
3414     * <li> Opens a submenu when selected.
3415     * <li> Calls back to the callback's onMenuItemSelected when an item is
3416     * selected.
3417     */
3418    private final class DialogMenuCallback implements MenuBuilder.Callback, MenuPresenter.Callback {
3419        private int mFeatureId;
3420        private MenuDialogHelper mSubMenuHelper;
3421
3422        public DialogMenuCallback(int featureId) {
3423            mFeatureId = featureId;
3424        }
3425
3426        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
3427            if (menu.getRootMenu() != menu) {
3428                onCloseSubMenu(menu);
3429            }
3430
3431            if (allMenusAreClosing) {
3432                Callback callback = getCallback();
3433                if (callback != null && !isDestroyed()) {
3434                    callback.onPanelClosed(mFeatureId, menu);
3435                }
3436
3437                if (menu == mContextMenu) {
3438                    dismissContextMenu();
3439                }
3440
3441                // Dismiss the submenu, if it is showing
3442                if (mSubMenuHelper != null) {
3443                    mSubMenuHelper.dismiss();
3444                    mSubMenuHelper = null;
3445                }
3446            }
3447        }
3448
3449        public void onCloseSubMenu(MenuBuilder menu) {
3450            Callback callback = getCallback();
3451            if (callback != null && !isDestroyed()) {
3452                callback.onPanelClosed(mFeatureId, menu.getRootMenu());
3453            }
3454        }
3455
3456        public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
3457            Callback callback = getCallback();
3458            return (callback != null && !isDestroyed())
3459                    && callback.onMenuItemSelected(mFeatureId, item);
3460        }
3461
3462        public void onMenuModeChange(MenuBuilder menu) {
3463        }
3464
3465        public boolean onOpenSubMenu(MenuBuilder subMenu) {
3466            // Set a simple callback for the submenu
3467            subMenu.setCallback(this);
3468
3469            // The window manager will give us a valid window token
3470            mSubMenuHelper = new MenuDialogHelper(subMenu);
3471            mSubMenuHelper.show(null);
3472
3473            return true;
3474        }
3475    }
3476
3477    void sendCloseSystemWindows() {
3478        PhoneWindowManager.sendCloseSystemWindows(getContext(), null);
3479    }
3480
3481    void sendCloseSystemWindows(String reason) {
3482        PhoneWindowManager.sendCloseSystemWindows(getContext(), reason);
3483    }
3484}
3485