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