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