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