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