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