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