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