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