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