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