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