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