PhoneWindow.java revision 02b74a07de57962b52ea62d7347d68bc7f079a05
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        if (hasFeature(FEATURE_ACTION_BAR) && panel.featureId == FEATURE_OPTIONS_PANEL) {
889            mDecor.post(new Runnable() {
890                public void run() {
891                    mActionButtonPopup = new ActionButtonSubmenu(getContext(), subMenu);
892                    mActionButtonPopup.show();
893                    Callback cb = getCallback();
894                    if (cb != null) {
895                        cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
896                    }
897                }
898            });
899        } else {
900            // The window manager will give us a valid window token
901            new MenuDialogHelper(subMenu).show(null);
902        }
903
904        return true;
905    }
906
907    public void onMenuModeChange(MenuBuilder menu) {
908        reopenMenu(true);
909    }
910
911    private void reopenMenu(boolean toggleMenuMode) {
912        if (mActionBar != null) {
913            final Callback cb = getCallback();
914            if (!mActionBar.isOverflowMenuShowing() || !toggleMenuMode) {
915                if (cb != null) {
916                    final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
917                    if (cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) {
918                        cb.onMenuOpened(FEATURE_ACTION_BAR, st.menu);
919                        mActionBar.openOverflowMenu();
920                    }
921                }
922            } else {
923                mActionBar.hideOverflowMenu();
924                if (cb != null) {
925                    final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
926                    cb.onPanelClosed(FEATURE_ACTION_BAR, st.menu);
927                }
928            }
929            return;
930        }
931
932        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
933
934        // Save the future expanded mode state since closePanel will reset it
935        boolean newExpandedMode = toggleMenuMode ? !st.isInExpandedMode : st.isInExpandedMode;
936
937        st.refreshDecorView = true;
938        closePanel(st, false);
939
940        // Set the expanded mode state
941        st.isInExpandedMode = newExpandedMode;
942
943        openPanel(st, null);
944    }
945
946    /**
947     * Initializes the menu associated with the given panel feature state. You
948     * must at the very least set PanelFeatureState.menu to the Menu to be
949     * associated with the given panel state. The default implementation creates
950     * a new menu for the panel state.
951     *
952     * @param st The panel whose menu is being initialized.
953     * @return Whether the initialization was successful.
954     */
955    protected boolean initializePanelMenu(final PanelFeatureState st) {
956        final MenuBuilder menu = new MenuBuilder(getContext());
957
958        menu.setCallback(this);
959        st.setMenu(menu);
960
961        return true;
962    }
963
964    /**
965     * Perform initial setup of a panel. This should at the very least set the
966     * style information in the PanelFeatureState and must set
967     * PanelFeatureState.decor to the panel's window decor view.
968     *
969     * @param st The panel being initialized.
970     */
971    protected boolean initializePanelDecor(PanelFeatureState st) {
972        st.decorView = new DecorView(getContext(), st.featureId);
973        st.gravity = Gravity.CENTER | Gravity.BOTTOM;
974        st.setStyle(getContext());
975
976        return true;
977    }
978
979    /**
980     * Initializes the panel associated with the panel feature state. You must
981     * at the very least set PanelFeatureState.panel to the View implementing
982     * its contents. The default implementation gets the panel from the menu.
983     *
984     * @param st The panel state being initialized.
985     * @return Whether the initialization was successful.
986     */
987    protected boolean initializePanelContent(PanelFeatureState st) {
988
989        if (st.createdPanelView != null) {
990            st.shownPanelView = st.createdPanelView;
991            return true;
992        }
993
994        final MenuBuilder menu = (MenuBuilder)st.menu;
995        if (menu == null) {
996            return false;
997        }
998
999        st.shownPanelView = menu.getMenuView((st.isInExpandedMode) ? MenuBuilder.TYPE_EXPANDED
1000                : MenuBuilder.TYPE_ICON, st.decorView);
1001
1002        if (st.shownPanelView != null) {
1003            // Use the menu View's default animations if it has any
1004            final int defaultAnimations = ((MenuView) st.shownPanelView).getWindowAnimations();
1005            if (defaultAnimations != 0) {
1006                st.windowAnimations = defaultAnimations;
1007            }
1008            return true;
1009        } else {
1010            return false;
1011        }
1012    }
1013
1014    @Override
1015    public boolean performContextMenuIdentifierAction(int id, int flags) {
1016        return (mContextMenu != null) ? mContextMenu.performIdentifierAction(id, flags) : false;
1017    }
1018
1019    @Override
1020    public final void setBackgroundDrawable(Drawable drawable) {
1021        if (drawable != mBackgroundDrawable || mBackgroundResource != 0) {
1022            mBackgroundResource = 0;
1023            mBackgroundDrawable = drawable;
1024            if (mDecor != null) {
1025                mDecor.setWindowBackground(drawable);
1026            }
1027        }
1028    }
1029
1030    @Override
1031    public final void setFeatureDrawableResource(int featureId, int resId) {
1032        if (resId != 0) {
1033            DrawableFeatureState st = getDrawableState(featureId, true);
1034            if (st.resid != resId) {
1035                st.resid = resId;
1036                st.uri = null;
1037                st.local = getContext().getResources().getDrawable(resId);
1038                updateDrawable(featureId, st, false);
1039            }
1040        } else {
1041            setFeatureDrawable(featureId, null);
1042        }
1043    }
1044
1045    @Override
1046    public final void setFeatureDrawableUri(int featureId, Uri uri) {
1047        if (uri != null) {
1048            DrawableFeatureState st = getDrawableState(featureId, true);
1049            if (st.uri == null || !st.uri.equals(uri)) {
1050                st.resid = 0;
1051                st.uri = uri;
1052                st.local = loadImageURI(uri);
1053                updateDrawable(featureId, st, false);
1054            }
1055        } else {
1056            setFeatureDrawable(featureId, null);
1057        }
1058    }
1059
1060    @Override
1061    public final void setFeatureDrawable(int featureId, Drawable drawable) {
1062        DrawableFeatureState st = getDrawableState(featureId, true);
1063        st.resid = 0;
1064        st.uri = null;
1065        if (st.local != drawable) {
1066            st.local = drawable;
1067            updateDrawable(featureId, st, false);
1068        }
1069    }
1070
1071    @Override
1072    public void setFeatureDrawableAlpha(int featureId, int alpha) {
1073        DrawableFeatureState st = getDrawableState(featureId, true);
1074        if (st.alpha != alpha) {
1075            st.alpha = alpha;
1076            updateDrawable(featureId, st, false);
1077        }
1078    }
1079
1080    protected final void setFeatureDefaultDrawable(int featureId, Drawable drawable) {
1081        DrawableFeatureState st = getDrawableState(featureId, true);
1082        if (st.def != drawable) {
1083            st.def = drawable;
1084            updateDrawable(featureId, st, false);
1085        }
1086    }
1087
1088    @Override
1089    public final void setFeatureInt(int featureId, int value) {
1090        // XXX Should do more management (as with drawable features) to
1091        // deal with interactions between multiple window policies.
1092        updateInt(featureId, value, false);
1093    }
1094
1095    /**
1096     * Update the state of a drawable feature. This should be called, for every
1097     * drawable feature supported, as part of onActive(), to make sure that the
1098     * contents of a containing window is properly updated.
1099     *
1100     * @see #onActive
1101     * @param featureId The desired drawable feature to change.
1102     * @param fromActive Always true when called from onActive().
1103     */
1104    protected final void updateDrawable(int featureId, boolean fromActive) {
1105        final DrawableFeatureState st = getDrawableState(featureId, false);
1106        if (st != null) {
1107            updateDrawable(featureId, st, fromActive);
1108        }
1109    }
1110
1111    /**
1112     * Called when a Drawable feature changes, for the window to update its
1113     * graphics.
1114     *
1115     * @param featureId The feature being changed.
1116     * @param drawable The new Drawable to show, or null if none.
1117     * @param alpha The new alpha blending of the Drawable.
1118     */
1119    protected void onDrawableChanged(int featureId, Drawable drawable, int alpha) {
1120        ImageView view;
1121        if (featureId == FEATURE_LEFT_ICON) {
1122            view = getLeftIconView();
1123        } else if (featureId == FEATURE_RIGHT_ICON) {
1124            view = getRightIconView();
1125        } else {
1126            return;
1127        }
1128
1129        if (drawable != null) {
1130            drawable.setAlpha(alpha);
1131            view.setImageDrawable(drawable);
1132            view.setVisibility(View.VISIBLE);
1133        } else {
1134            view.setVisibility(View.GONE);
1135        }
1136    }
1137
1138    /**
1139     * Called when an int feature changes, for the window to update its
1140     * graphics.
1141     *
1142     * @param featureId The feature being changed.
1143     * @param value The new integer value.
1144     */
1145    protected void onIntChanged(int featureId, int value) {
1146        if (featureId == FEATURE_PROGRESS || featureId == FEATURE_INDETERMINATE_PROGRESS) {
1147            updateProgressBars(value);
1148        } else if (featureId == FEATURE_CUSTOM_TITLE) {
1149            FrameLayout titleContainer = (FrameLayout) findViewById(com.android.internal.R.id.title_container);
1150            if (titleContainer != null) {
1151                mLayoutInflater.inflate(value, titleContainer);
1152            }
1153        }
1154    }
1155
1156    /**
1157     * Updates the progress bars that are shown in the title bar.
1158     *
1159     * @param value Can be one of {@link Window#PROGRESS_VISIBILITY_ON},
1160     *            {@link Window#PROGRESS_VISIBILITY_OFF},
1161     *            {@link Window#PROGRESS_INDETERMINATE_ON},
1162     *            {@link Window#PROGRESS_INDETERMINATE_OFF}, or a value
1163     *            starting at {@link Window#PROGRESS_START} through
1164     *            {@link Window#PROGRESS_END} for setting the default
1165     *            progress (if {@link Window#PROGRESS_END} is given,
1166     *            the progress bar widgets in the title will be hidden after an
1167     *            animation), a value between
1168     *            {@link Window#PROGRESS_SECONDARY_START} -
1169     *            {@link Window#PROGRESS_SECONDARY_END} for the
1170     *            secondary progress (if
1171     *            {@link Window#PROGRESS_SECONDARY_END} is given, the
1172     *            progress bar widgets will still be shown with the secondary
1173     *            progress bar will be completely filled in.)
1174     */
1175    private void updateProgressBars(int value) {
1176        ProgressBar circularProgressBar = getCircularProgressBar(true);
1177        ProgressBar horizontalProgressBar = getHorizontalProgressBar(true);
1178
1179        final int features = getLocalFeatures();
1180        if (value == PROGRESS_VISIBILITY_ON) {
1181            if ((features & (1 << FEATURE_PROGRESS)) != 0) {
1182                int level = horizontalProgressBar.getProgress();
1183                int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ?
1184                        View.VISIBLE : View.INVISIBLE;
1185                horizontalProgressBar.setVisibility(visibility);
1186            }
1187            if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
1188                circularProgressBar.setVisibility(View.VISIBLE);
1189            }
1190        } else if (value == PROGRESS_VISIBILITY_OFF) {
1191            if ((features & (1 << FEATURE_PROGRESS)) != 0) {
1192                horizontalProgressBar.setVisibility(View.GONE);
1193            }
1194            if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
1195                circularProgressBar.setVisibility(View.GONE);
1196            }
1197        } else if (value == PROGRESS_INDETERMINATE_ON) {
1198            horizontalProgressBar.setIndeterminate(true);
1199        } else if (value == PROGRESS_INDETERMINATE_OFF) {
1200            horizontalProgressBar.setIndeterminate(false);
1201        } else if (PROGRESS_START <= value && value <= PROGRESS_END) {
1202            // We want to set the progress value before testing for visibility
1203            // so that when the progress bar becomes visible again, it has the
1204            // correct level.
1205            horizontalProgressBar.setProgress(value - PROGRESS_START);
1206
1207            if (value < PROGRESS_END) {
1208                showProgressBars(horizontalProgressBar, circularProgressBar);
1209            } else {
1210                hideProgressBars(horizontalProgressBar, circularProgressBar);
1211            }
1212        } else if (PROGRESS_SECONDARY_START <= value && value <= PROGRESS_SECONDARY_END) {
1213            horizontalProgressBar.setSecondaryProgress(value - PROGRESS_SECONDARY_START);
1214
1215            showProgressBars(horizontalProgressBar, circularProgressBar);
1216        }
1217
1218    }
1219
1220    private void showProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
1221        final int features = getLocalFeatures();
1222        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
1223                spinnyProgressBar.getVisibility() == View.INVISIBLE) {
1224            spinnyProgressBar.setVisibility(View.VISIBLE);
1225        }
1226        // Only show the progress bars if the primary progress is not complete
1227        if ((features & (1 << FEATURE_PROGRESS)) != 0 &&
1228                horizontalProgressBar.getProgress() < 10000) {
1229            horizontalProgressBar.setVisibility(View.VISIBLE);
1230        }
1231    }
1232
1233    private void hideProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
1234        final int features = getLocalFeatures();
1235        Animation anim = AnimationUtils.loadAnimation(getContext(), com.android.internal.R.anim.fade_out);
1236        anim.setDuration(1000);
1237        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
1238                spinnyProgressBar.getVisibility() == View.VISIBLE) {
1239            spinnyProgressBar.startAnimation(anim);
1240            spinnyProgressBar.setVisibility(View.INVISIBLE);
1241        }
1242        if ((features & (1 << FEATURE_PROGRESS)) != 0 &&
1243                horizontalProgressBar.getVisibility() == View.VISIBLE) {
1244            horizontalProgressBar.startAnimation(anim);
1245            horizontalProgressBar.setVisibility(View.INVISIBLE);
1246        }
1247    }
1248
1249    /**
1250     * Request that key events come to this activity. Use this if your activity
1251     * has no views with focus, but the activity still wants a chance to process
1252     * key events.
1253     */
1254    @Override
1255    public void takeKeyEvents(boolean get) {
1256        mDecor.setFocusable(get);
1257    }
1258
1259    @Override
1260    public boolean superDispatchKeyEvent(KeyEvent event) {
1261        return mDecor.superDispatchKeyEvent(event);
1262    }
1263
1264    @Override
1265    public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
1266        return mDecor.superDispatchKeyShortcutEvent(event);
1267    }
1268
1269    @Override
1270    public boolean superDispatchTouchEvent(MotionEvent event) {
1271        return mDecor.superDispatchTouchEvent(event);
1272    }
1273
1274    @Override
1275    public boolean superDispatchTrackballEvent(MotionEvent event) {
1276        return mDecor.superDispatchTrackballEvent(event);
1277    }
1278
1279    @Override
1280    public boolean superDispatchGenericMotionEvent(MotionEvent event) {
1281        return mDecor.superDispatchGenericMotionEvent(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        @Override
1698        public boolean dispatchGenericMotionEvent(MotionEvent ev) {
1699            final Callback cb = getCallback();
1700            return cb != null && mFeatureId < 0 ? cb.dispatchGenericMotionEvent(ev) : super
1701                    .dispatchGenericMotionEvent(ev);
1702        }
1703
1704        public boolean superDispatchKeyEvent(KeyEvent event) {
1705            return super.dispatchKeyEvent(event);
1706        }
1707
1708        public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
1709            return super.dispatchKeyShortcutEvent(event);
1710        }
1711
1712        public boolean superDispatchTouchEvent(MotionEvent event) {
1713            return super.dispatchTouchEvent(event);
1714        }
1715
1716        public boolean superDispatchTrackballEvent(MotionEvent event) {
1717            return super.dispatchTrackballEvent(event);
1718        }
1719
1720        public boolean superDispatchGenericMotionEvent(MotionEvent event) {
1721            return super.dispatchGenericMotionEvent(event);
1722        }
1723
1724        @Override
1725        public boolean onTouchEvent(MotionEvent event) {
1726            return onInterceptTouchEvent(event);
1727        }
1728
1729        private boolean isOutOfBounds(int x, int y) {
1730            return x < -5 || y < -5 || x > (getWidth() + 5)
1731                    || y > (getHeight() + 5);
1732        }
1733
1734        @Override
1735        public boolean onInterceptTouchEvent(MotionEvent event) {
1736            int action = event.getAction();
1737            if (mFeatureId >= 0) {
1738                if (action == MotionEvent.ACTION_DOWN) {
1739                    int x = (int)event.getX();
1740                    int y = (int)event.getY();
1741                    if (isOutOfBounds(x, y)) {
1742                        closePanel(mFeatureId);
1743                        return true;
1744                    }
1745                }
1746            }
1747
1748            if (!SWEEP_OPEN_MENU) {
1749                return false;
1750            }
1751
1752            if (mFeatureId >= 0) {
1753                if (action == MotionEvent.ACTION_DOWN) {
1754                    Log.i(TAG, "Watchiing!");
1755                    mWatchingForMenu = true;
1756                    mDownY = (int) event.getY();
1757                    return false;
1758                }
1759
1760                if (!mWatchingForMenu) {
1761                    return false;
1762                }
1763
1764                int y = (int)event.getY();
1765                if (action == MotionEvent.ACTION_MOVE) {
1766                    if (y > (mDownY+30)) {
1767                        Log.i(TAG, "Closing!");
1768                        closePanel(mFeatureId);
1769                        mWatchingForMenu = false;
1770                        return true;
1771                    }
1772                } else if (action == MotionEvent.ACTION_UP) {
1773                    mWatchingForMenu = false;
1774                }
1775
1776                return false;
1777            }
1778
1779            //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY()
1780            //        + " (in " + getHeight() + ")");
1781
1782            if (action == MotionEvent.ACTION_DOWN) {
1783                int y = (int)event.getY();
1784                if (y >= (getHeight()-5) && !hasChildren()) {
1785                    Log.i(TAG, "Watchiing!");
1786                    mWatchingForMenu = true;
1787                }
1788                return false;
1789            }
1790
1791            if (!mWatchingForMenu) {
1792                return false;
1793            }
1794
1795            int y = (int)event.getY();
1796            if (action == MotionEvent.ACTION_MOVE) {
1797                if (y < (getHeight()-30)) {
1798                    Log.i(TAG, "Opening!");
1799                    openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent(
1800                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU));
1801                    mWatchingForMenu = false;
1802                    return true;
1803                }
1804            } else if (action == MotionEvent.ACTION_UP) {
1805                mWatchingForMenu = false;
1806            }
1807
1808            return false;
1809        }
1810
1811        @Override
1812        public void sendAccessibilityEvent(int eventType) {
1813            if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
1814                return;
1815            }
1816
1817            // if we are showing a feature that should be announced and one child
1818            // make this child the event source since this is the feature itself
1819            // otherwise the callback will take over and announce its client
1820            if ((mFeatureId == FEATURE_OPTIONS_PANEL ||
1821                    mFeatureId == FEATURE_CONTEXT_MENU ||
1822                    mFeatureId == FEATURE_PROGRESS ||
1823                    mFeatureId == FEATURE_INDETERMINATE_PROGRESS)
1824                    && getChildCount() == 1) {
1825                getChildAt(0).sendAccessibilityEvent(eventType);
1826            } else {
1827                super.sendAccessibilityEvent(eventType);
1828            }
1829        }
1830
1831        @Override
1832        public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1833            final Callback cb = getCallback();
1834            if (cb != null) {
1835                if (cb.dispatchPopulateAccessibilityEvent(event)) {
1836                    return true;
1837                }
1838            }
1839            return super.dispatchPopulateAccessibilityEvent(event);
1840        }
1841
1842        @Override
1843        protected boolean setFrame(int l, int t, int r, int b) {
1844            boolean changed = super.setFrame(l, t, r, b);
1845            if (changed) {
1846                final Rect drawingBounds = mDrawingBounds;
1847                getDrawingRect(drawingBounds);
1848
1849                Drawable fg = getForeground();
1850                if (fg != null) {
1851                    final Rect frameOffsets = mFrameOffsets;
1852                    drawingBounds.left += frameOffsets.left;
1853                    drawingBounds.top += frameOffsets.top;
1854                    drawingBounds.right -= frameOffsets.right;
1855                    drawingBounds.bottom -= frameOffsets.bottom;
1856                    fg.setBounds(drawingBounds);
1857                    final Rect framePadding = mFramePadding;
1858                    drawingBounds.left += framePadding.left - frameOffsets.left;
1859                    drawingBounds.top += framePadding.top - frameOffsets.top;
1860                    drawingBounds.right -= framePadding.right - frameOffsets.right;
1861                    drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom;
1862                }
1863
1864                Drawable bg = getBackground();
1865                if (bg != null) {
1866                    bg.setBounds(drawingBounds);
1867                }
1868
1869                if (SWEEP_OPEN_MENU) {
1870                    if (mMenuBackground == null && mFeatureId < 0
1871                            && getAttributes().height
1872                            == WindowManager.LayoutParams.MATCH_PARENT) {
1873                        mMenuBackground = getContext().getResources().getDrawable(
1874                                com.android.internal.R.drawable.menu_background);
1875                    }
1876                    if (mMenuBackground != null) {
1877                        mMenuBackground.setBounds(drawingBounds.left,
1878                                drawingBounds.bottom-6, drawingBounds.right,
1879                                drawingBounds.bottom+20);
1880                    }
1881                }
1882            }
1883            return changed;
1884        }
1885
1886        @Override
1887        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1888            final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
1889            final boolean isPortrait = metrics.widthPixels < metrics.heightPixels;
1890
1891            final int widthMode = getMode(widthMeasureSpec);
1892
1893            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1894
1895            int width = getMeasuredWidth();
1896            boolean measure = false;
1897
1898            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY);
1899
1900            final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor;
1901
1902            if (widthMode == AT_MOST && tv.type != TypedValue.TYPE_NULL) {
1903                final int min;
1904                if (tv.type == TypedValue.TYPE_DIMENSION) {
1905                    min = (int)tv.getDimension(metrics);
1906                } else if (tv.type == TypedValue.TYPE_FRACTION) {
1907                    min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels);
1908                } else {
1909                    min = 0;
1910                }
1911
1912                if (width < min) {
1913                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY);
1914                    measure = true;
1915                }
1916            }
1917
1918            // TODO: Support height?
1919
1920            if (measure) {
1921                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1922            }
1923        }
1924
1925        @Override
1926        public void draw(Canvas canvas) {
1927            super.draw(canvas);
1928
1929            if (mMenuBackground != null) {
1930                mMenuBackground.draw(canvas);
1931            }
1932        }
1933
1934
1935        @Override
1936        public boolean showContextMenuForChild(View originalView) {
1937            // Reuse the context menu builder
1938            if (mContextMenu == null) {
1939                mContextMenu = new ContextMenuBuilder(getContext());
1940                mContextMenu.setCallback(mContextMenuCallback);
1941            } else {
1942                mContextMenu.clearAll();
1943            }
1944
1945            mContextMenuHelper = mContextMenu.show(originalView, originalView.getWindowToken());
1946            return mContextMenuHelper != null;
1947        }
1948
1949        @Override
1950        public ActionMode startActionModeForChild(View originalView,
1951                ActionMode.Callback callback) {
1952            // originalView can be used here to be sure that we don't obscure
1953            // relevant content with the context mode UI.
1954            return startActionMode(callback);
1955        }
1956
1957        @Override
1958        public ActionMode startActionMode(ActionMode.Callback callback) {
1959            if (mActionMode != null) {
1960                mActionMode.finish();
1961            }
1962
1963            final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback);
1964            ActionMode mode = null;
1965            try {
1966                mode = getCallback().onWindowStartingActionMode(wrappedCallback);
1967            } catch (AbstractMethodError ame) {
1968                // Older apps might not implement this callback method.
1969            }
1970            if (mode != null) {
1971                mActionMode = mode;
1972            } else {
1973                if (mActionModeView == null) {
1974                    if (hasFeature(FEATURE_ACTION_MODE_OVERLAY)) {
1975                        mActionModeView = new ActionBarContextView(mContext);
1976                        mActionModePopup = new PopupWindow(mContext, null,
1977                                com.android.internal.R.attr.actionModePopupWindowStyle);
1978                        mActionModePopup.setLayoutInScreenEnabled(true);
1979                        mActionModePopup.setClippingEnabled(false);
1980                        mActionModePopup.setContentView(mActionModeView);
1981                        mActionModePopup.setWidth(MATCH_PARENT);
1982
1983                        TypedValue heightValue = new TypedValue();
1984                        mContext.getTheme().resolveAttribute(
1985                                com.android.internal.R.attr.actionBarSize, heightValue, false);
1986                        final int height = TypedValue.complexToDimensionPixelSize(heightValue.data,
1987                                mContext.getResources().getDisplayMetrics());
1988                        mActionModePopup.setHeight(height);
1989                    } else {
1990                        ViewStub stub = (ViewStub) findViewById(
1991                                com.android.internal.R.id.action_mode_bar_stub);
1992                        if (stub != null) {
1993                            mActionModeView = (ActionBarContextView) stub.inflate();
1994                        }
1995                    }
1996                }
1997
1998                if (mActionModeView != null) {
1999                    mActionModeView.killMode();
2000                    mode = new StandaloneActionMode(getContext(), mActionModeView, wrappedCallback);
2001                    if (callback.onCreateActionMode(mode, mode.getMenu())) {
2002                        mode.invalidate();
2003                        mActionModeView.initForMode(mode);
2004                        mActionModeView.setVisibility(View.VISIBLE);
2005                        mActionMode = mode;
2006                        if (mActionModePopup != null) {
2007                            mActionModePopup.showAtLocation(this,
2008                                    Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
2009                        }
2010                    } else {
2011                        mActionMode = null;
2012                    }
2013                }
2014            }
2015            if (mActionMode != null) {
2016                try {
2017                    getCallback().onActionModeStarted(mActionMode);
2018                } catch (AbstractMethodError ame) {
2019                    // Older apps might not implement this callback method.
2020                }
2021            }
2022            return mActionMode;
2023        }
2024
2025        public void startChanging() {
2026            mChanging = true;
2027        }
2028
2029        public void finishChanging() {
2030            mChanging = false;
2031            drawableChanged();
2032        }
2033
2034        public void setWindowBackground(Drawable drawable) {
2035            if (getBackground() != drawable) {
2036                setBackgroundDrawable(drawable);
2037                if (drawable != null) {
2038                    drawable.getPadding(mBackgroundPadding);
2039                } else {
2040                    mBackgroundPadding.setEmpty();
2041                }
2042                drawableChanged();
2043            }
2044        }
2045
2046        public void setWindowFrame(Drawable drawable) {
2047            if (getForeground() != drawable) {
2048                setForeground(drawable);
2049                if (drawable != null) {
2050                    drawable.getPadding(mFramePadding);
2051                } else {
2052                    mFramePadding.setEmpty();
2053                }
2054                drawableChanged();
2055            }
2056        }
2057
2058        @Override
2059        protected boolean fitSystemWindows(Rect insets) {
2060            mFrameOffsets.set(insets);
2061            if (getForeground() != null) {
2062                drawableChanged();
2063            }
2064            return super.fitSystemWindows(insets);
2065        }
2066
2067        private void drawableChanged() {
2068            if (mChanging) {
2069                return;
2070            }
2071
2072            setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top
2073                    + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right,
2074                    mFramePadding.bottom + mBackgroundPadding.bottom);
2075            requestLayout();
2076            invalidate();
2077
2078            int opacity = PixelFormat.OPAQUE;
2079
2080            // Note: if there is no background, we will assume opaque. The
2081            // common case seems to be that an application sets there to be
2082            // no background so it can draw everything itself. For that,
2083            // we would like to assume OPAQUE and let the app force it to
2084            // the slower TRANSLUCENT mode if that is really what it wants.
2085            Drawable bg = getBackground();
2086            Drawable fg = getForeground();
2087            if (bg != null) {
2088                if (fg == null) {
2089                    opacity = bg.getOpacity();
2090                } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0
2091                        && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) {
2092                    // If the frame padding is zero, then we can be opaque
2093                    // if either the frame -or- the background is opaque.
2094                    int fop = fg.getOpacity();
2095                    int bop = bg.getOpacity();
2096                    if (Config.LOGV)
2097                        Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop);
2098                    if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) {
2099                        opacity = PixelFormat.OPAQUE;
2100                    } else if (fop == PixelFormat.UNKNOWN) {
2101                        opacity = bop;
2102                    } else if (bop == PixelFormat.UNKNOWN) {
2103                        opacity = fop;
2104                    } else {
2105                        opacity = Drawable.resolveOpacity(fop, bop);
2106                    }
2107                } else {
2108                    // For now we have to assume translucent if there is a
2109                    // frame with padding... there is no way to tell if the
2110                    // frame and background together will draw all pixels.
2111                    if (Config.LOGV)
2112                        Log.v(TAG, "Padding: " + mFramePadding);
2113                    opacity = PixelFormat.TRANSLUCENT;
2114                }
2115            }
2116
2117            if (Config.LOGV)
2118                Log.v(TAG, "Background: " + bg + ", Frame: " + fg);
2119            if (Config.LOGV)
2120                Log.v(TAG, "Selected default opacity: " + opacity);
2121
2122            mDefaultOpacity = opacity;
2123            if (mFeatureId < 0) {
2124                setDefaultWindowFormat(opacity);
2125            }
2126        }
2127
2128        @Override
2129        public void onWindowFocusChanged(boolean hasWindowFocus) {
2130            super.onWindowFocusChanged(hasWindowFocus);
2131
2132            mPanelMayLongPress = false;
2133
2134            // If the user is chording a menu shortcut, release the chord since
2135            // this window lost focus
2136            if (!hasWindowFocus && mPanelChordingKey != 0) {
2137                closePanel(FEATURE_OPTIONS_PANEL);
2138            }
2139
2140            final Callback cb = getCallback();
2141            if (cb != null && mFeatureId < 0) {
2142                cb.onWindowFocusChanged(hasWindowFocus);
2143            }
2144        }
2145
2146        @Override
2147        protected void onAttachedToWindow() {
2148            super.onAttachedToWindow();
2149
2150            final Callback cb = getCallback();
2151            if (cb != null && mFeatureId < 0) {
2152                cb.onAttachedToWindow();
2153            }
2154
2155            if (mFeatureId == -1) {
2156                /*
2157                 * The main window has been attached, try to restore any panels
2158                 * that may have been open before. This is called in cases where
2159                 * an activity is being killed for configuration change and the
2160                 * menu was open. When the activity is recreated, the menu
2161                 * should be shown again.
2162                 */
2163                openPanelsAfterRestore();
2164            }
2165        }
2166
2167        @Override
2168        protected void onDetachedFromWindow() {
2169            super.onDetachedFromWindow();
2170
2171            final Callback cb = getCallback();
2172            if (cb != null && mFeatureId < 0) {
2173                cb.onDetachedFromWindow();
2174            }
2175
2176            if (mActionButtonPopup != null) {
2177                if (mActionButtonPopup.isShowing()) {
2178                    mActionButtonPopup.dismiss();
2179                }
2180                mActionButtonPopup = null;
2181            }
2182        }
2183
2184        @Override
2185        protected void onConfigurationChanged(Configuration newConfig) {
2186            if (mActionButtonPopup != null) {
2187                mActionButtonPopup.dismiss();
2188                post(mActionButtonPopup);
2189            }
2190        }
2191
2192        @Override
2193        public void onCloseSystemDialogs(String reason) {
2194            if (mFeatureId >= 0) {
2195                closeAllPanels();
2196            }
2197        }
2198
2199        public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() {
2200            return mFeatureId < 0 ? mTakeSurfaceCallback : null;
2201        }
2202
2203        public InputQueue.Callback willYouTakeTheInputQueue() {
2204            return mFeatureId < 0 ? mTakeInputQueueCallback : null;
2205        }
2206
2207        public void setSurfaceType(int type) {
2208            PhoneWindow.this.setType(type);
2209        }
2210
2211        public void setSurfaceFormat(int format) {
2212            PhoneWindow.this.setFormat(format);
2213        }
2214
2215        public void setSurfaceKeepScreenOn(boolean keepOn) {
2216            if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2217            else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2218        }
2219
2220        /**
2221         * Clears out internal reference when the action mode is destroyed.
2222         */
2223        private class ActionModeCallbackWrapper implements ActionMode.Callback {
2224            private ActionMode.Callback mWrapped;
2225
2226            public ActionModeCallbackWrapper(ActionMode.Callback wrapped) {
2227                mWrapped = wrapped;
2228            }
2229
2230            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2231                return mWrapped.onCreateActionMode(mode, menu);
2232            }
2233
2234            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2235                return mWrapped.onPrepareActionMode(mode, menu);
2236            }
2237
2238            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2239                return mWrapped.onActionItemClicked(mode, item);
2240            }
2241
2242            public void onDestroyActionMode(ActionMode mode) {
2243                mWrapped.onDestroyActionMode(mode);
2244                if (mActionModePopup != null) {
2245                    mActionModePopup.dismiss();
2246                } else if (mActionModeView != null) {
2247                    mActionModeView.setVisibility(GONE);
2248                }
2249                if (mActionModeView != null) {
2250                    mActionModeView.removeAllViews();
2251                }
2252                try {
2253                    getCallback().onActionModeFinished(mActionMode);
2254                } catch (AbstractMethodError ame) {
2255                    // Older apps might not implement this callback method.
2256                }
2257                mActionMode = null;
2258            }
2259        }
2260    }
2261
2262    protected DecorView generateDecor() {
2263        return new DecorView(getContext(), -1);
2264    }
2265
2266    protected void setFeatureFromAttrs(int featureId, TypedArray attrs,
2267            int drawableAttr, int alphaAttr) {
2268        Drawable d = attrs.getDrawable(drawableAttr);
2269        if (d != null) {
2270            requestFeature(featureId);
2271            setFeatureDefaultDrawable(featureId, d);
2272        }
2273        if ((getFeatures() & (1 << featureId)) != 0) {
2274            int alpha = attrs.getInt(alphaAttr, -1);
2275            if (alpha >= 0) {
2276                setFeatureDrawableAlpha(featureId, alpha);
2277            }
2278        }
2279    }
2280
2281    protected ViewGroup generateLayout(DecorView decor) {
2282        // Apply data from current theme.
2283
2284        TypedArray a = getWindowStyle();
2285
2286        if (false) {
2287            System.out.println("From style:");
2288            String s = "Attrs:";
2289            for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) {
2290                s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "="
2291                        + a.getString(i);
2292            }
2293            System.out.println(s);
2294        }
2295
2296        mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
2297        int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
2298                & (~getForcedWindowFlags());
2299        if (mIsFloating) {
2300            setLayout(WRAP_CONTENT, WRAP_CONTENT);
2301            setFlags(0, flagsToUpdate);
2302        } else {
2303            setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
2304        }
2305
2306        if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
2307            requestFeature(FEATURE_NO_TITLE);
2308        } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) {
2309            // Don't allow an action bar if there is no title.
2310            requestFeature(FEATURE_ACTION_BAR);
2311        }
2312
2313        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) {
2314            requestFeature(FEATURE_ACTION_BAR_OVERLAY);
2315        }
2316
2317        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) {
2318            requestFeature(FEATURE_ACTION_MODE_OVERLAY);
2319        }
2320
2321        if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
2322            setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags()));
2323        }
2324
2325        if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) {
2326            setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
2327        }
2328
2329        if (a.getBoolean(com.android.internal.R.styleable.Window_windowEnableSplitTouch,
2330                getContext().getApplicationInfo().targetSdkVersion
2331                        >= android.os.Build.VERSION_CODES.HONEYCOMB)) {
2332            setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags()));
2333        }
2334
2335        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMajor, mMinWidthMajor);
2336        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMinor, mMinWidthMinor);
2337
2338        if (getContext().getApplicationInfo().targetSdkVersion
2339                < android.os.Build.VERSION_CODES.HONEYCOMB) {
2340            addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY);
2341        }
2342
2343        if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion
2344                >= android.os.Build.VERSION_CODES.HONEYCOMB) {
2345            if (a.getBoolean(
2346                    com.android.internal.R.styleable.Window_windowCloseOnTouchOutside,
2347                    false)) {
2348                setCloseOnTouchOutsideIfNotSet(true);
2349            }
2350        }
2351
2352        WindowManager.LayoutParams params = getAttributes();
2353
2354        if (!hasSoftInputMode()) {
2355            params.softInputMode = a.getInt(
2356                    com.android.internal.R.styleable.Window_windowSoftInputMode,
2357                    params.softInputMode);
2358        }
2359
2360        if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled,
2361                mIsFloating)) {
2362            /* All dialogs should have the window dimmed */
2363            if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
2364                params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
2365            }
2366            params.dimAmount = a.getFloat(
2367                    android.R.styleable.Window_backgroundDimAmount, 0.5f);
2368        }
2369
2370        if (params.windowAnimations == 0) {
2371            params.windowAnimations = a.getResourceId(
2372                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2373        }
2374
2375        // The rest are only done if this window is not embedded; otherwise,
2376        // the values are inherited from our container.
2377        if (getContainer() == null) {
2378            if (mBackgroundDrawable == null) {
2379                if (mBackgroundResource == 0) {
2380                    mBackgroundResource = a.getResourceId(
2381                            com.android.internal.R.styleable.Window_windowBackground, 0);
2382                }
2383                if (mFrameResource == 0) {
2384                    mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0);
2385                }
2386                if (false) {
2387                    System.out.println("Background: "
2388                            + Integer.toHexString(mBackgroundResource) + " Frame: "
2389                            + Integer.toHexString(mFrameResource));
2390                }
2391            }
2392            mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000);
2393        }
2394
2395        // Inflate the window decor.
2396
2397        int layoutResource;
2398        int features = getLocalFeatures();
2399        // System.out.println("Features: 0x" + Integer.toHexString(features));
2400        if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
2401            if (mIsFloating) {
2402                TypedValue res = new TypedValue();
2403                getContext().getTheme().resolveAttribute(
2404                        com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true);
2405                layoutResource = res.resourceId;
2406            } else {
2407                layoutResource = com.android.internal.R.layout.screen_title_icons;
2408            }
2409            // XXX Remove this once action bar supports these features.
2410            removeFeature(FEATURE_ACTION_BAR);
2411            // System.out.println("Title Icons!");
2412        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
2413                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
2414            // Special case for a window with only a progress bar (and title).
2415            // XXX Need to have a no-title version of embedded windows.
2416            layoutResource = com.android.internal.R.layout.screen_progress;
2417            // System.out.println("Progress!");
2418        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
2419            // Special case for a window with a custom title.
2420            // If the window is floating, we need a dialog layout
2421            if (mIsFloating) {
2422                TypedValue res = new TypedValue();
2423                getContext().getTheme().resolveAttribute(
2424                        com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true);
2425                layoutResource = res.resourceId;
2426            } else {
2427                layoutResource = com.android.internal.R.layout.screen_custom_title;
2428            }
2429            // XXX Remove this once action bar supports these features.
2430            removeFeature(FEATURE_ACTION_BAR);
2431        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
2432            // If no other features and not embedded, only need a title.
2433            // If the window is floating, we need a dialog layout
2434            if (mIsFloating) {
2435                TypedValue res = new TypedValue();
2436                getContext().getTheme().resolveAttribute(
2437                        com.android.internal.R.attr.dialogTitleDecorLayout, res, true);
2438                layoutResource = res.resourceId;
2439            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
2440                if ((features & (1 << FEATURE_ACTION_BAR_OVERLAY)) != 0) {
2441                    layoutResource = com.android.internal.R.layout.screen_action_bar_overlay;
2442                } else {
2443                    layoutResource = com.android.internal.R.layout.screen_action_bar;
2444                }
2445            } else {
2446                layoutResource = com.android.internal.R.layout.screen_title;
2447            }
2448            // System.out.println("Title!");
2449        } else {
2450            // Embedded, so no decoration is needed.
2451            layoutResource = com.android.internal.R.layout.screen_simple;
2452            // System.out.println("Simple!");
2453        }
2454
2455        mDecor.startChanging();
2456
2457        View in = mLayoutInflater.inflate(layoutResource, null);
2458        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
2459
2460        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
2461        if (contentParent == null) {
2462            throw new RuntimeException("Window couldn't find content container view");
2463        }
2464
2465        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2466            ProgressBar progress = getCircularProgressBar(false);
2467            if (progress != null) {
2468                progress.setIndeterminate(true);
2469            }
2470        }
2471
2472        // Remaining setup -- of background and title -- that only applies
2473        // to top-level windows.
2474        if (getContainer() == null) {
2475            Drawable drawable = mBackgroundDrawable;
2476            if (mBackgroundResource != 0) {
2477                drawable = getContext().getResources().getDrawable(mBackgroundResource);
2478            }
2479            mDecor.setWindowBackground(drawable);
2480            drawable = null;
2481            if (mFrameResource != 0) {
2482                drawable = getContext().getResources().getDrawable(mFrameResource);
2483            }
2484            mDecor.setWindowFrame(drawable);
2485
2486            // System.out.println("Text=" + Integer.toHexString(mTextColor) +
2487            // " Sel=" + Integer.toHexString(mTextSelectedColor) +
2488            // " Title=" + Integer.toHexString(mTitleColor));
2489
2490            if (mTitleColor == 0) {
2491                mTitleColor = mTextColor;
2492            }
2493
2494            if (mTitle != null) {
2495                setTitle(mTitle);
2496            }
2497            setTitleColor(mTitleColor);
2498        }
2499
2500        mDecor.finishChanging();
2501
2502        return contentParent;
2503    }
2504
2505    /** @hide */
2506    public void alwaysReadCloseOnTouchAttr() {
2507        mAlwaysReadCloseOnTouchAttr = true;
2508    }
2509
2510    private void installDecor() {
2511        if (mDecor == null) {
2512            mDecor = generateDecor();
2513            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
2514            mDecor.setIsRootNamespace(true);
2515        }
2516        if (mContentParent == null) {
2517            mContentParent = generateLayout(mDecor);
2518
2519            mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
2520            if (mTitleView != null) {
2521                if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
2522                    View titleContainer = findViewById(com.android.internal.R.id.title_container);
2523                    if (titleContainer != null) {
2524                        titleContainer.setVisibility(View.GONE);
2525                    } else {
2526                        mTitleView.setVisibility(View.GONE);
2527                    }
2528                    if (mContentParent instanceof FrameLayout) {
2529                        ((FrameLayout)mContentParent).setForeground(null);
2530                    }
2531                } else {
2532                    mTitleView.setText(mTitle);
2533                }
2534            } else {
2535                mActionBar = (ActionBarView) findViewById(com.android.internal.R.id.action_bar);
2536                if (mActionBar != null) {
2537                    if (mActionBar.getTitle() == null) {
2538                        mActionBar.setWindowTitle(mTitle);
2539                    }
2540                    final int localFeatures = getLocalFeatures();
2541                    if ((localFeatures & (1 << FEATURE_PROGRESS)) != 0) {
2542                        mActionBar.initProgress();
2543                    }
2544                    if ((localFeatures & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2545                        mActionBar.initIndeterminateProgress();
2546                    }
2547                    // Post the panel invalidate for later; avoid application onCreateOptionsMenu
2548                    // being called in the middle of onCreate or similar.
2549                    mDecor.post(new Runnable() {
2550                        public void run() {
2551                            if (!isDestroyed()) {
2552                                invalidatePanelMenu(FEATURE_ACTION_BAR);
2553                            }
2554                        }
2555                    });
2556                }
2557            }
2558        }
2559    }
2560
2561    private Drawable loadImageURI(Uri uri) {
2562        try {
2563            return Drawable.createFromStream(
2564                    getContext().getContentResolver().openInputStream(uri), null);
2565        } catch (Exception e) {
2566            Log.w(TAG, "Unable to open content: " + uri);
2567        }
2568        return null;
2569    }
2570
2571    private DrawableFeatureState getDrawableState(int featureId, boolean required) {
2572        if ((getFeatures() & (1 << featureId)) == 0) {
2573            if (!required) {
2574                return null;
2575            }
2576            throw new RuntimeException("The feature has not been requested");
2577        }
2578
2579        DrawableFeatureState[] ar;
2580        if ((ar = mDrawables) == null || ar.length <= featureId) {
2581            DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1];
2582            if (ar != null) {
2583                System.arraycopy(ar, 0, nar, 0, ar.length);
2584            }
2585            mDrawables = ar = nar;
2586        }
2587
2588        DrawableFeatureState st = ar[featureId];
2589        if (st == null) {
2590            ar[featureId] = st = new DrawableFeatureState(featureId);
2591        }
2592        return st;
2593    }
2594
2595    /**
2596     * Gets a panel's state based on its feature ID.
2597     *
2598     * @param featureId The feature ID of the panel.
2599     * @param required Whether the panel is required (if it is required and it
2600     *            isn't in our features, this throws an exception).
2601     * @return The panel state.
2602     */
2603    private PanelFeatureState getPanelState(int featureId, boolean required) {
2604        return getPanelState(featureId, required, null);
2605    }
2606
2607    /**
2608     * Gets a panel's state based on its feature ID.
2609     *
2610     * @param featureId The feature ID of the panel.
2611     * @param required Whether the panel is required (if it is required and it
2612     *            isn't in our features, this throws an exception).
2613     * @param convertPanelState Optional: If the panel state does not exist, use
2614     *            this as the panel state.
2615     * @return The panel state.
2616     */
2617    private PanelFeatureState getPanelState(int featureId, boolean required,
2618            PanelFeatureState convertPanelState) {
2619        if ((getFeatures() & (1 << featureId)) == 0) {
2620            if (!required) {
2621                return null;
2622            }
2623            throw new RuntimeException("The feature has not been requested");
2624        }
2625
2626        PanelFeatureState[] ar;
2627        if ((ar = mPanels) == null || ar.length <= featureId) {
2628            PanelFeatureState[] nar = new PanelFeatureState[featureId + 1];
2629            if (ar != null) {
2630                System.arraycopy(ar, 0, nar, 0, ar.length);
2631            }
2632            mPanels = ar = nar;
2633        }
2634
2635        PanelFeatureState st = ar[featureId];
2636        if (st == null) {
2637            ar[featureId] = st = (convertPanelState != null)
2638                    ? convertPanelState
2639                    : new PanelFeatureState(featureId);
2640        }
2641        return st;
2642    }
2643
2644    @Override
2645    public final void setChildDrawable(int featureId, Drawable drawable) {
2646        DrawableFeatureState st = getDrawableState(featureId, true);
2647        st.child = drawable;
2648        updateDrawable(featureId, st, false);
2649    }
2650
2651    @Override
2652    public final void setChildInt(int featureId, int value) {
2653        updateInt(featureId, value, false);
2654    }
2655
2656    @Override
2657    public boolean isShortcutKey(int keyCode, KeyEvent event) {
2658        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
2659        return st.menu != null && st.menu.isShortcutKey(keyCode, event);
2660    }
2661
2662    private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) {
2663        // Do nothing if the decor is not yet installed... an update will
2664        // need to be forced when we eventually become active.
2665        if (mContentParent == null) {
2666            return;
2667        }
2668
2669        final int featureMask = 1 << featureId;
2670
2671        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2672            return;
2673        }
2674
2675        Drawable drawable = null;
2676        if (st != null) {
2677            drawable = st.child;
2678            if (drawable == null)
2679                drawable = st.local;
2680            if (drawable == null)
2681                drawable = st.def;
2682        }
2683        if ((getLocalFeatures() & featureMask) == 0) {
2684            if (getContainer() != null) {
2685                if (isActive() || fromResume) {
2686                    getContainer().setChildDrawable(featureId, drawable);
2687                }
2688            }
2689        } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) {
2690            // System.out.println("Drawable changed: old=" + st.cur
2691            // + ", new=" + drawable);
2692            st.cur = drawable;
2693            st.curAlpha = st.alpha;
2694            onDrawableChanged(featureId, drawable, st.alpha);
2695        }
2696    }
2697
2698    private void updateInt(int featureId, int value, boolean fromResume) {
2699
2700        // Do nothing if the decor is not yet installed... an update will
2701        // need to be forced when we eventually become active.
2702        if (mContentParent == null) {
2703            return;
2704        }
2705
2706        final int featureMask = 1 << featureId;
2707
2708        if ((getFeatures() & featureMask) == 0 && !fromResume) {
2709            return;
2710        }
2711
2712        if ((getLocalFeatures() & featureMask) == 0) {
2713            if (getContainer() != null) {
2714                getContainer().setChildInt(featureId, value);
2715            }
2716        } else {
2717            onIntChanged(featureId, value);
2718        }
2719    }
2720
2721    private ImageView getLeftIconView() {
2722        if (mLeftIconView != null) {
2723            return mLeftIconView;
2724        }
2725        if (mContentParent == null) {
2726            installDecor();
2727        }
2728        return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon));
2729    }
2730
2731    private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) {
2732        if (mCircularProgressBar != null) {
2733            return mCircularProgressBar;
2734        }
2735        if (mContentParent == null && shouldInstallDecor) {
2736            installDecor();
2737        }
2738        mCircularProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_circular);
2739        if (mCircularProgressBar != null) {
2740            mCircularProgressBar.setVisibility(View.INVISIBLE);
2741        }
2742        return mCircularProgressBar;
2743    }
2744
2745    private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) {
2746        if (mHorizontalProgressBar != null) {
2747            return mHorizontalProgressBar;
2748        }
2749        if (mContentParent == null && shouldInstallDecor) {
2750            installDecor();
2751        }
2752        mHorizontalProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_horizontal);
2753        if (mHorizontalProgressBar != null) {
2754            mHorizontalProgressBar.setVisibility(View.INVISIBLE);
2755        }
2756        return mHorizontalProgressBar;
2757    }
2758
2759    private ImageView getRightIconView() {
2760        if (mRightIconView != null) {
2761            return mRightIconView;
2762        }
2763        if (mContentParent == null) {
2764            installDecor();
2765        }
2766        return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon));
2767    }
2768
2769    /**
2770     * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)}
2771     * callback. This method will grab whatever extra state is needed for the
2772     * callback that isn't given in the parameters. If the panel is not open,
2773     * this will not perform the callback.
2774     *
2775     * @param featureId Feature ID of the panel that was closed. Must be given.
2776     * @param panel Panel that was closed. Optional but useful if there is no
2777     *            menu given.
2778     * @param menu The menu that was closed. Optional, but give if you have.
2779     */
2780    private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) {
2781        final Callback cb = getCallback();
2782        if (cb == null)
2783            return;
2784
2785        // Try to get a menu
2786        if (menu == null) {
2787            // Need a panel to grab the menu, so try to get that
2788            if (panel == null) {
2789                if ((featureId >= 0) && (featureId < mPanels.length)) {
2790                    panel = mPanels[featureId];
2791                }
2792            }
2793
2794            if (panel != null) {
2795                // menu still may be null, which is okay--we tried our best
2796                menu = panel.menu;
2797            }
2798        }
2799
2800        // If the panel is not open, do not callback
2801        if ((panel != null) && (!panel.isOpen))
2802            return;
2803
2804        cb.onPanelClosed(featureId, menu);
2805    }
2806
2807    /**
2808     * Helper method for adding launch-search to most applications. Opens the
2809     * search window using default settings.
2810     *
2811     * @return true if search window opened
2812     */
2813    private boolean launchDefaultSearch() {
2814        final Callback cb = getCallback();
2815        if (cb == null) {
2816            return false;
2817        } else {
2818            sendCloseSystemWindows("search");
2819            return cb.onSearchRequested();
2820        }
2821    }
2822
2823    @Override
2824    public void setVolumeControlStream(int streamType) {
2825        mVolumeControlStreamType = streamType;
2826    }
2827
2828    @Override
2829    public int getVolumeControlStream() {
2830        return mVolumeControlStreamType;
2831    }
2832
2833    private static final class DrawableFeatureState {
2834        DrawableFeatureState(int _featureId) {
2835            featureId = _featureId;
2836        }
2837
2838        final int featureId;
2839
2840        int resid;
2841
2842        Uri uri;
2843
2844        Drawable local;
2845
2846        Drawable child;
2847
2848        Drawable def;
2849
2850        Drawable cur;
2851
2852        int alpha = 255;
2853
2854        int curAlpha = 255;
2855    }
2856
2857    private static final class PanelFeatureState {
2858
2859        /** Feature ID for this panel. */
2860        int featureId;
2861
2862        // Information pulled from the style for this panel.
2863
2864        int background;
2865
2866        /** The background when the panel spans the entire available width. */
2867        int fullBackground;
2868
2869        int gravity;
2870
2871        int x;
2872
2873        int y;
2874
2875        int windowAnimations;
2876
2877        /** Dynamic state of the panel. */
2878        DecorView decorView;
2879
2880        /** The panel that was returned by onCreatePanelView(). */
2881        View createdPanelView;
2882
2883        /** The panel that we are actually showing. */
2884        View shownPanelView;
2885
2886        /** Use {@link #setMenu} to set this. */
2887        Menu menu;
2888
2889        /**
2890         * Whether the panel has been prepared (see
2891         * {@link PhoneWindow#preparePanel}).
2892         */
2893        boolean isPrepared;
2894
2895        /**
2896         * Whether an item's action has been performed. This happens in obvious
2897         * scenarios (user clicks on menu item), but can also happen with
2898         * chording menu+(shortcut key).
2899         */
2900        boolean isHandled;
2901
2902        boolean isOpen;
2903
2904        /**
2905         * True if the menu is in expanded mode, false if the menu is in icon
2906         * mode
2907         */
2908        boolean isInExpandedMode;
2909
2910        public boolean qwertyMode;
2911
2912        boolean refreshDecorView;
2913
2914        boolean refreshMenuContent;
2915
2916        boolean wasLastOpen;
2917
2918        boolean wasLastExpanded;
2919
2920        /**
2921         * Contains the state of the menu when told to freeze.
2922         */
2923        Bundle frozenMenuState;
2924
2925        PanelFeatureState(int featureId) {
2926            this.featureId = featureId;
2927
2928            refreshDecorView = false;
2929        }
2930
2931        void setStyle(Context context) {
2932            TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
2933            background = a.getResourceId(
2934                    com.android.internal.R.styleable.Theme_panelBackground, 0);
2935            fullBackground = a.getResourceId(
2936                    com.android.internal.R.styleable.Theme_panelFullBackground, 0);
2937            windowAnimations = a.getResourceId(
2938                    com.android.internal.R.styleable.Theme_windowAnimationStyle, 0);
2939            a.recycle();
2940        }
2941
2942        void setMenu(Menu menu) {
2943            this.menu = menu;
2944
2945            if (frozenMenuState != null) {
2946                ((MenuBuilder) menu).restoreHierarchyState(frozenMenuState);
2947                frozenMenuState = null;
2948            }
2949        }
2950
2951        Parcelable onSaveInstanceState() {
2952            SavedState savedState = new SavedState();
2953            savedState.featureId = featureId;
2954            savedState.isOpen = isOpen;
2955            savedState.isInExpandedMode = isInExpandedMode;
2956
2957            if (menu != null) {
2958                savedState.menuState = new Bundle();
2959                ((MenuBuilder) menu).saveHierarchyState(savedState.menuState);
2960            }
2961
2962            return savedState;
2963        }
2964
2965        void onRestoreInstanceState(Parcelable state) {
2966            SavedState savedState = (SavedState) state;
2967            featureId = savedState.featureId;
2968            wasLastOpen = savedState.isOpen;
2969            wasLastExpanded = savedState.isInExpandedMode;
2970            frozenMenuState = savedState.menuState;
2971
2972            /*
2973             * A LocalActivityManager keeps the same instance of this class around.
2974             * The first time the menu is being shown after restoring, the
2975             * Activity.onCreateOptionsMenu should be called. But, if it is the
2976             * same instance then menu != null and we won't call that method.
2977             * So, clear this.  Also clear any cached views.
2978             */
2979            menu = null;
2980            createdPanelView = null;
2981            shownPanelView = null;
2982            decorView = null;
2983        }
2984
2985        private static class SavedState implements Parcelable {
2986            int featureId;
2987            boolean isOpen;
2988            boolean isInExpandedMode;
2989            Bundle menuState;
2990
2991            public int describeContents() {
2992                return 0;
2993            }
2994
2995            public void writeToParcel(Parcel dest, int flags) {
2996                dest.writeInt(featureId);
2997                dest.writeInt(isOpen ? 1 : 0);
2998                dest.writeInt(isInExpandedMode ? 1 : 0);
2999
3000                if (isOpen) {
3001                    dest.writeBundle(menuState);
3002                }
3003            }
3004
3005            private static SavedState readFromParcel(Parcel source) {
3006                SavedState savedState = new SavedState();
3007                savedState.featureId = source.readInt();
3008                savedState.isOpen = source.readInt() == 1;
3009                savedState.isInExpandedMode = source.readInt() == 1;
3010
3011                if (savedState.isOpen) {
3012                    savedState.menuState = source.readBundle();
3013                }
3014
3015                return savedState;
3016            }
3017
3018            public static final Parcelable.Creator<SavedState> CREATOR
3019                    = new Parcelable.Creator<SavedState>() {
3020                public SavedState createFromParcel(Parcel in) {
3021                    return readFromParcel(in);
3022                }
3023
3024                public SavedState[] newArray(int size) {
3025                    return new SavedState[size];
3026                }
3027            };
3028        }
3029
3030    }
3031
3032    /**
3033     * Simple implementation of MenuBuilder.Callback that:
3034     * <li> Opens a submenu when selected.
3035     * <li> Calls back to the callback's onMenuItemSelected when an item is
3036     * selected.
3037     */
3038    private final class DialogMenuCallback implements MenuBuilder.Callback {
3039        private int mFeatureId;
3040        private MenuDialogHelper mSubMenuHelper;
3041
3042        public DialogMenuCallback(int featureId) {
3043            mFeatureId = featureId;
3044        }
3045
3046        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
3047            if (allMenusAreClosing) {
3048                Callback callback = getCallback();
3049                if (callback != null) callback.onPanelClosed(mFeatureId, menu);
3050
3051                if (menu == mContextMenu) {
3052                    dismissContextMenu();
3053                }
3054
3055                // Dismiss the submenu, if it is showing
3056                if (mSubMenuHelper != null) {
3057                    mSubMenuHelper.dismiss();
3058                    mSubMenuHelper = null;
3059                }
3060            }
3061        }
3062
3063        public void onCloseSubMenu(SubMenuBuilder menu) {
3064            Callback callback = getCallback();
3065            if (callback != null) callback.onPanelClosed(mFeatureId, menu.getRootMenu());
3066        }
3067
3068        public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
3069            Callback callback = getCallback();
3070            return (callback != null) && callback.onMenuItemSelected(mFeatureId, item);
3071        }
3072
3073        public void onMenuModeChange(MenuBuilder menu) {
3074        }
3075
3076        public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
3077            // Set a simple callback for the submenu
3078            subMenu.setCallback(this);
3079
3080            // The window manager will give us a valid window token
3081            mSubMenuHelper = new MenuDialogHelper(subMenu);
3082            mSubMenuHelper.show(null);
3083
3084            return true;
3085        }
3086    }
3087
3088    void sendCloseSystemWindows() {
3089        PhoneWindowManager.sendCloseSystemWindows(getContext(), null);
3090    }
3091
3092    void sendCloseSystemWindows(String reason) {
3093        PhoneWindowManager.sendCloseSystemWindows(getContext(), reason);
3094    }
3095
3096    private class ActionButtonSubmenu extends MenuPopupHelper implements Runnable {
3097        private SubMenuBuilder mSubMenu;
3098
3099        public ActionButtonSubmenu(Context context, SubMenuBuilder subMenu) {
3100            super(context, subMenu);
3101            mSubMenu = subMenu;
3102
3103            MenuBuilder parentMenu = subMenu.getRootMenu();
3104            MenuItemImpl item = (MenuItemImpl) subMenu.getItem();
3105            if (!item.isActionButton()) {
3106                // Give a reasonable anchor to nested submenus.
3107                ActionMenuView amv = (ActionMenuView) parentMenu.getMenuView(
3108                        MenuBuilder.TYPE_ACTION_BUTTON, null);
3109
3110                View anchor = amv.getOverflowButton();
3111                if (anchor == null) {
3112                    anchor = amv;
3113                }
3114                setAnchorView(anchor);
3115            }
3116        }
3117
3118        @Override
3119        public void onDismiss() {
3120            super.onDismiss();
3121            mSubMenu.getCallback().onCloseSubMenu(mSubMenu);
3122            mActionButtonPopup = null;
3123        }
3124
3125        @Override
3126        public void run() {
3127            if (tryShow()) {
3128                Callback cb = getCallback();
3129                if (cb != null) {
3130                    cb.onMenuOpened(FEATURE_ACTION_BAR, mSubMenu);
3131                }
3132            }
3133        }
3134    }
3135}
3136