PhoneWindow.java revision f1f5054f7aed6c06657955e43a680ed54c463986
1/*
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16package com.android.internal.policy.impl;
17
18import static android.view.View.MeasureSpec.AT_MOST;
19import static android.view.View.MeasureSpec.EXACTLY;
20import static android.view.View.MeasureSpec.getMode;
21import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
22import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
23import static android.view.WindowManager.LayoutParams.*;
24
25import com.android.internal.view.RootViewSurfaceTaker;
26import com.android.internal.view.StandaloneActionMode;
27import com.android.internal.view.menu.ContextMenuBuilder;
28import com.android.internal.view.menu.IconMenuPresenter;
29import com.android.internal.view.menu.ListMenuPresenter;
30import com.android.internal.view.menu.MenuBuilder;
31import com.android.internal.view.menu.MenuDialogHelper;
32import com.android.internal.view.menu.MenuPresenter;
33import com.android.internal.view.menu.MenuView;
34import com.android.internal.widget.ActionBarContainer;
35import com.android.internal.widget.ActionBarContextView;
36import com.android.internal.widget.ActionBarOverlayLayout;
37import com.android.internal.widget.ActionBarView;
38
39import android.app.KeyguardManager;
40import android.content.Context;
41import android.content.pm.ActivityInfo;
42import android.content.res.Configuration;
43import android.content.res.Resources;
44import android.content.res.TypedArray;
45import android.graphics.Canvas;
46import android.graphics.PixelFormat;
47import android.graphics.Rect;
48import android.graphics.drawable.Drawable;
49import android.media.AudioManager;
50import android.net.Uri;
51import android.os.Bundle;
52import android.os.Handler;
53import android.os.Parcel;
54import android.os.Parcelable;
55import android.os.RemoteException;
56import android.os.ServiceManager;
57import android.util.AndroidRuntimeException;
58import android.util.DisplayMetrics;
59import android.util.EventLog;
60import android.util.Log;
61import android.util.Slog;
62import android.util.SparseArray;
63import android.util.TypedValue;
64import android.view.ActionMode;
65import android.view.ContextThemeWrapper;
66import android.view.Gravity;
67import android.view.IRotationWatcher;
68import android.view.IWindowManager;
69import android.view.InputQueue;
70import android.view.KeyCharacterMap;
71import android.view.KeyEvent;
72import android.view.LayoutInflater;
73import android.view.Menu;
74import android.view.MenuItem;
75import android.view.MotionEvent;
76import android.view.SurfaceHolder;
77import android.view.View;
78import android.view.ViewGroup;
79import android.view.ViewManager;
80import android.view.ViewParent;
81import android.view.ViewStub;
82import android.view.Window;
83import android.view.WindowManager;
84import android.view.accessibility.AccessibilityEvent;
85import android.view.accessibility.AccessibilityManager;
86import android.view.animation.Animation;
87import android.view.animation.AnimationUtils;
88import android.widget.FrameLayout;
89import android.widget.ImageView;
90import android.widget.PopupWindow;
91import android.widget.ProgressBar;
92import android.widget.TextView;
93
94import java.lang.ref.WeakReference;
95import java.util.ArrayList;
96
97/**
98 * Android-specific Window.
99 * <p>
100 * todo: need to pull the generic functionality out into a base class
101 * in android.widget.
102 */
103public class PhoneWindow extends Window implements MenuBuilder.Callback {
104
105    private final static String TAG = "PhoneWindow";
106
107    private final static boolean SWEEP_OPEN_MENU = false;
108
109    /**
110     * Simple callback used by the context menu and its submenus. The options
111     * menu submenus do not use this (their behavior is more complex).
112     */
113    final DialogMenuCallback mContextMenuCallback = new DialogMenuCallback(FEATURE_CONTEXT_MENU);
114
115    final TypedValue mMinWidthMajor = new TypedValue();
116    final TypedValue mMinWidthMinor = new TypedValue();
117    TypedValue mFixedWidthMajor;
118    TypedValue mFixedWidthMinor;
119    TypedValue mFixedHeightMajor;
120    TypedValue mFixedHeightMinor;
121
122    // This is the top-level view of the window, containing the window decor.
123    private DecorView mDecor;
124
125    // This is the view in which the window contents are placed. It is either
126    // mDecor itself, or a child of mDecor where the contents go.
127    private ViewGroup mContentParent;
128
129    SurfaceHolder.Callback2 mTakeSurfaceCallback;
130
131    InputQueue.Callback mTakeInputQueueCallback;
132
133    private boolean mIsFloating;
134
135    private LayoutInflater mLayoutInflater;
136
137    private TextView mTitleView;
138
139    private ActionBarView mActionBar;
140    private ActionMenuPresenterCallback mActionMenuPresenterCallback;
141    private PanelMenuPresenterCallback mPanelMenuPresenterCallback;
142
143    // The icon resource has been explicitly set elsewhere
144    // and should not be overwritten with a default.
145    static final int FLAG_RESOURCE_SET_ICON = 1 << 0;
146
147    // The logo resource has been explicitly set elsewhere
148    // and should not be overwritten with a default.
149    static final int FLAG_RESOURCE_SET_LOGO = 1 << 1;
150
151    // The icon resource is currently configured to use the system fallback
152    // as no default was previously specified. Anything can override this.
153    static final int FLAG_RESOURCE_SET_ICON_FALLBACK = 1 << 2;
154
155    int mResourcesSetFlags;
156    int mIconRes;
157    int mLogoRes;
158
159    private DrawableFeatureState[] mDrawables;
160
161    private PanelFeatureState[] mPanels;
162
163    /**
164     * The panel that is prepared or opened (the most recent one if there are
165     * multiple panels). Shortcuts will go to this panel. It gets set in
166     * {@link #preparePanel} and cleared in {@link #closePanel}.
167     */
168    private PanelFeatureState mPreparedPanel;
169
170    /**
171     * The keycode that is currently held down (as a modifier) for chording. If
172     * this is 0, there is no key held down.
173     */
174    private int mPanelChordingKey;
175
176    private ImageView mLeftIconView;
177
178    private ImageView mRightIconView;
179
180    private ProgressBar mCircularProgressBar;
181
182    private ProgressBar mHorizontalProgressBar;
183
184    private int mBackgroundResource = 0;
185
186    private Drawable mBackgroundDrawable;
187
188    private int mFrameResource = 0;
189
190    private int mTextColor = 0;
191
192    private CharSequence mTitle = null;
193
194    private int mTitleColor = 0;
195
196    private boolean mAlwaysReadCloseOnTouchAttr = false;
197
198    private ContextMenuBuilder mContextMenu;
199    private MenuDialogHelper mContextMenuHelper;
200    private boolean mClosingActionMenu;
201
202    private int mVolumeControlStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE;
203
204    private AudioManager mAudioManager;
205    private KeyguardManager mKeyguardManager;
206
207    private int mUiOptions = 0;
208
209    private boolean mInvalidatePanelMenuPosted;
210    private int mInvalidatePanelMenuFeatures;
211    private final Runnable mInvalidatePanelMenuRunnable = new Runnable() {
212        @Override public void run() {
213            for (int i = 0; i <= FEATURE_MAX; i++) {
214                if ((mInvalidatePanelMenuFeatures & 1 << i) != 0) {
215                    doInvalidatePanelMenu(i);
216                }
217            }
218            mInvalidatePanelMenuPosted = false;
219            mInvalidatePanelMenuFeatures = 0;
220        }
221    };
222
223    static class WindowManagerHolder {
224        static final IWindowManager sWindowManager = IWindowManager.Stub.asInterface(
225                ServiceManager.getService("window"));
226    }
227
228    static final RotationWatcher sRotationWatcher = new RotationWatcher();
229
230    public PhoneWindow(Context context) {
231        super(context);
232        mLayoutInflater = LayoutInflater.from(context);
233    }
234
235    @Override
236    public final void setContainer(Window container) {
237        super.setContainer(container);
238    }
239
240    @Override
241    public boolean requestFeature(int featureId) {
242        if (mContentParent != null) {
243            throw new AndroidRuntimeException("requestFeature() must be called before adding content");
244        }
245        final int features = getFeatures();
246        if ((features != DEFAULT_FEATURES) && (featureId == FEATURE_CUSTOM_TITLE)) {
247
248            /* Another feature is enabled and the user is trying to enable the custom title feature */
249            throw new AndroidRuntimeException("You cannot combine custom titles with other title features");
250        }
251        if (((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) &&
252                (featureId != FEATURE_CUSTOM_TITLE) && (featureId != FEATURE_ACTION_MODE_OVERLAY)) {
253
254            /* Custom title feature is enabled and the user is trying to enable another feature */
255            throw new AndroidRuntimeException("You cannot combine custom titles with other title features");
256        }
257        if ((features & (1 << FEATURE_NO_TITLE)) != 0 && featureId == FEATURE_ACTION_BAR) {
258            return false; // Ignore. No title dominates.
259        }
260        if ((features & (1 << FEATURE_ACTION_BAR)) != 0 && featureId == FEATURE_NO_TITLE) {
261            // Remove the action bar feature if we have no title. No title dominates.
262            removeFeature(FEATURE_ACTION_BAR);
263        }
264        return super.requestFeature(featureId);
265    }
266
267    @Override
268    public void setUiOptions(int uiOptions) {
269        mUiOptions = uiOptions;
270    }
271
272    @Override
273    public void setUiOptions(int uiOptions, int mask) {
274        mUiOptions = (mUiOptions & ~mask) | (uiOptions & mask);
275    }
276
277    @Override
278    public void setContentView(int layoutResID) {
279        if (mContentParent == null) {
280            installDecor();
281        } else {
282            mContentParent.removeAllViews();
283        }
284        mLayoutInflater.inflate(layoutResID, mContentParent);
285        final Callback cb = getCallback();
286        if (cb != null && !isDestroyed()) {
287            cb.onContentChanged();
288        }
289    }
290
291    @Override
292    public void setContentView(View view) {
293        setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
294    }
295
296    @Override
297    public void setContentView(View view, ViewGroup.LayoutParams params) {
298        if (mContentParent == null) {
299            installDecor();
300        } else {
301            mContentParent.removeAllViews();
302        }
303        mContentParent.addView(view, params);
304        final Callback cb = getCallback();
305        if (cb != null && !isDestroyed()) {
306            cb.onContentChanged();
307        }
308    }
309
310    @Override
311    public void addContentView(View view, ViewGroup.LayoutParams params) {
312        if (mContentParent == null) {
313            installDecor();
314        }
315        mContentParent.addView(view, params);
316        final Callback cb = getCallback();
317        if (cb != null && !isDestroyed()) {
318            cb.onContentChanged();
319        }
320    }
321
322    @Override
323    public View getCurrentFocus() {
324        return mDecor != null ? mDecor.findFocus() : null;
325    }
326
327    @Override
328    public void takeSurface(SurfaceHolder.Callback2 callback) {
329        mTakeSurfaceCallback = callback;
330    }
331
332    public void takeInputQueue(InputQueue.Callback callback) {
333        mTakeInputQueueCallback = callback;
334    }
335
336    @Override
337    public boolean isFloating() {
338        return mIsFloating;
339    }
340
341    /**
342     * Return a LayoutInflater instance that can be used to inflate XML view layout
343     * resources for use in this Window.
344     *
345     * @return LayoutInflater The shared LayoutInflater.
346     */
347    @Override
348    public LayoutInflater getLayoutInflater() {
349        return mLayoutInflater;
350    }
351
352    @Override
353    public void setTitle(CharSequence title) {
354        if (mTitleView != null) {
355            mTitleView.setText(title);
356        } else if (mActionBar != null) {
357            mActionBar.setWindowTitle(title);
358        }
359        mTitle = title;
360    }
361
362    @Override
363    public void setTitleColor(int textColor) {
364        if (mTitleView != null) {
365            mTitleView.setTextColor(textColor);
366        }
367        mTitleColor = textColor;
368    }
369
370    /**
371     * Prepares the panel to either be opened or chorded. This creates the Menu
372     * instance for the panel and populates it via the Activity callbacks.
373     *
374     * @param st The panel state to prepare.
375     * @param event The event that triggered the preparing of the panel.
376     * @return Whether the panel was prepared. If the panel should not be shown,
377     *         returns false.
378     */
379    public final boolean preparePanel(PanelFeatureState st, KeyEvent event) {
380        if (isDestroyed()) {
381            return false;
382        }
383
384        // Already prepared (isPrepared will be reset to false later)
385        if (st.isPrepared) {
386            return true;
387        }
388
389        if ((mPreparedPanel != null) && (mPreparedPanel != st)) {
390            // Another Panel is prepared and possibly open, so close it
391            closePanel(mPreparedPanel, false);
392        }
393
394        final Callback cb = getCallback();
395
396        if (cb != null) {
397            st.createdPanelView = cb.onCreatePanelView(st.featureId);
398        }
399
400        final boolean isActionBarMenu =
401                (st.featureId == FEATURE_OPTIONS_PANEL || st.featureId == FEATURE_ACTION_BAR);
402
403        if (isActionBarMenu && mActionBar != null) {
404            // Enforce ordering guarantees around events so that the action bar never
405            // dispatches menu-related events before the panel is prepared.
406            mActionBar.setMenuPrepared();
407        }
408
409        if (st.createdPanelView == null) {
410            // Init the panel state's menu--return false if init failed
411            if (st.menu == null || st.refreshMenuContent) {
412                if (st.menu == null) {
413                    if (!initializePanelMenu(st) || (st.menu == null)) {
414                        return false;
415                    }
416                }
417
418                if (isActionBarMenu && mActionBar != null) {
419                    if (mActionMenuPresenterCallback == null) {
420                        mActionMenuPresenterCallback = new ActionMenuPresenterCallback();
421                    }
422                    mActionBar.setMenu(st.menu, mActionMenuPresenterCallback);
423                }
424
425                // Call callback, and return if it doesn't want to display menu.
426
427                // Creating the panel menu will involve a lot of manipulation;
428                // don't dispatch change events to presenters until we're done.
429                st.menu.stopDispatchingItemsChanged();
430                if ((cb == null) || !cb.onCreatePanelMenu(st.featureId, st.menu)) {
431                    // Ditch the menu created above
432                    st.setMenu(null);
433
434                    if (isActionBarMenu && mActionBar != null) {
435                        // Don't show it in the action bar either
436                        mActionBar.setMenu(null, mActionMenuPresenterCallback);
437                    }
438
439                    return false;
440                }
441
442                st.refreshMenuContent = false;
443            }
444
445            // Callback and return if the callback does not want to show the menu
446
447            // Preparing the panel menu can involve a lot of manipulation;
448            // don't dispatch change events to presenters until we're done.
449            st.menu.stopDispatchingItemsChanged();
450
451            // Restore action view state before we prepare. This gives apps
452            // an opportunity to override frozen/restored state in onPrepare.
453            if (st.frozenActionViewState != null) {
454                st.menu.restoreActionViewStates(st.frozenActionViewState);
455                st.frozenActionViewState = null;
456            }
457
458            if (!cb.onPreparePanel(st.featureId, st.createdPanelView, st.menu)) {
459                if (isActionBarMenu && mActionBar != null) {
460                    // The app didn't want to show the menu for now but it still exists.
461                    // Clear it out of the action bar.
462                    mActionBar.setMenu(null, mActionMenuPresenterCallback);
463                }
464                st.menu.startDispatchingItemsChanged();
465                return false;
466            }
467
468            // Set the proper keymap
469            KeyCharacterMap kmap = KeyCharacterMap.load(
470                    event != null ? event.getDeviceId() : KeyCharacterMap.VIRTUAL_KEYBOARD);
471            st.qwertyMode = kmap.getKeyboardType() != KeyCharacterMap.NUMERIC;
472            st.menu.setQwertyMode(st.qwertyMode);
473            st.menu.startDispatchingItemsChanged();
474        }
475
476        // Set other state
477        st.isPrepared = true;
478        st.isHandled = false;
479        mPreparedPanel = st;
480
481        return true;
482    }
483
484    @Override
485    public void onConfigurationChanged(Configuration newConfig) {
486        // Action bars handle their own menu state
487        if (mActionBar == null) {
488            PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
489            if ((st != null) && (st.menu != null)) {
490                if (st.isOpen) {
491                    // Freeze state
492                    final Bundle state = new Bundle();
493                    if (st.iconMenuPresenter != null) {
494                        st.iconMenuPresenter.saveHierarchyState(state);
495                    }
496                    if (st.listMenuPresenter != null) {
497                        st.listMenuPresenter.saveHierarchyState(state);
498                    }
499
500                    // Remove the menu views since they need to be recreated
501                    // according to the new configuration
502                    clearMenuViews(st);
503
504                    // Re-open the same menu
505                    reopenMenu(false);
506
507                    // Restore state
508                    if (st.iconMenuPresenter != null) {
509                        st.iconMenuPresenter.restoreHierarchyState(state);
510                    }
511                    if (st.listMenuPresenter != null) {
512                        st.listMenuPresenter.restoreHierarchyState(state);
513                    }
514
515                } else {
516                    // Clear menu views so on next menu opening, it will use
517                    // the proper layout
518                    clearMenuViews(st);
519                }
520            }
521        }
522    }
523
524    private static void clearMenuViews(PanelFeatureState st) {
525        // This can be called on config changes, so we should make sure
526        // the views will be reconstructed based on the new orientation, etc.
527
528        // Allow the callback to create a new panel view
529        st.createdPanelView = null;
530
531        // Causes the decor view to be recreated
532        st.refreshDecorView = true;
533
534        st.clearMenuPresenters();
535    }
536
537    @Override
538    public final void openPanel(int featureId, KeyEvent event) {
539        if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
540                mActionBar.isOverflowReserved()) {
541            if (mActionBar.getVisibility() == View.VISIBLE) {
542                mActionBar.showOverflowMenu();
543            }
544        } else {
545            openPanel(getPanelState(featureId, true), event);
546        }
547    }
548
549    private void openPanel(PanelFeatureState st, KeyEvent event) {
550        // System.out.println("Open panel: isOpen=" + st.isOpen);
551
552        // Already open, return
553        Slog.d(TAG, "openPanel: b9404689 entry, st=" + st + " decorView=" + st.decorView);
554        if (st.isOpen || isDestroyed()) {
555            return;
556        }
557
558        // Don't open an options panel for honeycomb apps on xlarge devices.
559        // (The app should be using an action bar for menu items.)
560        if (st.featureId == FEATURE_OPTIONS_PANEL) {
561            Context context = getContext();
562            Configuration config = context.getResources().getConfiguration();
563            boolean isXLarge = (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
564                    Configuration.SCREENLAYOUT_SIZE_XLARGE;
565            boolean isHoneycombApp = context.getApplicationInfo().targetSdkVersion >=
566                    android.os.Build.VERSION_CODES.HONEYCOMB;
567
568            if (isXLarge && isHoneycombApp) {
569                return;
570            }
571        }
572
573        Callback cb = getCallback();
574        if ((cb != null) && (!cb.onMenuOpened(st.featureId, st.menu))) {
575            // Callback doesn't want the menu to open, reset any state
576            closePanel(st, true);
577            return;
578        }
579
580        final WindowManager wm = getWindowManager();
581        if (wm == null) {
582            return;
583        }
584
585        // Prepare panel (should have been done before, but just in case)
586        if (!preparePanel(st, event)) {
587            return;
588        }
589
590        int width = WRAP_CONTENT;
591        if (st.decorView == null || st.refreshDecorView) {
592            if (st.decorView == null) {
593                // Initialize the panel decor, this will populate st.decorView
594                if (!initializePanelDecor(st) || (st.decorView == null))
595                    return;
596            } else if (st.refreshDecorView && (st.decorView.getChildCount() > 0)) {
597                // Decor needs refreshing, so remove its views
598                st.decorView.removeAllViews();
599            }
600
601            // This will populate st.shownPanelView
602            if (!initializePanelContent(st) || !st.hasPanelItems()) {
603                return;
604            }
605
606            ViewGroup.LayoutParams lp = st.shownPanelView.getLayoutParams();
607            if (lp == null) {
608                lp = new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
609            }
610
611            int backgroundResId;
612            if (lp.width == ViewGroup.LayoutParams.MATCH_PARENT) {
613                // If the contents is fill parent for the width, set the
614                // corresponding background
615                backgroundResId = st.fullBackground;
616                width = MATCH_PARENT;
617            } else {
618                // Otherwise, set the normal panel background
619                backgroundResId = st.background;
620            }
621            st.decorView.setWindowBackground(getContext().getResources().getDrawable(
622                    backgroundResId));
623
624            ViewParent shownPanelParent = st.shownPanelView.getParent();
625            if (shownPanelParent != null && shownPanelParent instanceof ViewGroup) {
626                ((ViewGroup) shownPanelParent).removeView(st.shownPanelView);
627            }
628            st.decorView.addView(st.shownPanelView, lp);
629
630            /*
631             * Give focus to the view, if it or one of its children does not
632             * already have it.
633             */
634            if (!st.shownPanelView.hasFocus()) {
635                st.shownPanelView.requestFocus();
636            }
637        } else if (!st.isInListMode()) {
638            width = MATCH_PARENT;
639        } else if (st.createdPanelView != null) {
640            // If we already had a panel view, carry width=MATCH_PARENT through
641            // as we did above when it was created.
642            ViewGroup.LayoutParams lp = st.createdPanelView.getLayoutParams();
643            if (lp != null && lp.width == ViewGroup.LayoutParams.MATCH_PARENT) {
644                width = MATCH_PARENT;
645            }
646        }
647
648        Slog.d(TAG, "openPanel: b9404689 setting isOpen true, st=" + st + " decorView="
649                + st.decorView);
650        st.isOpen = true;
651        st.isHandled = false;
652
653        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
654                width, WRAP_CONTENT,
655                st.x, st.y, WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG,
656                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
657                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
658                st.decorView.mDefaultOpacity);
659
660        if (st.isCompact) {
661            lp.gravity = getOptionsPanelGravity();
662            sRotationWatcher.addWindow(this);
663        } else {
664            lp.gravity = st.gravity;
665        }
666
667        lp.windowAnimations = st.windowAnimations;
668
669        wm.addView(st.decorView, lp);
670        // Log.v(TAG, "Adding main menu to window manager.");
671    }
672
673    @Override
674    public final void closePanel(int featureId) {
675        if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
676                mActionBar.isOverflowReserved()) {
677            mActionBar.hideOverflowMenu();
678        } else if (featureId == FEATURE_CONTEXT_MENU) {
679            closeContextMenu();
680        } else {
681            closePanel(getPanelState(featureId, true), true);
682        }
683    }
684
685    /**
686     * Closes the given panel.
687     *
688     * @param st The panel to be closed.
689     * @param doCallback Whether to notify the callback that the panel was
690     *            closed. If the panel is in the process of re-opening or
691     *            opening another panel (e.g., menu opening a sub menu), the
692     *            callback should not happen and this variable should be false.
693     *            In addition, this method internally will only perform the
694     *            callback if the panel is open.
695     */
696    public final void closePanel(PanelFeatureState st, boolean doCallback) {
697        // System.out.println("Close panel: isOpen=" + st.isOpen);
698        Slog.d(TAG, "closePanel: b9404689 entry, st=" + st + " decorView=" + st.decorView);
699        if (doCallback && st.featureId == FEATURE_OPTIONS_PANEL &&
700                mActionBar != null && mActionBar.isOverflowMenuShowing()) {
701            checkCloseActionMenu(st.menu);
702            Slog.d(TAG, "closePanel: b9404689 early return");
703            return;
704        }
705
706        final ViewManager wm = getWindowManager();
707        if ((wm != null) && st.isOpen) {
708            if (st.decorView != null) {
709                wm.removeView(st.decorView);
710                // Log.v(TAG, "Removing main menu from window manager.");
711                if (st.isCompact) {
712                    sRotationWatcher.removeWindow(this);
713                }
714            }
715
716            if (doCallback) {
717                callOnPanelClosed(st.featureId, st, null);
718            }
719        }
720
721        st.isPrepared = false;
722        st.isHandled = false;
723        st.isOpen = false;
724
725        // This view is no longer shown, so null it out
726        st.shownPanelView = null;
727
728        if (st.isInExpandedMode) {
729            // Next time the menu opens, it should not be in expanded mode, so
730            // force a refresh of the decor
731            st.refreshDecorView = true;
732            st.isInExpandedMode = false;
733        }
734
735        if (mPreparedPanel == st) {
736            mPreparedPanel = null;
737            mPanelChordingKey = 0;
738        }
739    }
740
741    void checkCloseActionMenu(Menu menu) {
742        if (mClosingActionMenu) {
743            return;
744        }
745
746        mClosingActionMenu = true;
747        mActionBar.dismissPopupMenus();
748        Callback cb = getCallback();
749        if (cb != null && !isDestroyed()) {
750            cb.onPanelClosed(FEATURE_ACTION_BAR, menu);
751        }
752        mClosingActionMenu = false;
753    }
754
755    @Override
756    public final void togglePanel(int featureId, KeyEvent event) {
757        PanelFeatureState st = getPanelState(featureId, true);
758        if (st.isOpen) {
759            closePanel(st, true);
760        } else {
761            openPanel(st, event);
762        }
763    }
764
765    @Override
766    public void invalidatePanelMenu(int featureId) {
767        mInvalidatePanelMenuFeatures |= 1 << featureId;
768
769        if (!mInvalidatePanelMenuPosted && mDecor != null) {
770            mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
771            mInvalidatePanelMenuPosted = true;
772        }
773    }
774
775    void doInvalidatePanelMenu(int featureId) {
776        PanelFeatureState st = getPanelState(featureId, true);
777        Bundle savedActionViewStates = null;
778        if (st.menu != null) {
779            savedActionViewStates = new Bundle();
780            st.menu.saveActionViewStates(savedActionViewStates);
781            if (savedActionViewStates.size() > 0) {
782                st.frozenActionViewState = savedActionViewStates;
783            }
784            // This will be started again when the panel is prepared.
785            st.menu.stopDispatchingItemsChanged();
786            st.menu.clear();
787        }
788        st.refreshMenuContent = true;
789        st.refreshDecorView = true;
790
791        // Prepare the options panel if we have an action bar
792        if ((featureId == FEATURE_ACTION_BAR || featureId == FEATURE_OPTIONS_PANEL)
793                && mActionBar != null) {
794            st = getPanelState(Window.FEATURE_OPTIONS_PANEL, false);
795            if (st != null) {
796                st.isPrepared = false;
797                preparePanel(st, null);
798            }
799        }
800    }
801
802    /**
803     * Called when the panel key is pushed down.
804     * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}.
805     * @param event The key event.
806     * @return Whether the key was handled.
807     */
808    public final boolean onKeyDownPanel(int featureId, KeyEvent event) {
809        final int keyCode = event.getKeyCode();
810
811        if (event.getRepeatCount() == 0) {
812            // The panel key was pushed, so set the chording key
813            mPanelChordingKey = keyCode;
814
815            PanelFeatureState st = getPanelState(featureId, true);
816            if (!st.isOpen) {
817                return preparePanel(st, event);
818            }
819        }
820
821        return false;
822    }
823
824    /**
825     * Called when the panel key is released.
826     * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}.
827     * @param event The key event.
828     */
829    public final void onKeyUpPanel(int featureId, KeyEvent event) {
830        // The panel key was released, so clear the chording key
831        if (mPanelChordingKey != 0) {
832            mPanelChordingKey = 0;
833
834            if (event.isCanceled() || (mDecor != null && mDecor.mActionMode != null)) {
835                return;
836            }
837
838            boolean playSoundEffect = false;
839            final PanelFeatureState st = getPanelState(featureId, true);
840            if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null &&
841                    mActionBar.isOverflowReserved()) {
842                if (mActionBar.getVisibility() == View.VISIBLE) {
843                    if (!mActionBar.isOverflowMenuShowing()) {
844                        if (!isDestroyed() && preparePanel(st, event)) {
845                            playSoundEffect = mActionBar.showOverflowMenu();
846                        }
847                    } else {
848                        playSoundEffect = mActionBar.hideOverflowMenu();
849                    }
850                }
851            } else {
852                if (st.isOpen || st.isHandled) {
853
854                    // Play the sound effect if the user closed an open menu (and not if
855                    // they just released a menu shortcut)
856                    playSoundEffect = st.isOpen;
857
858                    // Close menu
859                    closePanel(st, true);
860
861                } else if (st.isPrepared) {
862                    boolean show = true;
863                    if (st.refreshMenuContent) {
864                        // Something may have invalidated the menu since we prepared it.
865                        // Re-prepare it to refresh.
866                        st.isPrepared = false;
867                        show = preparePanel(st, event);
868                    }
869
870                    if (show) {
871                        // Write 'menu opened' to event log
872                        EventLog.writeEvent(50001, 0);
873
874                        // Show menu
875                        openPanel(st, event);
876
877                        playSoundEffect = true;
878                    }
879                }
880            }
881
882            if (playSoundEffect) {
883                AudioManager audioManager = (AudioManager) getContext().getSystemService(
884                        Context.AUDIO_SERVICE);
885                if (audioManager != null) {
886                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
887                } else {
888                    Log.w(TAG, "Couldn't get audio manager");
889                }
890            }
891        }
892    }
893
894    @Override
895    public final void closeAllPanels() {
896        final ViewManager wm = getWindowManager();
897        if (wm == null) {
898            return;
899        }
900
901        final PanelFeatureState[] panels = mPanels;
902        final int N = panels != null ? panels.length : 0;
903        for (int i = 0; i < N; i++) {
904            final PanelFeatureState panel = panels[i];
905            if (panel != null) {
906                closePanel(panel, true);
907            }
908        }
909
910        closeContextMenu();
911    }
912
913    /**
914     * Closes the context menu. This notifies the menu logic of the close, along
915     * with dismissing it from the UI.
916     */
917    private synchronized void closeContextMenu() {
918        if (mContextMenu != null) {
919            mContextMenu.close();
920            dismissContextMenu();
921        }
922    }
923
924    /**
925     * Dismisses just the context menu UI. To close the context menu, use
926     * {@link #closeContextMenu()}.
927     */
928    private synchronized void dismissContextMenu() {
929        mContextMenu = null;
930
931        if (mContextMenuHelper != null) {
932            mContextMenuHelper.dismiss();
933            mContextMenuHelper = null;
934        }
935    }
936
937    @Override
938    public boolean performPanelShortcut(int featureId, int keyCode, KeyEvent event, int flags) {
939        return performPanelShortcut(getPanelState(featureId, true), keyCode, event, flags);
940    }
941
942    private boolean performPanelShortcut(PanelFeatureState st, int keyCode, KeyEvent event,
943            int flags) {
944        if (event.isSystem() || (st == null)) {
945            return false;
946        }
947
948        boolean handled = false;
949
950        // Only try to perform menu shortcuts if preparePanel returned true (possible false
951        // return value from application not wanting to show the menu).
952        if ((st.isPrepared || preparePanel(st, event)) && st.menu != null) {
953            // The menu is prepared now, perform the shortcut on it
954            handled = st.menu.performShortcut(keyCode, event, flags);
955        }
956
957        if (handled) {
958            // Mark as handled
959            st.isHandled = true;
960
961            // Only close down the menu if we don't have an action bar keeping it open.
962            if ((flags & Menu.FLAG_PERFORM_NO_CLOSE) == 0 && mActionBar == null) {
963                closePanel(st, true);
964            }
965        }
966
967        return handled;
968    }
969
970    @Override
971    public boolean performPanelIdentifierAction(int featureId, int id, int flags) {
972
973        PanelFeatureState st = getPanelState(featureId, true);
974        if (!preparePanel(st, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU))) {
975            return false;
976        }
977        if (st.menu == null) {
978            return false;
979        }
980
981        boolean res = st.menu.performIdentifierAction(id, flags);
982
983        // Only close down the menu if we don't have an action bar keeping it open.
984        if (mActionBar == null) {
985            closePanel(st, true);
986        }
987
988        return res;
989    }
990
991    public PanelFeatureState findMenuPanel(Menu menu) {
992        final PanelFeatureState[] panels = mPanels;
993        final int N = panels != null ? panels.length : 0;
994        for (int i = 0; i < N; i++) {
995            final PanelFeatureState panel = panels[i];
996            if (panel != null && panel.menu == menu) {
997                return panel;
998            }
999        }
1000        return null;
1001    }
1002
1003    public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
1004        final Callback cb = getCallback();
1005        if (cb != null && !isDestroyed()) {
1006            final PanelFeatureState panel = findMenuPanel(menu.getRootMenu());
1007            if (panel != null) {
1008                return cb.onMenuItemSelected(panel.featureId, item);
1009            }
1010        }
1011        return false;
1012    }
1013
1014    public void onMenuModeChange(MenuBuilder menu) {
1015        reopenMenu(true);
1016    }
1017
1018    private void reopenMenu(boolean toggleMenuMode) {
1019        if (mActionBar != null && mActionBar.isOverflowReserved()) {
1020            final Callback cb = getCallback();
1021            if (!mActionBar.isOverflowMenuShowing() || !toggleMenuMode) {
1022                if (cb != null && !isDestroyed() && mActionBar.getVisibility() == View.VISIBLE) {
1023                    // If we have a menu invalidation pending, do it now.
1024                    if (mInvalidatePanelMenuPosted &&
1025                            (mInvalidatePanelMenuFeatures & (1 << FEATURE_OPTIONS_PANEL)) != 0) {
1026                        mDecor.removeCallbacks(mInvalidatePanelMenuRunnable);
1027                        mInvalidatePanelMenuRunnable.run();
1028                    }
1029
1030                    final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
1031
1032                    // If we don't have a menu or we're waiting for a full content refresh,
1033                    // forget it. This is a lingering event that no longer matters.
1034                    if (st.menu != null && !st.refreshMenuContent &&
1035                            cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) {
1036                        cb.onMenuOpened(FEATURE_ACTION_BAR, st.menu);
1037                        mActionBar.showOverflowMenu();
1038                    }
1039                }
1040            } else {
1041                mActionBar.hideOverflowMenu();
1042                if (cb != null && !isDestroyed()) {
1043                    final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
1044                    cb.onPanelClosed(FEATURE_ACTION_BAR, st.menu);
1045                }
1046            }
1047            return;
1048        }
1049
1050        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
1051
1052        // Save the future expanded mode state since closePanel will reset it
1053        boolean newExpandedMode = toggleMenuMode ? !st.isInExpandedMode : st.isInExpandedMode;
1054
1055        st.refreshDecorView = true;
1056        closePanel(st, false);
1057
1058        // Set the expanded mode state
1059        st.isInExpandedMode = newExpandedMode;
1060
1061        openPanel(st, null);
1062    }
1063
1064    /**
1065     * Initializes the menu associated with the given panel feature state. You
1066     * must at the very least set PanelFeatureState.menu to the Menu to be
1067     * associated with the given panel state. The default implementation creates
1068     * a new menu for the panel state.
1069     *
1070     * @param st The panel whose menu is being initialized.
1071     * @return Whether the initialization was successful.
1072     */
1073    protected boolean initializePanelMenu(final PanelFeatureState st) {
1074        Context context = getContext();
1075
1076        // If we have an action bar, initialize the menu with a context themed for it.
1077        if ((st.featureId == FEATURE_OPTIONS_PANEL || st.featureId == FEATURE_ACTION_BAR) &&
1078                mActionBar != null) {
1079            TypedValue outValue = new TypedValue();
1080            Resources.Theme currentTheme = context.getTheme();
1081            currentTheme.resolveAttribute(com.android.internal.R.attr.actionBarWidgetTheme,
1082                    outValue, true);
1083            final int targetThemeRes = outValue.resourceId;
1084
1085            if (targetThemeRes != 0 && context.getThemeResId() != targetThemeRes) {
1086                context = new ContextThemeWrapper(context, targetThemeRes);
1087            }
1088        }
1089
1090        final MenuBuilder menu = new MenuBuilder(context);
1091
1092        menu.setCallback(this);
1093        st.setMenu(menu);
1094
1095        return true;
1096    }
1097
1098    /**
1099     * Perform initial setup of a panel. This should at the very least set the
1100     * style information in the PanelFeatureState and must set
1101     * PanelFeatureState.decor to the panel's window decor view.
1102     *
1103     * @param st The panel being initialized.
1104     */
1105    protected boolean initializePanelDecor(PanelFeatureState st) {
1106        st.decorView = new DecorView(getContext(), st.featureId);
1107        Slog.d(TAG, "initializePanelDecor: b9404689 st=" + st + " decorView=" + st.decorView);
1108        st.gravity = Gravity.CENTER | Gravity.BOTTOM;
1109        st.setStyle(getContext());
1110
1111        return true;
1112    }
1113
1114    /**
1115     * Determine the gravity value for the options panel. This can
1116     * differ in compact mode.
1117     *
1118     * @return gravity value to use for the panel window
1119     */
1120    private int getOptionsPanelGravity() {
1121        try {
1122            return WindowManagerHolder.sWindowManager.getPreferredOptionsPanelGravity();
1123        } catch (RemoteException ex) {
1124            Log.e(TAG, "Couldn't getOptionsPanelGravity; using default", ex);
1125            return Gravity.CENTER | Gravity.BOTTOM;
1126        }
1127    }
1128
1129    void onOptionsPanelRotationChanged() {
1130        final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
1131        if (st == null) return;
1132
1133        final WindowManager.LayoutParams lp = st.decorView != null ?
1134                (WindowManager.LayoutParams) st.decorView.getLayoutParams() : null;
1135        if (lp != null) {
1136            lp.gravity = getOptionsPanelGravity();
1137            final ViewManager wm = getWindowManager();
1138            if (wm != null) {
1139                wm.updateViewLayout(st.decorView, lp);
1140            }
1141        }
1142    }
1143
1144    /**
1145     * Initializes the panel associated with the panel feature state. You must
1146     * at the very least set PanelFeatureState.panel to the View implementing
1147     * its contents. The default implementation gets the panel from the menu.
1148     *
1149     * @param st The panel state being initialized.
1150     * @return Whether the initialization was successful.
1151     */
1152    protected boolean initializePanelContent(PanelFeatureState st) {
1153        if (st.createdPanelView != null) {
1154            st.shownPanelView = st.createdPanelView;
1155            return true;
1156        }
1157
1158        if (st.menu == null) {
1159            return false;
1160        }
1161
1162        if (mPanelMenuPresenterCallback == null) {
1163            mPanelMenuPresenterCallback = new PanelMenuPresenterCallback();
1164        }
1165
1166        MenuView menuView = st.isInListMode()
1167                ? st.getListMenuView(getContext(), mPanelMenuPresenterCallback)
1168                : st.getIconMenuView(getContext(), mPanelMenuPresenterCallback);
1169
1170        st.shownPanelView = (View) menuView;
1171
1172        if (st.shownPanelView != null) {
1173            // Use the menu View's default animations if it has any
1174            final int defaultAnimations = menuView.getWindowAnimations();
1175            if (defaultAnimations != 0) {
1176                st.windowAnimations = defaultAnimations;
1177            }
1178            return true;
1179        } else {
1180            return false;
1181        }
1182    }
1183
1184    @Override
1185    public boolean performContextMenuIdentifierAction(int id, int flags) {
1186        return (mContextMenu != null) ? mContextMenu.performIdentifierAction(id, flags) : false;
1187    }
1188
1189    @Override
1190    public final void setBackgroundDrawable(Drawable drawable) {
1191        if (drawable != mBackgroundDrawable || mBackgroundResource != 0) {
1192            mBackgroundResource = 0;
1193            mBackgroundDrawable = drawable;
1194            if (mDecor != null) {
1195                mDecor.setWindowBackground(drawable);
1196            }
1197        }
1198    }
1199
1200    @Override
1201    public final void setFeatureDrawableResource(int featureId, int resId) {
1202        if (resId != 0) {
1203            DrawableFeatureState st = getDrawableState(featureId, true);
1204            if (st.resid != resId) {
1205                st.resid = resId;
1206                st.uri = null;
1207                st.local = getContext().getResources().getDrawable(resId);
1208                updateDrawable(featureId, st, false);
1209            }
1210        } else {
1211            setFeatureDrawable(featureId, null);
1212        }
1213    }
1214
1215    @Override
1216    public final void setFeatureDrawableUri(int featureId, Uri uri) {
1217        if (uri != null) {
1218            DrawableFeatureState st = getDrawableState(featureId, true);
1219            if (st.uri == null || !st.uri.equals(uri)) {
1220                st.resid = 0;
1221                st.uri = uri;
1222                st.local = loadImageURI(uri);
1223                updateDrawable(featureId, st, false);
1224            }
1225        } else {
1226            setFeatureDrawable(featureId, null);
1227        }
1228    }
1229
1230    @Override
1231    public final void setFeatureDrawable(int featureId, Drawable drawable) {
1232        DrawableFeatureState st = getDrawableState(featureId, true);
1233        st.resid = 0;
1234        st.uri = null;
1235        if (st.local != drawable) {
1236            st.local = drawable;
1237            updateDrawable(featureId, st, false);
1238        }
1239    }
1240
1241    @Override
1242    public void setFeatureDrawableAlpha(int featureId, int alpha) {
1243        DrawableFeatureState st = getDrawableState(featureId, true);
1244        if (st.alpha != alpha) {
1245            st.alpha = alpha;
1246            updateDrawable(featureId, st, false);
1247        }
1248    }
1249
1250    protected final void setFeatureDefaultDrawable(int featureId, Drawable drawable) {
1251        DrawableFeatureState st = getDrawableState(featureId, true);
1252        if (st.def != drawable) {
1253            st.def = drawable;
1254            updateDrawable(featureId, st, false);
1255        }
1256    }
1257
1258    @Override
1259    public final void setFeatureInt(int featureId, int value) {
1260        // XXX Should do more management (as with drawable features) to
1261        // deal with interactions between multiple window policies.
1262        updateInt(featureId, value, false);
1263    }
1264
1265    /**
1266     * Update the state of a drawable feature. This should be called, for every
1267     * drawable feature supported, as part of onActive(), to make sure that the
1268     * contents of a containing window is properly updated.
1269     *
1270     * @see #onActive
1271     * @param featureId The desired drawable feature to change.
1272     * @param fromActive Always true when called from onActive().
1273     */
1274    protected final void updateDrawable(int featureId, boolean fromActive) {
1275        final DrawableFeatureState st = getDrawableState(featureId, false);
1276        if (st != null) {
1277            updateDrawable(featureId, st, fromActive);
1278        }
1279    }
1280
1281    /**
1282     * Called when a Drawable feature changes, for the window to update its
1283     * graphics.
1284     *
1285     * @param featureId The feature being changed.
1286     * @param drawable The new Drawable to show, or null if none.
1287     * @param alpha The new alpha blending of the Drawable.
1288     */
1289    protected void onDrawableChanged(int featureId, Drawable drawable, int alpha) {
1290        ImageView view;
1291        if (featureId == FEATURE_LEFT_ICON) {
1292            view = getLeftIconView();
1293        } else if (featureId == FEATURE_RIGHT_ICON) {
1294            view = getRightIconView();
1295        } else {
1296            return;
1297        }
1298
1299        if (drawable != null) {
1300            drawable.setAlpha(alpha);
1301            view.setImageDrawable(drawable);
1302            view.setVisibility(View.VISIBLE);
1303        } else {
1304            view.setVisibility(View.GONE);
1305        }
1306    }
1307
1308    /**
1309     * Called when an int feature changes, for the window to update its
1310     * graphics.
1311     *
1312     * @param featureId The feature being changed.
1313     * @param value The new integer value.
1314     */
1315    protected void onIntChanged(int featureId, int value) {
1316        if (featureId == FEATURE_PROGRESS || featureId == FEATURE_INDETERMINATE_PROGRESS) {
1317            updateProgressBars(value);
1318        } else if (featureId == FEATURE_CUSTOM_TITLE) {
1319            FrameLayout titleContainer = (FrameLayout) findViewById(com.android.internal.R.id.title_container);
1320            if (titleContainer != null) {
1321                mLayoutInflater.inflate(value, titleContainer);
1322            }
1323        }
1324    }
1325
1326    /**
1327     * Updates the progress bars that are shown in the title bar.
1328     *
1329     * @param value Can be one of {@link Window#PROGRESS_VISIBILITY_ON},
1330     *            {@link Window#PROGRESS_VISIBILITY_OFF},
1331     *            {@link Window#PROGRESS_INDETERMINATE_ON},
1332     *            {@link Window#PROGRESS_INDETERMINATE_OFF}, or a value
1333     *            starting at {@link Window#PROGRESS_START} through
1334     *            {@link Window#PROGRESS_END} for setting the default
1335     *            progress (if {@link Window#PROGRESS_END} is given,
1336     *            the progress bar widgets in the title will be hidden after an
1337     *            animation), a value between
1338     *            {@link Window#PROGRESS_SECONDARY_START} -
1339     *            {@link Window#PROGRESS_SECONDARY_END} for the
1340     *            secondary progress (if
1341     *            {@link Window#PROGRESS_SECONDARY_END} is given, the
1342     *            progress bar widgets will still be shown with the secondary
1343     *            progress bar will be completely filled in.)
1344     */
1345    private void updateProgressBars(int value) {
1346        ProgressBar circularProgressBar = getCircularProgressBar(true);
1347        ProgressBar horizontalProgressBar = getHorizontalProgressBar(true);
1348
1349        final int features = getLocalFeatures();
1350        if (value == PROGRESS_VISIBILITY_ON) {
1351            if ((features & (1 << FEATURE_PROGRESS)) != 0) {
1352                int level = horizontalProgressBar.getProgress();
1353                int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ?
1354                        View.VISIBLE : View.INVISIBLE;
1355                horizontalProgressBar.setVisibility(visibility);
1356            }
1357            if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
1358                circularProgressBar.setVisibility(View.VISIBLE);
1359            }
1360        } else if (value == PROGRESS_VISIBILITY_OFF) {
1361            if ((features & (1 << FEATURE_PROGRESS)) != 0) {
1362                horizontalProgressBar.setVisibility(View.GONE);
1363            }
1364            if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
1365                circularProgressBar.setVisibility(View.GONE);
1366            }
1367        } else if (value == PROGRESS_INDETERMINATE_ON) {
1368            horizontalProgressBar.setIndeterminate(true);
1369        } else if (value == PROGRESS_INDETERMINATE_OFF) {
1370            horizontalProgressBar.setIndeterminate(false);
1371        } else if (PROGRESS_START <= value && value <= PROGRESS_END) {
1372            // We want to set the progress value before testing for visibility
1373            // so that when the progress bar becomes visible again, it has the
1374            // correct level.
1375            horizontalProgressBar.setProgress(value - PROGRESS_START);
1376
1377            if (value < PROGRESS_END) {
1378                showProgressBars(horizontalProgressBar, circularProgressBar);
1379            } else {
1380                hideProgressBars(horizontalProgressBar, circularProgressBar);
1381            }
1382        } else if (PROGRESS_SECONDARY_START <= value && value <= PROGRESS_SECONDARY_END) {
1383            horizontalProgressBar.setSecondaryProgress(value - PROGRESS_SECONDARY_START);
1384
1385            showProgressBars(horizontalProgressBar, circularProgressBar);
1386        }
1387
1388    }
1389
1390    private void showProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
1391        final int features = getLocalFeatures();
1392        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
1393                spinnyProgressBar.getVisibility() == View.INVISIBLE) {
1394            spinnyProgressBar.setVisibility(View.VISIBLE);
1395        }
1396        // Only show the progress bars if the primary progress is not complete
1397        if ((features & (1 << FEATURE_PROGRESS)) != 0 &&
1398                horizontalProgressBar.getProgress() < 10000) {
1399            horizontalProgressBar.setVisibility(View.VISIBLE);
1400        }
1401    }
1402
1403    private void hideProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) {
1404        final int features = getLocalFeatures();
1405        Animation anim = AnimationUtils.loadAnimation(getContext(), com.android.internal.R.anim.fade_out);
1406        anim.setDuration(1000);
1407        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 &&
1408                spinnyProgressBar.getVisibility() == View.VISIBLE) {
1409            spinnyProgressBar.startAnimation(anim);
1410            spinnyProgressBar.setVisibility(View.INVISIBLE);
1411        }
1412        if ((features & (1 << FEATURE_PROGRESS)) != 0 &&
1413                horizontalProgressBar.getVisibility() == View.VISIBLE) {
1414            horizontalProgressBar.startAnimation(anim);
1415            horizontalProgressBar.setVisibility(View.INVISIBLE);
1416        }
1417    }
1418
1419    @Override
1420    public void setIcon(int resId) {
1421        mIconRes = resId;
1422        mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON;
1423        mResourcesSetFlags &= ~FLAG_RESOURCE_SET_ICON_FALLBACK;
1424        if (mActionBar != null) {
1425            mActionBar.setIcon(resId);
1426        }
1427    }
1428
1429    @Override
1430    public void setDefaultIcon(int resId) {
1431        if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0) {
1432            return;
1433        }
1434        mIconRes = resId;
1435        if (mActionBar != null && (!mActionBar.hasIcon() ||
1436                (mResourcesSetFlags & FLAG_RESOURCE_SET_ICON_FALLBACK) != 0)) {
1437            if (resId != 0) {
1438                mActionBar.setIcon(resId);
1439                mResourcesSetFlags &= ~FLAG_RESOURCE_SET_ICON_FALLBACK;
1440            } else {
1441                mActionBar.setIcon(getContext().getPackageManager().getDefaultActivityIcon());
1442                mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK;
1443            }
1444        }
1445    }
1446
1447    @Override
1448    public void setLogo(int resId) {
1449        mLogoRes = resId;
1450        mResourcesSetFlags |= FLAG_RESOURCE_SET_LOGO;
1451        if (mActionBar != null) {
1452            mActionBar.setLogo(resId);
1453        }
1454    }
1455
1456    @Override
1457    public void setDefaultLogo(int resId) {
1458        if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0) {
1459            return;
1460        }
1461        mLogoRes = resId;
1462        if (mActionBar != null && !mActionBar.hasLogo()) {
1463            mActionBar.setLogo(resId);
1464        }
1465    }
1466
1467    /**
1468     * Request that key events come to this activity. Use this if your activity
1469     * has no views with focus, but the activity still wants a chance to process
1470     * key events.
1471     */
1472    @Override
1473    public void takeKeyEvents(boolean get) {
1474        mDecor.setFocusable(get);
1475    }
1476
1477    @Override
1478    public boolean superDispatchKeyEvent(KeyEvent event) {
1479        return mDecor.superDispatchKeyEvent(event);
1480    }
1481
1482    @Override
1483    public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
1484        return mDecor.superDispatchKeyShortcutEvent(event);
1485    }
1486
1487    @Override
1488    public boolean superDispatchTouchEvent(MotionEvent event) {
1489        return mDecor.superDispatchTouchEvent(event);
1490    }
1491
1492    @Override
1493    public boolean superDispatchTrackballEvent(MotionEvent event) {
1494        return mDecor.superDispatchTrackballEvent(event);
1495    }
1496
1497    @Override
1498    public boolean superDispatchGenericMotionEvent(MotionEvent event) {
1499        return mDecor.superDispatchGenericMotionEvent(event);
1500    }
1501
1502    /**
1503     * A key was pressed down and not handled by anything else in the window.
1504     *
1505     * @see #onKeyUp
1506     * @see android.view.KeyEvent
1507     */
1508    protected boolean onKeyDown(int featureId, int keyCode, KeyEvent event) {
1509        /* ****************************************************************************
1510         * HOW TO DECIDE WHERE YOUR KEY HANDLING GOES.
1511         *
1512         * If your key handling must happen before the app gets a crack at the event,
1513         * it goes in PhoneWindowManager.
1514         *
1515         * If your key handling should happen in all windows, and does not depend on
1516         * the state of the current application, other than that the current
1517         * application can override the behavior by handling the event itself, it
1518         * should go in PhoneFallbackEventHandler.
1519         *
1520         * Only if your handling depends on the window, and the fact that it has
1521         * a DecorView, should it go here.
1522         * ****************************************************************************/
1523
1524        final KeyEvent.DispatcherState dispatcher =
1525                mDecor != null ? mDecor.getKeyDispatcherState() : null;
1526        //Log.i(TAG, "Key down: repeat=" + event.getRepeatCount()
1527        //        + " flags=0x" + Integer.toHexString(event.getFlags()));
1528
1529        switch (keyCode) {
1530            case KeyEvent.KEYCODE_VOLUME_UP:
1531            case KeyEvent.KEYCODE_VOLUME_DOWN:
1532            case KeyEvent.KEYCODE_VOLUME_MUTE: {
1533                // Similar code is in PhoneFallbackEventHandler in case the window
1534                // doesn't have one of these.  In this case, we execute it here and
1535                // eat the event instead, because we have mVolumeControlStreamType
1536                // and they don't.
1537                getAudioManager().handleKeyDown(event, mVolumeControlStreamType);
1538                return true;
1539            }
1540
1541            case KeyEvent.KEYCODE_MENU: {
1542                onKeyDownPanel((featureId < 0) ? FEATURE_OPTIONS_PANEL : featureId, event);
1543                return true;
1544            }
1545
1546            case KeyEvent.KEYCODE_BACK: {
1547                if (event.getRepeatCount() > 0) break;
1548                if (featureId < 0) break;
1549                // Currently don't do anything with long press.
1550                if (dispatcher != null) {
1551                    dispatcher.startTracking(event, this);
1552                }
1553                return true;
1554            }
1555
1556        }
1557
1558        return false;
1559    }
1560
1561    private KeyguardManager getKeyguardManager() {
1562        if (mKeyguardManager == null) {
1563            mKeyguardManager = (KeyguardManager) getContext().getSystemService(
1564                    Context.KEYGUARD_SERVICE);
1565        }
1566        return mKeyguardManager;
1567    }
1568
1569    AudioManager getAudioManager() {
1570        if (mAudioManager == null) {
1571            mAudioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
1572        }
1573        return mAudioManager;
1574    }
1575
1576    /**
1577     * A key was released and not handled by anything else in the window.
1578     *
1579     * @see #onKeyDown
1580     * @see android.view.KeyEvent
1581     */
1582    protected boolean onKeyUp(int featureId, int keyCode, KeyEvent event) {
1583        final KeyEvent.DispatcherState dispatcher =
1584                mDecor != null ? mDecor.getKeyDispatcherState() : null;
1585        if (dispatcher != null) {
1586            dispatcher.handleUpEvent(event);
1587        }
1588        //Log.i(TAG, "Key up: repeat=" + event.getRepeatCount()
1589        //        + " flags=0x" + Integer.toHexString(event.getFlags()));
1590
1591        switch (keyCode) {
1592            case KeyEvent.KEYCODE_VOLUME_UP:
1593            case KeyEvent.KEYCODE_VOLUME_DOWN:
1594            case KeyEvent.KEYCODE_VOLUME_MUTE: {
1595                // Similar code is in PhoneFallbackEventHandler in case the window
1596                // doesn't have one of these.  In this case, we execute it here and
1597                // eat the event instead, because we have mVolumeControlStreamType
1598                // and they don't.
1599                getAudioManager().handleKeyUp(event, mVolumeControlStreamType);
1600                return true;
1601            }
1602
1603            case KeyEvent.KEYCODE_MENU: {
1604                onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId,
1605                        event);
1606                return true;
1607            }
1608
1609            case KeyEvent.KEYCODE_BACK: {
1610                if (featureId < 0) break;
1611                if (event.isTracking() && !event.isCanceled()) {
1612                    if (featureId == FEATURE_OPTIONS_PANEL) {
1613                        PanelFeatureState st = getPanelState(featureId, false);
1614                        if (st != null && st.isInExpandedMode) {
1615                            // If the user is in an expanded menu and hits back, it
1616                            // should go back to the icon menu
1617                            reopenMenu(true);
1618                            return true;
1619                        }
1620                    }
1621                    closePanel(featureId);
1622                    return true;
1623                }
1624                break;
1625            }
1626
1627            case KeyEvent.KEYCODE_SEARCH: {
1628                /*
1629                 * Do this in onKeyUp since the Search key is also used for
1630                 * chording quick launch shortcuts.
1631                 */
1632                if (getKeyguardManager().inKeyguardRestrictedInputMode()) {
1633                    break;
1634                }
1635                if (event.isTracking() && !event.isCanceled()) {
1636                    launchDefaultSearch();
1637                }
1638                return true;
1639            }
1640        }
1641
1642        return false;
1643    }
1644
1645    @Override
1646    protected void onActive() {
1647    }
1648
1649    @Override
1650    public final View getDecorView() {
1651        if (mDecor == null) {
1652            installDecor();
1653        }
1654        return mDecor;
1655    }
1656
1657    @Override
1658    public final View peekDecorView() {
1659        return mDecor;
1660    }
1661
1662    static private final String FOCUSED_ID_TAG = "android:focusedViewId";
1663    static private final String VIEWS_TAG = "android:views";
1664    static private final String PANELS_TAG = "android:Panels";
1665    static private final String ACTION_BAR_TAG = "android:ActionBar";
1666
1667    /** {@inheritDoc} */
1668    @Override
1669    public Bundle saveHierarchyState() {
1670        Bundle outState = new Bundle();
1671        if (mContentParent == null) {
1672            return outState;
1673        }
1674
1675        SparseArray<Parcelable> states = new SparseArray<Parcelable>();
1676        mContentParent.saveHierarchyState(states);
1677        outState.putSparseParcelableArray(VIEWS_TAG, states);
1678
1679        // save the focused view id
1680        View focusedView = mContentParent.findFocus();
1681        if (focusedView != null) {
1682            if (focusedView.getId() != View.NO_ID) {
1683                outState.putInt(FOCUSED_ID_TAG, focusedView.getId());
1684            } else {
1685                if (false) {
1686                    Log.d(TAG, "couldn't save which view has focus because the focused view "
1687                            + focusedView + " has no id.");
1688                }
1689            }
1690        }
1691
1692        // save the panels
1693        SparseArray<Parcelable> panelStates = new SparseArray<Parcelable>();
1694        savePanelState(panelStates);
1695        if (panelStates.size() > 0) {
1696            outState.putSparseParcelableArray(PANELS_TAG, panelStates);
1697        }
1698
1699        if (mActionBar != null) {
1700            SparseArray<Parcelable> actionBarStates = new SparseArray<Parcelable>();
1701            mActionBar.saveHierarchyState(actionBarStates);
1702            outState.putSparseParcelableArray(ACTION_BAR_TAG, actionBarStates);
1703        }
1704
1705        return outState;
1706    }
1707
1708    /** {@inheritDoc} */
1709    @Override
1710    public void restoreHierarchyState(Bundle savedInstanceState) {
1711        if (mContentParent == null) {
1712            return;
1713        }
1714
1715        SparseArray<Parcelable> savedStates
1716                = savedInstanceState.getSparseParcelableArray(VIEWS_TAG);
1717        if (savedStates != null) {
1718            mContentParent.restoreHierarchyState(savedStates);
1719        }
1720
1721        // restore the focused view
1722        int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID);
1723        if (focusedViewId != View.NO_ID) {
1724            View needsFocus = mContentParent.findViewById(focusedViewId);
1725            if (needsFocus != null) {
1726                needsFocus.requestFocus();
1727            } else {
1728                Log.w(TAG,
1729                        "Previously focused view reported id " + focusedViewId
1730                                + " during save, but can't be found during restore.");
1731            }
1732        }
1733
1734        // restore the panels
1735        SparseArray<Parcelable> panelStates = savedInstanceState.getSparseParcelableArray(PANELS_TAG);
1736        if (panelStates != null) {
1737            restorePanelState(panelStates);
1738        }
1739
1740        if (mActionBar != null) {
1741            SparseArray<Parcelable> actionBarStates =
1742                    savedInstanceState.getSparseParcelableArray(ACTION_BAR_TAG);
1743            if (actionBarStates != null) {
1744                mActionBar.restoreHierarchyState(actionBarStates);
1745            } else {
1746                Log.w(TAG, "Missing saved instance states for action bar views! " +
1747                        "State will not be restored.");
1748            }
1749        }
1750    }
1751
1752    /**
1753     * Invoked when the panels should freeze their state.
1754     *
1755     * @param icicles Save state into this. This is usually indexed by the
1756     *            featureId. This will be given to {@link #restorePanelState} in the
1757     *            future.
1758     */
1759    private void savePanelState(SparseArray<Parcelable> icicles) {
1760        PanelFeatureState[] panels = mPanels;
1761        if (panels == null) {
1762            return;
1763        }
1764
1765        for (int curFeatureId = panels.length - 1; curFeatureId >= 0; curFeatureId--) {
1766            if (panels[curFeatureId] != null) {
1767                icicles.put(curFeatureId, panels[curFeatureId].onSaveInstanceState());
1768            }
1769        }
1770    }
1771
1772    /**
1773     * Invoked when the panels should thaw their state from a previously frozen state.
1774     *
1775     * @param icicles The state saved by {@link #savePanelState} that needs to be thawed.
1776     */
1777    private void restorePanelState(SparseArray<Parcelable> icicles) {
1778        PanelFeatureState st;
1779        int curFeatureId;
1780        for (int i = icicles.size() - 1; i >= 0; i--) {
1781            curFeatureId = icicles.keyAt(i);
1782            st = getPanelState(curFeatureId, false /* required */);
1783            if (st == null) {
1784                // The panel must not have been required, and is currently not around, skip it
1785                continue;
1786            }
1787
1788            st.onRestoreInstanceState(icicles.get(curFeatureId));
1789            invalidatePanelMenu(curFeatureId);
1790        }
1791
1792        /*
1793         * Implementation note: call openPanelsAfterRestore later to actually open the
1794         * restored panels.
1795         */
1796    }
1797
1798    /**
1799     * Opens the panels that have had their state restored. This should be
1800     * called sometime after {@link #restorePanelState} when it is safe to add
1801     * to the window manager.
1802     */
1803    private void openPanelsAfterRestore() {
1804        PanelFeatureState[] panels = mPanels;
1805
1806        if (panels == null) {
1807            return;
1808        }
1809
1810        PanelFeatureState st;
1811        for (int i = panels.length - 1; i >= 0; i--) {
1812            st = panels[i];
1813            // We restore the panel if it was last open; we skip it if it
1814            // now is open, to avoid a race condition if the user immediately
1815            // opens it when we are resuming.
1816            if (st != null) {
1817                st.applyFrozenState();
1818                if (!st.isOpen && st.wasLastOpen) {
1819                    st.isInExpandedMode = st.wasLastExpanded;
1820                    openPanel(st, null);
1821                }
1822            }
1823        }
1824    }
1825
1826    private class PanelMenuPresenterCallback implements MenuPresenter.Callback {
1827        @Override
1828        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
1829            final Menu parentMenu = menu.getRootMenu();
1830            final boolean isSubMenu = parentMenu != menu;
1831            final PanelFeatureState panel = findMenuPanel(isSubMenu ? parentMenu : menu);
1832            if (panel != null) {
1833                if (isSubMenu) {
1834                    callOnPanelClosed(panel.featureId, panel, parentMenu);
1835                    closePanel(panel, true);
1836                } else {
1837                    // Close the panel and only do the callback if the menu is being
1838                    // closed completely, not if opening a sub menu
1839                    closePanel(panel, allMenusAreClosing);
1840                }
1841            }
1842        }
1843
1844        @Override
1845        public boolean onOpenSubMenu(MenuBuilder subMenu) {
1846            if (subMenu == null && hasFeature(FEATURE_ACTION_BAR)) {
1847                Callback cb = getCallback();
1848                if (cb != null && !isDestroyed()) {
1849                    cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
1850                }
1851            }
1852
1853            return true;
1854        }
1855    }
1856
1857    private final class ActionMenuPresenterCallback implements MenuPresenter.Callback {
1858        @Override
1859        public boolean onOpenSubMenu(MenuBuilder subMenu) {
1860            Callback cb = getCallback();
1861            if (cb != null) {
1862                cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
1863                return true;
1864            }
1865            return false;
1866        }
1867
1868        @Override
1869        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
1870            checkCloseActionMenu(menu);
1871        }
1872    }
1873
1874    private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
1875        /* package */int mDefaultOpacity = PixelFormat.OPAQUE;
1876
1877        /** The feature ID of the panel, or -1 if this is the application's DecorView */
1878        private final int mFeatureId;
1879
1880        private final Rect mDrawingBounds = new Rect();
1881
1882        private final Rect mBackgroundPadding = new Rect();
1883
1884        private final Rect mFramePadding = new Rect();
1885
1886        private final Rect mFrameOffsets = new Rect();
1887
1888        private boolean mChanging;
1889
1890        private Drawable mMenuBackground;
1891        private boolean mWatchingForMenu;
1892        private int mDownY;
1893
1894        private ActionMode mActionMode;
1895        private ActionBarContextView mActionModeView;
1896        private PopupWindow mActionModePopup;
1897        private Runnable mShowActionModePopup;
1898
1899        public DecorView(Context context, int featureId) {
1900            super(context);
1901            mFeatureId = featureId;
1902        }
1903
1904        @Override
1905        public boolean dispatchKeyEvent(KeyEvent event) {
1906            final int keyCode = event.getKeyCode();
1907            final int action = event.getAction();
1908            final boolean isDown = action == KeyEvent.ACTION_DOWN;
1909
1910            if (isDown && (event.getRepeatCount() == 0)) {
1911                // First handle chording of panel key: if a panel key is held
1912                // but not released, try to execute a shortcut in it.
1913                if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) {
1914                    boolean handled = dispatchKeyShortcutEvent(event);
1915                    if (handled) {
1916                        return true;
1917                    }
1918                }
1919
1920                // If a panel is open, perform a shortcut on it without the
1921                // chorded panel key
1922                if ((mPreparedPanel != null) && mPreparedPanel.isOpen) {
1923                    if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) {
1924                        return true;
1925                    }
1926                }
1927            }
1928
1929            if (!isDestroyed()) {
1930                final Callback cb = getCallback();
1931                final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event)
1932                        : super.dispatchKeyEvent(event);
1933                if (handled) {
1934                    return true;
1935                }
1936            }
1937
1938            return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event)
1939                    : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event);
1940        }
1941
1942        @Override
1943        public boolean dispatchKeyShortcutEvent(KeyEvent ev) {
1944            // If the panel is already prepared, then perform the shortcut using it.
1945            boolean handled;
1946            if (mPreparedPanel != null) {
1947                handled = performPanelShortcut(mPreparedPanel, ev.getKeyCode(), ev,
1948                        Menu.FLAG_PERFORM_NO_CLOSE);
1949                if (handled) {
1950                    if (mPreparedPanel != null) {
1951                        mPreparedPanel.isHandled = true;
1952                    }
1953                    return true;
1954                }
1955            }
1956
1957            // Shortcut not handled by the panel.  Dispatch to the view hierarchy.
1958            final Callback cb = getCallback();
1959            handled = cb != null && !isDestroyed() && mFeatureId < 0
1960                    ? cb.dispatchKeyShortcutEvent(ev) : super.dispatchKeyShortcutEvent(ev);
1961            if (handled) {
1962                return true;
1963            }
1964
1965            // If the panel is not prepared, then we may be trying to handle a shortcut key
1966            // combination such as Control+C.  Temporarily prepare the panel then mark it
1967            // unprepared again when finished to ensure that the panel will again be prepared
1968            // the next time it is shown for real.
1969            if (mPreparedPanel == null) {
1970                PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
1971                preparePanel(st, ev);
1972                handled = performPanelShortcut(st, ev.getKeyCode(), ev,
1973                        Menu.FLAG_PERFORM_NO_CLOSE);
1974                st.isPrepared = false;
1975                if (handled) {
1976                    return true;
1977                }
1978            }
1979            return false;
1980        }
1981
1982        @Override
1983        public boolean dispatchTouchEvent(MotionEvent ev) {
1984            final Callback cb = getCallback();
1985            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
1986                    : super.dispatchTouchEvent(ev);
1987        }
1988
1989        @Override
1990        public boolean dispatchTrackballEvent(MotionEvent ev) {
1991            final Callback cb = getCallback();
1992            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev)
1993                    : super.dispatchTrackballEvent(ev);
1994        }
1995
1996        @Override
1997        public boolean dispatchGenericMotionEvent(MotionEvent ev) {
1998            final Callback cb = getCallback();
1999            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchGenericMotionEvent(ev)
2000                    : super.dispatchGenericMotionEvent(ev);
2001        }
2002
2003        public boolean superDispatchKeyEvent(KeyEvent event) {
2004            if (super.dispatchKeyEvent(event)) {
2005                return true;
2006            }
2007
2008            // Not handled by the view hierarchy, does the action bar want it
2009            // to cancel out of something special?
2010            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
2011                final int action = event.getAction();
2012                // Back cancels action modes first.
2013                if (mActionMode != null) {
2014                    if (action == KeyEvent.ACTION_UP) {
2015                        mActionMode.finish();
2016                    }
2017                    return true;
2018                }
2019
2020                // Next collapse any expanded action views.
2021                if (mActionBar != null && mActionBar.hasExpandedActionView()) {
2022                    if (action == KeyEvent.ACTION_UP) {
2023                        mActionBar.collapseActionView();
2024                    }
2025                    return true;
2026                }
2027            }
2028
2029            return false;
2030        }
2031
2032        public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
2033            return super.dispatchKeyShortcutEvent(event);
2034        }
2035
2036        public boolean superDispatchTouchEvent(MotionEvent event) {
2037            return super.dispatchTouchEvent(event);
2038        }
2039
2040        public boolean superDispatchTrackballEvent(MotionEvent event) {
2041            return super.dispatchTrackballEvent(event);
2042        }
2043
2044        public boolean superDispatchGenericMotionEvent(MotionEvent event) {
2045            return super.dispatchGenericMotionEvent(event);
2046        }
2047
2048        @Override
2049        public boolean onTouchEvent(MotionEvent event) {
2050            return onInterceptTouchEvent(event);
2051        }
2052
2053        private boolean isOutOfBounds(int x, int y) {
2054            return x < -5 || y < -5 || x > (getWidth() + 5)
2055                    || y > (getHeight() + 5);
2056        }
2057
2058        @Override
2059        public boolean onInterceptTouchEvent(MotionEvent event) {
2060            int action = event.getAction();
2061            if (mFeatureId >= 0) {
2062                if (action == MotionEvent.ACTION_DOWN) {
2063                    int x = (int)event.getX();
2064                    int y = (int)event.getY();
2065                    if (isOutOfBounds(x, y)) {
2066                        closePanel(mFeatureId);
2067                        return true;
2068                    }
2069                }
2070            }
2071
2072            if (!SWEEP_OPEN_MENU) {
2073                return false;
2074            }
2075
2076            if (mFeatureId >= 0) {
2077                if (action == MotionEvent.ACTION_DOWN) {
2078                    Log.i(TAG, "Watchiing!");
2079                    mWatchingForMenu = true;
2080                    mDownY = (int) event.getY();
2081                    return false;
2082                }
2083
2084                if (!mWatchingForMenu) {
2085                    return false;
2086                }
2087
2088                int y = (int)event.getY();
2089                if (action == MotionEvent.ACTION_MOVE) {
2090                    if (y > (mDownY+30)) {
2091                        Log.i(TAG, "Closing!");
2092                        closePanel(mFeatureId);
2093                        mWatchingForMenu = false;
2094                        return true;
2095                    }
2096                } else if (action == MotionEvent.ACTION_UP) {
2097                    mWatchingForMenu = false;
2098                }
2099
2100                return false;
2101            }
2102
2103            //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY()
2104            //        + " (in " + getHeight() + ")");
2105
2106            if (action == MotionEvent.ACTION_DOWN) {
2107                int y = (int)event.getY();
2108                if (y >= (getHeight()-5) && !hasChildren()) {
2109                    Log.i(TAG, "Watchiing!");
2110                    mWatchingForMenu = true;
2111                }
2112                return false;
2113            }
2114
2115            if (!mWatchingForMenu) {
2116                return false;
2117            }
2118
2119            int y = (int)event.getY();
2120            if (action == MotionEvent.ACTION_MOVE) {
2121                if (y < (getHeight()-30)) {
2122                    Log.i(TAG, "Opening!");
2123                    openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent(
2124                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU));
2125                    mWatchingForMenu = false;
2126                    return true;
2127                }
2128            } else if (action == MotionEvent.ACTION_UP) {
2129                mWatchingForMenu = false;
2130            }
2131
2132            return false;
2133        }
2134
2135        @Override
2136        public void sendAccessibilityEvent(int eventType) {
2137            if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
2138                return;
2139            }
2140
2141            // if we are showing a feature that should be announced and one child
2142            // make this child the event source since this is the feature itself
2143            // otherwise the callback will take over and announce its client
2144            if ((mFeatureId == FEATURE_OPTIONS_PANEL ||
2145                    mFeatureId == FEATURE_CONTEXT_MENU ||
2146                    mFeatureId == FEATURE_PROGRESS ||
2147                    mFeatureId == FEATURE_INDETERMINATE_PROGRESS)
2148                    && getChildCount() == 1) {
2149                getChildAt(0).sendAccessibilityEvent(eventType);
2150            } else {
2151                super.sendAccessibilityEvent(eventType);
2152            }
2153        }
2154
2155        @Override
2156        public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2157            final Callback cb = getCallback();
2158            if (cb != null && !isDestroyed()) {
2159                if (cb.dispatchPopulateAccessibilityEvent(event)) {
2160                    return true;
2161                }
2162            }
2163            return super.dispatchPopulateAccessibilityEvent(event);
2164        }
2165
2166        @Override
2167        protected boolean setFrame(int l, int t, int r, int b) {
2168            boolean changed = super.setFrame(l, t, r, b);
2169            if (changed) {
2170                final Rect drawingBounds = mDrawingBounds;
2171                getDrawingRect(drawingBounds);
2172
2173                Drawable fg = getForeground();
2174                if (fg != null) {
2175                    final Rect frameOffsets = mFrameOffsets;
2176                    drawingBounds.left += frameOffsets.left;
2177                    drawingBounds.top += frameOffsets.top;
2178                    drawingBounds.right -= frameOffsets.right;
2179                    drawingBounds.bottom -= frameOffsets.bottom;
2180                    fg.setBounds(drawingBounds);
2181                    final Rect framePadding = mFramePadding;
2182                    drawingBounds.left += framePadding.left - frameOffsets.left;
2183                    drawingBounds.top += framePadding.top - frameOffsets.top;
2184                    drawingBounds.right -= framePadding.right - frameOffsets.right;
2185                    drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom;
2186                }
2187
2188                Drawable bg = getBackground();
2189                if (bg != null) {
2190                    bg.setBounds(drawingBounds);
2191                }
2192
2193                if (SWEEP_OPEN_MENU) {
2194                    if (mMenuBackground == null && mFeatureId < 0
2195                            && getAttributes().height
2196                            == WindowManager.LayoutParams.MATCH_PARENT) {
2197                        mMenuBackground = getContext().getResources().getDrawable(
2198                                com.android.internal.R.drawable.menu_background);
2199                    }
2200                    if (mMenuBackground != null) {
2201                        mMenuBackground.setBounds(drawingBounds.left,
2202                                drawingBounds.bottom-6, drawingBounds.right,
2203                                drawingBounds.bottom+20);
2204                    }
2205                }
2206            }
2207            return changed;
2208        }
2209
2210        @Override
2211        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2212            final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
2213            final boolean isPortrait = metrics.widthPixels < metrics.heightPixels;
2214
2215            final int widthMode = getMode(widthMeasureSpec);
2216            final int heightMode = getMode(heightMeasureSpec);
2217
2218            boolean fixedWidth = false;
2219            if (widthMode == AT_MOST) {
2220                final TypedValue tvw = isPortrait ? mFixedWidthMinor : mFixedWidthMajor;
2221                if (tvw != null && tvw.type != TypedValue.TYPE_NULL) {
2222                    final int w;
2223                    if (tvw.type == TypedValue.TYPE_DIMENSION) {
2224                        w = (int) tvw.getDimension(metrics);
2225                    } else if (tvw.type == TypedValue.TYPE_FRACTION) {
2226                        w = (int) tvw.getFraction(metrics.widthPixels, metrics.widthPixels);
2227                    } else {
2228                        w = 0;
2229                    }
2230
2231                    if (w > 0) {
2232                        final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
2233                        widthMeasureSpec = MeasureSpec.makeMeasureSpec(
2234                                Math.min(w, widthSize), EXACTLY);
2235                        fixedWidth = true;
2236                    }
2237                }
2238            }
2239
2240            if (heightMode == AT_MOST) {
2241                final TypedValue tvh = isPortrait ? mFixedHeightMajor : mFixedHeightMinor;
2242                if (tvh != null && tvh.type != TypedValue.TYPE_NULL) {
2243                    final int h;
2244                    if (tvh.type == TypedValue.TYPE_DIMENSION) {
2245                        h = (int) tvh.getDimension(metrics);
2246                    } else if (tvh.type == TypedValue.TYPE_FRACTION) {
2247                        h = (int) tvh.getFraction(metrics.heightPixels, metrics.heightPixels);
2248                    } else {
2249                        h = 0;
2250                    }
2251
2252                    if (h > 0) {
2253                        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
2254                        heightMeasureSpec = MeasureSpec.makeMeasureSpec(
2255                                Math.min(h, heightSize), EXACTLY);
2256                    }
2257                }
2258            }
2259
2260            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
2261
2262            int width = getMeasuredWidth();
2263            boolean measure = false;
2264
2265            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY);
2266
2267            if (!fixedWidth && widthMode == AT_MOST) {
2268                final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor;
2269                if (tv.type != TypedValue.TYPE_NULL) {
2270                    final int min;
2271                    if (tv.type == TypedValue.TYPE_DIMENSION) {
2272                        min = (int)tv.getDimension(metrics);
2273                    } else if (tv.type == TypedValue.TYPE_FRACTION) {
2274                        min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels);
2275                    } else {
2276                        min = 0;
2277                    }
2278
2279                    if (width < min) {
2280                        widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY);
2281                        measure = true;
2282                    }
2283                }
2284            }
2285
2286            // TODO: Support height?
2287
2288            if (measure) {
2289                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
2290            }
2291        }
2292
2293        @Override
2294        public void draw(Canvas canvas) {
2295            super.draw(canvas);
2296
2297            if (mMenuBackground != null) {
2298                mMenuBackground.draw(canvas);
2299            }
2300        }
2301
2302
2303        @Override
2304        public boolean showContextMenuForChild(View originalView) {
2305            // Reuse the context menu builder
2306            if (mContextMenu == null) {
2307                mContextMenu = new ContextMenuBuilder(getContext());
2308                mContextMenu.setCallback(mContextMenuCallback);
2309            } else {
2310                mContextMenu.clearAll();
2311            }
2312
2313            final MenuDialogHelper helper = mContextMenu.show(originalView,
2314                    originalView.getWindowToken());
2315            if (helper != null) {
2316                helper.setPresenterCallback(mContextMenuCallback);
2317            }
2318            mContextMenuHelper = helper;
2319            return helper != null;
2320        }
2321
2322        @Override
2323        public ActionMode startActionModeForChild(View originalView,
2324                ActionMode.Callback callback) {
2325            // originalView can be used here to be sure that we don't obscure
2326            // relevant content with the context mode UI.
2327            return startActionMode(callback);
2328        }
2329
2330        @Override
2331        public ActionMode startActionMode(ActionMode.Callback callback) {
2332            if (mActionMode != null) {
2333                mActionMode.finish();
2334            }
2335
2336            final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback);
2337            ActionMode mode = null;
2338            if (getCallback() != null && !isDestroyed()) {
2339                try {
2340                    mode = getCallback().onWindowStartingActionMode(wrappedCallback);
2341                } catch (AbstractMethodError ame) {
2342                    // Older apps might not implement this callback method.
2343                }
2344            }
2345            if (mode != null) {
2346                mActionMode = mode;
2347            } else {
2348                if (mActionModeView == null) {
2349                    if (isFloating()) {
2350                        mActionModeView = new ActionBarContextView(mContext);
2351                        mActionModePopup = new PopupWindow(mContext, null,
2352                                com.android.internal.R.attr.actionModePopupWindowStyle);
2353                        mActionModePopup.setWindowLayoutType(
2354                                WindowManager.LayoutParams.TYPE_APPLICATION);
2355                        mActionModePopup.setContentView(mActionModeView);
2356                        mActionModePopup.setWidth(MATCH_PARENT);
2357
2358                        TypedValue heightValue = new TypedValue();
2359                        mContext.getTheme().resolveAttribute(
2360                                com.android.internal.R.attr.actionBarSize, heightValue, true);
2361                        final int height = TypedValue.complexToDimensionPixelSize(heightValue.data,
2362                                mContext.getResources().getDisplayMetrics());
2363                        mActionModeView.setContentHeight(height);
2364                        mActionModePopup.setHeight(WRAP_CONTENT);
2365                        mShowActionModePopup = new Runnable() {
2366                            public void run() {
2367                                mActionModePopup.showAtLocation(
2368                                        mActionModeView.getApplicationWindowToken(),
2369                                        Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
2370                            }
2371                        };
2372                    } else {
2373                        ViewStub stub = (ViewStub) findViewById(
2374                                com.android.internal.R.id.action_mode_bar_stub);
2375                        if (stub != null) {
2376                            mActionModeView = (ActionBarContextView) stub.inflate();
2377                        }
2378                    }
2379                }
2380
2381                if (mActionModeView != null) {
2382                    mActionModeView.killMode();
2383                    mode = new StandaloneActionMode(getContext(), mActionModeView, wrappedCallback,
2384                            mActionModePopup == null);
2385                    if (callback.onCreateActionMode(mode, mode.getMenu())) {
2386                        mode.invalidate();
2387                        mActionModeView.initForMode(mode);
2388                        mActionModeView.setVisibility(View.VISIBLE);
2389                        mActionMode = mode;
2390                        if (mActionModePopup != null) {
2391                            post(mShowActionModePopup);
2392                        }
2393                        mActionModeView.sendAccessibilityEvent(
2394                                AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2395                    } else {
2396                        mActionMode = null;
2397                    }
2398                }
2399            }
2400            if (mActionMode != null && getCallback() != null && !isDestroyed()) {
2401                try {
2402                    getCallback().onActionModeStarted(mActionMode);
2403                } catch (AbstractMethodError ame) {
2404                    // Older apps might not implement this callback method.
2405                }
2406            }
2407            return mActionMode;
2408        }
2409
2410        public void startChanging() {
2411            mChanging = true;
2412        }
2413
2414        public void finishChanging() {
2415            mChanging = false;
2416            drawableChanged();
2417        }
2418
2419        public void setWindowBackground(Drawable drawable) {
2420            if (getBackground() != drawable) {
2421                setBackgroundDrawable(drawable);
2422                if (drawable != null) {
2423                    drawable.getPadding(mBackgroundPadding);
2424                } else {
2425                    mBackgroundPadding.setEmpty();
2426                }
2427                drawableChanged();
2428            }
2429        }
2430
2431        @Override
2432        public void setBackgroundDrawable(Drawable d) {
2433            super.setBackgroundDrawable(d);
2434            if (getWindowToken() != null) {
2435                updateWindowResizeState();
2436            }
2437        }
2438
2439        public void setWindowFrame(Drawable drawable) {
2440            if (getForeground() != drawable) {
2441                setForeground(drawable);
2442                if (drawable != null) {
2443                    drawable.getPadding(mFramePadding);
2444                } else {
2445                    mFramePadding.setEmpty();
2446                }
2447                drawableChanged();
2448            }
2449        }
2450
2451        @Override
2452        protected boolean fitSystemWindows(Rect insets) {
2453            mFrameOffsets.set(insets);
2454            if (getForeground() != null) {
2455                drawableChanged();
2456            }
2457            return super.fitSystemWindows(insets);
2458        }
2459
2460        private void drawableChanged() {
2461            if (mChanging) {
2462                return;
2463            }
2464
2465            setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top
2466                    + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right,
2467                    mFramePadding.bottom + mBackgroundPadding.bottom);
2468            requestLayout();
2469            invalidate();
2470
2471            int opacity = PixelFormat.OPAQUE;
2472
2473            // Note: if there is no background, we will assume opaque. The
2474            // common case seems to be that an application sets there to be
2475            // no background so it can draw everything itself. For that,
2476            // we would like to assume OPAQUE and let the app force it to
2477            // the slower TRANSLUCENT mode if that is really what it wants.
2478            Drawable bg = getBackground();
2479            Drawable fg = getForeground();
2480            if (bg != null) {
2481                if (fg == null) {
2482                    opacity = bg.getOpacity();
2483                } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0
2484                        && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) {
2485                    // If the frame padding is zero, then we can be opaque
2486                    // if either the frame -or- the background is opaque.
2487                    int fop = fg.getOpacity();
2488                    int bop = bg.getOpacity();
2489                    if (false)
2490                        Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop);
2491                    if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) {
2492                        opacity = PixelFormat.OPAQUE;
2493                    } else if (fop == PixelFormat.UNKNOWN) {
2494                        opacity = bop;
2495                    } else if (bop == PixelFormat.UNKNOWN) {
2496                        opacity = fop;
2497                    } else {
2498                        opacity = Drawable.resolveOpacity(fop, bop);
2499                    }
2500                } else {
2501                    // For now we have to assume translucent if there is a
2502                    // frame with padding... there is no way to tell if the
2503                    // frame and background together will draw all pixels.
2504                    if (false)
2505                        Log.v(TAG, "Padding: " + mFramePadding);
2506                    opacity = PixelFormat.TRANSLUCENT;
2507                }
2508            }
2509
2510            if (false)
2511                Log.v(TAG, "Background: " + bg + ", Frame: " + fg);
2512            if (false)
2513                Log.v(TAG, "Selected default opacity: " + opacity);
2514
2515            mDefaultOpacity = opacity;
2516            if (mFeatureId < 0) {
2517                setDefaultWindowFormat(opacity);
2518            }
2519        }
2520
2521        @Override
2522        public void onWindowFocusChanged(boolean hasWindowFocus) {
2523            super.onWindowFocusChanged(hasWindowFocus);
2524
2525            // If the user is chording a menu shortcut, release the chord since
2526            // this window lost focus
2527            if (!hasWindowFocus && mPanelChordingKey != 0) {
2528                closePanel(FEATURE_OPTIONS_PANEL);
2529            }
2530
2531            final Callback cb = getCallback();
2532            if (cb != null && !isDestroyed() && mFeatureId < 0) {
2533                cb.onWindowFocusChanged(hasWindowFocus);
2534            }
2535        }
2536
2537        void updateWindowResizeState() {
2538            Drawable bg = getBackground();
2539            hackTurnOffWindowResizeAnim(bg == null || bg.getOpacity()
2540                    != PixelFormat.OPAQUE);
2541        }
2542
2543        @Override
2544        protected void onAttachedToWindow() {
2545            super.onAttachedToWindow();
2546
2547            updateWindowResizeState();
2548
2549            final Callback cb = getCallback();
2550            if (cb != null && !isDestroyed() && mFeatureId < 0) {
2551                cb.onAttachedToWindow();
2552            }
2553
2554            if (mFeatureId == -1) {
2555                /*
2556                 * The main window has been attached, try to restore any panels
2557                 * that may have been open before. This is called in cases where
2558                 * an activity is being killed for configuration change and the
2559                 * menu was open. When the activity is recreated, the menu
2560                 * should be shown again.
2561                 */
2562                openPanelsAfterRestore();
2563            }
2564        }
2565
2566        @Override
2567        protected void onDetachedFromWindow() {
2568            super.onDetachedFromWindow();
2569
2570            final Callback cb = getCallback();
2571            if (cb != null && mFeatureId < 0) {
2572                cb.onDetachedFromWindow();
2573            }
2574
2575            if (mActionBar != null) {
2576                mActionBar.dismissPopupMenus();
2577            }
2578
2579            if (mActionModePopup != null) {
2580                removeCallbacks(mShowActionModePopup);
2581                if (mActionModePopup.isShowing()) {
2582                    mActionModePopup.dismiss();
2583                }
2584                mActionModePopup = null;
2585            }
2586
2587            PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
2588            if (st != null && st.menu != null && mFeatureId < 0) {
2589                st.menu.close();
2590            }
2591        }
2592
2593        @Override
2594        public void onCloseSystemDialogs(String reason) {
2595            if (mFeatureId >= 0) {
2596                closeAllPanels();
2597            }
2598        }
2599
2600        public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() {
2601            return mFeatureId < 0 ? mTakeSurfaceCallback : null;
2602        }
2603
2604        public InputQueue.Callback willYouTakeTheInputQueue() {
2605            return mFeatureId < 0 ? mTakeInputQueueCallback : null;
2606        }
2607
2608        public void setSurfaceType(int type) {
2609            PhoneWindow.this.setType(type);
2610        }
2611
2612        public void setSurfaceFormat(int format) {
2613            PhoneWindow.this.setFormat(format);
2614        }
2615
2616        public void setSurfaceKeepScreenOn(boolean keepOn) {
2617            if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2618            else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2619        }
2620
2621        /**
2622         * Clears out internal reference when the action mode is destroyed.
2623         */
2624        private class ActionModeCallbackWrapper implements ActionMode.Callback {
2625            private ActionMode.Callback mWrapped;
2626
2627            public ActionModeCallbackWrapper(ActionMode.Callback wrapped) {
2628                mWrapped = wrapped;
2629            }
2630
2631            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2632                return mWrapped.onCreateActionMode(mode, menu);
2633            }
2634
2635            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2636                return mWrapped.onPrepareActionMode(mode, menu);
2637            }
2638
2639            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2640                return mWrapped.onActionItemClicked(mode, item);
2641            }
2642
2643            public void onDestroyActionMode(ActionMode mode) {
2644                mWrapped.onDestroyActionMode(mode);
2645                if (mActionModePopup != null) {
2646                    removeCallbacks(mShowActionModePopup);
2647                    mActionModePopup.dismiss();
2648                } else if (mActionModeView != null) {
2649                    mActionModeView.setVisibility(GONE);
2650                }
2651                if (mActionModeView != null) {
2652                    mActionModeView.removeAllViews();
2653                }
2654                if (getCallback() != null && !isDestroyed()) {
2655                    try {
2656                        getCallback().onActionModeFinished(mActionMode);
2657                    } catch (AbstractMethodError ame) {
2658                        // Older apps might not implement this callback method.
2659                    }
2660                }
2661                mActionMode = null;
2662            }
2663        }
2664    }
2665
2666    protected DecorView generateDecor() {
2667        return new DecorView(getContext(), -1);
2668    }
2669
2670    protected void setFeatureFromAttrs(int featureId, TypedArray attrs,
2671            int drawableAttr, int alphaAttr) {
2672        Drawable d = attrs.getDrawable(drawableAttr);
2673        if (d != null) {
2674            requestFeature(featureId);
2675            setFeatureDefaultDrawable(featureId, d);
2676        }
2677        if ((getFeatures() & (1 << featureId)) != 0) {
2678            int alpha = attrs.getInt(alphaAttr, -1);
2679            if (alpha >= 0) {
2680                setFeatureDrawableAlpha(featureId, alpha);
2681            }
2682        }
2683    }
2684
2685    protected ViewGroup generateLayout(DecorView decor) {
2686        // Apply data from current theme.
2687
2688        TypedArray a = getWindowStyle();
2689
2690        if (false) {
2691            System.out.println("From style:");
2692            String s = "Attrs:";
2693            for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) {
2694                s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "="
2695                        + a.getString(i);
2696            }
2697            System.out.println(s);
2698        }
2699
2700        mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
2701        int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR)
2702                & (~getForcedWindowFlags());
2703        if (mIsFloating) {
2704            setLayout(WRAP_CONTENT, WRAP_CONTENT);
2705            setFlags(0, flagsToUpdate);
2706        } else {
2707            setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
2708        }
2709
2710        if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
2711            requestFeature(FEATURE_NO_TITLE);
2712        } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) {
2713            // Don't allow an action bar if there is no title.
2714            requestFeature(FEATURE_ACTION_BAR);
2715        }
2716
2717        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) {
2718            requestFeature(FEATURE_ACTION_BAR_OVERLAY);
2719        }
2720
2721        if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) {
2722            requestFeature(FEATURE_ACTION_MODE_OVERLAY);
2723        }
2724
2725        if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
2726            setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
2727        }
2728
2729        if (a.getBoolean(com.android.internal.R.styleable.Window_windowOverscan, false)) {
2730            setFlags(FLAG_LAYOUT_IN_OVERSCAN, FLAG_LAYOUT_IN_OVERSCAN&(~getForcedWindowFlags()));
2731        }
2732
2733        if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) {
2734            setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags()));
2735        }
2736
2737        if (a.getBoolean(com.android.internal.R.styleable.Window_windowEnableSplitTouch,
2738                getContext().getApplicationInfo().targetSdkVersion
2739                        >= android.os.Build.VERSION_CODES.HONEYCOMB)) {
2740            setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags()));
2741        }
2742
2743        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMajor, mMinWidthMajor);
2744        a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMinor, mMinWidthMinor);
2745        if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedWidthMajor)) {
2746            if (mFixedWidthMajor == null) mFixedWidthMajor = new TypedValue();
2747            a.getValue(com.android.internal.R.styleable.Window_windowFixedWidthMajor,
2748                    mFixedWidthMajor);
2749        }
2750        if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedWidthMinor)) {
2751            if (mFixedWidthMinor == null) mFixedWidthMinor = new TypedValue();
2752            a.getValue(com.android.internal.R.styleable.Window_windowFixedWidthMinor,
2753                    mFixedWidthMinor);
2754        }
2755        if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedHeightMajor)) {
2756            if (mFixedHeightMajor == null) mFixedHeightMajor = new TypedValue();
2757            a.getValue(com.android.internal.R.styleable.Window_windowFixedHeightMajor,
2758                    mFixedHeightMajor);
2759        }
2760        if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedHeightMinor)) {
2761            if (mFixedHeightMinor == null) mFixedHeightMinor = new TypedValue();
2762            a.getValue(com.android.internal.R.styleable.Window_windowFixedHeightMinor,
2763                    mFixedHeightMinor);
2764        }
2765
2766        final Context context = getContext();
2767        final int targetSdk = context.getApplicationInfo().targetSdkVersion;
2768        final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
2769        final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
2770        final boolean targetHcNeedsOptions = context.getResources().getBoolean(
2771                com.android.internal.R.bool.target_honeycomb_needs_options_menu);
2772        final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);
2773
2774        if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
2775            addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY);
2776        } else {
2777            clearFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY);
2778        }
2779
2780        if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion
2781                >= android.os.Build.VERSION_CODES.HONEYCOMB) {
2782            if (a.getBoolean(
2783                    com.android.internal.R.styleable.Window_windowCloseOnTouchOutside,
2784                    false)) {
2785                setCloseOnTouchOutsideIfNotSet(true);
2786            }
2787        }
2788
2789        WindowManager.LayoutParams params = getAttributes();
2790
2791        if (!hasSoftInputMode()) {
2792            params.softInputMode = a.getInt(
2793                    com.android.internal.R.styleable.Window_windowSoftInputMode,
2794                    params.softInputMode);
2795        }
2796
2797        if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled,
2798                mIsFloating)) {
2799            /* All dialogs should have the window dimmed */
2800            if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) {
2801                params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
2802            }
2803            if (!haveDimAmount()) {
2804                params.dimAmount = a.getFloat(
2805                        android.R.styleable.Window_backgroundDimAmount, 0.5f);
2806            }
2807        }
2808
2809        if (params.windowAnimations == 0) {
2810            params.windowAnimations = a.getResourceId(
2811                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2812        }
2813
2814        // The rest are only done if this window is not embedded; otherwise,
2815        // the values are inherited from our container.
2816        if (getContainer() == null) {
2817            if (mBackgroundDrawable == null) {
2818                if (mBackgroundResource == 0) {
2819                    mBackgroundResource = a.getResourceId(
2820                            com.android.internal.R.styleable.Window_windowBackground, 0);
2821                }
2822                if (mFrameResource == 0) {
2823                    mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0);
2824                }
2825                if (false) {
2826                    System.out.println("Background: "
2827                            + Integer.toHexString(mBackgroundResource) + " Frame: "
2828                            + Integer.toHexString(mFrameResource));
2829                }
2830            }
2831            mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000);
2832        }
2833
2834        // Inflate the window decor.
2835
2836        int layoutResource;
2837        int features = getLocalFeatures();
2838        // System.out.println("Features: 0x" + Integer.toHexString(features));
2839        if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
2840            if (mIsFloating) {
2841                TypedValue res = new TypedValue();
2842                getContext().getTheme().resolveAttribute(
2843                        com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true);
2844                layoutResource = res.resourceId;
2845            } else {
2846                layoutResource = com.android.internal.R.layout.screen_title_icons;
2847            }
2848            // XXX Remove this once action bar supports these features.
2849            removeFeature(FEATURE_ACTION_BAR);
2850            // System.out.println("Title Icons!");
2851        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
2852                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
2853            // Special case for a window with only a progress bar (and title).
2854            // XXX Need to have a no-title version of embedded windows.
2855            layoutResource = com.android.internal.R.layout.screen_progress;
2856            // System.out.println("Progress!");
2857        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
2858            // Special case for a window with a custom title.
2859            // If the window is floating, we need a dialog layout
2860            if (mIsFloating) {
2861                TypedValue res = new TypedValue();
2862                getContext().getTheme().resolveAttribute(
2863                        com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true);
2864                layoutResource = res.resourceId;
2865            } else {
2866                layoutResource = com.android.internal.R.layout.screen_custom_title;
2867            }
2868            // XXX Remove this once action bar supports these features.
2869            removeFeature(FEATURE_ACTION_BAR);
2870        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
2871            // If no other features and not embedded, only need a title.
2872            // If the window is floating, we need a dialog layout
2873            if (mIsFloating) {
2874                TypedValue res = new TypedValue();
2875                getContext().getTheme().resolveAttribute(
2876                        com.android.internal.R.attr.dialogTitleDecorLayout, res, true);
2877                layoutResource = res.resourceId;
2878            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
2879                layoutResource = com.android.internal.R.layout.screen_action_bar;
2880            } else {
2881                layoutResource = com.android.internal.R.layout.screen_title;
2882            }
2883            // System.out.println("Title!");
2884        } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
2885            layoutResource = com.android.internal.R.layout.screen_simple_overlay_action_mode;
2886        } else {
2887            // Embedded, so no decoration is needed.
2888            layoutResource = com.android.internal.R.layout.screen_simple;
2889            // System.out.println("Simple!");
2890        }
2891
2892        mDecor.startChanging();
2893
2894        View in = mLayoutInflater.inflate(layoutResource, null);
2895        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
2896
2897        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
2898        if (contentParent == null) {
2899            throw new RuntimeException("Window couldn't find content container view");
2900        }
2901
2902        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2903            ProgressBar progress = getCircularProgressBar(false);
2904            if (progress != null) {
2905                progress.setIndeterminate(true);
2906            }
2907        }
2908
2909        // Remaining setup -- of background and title -- that only applies
2910        // to top-level windows.
2911        if (getContainer() == null) {
2912            Drawable drawable = mBackgroundDrawable;
2913            if (mBackgroundResource != 0) {
2914                drawable = getContext().getResources().getDrawable(mBackgroundResource);
2915            }
2916            mDecor.setWindowBackground(drawable);
2917            drawable = null;
2918            if (mFrameResource != 0) {
2919                drawable = getContext().getResources().getDrawable(mFrameResource);
2920            }
2921            mDecor.setWindowFrame(drawable);
2922
2923            // System.out.println("Text=" + Integer.toHexString(mTextColor) +
2924            // " Sel=" + Integer.toHexString(mTextSelectedColor) +
2925            // " Title=" + Integer.toHexString(mTitleColor));
2926
2927            if (mTitleColor == 0) {
2928                mTitleColor = mTextColor;
2929            }
2930
2931            if (mTitle != null) {
2932                setTitle(mTitle);
2933            }
2934            setTitleColor(mTitleColor);
2935        }
2936
2937        mDecor.finishChanging();
2938
2939        return contentParent;
2940    }
2941
2942    /** @hide */
2943    public void alwaysReadCloseOnTouchAttr() {
2944        mAlwaysReadCloseOnTouchAttr = true;
2945    }
2946
2947    private void installDecor() {
2948        if (mDecor == null) {
2949            mDecor = generateDecor();
2950            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
2951            mDecor.setIsRootNamespace(true);
2952            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
2953                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
2954            }
2955        }
2956        if (mContentParent == null) {
2957            mContentParent = generateLayout(mDecor);
2958
2959            // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
2960            mDecor.makeOptionalFitsSystemWindows();
2961
2962            mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
2963            if (mTitleView != null) {
2964                mTitleView.setLayoutDirection(mDecor.getLayoutDirection());
2965                if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
2966                    View titleContainer = findViewById(com.android.internal.R.id.title_container);
2967                    if (titleContainer != null) {
2968                        titleContainer.setVisibility(View.GONE);
2969                    } else {
2970                        mTitleView.setVisibility(View.GONE);
2971                    }
2972                    if (mContentParent instanceof FrameLayout) {
2973                        ((FrameLayout)mContentParent).setForeground(null);
2974                    }
2975                } else {
2976                    mTitleView.setText(mTitle);
2977                }
2978            } else {
2979                mActionBar = (ActionBarView) findViewById(com.android.internal.R.id.action_bar);
2980                if (mActionBar != null) {
2981                    mActionBar.setWindowCallback(getCallback());
2982                    if (mActionBar.getTitle() == null) {
2983                        mActionBar.setWindowTitle(mTitle);
2984                    }
2985                    final int localFeatures = getLocalFeatures();
2986                    if ((localFeatures & (1 << FEATURE_PROGRESS)) != 0) {
2987                        mActionBar.initProgress();
2988                    }
2989                    if ((localFeatures & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
2990                        mActionBar.initIndeterminateProgress();
2991                    }
2992
2993                    boolean splitActionBar = false;
2994                    final boolean splitWhenNarrow =
2995                            (mUiOptions & ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW) != 0;
2996                    if (splitWhenNarrow) {
2997                        splitActionBar = getContext().getResources().getBoolean(
2998                                com.android.internal.R.bool.split_action_bar_is_narrow);
2999                    } else {
3000                        splitActionBar = getWindowStyle().getBoolean(
3001                                com.android.internal.R.styleable.Window_windowSplitActionBar, false);
3002                    }
3003                    final ActionBarContainer splitView = (ActionBarContainer) findViewById(
3004                            com.android.internal.R.id.split_action_bar);
3005                    if (splitView != null) {
3006                        mActionBar.setSplitView(splitView);
3007                        mActionBar.setSplitActionBar(splitActionBar);
3008                        mActionBar.setSplitWhenNarrow(splitWhenNarrow);
3009
3010                        final ActionBarContextView cab = (ActionBarContextView) findViewById(
3011                                com.android.internal.R.id.action_context_bar);
3012                        cab.setSplitView(splitView);
3013                        cab.setSplitActionBar(splitActionBar);
3014                        cab.setSplitWhenNarrow(splitWhenNarrow);
3015                    } else if (splitActionBar) {
3016                        Log.e(TAG, "Requested split action bar with " +
3017                                "incompatible window decor! Ignoring request.");
3018                    }
3019
3020                    if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0 ||
3021                            (mIconRes != 0 && !mActionBar.hasIcon())) {
3022                        mActionBar.setIcon(mIconRes);
3023                    } else if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) == 0 &&
3024                            mIconRes == 0 && !mActionBar.hasIcon()) {
3025                        mActionBar.setIcon(
3026                                getContext().getPackageManager().getDefaultActivityIcon());
3027                        mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK;
3028                    }
3029                    if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0 ||
3030                            (mLogoRes != 0 && !mActionBar.hasLogo())) {
3031                        mActionBar.setLogo(mLogoRes);
3032                    }
3033
3034                    // Post the panel invalidate for later; avoid application onCreateOptionsMenu
3035                    // being called in the middle of onCreate or similar.
3036                    mDecor.post(new Runnable() {
3037                        public void run() {
3038                            // Invalidate if the panel menu hasn't been created before this.
3039                            PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
3040                            if (!isDestroyed() && (st == null || st.menu == null)) {
3041                                invalidatePanelMenu(FEATURE_ACTION_BAR);
3042                            }
3043                        }
3044                    });
3045                }
3046            }
3047        }
3048    }
3049
3050    private Drawable loadImageURI(Uri uri) {
3051        try {
3052            return Drawable.createFromStream(
3053                    getContext().getContentResolver().openInputStream(uri), null);
3054        } catch (Exception e) {
3055            Log.w(TAG, "Unable to open content: " + uri);
3056        }
3057        return null;
3058    }
3059
3060    private DrawableFeatureState getDrawableState(int featureId, boolean required) {
3061        if ((getFeatures() & (1 << featureId)) == 0) {
3062            if (!required) {
3063                return null;
3064            }
3065            throw new RuntimeException("The feature has not been requested");
3066        }
3067
3068        DrawableFeatureState[] ar;
3069        if ((ar = mDrawables) == null || ar.length <= featureId) {
3070            DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1];
3071            if (ar != null) {
3072                System.arraycopy(ar, 0, nar, 0, ar.length);
3073            }
3074            mDrawables = ar = nar;
3075        }
3076
3077        DrawableFeatureState st = ar[featureId];
3078        if (st == null) {
3079            ar[featureId] = st = new DrawableFeatureState(featureId);
3080        }
3081        return st;
3082    }
3083
3084    /**
3085     * Gets a panel's state based on its feature ID.
3086     *
3087     * @param featureId The feature ID of the panel.
3088     * @param required Whether the panel is required (if it is required and it
3089     *            isn't in our features, this throws an exception).
3090     * @return The panel state.
3091     */
3092    private PanelFeatureState getPanelState(int featureId, boolean required) {
3093        return getPanelState(featureId, required, null);
3094    }
3095
3096    /**
3097     * Gets a panel's state based on its feature ID.
3098     *
3099     * @param featureId The feature ID of the panel.
3100     * @param required Whether the panel is required (if it is required and it
3101     *            isn't in our features, this throws an exception).
3102     * @param convertPanelState Optional: If the panel state does not exist, use
3103     *            this as the panel state.
3104     * @return The panel state.
3105     */
3106    private PanelFeatureState getPanelState(int featureId, boolean required,
3107            PanelFeatureState convertPanelState) {
3108        if ((getFeatures() & (1 << featureId)) == 0) {
3109            if (!required) {
3110                return null;
3111            }
3112            throw new RuntimeException("The feature has not been requested");
3113        }
3114
3115        PanelFeatureState[] ar;
3116        if ((ar = mPanels) == null || ar.length <= featureId) {
3117            PanelFeatureState[] nar = new PanelFeatureState[featureId + 1];
3118            if (ar != null) {
3119                System.arraycopy(ar, 0, nar, 0, ar.length);
3120            }
3121            mPanels = ar = nar;
3122        }
3123
3124        PanelFeatureState st = ar[featureId];
3125        if (st == null) {
3126            ar[featureId] = st = (convertPanelState != null)
3127                    ? convertPanelState
3128                    : new PanelFeatureState(featureId);
3129        }
3130        return st;
3131    }
3132
3133    @Override
3134    public final void setChildDrawable(int featureId, Drawable drawable) {
3135        DrawableFeatureState st = getDrawableState(featureId, true);
3136        st.child = drawable;
3137        updateDrawable(featureId, st, false);
3138    }
3139
3140    @Override
3141    public final void setChildInt(int featureId, int value) {
3142        updateInt(featureId, value, false);
3143    }
3144
3145    @Override
3146    public boolean isShortcutKey(int keyCode, KeyEvent event) {
3147        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true);
3148        return st.menu != null && st.menu.isShortcutKey(keyCode, event);
3149    }
3150
3151    private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) {
3152        // Do nothing if the decor is not yet installed... an update will
3153        // need to be forced when we eventually become active.
3154        if (mContentParent == null) {
3155            return;
3156        }
3157
3158        final int featureMask = 1 << featureId;
3159
3160        if ((getFeatures() & featureMask) == 0 && !fromResume) {
3161            return;
3162        }
3163
3164        Drawable drawable = null;
3165        if (st != null) {
3166            drawable = st.child;
3167            if (drawable == null)
3168                drawable = st.local;
3169            if (drawable == null)
3170                drawable = st.def;
3171        }
3172        if ((getLocalFeatures() & featureMask) == 0) {
3173            if (getContainer() != null) {
3174                if (isActive() || fromResume) {
3175                    getContainer().setChildDrawable(featureId, drawable);
3176                }
3177            }
3178        } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) {
3179            // System.out.println("Drawable changed: old=" + st.cur
3180            // + ", new=" + drawable);
3181            st.cur = drawable;
3182            st.curAlpha = st.alpha;
3183            onDrawableChanged(featureId, drawable, st.alpha);
3184        }
3185    }
3186
3187    private void updateInt(int featureId, int value, boolean fromResume) {
3188
3189        // Do nothing if the decor is not yet installed... an update will
3190        // need to be forced when we eventually become active.
3191        if (mContentParent == null) {
3192            return;
3193        }
3194
3195        final int featureMask = 1 << featureId;
3196
3197        if ((getFeatures() & featureMask) == 0 && !fromResume) {
3198            return;
3199        }
3200
3201        if ((getLocalFeatures() & featureMask) == 0) {
3202            if (getContainer() != null) {
3203                getContainer().setChildInt(featureId, value);
3204            }
3205        } else {
3206            onIntChanged(featureId, value);
3207        }
3208    }
3209
3210    private ImageView getLeftIconView() {
3211        if (mLeftIconView != null) {
3212            return mLeftIconView;
3213        }
3214        if (mContentParent == null) {
3215            installDecor();
3216        }
3217        return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon));
3218    }
3219
3220    private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) {
3221        if (mCircularProgressBar != null) {
3222            return mCircularProgressBar;
3223        }
3224        if (mContentParent == null && shouldInstallDecor) {
3225            installDecor();
3226        }
3227        mCircularProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_circular);
3228        if (mCircularProgressBar != null) {
3229            mCircularProgressBar.setVisibility(View.INVISIBLE);
3230        }
3231        return mCircularProgressBar;
3232    }
3233
3234    private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) {
3235        if (mHorizontalProgressBar != null) {
3236            return mHorizontalProgressBar;
3237        }
3238        if (mContentParent == null && shouldInstallDecor) {
3239            installDecor();
3240        }
3241        mHorizontalProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_horizontal);
3242        if (mHorizontalProgressBar != null) {
3243            mHorizontalProgressBar.setVisibility(View.INVISIBLE);
3244        }
3245        return mHorizontalProgressBar;
3246    }
3247
3248    private ImageView getRightIconView() {
3249        if (mRightIconView != null) {
3250            return mRightIconView;
3251        }
3252        if (mContentParent == null) {
3253            installDecor();
3254        }
3255        return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon));
3256    }
3257
3258    /**
3259     * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)}
3260     * callback. This method will grab whatever extra state is needed for the
3261     * callback that isn't given in the parameters. If the panel is not open,
3262     * this will not perform the callback.
3263     *
3264     * @param featureId Feature ID of the panel that was closed. Must be given.
3265     * @param panel Panel that was closed. Optional but useful if there is no
3266     *            menu given.
3267     * @param menu The menu that was closed. Optional, but give if you have.
3268     */
3269    private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) {
3270        final Callback cb = getCallback();
3271        if (cb == null)
3272            return;
3273
3274        // Try to get a menu
3275        if (menu == null) {
3276            // Need a panel to grab the menu, so try to get that
3277            if (panel == null) {
3278                if ((featureId >= 0) && (featureId < mPanels.length)) {
3279                    panel = mPanels[featureId];
3280                }
3281            }
3282
3283            if (panel != null) {
3284                // menu still may be null, which is okay--we tried our best
3285                menu = panel.menu;
3286            }
3287        }
3288
3289        // If the panel is not open, do not callback
3290        if ((panel != null) && (!panel.isOpen))
3291            return;
3292
3293        if (!isDestroyed()) {
3294            cb.onPanelClosed(featureId, menu);
3295        }
3296    }
3297
3298    /**
3299     * Helper method for adding launch-search to most applications. Opens the
3300     * search window using default settings.
3301     *
3302     * @return true if search window opened
3303     */
3304    private boolean launchDefaultSearch() {
3305        final Callback cb = getCallback();
3306        if (cb == null || isDestroyed()) {
3307            return false;
3308        } else {
3309            sendCloseSystemWindows("search");
3310            return cb.onSearchRequested();
3311        }
3312    }
3313
3314    @Override
3315    public void setVolumeControlStream(int streamType) {
3316        mVolumeControlStreamType = streamType;
3317    }
3318
3319    @Override
3320    public int getVolumeControlStream() {
3321        return mVolumeControlStreamType;
3322    }
3323
3324    private static final class DrawableFeatureState {
3325        DrawableFeatureState(int _featureId) {
3326            featureId = _featureId;
3327        }
3328
3329        final int featureId;
3330
3331        int resid;
3332
3333        Uri uri;
3334
3335        Drawable local;
3336
3337        Drawable child;
3338
3339        Drawable def;
3340
3341        Drawable cur;
3342
3343        int alpha = 255;
3344
3345        int curAlpha = 255;
3346    }
3347
3348    private static final class PanelFeatureState {
3349
3350        /** Feature ID for this panel. */
3351        int featureId;
3352
3353        // Information pulled from the style for this panel.
3354
3355        int background;
3356
3357        /** The background when the panel spans the entire available width. */
3358        int fullBackground;
3359
3360        int gravity;
3361
3362        int x;
3363
3364        int y;
3365
3366        int windowAnimations;
3367
3368        /** Dynamic state of the panel. */
3369        DecorView decorView;
3370
3371        /** The panel that was returned by onCreatePanelView(). */
3372        View createdPanelView;
3373
3374        /** The panel that we are actually showing. */
3375        View shownPanelView;
3376
3377        /** Use {@link #setMenu} to set this. */
3378        MenuBuilder menu;
3379
3380        IconMenuPresenter iconMenuPresenter;
3381        ListMenuPresenter listMenuPresenter;
3382
3383        /** true if this menu will show in single-list compact mode */
3384        boolean isCompact;
3385
3386        /** Theme resource ID for list elements of the panel menu */
3387        int listPresenterTheme;
3388
3389        /**
3390         * Whether the panel has been prepared (see
3391         * {@link PhoneWindow#preparePanel}).
3392         */
3393        boolean isPrepared;
3394
3395        /**
3396         * Whether an item's action has been performed. This happens in obvious
3397         * scenarios (user clicks on menu item), but can also happen with
3398         * chording menu+(shortcut key).
3399         */
3400        boolean isHandled;
3401
3402        boolean isOpen;
3403
3404        /**
3405         * True if the menu is in expanded mode, false if the menu is in icon
3406         * mode
3407         */
3408        boolean isInExpandedMode;
3409
3410        public boolean qwertyMode;
3411
3412        boolean refreshDecorView;
3413
3414        boolean refreshMenuContent;
3415
3416        boolean wasLastOpen;
3417
3418        boolean wasLastExpanded;
3419
3420        /**
3421         * Contains the state of the menu when told to freeze.
3422         */
3423        Bundle frozenMenuState;
3424
3425        /**
3426         * Contains the state of associated action views when told to freeze.
3427         * These are saved across invalidations.
3428         */
3429        Bundle frozenActionViewState;
3430
3431        PanelFeatureState(int featureId) {
3432            this.featureId = featureId;
3433
3434            refreshDecorView = false;
3435        }
3436
3437        public boolean isInListMode() {
3438            return isInExpandedMode || isCompact;
3439        }
3440
3441        public boolean hasPanelItems() {
3442            if (shownPanelView == null) return false;
3443            if (createdPanelView != null) return true;
3444
3445            if (isCompact || isInExpandedMode) {
3446                return listMenuPresenter.getAdapter().getCount() > 0;
3447            } else {
3448                return ((ViewGroup) shownPanelView).getChildCount() > 0;
3449            }
3450        }
3451
3452        /**
3453         * Unregister and free attached MenuPresenters. They will be recreated as needed.
3454         */
3455        public void clearMenuPresenters() {
3456            if (menu != null) {
3457                menu.removeMenuPresenter(iconMenuPresenter);
3458                menu.removeMenuPresenter(listMenuPresenter);
3459            }
3460            iconMenuPresenter = null;
3461            listMenuPresenter = null;
3462        }
3463
3464        void setStyle(Context context) {
3465            TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
3466            background = a.getResourceId(
3467                    com.android.internal.R.styleable.Theme_panelBackground, 0);
3468            fullBackground = a.getResourceId(
3469                    com.android.internal.R.styleable.Theme_panelFullBackground, 0);
3470            windowAnimations = a.getResourceId(
3471                    com.android.internal.R.styleable.Theme_windowAnimationStyle, 0);
3472            isCompact = a.getBoolean(
3473                    com.android.internal.R.styleable.Theme_panelMenuIsCompact, false);
3474            listPresenterTheme = a.getResourceId(
3475                    com.android.internal.R.styleable.Theme_panelMenuListTheme,
3476                    com.android.internal.R.style.Theme_ExpandedMenu);
3477            a.recycle();
3478        }
3479
3480        void setMenu(MenuBuilder menu) {
3481            if (menu == this.menu) return;
3482
3483            if (this.menu != null) {
3484                this.menu.removeMenuPresenter(iconMenuPresenter);
3485                this.menu.removeMenuPresenter(listMenuPresenter);
3486            }
3487            this.menu = menu;
3488            if (menu != null) {
3489                if (iconMenuPresenter != null) menu.addMenuPresenter(iconMenuPresenter);
3490                if (listMenuPresenter != null) menu.addMenuPresenter(listMenuPresenter);
3491            }
3492        }
3493
3494        MenuView getListMenuView(Context context, MenuPresenter.Callback cb) {
3495            if (menu == null) return null;
3496
3497            if (!isCompact) {
3498                getIconMenuView(context, cb); // Need this initialized to know where our offset goes
3499            }
3500
3501            if (listMenuPresenter == null) {
3502                listMenuPresenter = new ListMenuPresenter(
3503                        com.android.internal.R.layout.list_menu_item_layout, listPresenterTheme);
3504                listMenuPresenter.setCallback(cb);
3505                listMenuPresenter.setId(com.android.internal.R.id.list_menu_presenter);
3506                menu.addMenuPresenter(listMenuPresenter);
3507            }
3508
3509            if (iconMenuPresenter != null) {
3510                listMenuPresenter.setItemIndexOffset(
3511                        iconMenuPresenter.getNumActualItemsShown());
3512            }
3513            MenuView result = listMenuPresenter.getMenuView(decorView);
3514
3515            return result;
3516        }
3517
3518        MenuView getIconMenuView(Context context, MenuPresenter.Callback cb) {
3519            if (menu == null) return null;
3520
3521            if (iconMenuPresenter == null) {
3522                iconMenuPresenter = new IconMenuPresenter(context);
3523                iconMenuPresenter.setCallback(cb);
3524                iconMenuPresenter.setId(com.android.internal.R.id.icon_menu_presenter);
3525                menu.addMenuPresenter(iconMenuPresenter);
3526            }
3527
3528            MenuView result = iconMenuPresenter.getMenuView(decorView);
3529
3530            return result;
3531        }
3532
3533        Parcelable onSaveInstanceState() {
3534            SavedState savedState = new SavedState();
3535            savedState.featureId = featureId;
3536            savedState.isOpen = isOpen;
3537            savedState.isInExpandedMode = isInExpandedMode;
3538
3539            if (menu != null) {
3540                savedState.menuState = new Bundle();
3541                menu.savePresenterStates(savedState.menuState);
3542            }
3543
3544            return savedState;
3545        }
3546
3547        void onRestoreInstanceState(Parcelable state) {
3548            SavedState savedState = (SavedState) state;
3549            featureId = savedState.featureId;
3550            wasLastOpen = savedState.isOpen;
3551            wasLastExpanded = savedState.isInExpandedMode;
3552            frozenMenuState = savedState.menuState;
3553
3554            /*
3555             * A LocalActivityManager keeps the same instance of this class around.
3556             * The first time the menu is being shown after restoring, the
3557             * Activity.onCreateOptionsMenu should be called. But, if it is the
3558             * same instance then menu != null and we won't call that method.
3559             * We clear any cached views here. The caller should invalidatePanelMenu.
3560             */
3561            createdPanelView = null;
3562            shownPanelView = null;
3563            decorView = null;
3564        }
3565
3566        void applyFrozenState() {
3567            if (menu != null && frozenMenuState != null) {
3568                menu.restorePresenterStates(frozenMenuState);
3569                frozenMenuState = null;
3570            }
3571        }
3572
3573        private static class SavedState implements Parcelable {
3574            int featureId;
3575            boolean isOpen;
3576            boolean isInExpandedMode;
3577            Bundle menuState;
3578
3579            public int describeContents() {
3580                return 0;
3581            }
3582
3583            public void writeToParcel(Parcel dest, int flags) {
3584                dest.writeInt(featureId);
3585                dest.writeInt(isOpen ? 1 : 0);
3586                dest.writeInt(isInExpandedMode ? 1 : 0);
3587
3588                if (isOpen) {
3589                    dest.writeBundle(menuState);
3590                }
3591            }
3592
3593            private static SavedState readFromParcel(Parcel source) {
3594                SavedState savedState = new SavedState();
3595                savedState.featureId = source.readInt();
3596                savedState.isOpen = source.readInt() == 1;
3597                savedState.isInExpandedMode = source.readInt() == 1;
3598
3599                if (savedState.isOpen) {
3600                    savedState.menuState = source.readBundle();
3601                }
3602
3603                return savedState;
3604            }
3605
3606            public static final Parcelable.Creator<SavedState> CREATOR
3607                    = new Parcelable.Creator<SavedState>() {
3608                public SavedState createFromParcel(Parcel in) {
3609                    return readFromParcel(in);
3610                }
3611
3612                public SavedState[] newArray(int size) {
3613                    return new SavedState[size];
3614                }
3615            };
3616        }
3617
3618    }
3619
3620    static class RotationWatcher extends IRotationWatcher.Stub {
3621        private Handler mHandler;
3622        private final Runnable mRotationChanged = new Runnable() {
3623            public void run() {
3624                dispatchRotationChanged();
3625            }
3626        };
3627        private final ArrayList<WeakReference<PhoneWindow>> mWindows =
3628                new ArrayList<WeakReference<PhoneWindow>>();
3629        private boolean mIsWatching;
3630
3631        @Override
3632        public void onRotationChanged(int rotation) throws RemoteException {
3633            mHandler.post(mRotationChanged);
3634        }
3635
3636        public void addWindow(PhoneWindow phoneWindow) {
3637            synchronized (mWindows) {
3638                if (!mIsWatching) {
3639                    try {
3640                        WindowManagerHolder.sWindowManager.watchRotation(this);
3641                        mHandler = new Handler();
3642                        mIsWatching = true;
3643                    } catch (RemoteException ex) {
3644                        Log.e(TAG, "Couldn't start watching for device rotation", ex);
3645                    }
3646                }
3647                mWindows.add(new WeakReference<PhoneWindow>(phoneWindow));
3648            }
3649        }
3650
3651        public void removeWindow(PhoneWindow phoneWindow) {
3652            synchronized (mWindows) {
3653                int i = 0;
3654                while (i < mWindows.size()) {
3655                    final WeakReference<PhoneWindow> ref = mWindows.get(i);
3656                    final PhoneWindow win = ref.get();
3657                    if (win == null || win == phoneWindow) {
3658                        mWindows.remove(i);
3659                    } else {
3660                        i++;
3661                    }
3662                }
3663            }
3664        }
3665
3666        void dispatchRotationChanged() {
3667            synchronized (mWindows) {
3668                int i = 0;
3669                while (i < mWindows.size()) {
3670                    final WeakReference<PhoneWindow> ref = mWindows.get(i);
3671                    final PhoneWindow win = ref.get();
3672                    if (win != null) {
3673                        win.onOptionsPanelRotationChanged();
3674                        i++;
3675                    } else {
3676                        mWindows.remove(i);
3677                    }
3678                }
3679            }
3680        }
3681    }
3682
3683    /**
3684     * Simple implementation of MenuBuilder.Callback that:
3685     * <li> Opens a submenu when selected.
3686     * <li> Calls back to the callback's onMenuItemSelected when an item is
3687     * selected.
3688     */
3689    private final class DialogMenuCallback implements MenuBuilder.Callback, MenuPresenter.Callback {
3690        private int mFeatureId;
3691        private MenuDialogHelper mSubMenuHelper;
3692
3693        public DialogMenuCallback(int featureId) {
3694            mFeatureId = featureId;
3695        }
3696
3697        public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
3698            if (menu.getRootMenu() != menu) {
3699                onCloseSubMenu(menu);
3700            }
3701
3702            if (allMenusAreClosing) {
3703                Callback callback = getCallback();
3704                if (callback != null && !isDestroyed()) {
3705                    callback.onPanelClosed(mFeatureId, menu);
3706                }
3707
3708                if (menu == mContextMenu) {
3709                    dismissContextMenu();
3710                }
3711
3712                // Dismiss the submenu, if it is showing
3713                if (mSubMenuHelper != null) {
3714                    mSubMenuHelper.dismiss();
3715                    mSubMenuHelper = null;
3716                }
3717            }
3718        }
3719
3720        public void onCloseSubMenu(MenuBuilder menu) {
3721            Callback callback = getCallback();
3722            if (callback != null && !isDestroyed()) {
3723                callback.onPanelClosed(mFeatureId, menu.getRootMenu());
3724            }
3725        }
3726
3727        public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
3728            Callback callback = getCallback();
3729            return (callback != null && !isDestroyed())
3730                    && callback.onMenuItemSelected(mFeatureId, item);
3731        }
3732
3733        public void onMenuModeChange(MenuBuilder menu) {
3734        }
3735
3736        public boolean onOpenSubMenu(MenuBuilder subMenu) {
3737            if (subMenu == null) return false;
3738
3739            // Set a simple callback for the submenu
3740            subMenu.setCallback(this);
3741
3742            // The window manager will give us a valid window token
3743            mSubMenuHelper = new MenuDialogHelper(subMenu);
3744            mSubMenuHelper.show(null);
3745
3746            return true;
3747        }
3748    }
3749
3750    void sendCloseSystemWindows() {
3751        PhoneWindowManager.sendCloseSystemWindows(getContext(), null);
3752    }
3753
3754    void sendCloseSystemWindows(String reason) {
3755        PhoneWindowManager.sendCloseSystemWindows(getContext(), reason);
3756    }
3757}
3758