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