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